Skip to main content

faucet_cli/commands/
notify.rs

1//! `faucet notify test` — fire one synthetic event through a config's
2//! `notifications:` rules to validate channel setup end-to-end (no pipeline
3//! runs). Uses the real delivery path, so a Slack/PagerDuty/webhook that is
4//! reachable will actually receive the test message.
5
6use crate::cli::{NotifyArgs, NotifyCommand, NotifyTestArgs};
7use crate::config::PipelineConfig;
8use crate::error::{CliError, CliResult};
9use crate::notify::{Notifier, NotifyEvent};
10
11/// Execute the `notify` subcommand.
12pub async fn run(args: NotifyArgs) -> CliResult<()> {
13    match args.command {
14        NotifyCommand::Test(a) => test(a).await,
15    }
16}
17
18async fn test(args: NotifyTestArgs) -> CliResult<()> {
19    let cwd = std::env::current_dir()?;
20    let env_path =
21        crate::env_loader::resolve_env_file(args.env_file.as_deref(), args.no_env_file, &cwd)?;
22    crate::env_loader::load_env_file_if_present(env_path.as_deref())?;
23
24    let path = match args.config {
25        Some(p) => p,
26        None => crate::env_loader::discover_config_path(&cwd).ok_or(CliError::NoConfigOrFromEnv)?,
27    };
28    // Real load (resolves secrets) so channel credentials are live for delivery.
29    let cfg = PipelineConfig::from_path_async(&path, None).await?;
30    if cfg.notifications.is_empty() {
31        return Err(CliError::Config(
32            "no `notifications:` block in this config — add one, or run \
33             `faucet schema notifications` to see the block's JSON Schema"
34                .to_string(),
35        ));
36    }
37
38    let notifier = Notifier::from_specs(&cfg.notifications)?
39        .expect("a non-empty notifications list yields Some(notifier)");
40    let pipeline = cfg
41        .name
42        .clone()
43        .unwrap_or_else(|| "faucet-notify-test".to_string());
44    let event = synth_event(&args.event, &pipeline)?;
45
46    println!(
47        "Firing synthetic `{}` event through {} notification rule(s)…",
48        args.event,
49        cfg.notifications.len()
50    );
51    notifier.emit(event).await;
52    println!("Done — check your channels. Any delivery failure was logged above.");
53    Ok(())
54}
55
56/// Build a synthetic event for the requested kind. DLQ uses a large count so it
57/// clears any configured `dlq_threshold`.
58fn synth_event(kind: &str, pipeline: &str) -> CliResult<NotifyEvent> {
59    Ok(match kind {
60        "run_failure" => NotifyEvent::run_failure(
61            pipeline,
62            "",
63            "test",
64            "synthetic test failure from `faucet notify test`",
65        ),
66        "run_success" => NotifyEvent::run_success(pipeline, "", 0),
67        "sla_breach" => NotifyEvent::sla_breach(pipeline, "", "staleness", "synthetic SLA breach"),
68        "circuit_open" => NotifyEvent::circuit_open(pipeline, "", 5, 30),
69        "contract_abort" => NotifyEvent::contract_abort(pipeline, "", "synthetic contract breach"),
70        "dlq_threshold" => NotifyEvent::dlq_threshold(pipeline, "", 1_000_000),
71        "scheduler_stuck" => NotifyEvent::scheduler_stuck(pipeline, "synthetic scheduler-stuck"),
72        other => {
73            return Err(CliError::Config(format!(
74                "unknown --event `{other}` (expected one of: run_failure, run_success, \
75                 sla_breach, circuit_open, contract_abort, dlq_threshold, scheduler_stuck)"
76            )));
77        }
78    })
79}
80
81#[cfg(test)]
82mod tests {
83    use super::*;
84
85    #[test]
86    fn synth_event_maps_known_kinds() {
87        use crate::notify::EventKind;
88        assert_eq!(
89            synth_event("run_failure", "p").unwrap().kind,
90            EventKind::RunFailure
91        );
92        assert_eq!(
93            synth_event("scheduler_stuck", "p").unwrap().kind,
94            EventKind::SchedulerStuck
95        );
96        // DLQ synthetic count clears any reasonable threshold.
97        assert_eq!(
98            synth_event("dlq_threshold", "p")
99                .unwrap()
100                .details
101                .get("records_dlq")
102                .and_then(|v| v.as_u64()),
103            Some(1_000_000)
104        );
105    }
106
107    #[test]
108    fn synth_event_rejects_unknown_kind() {
109        assert!(synth_event("nope", "p").is_err());
110    }
111}