1use 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
12pub(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#[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
51pub 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 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
107pub(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 #[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 #[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 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 mut cfg = cfg;
227 crate::partition::resolve_config_bounds(&mut cfg, &auth).await?;
228 let nodes = expand(&cfg)?;
229 #[cfg(feature = "catalog")]
234 let snapshot_inputs = catalog
235 .as_ref()
236 .map(|handle| (handle.clone(), nodes.clone(), pipeline_name.clone()));
237 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 #[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 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 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 #[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 match args.output {
346 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 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 faucet_core::shutdown_otel();
381
382 if summary.had_failures() {
383 return Err(CliError::PipelineHadFailures { count: failed });
384 }
385 Ok(())
386}
387
388#[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#[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#[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
430pub(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
454pub(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
480fn 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 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 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 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 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 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 let c = resolve_run_clock(None).unwrap();
611 assert!(c.format("%Y").to_string().parse::<i32>().unwrap() >= 2025);
612 assert!(resolve_run_clock(Some("not-a-date")).is_err());
614 }
615}