Skip to main content

schedr_agent/
api.rs

1//! A task's requests to schedr's REST API (M4.11h, the user's B2): sent to the master over the
2//! agent's stream, which runs them as the task; resent on a new stream until answered, for at
3//! most [`API_CALL_LIMIT`].
4
5use std::sync::Arc;
6use std::time::Duration;
7
8use schedr_proto::pb;
9use tokio::sync::oneshot;
10
11/// How long a call waits for its answer, over reconnects, before it is given up.
12pub const API_CALL_LIMIT: Duration = Duration::from_mins(1);
13
14/// Sends a call on to the master (through the agent's loop); the answer comes on the receiver.
15pub type ApiSend = Arc<dyn Fn(pb::ApiCall) -> oneshot::Receiver<pb::ApiAnswer> + Send + Sync>;
16
17/// What an attempt or a trigger calls the API with.
18#[derive(Clone)]
19pub struct ApiCaller {
20    attempt_id: String,
21    trigger_dag_id: String,
22    send: ApiSend,
23}
24
25impl std::fmt::Debug for ApiCaller {
26    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
27        f.debug_struct("ApiCaller")
28            .field("attempt_id", &self.attempt_id)
29            .field("trigger_dag_id", &self.trigger_dag_id)
30            .finish_non_exhaustive()
31    }
32}
33
34impl PartialEq for ApiCaller {
35    fn eq(&self, other: &Self) -> bool {
36        self.attempt_id == other.attempt_id && self.trigger_dag_id == other.trigger_dag_id
37    }
38}
39
40/// An API call's request, as a task makes it.
41#[derive(Debug, Clone, PartialEq, Eq)]
42pub struct ApiRequest {
43    /// `GET`, `POST`, ...
44    pub method: String,
45    /// The path and its query.
46    pub path: String,
47    /// The body, JSON.
48    pub body: Option<serde_json::Value>,
49    /// Its `Idempotency-Key`.
50    pub idempotency_key: Option<String>,
51    /// Whether [`ApiRequest::masked_by`] changed it: the task is told (B189's rule).
52    pub masked: bool,
53}
54
55impl ApiRequest {
56    /// The request with what the task read of its secrets masked in its body, as an output is:
57    /// what the API stores is shown to people (Codex's review of M4.11h).
58    #[must_use]
59    pub fn masked_by(mut self, secrets: Option<&crate::secrets::AttemptSecrets>) -> Self {
60        let Some(mask) = secrets
61            .map(|secrets| &secrets.mask)
62            .filter(|mask| !mask.is_empty())
63        else {
64            return self;
65        };
66        if let Some(body) = &self.body {
67            let masked = mask.mask_json(body);
68            self.masked |= &masked != body;
69            self.body = Some(masked);
70        }
71        // Stored too, as `request_key` (Grok's review).
72        if let Some(key) = &self.idempotency_key {
73            let masked = mask.mask_text(key);
74            self.masked |= &masked != key;
75            self.idempotency_key = Some(masked);
76        }
77        self
78    }
79
80    /// What the task is told of its request, if anything: that a secret in it was masked.
81    #[must_use]
82    pub fn note(&self) -> Option<String> {
83        self.masked.then(|| MASKED_REQUEST.to_owned())
84    }
85}
86
87impl ApiCaller {
88    /// The caller of attempt `attempt_id`.
89    #[must_use]
90    pub fn of_attempt(attempt_id: &str, send: ApiSend) -> Self {
91        Self {
92            attempt_id: attempt_id.to_owned(),
93            trigger_dag_id: String::new(),
94            send,
95        }
96    }
97
98    /// The caller of trigger instance `instance_id` of DAG `dag_id`.
99    #[must_use]
100    pub fn of_trigger(instance_id: &str, dag_id: &str, send: ApiSend) -> Self {
101        Self {
102            attempt_id: instance_id.to_owned(),
103            trigger_dag_id: dag_id.to_owned(),
104            send,
105        }
106    }
107
108    /// Makes the call: the status and body the API answered, or 503 when no answer came in
109    /// time (the agent away from its master that long).
110    pub async fn call(&self, request: ApiRequest) -> (u16, serde_json::Value) {
111        self.call_within(request, API_CALL_LIMIT).await
112    }
113
114    async fn call_within(&self, request: ApiRequest, limit: Duration) -> (u16, serde_json::Value) {
115        // Sent again after a reconnect, or by the task after a 503 with the key it is told, a
116        // call is still one (Codex's and Grok's reviews): the caller's own key, or this one.
117        let key = request.idempotency_key.unwrap_or_else(new_call_key);
118        let call = pb::ApiCall {
119            request_id: 0,
120            attempt_id: self.attempt_id.clone(),
121            trigger_dag_id: self.trigger_dag_id.clone(),
122            method: request.method,
123            path: request.path,
124            body_json: request
125                .body
126                .map(|body| serde_json::to_vec(&body).unwrap_or_default())
127                .unwrap_or_default(),
128            idempotency_key: key.clone(),
129        };
130        let answer = (self.send)(call);
131        match tokio::time::timeout(limit, answer).await {
132            Ok(Ok(answer)) => {
133                let body = if answer.body_json.is_empty() {
134                    serde_json::Value::Null
135                } else {
136                    serde_json::from_slice(&answer.body_json).unwrap_or_else(
137                        |_| serde_json::json!({"error": "the API's answer doesn't read"}),
138                    )
139                };
140                (u16::try_from(answer.status).unwrap_or(500), body)
141            }
142            Ok(Err(_)) => {
143                unavailable_with_key("the agent stopped before the master answered", &key)
144            }
145            Err(_) => unavailable_with_key(
146                &format!(
147                    "no answer from the master within {} s: the call may still be made; send it \
148                     again with Idempotency-Key `{key}`",
149                    limit.as_secs()
150                ),
151                &key,
152            ),
153        }
154    }
155}
156
157/// A runner's [`schedr_model::runner::RunnerMessage::ApiCall`] answered: through `api`, or
158/// refused where there is none.
159pub async fn runner_answer(
160    api: Option<&ApiCaller>,
161    request: ApiRequest,
162) -> schedr_model::runner::AgentMessage {
163    let note = request.note();
164    let (status, body) = match api {
165        Some(api) => api.call(request).await,
166        None => unavailable(NO_MASTER),
167    };
168    schedr_model::runner::AgentMessage::ApiAnswer { status, body, note }
169}
170
171/// What a task is told when its request held a secret it read (as a trigger's log is, B189).
172pub const MASKED_REQUEST: &str = "schedr: a request to the API held a secret this task read: it \
173                                  was sent masked (****), as an output is; event keys differing \
174                                  only in secrets count as one key";
175
176/// Why a process that isn't a task's or a trigger's (a connection's test) can't call the API.
177pub const NO_MASTER: &str = "schedr's API is called from a task or a trigger a worker runs, as \
178                             that task; this process runs for neither (a connection's test)";
179
180/// A key of a call's own, for one made without: unique in this process (the clock and a count).
181fn new_call_key() -> String {
182    static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
183    let n = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
184    let now = std::time::SystemTime::now()
185        .duration_since(std::time::UNIX_EPOCH)
186        .map_or(0, |since| since.as_nanos());
187    format!("schedr-call-{now:x}-{n}")
188}
189
190/// A 503 naming the key the call was made with, to send it again with.
191fn unavailable_with_key(why: &str, key: &str) -> (u16, serde_json::Value) {
192    (
193        503,
194        serde_json::json!({ "error": why, "idempotency_key": key }),
195    )
196}
197
198fn unavailable(why: &str) -> (u16, serde_json::Value) {
199    (503, serde_json::json!({ "error": why }))
200}
201
202#[cfg(test)]
203mod tests {
204    use super::*;
205
206    fn caller(answer: Option<pb::ApiAnswer>) -> ApiCaller {
207        let sent = Arc::new(std::sync::Mutex::new(Vec::new()));
208        let kept = Arc::new(std::sync::Mutex::new(Vec::new()));
209        ApiCaller::of_attempt(
210            "a1",
211            Arc::new(move |call| {
212                sent.lock().unwrap().push(call);
213                let (tx, rx) = oneshot::channel();
214                match &answer {
215                    Some(answer) => {
216                        let _ = tx.send(answer.clone());
217                    }
218                    // Kept unanswered, as a master away.
219                    None => kept.lock().unwrap().push(tx),
220                }
221                rx
222            }),
223        )
224    }
225
226    fn post() -> ApiRequest {
227        ApiRequest {
228            method: "POST".to_owned(),
229            path: "/api/v1/events".to_owned(),
230            body: Some(serde_json::json!({"name": "paid", "key": "o-1"})),
231            idempotency_key: Some("k".to_owned()),
232            masked: false,
233        }
234    }
235
236    #[tokio::test]
237    async fn a_call_gives_what_the_master_answered() {
238        let answer = pb::ApiAnswer {
239            request_id: 1,
240            status: 201,
241            body_json: br#"{"id": "e1", "new": true}"#.to_vec(),
242        };
243        let (status, body) = caller(Some(answer)).call(post()).await;
244        assert_eq!(status, 201);
245        assert_eq!(body["id"], "e1");
246    }
247
248    #[tokio::test]
249    async fn a_call_unanswered_in_time_is_unavailable() {
250        let (status, body) = caller(None)
251            .call_within(post(), Duration::from_millis(20))
252            .await;
253        assert_eq!(status, 503);
254        assert!(
255            body["error"]
256                .as_str()
257                .unwrap()
258                .contains("Idempotency-Key `k`")
259        );
260        assert_eq!(body["idempotency_key"], "k");
261        // One made without a key is given one, and told it (Grok's review).
262        let keyless = ApiRequest {
263            idempotency_key: None,
264            ..post()
265        };
266        let (_, body) = caller(None)
267            .call_within(keyless, Duration::from_millis(20))
268            .await;
269        assert!(
270            body["idempotency_key"]
271                .as_str()
272                .unwrap()
273                .starts_with("schedr-call-"),
274            "{body}"
275        );
276    }
277}