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    // Resolve discoverable partition bounds before planning (#479): `expand` is
224    // synchronous and has no registry access, and it needs concrete bounds. A
225    // config with no probes does no I/O here.
226    let mut cfg = cfg;
227    crate::partition::resolve_config_bounds(&mut cfg, &auth).await?;
228    let nodes = expand(&cfg)?;
229    // Capture the config-snapshot inputs (#374) before `nodes` / `catalog` are
230    // moved into the executor; recorded after a fully-successful run below. The
231    // snapshot represents the fully-resolved config (all rows) — runtime row
232    // selection is a per-invocation concern, so it is captured pre-selection.
233    #[cfg(feature = "catalog")]
234    let snapshot_inputs = catalog
235        .as_ref()
236        .map(|handle| (handle.clone(), nodes.clone(), pipeline_name.clone()));
237    // Runtime matrix-row selection (#370/#371/#376/#377): status gate → tag
238    // narrowing → parent policy → skip. A plain config (no `status`/`tags`, no
239    // selection flags) returns every row unchanged.
240    let selection =
241        crate::select::RunSelection::from_args(&args.selection, cfg.selection.as_ref())?;
242    let nodes = crate::select::select_nodes(nodes, &selection, !cfg.matrix.is_empty())?;
243    // The TUI wires `q` / Ctrl-C to this token: in-flight invocations stop at
244    // their next page boundary and flush (#146 H16). Plain runs keep `None`.
245    #[cfg(feature = "cli-tui")]
246    let tui_cancel = tui_active.then(faucet_core::CancellationToken::new);
247    #[cfg(not(feature = "cli-tui"))]
248    let tui_cancel: Option<faucet_core::CancellationToken> = None;
249    let started_at = Utc::now();
250    let run_fut = run_expanded(
251        nodes,
252        ExecuteOptions {
253            pipeline_name: pipeline_name.clone(),
254            run_id: None,
255            execution: cfg.execution.clone(),
256            dry_run: args.dry_run,
257            limit: args.limit,
258            state_path_override: args.state_path.clone(),
259            shard: None,
260            auth,
261            clock: resolve_run_clock(args.clock.as_deref())?,
262            // Plain runs have no external cancel signal (the executor still
263            // cooperatively cancels in-flight rows on `on_error: stop`); a
264            // TUI session cancels via `q` / Ctrl-C.
265            cancel: tui_cancel.clone(),
266            resilience,
267            sla: cfg.sla.clone(),
268            #[cfg(feature = "lineage")]
269            lineage,
270            #[cfg(feature = "lineage")]
271            lineage_cfg: cfg.lineage.clone(),
272            #[cfg(feature = "notify")]
273            notifier,
274            #[cfg(feature = "catalog")]
275            catalog,
276        },
277    );
278    #[cfg(feature = "cli-tui")]
279    let summary = match (tui_handle, tui_cancel) {
280        (Some(handle), Some(cancel)) => {
281            let result = crate::tui::drive(run_fut, &pipeline_name, handle, cancel).await;
282            if result
283                .as_ref()
284                .map(|s| s.failure_count() > 0)
285                .unwrap_or(true)
286            {
287                // The failure context lived on the alternate screen — replay
288                // the tail of the log ring to stderr now that it's gone.
289                crate::tui::flush_logs_to_stderr(25);
290            }
291            result?
292        }
293        _ => {
294            #[cfg(feature = "cli-progress")]
295            let s = drive_progress_or_plain(run_fut, &pipeline_name, progress_handle).await?;
296            #[cfg(not(feature = "cli-progress"))]
297            let s = run_fut.await?;
298            s
299        }
300    };
301    #[cfg(not(feature = "cli-tui"))]
302    let summary = {
303        #[cfg(feature = "cli-progress")]
304        let s = drive_progress_or_plain(run_fut, &pipeline_name, progress_handle).await?;
305        #[cfg(not(feature = "cli-progress"))]
306        let s = run_fut.await?;
307        s
308    };
309
310    let finished_at = Utc::now();
311    let total_written: usize = summary.invocations.iter().map(|i| i.records_written).sum();
312    let success = summary
313        .invocations
314        .iter()
315        .filter(|i| i.error.is_none())
316        .count();
317    let failed = summary.failure_count();
318
319    // Record the resolved config snapshot for `faucet plan --diff` (best-effort;
320    // #374 / #279) — only on a fully-successful run.
321    #[cfg(feature = "catalog")]
322    if let Some((handle, snap_nodes, name)) = snapshot_inputs {
323        crate::catalog::snapshot::record_if_ok(
324            Some(&handle),
325            &name,
326            crate::catalog::snapshot::on_error_str(&cfg.execution),
327            &snap_nodes,
328            failed == 0,
329            chrono::Utc::now(),
330        )
331        .await;
332    }
333
334    tracing::info!(
335        pipeline = %pipeline_name,
336        invocations = summary.invocations.len(),
337        succeeded = success,
338        failed,
339        records_written = total_written,
340        "pipeline completed"
341    );
342    // End-of-run summary. `text` is the human line (default); `json` / `ndjson`
343    // emit a machine-readable summary and keep stdout otherwise clean so
344    // `faucet run` is scriptable in CI / cron / Slack (#390). Logs are on stderr.
345    match args.output {
346        // Human status → stderr, so stdout belongs exclusively to the sink /
347        // the machine-readable json|ndjson contract (#424). Piping a
348        // stdout-sink run stays clean.
349        RunOutput::Text => eprintln!(
350            "{}: {} invocation{}, {} ok, {} failed, wrote {} record{}",
351            pipeline_name,
352            summary.invocations.len(),
353            if summary.invocations.len() == 1 {
354                ""
355            } else {
356                "s"
357            },
358            success,
359            failed,
360            total_written,
361            if total_written == 1 { "" } else { "s" }
362        ),
363        RunOutput::Json => {
364            let doc = summary_document(&pipeline_name, started_at, finished_at, &summary);
365            let rendered = serde_json::to_string_pretty(&doc).unwrap_or_else(|_| "{}".to_string());
366            // Belt-and-suspenders: scrub any resolved secret that reached an
367            // error string before it hits stdout (#390 secret-redaction AC).
368            println!("{}", crate::secrets::registry::redact(&rendered));
369        }
370        RunOutput::Ndjson => {
371            for row in summary_rows(&summary) {
372                let line = serde_json::to_string(&row).unwrap_or_else(|_| "{}".to_string());
373                println!("{}", crate::secrets::registry::redact(&line));
374            }
375        }
376    }
377
378    // Flush any buffered OTLP telemetry before the process exits (no-op without
379    // the `otel` feature). Done on both the success and failure exit paths.
380    faucet_core::shutdown_otel();
381
382    if summary.had_failures() {
383        return Err(CliError::PipelineHadFailures { count: failed });
384    }
385    Ok(())
386}
387
388/// One matrix row's line in a `--output json`/`ndjson` summary (#390). Every
389/// field is a counter the pipeline already maintains; `rows_in` is `null` when
390/// input sampling was not active (no `lineage:` / `catalog:` block).
391#[derive(Debug, Serialize)]
392pub(crate) struct RunRowSummary {
393    pub row_id: String,
394    #[serde(skip_serializing_if = "Option::is_none")]
395    pub parent_key: Option<String>,
396    pub source: String,
397    pub sink: String,
398    pub status: &'static str,
399    pub rows_in: Option<u64>,
400    pub rows_out: u64,
401    pub duration_ms: u64,
402    pub dlq_count: u64,
403    #[serde(skip_serializing_if = "Option::is_none")]
404    pub bookmark: Option<serde_json::Value>,
405    #[serde(skip_serializing_if = "Option::is_none")]
406    pub error: Option<String>,
407}
408
409/// Aggregate counters across every row.
410#[derive(Debug, Serialize)]
411pub(crate) struct RunTotals {
412    pub rows: usize,
413    pub rows_out: u64,
414    pub dlq_count: u64,
415    pub ok: usize,
416    pub failed: usize,
417}
418
419/// The full `--output json` document.
420#[derive(Debug, Serialize)]
421pub(crate) struct RunSummaryDocument {
422    pub pipeline: String,
423    pub started_at: DateTime<Utc>,
424    pub finished_at: DateTime<Utc>,
425    pub status: &'static str,
426    pub totals: RunTotals,
427    pub rows: Vec<RunRowSummary>,
428}
429
430/// Project one invocation outcome into its summary row.
431pub(crate) fn summary_rows(summary: &RunSummary) -> Vec<RunRowSummary> {
432    summary
433        .invocations
434        .iter()
435        .map(|o| {
436            let m = o.metrics.clone().unwrap_or_default();
437            RunRowSummary {
438                row_id: o.row_id.clone(),
439                parent_key: o.parent_record_key.clone(),
440                source: m.source_kind,
441                sink: m.sink_kind,
442                status: if o.error.is_some() { "failed" } else { "ok" },
443                rows_in: m.records_read,
444                rows_out: o.records_written as u64,
445                duration_ms: m.duration_ms,
446                dlq_count: m.dlq_count,
447                bookmark: m.bookmark,
448                error: o.error.clone(),
449            }
450        })
451        .collect()
452}
453
454/// Build the top-level `--output json` document from a run summary.
455pub(crate) fn summary_document(
456    pipeline: &str,
457    started_at: DateTime<Utc>,
458    finished_at: DateTime<Utc>,
459    summary: &RunSummary,
460) -> RunSummaryDocument {
461    let rows = summary_rows(summary);
462    let failed = rows.iter().filter(|r| r.status == "failed").count();
463    let totals = RunTotals {
464        rows: rows.len(),
465        rows_out: rows.iter().map(|r| r.rows_out).sum(),
466        dlq_count: rows.iter().map(|r| r.dlq_count).sum(),
467        ok: rows.len() - failed,
468        failed,
469    };
470    RunSummaryDocument {
471        pipeline: pipeline.to_string(),
472        started_at,
473        finished_at,
474        status: if failed > 0 { "failed" } else { "ok" },
475        totals,
476        rows,
477    }
478}
479
480/// Report a topology-mode run through the same `--output` surfaces as a matrix
481/// run, then map any node failures to the process exit code (#71/#72).
482fn finish_topology_run(
483    pipeline_name: &str,
484    started_at: DateTime<Utc>,
485    finished_at: DateTime<Utc>,
486    summary: &RunSummary,
487    output: RunOutput,
488) -> CliResult<()> {
489    let total_written: usize = summary.invocations.iter().map(|i| i.records_written).sum();
490    let failed = summary.failure_count();
491    let success = summary.invocations.len() - failed;
492
493    tracing::info!(
494        pipeline = %pipeline_name,
495        nodes = summary.invocations.len(),
496        succeeded = success,
497        failed,
498        records_written = total_written,
499        "topology completed"
500    );
501
502    match output {
503        // Human status → stderr; stdout stays clean for the sink / json|ndjson (#424).
504        RunOutput::Text => eprintln!(
505            "{}: {} sink node{}, {} ok, {} failed, wrote {} record{}",
506            pipeline_name,
507            summary.invocations.len(),
508            if summary.invocations.len() == 1 {
509                ""
510            } else {
511                "s"
512            },
513            success,
514            failed,
515            total_written,
516            if total_written == 1 { "" } else { "s" }
517        ),
518        RunOutput::Json => {
519            let doc = summary_document(pipeline_name, started_at, finished_at, summary);
520            let rendered = serde_json::to_string_pretty(&doc).unwrap_or_else(|_| "{}".to_string());
521            println!("{}", crate::secrets::registry::redact(&rendered));
522        }
523        RunOutput::Ndjson => {
524            for row in summary_rows(summary) {
525                let line = serde_json::to_string(&row).unwrap_or_else(|_| "{}".to_string());
526                println!("{}", crate::secrets::registry::redact(&line));
527            }
528        }
529    }
530
531    faucet_core::shutdown_otel();
532
533    if summary.had_failures() {
534        return Err(CliError::TopologyHadFailures { count: failed });
535    }
536    Ok(())
537}
538
539#[cfg(test)]
540mod tests {
541    use super::*;
542    use crate::executor::{InvocationMetrics, InvocationOutcome};
543
544    fn outcome(id: &str, written: usize, err: Option<&str>) -> InvocationOutcome {
545        InvocationOutcome {
546            row_id: id.into(),
547            parent_record_key: None,
548            records_written: written,
549            error: err.map(|s| s.to_string()),
550            metrics: Some(InvocationMetrics {
551                source_kind: "rest".into(),
552                sink_kind: "jsonl".into(),
553                duration_ms: 12,
554                records_read: Some(written as u64),
555                dlq_count: 0,
556                bookmark: None,
557            }),
558        }
559    }
560
561    #[test]
562    fn summary_document_aggregates_rows_and_status() {
563        let summary = RunSummary {
564            invocations: vec![outcome("a", 3, None), outcome("b", 0, Some("boom"))],
565        };
566        let now = Utc::now();
567        let doc = summary_document("demo", now, now, &summary);
568        assert_eq!(doc.status, "failed");
569        assert_eq!(doc.totals.rows, 2);
570        assert_eq!(doc.totals.rows_out, 3);
571        assert_eq!(doc.totals.ok, 1);
572        assert_eq!(doc.totals.failed, 1);
573        assert_eq!(doc.rows[0].source, "rest");
574        assert_eq!(doc.rows[0].rows_in, Some(3));
575        assert_eq!(doc.rows[1].status, "failed");
576        assert_eq!(doc.rows[1].error.as_deref(), Some("boom"));
577        // Serializes cleanly.
578        let json = serde_json::to_string(&doc).unwrap();
579        assert!(json.contains("\"pipeline\":\"demo\""), "{json}");
580    }
581
582    #[test]
583    fn all_ok_run_reports_ok_status() {
584        let summary = RunSummary {
585            invocations: vec![outcome("only", 5, None)],
586        };
587        let now = Utc::now();
588        let doc = summary_document("p", now, now, &summary);
589        assert_eq!(doc.status, "ok");
590        assert_eq!(doc.totals.failed, 0);
591    }
592
593    #[cfg(feature = "cli-progress")]
594    #[tokio::test]
595    async fn drive_progress_or_plain_without_handle_just_awaits() {
596        // No recorder handle (non-TTY / --quiet) → the future is awaited plainly.
597        let out = super::drive_progress_or_plain(async { 7_usize }, "p", None).await;
598        assert_eq!(out, 7);
599    }
600
601    #[test]
602    fn run_clock_parses_rfc3339_date_and_defaults() {
603        // RFC3339
604        let c = resolve_run_clock(Some("2026-01-31T12:00:00Z")).unwrap();
605        assert_eq!(c.format("%Y-%m-%d %H:%M").to_string(), "2026-01-31 12:00");
606        // date-only → midnight UTC
607        let c = resolve_run_clock(Some("2026-01-31")).unwrap();
608        assert_eq!(c.format("%Y-%m-%d %H:%M").to_string(), "2026-01-31 00:00");
609        // default = now (just assert it's Ok / recent year)
610        let c = resolve_run_clock(None).unwrap();
611        assert!(c.format("%Y").to_string().parse::<i32>().unwrap() >= 2025);
612        // bad input errors
613        assert!(resolve_run_clock(Some("not-a-date")).is_err());
614    }
615}