Skip to main content

schedr_bin/
task_api.rs

1//! The REST API as the master runs it for tasks (M4.11h, the user's B2): the API's own router,
2//! in this process, each request marked proven and named after the task that makes it.
3
4use std::future::Future;
5use std::pin::Pin;
6
7use axum::body::Body;
8use schedr_api::auth::{MAX_NAME, ProvenUi, USER_HEADER};
9use schedr_api::{ApiState, router};
10use schedr_db::Database;
11use schedr_master::core::task_api::{TaskApi, TaskApiRequest, TaskApiResponse};
12use sha2::Digest as _;
13use tower::ServiceExt as _;
14
15/// The router a master calls for its tasks.
16#[derive(Debug, Clone)]
17pub struct RouterTaskApi {
18    router: axum::Router,
19    /// The largest answer read back, larger refused: it goes to the worker in one message.
20    max_answer: usize,
21}
22
23impl RouterTaskApi {
24    /// The API over `db`, taking events of up to `max_event_size` bytes (`[events] max_size`)
25    /// within `limits`, giving answers of up to `max_answer` bytes.
26    #[must_use]
27    pub fn new(
28        db: Database,
29        (max_event_size, limits): (usize, schedr_api::state::ApiLimits),
30        max_answer: usize,
31    ) -> Self {
32        let state = ApiState::new(db, None)
33            .with_max_event_size(max_event_size)
34            .with_limits(limits, schedr_api::series::cache::CacheLimits::default());
35        Self {
36            router: router(state),
37            max_answer,
38        }
39    }
40}
41
42/// The name a task's requests are made as: its caller, or, past what the API takes as a name
43/// (a long DAG and task ID), its start and a hash of the whole, so it is still its own and not
44/// `anonymous` (Codex's review of M4.11h).
45fn user_name(caller: &str) -> String {
46    if caller.len() <= MAX_NAME {
47        return caller.to_owned();
48    }
49    let digest = sha2::Sha256::digest(caller.as_bytes());
50    let hash = digest[..12]
51        .iter()
52        .fold(String::new(), |hash, byte| hash + &format!("{byte:02x}"));
53    // IDs are ASCII: any byte is a boundary; room for `~` and the hash.
54    let start = caller.get(..MAX_NAME - 1 - hash.len()).unwrap_or_default();
55    format!("{start}~{hash}")
56}
57
58fn failed(status: u16, why: &str) -> TaskApiResponse {
59    TaskApiResponse {
60        status,
61        body: serde_json::to_vec(&serde_json::json!({ "error": why })).unwrap_or_default(),
62    }
63}
64
65impl TaskApi for RouterTaskApi {
66    fn call(
67        &self,
68        request: TaskApiRequest,
69    ) -> Pin<Box<dyn Future<Output = TaskApiResponse> + Send + '_>> {
70        Box::pin(async move {
71            let mut builder = axum::http::Request::builder()
72                .method(request.method.as_str())
73                .uri(request.path.as_str())
74                .header(USER_HEADER, user_name(&request.caller));
75            if !request.body.is_empty() {
76                builder = builder.header("content-type", "application/json");
77            }
78            if let Some(key) = &request.idempotency_key {
79                builder = builder.header("idempotency-key", key.as_str());
80            }
81            let mut http = match builder.body(Body::from(request.body)) {
82                Ok(http) => http,
83                Err(error) => return failed(400, &format!("the request doesn't read: {error}")),
84            };
85            // As `schedr ui`'s port marks its requests: the user is the one named.
86            http.extensions_mut().insert(ProvenUi);
87            let response = match self.router.clone().oneshot(http).await {
88                Ok(response) => response,
89                Err(never) => match never {},
90            };
91            let status = response.status().as_u16();
92            match axum::body::to_bytes(response.into_body(), self.max_answer).await {
93                Ok(body) => TaskApiResponse {
94                    status,
95                    body: body.to_vec(),
96                },
97                Err(_) => failed(
98                    502,
99                    &format!(
100                        "the API's answer is over the {} bytes a worker's message takes ([grpc] \
101                         max_message_size): ask for less (`limit=`)",
102                        self.max_answer
103                    ),
104                ),
105            }
106        })
107    }
108}
109
110#[cfg(test)]
111mod tests {
112    use super::*;
113
114    #[test]
115    fn a_long_caller_keeps_a_name_of_its_own_within_the_limit() {
116        let long = |task: &str| format!("task:{}/r1/{task}", "d".repeat(250));
117        let (a, b) = (user_name(&long("a")), user_name(&long("b")));
118        assert_eq!(a.len(), MAX_NAME);
119        assert_ne!(a, b);
120        assert_eq!(user_name("task:d/r1/t"), "task:d/r1/t");
121    }
122}