1use crate::auth_catalog::{AuthCatalog, build_auth_catalog};
7use crate::cli::ScheduleArgs;
8use crate::config::PipelineConfig;
9use crate::error::{CliError, CliResult};
10use crate::executor::{ExecuteOptions, RunSummary, run_expanded};
11use crate::expand::{ExpandedNode, expand};
12use crate::schedule::compiled::CompiledSchedule;
13use crate::schedule::metrics as m;
14use crate::schedule::state::{AfterRun, RunOutcome, SchedulerState, TickAction};
15use chrono::{DateTime, Utc};
16use std::time::Duration;
17use tokio::task::JoinHandle;
18use tokio::time::Instant;
19use tracing::Instrument;
20
21struct RunningRun {
23 handle: JoinHandle<CliResult<RunSummary>>,
24 started: Instant,
25}
26
27struct RunFinished {
29 outcome: RunOutcome,
30 duration: Duration,
31 detail: Option<String>,
32 cooldown: Option<Duration>,
34}
35
36struct Shutdown {
38 #[cfg(unix)]
39 sigterm: tokio::signal::unix::Signal,
40}
41
42impl Shutdown {
43 fn new() -> CliResult<Self> {
44 #[cfg(unix)]
45 {
46 use tokio::signal::unix::{SignalKind, signal};
47 let sigterm = signal(SignalKind::terminate()).map_err(|e| {
48 CliError::Internal(format!("failed to install SIGTERM handler: {e}"))
49 })?;
50 Ok(Self { sigterm })
51 }
52 #[cfg(not(unix))]
53 {
54 Ok(Self {})
55 }
56 }
57
58 async fn recv(&mut self) {
60 #[cfg(unix)]
61 {
62 tokio::select! {
63 _ = tokio::signal::ctrl_c() => {}
64 _ = self.sigterm.recv() => {}
65 }
66 }
67 #[cfg(not(unix))]
68 {
69 let _ = tokio::signal::ctrl_c().await;
70 }
71 }
72}
73
74struct Reload {
77 #[cfg(unix)]
78 sighup: tokio::signal::unix::Signal,
79}
80
81impl Reload {
82 fn new() -> CliResult<Self> {
83 #[cfg(unix)]
84 {
85 use tokio::signal::unix::{SignalKind, signal};
86 let sighup = signal(SignalKind::hangup()).map_err(|e| {
87 CliError::Internal(format!("failed to install SIGHUP handler: {e}"))
88 })?;
89 Ok(Self { sighup })
90 }
91 #[cfg(not(unix))]
92 {
93 Ok(Self {})
94 }
95 }
96
97 async fn recv(&mut self) {
99 #[cfg(unix)]
100 {
101 self.sighup.recv().await;
102 }
103 #[cfg(not(unix))]
104 {
105 std::future::pending::<()>().await;
106 }
107 }
108}
109
110struct ReloadedBundle {
115 compiled: CompiledSchedule,
116 nodes: Vec<ExpandedNode>,
117 execution: Option<crate::config::ExecutionSpec>,
118 resilience: Option<faucet_core::ResiliencePolicy>,
119 sla: Option<crate::sla::SlaSpec>,
120 cron: String,
121 timezone: String,
122}
123
124async fn reload_bundle(path: &std::path::Path, profile: Option<&str>) -> CliResult<ReloadedBundle> {
128 let cfg = PipelineConfig::from_path_async(path, profile).await?;
129 let spec = cfg.schedule.as_ref().ok_or_else(|| {
130 CliError::Config("reload: config no longer has a `schedule:` block".into())
131 })?;
132 let compiled = CompiledSchedule::compile(spec)?;
133 let cron = spec.cron.clone();
134 let timezone = spec.timezone.clone();
135 let nodes = expand(&cfg)?;
136 let resilience = match &cfg.resilience {
137 Some(spec) => Some(spec.to_policy()?),
138 None => None,
139 };
140 Ok(ReloadedBundle {
141 compiled,
142 nodes,
143 execution: cfg.execution.clone(),
144 resilience,
145 sla: cfg.sla.clone(),
146 cron,
147 timezone,
148 })
149}
150
151const MAX_SLEEP: Duration = Duration::from_secs(30);
154
155pub async fn run(args: ScheduleArgs) -> CliResult<()> {
157 let cwd = std::env::current_dir()?;
158 let env_path =
159 crate::env_loader::resolve_env_file(args.env_file.as_deref(), args.no_env_file, &cwd)?;
160 crate::env_loader::load_env_file_if_present(env_path.as_deref())?;
161 let path = match args.config {
162 Some(p) => p,
163 None => crate::env_loader::discover_config_path(&cwd).ok_or(CliError::NoConfigOrFromEnv)?,
164 };
165
166 let cfg = PipelineConfig::from_path_async(&path, args.profile.as_deref()).await?;
167 let spec = cfg.schedule.as_ref().ok_or_else(|| {
168 CliError::Config(
169 "no `schedule:` block in config — use `faucet run` for a one-shot run, or add a `schedule:` block"
170 .into(),
171 )
172 })?;
173 let compiled = CompiledSchedule::compile(spec)?;
174 let cron = spec.cron.clone();
175 let timezone = spec.timezone.clone();
176
177 crate::obs::install(&cfg)?;
178
179 let pipeline_name = cfg.name.clone().unwrap_or_else(|| {
180 path.file_stem()
181 .and_then(|s| s.to_str())
182 .unwrap_or("pipeline")
183 .to_owned()
184 });
185
186 let auth = build_auth_catalog(cfg.auth.as_ref())?;
187 #[cfg(feature = "lineage")]
190 let lineage = crate::lineage_glue::build_emitter(cfg.lineage.as_ref())
191 .map_err(|e| CliError::Config(format!("lineage: {e}")))?;
192 #[cfg(feature = "lineage")]
193 let lineage_cfg = cfg.lineage.clone();
194 #[cfg(feature = "notify")]
197 let notifier = crate::notify::Notifier::from_specs(&cfg.notifications)?;
198 #[cfg(feature = "catalog")]
201 let catalog = match cfg.catalog.as_ref() {
202 Some(spec) => Some(crate::catalog::connect_from_spec(spec).await?),
203 None => None,
204 };
205 let nodes = expand(&cfg)?; let execution = cfg.execution.clone();
207 let resilience = match &cfg.resilience {
208 Some(spec) => Some(spec.to_policy()?),
209 None => None,
210 };
211
212 if args.once {
213 return run_once(
214 &nodes,
215 &auth,
216 &execution,
217 &compiled,
218 &pipeline_name,
219 &resilience,
220 &cfg.sla,
221 #[cfg(feature = "lineage")]
222 &lineage,
223 #[cfg(feature = "lineage")]
224 &lineage_cfg,
225 #[cfg(feature = "notify")]
226 ¬ifier,
227 #[cfg(feature = "catalog")]
228 &catalog,
229 )
230 .await;
231 }
232
233 run_loop(
234 compiled,
235 nodes,
236 auth,
237 execution,
238 pipeline_name,
239 cron,
240 timezone,
241 resilience,
242 cfg.sla.clone(),
243 path,
244 args.profile,
245 #[cfg(feature = "lineage")]
246 lineage,
247 #[cfg(feature = "lineage")]
248 lineage_cfg,
249 #[cfg(feature = "notify")]
250 notifier,
251 #[cfg(feature = "catalog")]
252 catalog,
253 )
254 .await
255}
256
257#[allow(clippy::too_many_arguments)]
260fn make_opts(
261 pipeline_name: &str,
262 execution: &Option<crate::config::ExecutionSpec>,
263 auth: &AuthCatalog,
264 clock: chrono::DateTime<chrono::FixedOffset>,
265 resilience: &Option<faucet_core::ResiliencePolicy>,
266 sla: &Option<crate::sla::SlaSpec>,
267 #[cfg(feature = "lineage")] lineage: &Option<std::sync::Arc<faucet_lineage::LineageEmitter>>,
268 #[cfg(feature = "lineage")] lineage_cfg: &Option<faucet_lineage::LineageConfig>,
269 #[cfg(feature = "notify")] notifier: &Option<std::sync::Arc<crate::notify::Notifier>>,
270 #[cfg(feature = "catalog")] catalog: &Option<crate::catalog::CatalogHandle>,
271) -> ExecuteOptions {
272 ExecuteOptions {
273 pipeline_name: pipeline_name.to_string(),
274 execution: execution.clone(),
275 dry_run: false,
276 limit: None,
277 state_path_override: None,
278 shard: None,
279 auth: auth.clone(),
280 clock,
281 cancel: None,
282 resilience: resilience.clone(),
283 sla: sla.clone(),
284 #[cfg(feature = "lineage")]
285 lineage: lineage.clone(),
286 #[cfg(feature = "lineage")]
287 lineage_cfg: lineage_cfg.clone(),
288 #[cfg(feature = "notify")]
289 notifier: notifier.clone(),
290 #[cfg(feature = "catalog")]
291 catalog: catalog.clone(),
292 }
293}
294
295fn run_span(run_ordinal: u64, scheduled_for: DateTime<Utc>, tick: DateTime<Utc>) -> tracing::Span {
299 tracing::info_span!(
300 "faucet.schedule.run",
301 run_ordinal,
302 scheduled_for_unix_seconds = scheduled_for.timestamp(),
303 tick_unix_seconds = tick.timestamp(),
304 )
305}
306
307fn spawn_run(
310 nodes: Vec<ExpandedNode>,
311 opts: ExecuteOptions,
312 timeout: Option<Duration>,
313 span: tracing::Span,
314) -> JoinHandle<CliResult<RunSummary>> {
315 tokio::spawn(
316 async move {
317 match timeout {
318 Some(d) => match tokio::time::timeout(d, run_expanded(nodes, opts)).await {
319 Ok(r) => r,
320 Err(_) => Err(CliError::Internal(format!(
321 "scheduled run exceeded run_timeout_secs ({}s) and was aborted",
322 d.as_secs()
323 ))),
324 },
325 None => run_expanded(nodes, opts).await,
326 }
327 }
328 .instrument(span),
329 )
330}
331
332const CIRCUIT_OPEN_PREFIX: &str = "Circuit open after";
338
339fn classify(
343 joined: Result<CliResult<RunSummary>, tokio::task::JoinError>,
344 breaker_cooldown: Option<Duration>,
345) -> RunFinished {
346 let circuit_open = match &joined {
348 Ok(Ok(summary)) => summary
349 .invocations
350 .iter()
351 .filter_map(|i| i.error.as_deref())
352 .any(|e| e.starts_with(CIRCUIT_OPEN_PREFIX)),
353 Ok(Err(e)) => e.to_string().contains(CIRCUIT_OPEN_PREFIX),
354 Err(_) => false,
355 };
356 let cooldown = if circuit_open {
359 let reconstructed: Result<(), faucet_core::FaucetError> =
360 Err(faucet_core::FaucetError::CircuitOpen {
361 failures: 0,
362 cooldown: breaker_cooldown.unwrap_or(Duration::ZERO),
363 });
364 crate::schedule::state::cooldown_delay(&reconstructed).filter(|d| !d.is_zero())
365 } else {
366 None
367 };
368
369 let (outcome, detail) = match joined {
370 Ok(Ok(summary)) if summary.had_failures() => (
371 RunOutcome::Failure,
372 Some(format!("{} invocation(s) failed", summary.failure_count())),
373 ),
374 Ok(Ok(_)) => (RunOutcome::Success, None),
375 Ok(Err(e)) => (RunOutcome::Failure, Some(e.to_string())),
376 Err(je) => (
377 RunOutcome::Failure,
378 Some(format!("run task panicked: {je}")),
379 ),
380 };
381 RunFinished {
382 outcome,
383 duration: Duration::ZERO,
384 detail,
385 cooldown,
386 }
387}
388
389#[allow(clippy::too_many_arguments)]
391async fn run_once(
392 nodes: &[ExpandedNode],
393 auth: &AuthCatalog,
394 execution: &Option<crate::config::ExecutionSpec>,
395 compiled: &CompiledSchedule,
396 pipeline_name: &str,
397 resilience: &Option<faucet_core::ResiliencePolicy>,
398 sla: &Option<crate::sla::SlaSpec>,
399 #[cfg(feature = "lineage")] lineage: &Option<std::sync::Arc<faucet_lineage::LineageEmitter>>,
400 #[cfg(feature = "lineage")] lineage_cfg: &Option<faucet_lineage::LineageConfig>,
401 #[cfg(feature = "notify")] notifier: &Option<std::sync::Arc<crate::notify::Notifier>>,
402 #[cfg(feature = "catalog")] catalog: &Option<crate::catalog::CatalogHandle>,
403) -> CliResult<()> {
404 tracing::info!(pipeline = %pipeline_name, "schedule --once: running one pipeline now");
405 let now = chrono::Utc::now();
406 let opts = make_opts(
407 pipeline_name,
408 execution,
409 auth,
410 compiled.clock_at(now),
411 resilience,
412 sla,
413 #[cfg(feature = "lineage")]
414 lineage,
415 #[cfg(feature = "lineage")]
416 lineage_cfg,
417 #[cfg(feature = "notify")]
418 notifier,
419 #[cfg(feature = "catalog")]
420 catalog,
421 );
422 let span = run_span(1, now, now);
423 let fut = run_expanded(nodes.to_vec(), opts).instrument(span);
424 let summary = match compiled.run_timeout {
425 Some(d) => tokio::time::timeout(d, fut).await.map_err(|_| {
426 CliError::Internal(format!(
427 "--once run exceeded run_timeout_secs ({}s)",
428 d.as_secs()
429 ))
430 })??,
431 None => fut.await?,
432 };
433 if summary.had_failures() {
434 return Err(CliError::PipelineHadFailures {
435 count: summary.failure_count(),
436 });
437 }
438 Ok(())
439}
440
441#[allow(clippy::too_many_arguments)]
443async fn run_loop(
444 mut compiled: CompiledSchedule,
445 mut nodes: Vec<ExpandedNode>,
446 auth: AuthCatalog,
447 mut execution: Option<crate::config::ExecutionSpec>,
448 pipeline_name: String,
449 mut cron: String,
450 mut timezone: String,
451 mut resilience: Option<faucet_core::ResiliencePolicy>,
452 mut sla: Option<crate::sla::SlaSpec>,
453 path: std::path::PathBuf,
454 profile: Option<String>,
455 #[cfg(feature = "lineage")] lineage: Option<std::sync::Arc<faucet_lineage::LineageEmitter>>,
456 #[cfg(feature = "lineage")] lineage_cfg: Option<faucet_lineage::LineageConfig>,
457 #[cfg(feature = "notify")] notifier: Option<std::sync::Arc<crate::notify::Notifier>>,
458 #[cfg(feature = "catalog")] catalog: Option<crate::catalog::CatalogHandle>,
459) -> CliResult<()> {
460 let mut state = SchedulerState::new(&compiled);
461 let mut breaker_cooldown = resilience
464 .as_ref()
465 .and_then(|r| r.circuit_breaker)
466 .map(|cb| cb.cooldown);
467 let mut shutdown = Shutdown::new()?;
468 let mut reload = Reload::new()?;
469 let mut running: Option<RunningRun> = None;
470 let mut pending_scheduled_for: Option<DateTime<Utc>> = None;
471 let mut run_ordinal: u64 = 0;
472
473 let mut next_due = if compiled.start_immediately {
474 Utc::now()
475 } else {
476 compiled
477 .next_after(Utc::now())
478 .ok_or_else(|| CliError::Config("schedule: no upcoming occurrence".into()))?
479 };
480
481 let upcoming: Vec<String> = {
484 let mut t = Utc::now();
485 let mut v = Vec::with_capacity(3);
486 while v.len() < 3 {
487 match compiled.next_after(t) {
488 Some(n) => {
489 v.push(n.to_rfc3339());
490 t = n;
491 }
492 None => break,
493 }
494 }
495 v
496 };
497 tracing::info!(
498 pipeline = %pipeline_name,
499 cron = %cron,
500 timezone = %timezone,
501 next_occurrences = ?upcoming,
502 "scheduler started (Ctrl-C / SIGTERM to stop)"
503 );
504
505 m::describe();
511 m::in_flight(&pipeline_name, 0);
512 m::consecutive_failures(&pipeline_name, 0);
513
514 loop {
515 let now = Utc::now();
516
517 if now >= next_due {
518 match state.on_tick(running.is_some()) {
519 TickAction::Dispatch => {
520 run_ordinal += 1;
521 let opts = make_opts(
522 &pipeline_name,
523 &execution,
524 &auth,
525 compiled.clock_at(next_due),
526 &resilience,
527 &sla,
528 #[cfg(feature = "lineage")]
529 &lineage,
530 #[cfg(feature = "lineage")]
531 &lineage_cfg,
532 #[cfg(feature = "notify")]
533 ¬ifier,
534 #[cfg(feature = "catalog")]
535 &catalog,
536 );
537 let span = run_span(run_ordinal, next_due, now);
538 let handle = spawn_run(nodes.clone(), opts, compiled.run_timeout, span);
539 m::in_flight(&pipeline_name, 1);
540 m::last_run_started(&pipeline_name, now);
541 m::lateness(&pipeline_name, now - next_due);
542 tracing::info!(pipeline = %pipeline_name, run_ordinal, scheduled_for = %next_due, "run started");
543 running = Some(RunningRun {
544 handle,
545 started: Instant::now(),
546 });
547 }
548 TickAction::Skip => {
549 m::overlap(&pipeline_name, "skip");
550 m::run_outcome(&pipeline_name, "skipped");
551 tracing::warn!(pipeline = %pipeline_name, scheduled_for = %next_due, "tick skipped — previous run still in progress");
552 }
553 TickAction::Queue => {
554 m::overlap(&pipeline_name, "queue");
555 if pending_scheduled_for.is_none() {
556 pending_scheduled_for = Some(next_due);
557 }
558 tracing::warn!(pipeline = %pipeline_name, scheduled_for = %next_due, "tick queued — will run after current run finishes");
559 }
560 TickAction::ForbidAbort => {
561 m::overlap(&pipeline_name, "forbid");
562 m::in_flight(&pipeline_name, 0);
566 return Err(CliError::ScheduleOverlapForbidden);
567 }
568 }
569 next_due = match compiled.next_due_after_tick(next_due, Utc::now()) {
574 Some(t) => t,
575 None => {
576 tracing::info!(pipeline = %pipeline_name, "no further scheduled occurrences; exiting");
577 return Ok(());
578 }
579 };
580 }
581
582 let now2 = Utc::now();
583 m::heartbeat(&pipeline_name, now2);
584 m::next_tick(&pipeline_name, next_due);
585 let chunk = (next_due - now2)
586 .to_std()
587 .unwrap_or(Duration::ZERO)
588 .min(MAX_SLEEP);
589
590 tokio::select! {
591 biased;
592
593 _ = shutdown.recv() => {
594 tracing::info!(pipeline = %pipeline_name, "shutdown signal received; draining in-flight run");
595 graceful_shutdown(running.take(), compiled.shutdown_grace, &pipeline_name).await;
596 faucet_core::shutdown_otel();
599 return Ok(());
600 }
601
602 finished = wait_for_run(&mut running, breaker_cooldown) => {
603 let mut finished = finished;
604 if let Some(rr) = running.take() {
605 finished.duration = rr.started.elapsed();
606 }
607 m::in_flight(&pipeline_name, 0);
608 let done_at = Utc::now();
609
610 if let Some(d) = finished.cooldown
618 && let Ok(delta) = chrono::Duration::from_std(d)
619 {
620 let resume = done_at + delta;
621 if resume > next_due {
622 next_due = resume;
623 }
624 tracing::warn!(
625 pipeline = %pipeline_name,
626 cooldown_secs = d.as_secs(),
627 next_due = %next_due,
628 "circuit breaker opened; delaying re-entry by cooldown"
629 );
630 }
631 m::last_run_completed(&pipeline_name, done_at);
632 m::last_run_duration(&pipeline_name, finished.duration);
633 m::run_outcome(&pipeline_name, match finished.outcome {
634 RunOutcome::Success => "ok",
635 RunOutcome::Failure => "err",
636 });
637 match finished.outcome {
638 RunOutcome::Success => tracing::info!(
639 pipeline = %pipeline_name, secs = finished.duration.as_secs_f64(), "run completed"
640 ),
641 RunOutcome::Failure => tracing::error!(
642 pipeline = %pipeline_name, detail = finished.detail.as_deref().unwrap_or("unknown"),
643 "run failed"
644 ),
645 }
646
647 let after = state.on_run_finished(finished.outcome);
648 m::consecutive_failures(&pipeline_name, state.consecutive_failures());
649 match after {
650 AfterRun::ExitOk => {
651 tracing::info!(pipeline = %pipeline_name, "max_runs reached; exiting");
652 return Ok(());
653 }
654 AfterRun::ExitFailure { consecutive } => {
655 #[cfg(feature = "notify")]
656 if let Some(n) = ¬ifier {
657 n.emit(crate::notify::NotifyEvent::scheduler_stuck(
658 &pipeline_name,
659 format!(
660 "scheduler exiting after {consecutive} consecutive failures"
661 ),
662 ))
663 .await;
664 }
665 return Err(CliError::PipelineHadFailures { count: consecutive as usize });
666 }
667 AfterRun::Continue { dispatch_pending } => {
668 if dispatch_pending {
669 run_ordinal += 1;
670 let sched_for = pending_scheduled_for.take().unwrap_or(done_at);
671 let opts = make_opts(
672 &pipeline_name,
673 &execution,
674 &auth,
675 compiled.clock_at(sched_for),
676 &resilience,
677 &sla,
678 #[cfg(feature = "lineage")]
679 &lineage,
680 #[cfg(feature = "lineage")]
681 &lineage_cfg,
682 #[cfg(feature = "notify")]
683 ¬ifier,
684 #[cfg(feature = "catalog")]
685 &catalog,
686 );
687 let span = run_span(run_ordinal, sched_for, done_at);
688 let handle = spawn_run(nodes.clone(), opts, compiled.run_timeout, span);
689 m::in_flight(&pipeline_name, 1);
690 m::last_run_started(&pipeline_name, done_at);
691 m::lateness(&pipeline_name, done_at - sched_for);
692 tracing::info!(pipeline = %pipeline_name, run_ordinal, scheduled_for = %sched_for, "queued run started");
693 running = Some(RunningRun { handle, started: Instant::now() });
694 }
695 }
696 }
697 }
698
699 _ = reload.recv() => {
700 match reload_bundle(&path, profile.as_deref()).await {
705 Ok(b) => {
706 compiled = b.compiled;
707 nodes = b.nodes;
708 execution = b.execution;
709 resilience = b.resilience;
710 sla = b.sla;
711 cron = b.cron;
712 timezone = b.timezone;
713 breaker_cooldown = resilience
714 .as_ref()
715 .and_then(|r| r.circuit_breaker)
716 .map(|cb| cb.cooldown);
717 next_due = if compiled.start_immediately {
718 Utc::now()
719 } else {
720 compiled.next_after(Utc::now()).unwrap_or(next_due)
721 };
722 m::reload(&pipeline_name, "ok");
723 tracing::info!(
724 pipeline = %pipeline_name, cron = %cron, timezone = %timezone,
725 next_due = %next_due, "config reloaded (SIGHUP)"
726 );
727 }
728 Err(e) => {
729 m::reload(&pipeline_name, "error");
730 tracing::error!(
731 pipeline = %pipeline_name, error = %e,
732 "config reload failed; keeping the previous config"
733 );
734 }
735 }
736 }
737
738 _ = tokio::time::sleep(chunk) => { }
739 }
740 }
741}
742
743async fn wait_for_run(
746 running: &mut Option<RunningRun>,
747 breaker_cooldown: Option<Duration>,
748) -> RunFinished {
749 match running {
750 Some(rr) => classify((&mut rr.handle).await, breaker_cooldown),
751 None => std::future::pending().await,
752 }
753}
754
755async fn graceful_shutdown(running: Option<RunningRun>, grace: Duration, pipeline_name: &str) {
757 if let Some(mut rr) = running {
758 match tokio::time::timeout(grace, &mut rr.handle).await {
759 Ok(_) => {
760 tracing::info!(pipeline = %pipeline_name, "in-flight run finished during shutdown grace")
761 }
762 Err(_) => {
763 rr.handle.abort();
764 tracing::warn!(
765 pipeline = %pipeline_name,
766 grace_secs = grace.as_secs(),
767 "in-flight run exceeded shutdown grace; aborted (partial sink state possible; bookmark preserved for the next run)"
768 );
769 }
770 }
771 m::in_flight(pipeline_name, 0);
772 }
773}
774
775#[cfg(test)]
776mod tests {
777 use super::*;
778 use crate::schedule::spec::ScheduleSpec;
779
780 fn compiled(yaml: &str) -> CompiledSchedule {
781 let spec: ScheduleSpec = serde_yaml::from_str(yaml).unwrap();
782 CompiledSchedule::compile(&spec).unwrap()
783 }
784
785 #[tokio::test]
789 async fn reload_bundle_validates_and_builds() {
790 let dir = tempfile::tempdir().unwrap();
791 let good = dir.path().join("good.yaml");
792 std::fs::write(
793 &good,
794 "version: 1\nname: sch\npipeline:\n source:\n type: csv\n config:\n path: in.csv\n sink:\n type: jsonl\n config:\n path: out.jsonl\nschedule:\n cron: \"*/5 * * * *\"\n timezone: UTC\n",
795 )
796 .unwrap();
797 let b = reload_bundle(&good, None)
798 .await
799 .expect("valid config reloads");
800 assert_eq!(b.cron, "*/5 * * * *");
801 assert_eq!(b.timezone, "UTC");
802 assert_eq!(b.nodes.len(), 1);
803
804 let bad = dir.path().join("bad.yaml");
806 std::fs::write(
807 &bad,
808 "version: 1\npipeline:\n source:\n type: csv\n config:\n path: in.csv\n sink:\n type: jsonl\n config:\n path: out.jsonl\n",
809 )
810 .unwrap();
811 assert!(reload_bundle(&bad, None).await.is_err());
812 }
813
814 fn summary(failures: usize, total: usize) -> RunSummary {
815 let mut invocations = Vec::new();
816 for i in 0..total {
817 invocations.push(crate::executor::InvocationOutcome {
818 row_id: format!("r{i}"),
819 parent_record_key: None,
820 records_written: if i < failures { 0 } else { 3 },
821 error: if i < failures {
822 Some("boom".into())
823 } else {
824 None
825 },
826 });
827 }
828 RunSummary { invocations }
829 }
830
831 #[test]
832 fn classify_success_when_no_failures() {
833 let joined = Ok(Ok(summary(0, 2)));
834 let f = classify(joined, None);
835 assert_eq!(f.outcome, RunOutcome::Success);
836 assert!(f.detail.is_none());
837 assert!(f.cooldown.is_none());
838 }
839
840 #[test]
841 fn classify_failure_when_some_invocations_failed() {
842 let joined = Ok(Ok(summary(2, 5)));
843 let f = classify(joined, None);
844 assert_eq!(f.outcome, RunOutcome::Failure);
845 assert_eq!(f.detail.as_deref(), Some("2 invocation(s) failed"));
846 assert!(f.cooldown.is_none());
847 }
848
849 #[test]
850 fn classify_failure_when_run_errored() {
851 let joined: Result<CliResult<RunSummary>, tokio::task::JoinError> =
852 Ok(Err(CliError::Internal("disk full".into())));
853 let f = classify(joined, None);
854 assert_eq!(f.outcome, RunOutcome::Failure);
855 assert!(f.detail.as_deref().unwrap().contains("disk full"));
856 }
857
858 #[tokio::test]
859 async fn classify_failure_when_task_panicked() {
860 let handle = tokio::spawn(async { panic!("kaboom") });
862 let joined: Result<CliResult<RunSummary>, tokio::task::JoinError> = handle.await.map(Ok);
863 let f = classify(joined, None);
864 assert_eq!(f.outcome, RunOutcome::Failure);
865 assert!(
866 f.detail.as_deref().unwrap().contains("panicked"),
867 "{:?}",
868 f.detail
869 );
870 }
871
872 #[test]
873 fn classify_recovers_cooldown_from_circuit_open_invocation() {
874 let circuit_open_msg = faucet_core::FaucetError::CircuitOpen {
877 failures: 3,
878 cooldown: Duration::from_secs(60),
879 }
880 .to_string();
881 let invocations = vec![crate::executor::InvocationOutcome {
882 row_id: "r0".into(),
883 parent_record_key: None,
884 records_written: 0,
885 error: Some(circuit_open_msg),
886 }];
887 let joined = Ok(Ok(RunSummary { invocations }));
888 let f = classify(joined, Some(Duration::from_secs(45)));
889 assert_eq!(f.outcome, RunOutcome::Failure);
890 assert_eq!(f.cooldown, Some(Duration::from_secs(45)));
891 }
892
893 #[test]
894 fn classify_circuit_open_without_configured_cooldown_yields_none() {
895 let circuit_open_msg = faucet_core::FaucetError::CircuitOpen {
898 failures: 1,
899 cooldown: Duration::from_secs(10),
900 }
901 .to_string();
902 let invocations = vec![crate::executor::InvocationOutcome {
903 row_id: "r0".into(),
904 parent_record_key: None,
905 records_written: 0,
906 error: Some(circuit_open_msg),
907 }];
908 let joined = Ok(Ok(RunSummary { invocations }));
909 let f = classify(joined, None);
910 assert_eq!(f.outcome, RunOutcome::Failure);
911 assert!(f.cooldown.is_none());
912 }
913
914 #[test]
915 fn classify_no_cooldown_for_ordinary_failure() {
916 let joined = Ok(Ok(summary(1, 2)));
919 let f = classify(joined, Some(Duration::from_secs(30)));
920 assert_eq!(f.outcome, RunOutcome::Failure);
921 assert!(f.cooldown.is_none());
922 }
923
924 #[test]
925 fn run_span_carries_ordinal_and_times() {
926 let scheduled = Utc::now();
927 let tick = scheduled + chrono::Duration::seconds(3);
928 let span = run_span(7, scheduled, tick);
929 assert_eq!(span.metadata().unwrap().name(), "faucet.schedule.run");
932 }
933
934 #[tokio::test]
935 async fn wait_for_run_returns_classified_outcome() {
936 let handle = tokio::spawn(async { Ok(summary(0, 1)) });
937 let mut running = Some(RunningRun {
938 handle,
939 started: Instant::now(),
940 });
941 let finished = wait_for_run(&mut running, None).await;
942 assert_eq!(finished.outcome, RunOutcome::Success);
943 }
944
945 #[tokio::test]
946 async fn spawn_run_times_out_into_internal_error() {
947 let dir = tempfile::tempdir().unwrap();
950 let input = dir.path().join("in.csv");
951 let output = dir.path().join("out.jsonl");
952 std::fs::write(&input, "name\nx\n").unwrap();
953 let yaml = format!(
955 "version: 1\npipeline:\n source: {{ type: csv, config: {{ path: {input} }} }}\n sink: {{ type: jsonl, config: {{ path: {output} }} }}\n",
956 input = input.display(),
957 output = output.display(),
958 );
959 let cfg = crate::config::parse_with_extension(&yaml, "yaml").unwrap();
960 let nodes = expand(&cfg).unwrap();
961 let auth = AuthCatalog::new();
962 let opts = make_opts(
963 "to",
964 &None,
965 &auth,
966 Utc::now().fixed_offset(),
967 &None,
968 &None,
969 #[cfg(feature = "lineage")]
970 &None,
971 #[cfg(feature = "lineage")]
972 &None,
973 #[cfg(feature = "notify")]
974 &None,
975 #[cfg(feature = "catalog")]
976 &None,
977 );
978 let handle = spawn_run(
981 nodes,
982 opts,
983 Some(Duration::from_nanos(1)),
984 run_span(1, Utc::now(), Utc::now()),
985 );
986 let joined = handle.await.unwrap();
987 if let Err(CliError::Internal(msg)) = &joined {
991 assert!(msg.contains("run_timeout_secs"), "{msg}");
992 }
993 }
994
995 #[tokio::test]
996 async fn make_opts_disables_dry_run_limit_and_state_override() {
997 let auth = AuthCatalog::new();
998 let clock = Utc::now().fixed_offset();
999 let opts = make_opts(
1000 "p",
1001 &None,
1002 &auth,
1003 clock,
1004 &None,
1005 &None,
1006 #[cfg(feature = "lineage")]
1007 &None,
1008 #[cfg(feature = "lineage")]
1009 &None,
1010 #[cfg(feature = "notify")]
1011 &None,
1012 #[cfg(feature = "catalog")]
1013 &None,
1014 );
1015 assert_eq!(opts.pipeline_name, "p");
1016 assert!(!opts.dry_run);
1017 assert!(opts.limit.is_none());
1018 assert!(opts.state_path_override.is_none());
1019 assert!(opts.cancel.is_none());
1020 assert_eq!(opts.clock, clock);
1021 }
1022
1023 #[tokio::test]
1024 async fn graceful_shutdown_awaits_finished_run() {
1025 let c = compiled("cron: \"* * * * *\"\nshutdown_grace_secs: 5");
1027 let handle = tokio::spawn(async { Ok(summary(0, 1)) });
1028 let running = Some(RunningRun {
1029 handle,
1030 started: Instant::now(),
1031 });
1032 graceful_shutdown(running, c.shutdown_grace, "p").await;
1034 }
1035
1036 #[tokio::test]
1037 async fn graceful_shutdown_aborts_run_exceeding_grace() {
1038 let handle = tokio::spawn(async {
1040 tokio::time::sleep(Duration::from_secs(3600)).await;
1041 Ok(summary(0, 1))
1042 });
1043 let running = Some(RunningRun {
1044 handle,
1045 started: Instant::now(),
1046 });
1047 graceful_shutdown(running, Duration::from_millis(50), "p").await;
1049 }
1050
1051 #[tokio::test]
1052 async fn graceful_shutdown_noop_when_idle() {
1053 graceful_shutdown(None, Duration::from_secs(1), "p").await;
1055 }
1056}