Skip to main content

mz_testdrive/
action.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10use std::collections::{BTreeMap, BTreeSet};
11use std::future::Future;
12
13use std::path::PathBuf;
14use std::str::FromStr;
15use std::sync::LazyLock;
16use std::time::Duration;
17use std::{env, fs};
18
19use anyhow::{Context, anyhow, bail};
20use async_trait::async_trait;
21use aws_credential_types::provider::ProvideCredentials;
22use aws_types::SdkConfig;
23use futures::future::FutureExt;
24use itertools::Itertools;
25use mz_adapter::catalog::{Catalog, ConnCatalog, DebugAwsContext};
26use mz_adapter::session::Session;
27use mz_build_info::BuildInfo;
28use mz_catalog::config::ClusterReplicaSizeMap;
29use mz_catalog::durable::BootstrapArgs;
30use mz_ccsr::SubjectVersion;
31use mz_kafka_util::client::{
32    MzClientContext, create_new_client_config_simple, create_with_context,
33};
34use mz_ore::error::ErrorExt;
35use mz_ore::metrics::MetricsRegistry;
36use mz_ore::now::SYSTEM_TIME;
37use mz_ore::retry::Retry;
38use mz_ore::secure::Zeroizing;
39use mz_ore::task;
40use mz_ore::url::SensitiveUrl;
41use mz_persist_client::cache::PersistClientCache;
42use mz_persist_client::cfg::PersistConfig;
43use mz_persist_client::rpc::PubSubClientConnection;
44use mz_persist_client::{PersistClient, PersistLocation};
45use mz_postgres_util::{
46    Sql, batch_execute as pg_batch_execute, query as pg_query, query_one as pg_query_one,
47    sql as pg_sql,
48};
49use mz_sql::catalog::EnvironmentId;
50use mz_tls_util::make_tls;
51use openssl::pkcs12::Pkcs12;
52use rdkafka::ClientConfig;
53use rdkafka::producer::Producer;
54use regex::{Captures, Regex};
55use semver::Version;
56use tokio_postgres::CancelToken;
57use tokio_postgres::error::{DbError, SqlState};
58use tracing::info;
59use url::Url;
60
61use crate::error::PosError;
62use crate::parser::{
63    Command, PosCommand, SqlExpectedError, SqlOutput, VersionConstraint, validate_ident,
64};
65use crate::util;
66use crate::util::postgres::postgres_client;
67
68pub mod consistency;
69
70mod duckdb;
71mod file;
72mod fivetran;
73mod glue;
74mod http;
75mod kafka;
76mod mysql;
77mod nop;
78mod persist;
79mod postgres;
80mod protobuf;
81mod psql;
82mod s3;
83mod schema_registry;
84mod set;
85mod skip_end;
86mod skip_if;
87mod sleep;
88mod sql;
89mod sql_server;
90mod version_check;
91mod webhook;
92
93pub(crate) async fn verify_kafka_topics_exhausted(state: &State) -> Result<(), anyhow::Error> {
94    kafka::verify_topics_exhausted(state).await
95}
96
97/// User-settable configuration parameters.
98#[derive(Debug, Clone)]
99pub struct Config {
100    // === Testdrive options. ===
101    /// Variables to make available to the testdrive script.
102    ///
103    /// The value of each entry will be made available to the script in a
104    /// variable named `arg.KEY`.
105    pub arg_vars: BTreeMap<String, String>,
106    /// A random number to distinguish each run of a testdrive script.
107    pub seed: Option<String>,
108    /// Whether to reset Materialize state before executing each script and
109    /// to clean up AWS state after each script.
110    pub reset: bool,
111    /// Force the use of the specified temporary directory to use.
112    ///
113    /// If unspecified, testdrive creates a temporary directory with a random
114    /// name.
115    pub temp_dir: Option<String>,
116    /// Source string to print out on errors.
117    pub source: Option<String>,
118    /// The default timeout for cancellable operations.
119    pub default_timeout: Duration,
120    /// The default number of tries for retriable operations.
121    pub default_max_tries: usize,
122    /// The initial backoff interval for retry operations.
123    ///
124    /// Set to 0 to retry immediately on failure.
125    pub initial_backoff: Duration,
126    /// Backoff factor to use for retry operations.
127    ///
128    /// Set to 1 to retry at a steady pace.
129    pub backoff_factor: f64,
130    /// Should we skip coordinator and catalog consistency checks.
131    pub consistency_checks: consistency::Level,
132    /// How long a single consistency check may take before the test file fails.
133    pub consistency_check_timeout: Duration,
134    /// Whether to run statement logging consistency checks (adds a few seconds at the end of every
135    /// test file).
136    pub check_statement_logging: bool,
137    /// Whether to automatically rewrite wrong results instead of failing.
138    pub rewrite_results: bool,
139
140    // === Materialize options. ===
141    /// The pgwire connection parameters for the Materialize instance that
142    /// testdrive will connect to.
143    pub materialize_pgconfig: tokio_postgres::Config,
144    /// The internal pgwire connection parameters for the Materialize instance that
145    /// testdrive will connect to.
146    pub materialize_internal_pgconfig: tokio_postgres::Config,
147    /// Whether to use HTTPS instead of plain HTTP for the HTTP(S) connections.
148    pub materialize_use_https: bool,
149    /// The port for the public endpoints of the materialize instance that
150    /// testdrive will connect to via HTTP.
151    pub materialize_http_port: u16,
152    /// The port for the internal endpoints of the materialize instance that
153    /// testdrive will connect to via HTTP.
154    pub materialize_internal_http_port: u16,
155    /// The port for the password endpoints of the materialize instance that
156    /// testdrive will connect to via SQL.
157    pub materialize_password_sql_port: u16,
158    /// The port for the SASL endpoints of the materialize instance that
159    /// testdrive will connect to via SQL.
160    pub materialize_sasl_sql_port: u16,
161    /// Session parameters to set after connecting to materialize.
162    pub materialize_params: Vec<(String, String)>,
163    /// An optional catalog configuration.
164    pub materialize_catalog_config: Option<CatalogConfig>,
165    /// Build information
166    pub build_info: &'static BuildInfo,
167    /// Configured cluster replica sizes
168    pub materialize_cluster_replica_sizes: ClusterReplicaSizeMap,
169
170    // === Persist options. ===
171    /// Handle to the persist consensus system.
172    pub persist_consensus_url: Option<SensitiveUrl>,
173    /// Handle to the persist blob storage.
174    pub persist_blob_url: Option<SensitiveUrl>,
175
176    // === Confluent options. ===
177    /// The address of the Kafka broker that testdrive will interact with.
178    pub kafka_addr: String,
179    /// Default number of partitions to use for topics
180    pub kafka_default_partitions: usize,
181    /// Arbitrary rdkafka options for testdrive to use when connecting to the
182    /// Kafka broker.
183    pub kafka_opts: Vec<(String, String)>,
184    /// The URL of the schema registry that testdrive will connect to.
185    pub schema_registry_url: Url,
186    /// An optional path to a TLS certificate that testdrive will present when
187    /// performing client authentication.
188    ///
189    /// The keystore must be in the PKCS#12 format.
190    pub cert_path: Option<String>,
191    /// An optional password for the TLS certificate.
192    pub cert_password: Option<String>,
193    /// An optional username for basic authentication with the Confluent Schema
194    /// Registry.
195    pub ccsr_username: Option<String>,
196    /// An optional password for basic authentication with the Confluent Schema
197    /// Registry.
198    pub ccsr_password: Option<String>,
199
200    // === AWS options. ===
201    /// The configuration to use when connecting to AWS.
202    pub aws_config: SdkConfig,
203    /// The ID of the AWS account that `aws_config` configures.
204    pub aws_account: String,
205
206    // === Fivetran options. ===
207    /// Address of the Fivetran Destination that is currently running.
208    pub fivetran_destination_url: String,
209    /// Directory that is accessible to the Fivetran Destination.
210    pub fivetran_destination_files_path: String,
211}
212
213pub struct MaterializeState {
214    catalog_config: Option<CatalogConfig>,
215
216    sql_addr: String,
217    use_https: bool,
218    http_addr: String,
219    internal_sql_addr: String,
220    internal_http_addr: String,
221    password_sql_addr: String,
222    sasl_sql_addr: String,
223    user: String,
224    pgclient: tokio_postgres::Client,
225    environment_id: EnvironmentId,
226    bootstrap_args: BootstrapArgs,
227    // The AWS environment context, queried once from the running environmentd at
228    // startup, the same way environment_id is. The builtin AWS connection views
229    // fold these values into their optimized expressions, so the catalog copy
230    // opened for the consistency check must resolve them the same way. Queried
231    // at startup rather than at check time because a check-time query runs after
232    // arbitrary test state and is less reliable, while startup runs against a
233    // clean session on the currently connected version.
234    aws_account_id: Option<String>,
235    aws_external_id_prefix: Option<String>,
236    aws_connection_role_arn: Option<String>,
237}
238
239pub struct State {
240    // The Config that this `State` was originally created from.
241    pub config: Config,
242
243    // === Testdrive state. ===
244    arg_vars: BTreeMap<String, String>,
245    cmd_vars: BTreeMap<String, String>,
246    seed: String,
247    temp_path: PathBuf,
248    _tempfile: Option<tempfile::TempDir>,
249    default_timeout: Duration,
250    timeout: Duration,
251    max_tries: usize,
252    initial_backoff: Duration,
253    backoff_factor: f64,
254    consistency_checks: consistency::Level,
255    consistency_check_timeout: Duration,
256    check_statement_logging: bool,
257    consistency_checks_adhoc_skip: bool,
258    regex: Option<Regex>,
259    regex_replacement: String,
260    error_line_count: usize,
261    error_string: String,
262
263    // === Materialize state. ===
264    materialize: MaterializeState,
265
266    // === Persist state. ===
267    persist_consensus_url: Option<SensitiveUrl>,
268    persist_blob_url: Option<SensitiveUrl>,
269    build_info: &'static BuildInfo,
270    persist_clients: PersistClientCache,
271
272    // === Confluent state. ===
273    schema_registry_url: Url,
274    ccsr_client: mz_ccsr::Client,
275    kafka_addr: String,
276    kafka_admin: rdkafka::admin::AdminClient<MzClientContext>,
277    kafka_admin_opts: rdkafka::admin::AdminOptions,
278    kafka_config: ClientConfig,
279    kafka_default_partitions: usize,
280    kafka_producer: rdkafka::producer::FutureProducer<MzClientContext>,
281    kafka_topics: BTreeMap<String, usize>,
282    /// Topics whose final `kafka-verify-data` must consume the complete topic.
283    kafka_verify_topics: BTreeSet<String>,
284
285    // === AWS state. ===
286    aws_account: String,
287    aws_config: SdkConfig,
288
289    // === Database driver state. ===
290    pub duckdb_clients: BTreeMap<String, std::sync::Arc<std::sync::Mutex<::duckdb::Connection>>>,
291    mysql_clients: BTreeMap<String, mysql_async::Conn>,
292    postgres_clients: BTreeMap<String, tokio_postgres::Client>,
293    sql_server_clients: BTreeMap<String, mz_sql_server_util::Client>,
294    /// Tasks spawned by `postgres-execute background=true`. Joined at the end
295    /// of the file so their failures fail the test.
296    background_tasks: Vec<BackgroundTask>,
297
298    // === Fivetran state. ===
299    fivetran_destination_url: String,
300    fivetran_destination_files_path: String,
301
302    // === Rewrite state. ===
303    rewrite_results: bool,
304    /// Current file, results are replaced inline
305    pub rewrites: Vec<Rewrite>,
306    /// Start position of currently expected result
307    pub rewrite_pos_start: usize,
308    /// End position of currently expected result
309    pub rewrite_pos_end: usize,
310}
311
312pub struct Rewrite {
313    pub content: String,
314    pub start: usize,
315    pub end: usize,
316}
317
318/// A query spawned by `postgres-execute background=true`, retained so it can be
319/// joined at the end of the file.
320///
321/// Aborting `handle` stops the Rust task from awaiting the query's response,
322/// but it does not stop the query on the server. The tokio-postgres connection
323/// driver waits for every pending response before it closes the connection, so
324/// dropping the client leaves the SQL running until Materialize replies. To
325/// actually stop a query that overran its deadline we send an out-of-band
326/// cancel request through `cancel_token`, the same mechanism psql uses for
327/// Ctrl-C, before aborting the task.
328pub(crate) struct BackgroundTask {
329    desc: String,
330    handle: task::JoinHandle<Result<(), anyhow::Error>>,
331    cancel_token: CancelToken,
332    /// Connection URL, used to rebuild the TLS connector that the cancel
333    /// request opens its own connection with.
334    url: String,
335}
336
337/// Best-effort cancellation of the in-progress query on the connection
338/// `cancel_token` was derived from. Opens a fresh connection to send the cancel
339/// request. Cancellation is inherently racy and the caller aborts the task
340/// regardless, so failures are logged rather than propagated.
341async fn cancel_background_query(cancel_token: &CancelToken, url: &str, timeout: Duration) {
342    let tls = match tokio_postgres::Config::from_str(url)
343        .map_err(anyhow::Error::from)
344        .and_then(|config| make_tls(&config).map_err(anyhow::Error::from))
345    {
346        Ok(tls) => tls,
347        Err(e) => {
348            tracing::warn!("could not build TLS connector to cancel background query: {e}");
349            return;
350        }
351    };
352    match tokio::time::timeout(timeout, cancel_token.cancel_query(tls)).await {
353        Ok(Ok(())) => {}
354        Ok(Err(e)) => tracing::warn!("cancel request for background query failed: {e}"),
355        Err(_) => tracing::warn!("cancel request for background query timed out"),
356    }
357}
358
359impl State {
360    pub async fn initialize_cmd_vars(&mut self) -> Result<(), anyhow::Error> {
361        self.cmd_vars
362            .insert("testdrive.kafka-addr".into(), self.kafka_addr.clone());
363        self.cmd_vars.insert(
364            "testdrive.schema-registry-url".into(),
365            self.schema_registry_url.to_string(),
366        );
367        self.cmd_vars
368            .insert("testdrive.seed".into(), self.seed.clone());
369        self.cmd_vars.insert(
370            "testdrive.temp-dir".into(),
371            self.temp_path.display().to_string(),
372        );
373        self.cmd_vars
374            .insert("testdrive.aws-region".into(), self.aws_region().into());
375        self.cmd_vars
376            .insert("testdrive.aws-endpoint".into(), self.aws_endpoint().into());
377        self.cmd_vars
378            .insert("testdrive.aws-account".into(), self.aws_account.clone());
379        {
380            let aws_credentials = self
381                .aws_config
382                .credentials_provider()
383                .ok_or_else(|| anyhow!("no AWS credentials provider configured"))?
384                .provide_credentials()
385                .await
386                .context("fetching AWS credentials")?;
387            self.cmd_vars.insert(
388                "testdrive.aws-access-key-id".into(),
389                aws_credentials.access_key_id().to_owned(),
390            );
391            self.cmd_vars.insert(
392                "testdrive.aws-secret-access-key".into(),
393                aws_credentials.secret_access_key().to_owned(),
394            );
395            self.cmd_vars.insert(
396                "testdrive.aws-token".into(),
397                aws_credentials
398                    .session_token()
399                    .map(|token| token.to_owned())
400                    .unwrap_or_else(String::new),
401            );
402        }
403        self.cmd_vars.insert(
404            "testdrive.materialize-environment-id".into(),
405            self.materialize.environment_id.to_string(),
406        );
407        self.cmd_vars.insert(
408            "testdrive.materialize-sql-addr".into(),
409            self.materialize.sql_addr.clone(),
410        );
411        self.cmd_vars.insert(
412            "testdrive.materialize-internal-sql-addr".into(),
413            self.materialize.internal_sql_addr.clone(),
414        );
415        self.cmd_vars.insert(
416            "testdrive.materialize-password-sql-addr".into(),
417            self.materialize.password_sql_addr.clone(),
418        );
419        self.cmd_vars.insert(
420            "testdrive.materialize-sasl-sql-addr".into(),
421            self.materialize.sasl_sql_addr.clone(),
422        );
423        self.cmd_vars.insert(
424            "testdrive.materialize-user".into(),
425            self.materialize.user.clone(),
426        );
427        self.cmd_vars.insert(
428            "testdrive.fivetran-destination-url".into(),
429            self.fivetran_destination_url.clone(),
430        );
431        self.cmd_vars.insert(
432            "testdrive.fivetran-destination-files-path".into(),
433            self.fivetran_destination_files_path.clone(),
434        );
435
436        for (key, value) in env::vars() {
437            self.cmd_vars.insert(format!("env.{}", key), value);
438        }
439
440        for (key, value) in &self.arg_vars {
441            validate_ident(key)?;
442            self.cmd_vars
443                .insert(format!("arg.{}", key), value.to_string());
444        }
445
446        Ok(())
447    }
448    /// Makes of copy of the durable catalog and runs a function on its
449    /// state. Returns `None` if there's no catalog information in the State.
450    pub async fn with_catalog_copy<F, T>(
451        &self,
452        system_parameter_defaults: BTreeMap<String, String>,
453        build_info: &'static BuildInfo,
454        bootstrap_args: &BootstrapArgs,
455        enable_expression_cache_override: Option<bool>,
456        f: F,
457    ) -> Result<Option<T>, anyhow::Error>
458    where
459        F: FnOnce(ConnCatalog) -> T,
460    {
461        async fn persist_client(
462            persist_consensus_url: SensitiveUrl,
463            persist_blob_url: SensitiveUrl,
464            persist_clients: &PersistClientCache,
465        ) -> Result<PersistClient, anyhow::Error> {
466            let persist_location = PersistLocation {
467                blob_uri: persist_blob_url,
468                consensus_uri: persist_consensus_url,
469            };
470            Ok(persist_clients.open(persist_location).await?)
471        }
472
473        if let Some(CatalogConfig {
474            persist_consensus_url,
475            persist_blob_url,
476        }) = &self.materialize.catalog_config
477        {
478            let persist_client = persist_client(
479                persist_consensus_url.clone(),
480                persist_blob_url.clone(),
481                &self.persist_clients,
482            )
483            .await?;
484            let aws_context = DebugAwsContext {
485                aws_account_id: self.materialize.aws_account_id.clone(),
486                aws_external_id_prefix: self.materialize.aws_external_id_prefix.clone(),
487                aws_connection_role_arn: self.materialize.aws_connection_role_arn.clone(),
488            };
489            let catalog = Catalog::open_debug_read_only_persist_catalog_config(
490                persist_client,
491                SYSTEM_TIME.clone(),
492                self.materialize.environment_id.clone(),
493                system_parameter_defaults,
494                build_info,
495                bootstrap_args,
496                enable_expression_cache_override,
497                Some(aws_context),
498            )
499            .await?;
500            let res = f(catalog.for_session(&Session::dummy()));
501            catalog.expire().await;
502            Ok(Some(res))
503        } else {
504            Ok(None)
505        }
506    }
507
508    pub fn aws_endpoint(&self) -> &str {
509        self.aws_config.endpoint_url().unwrap_or("")
510    }
511
512    pub fn aws_region(&self) -> &str {
513        self.aws_config.region().map(|r| r.as_ref()).unwrap_or("")
514    }
515
516    /// Resets the adhoc skip consistency check that users can toggle per-file, and returns whether
517    /// the consistency checks should be skipped for this current run.
518    pub fn clear_skip_consistency_checks(&mut self) -> bool {
519        std::mem::replace(&mut self.consistency_checks_adhoc_skip, false)
520    }
521
522    /// Joins all tasks spawned by `postgres-execute background=true`,
523    /// returning one error per task that failed or did not complete within the
524    /// default timeout. Must be called before the end of the file so that
525    /// background failures fail the test.
526    pub(crate) async fn join_background_tasks(&mut self) -> Vec<anyhow::Error> {
527        let mut errors = Vec::new();
528        for BackgroundTask {
529            desc,
530            mut handle,
531            cancel_token,
532            url,
533        } in self.background_tasks.drain(..)
534        {
535            // Poll the handle by reference so it survives a timeout. Dropping a
536            // `JoinHandle` only detaches the task, it does not stop it, and a
537            // detached background query would keep running SQL against the same
538            // Materialize instance while later files execute.
539            match tokio::time::timeout(self.default_timeout, &mut handle).await {
540                Ok(Ok(())) => {}
541                Ok(Err(e)) => errors.push(e.context(format!("background query failed: {desc}"))),
542                Err(_) => {
543                    // Aborting `handle` alone leaves the query running on the
544                    // server. Cancel it first so it cannot overlap consistency
545                    // checks or later files, then abort and reap the task.
546                    cancel_background_query(&cancel_token, &url, self.default_timeout).await;
547                    handle.abort_and_wait().await;
548                    errors.push(anyhow!(
549                        "background query did not complete before the end of the file: {desc}"
550                    ));
551                }
552            }
553        }
554        errors
555    }
556
557    pub async fn reset_materialize(&self) -> Result<(), anyhow::Error> {
558        let (inner_client, _) = postgres_client(
559            &format!(
560                "postgres://mz_system:materialize@{}",
561                self.materialize.internal_sql_addr
562            ),
563            self.default_timeout,
564        )
565        .await?;
566
567        let version = pg_query_one(&inner_client, pg_sql!("SELECT mz_version_num()"), &[])
568            .await
569            .context("getting version of materialize")
570            .map(|row| row.get::<_, i32>(0))?;
571
572        let semver = pg_query_one(
573            &inner_client,
574            pg_sql!("SELECT right(split_part(mz_version(), ' ', 1), -1)"),
575            &[],
576        )
577        .await
578        .context("getting semver of materialize")
579        .map(|row| row.get::<_, String>(0))?
580        .parse::<semver::Version>()
581        .context("parsing semver of materialize")?;
582
583        pg_batch_execute(&inner_client, pg_sql!("ALTER SYSTEM RESET ALL"))
584            .await
585            .context("resetting materialize state: ALTER SYSTEM RESET ALL")?;
586
587        // Dangerous functions are useful for tests so we enable it for all tests.
588        {
589            let rename_version = Version::parse("0.128.0-dev.1").expect("known to be valid");
590            let enable_unsafe_functions = if semver >= rename_version {
591                "unsafe_enable_unsafe_functions"
592            } else {
593                "enable_unsafe_functions"
594            };
595            let res = pg_batch_execute(
596                &inner_client,
597                pg_sql!(
598                    "ALTER SYSTEM SET {} = on",
599                    Sql::ident(enable_unsafe_functions)
600                ),
601            )
602            .await
603            .context("enabling dangerous functions");
604            if let Err(e) = res {
605                match e.root_cause().downcast_ref::<DbError>() {
606                    Some(e) if *e.code() == SqlState::CANT_CHANGE_RUNTIME_PARAM => {
607                        info!(
608                            "can't enable unsafe functions because the server is safe mode; \
609                             testdrive scripts will fail if they use unsafe functions",
610                        );
611                    }
612                    _ => return Err(e),
613                }
614            }
615        }
616
617        for row in pg_query(&inner_client, pg_sql!("SHOW DATABASES"), &[])
618            .await
619            .context("resetting materialize state: SHOW DATABASES")?
620        {
621            let db_name: String = row.get(0);
622            if db_name.starts_with("testdrive_no_reset_") {
623                continue;
624            }
625            let drop_database = pg_sql!("DROP DATABASE {}", Sql::ident(&db_name));
626            sql::print_query(drop_database.as_str(), None);
627            pg_batch_execute(&inner_client, drop_database)
628                .await
629                .context(format!(
630                    "resetting materialize state: DROP DATABASE {}",
631                    db_name,
632                ))?;
633        }
634
635        // Get all user clusters not running any objects owned by users
636        let inactive_user_clusters = "
637        WITH
638            active_user_clusters AS
639            (
640                SELECT DISTINCT cluster_id, object_id
641                FROM
642                    (
643                        SELECT cluster_id, id FROM mz_catalog.mz_sources
644                        UNION ALL SELECT cluster_id, id FROM mz_catalog.mz_sinks
645                        UNION ALL
646                            SELECT cluster_id, id
647                            FROM mz_catalog.mz_materialized_views
648                        UNION ALL
649                            SELECT cluster_id, id FROM mz_catalog.mz_indexes
650                        UNION ALL
651                            SELECT cluster_id, id
652                            FROM mz_internal.mz_subscriptions
653                    )
654                    AS t (cluster_id, object_id)
655                WHERE cluster_id IS NOT NULL AND object_id LIKE 'u%'
656            )
657        SELECT name
658        FROM mz_catalog.mz_clusters
659        WHERE
660            id NOT IN ( SELECT cluster_id FROM active_user_clusters ) AND id LIKE 'u%'
661                AND
662            owner_id LIKE 'u%';";
663
664        let inactive_clusters = pg_query(&inner_client, Sql::new(inactive_user_clusters), &[])
665            .await
666            .context("resetting materialize state: inactive_user_clusters")?;
667
668        if !inactive_clusters.is_empty() {
669            println!("cleaning up user clusters from previous tests...")
670        }
671
672        for cluster_name in inactive_clusters {
673            let cluster_name: String = cluster_name.get(0);
674            if cluster_name.starts_with("testdrive_no_reset_") {
675                continue;
676            }
677            let drop_cluster = pg_sql!("DROP CLUSTER {}", Sql::ident(&cluster_name));
678            sql::print_query(drop_cluster.as_str(), None);
679            pg_batch_execute(&inner_client, drop_cluster)
680                .await
681                .context(format!(
682                    "resetting materialize state: DROP CLUSTER {}",
683                    cluster_name,
684                ))?;
685        }
686
687        pg_batch_execute(&inner_client, pg_sql!("CREATE DATABASE materialize"))
688            .await
689            .context("resetting materialize state: CREATE DATABASE materialize")?;
690
691        // Attempt to remove all users but the current user. Old versions of
692        // Materialize did not support roles, so this degrades gracefully if
693        // mz_roles does not exist.
694        if let Ok(rows) = pg_query(&inner_client, pg_sql!("SELECT name FROM mz_roles"), &[]).await {
695            for row in rows {
696                let role_name: String = row.get(0);
697                if role_name == self.materialize.user || role_name.starts_with("mz_") {
698                    continue;
699                }
700                let drop_role = pg_sql!("DROP ROLE {}", Sql::ident(&role_name));
701                sql::print_query(drop_role.as_str(), None);
702                pg_batch_execute(&inner_client, drop_role)
703                    .await
704                    .context(format!(
705                        "resetting materialize state: DROP ROLE {}",
706                        role_name,
707                    ))?;
708            }
709        }
710
711        // Alter materialize user with all system privileges.
712        pg_batch_execute(
713            &inner_client,
714            pg_sql!(
715                "GRANT ALL PRIVILEGES ON SYSTEM TO {}",
716                Sql::ident(&self.materialize.user)
717            ),
718        )
719        .await?;
720
721        // Grant initial privileges.
722        pg_batch_execute(
723            &inner_client,
724            pg_sql!("GRANT USAGE ON DATABASE materialize TO PUBLIC"),
725        )
726        .await?;
727        pg_batch_execute(
728            &inner_client,
729            pg_sql!(
730                "GRANT ALL PRIVILEGES ON DATABASE materialize TO {}",
731                Sql::ident(&self.materialize.user)
732            ),
733        )
734        .await?;
735        pg_batch_execute(
736            &inner_client,
737            pg_sql!(
738                "GRANT ALL PRIVILEGES ON SCHEMA materialize.public TO {}",
739                Sql::ident(&self.materialize.user)
740            ),
741        )
742        .await?;
743
744        let cluster = match version {
745            ..=8199 => "default",
746            8200.. => "quickstart",
747        };
748        pg_batch_execute(
749            &inner_client,
750            pg_sql!("GRANT USAGE ON CLUSTER {} TO PUBLIC", Sql::ident(cluster)),
751        )
752        .await?;
753        pg_batch_execute(
754            &inner_client,
755            pg_sql!(
756                "GRANT ALL PRIVILEGES ON CLUSTER {} TO {}",
757                Sql::ident(cluster),
758                Sql::ident(&self.materialize.user)
759            ),
760        )
761        .await?;
762
763        Ok(())
764    }
765
766    /// Delete Kafka topics + CCSR subjects that were created in this run
767    pub async fn reset_kafka(&self) -> Result<(), anyhow::Error> {
768        use rdkafka::types::RDKafkaErrorCode;
769        let mut errors: Vec<anyhow::Error> = Vec::new();
770
771        let metadata = self.kafka_producer.client().fetch_metadata(
772            None,
773            Some(std::cmp::max(Duration::from_secs(1), self.default_timeout)),
774        )?;
775
776        let testdrive_topics: Vec<_> = metadata
777            .topics()
778            .iter()
779            .filter_map(|t| {
780                if t.name().starts_with("testdrive-") {
781                    Some(t.name())
782                } else {
783                    None
784                }
785            })
786            .collect();
787
788        if !testdrive_topics.is_empty() {
789            match self
790                .kafka_admin
791                .delete_topics(&testdrive_topics, &self.kafka_admin_opts)
792                .await
793            {
794                Ok(res) => {
795                    if res.len() != testdrive_topics.len() {
796                        errors.push(anyhow!(
797                            "kafka topic deletion returned {} results, but exactly {} expected",
798                            res.len(),
799                            testdrive_topics.len()
800                        ));
801                    }
802                    for (res, topic) in res.iter().zip_eq(testdrive_topics.iter()) {
803                        match res {
804                            Ok(_) | Err((_, RDKafkaErrorCode::UnknownTopicOrPartition)) => (),
805                            Err((_, err)) => {
806                                errors.push(anyhow!("unable to delete {}: {}", topic, err));
807                            }
808                        }
809                    }
810                }
811                Err(e) => {
812                    errors.push(e.into());
813                }
814            };
815        }
816
817        let schema_registry_errors = self.reset_schema_registry().await;
818
819        errors.extend(schema_registry_errors);
820        if errors.is_empty() {
821            Ok(())
822        } else {
823            bail!(
824                "deleting Kafka topics: {} errors: {}",
825                errors.len(),
826                errors
827                    .into_iter()
828                    .map(|e| e.to_string_with_causes())
829                    .join("\n")
830            );
831        }
832    }
833
834    #[allow(clippy::disallowed_types)]
835    async fn reset_schema_registry(&self) -> Vec<anyhow::Error> {
836        use std::collections::HashMap;
837
838        let mut errors = Vec::new();
839        match self
840            .ccsr_client
841            .list_subjects()
842            .await
843            .context("listing schema registry subjects")
844        {
845            Ok(subjects) => {
846                let testdrive_subjects: Vec<_> = subjects
847                    .into_iter()
848                    .filter(|s| s.starts_with("testdrive-"))
849                    .collect();
850
851                // Build the dependency graphs: subject -> list of subjects it references
852                let mut graphs: HashMap<SubjectVersion, Vec<SubjectVersion>> = HashMap::new();
853
854                for subject in &testdrive_subjects {
855                    match self.ccsr_client.get_subject_with_references(subject).await {
856                        Ok((subj, refs)) => {
857                            // Filter to only testdrive subjects
858                            let refs: Vec<_> = refs
859                                .into_iter()
860                                .filter(|r| r.subject.starts_with("testdrive-"))
861                                .collect();
862                            graphs.insert(
863                                SubjectVersion {
864                                    subject: subj.name,
865                                    version: subj.version,
866                                },
867                                refs,
868                            );
869                        }
870                        Err(mz_ccsr::GetBySubjectError::SubjectNotFound) => {
871                            // Subject was already deleted, skip it
872                        }
873                        Err(e) => {
874                            errors.push(anyhow::anyhow!(
875                                "failed to get references for subject {}: {}",
876                                subject,
877                                e
878                            ));
879                        }
880                    }
881                }
882
883                // Get topological ordering (0 = root/no dependencies, higher = more dependents)
884                // We need to delete in reverse order (highest first = subjects that depend on others)
885                let subjects_to_delete: Vec<_> = match mz_ccsr::topological_sort(&graphs) {
886                    Ok(ordered) => {
887                        let mut subjects: Vec<_> = ordered.into_iter().collect();
888                        subjects.sort_by(|a, b| a.1.cmp(&b.1));
889                        subjects.into_iter().map(|(s, _)| s.clone()).collect()
890                    }
891                    Err(_) => {
892                        tracing::info!("Cycle detected, attempting to delete anyway");
893                        // Cycle detected or other error - fall back to deleting in any order
894                        graphs.into_keys().collect()
895                    }
896                };
897
898                for subject in subjects_to_delete {
899                    match self.ccsr_client.delete_subject(&subject.subject).await {
900                        Ok(()) | Err(mz_ccsr::DeleteError::SubjectNotFound) => (),
901                        Err(e) => errors.push(e.into()),
902                    }
903                }
904            }
905            Err(e) => {
906                errors.push(e);
907            }
908        }
909        errors
910    }
911}
912
913/// Configuration for the Catalog.
914#[derive(Debug, Clone)]
915pub struct CatalogConfig {
916    /// Handle to the persist consensus system.
917    pub persist_consensus_url: SensitiveUrl,
918    /// Handle to the persist blob storage.
919    pub persist_blob_url: SensitiveUrl,
920}
921
922pub enum ControlFlow {
923    Continue,
924    SkipBegin,
925    SkipEnd,
926}
927
928#[async_trait]
929pub(crate) trait Run {
930    async fn run(self, state: &mut State) -> Result<ControlFlow, PosError>;
931}
932
933#[async_trait]
934impl Run for PosCommand {
935    async fn run(self, state: &mut State) -> Result<ControlFlow, PosError> {
936        macro_rules! handle_version {
937            ($version_constraint:expr) => {
938                match $version_constraint {
939                    Some(VersionConstraint { min, max }) => {
940                        match version_check::run_version_check(min, max, state).await {
941                            Ok(true) => return Ok(ControlFlow::Continue),
942                            Ok(false) => {}
943                            Err(err) => return Err(PosError::new(err, self.pos)),
944                        }
945                    }
946                    None => {}
947                }
948            };
949        }
950
951        let wrap_err = |e| PosError::new(e, self.pos);
952        // Substitute variables at startup except for the command-specific ones
953        // Those will be substituted at runtime
954        let ignore_prefix = match &self.command {
955            Command::Builtin(builtin, _) => Some(builtin.name.clone()),
956            _ => None,
957        };
958        let subst = |msg: &str, vars: &BTreeMap<String, String>| {
959            substitute_vars(msg, vars, &ignore_prefix, false).map_err(wrap_err)
960        };
961        let subst_re = |msg: &str, vars: &BTreeMap<String, String>| {
962            substitute_vars(msg, vars, &ignore_prefix, true).map_err(wrap_err)
963        };
964
965        let r = match self.command {
966            Command::Builtin(mut builtin, version_constraint) => {
967                handle_version!(version_constraint);
968                for val in builtin.args.values_mut() {
969                    *val = subst(val, &state.cmd_vars)?;
970                }
971                for line in &mut builtin.input {
972                    *line = subst(line, &state.cmd_vars)?;
973                }
974                match builtin.name.as_ref() {
975                    "check-consistency" => consistency::run_consistency_checks(state).await,
976                    "skip-consistency-checks" => {
977                        consistency::skip_consistency_checks(builtin, state)
978                    }
979                    "check-shard-tombstone" => {
980                        consistency::run_check_shard_tombstone(builtin, state).await
981                    }
982                    "duckdb-execute" => duckdb::run_execute(builtin, state).await,
983                    "duckdb-query" => duckdb::run_query(builtin, state).await,
984                    "fivetran-destination" => {
985                        fivetran::run_destination_command(builtin, state).await
986                    }
987                    "file-append" => file::run_append(builtin, state).await,
988                    "file-delete" => file::run_delete(builtin, state).await,
989                    "glue-create-schema" => glue::run_create_schema(builtin, state).await,
990                    "glue-verify-compatibility" => {
991                        glue::run_verify_compatibility(builtin, state).await
992                    }
993                    "http-request" => http::run_request(builtin, state).await,
994                    "kafka-add-partitions" => kafka::run_add_partitions(builtin, state).await,
995                    "kafka-create-topic" => kafka::run_create_topic(builtin, state).await,
996                    "kafka-wait-topic" => kafka::run_wait_topic(builtin, state).await,
997                    "kafka-delete-records" => kafka::run_delete_records(builtin, state).await,
998                    "kafka-delete-topic-flaky" => kafka::run_delete_topic(builtin, state).await,
999                    "kafka-ingest" => kafka::run_ingest(builtin, state).await,
1000                    "kafka-verify-data" => kafka::run_verify_data(builtin, state).await,
1001                    "kafka-verify-commit" => kafka::run_verify_commit(builtin, state).await,
1002                    "kafka-verify-topic" => kafka::run_verify_topic(builtin, state).await,
1003                    "mysql-connect" => mysql::run_connect(builtin, state).await,
1004                    "mysql-execute" => mysql::run_execute(builtin, state).await,
1005                    "nop" => nop::run_nop(),
1006                    "postgres-connect" => postgres::run_connect(builtin, state).await,
1007                    "postgres-execute" => postgres::run_execute(builtin, state).await,
1008                    "postgres-verify-slot" => postgres::run_verify_slot(builtin, state).await,
1009                    "protobuf-compile-descriptors" => {
1010                        protobuf::run_compile_descriptors(builtin, state).await
1011                    }
1012                    "psql-execute" => psql::run_execute(builtin, state).await,
1013                    "s3-verify-data" => s3::run_verify_data(builtin, state).await,
1014                    "s3-verify-keys" => s3::run_verify_keys(builtin, state).await,
1015                    "s3-file-upload" => s3::run_upload(builtin, state).await,
1016                    "s3-set-presigned-url" => s3::run_set_presigned_url(builtin, state).await,
1017                    "s3-upload-parquet-types" => s3::run_upload_parquet_types(builtin, state).await,
1018                    "s3-upload-parquet-unsorted-map" => {
1019                        s3::run_upload_parquet_unsorted_map(builtin, state).await
1020                    }
1021                    "schema-registry-publish" => schema_registry::run_publish(builtin, state).await,
1022                    "schema-registry-verify" => schema_registry::run_verify(builtin, state).await,
1023                    "schema-registry-wait" => schema_registry::run_wait(builtin, state).await,
1024                    "skip-if" => skip_if::run_skip_if(builtin, state).await,
1025                    "skip-end" => skip_end::run_skip_end(),
1026                    "sql-server-connect" => sql_server::run_connect(builtin, state).await,
1027                    "sql-server-execute" => sql_server::run_execute(builtin, state).await,
1028                    "sql-server-set-from-sql" => sql_server::run_set_from_sql(builtin, state).await,
1029                    "persist-force-compaction" => {
1030                        persist::run_force_compaction(builtin, state).await
1031                    }
1032                    "random-sleep" => sleep::run_random_sleep(builtin),
1033                    "set-regex" => set::run_regex_set(builtin, state),
1034                    "unset-regex" => set::run_regex_unset(builtin, state),
1035                    "set-sql-timeout" => set::run_sql_timeout(builtin, state),
1036                    "set-max-tries" => set::run_max_tries(builtin, state),
1037                    "sleep-is-probably-flaky-i-have-justified-my-need-with-a-comment" => {
1038                        sleep::run_sleep(builtin)
1039                    }
1040                    "set" => set::set_vars(builtin, state),
1041                    "set-arg-default" => set::run_set_arg_default(builtin, state),
1042                    "set-from-sql" => set::run_set_from_sql(builtin, state).await,
1043                    "set-from-file" => set::run_set_from_file(builtin, state).await,
1044                    "webhook-append" => webhook::run_append(builtin, state).await,
1045                    _ => {
1046                        return Err(PosError::new(
1047                            anyhow!("unknown built-in command {}", builtin.name),
1048                            self.pos,
1049                        ));
1050                    }
1051                }
1052            }
1053            Command::Sql(mut sql, version_constraint) => {
1054                handle_version!(version_constraint);
1055                sql.query = subst(&sql.query, &state.cmd_vars)?;
1056                if let SqlOutput::Full { expected_rows, .. } = &mut sql.expected_output {
1057                    for row in expected_rows {
1058                        for col in row {
1059                            *col = subst(col, &state.cmd_vars)?;
1060                        }
1061                    }
1062                }
1063                sql::run_sql(sql, state).await
1064            }
1065            Command::FailSql(mut sql, version_constraint) => {
1066                handle_version!(version_constraint);
1067                sql.query = subst(&sql.query, &state.cmd_vars)?;
1068                sql.expected_error = match &sql.expected_error {
1069                    SqlExpectedError::Contains(s) => {
1070                        SqlExpectedError::Contains(subst(s, &state.cmd_vars)?)
1071                    }
1072                    SqlExpectedError::Exact(s) => {
1073                        SqlExpectedError::Exact(subst(s, &state.cmd_vars)?)
1074                    }
1075                    SqlExpectedError::Regex(s) => {
1076                        SqlExpectedError::Regex(subst_re(s, &state.cmd_vars)?)
1077                    }
1078                    SqlExpectedError::Timeout => SqlExpectedError::Timeout,
1079                };
1080                sql.expected_detail = match sql.expected_detail {
1081                    Some(s) => Some(subst(&s, &state.cmd_vars)?),
1082                    None => None,
1083                };
1084                sql.expected_hint = match sql.expected_hint {
1085                    Some(s) => Some(subst(&s, &state.cmd_vars)?),
1086                    None => None,
1087                };
1088                sql::run_fail_sql(sql, state).await
1089            }
1090        };
1091
1092        r.map_err(wrap_err)
1093    }
1094}
1095
1096/// Substituted `${}`-delimited variables from `vars` into `msg`
1097fn substitute_vars(
1098    msg: &str,
1099    vars: &BTreeMap<String, String>,
1100    ignore_prefix: &Option<String>,
1101    regex_escape: bool,
1102) -> Result<String, anyhow::Error> {
1103    static RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\$\{([^}]+)\}").unwrap());
1104    let mut err = None;
1105    let out = RE.replace_all(msg, |caps: &Captures| {
1106        let name = &caps[1];
1107        if let Some(ignore_prefix) = &ignore_prefix {
1108            if name.starts_with(format!("{}.", ignore_prefix).as_str()) {
1109                // Do not substitute, leave original variable name in place
1110                return caps.get(0).unwrap().as_str().to_string();
1111            }
1112        }
1113
1114        if let Some(val) = vars.get(name) {
1115            if regex_escape {
1116                regex::escape(val)
1117            } else {
1118                val.to_string()
1119            }
1120        } else {
1121            err = Some(anyhow!("unknown variable: {}", name));
1122            "#VAR-MISSING#".to_string()
1123        }
1124    });
1125    match err {
1126        Some(err) => Err(err),
1127        None => Ok(out.into_owned()),
1128    }
1129}
1130
1131/// Initializes a [`State`] object by connecting to the various external
1132/// services specified in `config`.
1133///
1134/// Returns the initialized `State` and a cleanup future. The cleanup future
1135/// should be `await`ed only *after* dropping the `State` to check whether any
1136/// errors occured while dropping the `State`. This awkward API is a workaround
1137/// for the lack of `AsyncDrop` support in Rust.
1138pub async fn create_state(
1139    config: &Config,
1140) -> Result<(State, impl Future<Output = Result<(), anyhow::Error>>), anyhow::Error> {
1141    let seed = config
1142        .seed
1143        .clone()
1144        .unwrap_or_else(|| format!("{:010}", rand::random::<u32>()));
1145
1146    let (_tempfile, temp_path) = match &config.temp_dir {
1147        Some(temp_dir) => {
1148            fs::create_dir_all(temp_dir).context("creating temporary directory")?;
1149            (None, PathBuf::from(&temp_dir))
1150        }
1151        _ => {
1152            // Stash the tempfile object so that it does not go out of scope and delete
1153            // the tempdir prematurely
1154            let tempfile_handle = tempfile::tempdir().context("creating temporary directory")?;
1155            let temp_path = tempfile_handle.path().to_path_buf();
1156            (Some(tempfile_handle), temp_path)
1157        }
1158    };
1159
1160    let materialize_catalog_config = config.materialize_catalog_config.clone();
1161
1162    let materialize_url = util::postgres::config_url(&config.materialize_pgconfig)?;
1163    info!("Connecting to {}", materialize_url.as_str());
1164    let (pgclient, pgconn) = Retry::default()
1165        .max_duration(config.default_timeout)
1166        .retry_async_canceling(|_| async move {
1167            let mut pgconfig = config.materialize_pgconfig.clone();
1168            pgconfig.connect_timeout(config.default_timeout);
1169            let tls = make_tls(&pgconfig)?;
1170            pgconfig.connect(tls).await.map_err(|e| anyhow!(e))
1171        })
1172        .await?;
1173
1174    let pgconn_task =
1175        task::spawn(|| "pgconn_task", pgconn).map(|join| join.context("running SQL connection"));
1176
1177    let materialize_state =
1178        create_materialize_state(&config, materialize_catalog_config, pgclient).await?;
1179
1180    let schema_registry_url = config.schema_registry_url.to_owned();
1181
1182    let ccsr_client = {
1183        let mut ccsr_config = mz_ccsr::ClientConfig::new(schema_registry_url.clone());
1184
1185        if let Some(cert_path) = &config.cert_path {
1186            let keystore = Zeroizing::new(fs::read(cert_path).context("reading cert")?);
1187            let pass = config.cert_password.as_deref().unwrap_or("");
1188            let ident = identity_from_pkcs12_der(&keystore, pass)
1189                .context("reading keystore file as pkcs12")?;
1190            ccsr_config = ccsr_config.identity(ident);
1191        }
1192
1193        if let Some(ccsr_username) = &config.ccsr_username {
1194            ccsr_config = ccsr_config.auth(ccsr_username.clone(), config.ccsr_password.clone());
1195        }
1196
1197        ccsr_config.build().context("Creating CCSR client")?
1198    };
1199
1200    let (kafka_addr, kafka_admin, kafka_admin_opts, kafka_producer, kafka_topics, kafka_config) = {
1201        use rdkafka::admin::{AdminClient, AdminOptions};
1202        use rdkafka::producer::FutureProducer;
1203
1204        let mut kafka_config = create_new_client_config_simple();
1205        kafka_config.set("bootstrap.servers", &config.kafka_addr);
1206        kafka_config.set("group.id", "materialize-testdrive");
1207        kafka_config.set("auto.offset.reset", "earliest");
1208        kafka_config.set("isolation.level", "read_committed");
1209        if let Some(cert_path) = &config.cert_path {
1210            kafka_config.set("security.protocol", "ssl");
1211            kafka_config.set("ssl.keystore.location", cert_path);
1212            if let Some(cert_password) = &config.cert_password {
1213                kafka_config.set("ssl.keystore.password", cert_password);
1214            }
1215        }
1216        kafka_config.set("message.max.bytes", "15728640");
1217
1218        for (key, value) in &config.kafka_opts {
1219            kafka_config.set(key, value);
1220        }
1221
1222        let admin: AdminClient<_> = create_with_context(&kafka_config, MzClientContext::default())
1223            .with_context(|| format!("opening Kafka connection: {}", config.kafka_addr))?;
1224
1225        let admin_opts = AdminOptions::new().operation_timeout(Some(config.default_timeout));
1226
1227        let producer: FutureProducer<_> =
1228            create_with_context(&kafka_config, MzClientContext::default()).with_context(|| {
1229                format!("opening Kafka producer connection: {}", config.kafka_addr)
1230            })?;
1231
1232        let topics = BTreeMap::new();
1233
1234        (
1235            config.kafka_addr.to_owned(),
1236            admin,
1237            admin_opts,
1238            producer,
1239            topics,
1240            kafka_config,
1241        )
1242    };
1243
1244    let mut state = State {
1245        config: config.clone(),
1246
1247        // === Testdrive state. ===
1248        arg_vars: config.arg_vars.clone(),
1249        cmd_vars: BTreeMap::new(),
1250        seed,
1251        temp_path,
1252        _tempfile,
1253        default_timeout: config.default_timeout,
1254        timeout: config.default_timeout,
1255        max_tries: config.default_max_tries,
1256        initial_backoff: config.initial_backoff,
1257        backoff_factor: config.backoff_factor,
1258        consistency_checks: config.consistency_checks,
1259        consistency_check_timeout: config.consistency_check_timeout,
1260        check_statement_logging: config.check_statement_logging,
1261        consistency_checks_adhoc_skip: false,
1262        regex: None,
1263        regex_replacement: set::DEFAULT_REGEX_REPLACEMENT.into(),
1264        rewrite_results: config.rewrite_results,
1265        error_line_count: 0,
1266        error_string: "".to_string(),
1267
1268        // === Materialize state. ===
1269        materialize: materialize_state,
1270
1271        // === Persist state. ===
1272        persist_consensus_url: config.persist_consensus_url.clone(),
1273        persist_blob_url: config.persist_blob_url.clone(),
1274        build_info: config.build_info,
1275        persist_clients: PersistClientCache::new(
1276            PersistConfig::new_default_configs(config.build_info, SYSTEM_TIME.clone()),
1277            &MetricsRegistry::new(),
1278            |_, _| PubSubClientConnection::noop(),
1279        ),
1280
1281        // === Confluent state. ===
1282        schema_registry_url,
1283        ccsr_client,
1284        kafka_addr,
1285        kafka_admin,
1286        kafka_admin_opts,
1287        kafka_config,
1288        kafka_default_partitions: config.kafka_default_partitions,
1289        kafka_producer,
1290        kafka_topics,
1291        kafka_verify_topics: BTreeSet::new(),
1292
1293        // === AWS state. ===
1294        aws_account: config.aws_account.clone(),
1295        aws_config: config.aws_config.clone(),
1296
1297        // === Database driver state. ===
1298        duckdb_clients: BTreeMap::new(),
1299        mysql_clients: BTreeMap::new(),
1300        postgres_clients: BTreeMap::new(),
1301        sql_server_clients: BTreeMap::new(),
1302        background_tasks: Vec::new(),
1303
1304        // === Fivetran state. ===
1305        fivetran_destination_url: config.fivetran_destination_url.clone(),
1306        fivetran_destination_files_path: config.fivetran_destination_files_path.clone(),
1307
1308        rewrites: Vec::new(),
1309        rewrite_pos_start: 0,
1310        rewrite_pos_end: 0,
1311    };
1312    state.initialize_cmd_vars().await?;
1313    Ok((state, pgconn_task))
1314}
1315
1316/// Converts a PKCS #12 keystore into a schema registry client identity.
1317///
1318/// The same keystore is handed to librdkafka, which reads PKCS #12 natively,
1319/// while the schema registry client's rustls backend only accepts PEM.
1320fn identity_from_pkcs12_der(der: &[u8], pass: &str) -> anyhow::Result<mz_ccsr::tls::Identity> {
1321    let parsed = Pkcs12::from_der(der)?.parse2(pass)?;
1322    let key = Zeroizing::new(
1323        parsed
1324            .pkey
1325            .context("keystore has no private key")?
1326            .private_key_to_pem_pkcs8()?,
1327    );
1328    let mut chain = parsed
1329        .cert
1330        .context("keystore has no certificate")?
1331        .to_pem()?;
1332    for ca in parsed.ca.into_iter().flatten() {
1333        chain.extend(ca.to_pem()?);
1334    }
1335    Ok(mz_ccsr::tls::Identity::from_pem(&key, &chain)?)
1336}
1337
1338async fn create_materialize_state(
1339    config: &&Config,
1340    materialize_catalog_config: Option<CatalogConfig>,
1341    pgclient: tokio_postgres::Client,
1342) -> Result<MaterializeState, anyhow::Error> {
1343    let materialize_url = util::postgres::config_url(&config.materialize_pgconfig)?;
1344    let materialize_internal_url =
1345        util::postgres::config_url(&config.materialize_internal_pgconfig)?;
1346
1347    for (key, value) in &config.materialize_params {
1348        // Session parameter values are raw SQL fragments from testdrive config.
1349        #[allow(clippy::disallowed_methods)]
1350        pgclient
1351            .batch_execute(&format!("SET {key} = {value}"))
1352            .await
1353            .context("setting session parameter")?;
1354    }
1355
1356    let materialize_user = config
1357        .materialize_pgconfig
1358        .get_user()
1359        .expect("testdrive URL must contain user")
1360        .to_string();
1361
1362    let materialize_sql_addr = format!(
1363        "{}:{}",
1364        materialize_url.host_str().unwrap(),
1365        materialize_url.port().unwrap()
1366    );
1367    let materialize_http_addr = format!(
1368        "{}:{}",
1369        materialize_url.host_str().unwrap(),
1370        config.materialize_http_port
1371    );
1372    let materialize_internal_sql_addr = format!(
1373        "{}:{}",
1374        materialize_internal_url.host_str().unwrap(),
1375        materialize_internal_url.port().unwrap()
1376    );
1377    let materialize_password_sql_addr = format!(
1378        "{}:{}",
1379        materialize_url.host_str().unwrap(),
1380        config.materialize_password_sql_port
1381    );
1382    let materialize_sasl_sql_addr = format!(
1383        "{}:{}",
1384        materialize_url.host_str().unwrap(),
1385        config.materialize_sasl_sql_port
1386    );
1387    let materialize_internal_http_addr = format!(
1388        "{}:{}",
1389        materialize_internal_url.host_str().unwrap(),
1390        config.materialize_internal_http_port
1391    );
1392    let environment_id = pg_query_one(&pgclient, pg_sql!("SELECT mz_environment_id()"), &[])
1393        .await?
1394        .get::<_, String>(0)
1395        .parse()
1396        .context("parsing environment ID")?;
1397
1398    // Tolerate the functions not existing: upgrade tests run testdrive against an
1399    // older environmentd whose catalog predates them. A version without them has
1400    // no context-folding views either, so no context is the correct fold.
1401    let (aws_account_id, aws_external_id_prefix, aws_connection_role_arn) = match pg_query_one(
1402        &pgclient,
1403        pg_sql!(
1404            "SELECT mz_aws_account_id(), mz_aws_external_id_prefix(), \
1405                 mz_aws_connection_role_arn()"
1406        ),
1407        &[],
1408    )
1409    .await
1410    {
1411        Ok(row) => (
1412            row.get::<_, Option<String>>(0),
1413            row.get::<_, Option<String>>(1),
1414            row.get::<_, Option<String>>(2),
1415        ),
1416        Err(_) => (None, None, None),
1417    };
1418
1419    let bootstrap_args = BootstrapArgs {
1420        cluster_replica_size_map: config.materialize_cluster_replica_sizes.clone(),
1421        default_cluster_replica_size: "ABC".to_string(),
1422        default_cluster_replication_factor: 1,
1423        bootstrap_role: None,
1424    };
1425
1426    let materialize_state = MaterializeState {
1427        catalog_config: materialize_catalog_config,
1428        sql_addr: materialize_sql_addr,
1429        use_https: config.materialize_use_https,
1430        http_addr: materialize_http_addr,
1431        internal_sql_addr: materialize_internal_sql_addr,
1432        internal_http_addr: materialize_internal_http_addr,
1433        password_sql_addr: materialize_password_sql_addr,
1434        sasl_sql_addr: materialize_sasl_sql_addr,
1435        user: materialize_user,
1436        pgclient,
1437        environment_id,
1438        bootstrap_args,
1439        aws_account_id,
1440        aws_external_id_prefix,
1441        aws_connection_role_arn,
1442    };
1443
1444    Ok(materialize_state)
1445}