Skip to main content

faucet_cli/serve/handlers/
runs.rs

1//! `/v1/runs*` HTTP handlers. Thin glue: deserialize, call into `runner`/history,
2//! map to status codes. All run-mutating logic lives in `runner.rs`.
3
4use crate::serve::error::ServeError;
5use crate::serve::history::{DeleteOutcome, ListFilter, RunRecord, RunStatus};
6use crate::serve::rbac::AuthContext;
7use crate::serve::runner::{self, SubmitRequest, SubmitResponse};
8use crate::serve::state::ServerState;
9use axum::Json;
10use axum::extract::{Extension, Path, Query, State};
11use axum::http::StatusCode;
12use axum::response::IntoResponse;
13use chrono::{DateTime, Utc};
14use serde::{Deserialize, Serialize};
15
16/// Scrub any resolved secret that reached a run's error fields before the record
17/// is serialized into an HTTP response. The serve log subscriber's redaction
18/// writer only covers tracing/log output — API response bodies are a separate
19/// egress and must be scrubbed here.
20fn redact_record(rec: &mut RunRecord) {
21    if let Some(e) = &rec.error {
22        rec.error = Some(crate::secrets::registry::redact(e).into_owned());
23    }
24    for inv in &mut rec.invocations {
25        if let Some(e) = &inv.error {
26            inv.error = Some(crate::secrets::registry::redact(e).into_owned());
27        }
28    }
29}
30
31/// `POST /v1/runs` → 202. The auth middleware injects the resolved
32/// [`AuthContext`] so `submit` can attribute the `run.submit` audit record.
33pub async fn submit_run(
34    State(state): State<ServerState>,
35    Extension(actor): Extension<AuthContext>,
36    Json(req): Json<SubmitRequest>,
37) -> Result<(StatusCode, Json<SubmitResponse>), ServeError> {
38    let resp = runner::submit(state, req, actor).await?;
39    Ok((StatusCode::ACCEPTED, Json(resp)))
40}
41
42/// `GET /v1/runs/{id}` → 200 RunRecord. Fills live `elapsed_secs` for running runs.
43pub async fn get_run(
44    State(state): State<ServerState>,
45    Path(id): Path<String>,
46) -> Result<Json<RunRecord>, ServeError> {
47    let mut rec = state
48        .history()
49        .get(&id)
50        .await
51        .map_err(|e| ServeError::Internal(e.to_string()))?
52        .ok_or(ServeError::NotFound)?;
53    if rec.status == RunStatus::Running
54        && let Some(started) = rec.started_at
55    {
56        rec.elapsed_secs = (Utc::now() - started)
57            .to_std()
58            .ok()
59            .map(|d| d.as_secs_f64());
60    }
61    redact_record(&mut rec);
62    Ok(Json(rec))
63}
64
65/// `POST /v1/runs/{id}/cancel` → 202 (cancel requested) / 200 (terminal no-op) / 404.
66/// In cluster mode, cancel is best-effort: the run may complete on its owning
67/// instance before that instance processes the flag.
68pub async fn cancel_run(
69    State(state): State<ServerState>,
70    Extension(actor): Extension<AuthContext>,
71    Path(id): Path<String>,
72) -> Result<impl IntoResponse, ServeError> {
73    // 1. A live local token (this instance is running/queued it) → cancel now.
74    if state.registry().cancel(&id) {
75        crate::serve::audit::write(&state, &actor, "run.cancel", Some(id.clone()), None, "ok")
76            .await;
77        return Ok(StatusCode::ACCEPTED);
78    }
79
80    // 2. Look up the record.
81    let rec = match state
82        .history()
83        .get(&id)
84        .await
85        .map_err(|e| ServeError::Internal(e.to_string()))?
86    {
87        Some(r) => r,
88        None => return Err(ServeError::NotFound),
89    };
90
91    if rec.status.is_terminal() {
92        return Ok(StatusCode::OK); // already done — no-op.
93    }
94
95    // 3. Cluster mode: the run is owned by another instance (or unclaimed).
96    if state.cluster().enabled() {
97        // Unclaimed (Pending) → cancel it directly.
98        if state
99            .history()
100            .cancel_pending(&id)
101            .await
102            .map_err(|e| ServeError::Internal(e.to_string()))?
103        {
104            crate::serve::audit::write(&state, &actor, "run.cancel", Some(id.clone()), None, "ok")
105                .await;
106            return Ok(StatusCode::ACCEPTED);
107        }
108        // Otherwise it is running on a peer → flag it; the peer cancels on its
109        // next claim-loop tick.
110        state
111            .history()
112            .request_cancel(&id)
113            .await
114            .map_err(|e| ServeError::Internal(e.to_string()))?;
115        crate::serve::audit::write(&state, &actor, "run.cancel", Some(id.clone()), None, "ok")
116            .await;
117        return Ok(StatusCode::ACCEPTED);
118    }
119
120    // Single-instance, non-terminal, no local token: a transient race (the token
121    // was removed between the registry check and the history read as the run
122    // completes). Treat as a no-op — the run is finishing or just finished.
123    Ok(StatusCode::OK)
124}
125
126/// `DELETE /v1/runs/{id}` → 204 / 404 / 409 (still running).
127pub async fn delete_run(
128    State(state): State<ServerState>,
129    Extension(actor): Extension<AuthContext>,
130    Path(id): Path<String>,
131) -> Result<StatusCode, ServeError> {
132    match state
133        .history()
134        .delete(&id)
135        .await
136        .map_err(|e| ServeError::Internal(e.to_string()))?
137    {
138        DeleteOutcome::Deleted => {
139            crate::serve::audit::write(&state, &actor, "run.delete", Some(id.clone()), None, "ok")
140                .await;
141            Ok(StatusCode::NO_CONTENT)
142        }
143        DeleteOutcome::NotFound => Err(ServeError::NotFound),
144        DeleteOutcome::StillRunning => Err(ServeError::Conflict(
145            "run is still in flight — cancel it before deleting".into(),
146        )),
147    }
148}
149
150/// Query-param wrapper for an RFC3339 timestamp. `application/x-www-form-urlencoded`
151/// decodes `+` as a space, which corrupts explicit UTC offsets like `+05:30`; we
152/// restore the `+` before parsing, so both `…Z` and `…+05:30` query values work.
153#[derive(Debug, Clone, Copy)]
154pub(crate) struct DateTimeUtcParam(DateTime<Utc>);
155
156impl<'de> Deserialize<'de> for DateTimeUtcParam {
157    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
158        let raw = String::deserialize(d)?;
159        // Undo form-encoding's '+' → ' ' substitution before RFC3339 parsing.
160        let restored = raw.replace(' ', "+");
161        DateTime::parse_from_rfc3339(&restored)
162            .map(|dt| DateTimeUtcParam(dt.to_utc()))
163            .map_err(serde::de::Error::custom)
164    }
165}
166
167/// `GET /v1/runs` query string.
168#[derive(Debug, Deserialize)]
169pub struct ListQuery {
170    pub status: Option<RunStatus>,
171    pub name: Option<String>,
172    pub(crate) since: Option<DateTimeUtcParam>,
173    pub(crate) until: Option<DateTimeUtcParam>,
174    pub limit: Option<usize>,
175    pub cursor: Option<String>,
176}
177
178/// `GET /v1/runs` response body.
179#[derive(Debug, Serialize)]
180pub struct ListResponse {
181    pub runs: Vec<RunRecord>,
182    #[serde(skip_serializing_if = "Option::is_none")]
183    pub next_cursor: Option<String>,
184}
185
186const DEFAULT_LIMIT: usize = 50;
187const MAX_LIMIT: usize = 500;
188
189impl ListQuery {
190    fn into_filter(self) -> ListFilter {
191        ListFilter {
192            status: self.status,
193            name: self.name,
194            since: self.since.map(|p| p.0),
195            until: self.until.map(|p| p.0),
196            limit: self.limit.unwrap_or(DEFAULT_LIMIT).clamp(1, MAX_LIMIT),
197            cursor: self.cursor,
198        }
199    }
200}
201
202/// `GET /v1/runs` → 200.
203pub async fn list_runs(
204    State(state): State<ServerState>,
205    Query(query): Query<ListQuery>,
206) -> Result<Json<ListResponse>, ServeError> {
207    let page = state
208        .history()
209        .list(&query.into_filter())
210        .await
211        .map_err(|e| ServeError::Internal(e.to_string()))?;
212    let mut runs = page.runs;
213    for rec in &mut runs {
214        redact_record(rec);
215    }
216    Ok(Json(ListResponse {
217        runs,
218        next_cursor: page.next_cursor,
219    }))
220}
221
222#[cfg(test)]
223mod tests {
224    use super::*;
225
226    #[test]
227    fn datetime_param_restores_form_encoded_plus() {
228        // form-encoding turns the '+' of an offset into a space; the wrapper must
229        // restore it so both offset and Z forms parse to the same UTC instant.
230        let spaced: DateTimeUtcParam =
231            serde_json::from_value(serde_json::json!("2026-01-01T00:00:00 05:30")).unwrap();
232        let plus = chrono::DateTime::parse_from_rfc3339("2026-01-01T00:00:00+05:30")
233            .unwrap()
234            .to_utc();
235        assert_eq!(spaced.0, plus);
236
237        let zulu: DateTimeUtcParam =
238            serde_json::from_value(serde_json::json!("2026-01-01T00:00:00Z")).unwrap();
239        assert_eq!(
240            zulu.0,
241            chrono::DateTime::parse_from_rfc3339("2026-01-01T00:00:00Z")
242                .unwrap()
243                .to_utc()
244        );
245    }
246
247    #[test]
248    fn list_query_clamps_limit() {
249        let q = ListQuery {
250            status: None,
251            name: None,
252            since: None,
253            until: None,
254            limit: Some(99999),
255            cursor: None,
256        };
257        assert_eq!(q.into_filter().limit, MAX_LIMIT);
258        let q = ListQuery {
259            status: Some(RunStatus::Failed),
260            name: None,
261            since: None,
262            until: None,
263            limit: None,
264            cursor: None,
265        };
266        let f = q.into_filter();
267        assert_eq!(f.limit, DEFAULT_LIMIT);
268        assert_eq!(f.status, Some(RunStatus::Failed));
269    }
270
271    #[tokio::test]
272    async fn cancel_pending_run_in_cluster_mode_cancels_it() {
273        use crate::serve::history::{RunRecord, RunStatus};
274        use crate::serve::test_support::test_state_clustered;
275        use chrono::Utc;
276
277        let state = test_state_clustered();
278        // A pending run with no local token (simulating an unclaimed cluster run).
279        let mut rec = RunRecord::queued("p1".into(), None, Default::default(), None, Utc::now());
280        rec.status = RunStatus::Pending;
281        state.history().upsert(&rec).await.unwrap();
282
283        let resp = cancel_run(
284            axum::extract::State(state.clone()),
285            axum::extract::Extension(AuthContext {
286                principal: "test".into(),
287                role: crate::serve::rbac::Role::Admin,
288                source_ip: None,
289            }),
290            axum::extract::Path("p1".into()),
291        )
292        .await
293        .unwrap()
294        .into_response();
295        assert_eq!(resp.status(), StatusCode::ACCEPTED);
296        assert_eq!(
297            state.history().get("p1").await.unwrap().unwrap().status,
298            RunStatus::Cancelled
299        );
300    }
301}