Skip to main content

faucet_cli/serve/triggers/
enqueue.rs

1//! The single choke point all trigger fires funnel through. `build_submit_request`
2//! is pure (text + event → SubmitRequest); `fire` resolves the pipeline ref,
3//! substitutes, submits via the existing runner, and maps the outcome.
4
5use super::compiled::CompiledTrigger;
6use super::context::{self, TriggerEvent};
7use super::{metrics, spec::PipelineRef};
8use crate::serve::runner::{self, ConfigFormatWire, SubmitRequest};
9use crate::serve::state::ServerState;
10
11#[derive(Debug)]
12pub enum FireOutcome {
13    /// A new run was enqueued / a Pending record written (cluster).
14    Enqueued(String),
15    /// Same idempotency key with a conflicting payload hash — treated as a
16    /// committed no-op so a polling watcher does not retry the same event forever.
17    Coalesced,
18    /// Dropped without enqueuing (e.g. queue full); polling watchers must NOT
19    /// advance their cursor/edge on this outcome.
20    Dropped(&'static str),
21    /// An error building or submitting the run.
22    Error(String),
23}
24
25impl FireOutcome {
26    /// Whether the watcher may advance its cursor/edge past this event.
27    pub fn committed(&self) -> bool {
28        matches!(self, FireOutcome::Enqueued(_) | FireOutcome::Coalesced)
29    }
30}
31
32/// Resolve the pipeline ref to config text and substitute `${trigger.*}`.
33pub async fn resolve_config_text(
34    config: &PipelineRef,
35    event: &TriggerEvent,
36    name: &str,
37    fired_at: &str,
38) -> Result<String, String> {
39    let raw = match config {
40        PipelineRef::Path(p) => tokio::fs::read_to_string(p)
41            .await
42            .map_err(|e| format!("reading pipeline config '{p}': {e}"))?,
43        PipelineRef::Inline(v) => {
44            serde_yaml::to_string(v).map_err(|e| format!("serializing inline pipeline: {e}"))?
45        }
46    };
47    context::substitute(&raw, event, name, fired_at)
48}
49
50/// Build the `SubmitRequest` for an already-resolved config text. Pure.
51pub fn build_submit_request(
52    compiled: &CompiledTrigger,
53    event: &TriggerEvent,
54    config_text: String,
55    fired_at: &str,
56) -> SubmitRequest {
57    let name = compiled.name();
58    let mut labels = context::labels(name, event);
59    labels.extend(compiled.spec.run.labels.clone());
60    let run_name = compiled
61        .spec
62        .run
63        .name
64        .as_deref()
65        .map(|tpl| context::render_name(tpl, event, name, fired_at))
66        .unwrap_or_else(|| name.to_string());
67    SubmitRequest {
68        config: config_text,
69        config_format: ConfigFormatWire::Yaml,
70        name: Some(run_name),
71        labels,
72        timeout_secs: compiled.spec.run.timeout_secs,
73        doctor_first: false,
74        idempotency_key: Some(context::idempotency_key(name, event)),
75        clock: None,
76    }
77}
78
79/// Resolve + submit. `fired_at` is RFC3339 (caller-stamped).
80pub async fn fire(
81    state: &ServerState,
82    compiled: &CompiledTrigger,
83    event: TriggerEvent,
84    fired_at: &str,
85) -> FireOutcome {
86    let kind = compiled.kind_label();
87    metrics::fired(compiled.name(), kind);
88
89    let text =
90        match resolve_config_text(&compiled.spec.config, &event, compiled.name(), fired_at).await {
91            Ok(t) => t,
92            Err(e) => {
93                metrics::error(compiled.name(), kind);
94                return FireOutcome::Error(e);
95            }
96        };
97    let req = build_submit_request(compiled, &event, text, fired_at);
98    // True idempotency replays (same key + same payload) return Ok from submit
99    // and are counted as Enqueued here; the serve-layer
100    // faucet_serve_idempotency_hits_total captures them. A Conflict (same key,
101    // different payload hash) is treated as a committed no-op (Coalesced) so a
102    // polling watcher does not retry the same event forever.
103    match runner::submit(state.clone(), req).await {
104        Ok(resp) => {
105            metrics::enqueued(compiled.name());
106            FireOutcome::Enqueued(resp.run_id)
107        }
108        Err(crate::serve::error::ServeError::QueueFull { .. }) => {
109            metrics::dropped(compiled.name(), "queue_full");
110            FireOutcome::Dropped("queue_full")
111        }
112        Err(crate::serve::error::ServeError::Conflict(_)) => {
113            // Idempotency conflict (same key, different payload) — treat as a
114            // committed no-op so a poll doesn't retry forever.
115            metrics::coalesced(compiled.name());
116            FireOutcome::Coalesced
117        }
118        Err(e) => {
119            metrics::error(compiled.name(), kind);
120            FireOutcome::Error(e.api_error().error.message)
121        }
122    }
123}
124
125#[cfg(test)]
126mod tests {
127    use super::*;
128    use crate::serve::triggers::spec::{RunTemplate, TriggerKind, TriggerSpec};
129
130    fn compiled_webhook() -> CompiledTrigger {
131        CompiledTrigger {
132            spec: TriggerSpec {
133                name: "hook".into(),
134                enabled: true,
135                config: PipelineRef::Path("/tmp/x.yaml".into()),
136                run: RunTemplate {
137                    name: Some("{name}:{object_key}".into()),
138                    labels: Default::default(),
139                    timeout_secs: Some(60),
140                },
141                kind: TriggerKind::Webhook {
142                    methods: vec!["POST".into()],
143                    dedupe_header: None,
144                    debounce_secs: 0,
145                },
146            },
147            webhook_path: Some("/v1/triggers/hook".into()),
148        }
149    }
150
151    #[test]
152    fn builds_request_with_labels_idem_and_timeout() {
153        let event = TriggerEvent::Object {
154            bucket: "b".into(),
155            key: "k".into(),
156            size: 1,
157            last_modified: "2026-06-12T00:00:00Z".into(),
158        };
159        let req = build_submit_request(&compiled_webhook(), &event, "version: 1".into(), "now");
160        assert_eq!(req.name.as_deref(), Some("hook:k"));
161        assert_eq!(req.timeout_secs, Some(60));
162        assert_eq!(
163            req.idempotency_key.as_deref(),
164            Some("trig:hook:b:k:2026-06-12T00:00:00Z")
165        );
166        assert_eq!(
167            req.labels.get("faucet.trigger.name").map(String::as_str),
168            Some("hook")
169        );
170        assert!(!req.doctor_first);
171    }
172}