Skip to main content

faucet_cli/commands/
replicate.rs

1//! `faucet replicate` — load a config with a `replication:` block, validate it,
2//! and run the two-phase snapshot→CDC orchestration.
3
4use crate::cli::ReplicateArgs;
5use crate::config::PipelineConfig;
6use crate::error::{CliError, CliResult};
7use crate::replication::compiled::CompiledReplication;
8use crate::replication::{ReplicationOptions, run_replication};
9
10/// Execute the `replicate` subcommand.
11pub async fn run(args: ReplicateArgs) -> CliResult<()> {
12    let cwd = std::env::current_dir()?;
13    let env_path =
14        crate::env_loader::resolve_env_file(args.env_file.as_deref(), args.no_env_file, &cwd)?;
15    crate::env_loader::load_env_file_if_present(env_path.as_deref())?;
16    let path = match args.config {
17        Some(p) => p,
18        None => crate::env_loader::discover_config_path(&cwd).ok_or(CliError::NoConfigOrFromEnv)?,
19    };
20
21    let cfg = PipelineConfig::from_path_async(&path, args.profile.as_deref()).await?;
22    let spec = cfg.replication.as_ref().ok_or_else(|| {
23        CliError::Config(
24            "no `replication:` block in config — use `faucet run` for a one-shot run, or add a \
25             `replication:` block (see `faucet schema replication`)"
26                .into(),
27        )
28    })?;
29    // Install observability before compiling the replication spec so the
30    // tracing subscriber is live and `CompiledReplication::compile`'s
31    // non-upsert-sink warning is actually emitted (it would be lost otherwise).
32    crate::obs::install(&cfg)?;
33
34    let compiled = CompiledReplication::compile(spec, &cfg)?;
35
36    let pipeline_name = cfg.name.clone().unwrap_or_else(|| {
37        path.file_stem()
38            .and_then(|s| s.to_str())
39            .unwrap_or("pipeline")
40            .to_owned()
41    });
42    let auth = crate::auth_catalog::build_auth_catalog(cfg.auth.as_ref())?;
43    let resilience = match &cfg.resilience {
44        Some(spec) => Some(spec.to_policy()?),
45        None => None,
46    };
47    #[cfg(feature = "notify")]
48    let notifier = crate::notify::Notifier::from_specs(&cfg.notifications)?;
49    #[cfg(feature = "catalog")]
50    let catalog = match cfg.catalog.as_ref() {
51        Some(spec) => Some(crate::catalog::connect_from_spec(spec).await?),
52        None => None,
53    };
54    // Config snapshot for `faucet plan --diff` (#374). Best-effort: skip if the
55    // config does not expand cleanly (some replication shapes are orchestration
56    // -only). Recorded after the replication run succeeds below.
57    #[cfg(feature = "catalog")]
58    let snapshot_inputs = catalog.as_ref().and_then(|handle| {
59        crate::expand::expand(&cfg)
60            .ok()
61            .map(|nodes| (handle.clone(), nodes, pipeline_name.clone()))
62    });
63
64    run_replication(
65        &cfg,
66        &compiled,
67        ReplicationOptions {
68            pipeline_name,
69            execution: cfg.execution.clone(),
70            auth,
71            clock: chrono::Utc::now().fixed_offset(),
72            resilience,
73            sla: cfg.sla.clone(),
74            #[cfg(feature = "notify")]
75            notifier,
76            #[cfg(feature = "catalog")]
77            catalog,
78        },
79    )
80    .await?;
81
82    // Reached only on success (errors returned via `?` above).
83    #[cfg(feature = "catalog")]
84    if let Some((handle, nodes, name)) = snapshot_inputs {
85        crate::catalog::snapshot::record_if_ok(
86            Some(&handle),
87            &name,
88            crate::catalog::snapshot::on_error_str(&cfg.execution),
89            &nodes,
90            true,
91            chrono::Utc::now(),
92        )
93        .await;
94    }
95
96    // Flush any buffered OTLP telemetry before exiting (no-op without `otel`).
97    faucet_core::shutdown_otel();
98
99    println!("replication finished");
100    Ok(())
101}
102
103#[cfg(test)]
104mod tests {
105    use super::*;
106    use std::io::Write;
107
108    /// Write `yaml` to a `faucet.yaml` inside a fresh temp dir and return the
109    /// path (the dir is leaked so the file outlives the call — fine for a test).
110    fn write_config(yaml: &str) -> std::path::PathBuf {
111        let dir = tempfile::tempdir().expect("tempdir");
112        let path = dir.path().join("repl.yaml");
113        let mut f = std::fs::File::create(&path).expect("create config");
114        f.write_all(yaml.as_bytes()).expect("write config");
115        f.flush().expect("flush");
116        // Keep the dir alive for the duration of the test process.
117        std::mem::forget(dir);
118        path
119    }
120
121    fn args(path: std::path::PathBuf) -> ReplicateArgs {
122        ReplicateArgs {
123            config: Some(path),
124            env_file: None,
125            no_env_file: true,
126            profile: None,
127        }
128    }
129
130    /// A valid pipeline config with NO `replication:` block must error out before
131    /// any orchestration runs (no Docker / network reached). Works under default
132    /// features (rest source + jsonl sink are always present).
133    #[tokio::test]
134    async fn errors_when_no_replication_block() {
135        let path = write_config(
136            r#"
137version: 1
138name: plain
139pipeline:
140  source: { type: rest, config: { url: "https://example.com/api" } }
141  sink:   { type: jsonl, config: { path: ./out.jsonl } }
142"#,
143        );
144        let err = run(args(path)).await.unwrap_err();
145        assert!(
146            format!("{err}").contains("replication"),
147            "should mention the missing replication block: {err}"
148        );
149    }
150
151    /// A config WITH a `replication:` block that fails `CompiledReplication::compile`
152    /// (here: `state: memory`, which the durable-state rule rejects) must error
153    /// before `run_replication` — so no Docker is needed. Gated on the connector
154    /// kinds being compiled in so `source_supports_exactly_once` / `source_schema`
155    /// resolve (otherwise compile would fail earlier on an unknown-kind error,
156    /// which is a different, also-acceptable failure but not the branch under test).
157    #[cfg(all(
158        feature = "source-postgres-cdc",
159        feature = "source-postgres",
160        feature = "sink-postgres"
161    ))]
162    #[tokio::test]
163    async fn errors_when_replication_spec_invalid() {
164        let path = write_config(
165            r#"
166version: 1
167name: mirror
168pipeline:
169  source: { type: postgres-cdc, config: { connection_url: "postgres://x", slot_name: s, publication_name: p } }
170  sink:   { type: postgres, config: { connection_url: "postgres://y", table_name: t, column_mapping: auto_map, write_mode: upsert, key: [id] } }
171  state:  { type: memory, config: {} }
172replication:
173  mode: snapshot_then_cdc
174  snapshot:
175    source: { type: postgres, config: { connection_url: "postgres://x", query: "SELECT * FROM t" } }
176"#,
177        );
178        let err = run(args(path)).await.unwrap_err();
179        assert!(
180            format!("{err}").contains("durable state"),
181            "should reject memory state at compile time: {err}"
182        );
183    }
184}