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    // Trigger-originated (non-HTTP) submission → attribute the audit record to
104    // the trigger (`trigger:<name>`).
105    let actor = crate::serve::rbac::AuthContext::trigger(compiled.name());
106    match runner::submit(state.clone(), req, actor).await {
107        Ok(resp) => {
108            metrics::enqueued(compiled.name());
109            FireOutcome::Enqueued(resp.run_id)
110        }
111        Err(crate::serve::error::ServeError::QueueFull { .. }) => {
112            metrics::dropped(compiled.name(), "queue_full");
113            FireOutcome::Dropped("queue_full")
114        }
115        Err(crate::serve::error::ServeError::Conflict(_)) => {
116            // Idempotency conflict (same key, different payload) — treat as a
117            // committed no-op so a poll doesn't retry forever.
118            metrics::coalesced(compiled.name());
119            FireOutcome::Coalesced
120        }
121        Err(e) => {
122            metrics::error(compiled.name(), kind);
123            FireOutcome::Error(e.api_error().error.message)
124        }
125    }
126}
127
128#[cfg(test)]
129mod tests {
130    use super::*;
131    use crate::serve::triggers::spec::{RunTemplate, TriggerKind, TriggerSpec};
132
133    fn compiled_webhook() -> CompiledTrigger {
134        CompiledTrigger {
135            spec: TriggerSpec {
136                name: "hook".into(),
137                enabled: true,
138                config: PipelineRef::Path("/tmp/x.yaml".into()),
139                run: RunTemplate {
140                    name: Some("{name}:{object_key}".into()),
141                    labels: Default::default(),
142                    timeout_secs: Some(60),
143                },
144                kind: TriggerKind::Webhook {
145                    methods: vec!["POST".into()],
146                    dedupe_header: None,
147                    debounce_secs: 0,
148                },
149            },
150            webhook_path: Some("/v1/triggers/hook".into()),
151        }
152    }
153
154    #[test]
155    fn builds_request_with_labels_idem_and_timeout() {
156        let event = TriggerEvent::Object {
157            bucket: "b".into(),
158            key: "k".into(),
159            size: 1,
160            last_modified: "2026-06-12T00:00:00Z".into(),
161        };
162        let req = build_submit_request(&compiled_webhook(), &event, "version: 1".into(), "now");
163        assert_eq!(req.name.as_deref(), Some("hook:k"));
164        assert_eq!(req.timeout_secs, Some(60));
165        assert_eq!(
166            req.idempotency_key.as_deref(),
167            Some("trig:hook:b:k:2026-06-12T00:00:00Z")
168        );
169        assert_eq!(
170            req.labels.get("faucet.trigger.name").map(String::as_str),
171            Some("hook")
172        );
173        assert!(!req.doctor_first);
174    }
175}