Skip to main content

schedr_master/core/
task_api.rs

1//! A task's REST requests through its agent (M4.11h, the user's B2): the master runs them
2//! through the API's own router as the task's identity, on an allow-list of routes, so a task
3//! needs no URL or token and reaches nothing else.
4
5use std::fmt::Debug;
6use std::future::Future;
7use std::pin::Pin;
8
9use schedr_proto::pb::{self, master_message};
10
11use super::{CoreError, MasterCore, Outgoing};
12
13/// The routes a task may call, by method and path (a query is allowed after it): the events
14/// (the user's, 2026-11-08), whose code is the API's own, and its own notifications (decision
15/// 421), which the master answers itself.
16pub const TASK_ROUTES: &[(&str, &str)] = &[
17    ("POST", "/api/v1/events"),
18    ("GET", "/api/v1/events"),
19    ("POST", NOTIFICATIONS),
20];
21
22/// A task's own notification: `{"channel": ..., "text": ..., "data": ...}`, answered 202 once
23/// queued.
24pub const NOTIFICATIONS: &str = "/api/v1/notifications";
25
26/// A request a task made, as the router gets it.
27#[derive(Debug, Clone, PartialEq, Eq)]
28pub struct TaskApiRequest {
29    /// `GET`, `POST`, ...
30    pub method: String,
31    /// The path and its query.
32    pub path: String,
33    /// The body, JSON; empty for none.
34    pub body: Vec<u8>,
35    /// Its `Idempotency-Key`, if any.
36    pub idempotency_key: Option<String>,
37    /// Who makes it: `task:<dag>/<run>/<task>` or `trigger:<dag>`, recorded as the user.
38    pub caller: String,
39}
40
41/// What the router answered.
42#[derive(Debug, Clone, PartialEq, Eq)]
43pub struct TaskApiResponse {
44    /// The HTTP status.
45    pub status: u16,
46    /// The body, JSON.
47    pub body: Vec<u8>,
48}
49
50/// The API, as the master calls it for tasks: the `schedr` binary gives it the REST router.
51pub trait TaskApi: Debug + Send + Sync {
52    /// Runs `request` through the API.
53    fn call(
54        &self,
55        request: TaskApiRequest,
56    ) -> Pin<Box<dyn Future<Output = TaskApiResponse> + Send + '_>>;
57}
58
59/// Whether a task may call `method` on `path` (its query aside).
60#[must_use]
61pub fn allowed(method: &str, path: &str) -> bool {
62    let bare = path.split_once('?').map_or(path, |(bare, _)| bare);
63    TASK_ROUTES
64        .iter()
65        .any(|(m, p)| m.eq_ignore_ascii_case(method) && *p == bare)
66}
67
68/// A call checked and ready to run, away from the core's lock (a request may take a while).
69#[derive(Debug)]
70pub struct ApiJob {
71    api: std::sync::Arc<dyn TaskApi>,
72    request: TaskApiRequest,
73    worker_id: String,
74    request_id: u64,
75}
76
77impl ApiJob {
78    /// Runs the request: the answer for the worker.
79    pub async fn run(self) -> Outgoing {
80        let response = self.api.call(self.request).await;
81        answer(
82            &self.worker_id,
83            self.request_id,
84            response.status,
85            response.body,
86        )
87    }
88}
89
90/// What to do with a task's call: answered already (refused), or to run.
91#[derive(Debug)]
92pub enum ApiCallPlan {
93    /// Refused: the answer.
94    Answered(Box<Outgoing>),
95    /// To run.
96    Run(ApiJob),
97}
98
99fn answer(worker_id: &str, request_id: u64, status: u16, body: Vec<u8>) -> Outgoing {
100    Outgoing {
101        worker_id: worker_id.to_owned(),
102        message: pb::MasterMessage {
103            message: Some(master_message::Message::ApiAnswer(pb::ApiAnswer {
104                request_id,
105                status: u32::from(status),
106                body_json: body,
107            })),
108            clock: None,
109        },
110    }
111}
112
113/// Why a task's own notification wasn't queued.
114#[derive(Debug)]
115enum Unsent {
116    /// Past `[notifications] max_per_attempt`.
117    OverQuota,
118    /// The database failed.
119    Db(schedr_db::DbError),
120}
121
122impl From<schedr_db::DbError> for Unsent {
123    fn from(error: schedr_db::DbError) -> Self {
124        Self::Db(error)
125    }
126}
127
128/// The body of a task's own notification.
129#[derive(Debug)]
130struct NotifyRequest {
131    channel: String,
132    text: Option<String>,
133    data: serde_json::Value,
134}
135
136impl NotifyRequest {
137    /// `{"channel": "...", "text": "..." | null, "data": ...}`, nothing else.
138    fn read(body: &[u8]) -> Result<Self, String> {
139        let value: serde_json::Value = serde_json::from_slice(body).map_err(|e| e.to_string())?;
140        let serde_json::Value::Object(mut map) = value else {
141            return Err("it isn't an object".to_owned());
142        };
143        if let Some(key) = map
144            .keys()
145            .find(|k| !matches!(k.as_str(), "channel" | "text" | "data"))
146        {
147            return Err(format!("unknown field `{key}`"));
148        }
149        let Some(serde_json::Value::String(channel)) = map.remove("channel") else {
150            return Err("`channel` is a channel's name".to_owned());
151        };
152        let text = match map.remove("text") {
153            None | Some(serde_json::Value::Null) => None,
154            Some(serde_json::Value::String(text)) => Some(text),
155            Some(_) => return Err("`text` is a string".to_owned()),
156        };
157        let data = map.remove("data").unwrap_or(serde_json::Value::Null);
158        Ok(Self {
159            channel,
160            text,
161            data,
162        })
163    }
164}
165
166fn refusal(why: &str) -> Vec<u8> {
167    serde_json::to_vec(&serde_json::json!({ "error": why })).unwrap_or_default()
168}
169
170impl MasterCore {
171    /// A task's request through its worker, run here (the core's callers that hold no lock
172    /// across it; the hub runs [`Self::plan_api_call`]'s job outside its lock).
173    pub(crate) async fn api_call(
174        &mut self,
175        worker_id: &str,
176        call: pb::ApiCall,
177        now: jiff::Timestamp,
178    ) -> Result<Vec<Outgoing>, CoreError> {
179        Ok(vec![
180            match self.plan_api_call(worker_id, call, now).await? {
181                ApiCallPlan::Answered(answer) => *answer,
182                ApiCallPlan::Run(job) => job.run().await,
183            },
184        ])
185    }
186
187    /// A task's request through its worker: to run as the task, if the worker holds that
188    /// attempt (or trigger) open and the route is on the list; refused otherwise.
189    ///
190    /// # Errors
191    ///
192    /// A database failure.
193    pub async fn plan_api_call(
194        &mut self,
195        worker_id: &str,
196        call: pb::ApiCall,
197        now: jiff::Timestamp,
198    ) -> Result<ApiCallPlan, CoreError> {
199        let refuse = |status: u16, why: &str| {
200            Ok(ApiCallPlan::Answered(Box::new(answer(
201                worker_id,
202                call.request_id,
203                status,
204                refusal(why),
205            ))))
206        };
207        if !allowed(&call.method, &call.path) {
208            return refuse(
209                403,
210                &format!(
211                    "`{} {}` isn't open to tasks: they may call {}",
212                    call.method,
213                    call.path,
214                    TASK_ROUTES
215                        .iter()
216                        .map(|(m, p)| format!("`{m} {p}`"))
217                        .collect::<Vec<_>>()
218                        .join(", ")
219                ),
220            );
221        }
222        if call
223            .path
224            .split_once('?')
225            .map_or(call.path.as_str(), |(bare, _)| bare)
226            == NOTIFICATIONS
227        {
228            let (status, body) = self.notify_call(worker_id, &call, now).await?;
229            return Ok(ApiCallPlan::Answered(Box::new(answer(
230                worker_id,
231                call.request_id,
232                status,
233                body,
234            ))));
235        }
236        let Some(caller) = self.api_caller(worker_id, &call).await? else {
237            return refuse(403, "no open attempt or trigger of this worker makes it");
238        };
239        let Some(api) = self.task_api.clone() else {
240            return refuse(503, "this master serves no API to tasks");
241        };
242        let request = TaskApiRequest {
243            method: call.method.to_ascii_uppercase(),
244            path: call.path.clone(),
245            body: call.body_json.clone(),
246            idempotency_key: Some(call.idempotency_key.clone()).filter(|key| !key.is_empty()),
247            caller,
248        };
249        Ok(ApiCallPlan::Run(ApiJob {
250            api,
251            request,
252            worker_id: worker_id.to_owned(),
253            request_id: call.request_id,
254        }))
255    }
256
257    /// A task's own notification (decision 421): to a channel of its DAG, or a server one,
258    /// queued with its count, at most `[notifications] max_per_attempt` an attempt.
259    async fn notify_call(
260        &self,
261        worker_id: &str,
262        call: &pb::ApiCall,
263        now: jiff::Timestamp,
264    ) -> Result<(u16, Vec<u8>), CoreError> {
265        if !call.trigger_dag_id.is_empty() {
266            return Ok((
267                403,
268                refusal("a trigger can't send notifications; a task can"),
269            ));
270        }
271        let attempt = self.db.attempt(&call.attempt_id).await?;
272        let Some(attempt) = attempt.filter(|a| a.worker_id == worker_id && a.status.is_none())
273        else {
274            return Ok((403, refusal("no open attempt of this worker makes it")));
275        };
276        let request = match NotifyRequest::read(&call.body_json) {
277            Ok(request) => request,
278            Err(error) => {
279                return Ok((
280                    400,
281                    refusal(&format!(
282                        "the body is {{\"channel\": ..., \"text\": ..., \"data\": ...}}: {error}"
283                    )),
284                ));
285            }
286        };
287        let Some(run) = self.db.run_tasks(&attempt.run_id).await? else {
288            return Ok((404, refusal("the attempt's run is gone")));
289        };
290        let task = if attempt.map_index >= 0 {
291            format!("{}[{}]", attempt.task_id, attempt.map_index)
292        } else {
293            attempt.task_id.to_string()
294        };
295        let mut event = crate::notifications::Event::new(&run.dag, now);
296        event.run_id = Some(&attempt.run_id);
297        event.task = Some(&task);
298        event.attempt = Some(attempt.try_number);
299        event.state = Some("running");
300        event.text = request.text;
301        event.data = request.data;
302        event.planned_for = self
303            .db
304            .run_record(&attempt.run_id)
305            .await?
306            .map(|r| r.planned_for);
307        let queued = match self.notifications.message(&event, &request.channel) {
308            Ok(queued) => queued,
309            Err(why) => return Ok((400, refusal(&why))),
310        };
311        let max = self.notifications.max_per_attempt;
312        let db = &self.db;
313        let key = call.idempotency_key.as_str();
314        // Over the quota rolls the whole write back, the call's key with it: sent again, it is
315        // refused again (not taken for one that was queued).
316        let sent = Box::pin(db.atomically(async {
317            // Sent again (its agent reconnected before the answer): queued already.
318            if !key.is_empty() && !db.first_notification_request(&attempt.id, key).await? {
319                return Ok(());
320            }
321            if !db.count_attempt_notification(&attempt.id, max).await? {
322                return Err(Unsent::OverQuota);
323            }
324            db.queue_notifications(std::slice::from_ref(&queued), now)
325                .await?;
326            Ok(())
327        }))
328        .await;
329        let counted = match sent {
330            Ok(()) => true,
331            Err(Unsent::OverQuota) => false,
332            Err(Unsent::Db(error)) => return Err(error.into()),
333        };
334        Ok(if counted {
335            (
336                202,
337                serde_json::to_vec(&serde_json::json!({"queued": true})).unwrap_or_default(),
338            )
339        } else {
340            (
341                429,
342                refusal(&format!(
343                    "this attempt has sent {max} notifications, the most it may \
344                     ([notifications] max_per_attempt)"
345                )),
346            )
347        })
348    }
349
350    /// Who makes `call`: the attempt it names, open on this worker, or its trigger instance.
351    async fn api_caller(
352        &self,
353        worker_id: &str,
354        call: &pb::ApiCall,
355    ) -> Result<Option<String>, CoreError> {
356        if !call.trigger_dag_id.is_empty() {
357            let record = self.db.trigger(&call.trigger_dag_id).await?;
358            let holds = record.is_some_and(|record| {
359                record.instance_id.as_deref() == Some(call.attempt_id.as_str())
360                    && record.worker_id.as_deref() == Some(worker_id)
361            });
362            return Ok(holds.then(|| format!("trigger:{}", call.trigger_dag_id)));
363        }
364        let Some(attempt) = self.db.attempt(&call.attempt_id).await? else {
365            return Ok(None);
366        };
367        if attempt.worker_id != worker_id || attempt.status.is_some() {
368            return Ok(None);
369        }
370        let dag = self
371            .db
372            .run_record(&attempt.run_id)
373            .await?
374            .map(|run| run.dag_id.to_string())
375            .unwrap_or_default();
376        let instance = if attempt.map_index < 0 {
377            String::new()
378        } else {
379            format!("[{}]", attempt.map_index)
380        };
381        Ok(Some(format!(
382            "task:{dag}/{}/{}{instance}",
383            attempt.run_id, attempt.task_id
384        )))
385    }
386}
387
388#[cfg(test)]
389mod tests {
390    use super::allowed;
391
392    #[test]
393    fn only_the_listed_routes_are_open_to_tasks() {
394        assert!(allowed("POST", "/api/v1/events"));
395        assert!(allowed("get", "/api/v1/events?name=paid&limit=5"));
396        assert!(!allowed("DELETE", "/api/v1/events"));
397        assert!(!allowed("POST", "/api/v1/dags/sync/pause"));
398        assert!(!allowed("GET", "/api/v1/events/../dags"));
399        assert!(!allowed("GET", "/api/v1/events/"));
400        assert!(allowed("POST", "/api/v1/notifications"));
401        assert!(!allowed("GET", "/api/v1/notifications"));
402    }
403}