1use std::sync::Arc;
6use std::time::Duration;
7
8use schedr_proto::pb;
9use tokio::sync::oneshot;
10
11pub const API_CALL_LIMIT: Duration = Duration::from_mins(1);
13
14pub type ApiSend = Arc<dyn Fn(pb::ApiCall) -> oneshot::Receiver<pb::ApiAnswer> + Send + Sync>;
16
17#[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#[derive(Debug, Clone, PartialEq, Eq)]
42pub struct ApiRequest {
43 pub method: String,
45 pub path: String,
47 pub body: Option<serde_json::Value>,
49 pub idempotency_key: Option<String>,
51 pub masked: bool,
53}
54
55impl ApiRequest {
56 #[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 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 #[must_use]
82 pub fn note(&self) -> Option<String> {
83 self.masked.then(|| MASKED_REQUEST.to_owned())
84 }
85}
86
87impl ApiCaller {
88 #[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 #[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 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 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
157pub 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
171pub 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
176pub 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
180fn 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
190fn 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 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 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}