Skip to main content

core_api/
timeouts.rs

1//! Static operation budgets shared by execution hosts and callers.
2//! Wait profiles only bound receiving a reply; their grace must never extend execution.
3use std::time::Duration;
4
5include!("timeouts.generated.rs");
6
7pub fn script_operation(target: &str, payload: &str) -> Option<Operation> {
8    let forwarded = FORWARD_PREFIXES
9        .iter()
10        .find_map(|prefix| target.strip_prefix(prefix));
11    let target = forwarded.unwrap_or(target);
12    if STORED_SCRIPT_SAVE.contains(&target) {
13        return Some(Operation::ScriptSave);
14    }
15    let saving = SOURCE_SCRIPT_SAVE.contains(&target);
16    if !saving && !SOURCE_SCRIPT_VALIDATION.contains(&target) {
17        return None;
18    }
19    let root: serde_json::Value = serde_json::from_str(payload).ok()?;
20    let input = if forwarded.is_some() {
21        root.get("call")?.get("input")?
22    } else if target.starts_with("/app/") {
23        root.get("input")?
24    } else {
25        &root
26    };
27    let scripts = input.get("script")?.get("scripts")?.as_object()?;
28    (!scripts.is_empty()).then_some(if saving {
29        Operation::ScriptSave
30    } else {
31        Operation::ScriptValidation
32    })
33}
34
35pub fn ordinary_operation(target: &str) -> Operation {
36    ORDINARY_OVERRIDES
37        .iter()
38        .find(|(value, _)| *value == target)
39        .map_or(Operation::CoreRequest, |(_, operation)| *operation)
40}
41
42pub fn request_operation(target: &str, payload: &str) -> Operation {
43    script_operation(target, payload).unwrap_or_else(|| ordinary_operation(target))
44}
45
46pub fn reply_timeout(operation: Operation, profile: WaitProfile) -> Duration {
47    operation.timeout() + profile.grace(operation)
48}
49
50#[cfg(test)]
51mod tests {
52    use super::*;
53
54    #[test]
55    fn shared_selection_and_wait_fixtures() {
56        let cases: serde_json::Value = serde_json::from_str(include_str!(
57            "../fixtures/operation-timeouts.conformance.json"
58        ))
59        .unwrap();
60        for case in cases.as_array().unwrap() {
61            let operation = request_operation(
62                case["target"].as_str().unwrap(),
63                &case["payload"].to_string(),
64            );
65            assert_eq!(
66                operation.id(),
67                case["operation"].as_str().unwrap(),
68                "{case}"
69            );
70            assert_eq!(
71                operation.timeout().as_millis(),
72                case["totalMs"].as_u64().unwrap() as u128
73            );
74            if let Some(wait) = case["lionWaitMs"].as_u64() {
75                assert_eq!(
76                    reply_timeout(operation, WaitProfile::LionForward).as_millis(),
77                    wait as u128
78                );
79            }
80        }
81    }
82}