Skip to main content

faucet_cli/commands/
run.rs

1//! `faucet run` — load a pipeline config, expand the matrix, execute every
2//! invocation under bounded concurrency.
3
4use crate::cli::{RunArgs, RunOutput};
5use crate::config::PipelineConfig;
6use crate::error::{CliError, CliResult};
7use crate::executor::{ExecuteOptions, RunSummary, run_expanded};
8use crate::expand::expand;
9use chrono::{DateTime, Utc};
10use serde::Serialize;
11
12/// Parse the optional `--clock` override (RFC3339 or `YYYY-MM-DD`), or default
13/// to process start. Returned as a UTC fixed-offset clock for `${now.*}`.
14/// Shared with `faucet test` (the `--clock` flag and per-case `clock:` field).
15pub(crate) fn resolve_run_clock(
16    flag: Option<&str>,
17) -> CliResult<chrono::DateTime<chrono::FixedOffset>> {
18    use chrono::{DateTime, NaiveDate, TimeZone, Utc};
19    match flag {
20        None => Ok(Utc::now().fixed_offset()),
21        Some(s) => {
22            if let Ok(dt) = DateTime::parse_from_rfc3339(s) {
23                return Ok(dt);
24            }
25            if let Ok(d) = NaiveDate::parse_from_str(s, "%Y-%m-%d") {
26                let ndt = d.and_hms_opt(0, 0, 0).expect("00:00:00 is valid");
27                return Ok(Utc.from_utc_datetime(&ndt).fixed_offset());
28            }
29            Err(CliError::Config(format!(
30                "--clock '{s}' is not RFC3339 (2026-01-31T00:00:00Z) or a date (2026-01-31)"
31            )))
32        }
33    }
34}
35
36/// Drive the run future under the inline progress line when a recorder handle
37/// is present (interactive terminal, not `--quiet`/`--tui`), else await it
38/// plainly. Keeps the two summary call sites in `run` free of nested cfgs.
39#[cfg(feature = "cli-progress")]
40async fn drive_progress_or_plain<T>(
41    run: impl Future<Output = T>,
42    pipeline: &str,
43    handle: Option<metrics_exporter_prometheus::PrometheusHandle>,
44) -> T {
45    match handle {
46        Some(h) => crate::progress::drive(run, pipeline, h).await,
47        None => run.await,
48    }
49}
50
51/// Execute the `run` subcommand.
52pub async fn run(args: RunArgs) -> CliResult<()> {
53    let cwd = std::env::current_dir()?;
54    let env_path =
55        crate::env_loader::resolve_env_file(args.env_file.as_deref(), args.no_env_file, &cwd)?;
56    crate::env_loader::load_env_file_if_present(env_path.as_deref())?;
57
58    let resolved_config_path: Option<std::path::PathBuf> = if args.from_env {
59        None
60    } else {
61        Some(match args.config.as_ref() {
62            Some(p) => p.clone(),
63            None => {
64                crate::env_loader::discover_config_path(&cwd).ok_or(CliError::NoConfigOrFromEnv)?
65            }
66        })
67    };
68
69    let cfg = if args.from_env {
70        if args.profile.is_some() {
71            tracing::warn!(
72                "--profile / FAUCET_PROFILE has no effect in --from-env mode (no config file to compose); ignoring"
73            );
74        }
75        if !args.param.is_empty() || !args.param_env.is_empty() {
76            return Err(CliError::Config(
77                "--param / --param-env have no effect in --from-env mode: the `params:` block \
78                 lives in a config file, and every value already comes from the environment"
79                    .into(),
80            ));
81        }
82        crate::env_config::from_process_env()?
83    } else {
84        // Typed run params (#444): `--param name=value` / `--param-env NAME[=V]`
85        // are bound before the typed parse, so `${param.*}` never reaches a
86        // connector. A config with no `params:` block is unaffected.
87        let inputs = crate::config::RunInputs {
88            params: crate::params::collect_cli_params(&args.param)?,
89            env: crate::params::collect_env_overrides(&args.param_env)?
90                .into_iter()
91                .collect(),
92            mode: crate::params::BindMode::Strict,
93        };
94        PipelineConfig::from_path_async_with(
95            resolved_config_path
96                .as_ref()
97                .expect("YAML mode always resolves a path above"),
98            args.profile.as_deref(),
99            &inputs,
100        )
101        .await?
102    };
103
104    execute(cfg, args, resolved_config_path).await
105}
106
107/// Execute an already-loaded config: install observability, build the auth
108/// catalog, expand + select rows, run, and report.
109///
110/// Split out of [`run`] so a caller that obtains its config some other way runs
111/// through the *identical* path — `faucet template run` materializes a
112/// registered template and hands it straight here, rather than re-implementing
113/// (and inevitably under-implementing) the lineage / notification / catalog /
114/// SLA / progress wiring below.
115pub(crate) async fn execute(
116    cfg: PipelineConfig,
117    args: RunArgs,
118    resolved_config_path: Option<std::path::PathBuf>,
119) -> CliResult<()> {
120    #[cfg(not(feature = "cli-tui"))]
121    if args.tui {
122        return Err(CliError::Config(
123            "--tui requires a binary built with the `cli-tui` feature \
124             (e.g. `cargo install faucet-cli --features cli-tui`)"
125                .into(),
126        ));
127    }
128    #[cfg(feature = "cli-tui")]
129    let tui_active = crate::tui::is_tui_session(args.tui);
130    #[cfg(not(feature = "cli-tui"))]
131    let tui_active = false;
132
133    // Exactly one observability install. A live view (the full-screen `--tui`
134    // or the inline `--progress` line) owns the Prometheus recorder so it can
135    // render the recorder's output; otherwise the standard install runs. The
136    // TUI supersedes the inline line when both are eligible.
137    #[cfg_attr(
138        not(any(feature = "cli-tui", feature = "cli-progress")),
139        allow(unused_mut)
140    )]
141    let mut live_view_owns_recorder = false;
142
143    #[cfg(feature = "cli-tui")]
144    let tui_handle = if tui_active {
145        let h = crate::tui::setup_observability(&cfg)?;
146        live_view_owns_recorder = true;
147        Some(h)
148    } else {
149        if args.tui {
150            tracing::info!("--tui: stdout is not a terminal; running without the TUI");
151        }
152        None
153    };
154
155    // Inline progress line (#385): only when the TUI isn't taking over, stdout
156    // is a terminal, and the operator did not pass `--quiet`. On a non-TTY /
157    // `--quiet` this is `None` and the run falls back to periodic log lines.
158    #[cfg(feature = "cli-progress")]
159    let progress_handle =
160        if !tui_active && crate::progress::is_progress_session(args.quiet, args.tui) {
161            let h = crate::livemetrics::setup_observability(&cfg)?;
162            live_view_owns_recorder = true;
163            Some(h)
164        } else {
165            None
166        };
167
168    if !live_view_owns_recorder {
169        crate::obs::install(&cfg)?;
170    }
171
172    let pipeline_name = cfg.name.clone().unwrap_or_else(|| {
173        resolved_config_path
174            .as_ref()
175            .and_then(|p| p.file_stem())
176            .and_then(|s| s.to_str())
177            .unwrap_or("pipeline")
178            .to_owned()
179    });
180
181    let auth = crate::auth_catalog::build_auth_catalog(cfg.auth.as_ref())?;
182
183    // Topology mode (#71/#72): an explicit `pipeline.nodes` graph replaces the
184    // matrix entirely. Run it directly and report through the same summary
185    // surfaces (`--output text|json|ndjson`), then return.
186    if crate::topology::is_topology(&cfg) {
187        let started_at = Utc::now();
188        let summary = crate::topology::run_topology(
189            &cfg,
190            &auth,
191            crate::topology::TopologyRunOptions {
192                cancel: None,
193                dry_run: args.dry_run,
194                limit: args.limit,
195                clock: Some(resolve_run_clock(args.clock.as_deref())?),
196            },
197        )
198        .await?;
199        let finished_at = Utc::now();
200        return finish_topology_run(
201            &pipeline_name,
202            started_at,
203            finished_at,
204            &summary,
205            args.output,
206        );
207    }
208
209    #[cfg(feature = "lineage")]
210    let lineage = crate::lineage_glue::build_emitter(cfg.lineage.as_ref())
211        .map_err(|e| CliError::Config(format!("lineage: {e}")))?;
212    let resilience = match &cfg.resilience {
213        Some(spec) => Some(spec.to_policy()?),
214        None => None,
215    };
216    #[cfg(feature = "notify")]
217    let notifier = crate::notify::Notifier::from_specs(&cfg.notifications)?;
218    #[cfg(feature = "catalog")]
219    let catalog = match cfg.catalog.as_ref() {
220        Some(spec) => Some(crate::catalog::connect_from_spec(spec).await?),
221        None => None,
222    };
223    let nodes = expand(&cfg)?;
224    // Capture the config-snapshot inputs (#374) before `nodes` / `catalog` are
225    // moved into the executor; recorded after a fully-successful run below. The
226    // snapshot represents the fully-resolved config (all rows) — runtime row
227    // selection is a per-invocation concern, so it is captured pre-selection.
228    #[cfg(feature = "catalog")]
229    let snapshot_inputs = catalog
230        .as_ref()
231        .map(|handle| (handle.clone(), nodes.clone(), pipeline_name.clone()));
232    // Runtime matrix-row selection (#370/#371/#376/#377): status gate → tag
233    // narrowing → parent policy → skip. A plain config (no `status`/`tags`, no
234    // selection flags) returns every row unchanged.
235    let selection =
236        crate::select::RunSelection::from_args(&args.selection, cfg.selection.as_ref())?;
237    let nodes = crate::select::select_nodes(nodes, &selection, !cfg.matrix.is_empty())?;
238    // The TUI wires `q` / Ctrl-C to this token: in-flight invocations stop at
239    // their next page boundary and flush (#146 H16). Plain runs keep `None`.
240    #[cfg(feature = "cli-tui")]
241    let tui_cancel = tui_active.then(faucet_core::CancellationToken::new);
242    #[cfg(not(feature = "cli-tui"))]
243    let tui_cancel: Option<faucet_core::CancellationToken> = None;
244    let started_at = Utc::now();
245    let run_fut = run_expanded(
246        nodes,
247        ExecuteOptions {
248            pipeline_name: pipeline_name.clone(),
249            execution: cfg.execution.clone(),
250            dry_run: args.dry_run,
251            limit: args.limit,
252            state_path_override: args.state_path.clone(),
253            shard: None,
254            auth,
255            clock: resolve_run_clock(args.clock.as_deref())?,
256            // Plain runs have no external cancel signal (the executor still
257            // cooperatively cancels in-flight rows on `on_error: stop`); a
258            // TUI session cancels via `q` / Ctrl-C.
259            cancel: tui_cancel.clone(),
260            resilience,
261            sla: cfg.sla.clone(),
262            #[cfg(feature = "lineage")]
263            lineage,
264            #[cfg(feature = "lineage")]
265            lineage_cfg: cfg.lineage.clone(),
266            #[cfg(feature = "notify")]
267            notifier,
268            #[cfg(feature = "catalog")]
269            catalog,
270        },
271    );
272    #[cfg(feature = "cli-tui")]
273    let summary = match (tui_handle, tui_cancel) {
274        (Some(handle), Some(cancel)) => {
275            let result = crate::tui::drive(run_fut, &pipeline_name, handle, cancel).await;
276            if result
277                .as_ref()
278                .map(|s| s.failure_count() > 0)
279                .unwrap_or(true)
280            {
281                // The failure context lived on the alternate screen — replay
282                // the tail of the log ring to stderr now that it's gone.
283                crate::tui::flush_logs_to_stderr(25);
284            }
285            result?
286        }
287        _ => {
288            #[cfg(feature = "cli-progress")]
289            let s = drive_progress_or_plain(run_fut, &pipeline_name, progress_handle).await?;
290            #[cfg(not(feature = "cli-progress"))]
291            let s = run_fut.await?;
292            s
293        }
294    };
295    #[cfg(not(feature = "cli-tui"))]
296    let summary = {
297        #[cfg(feature = "cli-progress")]
298        let s = drive_progress_or_plain(run_fut, &pipeline_name, progress_handle).await?;
299        #[cfg(not(feature = "cli-progress"))]
300        let s = run_fut.await?;
301        s
302    };
303
304    let finished_at = Utc::now();
305    let total_written: usize = summary.invocations.iter().map(|i| i.records_written).sum();
306    let success = summary
307        .invocations
308        .iter()
309        .filter(|i| i.error.is_none())
310        .count();
311    let failed = summary.failure_count();
312
313    // Record the resolved config snapshot for `faucet plan --diff` (best-effort;
314    // #374 / #279) — only on a fully-successful run.
315    #[cfg(feature = "catalog")]
316    if let Some((handle, snap_nodes, name)) = snapshot_inputs {
317        crate::catalog::snapshot::record_if_ok(
318            Some(&handle),
319            &name,
320            crate::catalog::snapshot::on_error_str(&cfg.execution),
321            &snap_nodes,
322            failed == 0,
323            chrono::Utc::now(),
324        )
325        .await;
326    }
327
328    tracing::info!(
329        pipeline = %pipeline_name,
330        invocations = summary.invocations.len(),
331        succeeded = success,
332        failed,
333        records_written = total_written,
334        "pipeline completed"
335    );
336    // End-of-run summary. `text` is the human line (default); `json` / `ndjson`
337    // emit a machine-readable summary and keep stdout otherwise clean so
338    // `faucet run` is scriptable in CI / cron / Slack (#390). Logs are on stderr.
339    match args.output {
340        // Human status → stderr, so stdout belongs exclusively to the sink /
341        // the machine-readable json|ndjson contract (#424). Piping a
342        // stdout-sink run stays clean.
343        RunOutput::Text => eprintln!(
344            "{}: {} invocation{}, {} ok, {} failed, wrote {} record{}",
345            pipeline_name,
346            summary.invocations.len(),
347            if summary.invocations.len() == 1 {
348                ""
349            } else {
350                "s"
351            },
352            success,
353            failed,
354            total_written,
355            if total_written == 1 { "" } else { "s" }
356        ),
357        RunOutput::Json => {
358            let doc = summary_document(&pipeline_name, started_at, finished_at, &summary);
359            let rendered = serde_json::to_string_pretty(&doc).unwrap_or_else(|_| "{}".to_string());
360            // Belt-and-suspenders: scrub any resolved secret that reached an
361            // error string before it hits stdout (#390 secret-redaction AC).
362            println!("{}", crate::secrets::registry::redact(&rendered));
363        }
364        RunOutput::Ndjson => {
365            for row in summary_rows(&summary) {
366                let line = serde_json::to_string(&row).unwrap_or_else(|_| "{}".to_string());
367                println!("{}", crate::secrets::registry::redact(&line));
368            }
369        }
370    }
371
372    // Flush any buffered OTLP telemetry before the process exits (no-op without
373    // the `otel` feature). Done on both the success and failure exit paths.
374    faucet_core::shutdown_otel();
375
376    if summary.had_failures() {
377        return Err(CliError::PipelineHadFailures { count: failed });
378    }
379    Ok(())
380}
381
382/// One matrix row's line in a `--output json`/`ndjson` summary (#390). Every
383/// field is a counter the pipeline already maintains; `rows_in` is `null` when
384/// input sampling was not active (no `lineage:` / `catalog:` block).
385#[derive(Debug, Serialize)]
386pub(crate) struct RunRowSummary {
387    pub row_id: String,
388    #[serde(skip_serializing_if = "Option::is_none")]
389    pub parent_key: Option<String>,
390    pub source: String,
391    pub sink: String,
392    pub status: &'static str,
393    pub rows_in: Option<u64>,
394    pub rows_out: u64,
395    pub duration_ms: u64,
396    pub dlq_count: u64,
397    #[serde(skip_serializing_if = "Option::is_none")]
398    pub bookmark: Option<serde_json::Value>,
399    #[serde(skip_serializing_if = "Option::is_none")]
400    pub error: Option<String>,
401}
402
403/// Aggregate counters across every row.
404#[derive(Debug, Serialize)]
405pub(crate) struct RunTotals {
406    pub rows: usize,
407    pub rows_out: u64,
408    pub dlq_count: u64,
409    pub ok: usize,
410    pub failed: usize,
411}
412
413/// The full `--output json` document.
414#[derive(Debug, Serialize)]
415pub(crate) struct RunSummaryDocument {
416    pub pipeline: String,
417    pub started_at: DateTime<Utc>,
418    pub finished_at: DateTime<Utc>,
419    pub status: &'static str,
420    pub totals: RunTotals,
421    pub rows: Vec<RunRowSummary>,
422}
423
424/// Project one invocation outcome into its summary row.
425pub(crate) fn summary_rows(summary: &RunSummary) -> Vec<RunRowSummary> {
426    summary
427        .invocations
428        .iter()
429        .map(|o| {
430            let m = o.metrics.clone().unwrap_or_default();
431            RunRowSummary {
432                row_id: o.row_id.clone(),
433                parent_key: o.parent_record_key.clone(),
434                source: m.source_kind,
435                sink: m.sink_kind,
436                status: if o.error.is_some() { "failed" } else { "ok" },
437                rows_in: m.records_read,
438                rows_out: o.records_written as u64,
439                duration_ms: m.duration_ms,
440                dlq_count: m.dlq_count,
441                bookmark: m.bookmark,
442                error: o.error.clone(),
443            }
444        })
445        .collect()
446}
447
448/// Build the top-level `--output json` document from a run summary.
449pub(crate) fn summary_document(
450    pipeline: &str,
451    started_at: DateTime<Utc>,
452    finished_at: DateTime<Utc>,
453    summary: &RunSummary,
454) -> RunSummaryDocument {
455    let rows = summary_rows(summary);
456    let failed = rows.iter().filter(|r| r.status == "failed").count();
457    let totals = RunTotals {
458        rows: rows.len(),
459        rows_out: rows.iter().map(|r| r.rows_out).sum(),
460        dlq_count: rows.iter().map(|r| r.dlq_count).sum(),
461        ok: rows.len() - failed,
462        failed,
463    };
464    RunSummaryDocument {
465        pipeline: pipeline.to_string(),
466        started_at,
467        finished_at,
468        status: if failed > 0 { "failed" } else { "ok" },
469        totals,
470        rows,
471    }
472}
473
474/// Report a topology-mode run through the same `--output` surfaces as a matrix
475/// run, then map any node failures to the process exit code (#71/#72).
476fn finish_topology_run(
477    pipeline_name: &str,
478    started_at: DateTime<Utc>,
479    finished_at: DateTime<Utc>,
480    summary: &RunSummary,
481    output: RunOutput,
482) -> CliResult<()> {
483    let total_written: usize = summary.invocations.iter().map(|i| i.records_written).sum();
484    let failed = summary.failure_count();
485    let success = summary.invocations.len() - failed;
486
487    tracing::info!(
488        pipeline = %pipeline_name,
489        nodes = summary.invocations.len(),
490        succeeded = success,
491        failed,
492        records_written = total_written,
493        "topology completed"
494    );
495
496    match output {
497        // Human status → stderr; stdout stays clean for the sink / json|ndjson (#424).
498        RunOutput::Text => eprintln!(
499            "{}: {} sink node{}, {} ok, {} failed, wrote {} record{}",
500            pipeline_name,
501            summary.invocations.len(),
502            if summary.invocations.len() == 1 {
503                ""
504            } else {
505                "s"
506            },
507            success,
508            failed,
509            total_written,
510            if total_written == 1 { "" } else { "s" }
511        ),
512        RunOutput::Json => {
513            let doc = summary_document(pipeline_name, started_at, finished_at, summary);
514            let rendered = serde_json::to_string_pretty(&doc).unwrap_or_else(|_| "{}".to_string());
515            println!("{}", crate::secrets::registry::redact(&rendered));
516        }
517        RunOutput::Ndjson => {
518            for row in summary_rows(summary) {
519                let line = serde_json::to_string(&row).unwrap_or_else(|_| "{}".to_string());
520                println!("{}", crate::secrets::registry::redact(&line));
521            }
522        }
523    }
524
525    faucet_core::shutdown_otel();
526
527    if summary.had_failures() {
528        return Err(CliError::TopologyHadFailures { count: failed });
529    }
530    Ok(())
531}
532
533#[cfg(test)]
534mod tests {
535    use super::*;
536    use crate::executor::{InvocationMetrics, InvocationOutcome};
537
538    fn outcome(id: &str, written: usize, err: Option<&str>) -> InvocationOutcome {
539        InvocationOutcome {
540            row_id: id.into(),
541            parent_record_key: None,
542            records_written: written,
543            error: err.map(|s| s.to_string()),
544            metrics: Some(InvocationMetrics {
545                source_kind: "rest".into(),
546                sink_kind: "jsonl".into(),
547                duration_ms: 12,
548                records_read: Some(written as u64),
549                dlq_count: 0,
550                bookmark: None,
551            }),
552        }
553    }
554
555    #[test]
556    fn summary_document_aggregates_rows_and_status() {
557        let summary = RunSummary {
558            invocations: vec![outcome("a", 3, None), outcome("b", 0, Some("boom"))],
559        };
560        let now = Utc::now();
561        let doc = summary_document("demo", now, now, &summary);
562        assert_eq!(doc.status, "failed");
563        assert_eq!(doc.totals.rows, 2);
564        assert_eq!(doc.totals.rows_out, 3);
565        assert_eq!(doc.totals.ok, 1);
566        assert_eq!(doc.totals.failed, 1);
567        assert_eq!(doc.rows[0].source, "rest");
568        assert_eq!(doc.rows[0].rows_in, Some(3));
569        assert_eq!(doc.rows[1].status, "failed");
570        assert_eq!(doc.rows[1].error.as_deref(), Some("boom"));
571        // Serializes cleanly.
572        let json = serde_json::to_string(&doc).unwrap();
573        assert!(json.contains("\"pipeline\":\"demo\""), "{json}");
574    }
575
576    #[test]
577    fn all_ok_run_reports_ok_status() {
578        let summary = RunSummary {
579            invocations: vec![outcome("only", 5, None)],
580        };
581        let now = Utc::now();
582        let doc = summary_document("p", now, now, &summary);
583        assert_eq!(doc.status, "ok");
584        assert_eq!(doc.totals.failed, 0);
585    }
586
587    #[cfg(feature = "cli-progress")]
588    #[tokio::test]
589    async fn drive_progress_or_plain_without_handle_just_awaits() {
590        // No recorder handle (non-TTY / --quiet) → the future is awaited plainly.
591        let out = super::drive_progress_or_plain(async { 7_usize }, "p", None).await;
592        assert_eq!(out, 7);
593    }
594
595    #[test]
596    fn run_clock_parses_rfc3339_date_and_defaults() {
597        // RFC3339
598        let c = resolve_run_clock(Some("2026-01-31T12:00:00Z")).unwrap();
599        assert_eq!(c.format("%Y-%m-%d %H:%M").to_string(), "2026-01-31 12:00");
600        // date-only → midnight UTC
601        let c = resolve_run_clock(Some("2026-01-31")).unwrap();
602        assert_eq!(c.format("%Y-%m-%d %H:%M").to_string(), "2026-01-31 00:00");
603        // default = now (just assert it's Ok / recent year)
604        let c = resolve_run_clock(None).unwrap();
605        assert!(c.format("%Y").to_string().parse::<i32>().unwrap() >= 2025);
606        // bad input errors
607        assert!(resolve_run_clock(Some("not-a-date")).is_err());
608    }
609}