1use std::collections::BTreeMap;
11use std::error::Error;
12use std::future::IntoFuture;
13use std::net::{IpAddr, Ipv4Addr, SocketAddr, TcpStream};
14use std::path::{Path, PathBuf};
15use std::pin::Pin;
16use std::str::FromStr;
17use std::sync::Arc;
18use std::sync::LazyLock;
19use std::time::Duration;
20use std::{env, fs, iter};
21
22use anyhow::anyhow;
23use futures::Future;
24use futures::future::{BoxFuture, LocalBoxFuture};
25use headers::{Header, HeaderMapExt};
26use http::Uri;
27use hyper::http::header::HeaderMap;
28use maplit::btreemap;
29use mz_adapter::TimestampExplanation;
30use mz_adapter_types::bootstrap_builtin_cluster_config::{
31 ANALYTICS_CLUSTER_DEFAULT_REPLICATION_FACTOR, BootstrapBuiltinClusterConfig,
32 CATALOG_SERVER_CLUSTER_DEFAULT_REPLICATION_FACTOR, PROBE_CLUSTER_DEFAULT_REPLICATION_FACTOR,
33 SUPPORT_CLUSTER_DEFAULT_REPLICATION_FACTOR, SYSTEM_CLUSTER_DEFAULT_REPLICATION_FACTOR,
34};
35
36use mz_auth::password::Password;
37use mz_catalog::config::ClusterReplicaSizeMap;
38use mz_controller::ControllerConfig;
39use mz_dyncfg::ConfigUpdates;
40use mz_license_keys::ValidatedLicenseKey;
41use mz_orchestrator_process::{ProcessOrchestrator, ProcessOrchestratorConfig};
42use mz_orchestrator_tracing::{TracingCliArgs, TracingOrchestrator};
43use mz_ore::metrics::MetricsRegistry;
44use mz_ore::now::{EpochMillis, NowFn, SYSTEM_TIME};
45use mz_ore::retry::Retry;
46use mz_ore::task;
47use mz_ore::tracing::{
48 OpenTelemetryConfig, StderrLogConfig, StderrLogFormat, TracingConfig, TracingHandle,
49};
50use mz_persist_client::PersistLocation;
51use mz_persist_client::cache::PersistClientCache;
52use mz_persist_client::cfg::{CONSENSUS_CONNECTION_POOL_MAX_SIZE, PersistConfig};
53use mz_persist_client::rpc::PersistGrpcPubSubServer;
54use mz_postgres_util::{
55 Sql, batch_execute as pg_batch_execute, execute as pg_execute, query_one as pg_query_one, sql,
56};
57use mz_secrets::SecretsController;
58use mz_server_core::listeners::v26_32_0::ListenersConfig;
59use mz_server_core::listeners::{
60 AllowedRoles, AuthenticatorKind, HttpListenerConfig, HttpRoutesEnabled, RouteGroup,
61};
62use mz_server_core::{ReloadTrigger, TlsCertConfig};
63use mz_sql::catalog::EnvironmentId;
64use mz_storage_types::connections::ConnectionContext;
65use mz_tracing::CloneableEnvFilter;
66use openssl::asn1::Asn1Time;
67use openssl::error::ErrorStack;
68use openssl::hash::MessageDigest;
69use openssl::nid::Nid;
70use openssl::pkey::{PKey, Private};
71use openssl::rsa::Rsa;
72use openssl::ssl::{SslConnector, SslConnectorBuilder, SslMethod, SslOptions};
73use openssl::x509::extension::{BasicConstraints, SubjectAlternativeName};
74use openssl::x509::{X509, X509Name, X509NameBuilder};
75use postgres::error::DbError;
76use postgres::tls::{MakeTlsConnect, TlsConnect};
77use postgres::types::{FromSql, Type};
78use postgres::{NoTls, Socket};
79use postgres_openssl::MakeTlsConnector;
80use tempfile::TempDir;
81use tokio::net::TcpListener;
82use tokio::runtime::Runtime;
83use tokio_postgres::config::{Host, SslMode};
84use tokio_postgres::{AsyncMessage, Client};
85use tokio_stream::wrappers::TcpListenerStream;
86use tower_http::cors::AllowOrigin;
87use tracing::Level;
88use tracing_capture::SharedStorage;
89use tracing_subscriber::EnvFilter;
90use tungstenite::stream::MaybeTlsStream;
91use tungstenite::{Message, WebSocket};
92
93use crate::{
94 CatalogConfig, FronteggAuthenticator, SqlListenerConfig, WebSocketAuth, WebSocketResponse,
95};
96
97pub static KAFKA_ADDRS: LazyLock<String> =
98 LazyLock::new(|| env::var("KAFKA_ADDRS").unwrap_or_else(|_| "localhost:9092".into()));
99
100#[derive(Clone)]
102pub struct TestHarness {
103 data_directory: Option<PathBuf>,
104 tls: Option<TlsCertConfig>,
105 frontegg: Option<FronteggAuthenticator>,
106 external_login_password_mz_system: Option<Password>,
107 listeners_config: ListenersConfig,
108 unsafe_mode: bool,
109 workers: usize,
110 now: NowFn,
111 seed: u32,
112 storage_usage_collection_interval: Duration,
113 storage_usage_retention_period: Option<Duration>,
114 default_cluster_replica_size: String,
115 default_cluster_replication_factor: u32,
116 builtin_system_cluster_config: BootstrapBuiltinClusterConfig,
117 builtin_catalog_server_cluster_config: BootstrapBuiltinClusterConfig,
118 builtin_probe_cluster_config: BootstrapBuiltinClusterConfig,
119 builtin_support_cluster_config: BootstrapBuiltinClusterConfig,
120 builtin_analytics_cluster_config: BootstrapBuiltinClusterConfig,
121
122 propagate_crashes: bool,
123 enable_tracing: bool,
124 orchestrator_tracing_cli_args: TracingCliArgs,
127 bootstrap_role: Option<String>,
128 deploy_generation: u64,
129 system_parameter_defaults: BTreeMap<String, String>,
130 internal_console_redirect_url: Option<String>,
131 metrics_registry: Option<MetricsRegistry>,
132 code_version: semver::Version,
133 capture: Option<SharedStorage>,
134 pub environment_id: EnvironmentId,
135}
136
137impl Default for TestHarness {
138 fn default() -> TestHarness {
139 TestHarness {
140 data_directory: None,
141 tls: None,
142 frontegg: None,
143 external_login_password_mz_system: None,
144 listeners_config: ListenersConfig {
145 sql: btreemap![
146 "external".to_owned() => SqlListenerConfig {
147 addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0),
148 authenticator_kind: AuthenticatorKind::None,
149 allowed_roles: AllowedRoles::Normal,
150 enable_tls: false,
151 },
152 "internal".to_owned() => SqlListenerConfig {
153 addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0),
154 authenticator_kind: AuthenticatorKind::None,
155 allowed_roles: AllowedRoles::NormalAndInternal,
156 enable_tls: false,
157 },
158 ],
159 http: btreemap![
160 "external".to_owned() => HttpListenerConfig {
161 addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0),
162 authenticator_kind: AuthenticatorKind::None,
163 enable_tls: false,
164 routes: HttpRoutesEnabled {
165 base: RouteGroup::Enabled(AllowedRoles::Normal),
166 webhook: RouteGroup::Enabled(AllowedRoles::Normal),
167 internal: RouteGroup::Disabled,
168 metrics: RouteGroup::Disabled,
169 profiling: RouteGroup::Disabled,
170 mcp_agent: RouteGroup::Disabled,
171 mcp_developer: RouteGroup::Disabled,
172 console_config: RouteGroup::Enabled(AllowedRoles::Normal),
173 },
174 },
175 "internal".to_owned() => HttpListenerConfig {
176 addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0),
177 authenticator_kind: AuthenticatorKind::None,
178 enable_tls: false,
179 routes: HttpRoutesEnabled {
180 base: RouteGroup::Enabled(AllowedRoles::NormalAndInternal),
181 webhook: RouteGroup::Enabled(AllowedRoles::NormalAndInternal),
182 internal: RouteGroup::Enabled(AllowedRoles::NormalAndInternal),
183 metrics: RouteGroup::Enabled(AllowedRoles::NormalAndInternal),
184 profiling: RouteGroup::Enabled(AllowedRoles::NormalAndInternal),
185 mcp_agent: RouteGroup::Disabled,
186 mcp_developer: RouteGroup::Disabled,
187 console_config: RouteGroup::Enabled(AllowedRoles::NormalAndInternal),
188 },
189 },
190 ],
191 },
192 unsafe_mode: false,
193 workers: 1,
194 now: SYSTEM_TIME.clone(),
195 seed: rand::random(),
196 storage_usage_collection_interval: Duration::from_secs(3600),
197 storage_usage_retention_period: None,
198 default_cluster_replica_size: "scale=1,workers=1".to_string(),
199 default_cluster_replication_factor: 1,
200 builtin_system_cluster_config: BootstrapBuiltinClusterConfig {
201 size: "scale=1,workers=1".to_string(),
202 replication_factor: SYSTEM_CLUSTER_DEFAULT_REPLICATION_FACTOR,
203 },
204 builtin_catalog_server_cluster_config: BootstrapBuiltinClusterConfig {
205 size: "scale=1,workers=1".to_string(),
206 replication_factor: CATALOG_SERVER_CLUSTER_DEFAULT_REPLICATION_FACTOR,
207 },
208 builtin_probe_cluster_config: BootstrapBuiltinClusterConfig {
209 size: "scale=1,workers=1".to_string(),
210 replication_factor: PROBE_CLUSTER_DEFAULT_REPLICATION_FACTOR,
211 },
212 builtin_support_cluster_config: BootstrapBuiltinClusterConfig {
213 size: "scale=1,workers=1".to_string(),
214 replication_factor: SUPPORT_CLUSTER_DEFAULT_REPLICATION_FACTOR,
215 },
216 builtin_analytics_cluster_config: BootstrapBuiltinClusterConfig {
217 size: "scale=1,workers=1".to_string(),
218 replication_factor: ANALYTICS_CLUSTER_DEFAULT_REPLICATION_FACTOR,
219 },
220 propagate_crashes: false,
221 enable_tracing: false,
222 bootstrap_role: Some("materialize".into()),
223 deploy_generation: 0,
224 system_parameter_defaults: BTreeMap::from([(
227 "log_filter".to_string(),
228 "error".to_string(),
229 )]),
230 internal_console_redirect_url: None,
231 metrics_registry: None,
232 orchestrator_tracing_cli_args: TracingCliArgs {
233 startup_log_filter: CloneableEnvFilter::from_str("error").expect("must parse"),
234 ..Default::default()
235 },
236 code_version: crate::BUILD_INFO.semver_version(),
237 environment_id: EnvironmentId::for_tests(),
238 capture: None,
239 }
240 }
241}
242
243impl TestHarness {
244 pub async fn start(self) -> TestServer {
248 self.try_start().await.expect("Failed to start test Server")
249 }
250
251 pub async fn start_with_trigger(self, tls_reload_certs: ReloadTrigger) -> TestServer {
253 self.try_start_with_trigger(tls_reload_certs)
254 .await
255 .expect("Failed to start test Server")
256 }
257
258 pub async fn try_start(self) -> Result<TestServer, anyhow::Error> {
260 self.try_start_with_trigger(mz_server_core::cert_reload_never_reload())
261 .await
262 }
263
264 pub async fn try_start_with_trigger(
266 self,
267 tls_reload_certs: ReloadTrigger,
268 ) -> Result<TestServer, anyhow::Error> {
269 let listeners = Listeners::new(&self).await?;
270 listeners.serve_with_trigger(self, tls_reload_certs).await
271 }
272
273 pub fn start_blocking(self) -> TestServerWithRuntime {
275 let runtime = tokio::runtime::Builder::new_multi_thread()
276 .enable_all()
277 .thread_stack_size(mz_ore::stack::STACK_SIZE)
278 .build()
279 .expect("failed to spawn runtime for test");
280 let runtime = Arc::new(runtime);
281 let server = runtime.block_on(self.start());
282 TestServerWithRuntime { runtime, server }
283 }
284
285 pub fn data_directory(mut self, data_directory: impl Into<PathBuf>) -> Self {
286 self.data_directory = Some(data_directory.into());
287 self
288 }
289
290 pub fn with_tls(mut self, cert_path: impl Into<PathBuf>, key_path: impl Into<PathBuf>) -> Self {
291 self.tls = Some(TlsCertConfig {
292 cert: cert_path.into(),
293 key: key_path.into(),
294 });
295 for (_, listener) in &mut self.listeners_config.sql {
296 listener.enable_tls = true;
297 }
298 for (_, listener) in &mut self.listeners_config.http {
299 listener.enable_tls = true;
300 }
301 self
302 }
303
304 pub fn unsafe_mode(mut self) -> Self {
305 self.unsafe_mode = true;
306 self
307 }
308
309 pub fn workers(mut self, workers: usize) -> Self {
310 self.workers = workers;
311 self
312 }
313
314 pub fn with_frontegg_auth(mut self, frontegg: &FronteggAuthenticator) -> Self {
315 self.frontegg = Some(frontegg.clone());
316 let enable_tls = self.tls.is_some();
317 self.listeners_config = ListenersConfig {
318 sql: btreemap! {
319 "external".to_owned() => SqlListenerConfig {
320 addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0),
321 authenticator_kind: AuthenticatorKind::Frontegg,
322 allowed_roles: AllowedRoles::Normal,
323 enable_tls,
324 },
325 "internal".to_owned() => SqlListenerConfig {
326 addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0),
327 authenticator_kind: AuthenticatorKind::None,
328 allowed_roles: AllowedRoles::NormalAndInternal,
329 enable_tls: false,
330 },
331 },
332 http: btreemap! {
333 "external".to_owned() => HttpListenerConfig {
334 addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0),
335 authenticator_kind: AuthenticatorKind::Frontegg,
336 enable_tls,
337 routes: HttpRoutesEnabled {
338 base: RouteGroup::Enabled(AllowedRoles::Normal),
339 webhook: RouteGroup::Enabled(AllowedRoles::Normal),
340 internal: RouteGroup::Disabled,
341 metrics: RouteGroup::Disabled,
342 profiling: RouteGroup::Disabled,
343 mcp_agent: RouteGroup::Disabled,
344 mcp_developer: RouteGroup::Disabled,
345 console_config: RouteGroup::Enabled(AllowedRoles::Normal),
346 },
347 },
348 "internal".to_owned() => HttpListenerConfig {
349 addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0),
350 authenticator_kind: AuthenticatorKind::None,
351 enable_tls: false,
352 routes: HttpRoutesEnabled {
353 base: RouteGroup::Enabled(AllowedRoles::NormalAndInternal),
354 webhook: RouteGroup::Enabled(AllowedRoles::NormalAndInternal),
355 internal: RouteGroup::Enabled(AllowedRoles::NormalAndInternal),
356 metrics: RouteGroup::Enabled(AllowedRoles::NormalAndInternal),
357 profiling: RouteGroup::Enabled(AllowedRoles::NormalAndInternal),
358 mcp_agent: RouteGroup::Disabled,
359 mcp_developer: RouteGroup::Disabled,
360 console_config: RouteGroup::Enabled(AllowedRoles::NormalAndInternal),
361 },
362 },
363 },
364 };
365 self
366 }
367
368 pub fn with_oidc_auth(
369 mut self,
370 issuer: Option<String>,
371 authentication_claim: Option<String>,
372 expected_audiences: Option<Vec<String>>,
373 external_login_password_mz_system: Option<Password>,
374 ) -> Self {
375 let enable_tls = self.tls.is_some();
376 self.listeners_config = ListenersConfig {
377 sql: btreemap! {
378 "external".to_owned() => SqlListenerConfig {
379 addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0),
380 authenticator_kind: AuthenticatorKind::Oidc,
381 allowed_roles: AllowedRoles::NormalAndInternal,
382 enable_tls,
383 },
384 "internal".to_owned() => SqlListenerConfig {
385 addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0),
386 authenticator_kind: AuthenticatorKind::None,
387 allowed_roles: AllowedRoles::NormalAndInternal,
388 enable_tls: false,
389 },
390 },
391 http: btreemap! {
392 "external".to_owned() => HttpListenerConfig {
393 addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0),
394 authenticator_kind: AuthenticatorKind::Oidc,
395 enable_tls,
396 routes: HttpRoutesEnabled {
397 base: RouteGroup::Enabled(AllowedRoles::NormalAndInternal),
398 webhook: RouteGroup::Enabled(AllowedRoles::NormalAndInternal),
399 internal: RouteGroup::Disabled,
400 metrics: RouteGroup::Disabled,
401 profiling: RouteGroup::Disabled,
402 mcp_agent: RouteGroup::Disabled,
403 mcp_developer: RouteGroup::Disabled,
404 console_config: RouteGroup::Enabled(AllowedRoles::NormalAndInternal),
405 },
406 },
407 "internal".to_owned() => HttpListenerConfig {
408 addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0),
409 authenticator_kind: AuthenticatorKind::None,
410 enable_tls: false,
411 routes: HttpRoutesEnabled {
412 base: RouteGroup::Enabled(AllowedRoles::NormalAndInternal),
413 webhook: RouteGroup::Enabled(AllowedRoles::NormalAndInternal),
414 internal: RouteGroup::Enabled(AllowedRoles::NormalAndInternal),
415 metrics: RouteGroup::Enabled(AllowedRoles::NormalAndInternal),
416 profiling: RouteGroup::Enabled(AllowedRoles::NormalAndInternal),
417 mcp_agent: RouteGroup::Disabled,
418 mcp_developer: RouteGroup::Disabled,
419 console_config: RouteGroup::Enabled(AllowedRoles::NormalAndInternal),
420 },
421 },
422 },
423 };
424
425 if let Some(issuer) = issuer {
426 self.system_parameter_defaults
427 .insert("oidc_issuer".to_string(), issuer);
428 }
429
430 if let Some(authentication_claim) = authentication_claim {
431 self.system_parameter_defaults.insert(
432 "oidc_authentication_claim".to_string(),
433 authentication_claim,
434 );
435 }
436
437 if let Some(expected_audiences) = expected_audiences {
438 self.system_parameter_defaults.insert(
439 "oidc_audience".to_string(),
440 serde_json::to_string(&expected_audiences).unwrap(),
441 );
442 }
443
444 if let Some(external_login_password_mz_system) = external_login_password_mz_system {
445 self.external_login_password_mz_system = Some(external_login_password_mz_system);
446 self.system_parameter_defaults
447 .insert("enable_password_auth".to_string(), "true".to_string());
448 }
449
450 self
451 }
452
453 pub fn with_password_auth(mut self, mz_system_password: Password) -> Self {
454 self.external_login_password_mz_system = Some(mz_system_password);
455 let enable_tls = self.tls.is_some();
456 self.listeners_config = ListenersConfig {
457 sql: btreemap! {
458 "external".to_owned() => SqlListenerConfig {
459 addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0),
460 authenticator_kind: AuthenticatorKind::Password,
461 allowed_roles: AllowedRoles::NormalAndInternal,
462 enable_tls,
463 },
464 },
465 http: btreemap! {
466 "external".to_owned() => HttpListenerConfig {
467 addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0),
468 authenticator_kind: AuthenticatorKind::Password,
469 enable_tls,
470 routes: HttpRoutesEnabled {
471 base: RouteGroup::Enabled(AllowedRoles::NormalAndInternal),
472 webhook: RouteGroup::Enabled(AllowedRoles::NormalAndInternal),
473 internal: RouteGroup::Enabled(AllowedRoles::Internal),
474 metrics: RouteGroup::Disabled,
475 profiling: RouteGroup::Enabled(AllowedRoles::Internal),
476 mcp_agent: RouteGroup::Disabled,
477 mcp_developer: RouteGroup::Disabled,
478 console_config: RouteGroup::Enabled(AllowedRoles::NormalAndInternal),
479 },
480 },
481 "metrics".to_owned() => HttpListenerConfig {
482 addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0),
483 authenticator_kind: AuthenticatorKind::None,
484 enable_tls: false,
485 routes: HttpRoutesEnabled {
486 base: RouteGroup::Disabled,
487 webhook: RouteGroup::Disabled,
488 internal: RouteGroup::Disabled,
489 metrics: RouteGroup::Enabled(AllowedRoles::NormalAndInternal),
490 profiling: RouteGroup::Disabled,
491 mcp_agent: RouteGroup::Disabled,
492 mcp_developer: RouteGroup::Disabled,
493 console_config: RouteGroup::Enabled(AllowedRoles::NormalAndInternal),
494 },
495 },
496 },
497 };
498 self
499 }
500
501 pub fn with_sasl_scram_auth(mut self, mz_system_password: Password) -> Self {
502 self.external_login_password_mz_system = Some(mz_system_password);
503 let enable_tls = self.tls.is_some();
504 self.listeners_config = ListenersConfig {
505 sql: btreemap! {
506 "external".to_owned() => SqlListenerConfig {
507 addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0),
508 authenticator_kind: AuthenticatorKind::Sasl,
509 allowed_roles: AllowedRoles::NormalAndInternal,
510 enable_tls,
511 },
512 },
513 http: btreemap! {
514 "external".to_owned() => HttpListenerConfig {
515 addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0),
516 authenticator_kind: AuthenticatorKind::Password,
517 enable_tls,
518 routes: HttpRoutesEnabled {
519 base: RouteGroup::Enabled(AllowedRoles::NormalAndInternal),
520 webhook: RouteGroup::Enabled(AllowedRoles::NormalAndInternal),
521 internal: RouteGroup::Enabled(AllowedRoles::NormalAndInternal),
522 metrics: RouteGroup::Disabled,
523 profiling: RouteGroup::Enabled(AllowedRoles::NormalAndInternal),
524 mcp_agent: RouteGroup::Disabled,
525 mcp_developer: RouteGroup::Disabled,
526 console_config: RouteGroup::Enabled(AllowedRoles::NormalAndInternal),
527 },
528 },
529 "metrics".to_owned() => HttpListenerConfig {
530 addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0),
531 authenticator_kind: AuthenticatorKind::None,
532 enable_tls: false,
533 routes: HttpRoutesEnabled {
534 base: RouteGroup::Disabled,
535 webhook: RouteGroup::Disabled,
536 internal: RouteGroup::Disabled,
537 metrics: RouteGroup::Enabled(AllowedRoles::NormalAndInternal),
538 profiling: RouteGroup::Disabled,
539 mcp_agent: RouteGroup::Disabled,
540 mcp_developer: RouteGroup::Disabled,
541 console_config: RouteGroup::Enabled(AllowedRoles::NormalAndInternal),
542 },
543 },
544 },
545 };
546 self
547 }
548
549 pub fn with_now(mut self, now: NowFn) -> Self {
550 self.now = now;
551 self
552 }
553
554 pub fn with_storage_usage_collection_interval(
555 mut self,
556 storage_usage_collection_interval: Duration,
557 ) -> Self {
558 self.storage_usage_collection_interval = storage_usage_collection_interval;
559 self
560 }
561
562 pub fn with_storage_usage_retention_period(
563 mut self,
564 storage_usage_retention_period: Duration,
565 ) -> Self {
566 self.storage_usage_retention_period = Some(storage_usage_retention_period);
567 self
568 }
569
570 pub fn with_default_cluster_replica_size(
571 mut self,
572 default_cluster_replica_size: String,
573 ) -> Self {
574 self.default_cluster_replica_size = default_cluster_replica_size;
575 self
576 }
577
578 pub fn with_builtin_system_cluster_replica_size(
579 mut self,
580 builtin_system_cluster_replica_size: String,
581 ) -> Self {
582 self.builtin_system_cluster_config.size = builtin_system_cluster_replica_size;
583 self
584 }
585
586 pub fn with_builtin_system_cluster_replication_factor(
587 mut self,
588 builtin_system_cluster_replication_factor: u32,
589 ) -> Self {
590 self.builtin_system_cluster_config.replication_factor =
591 builtin_system_cluster_replication_factor;
592 self
593 }
594
595 pub fn with_builtin_catalog_server_cluster_replica_size(
596 mut self,
597 builtin_catalog_server_cluster_replica_size: String,
598 ) -> Self {
599 self.builtin_catalog_server_cluster_config.size =
600 builtin_catalog_server_cluster_replica_size;
601 self
602 }
603
604 pub fn with_propagate_crashes(mut self, propagate_crashes: bool) -> Self {
605 self.propagate_crashes = propagate_crashes;
606 self
607 }
608
609 pub fn with_enable_tracing(mut self, enable_tracing: bool) -> Self {
610 self.enable_tracing = enable_tracing;
611 self
612 }
613
614 pub fn with_bootstrap_role(mut self, bootstrap_role: Option<String>) -> Self {
615 self.bootstrap_role = bootstrap_role;
616 self
617 }
618
619 pub fn with_deploy_generation(mut self, deploy_generation: u64) -> Self {
620 self.deploy_generation = deploy_generation;
621 self
622 }
623
624 pub fn with_system_parameter_default(mut self, param: String, value: String) -> Self {
625 self.system_parameter_defaults.insert(param, value);
626 self
627 }
628
629 pub fn with_mcp_routes(mut self, agent: bool, developer: bool) -> Self {
630 for config in self.listeners_config.http.values_mut() {
631 let roles = config
635 .routes
636 .base
637 .allowed_roles()
638 .unwrap_or(AllowedRoles::NormalAndInternal);
639 let group = |enabled| {
640 if enabled {
641 RouteGroup::Enabled(roles)
642 } else {
643 RouteGroup::Disabled
644 }
645 };
646 config.routes.mcp_agent = group(agent);
647 config.routes.mcp_developer = group(developer);
648 }
649 self
650 }
651
652 pub fn with_internal_console_redirect_url(
653 mut self,
654 internal_console_redirect_url: Option<String>,
655 ) -> Self {
656 self.internal_console_redirect_url = internal_console_redirect_url;
657 self
658 }
659
660 pub fn with_metrics_registry(mut self, registry: MetricsRegistry) -> Self {
661 self.metrics_registry = Some(registry);
662 self
663 }
664
665 pub fn with_code_version(mut self, version: semver::Version) -> Self {
666 self.code_version = version;
667 self
668 }
669
670 pub fn with_capture(mut self, storage: SharedStorage) -> Self {
671 self.capture = Some(storage);
672 self
673 }
674}
675
676pub struct Listeners {
677 pub inner: crate::Listeners,
678}
679
680impl Listeners {
681 pub async fn new(config: &TestHarness) -> Result<Listeners, anyhow::Error> {
682 let inner = crate::Listeners::bind(config.listeners_config.clone()).await?;
683 Ok(Listeners { inner })
684 }
685
686 pub async fn serve(self, config: TestHarness) -> Result<TestServer, anyhow::Error> {
687 self.serve_with_trigger(config, mz_server_core::cert_reload_never_reload())
688 .await
689 }
690
691 pub async fn serve_with_trigger(
692 self,
693 config: TestHarness,
694 tls_reload_certs: ReloadTrigger,
695 ) -> Result<TestServer, anyhow::Error> {
696 let (data_directory, temp_dir) = match config.data_directory {
697 None => {
698 let temp_dir = tempfile::tempdir()?;
703 (temp_dir.path().to_path_buf(), Some(temp_dir))
704 }
705 Some(data_directory) => (data_directory, None),
706 };
707 let scratch_dir = tempfile::tempdir()?;
708 let (consensus_uri, timestamp_oracle_url) = {
709 let seed = config.seed;
710 let cockroach_url = env::var("METADATA_BACKEND_URL")
711 .map_err(|_| anyhow!("METADATA_BACKEND_URL environment variable is not set"))?;
712 let (client, conn) = tokio_postgres::connect(&cockroach_url, NoTls).await?;
713 mz_ore::task::spawn(|| "startup-postgres-conn", async move {
714 if let Err(err) = conn.await {
715 panic!("connection error: {}", err);
716 };
717 });
718 let consensus_schema = sql!("consensus_{}", seed);
719 let tsoracle_schema = sql!("tsoracle_{}", seed);
720 pg_batch_execute(
721 &client,
722 sql!(
723 "CREATE SCHEMA IF NOT EXISTS {};
724 CREATE SCHEMA IF NOT EXISTS {};",
725 consensus_schema,
726 tsoracle_schema,
727 ),
728 )
729 .await?;
730 (
731 format!("{cockroach_url}?options=--search_path=consensus_{seed}")
732 .parse()
733 .expect("invalid consensus URI"),
734 format!("{cockroach_url}?options=--search_path=tsoracle_{seed}")
735 .parse()
736 .expect("invalid timestamp oracle URI"),
737 )
738 };
739 let metrics_registry = config.metrics_registry.unwrap_or_else(MetricsRegistry::new);
740 let orchestrator = ProcessOrchestrator::new(ProcessOrchestratorConfig {
741 image_dir: env::current_exe()?
742 .parent()
743 .unwrap()
744 .parent()
745 .unwrap()
746 .to_path_buf(),
747 suppress_output: false,
748 environment_id: config.environment_id.to_string(),
749 secrets_dir: data_directory.join("secrets"),
750 command_wrapper: vec![],
751 propagate_crashes: config.propagate_crashes,
752 tcp_proxy: None,
753 scratch_directory: scratch_dir.path().to_path_buf(),
754 })
755 .await?;
756 let orchestrator = Arc::new(orchestrator);
757 let persist_now = SYSTEM_TIME.clone();
760 let dyncfgs = mz_dyncfgs::all_dyncfgs();
761
762 let mut updates = ConfigUpdates::default();
763 updates.add(&CONSENSUS_CONNECTION_POOL_MAX_SIZE, 1);
766 updates.apply(&dyncfgs);
767
768 let mut persist_cfg = PersistConfig::new(&crate::BUILD_INFO, persist_now.clone(), dyncfgs);
769 persist_cfg.build_version = config.code_version;
770 persist_cfg.set_rollup_threshold(5);
772
773 let persist_pubsub_server = PersistGrpcPubSubServer::new(&persist_cfg, &metrics_registry);
774 let persist_pubsub_client = persist_pubsub_server.new_same_process_connection();
775 let persist_pubsub_tcp_listener =
776 TcpListener::bind(SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0))
777 .await
778 .expect("pubsub addr binding");
779 let persist_pubsub_server_port = persist_pubsub_tcp_listener
780 .local_addr()
781 .expect("pubsub addr has local addr")
782 .port();
783
784 mz_ore::task::spawn(|| "persist_pubsub_server", async move {
786 persist_pubsub_server
787 .serve_with_stream(TcpListenerStream::new(persist_pubsub_tcp_listener))
788 .await
789 .expect("success")
790 });
791 let persist_clients =
792 PersistClientCache::new(persist_cfg, &metrics_registry, |_, _| persist_pubsub_client);
793 let persist_clients = Arc::new(persist_clients);
794 let system_dyncfgs = Arc::clone(&persist_clients.cfg().configs);
795
796 let secrets_controller = Arc::clone(&orchestrator);
797 let connection_context = ConnectionContext::for_tests(orchestrator.reader());
798 let orchestrator = Arc::new(TracingOrchestrator::new(
799 orchestrator,
800 config.orchestrator_tracing_cli_args,
801 ));
802 let tracing_handle = if config.enable_tracing {
803 let config = TracingConfig::<fn(&tracing::Metadata) -> sentry_tracing::EventFilter> {
804 service_name: "environmentd",
805 stderr_log: StderrLogConfig {
806 format: StderrLogFormat::Json,
807 filter: EnvFilter::default(),
808 },
809 opentelemetry: Some(OpenTelemetryConfig {
810 endpoint: "http://fake_address_for_testing:8080".to_string(),
811 headers: http::HeaderMap::new(),
812 filter: EnvFilter::default().add_directive(Level::DEBUG.into()),
813 resource: opentelemetry_sdk::resource::Resource::builder().build(),
814 max_batch_queue_size: 2048,
815 max_export_batch_size: 512,
816 max_concurrent_exports: 1,
817 batch_scheduled_delay: Duration::from_millis(5000),
818 max_export_timeout: Duration::from_secs(30),
819 }),
820 tokio_console: None,
821 sentry: None,
822 build_version: crate::BUILD_INFO.version,
823 build_sha: crate::BUILD_INFO.sha,
824 registry: metrics_registry.clone(),
825 capture: config.capture,
826 };
827 mz_ore::tracing::configure(config).await?
828 } else {
829 TracingHandle::disabled()
830 };
831 let host_name = format!(
832 "localhost:{}",
833 self.inner.http["external"].handle.local_addr.port()
834 );
835 let catalog_config = CatalogConfig {
836 persist_clients: Arc::clone(&persist_clients),
837 metrics: Arc::new(mz_catalog::durable::Metrics::new(&MetricsRegistry::new())),
838 };
839
840 let inner = self
841 .inner
842 .serve(crate::Config {
843 catalog_config,
844 timestamp_oracle_url: Some(timestamp_oracle_url),
845 controller: ControllerConfig {
846 build_info: &crate::BUILD_INFO,
847 orchestrator,
848 clusterd_image: "clusterd".into(),
849 init_container_image: None,
850 deploy_generation: config.deploy_generation,
851 persist_location: PersistLocation {
852 blob_uri: format!("file://{}/persist/blob", data_directory.display())
853 .parse()
854 .expect("invalid blob URI"),
855 consensus_uri,
856 },
857 persist_clients,
858 now: config.now.clone(),
859 metrics_registry: metrics_registry.clone(),
860 persist_pubsub_url: format!("http://localhost:{}", persist_pubsub_server_port),
861 secrets_args: mz_service::secrets::SecretsReaderCliArgs {
862 secrets_reader: mz_service::secrets::SecretsControllerKind::LocalFile,
863 secrets_reader_local_file_dir: Some(data_directory.join("secrets")),
864 secrets_reader_kubernetes_context: None,
865 secrets_reader_aws_prefix: None,
866 secrets_reader_name_prefix: None,
867 },
868 connection_context,
869 replica_http_locator: Default::default(),
870 },
871 secrets_controller,
872 cloud_resource_controller: None,
873 system_dyncfgs,
874 tls: config.tls,
875 frontegg: config.frontegg,
876 frontegg_oauth_issuer_url: None,
877 unsafe_mode: config.unsafe_mode,
878 all_features: false,
879 metrics_registry: metrics_registry.clone(),
880 now: config.now,
881 environment_id: config.environment_id,
882 cors_allowed_origin: AllowOrigin::list([]),
883 cors_allowed_origin_list: Vec::new(),
884 cluster_replica_sizes: ClusterReplicaSizeMap::for_tests(),
885 bootstrap_default_cluster_replica_size: config.default_cluster_replica_size,
886 bootstrap_default_cluster_replication_factor: config
887 .default_cluster_replication_factor,
888 bootstrap_builtin_system_cluster_config: config.builtin_system_cluster_config,
889 bootstrap_builtin_catalog_server_cluster_config: config
890 .builtin_catalog_server_cluster_config,
891 bootstrap_builtin_probe_cluster_config: config.builtin_probe_cluster_config,
892 bootstrap_builtin_support_cluster_config: config.builtin_support_cluster_config,
893 bootstrap_builtin_analytics_cluster_config: config.builtin_analytics_cluster_config,
894 system_parameter_defaults: config.system_parameter_defaults,
895 availability_zones: Default::default(),
896 tracing_handle,
897 storage_usage_collection_interval: config.storage_usage_collection_interval,
898 storage_usage_retention_period: config.storage_usage_retention_period,
899 segment_api_key: None,
900 segment_client_side: false,
901 test_only_dummy_segment_client: false,
902 egress_addresses: vec![],
903 aws_account_id: None,
904 aws_privatelink_availability_zones: None,
905 launchdarkly_sdk_key: None,
906 launchdarkly_base_uri: None,
907 launchdarkly_key_map: Default::default(),
908 config_sync_file_path: None,
909 config_sync_timeout: Duration::from_secs(30),
910 config_sync_loop_interval: None,
911 bootstrap_role: config.bootstrap_role,
912 http_host_name: Some(host_name),
913 internal_console_redirect_url: config.internal_console_redirect_url,
914 tls_reload_certs,
915 helm_chart_version: None,
916 license_key: ValidatedLicenseKey::for_tests(),
917 external_login_password_mz_system: config.external_login_password_mz_system,
918 force_builtin_schema_migration: None,
919 })
920 .await?;
921
922 Ok(TestServer {
923 inner,
924 metrics_registry,
925 _temp_dir: temp_dir,
926 _scratch_dir: scratch_dir,
927 })
928 }
929}
930
931pub struct TestServer {
933 pub inner: crate::Server,
934 pub metrics_registry: MetricsRegistry,
935 _temp_dir: Option<TempDir>,
937 _scratch_dir: TempDir,
938}
939
940impl TestServer {
941 pub fn connect(&self) -> ConnectBuilder<'_, postgres::NoTls, NoHandle> {
942 ConnectBuilder::new(self).no_tls()
943 }
944
945 pub async fn enable_feature_flags(&self, flags: &[&'static str]) {
946 let internal_client = self.connect().internal().await.unwrap();
947
948 for flag in flags {
949 let query = sql!("ALTER SYSTEM SET {} = true;", Sql::ident(flag));
950 pg_batch_execute(&internal_client, query).await.unwrap();
951 }
952 }
953
954 pub async fn disable_feature_flags(&self, flags: &[&'static str]) {
955 let internal_client = self.connect().internal().await.unwrap();
956
957 for flag in flags {
958 let query = sql!("ALTER SYSTEM SET {} = false;", Sql::ident(flag));
959 pg_batch_execute(&internal_client, query).await.unwrap();
960 }
961 }
962
963 pub fn ws_addr(&self) -> Uri {
964 format!(
965 "ws://{}/api/experimental/sql",
966 self.inner.http_listener_handles["external"].local_addr
967 )
968 .parse()
969 .unwrap()
970 }
971
972 pub fn internal_ws_addr(&self) -> Uri {
973 format!(
974 "ws://{}/api/experimental/sql",
975 self.inner.http_listener_handles["internal"].local_addr
976 )
977 .parse()
978 .unwrap()
979 }
980
981 pub fn http_local_addr(&self) -> SocketAddr {
982 self.inner.http_listener_handles["external"].local_addr
983 }
984
985 pub fn internal_http_local_addr(&self) -> SocketAddr {
986 self.inner.http_listener_handles["internal"].local_addr
987 }
988
989 pub fn sql_local_addr(&self) -> SocketAddr {
990 self.inner.sql_listener_handles["external"].local_addr
991 }
992
993 pub fn internal_sql_local_addr(&self) -> SocketAddr {
994 self.inner.sql_listener_handles["internal"].local_addr
995 }
996}
997
998pub struct ConnectBuilder<'s, T, H> {
1002 server: &'s TestServer,
1004
1005 pg_config: tokio_postgres::Config,
1007 port: u16,
1009 tls: T,
1011
1012 notice_callback: Option<Box<dyn FnMut(tokio_postgres::error::DbError) + Send + 'static>>,
1014
1015 _with_handle: H,
1017}
1018
1019impl<'s> ConnectBuilder<'s, (), NoHandle> {
1020 fn new(server: &'s TestServer) -> Self {
1021 let mut pg_config = tokio_postgres::Config::new();
1022 pg_config
1023 .host(&Ipv4Addr::LOCALHOST.to_string())
1024 .user("materialize")
1025 .options("--welcome_message=off")
1026 .application_name("environmentd_test_framework");
1027
1028 ConnectBuilder {
1029 server,
1030 pg_config,
1031 port: server.sql_local_addr().port(),
1032 tls: (),
1033 notice_callback: None,
1034 _with_handle: NoHandle,
1035 }
1036 }
1037}
1038
1039impl<'s, T, H> ConnectBuilder<'s, T, H> {
1040 pub fn no_tls(self) -> ConnectBuilder<'s, postgres::NoTls, H> {
1044 ConnectBuilder {
1045 server: self.server,
1046 pg_config: self.pg_config,
1047 port: self.port,
1048 tls: postgres::NoTls,
1049 notice_callback: self.notice_callback,
1050 _with_handle: self._with_handle,
1051 }
1052 }
1053
1054 pub fn with_tls<Tls>(self, tls: Tls) -> ConnectBuilder<'s, Tls, H>
1056 where
1057 Tls: MakeTlsConnect<Socket> + Send + 'static,
1058 Tls::TlsConnect: Send,
1059 Tls::Stream: Send,
1060 <Tls::TlsConnect as TlsConnect<Socket>>::Future: Send,
1061 {
1062 ConnectBuilder {
1063 server: self.server,
1064 pg_config: self.pg_config,
1065 port: self.port,
1066 tls,
1067 notice_callback: self.notice_callback,
1068 _with_handle: self._with_handle,
1069 }
1070 }
1071
1072 pub fn with_config(mut self, pg_config: tokio_postgres::Config) -> Self {
1074 self.pg_config = pg_config;
1075 self
1076 }
1077
1078 pub fn ssl_mode(mut self, mode: SslMode) -> Self {
1080 self.pg_config.ssl_mode(mode);
1081 self
1082 }
1083
1084 pub fn user(mut self, user: &str) -> Self {
1086 self.pg_config.user(user);
1087 self
1088 }
1089
1090 pub fn password(mut self, password: &str) -> Self {
1092 self.pg_config.password(password);
1093 self
1094 }
1095
1096 pub fn application_name(mut self, application_name: &str) -> Self {
1098 self.pg_config.application_name(application_name);
1099 self
1100 }
1101
1102 pub fn dbname(mut self, dbname: &str) -> Self {
1104 self.pg_config.dbname(dbname);
1105 self
1106 }
1107
1108 pub fn options(mut self, options: &str) -> Self {
1110 self.pg_config.options(options);
1111 self
1112 }
1113
1114 pub fn internal(mut self) -> Self {
1119 self.port = self.server.internal_sql_local_addr().port();
1120 self.pg_config.user(mz_sql::session::user::SYSTEM_USER_NAME);
1121 self
1122 }
1123
1124 pub fn notice_callback(self, callback: impl FnMut(DbError) + Send + 'static) -> Self {
1126 ConnectBuilder {
1127 notice_callback: Some(Box::new(callback)),
1128 ..self
1129 }
1130 }
1131
1132 pub fn with_handle(self) -> ConnectBuilder<'s, T, WithHandle> {
1135 ConnectBuilder {
1136 server: self.server,
1137 pg_config: self.pg_config,
1138 port: self.port,
1139 tls: self.tls,
1140 notice_callback: self.notice_callback,
1141 _with_handle: WithHandle,
1142 }
1143 }
1144
1145 pub fn as_pg_config(&self) -> &tokio_postgres::Config {
1147 &self.pg_config
1148 }
1149}
1150
1151pub trait IncludeHandle: Send {
1154 type Output;
1155 fn transform_result(
1156 client: tokio_postgres::Client,
1157 handle: mz_ore::task::JoinHandle<()>,
1158 ) -> Self::Output;
1159}
1160
1161pub struct NoHandle;
1164impl IncludeHandle for NoHandle {
1165 type Output = tokio_postgres::Client;
1166 fn transform_result(
1167 client: tokio_postgres::Client,
1168 _handle: mz_ore::task::JoinHandle<()>,
1169 ) -> Self::Output {
1170 client
1171 }
1172}
1173
1174pub struct WithHandle;
1177impl IncludeHandle for WithHandle {
1178 type Output = (tokio_postgres::Client, mz_ore::task::JoinHandle<()>);
1179 fn transform_result(
1180 client: tokio_postgres::Client,
1181 handle: mz_ore::task::JoinHandle<()>,
1182 ) -> Self::Output {
1183 (client, handle)
1184 }
1185}
1186
1187impl<'s, T, H> IntoFuture for ConnectBuilder<'s, T, H>
1188where
1189 T: MakeTlsConnect<Socket> + Send + 'static,
1190 T::TlsConnect: Send,
1191 T::Stream: Send,
1192 <T::TlsConnect as TlsConnect<Socket>>::Future: Send,
1193 H: IncludeHandle,
1194{
1195 type Output = Result<H::Output, postgres::Error>;
1196 type IntoFuture = BoxFuture<'static, Self::Output>;
1197
1198 fn into_future(mut self) -> Self::IntoFuture {
1199 Box::pin(async move {
1200 assert!(
1201 self.pg_config.get_ports().is_empty(),
1202 "specifying multiple ports is not supported"
1203 );
1204 self.pg_config.port(self.port);
1205
1206 let (client, mut conn) = self.pg_config.connect(self.tls).await?;
1207 let mut notice_callback = self.notice_callback.take();
1208
1209 let handle = task::spawn(|| "connect", async move {
1210 while let Some(msg) = std::future::poll_fn(|cx| conn.poll_message(cx)).await {
1211 match msg {
1212 Ok(AsyncMessage::Notice(notice)) => {
1213 if let Some(callback) = notice_callback.as_mut() {
1214 callback(notice);
1215 }
1216 }
1217 Ok(msg) => {
1218 tracing::debug!(?msg, "Dropping message from database");
1219 }
1220 Err(e) => {
1221 tracing::info!("connection error: {e}");
1226 break;
1227 }
1228 }
1229 }
1230 tracing::info!("connection closed");
1231 });
1232
1233 let output = H::transform_result(client, handle);
1234 Ok(output)
1235 })
1236 }
1237}
1238
1239pub struct TestServerWithRuntime {
1244 server: TestServer,
1245 runtime: Arc<Runtime>,
1246}
1247
1248impl TestServerWithRuntime {
1249 pub fn runtime(&self) -> &Arc<Runtime> {
1253 &self.runtime
1254 }
1255
1256 pub fn inner(&self) -> &crate::Server {
1258 &self.server.inner
1259 }
1260
1261 pub fn connect<T>(&self, tls: T) -> Result<postgres::Client, postgres::Error>
1263 where
1264 T: MakeTlsConnect<Socket> + Send + 'static,
1265 T::TlsConnect: Send,
1266 T::Stream: Send,
1267 <T::TlsConnect as TlsConnect<Socket>>::Future: Send,
1268 {
1269 self.pg_config().connect(tls)
1270 }
1271
1272 pub fn connect_internal<T>(&self, tls: T) -> Result<postgres::Client, anyhow::Error>
1274 where
1275 T: MakeTlsConnect<Socket> + Send + 'static,
1276 T::TlsConnect: Send,
1277 T::Stream: Send,
1278 <T::TlsConnect as TlsConnect<Socket>>::Future: Send,
1279 {
1280 Ok(self.pg_config_internal().connect(tls)?)
1281 }
1282
1283 pub fn enable_feature_flags(&self, flags: &[&'static str]) {
1285 let mut internal_client = self.connect_internal(postgres::NoTls).unwrap();
1286
1287 for flag in flags {
1288 let query = sql!("ALTER SYSTEM SET {} = true;", Sql::ident(flag));
1289 #[allow(clippy::disallowed_methods)]
1292 internal_client.batch_execute(query.as_str()).unwrap();
1293 }
1294 }
1295
1296 pub fn disable_feature_flags(&self, flags: &[&'static str]) {
1298 let mut internal_client = self.connect_internal(postgres::NoTls).unwrap();
1299
1300 for flag in flags {
1301 let query = sql!("ALTER SYSTEM SET {} = false;", Sql::ident(flag));
1302 #[allow(clippy::disallowed_methods)]
1305 internal_client.batch_execute(query.as_str()).unwrap();
1306 }
1307 }
1308
1309 pub fn pg_config(&self) -> postgres::Config {
1312 let local_addr = self.server.sql_local_addr();
1313 let mut config = postgres::Config::new();
1314 config
1315 .host(&Ipv4Addr::LOCALHOST.to_string())
1316 .port(local_addr.port())
1317 .user("materialize")
1318 .options("--welcome_message=off");
1319 config
1320 }
1321
1322 pub fn pg_config_internal(&self) -> postgres::Config {
1325 let local_addr = self.server.internal_sql_local_addr();
1326 let mut config = postgres::Config::new();
1327 config
1328 .host(&Ipv4Addr::LOCALHOST.to_string())
1329 .port(local_addr.port())
1330 .user("mz_system")
1331 .options("--welcome_message=off");
1332 config
1333 }
1334
1335 pub fn ws_addr(&self) -> Uri {
1336 self.server.ws_addr()
1337 }
1338
1339 pub fn internal_ws_addr(&self) -> Uri {
1340 self.server.internal_ws_addr()
1341 }
1342
1343 pub fn http_local_addr(&self) -> SocketAddr {
1344 self.server.http_local_addr()
1345 }
1346
1347 pub fn internal_http_local_addr(&self) -> SocketAddr {
1348 self.server.internal_http_local_addr()
1349 }
1350
1351 pub fn sql_local_addr(&self) -> SocketAddr {
1352 self.server.sql_local_addr()
1353 }
1354
1355 pub fn internal_sql_local_addr(&self) -> SocketAddr {
1356 self.server.internal_sql_local_addr()
1357 }
1358
1359 pub fn metrics_registry(&self) -> &MetricsRegistry {
1361 &self.server.metrics_registry
1362 }
1363}
1364
1365#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
1366pub struct MzTimestamp(pub u64);
1367
1368impl<'a> FromSql<'a> for MzTimestamp {
1369 fn from_sql(ty: &Type, raw: &'a [u8]) -> Result<MzTimestamp, Box<dyn Error + Sync + Send>> {
1370 let n = mz_pgrepr::Numeric::from_sql(ty, raw)?;
1371 Ok(MzTimestamp(u64::try_from(n.0.0)?))
1372 }
1373
1374 fn accepts(ty: &Type) -> bool {
1375 mz_pgrepr::Numeric::accepts(ty)
1376 }
1377}
1378
1379pub trait PostgresErrorExt {
1380 fn unwrap_db_error(self) -> DbError;
1381}
1382
1383impl PostgresErrorExt for postgres::Error {
1384 fn unwrap_db_error(self) -> DbError {
1385 match self.source().and_then(|e| e.downcast_ref::<DbError>()) {
1386 Some(e) => e.clone(),
1387 None => panic!("expected DbError, but got: {:?}", self),
1388 }
1389 }
1390}
1391
1392impl<T, E> PostgresErrorExt for Result<T, E>
1393where
1394 E: PostgresErrorExt,
1395{
1396 fn unwrap_db_error(self) -> DbError {
1397 match self {
1398 Ok(_) => panic!("expected Err(DbError), but got Ok(_)"),
1399 Err(e) => e.unwrap_db_error(),
1400 }
1401 }
1402}
1403
1404pub async fn insert_with_deterministic_timestamps(
1408 table: &'static str,
1409 values: &'static str,
1410 server: &TestServer,
1411 now: Arc<std::sync::Mutex<EpochMillis>>,
1412) -> Result<(), Box<dyn Error>> {
1413 let client_write = server.connect().await?;
1414 let client_read = server.connect().await?;
1415
1416 let mut current_ts = get_explain_timestamp(table, &client_read).await;
1417
1418 let insert_query = format!("INSERT INTO {} VALUES {values}", Sql::ident(table));
1419
1420 #[allow(clippy::disallowed_methods)]
1423 let write_future = client_write.execute(&insert_query, &[]);
1424 let timestamp_interval = tokio::time::interval(Duration::from_millis(1));
1425
1426 let mut write_future = std::pin::pin!(write_future);
1427 let mut timestamp_interval = std::pin::pin!(timestamp_interval);
1428
1429 loop {
1432 tokio::select! {
1433 _ = (&mut write_future) => return Ok(()),
1434 _ = timestamp_interval.tick() => {
1435 current_ts += 1;
1436 *now.lock().expect("lock poisoned") = current_ts;
1437 }
1438 };
1439 }
1440}
1441
1442pub async fn get_explain_timestamp(from_suffix: &str, client: &Client) -> EpochMillis {
1443 try_get_explain_timestamp(from_suffix, client)
1444 .await
1445 .unwrap()
1446}
1447
1448pub async fn try_get_explain_timestamp(
1449 from_suffix: &str,
1450 client: &Client,
1451) -> Result<EpochMillis, anyhow::Error> {
1452 let det = get_explain_timestamp_determination(from_suffix, client).await?;
1453 let ts = det.determination.timestamp_context.timestamp_or_default();
1454 Ok(ts.into())
1455}
1456
1457pub async fn get_explain_timestamp_determination(
1458 from_suffix: &str,
1459 client: &Client,
1460) -> Result<TimestampExplanation, anyhow::Error> {
1461 #[allow(clippy::disallowed_methods)]
1464 let row = client
1465 .query_one(
1466 &format!("EXPLAIN TIMESTAMP AS JSON FOR SELECT * FROM {from_suffix}"),
1467 &[],
1468 )
1469 .await?;
1470 let explain: String = row.get(0);
1471 Ok(serde_json::from_str(&explain).unwrap())
1472}
1473
1474pub async fn create_postgres_source_with_table<'a>(
1482 server: &TestServer,
1483 mz_client: &Client,
1484 table_name: &str,
1485 table_schema: &str,
1486 source_name: &str,
1487) -> (
1488 Client,
1489 impl FnOnce(&'a Client, &'a Client) -> LocalBoxFuture<'a, ()>,
1490) {
1491 server
1492 .enable_feature_flags(&["enable_create_table_from_source"])
1493 .await;
1494
1495 let postgres_url = env::var("POSTGRES_URL")
1496 .map_err(|_| anyhow!("POSTGRES_URL environment variable is not set"))
1497 .unwrap();
1498
1499 let (pg_client, connection) = tokio_postgres::connect(&postgres_url, postgres::NoTls)
1500 .await
1501 .unwrap();
1502
1503 let pg_config: tokio_postgres::Config = postgres_url.parse().unwrap();
1504 let user = pg_config.get_user().unwrap_or("postgres");
1505 let db_name = pg_config.get_dbname().unwrap_or(user);
1506 let ports = pg_config.get_ports();
1507 let port = if ports.is_empty() { 5432 } else { ports[0] };
1508 let hosts = pg_config.get_hosts();
1509 let host = if hosts.is_empty() {
1510 "localhost".to_string()
1511 } else {
1512 match &hosts[0] {
1513 Host::Tcp(host) => host.to_string(),
1514 Host::Unix(host) => host.to_str().unwrap().to_string(),
1515 }
1516 };
1517 let password = pg_config.get_password();
1518
1519 mz_ore::task::spawn(|| "postgres-source-connection", async move {
1520 if let Err(e) = connection.await {
1521 panic!("connection error: {}", e);
1522 }
1523 });
1524
1525 let _ = pg_execute(
1527 &pg_client,
1528 sql!("DROP TABLE IF EXISTS {};", Sql::ident(table_name)),
1529 &[],
1530 )
1531 .await
1532 .unwrap();
1533 let _ = pg_execute(
1534 &pg_client,
1535 sql!("DROP PUBLICATION IF EXISTS {};", Sql::ident(source_name)),
1536 &[],
1537 )
1538 .await
1539 .unwrap();
1540 #[allow(clippy::disallowed_methods)]
1543 let _ = pg_client
1544 .execute(
1545 format!("CREATE TABLE {} {table_schema};", Sql::ident(table_name)).as_str(),
1546 &[],
1547 )
1548 .await
1549 .unwrap();
1550 let _ = pg_execute(
1551 &pg_client,
1552 sql!(
1553 "ALTER TABLE {} REPLICA IDENTITY FULL;",
1554 Sql::ident(table_name)
1555 ),
1556 &[],
1557 )
1558 .await
1559 .unwrap();
1560 let _ = pg_execute(
1561 &pg_client,
1562 sql!(
1563 "CREATE PUBLICATION {} FOR TABLE {};",
1564 Sql::ident(source_name),
1565 Sql::ident(table_name)
1566 ),
1567 &[],
1568 )
1569 .await
1570 .unwrap();
1571
1572 let mut connection_str = format!("HOST '{host}', PORT {port}, USER {user}, DATABASE {db_name}");
1574 if let Some(password) = password {
1575 let password = std::str::from_utf8(password).unwrap();
1576 pg_batch_execute(
1577 mz_client,
1578 sql!("CREATE SECRET s AS {}", Sql::literal(password)),
1579 )
1580 .await
1581 .unwrap();
1582 connection_str = format!("{connection_str}, PASSWORD SECRET s");
1583 }
1584 #[allow(clippy::disallowed_methods)]
1587 mz_client
1588 .batch_execute(format!("CREATE CONNECTION pgconn TO POSTGRES ({connection_str})").as_str())
1589 .await
1590 .unwrap();
1591 pg_batch_execute(
1592 mz_client,
1593 sql!(
1594 "CREATE SOURCE {} \
1595 FROM POSTGRES \
1596 CONNECTION pgconn \
1597 (PUBLICATION {})",
1598 Sql::ident(source_name),
1599 Sql::literal(source_name),
1600 ),
1601 )
1602 .await
1603 .unwrap();
1604 pg_batch_execute(
1605 mz_client,
1606 sql!(
1607 "CREATE TABLE {} \
1608 FROM SOURCE {} \
1609 (REFERENCE {});",
1610 Sql::ident(table_name),
1611 Sql::ident(source_name),
1612 Sql::ident(table_name),
1613 ),
1614 )
1615 .await
1616 .unwrap();
1617
1618 let table_name = table_name.to_string();
1619 let source_name = source_name.to_string();
1620 (
1621 pg_client,
1622 move |mz_client: &'a Client, pg_client: &'a Client| {
1623 let f: Pin<Box<dyn Future<Output = ()> + 'a>> = Box::pin(async move {
1624 pg_batch_execute(
1625 mz_client,
1626 sql!("DROP SOURCE {} CASCADE;", Sql::ident(&source_name)),
1627 )
1628 .await
1629 .unwrap();
1630 pg_batch_execute(mz_client, sql!("DROP CONNECTION pgconn;"))
1631 .await
1632 .unwrap();
1633
1634 let _ = pg_execute(
1635 pg_client,
1636 sql!("DROP PUBLICATION {};", Sql::ident(&source_name)),
1637 &[],
1638 )
1639 .await
1640 .unwrap();
1641 let _ = pg_execute(
1642 pg_client,
1643 sql!("DROP TABLE {};", Sql::ident(&table_name)),
1644 &[],
1645 )
1646 .await
1647 .unwrap();
1648 });
1649 f
1650 },
1651 )
1652}
1653
1654pub async fn wait_for_pg_table_population(mz_client: &Client, view_name: &str, source_rows: i64) {
1655 let current_isolation = pg_query_one(mz_client, sql!("SHOW transaction_isolation"), &[])
1656 .await
1657 .unwrap()
1658 .get::<_, String>(0);
1659 pg_batch_execute(mz_client, sql!("SET transaction_isolation = SERIALIZABLE"))
1660 .await
1661 .unwrap();
1662 Retry::default()
1663 .retry_async(|_| async move {
1664 let rows = pg_query_one(
1665 mz_client,
1666 sql!("SELECT COUNT(*) FROM {};", Sql::ident(view_name)),
1667 &[],
1668 )
1669 .await
1670 .unwrap()
1671 .get::<_, i64>(0);
1672 if rows == source_rows {
1673 Ok(())
1674 } else {
1675 Err(format!(
1676 "Waiting for {source_rows} row to be ingested. Currently at {rows}."
1677 ))
1678 }
1679 })
1680 .await
1681 .unwrap();
1682 pg_batch_execute(
1683 mz_client,
1684 sql!(
1685 "SET transaction_isolation = {}",
1686 Sql::literal(¤t_isolation),
1687 ),
1688 )
1689 .await
1690 .unwrap();
1691}
1692
1693pub fn auth_with_ws(
1695 ws: &mut WebSocket<MaybeTlsStream<TcpStream>>,
1696 mut options: BTreeMap<String, String>,
1697) -> Result<Vec<WebSocketResponse>, anyhow::Error> {
1698 if !options.contains_key("welcome_message") {
1699 options.insert("welcome_message".into(), "off".into());
1700 }
1701 auth_with_ws_impl(
1702 ws,
1703 Message::Text(
1704 serde_json::to_string(&WebSocketAuth::Basic {
1705 user: "materialize".into(),
1706 password: "".into(),
1707 options,
1708 })
1709 .unwrap()
1710 .into(),
1711 ),
1712 )
1713}
1714
1715pub fn auth_with_ws_impl(
1716 ws: &mut WebSocket<MaybeTlsStream<TcpStream>>,
1717 auth_message: Message,
1718) -> Result<Vec<WebSocketResponse>, anyhow::Error> {
1719 ws.send(auth_message)?;
1720
1721 let mut msgs = Vec::new();
1723 loop {
1724 let resp = ws.read()?;
1725 match resp {
1726 Message::Text(msg) => {
1727 let msg: WebSocketResponse = serde_json::from_str(&msg).unwrap();
1728 match msg {
1729 WebSocketResponse::ReadyForQuery(_) => break,
1730 msg => {
1731 msgs.push(msg);
1732 }
1733 }
1734 }
1735 Message::Ping(_) => continue,
1736 Message::Close(None) => return Err(anyhow!("ws closed after auth")),
1737 Message::Close(Some(close_frame)) => {
1738 return Err(anyhow!("ws closed after auth").context(close_frame));
1739 }
1740 _ => panic!("unexpected response: {:?}", resp),
1741 }
1742 }
1743 Ok(msgs)
1744}
1745
1746pub fn make_header<H: Header>(h: H) -> HeaderMap {
1747 let mut map = HeaderMap::new();
1748 map.typed_insert(h);
1749 map
1750}
1751
1752pub fn make_pg_tls<F>(configure: F) -> MakeTlsConnector
1753where
1754 F: FnOnce(&mut SslConnectorBuilder) -> Result<(), ErrorStack>,
1755{
1756 let mut connector_builder = SslConnector::builder(SslMethod::tls()).unwrap();
1757 let options = connector_builder.options() | SslOptions::NO_TLSV1_3;
1778 connector_builder.set_options(options);
1779 configure(&mut connector_builder).unwrap();
1780 MakeTlsConnector::new(connector_builder.build())
1781}
1782
1783pub struct Ca {
1785 pub dir: TempDir,
1786 pub name: X509Name,
1787 pub cert: X509,
1788 pub pkey: PKey<Private>,
1789}
1790
1791impl Ca {
1792 fn make_ca(name: &str, parent: Option<&Ca>) -> Result<Ca, Box<dyn Error>> {
1793 let dir = tempfile::tempdir()?;
1794 let rsa = Rsa::generate(2048)?;
1795 let pkey = PKey::from_rsa(rsa)?;
1796 let name = {
1797 let mut builder = X509NameBuilder::new()?;
1798 builder.append_entry_by_nid(Nid::COMMONNAME, name)?;
1799 builder.build()
1800 };
1801 let cert = {
1802 let mut builder = X509::builder()?;
1803 builder.set_version(2)?;
1804 builder.set_pubkey(&pkey)?;
1805 builder.set_issuer_name(parent.map(|ca| &ca.name).unwrap_or(&name))?;
1806 builder.set_subject_name(&name)?;
1807 builder.set_not_before(&*Asn1Time::days_from_now(0)?)?;
1808 builder.set_not_after(&*Asn1Time::days_from_now(365)?)?;
1809 builder.append_extension(BasicConstraints::new().critical().ca().build()?)?;
1810 builder.sign(
1811 parent.map(|ca| &ca.pkey).unwrap_or(&pkey),
1812 MessageDigest::sha256(),
1813 )?;
1814 builder.build()
1815 };
1816 fs::write(dir.path().join("ca.crt"), cert.to_pem()?)?;
1817 Ok(Ca {
1818 dir,
1819 name,
1820 cert,
1821 pkey,
1822 })
1823 }
1824
1825 pub fn new_root(name: &str) -> Result<Ca, Box<dyn Error>> {
1827 Ca::make_ca(name, None)
1828 }
1829
1830 pub fn ca_cert_path(&self) -> PathBuf {
1832 self.dir.path().join("ca.crt")
1833 }
1834
1835 pub fn request_ca(&self, name: &str) -> Result<Ca, Box<dyn Error>> {
1837 Ca::make_ca(name, Some(self))
1838 }
1839
1840 pub fn request_client_cert(&self, name: &str) -> Result<(PathBuf, PathBuf), Box<dyn Error>> {
1845 self.request_cert(name, iter::empty())
1846 }
1847
1848 pub fn request_cert<I>(&self, name: &str, ips: I) -> Result<(PathBuf, PathBuf), Box<dyn Error>>
1851 where
1852 I: IntoIterator<Item = IpAddr>,
1853 {
1854 let rsa = Rsa::generate(2048)?;
1855 let pkey = PKey::from_rsa(rsa)?;
1856 let subject_name = {
1857 let mut builder = X509NameBuilder::new()?;
1858 builder.append_entry_by_nid(Nid::COMMONNAME, name)?;
1859 builder.build()
1860 };
1861 let cert = {
1862 let mut builder = X509::builder()?;
1863 builder.set_version(2)?;
1864 builder.set_pubkey(&pkey)?;
1865 builder.set_issuer_name(self.cert.subject_name())?;
1866 builder.set_subject_name(&subject_name)?;
1867 builder.set_not_before(&*Asn1Time::days_from_now(0)?)?;
1868 builder.set_not_after(&*Asn1Time::days_from_now(365)?)?;
1869 for ip in ips {
1870 builder.append_extension(
1871 SubjectAlternativeName::new()
1872 .ip(&ip.to_string())
1873 .build(&builder.x509v3_context(None, None))?,
1874 )?;
1875 }
1876 builder.sign(&self.pkey, MessageDigest::sha256())?;
1877 builder.build()
1878 };
1879 let cert_path = self.dir.path().join(Path::new(name).with_extension("crt"));
1880 let key_path = self.dir.path().join(Path::new(name).with_extension("key"));
1881 fs::write(&cert_path, cert.to_pem()?)?;
1882 fs::write(&key_path, pkey.private_key_to_pem_pkcs8()?)?;
1883 Ok((cert_path, key_path))
1884 }
1885}