Skip to main content

core_api/
execution_budget.rs

1//! Transport metadata, independent of business inputs and Facade authorization control.
2//! Each hop sends remaining milliseconds and anchors them to its own monotonic clock.
3//! Zero means expired; absence preserves the receiver's existing local policy.
4use serde::{Deserialize, Serialize};
5use std::time::Duration;
6
7#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
8#[serde(try_from = "WireBudget", into = "WireBudget")]
9pub struct ExecutionBudget(u32);
10
11#[derive(Serialize, Deserialize)]
12#[serde(rename_all = "camelCase", deny_unknown_fields)]
13struct WireBudget {
14    remaining_ms: u64,
15}
16
17impl TryFrom<WireBudget> for ExecutionBudget {
18    type Error = &'static str;
19    fn try_from(value: WireBudget) -> Result<Self, Self::Error> {
20        if value.remaining_ms > i32::MAX as u64 {
21            return Err("executionBudget.remainingMs exceeds its limit");
22        }
23        Ok(Self(value.remaining_ms as u32))
24    }
25}
26
27impl From<ExecutionBudget> for WireBudget {
28    fn from(value: ExecutionBudget) -> Self {
29        Self {
30            remaining_ms: value.0 as u64,
31        }
32    }
33}
34
35impl ExecutionBudget {
36    /// Round down, never adding time at a transport boundary.
37    pub fn from_remaining(remaining: Duration) -> Self {
38        Self(remaining.as_millis().min(i32::MAX as u128) as u32)
39    }
40
41    pub fn remaining(self) -> Duration {
42        Duration::from_millis(self.0 as u64)
43    }
44}
45
46/// Adds an optional top-level field without changing the source API of existing envelopes.
47/// The wrapped object must not itself define `executionBudget`.
48#[derive(Debug, Serialize, Deserialize)]
49#[serde(rename_all = "camelCase")]
50pub struct Budgeted<T> {
51    #[serde(flatten)]
52    pub message: T,
53    #[serde(default, skip_serializing_if = "Option::is_none")]
54    pub execution_budget: Option<ExecutionBudget>,
55}
56
57#[cfg(test)]
58mod tests {
59    use super::*;
60
61    #[test]
62    fn optional_budget_round_trips_without_changing_the_business_envelope() {
63        #[derive(Debug, Serialize, Deserialize, PartialEq)]
64        struct Input {
65            target: String,
66        }
67        let wire = r#"{"target":"/example","executionBudget":{"remainingMs":0}}"#;
68        let decoded: Budgeted<Input> = serde_json::from_str(wire).unwrap();
69        assert_eq!(
70            decoded.execution_budget.unwrap().remaining(),
71            Duration::ZERO
72        );
73        assert_eq!(
74            serde_json::to_value(&decoded).unwrap(),
75            serde_json::from_str::<serde_json::Value>(wire).unwrap()
76        );
77        let legacy: Budgeted<Input> = serde_json::from_str(r#"{"target":"/example"}"#).unwrap();
78        assert!(legacy.execution_budget.is_none());
79        assert!(serde_json::to_value(legacy)
80            .unwrap()
81            .get("executionBudget")
82            .is_none());
83    }
84
85    #[test]
86    fn invalid_budgets_fail_closed_and_rounding_never_extends_time() {
87        for value in [
88            r#"{}"#,
89            r#"{"remainingMs":-1}"#,
90            r#"{"remainingMs":1.5}"#,
91            r#"{"remainingMs":2147483648}"#,
92            r#"{"remainingMs":null}"#,
93            r#"{"remainingMs":5,"extra":1}"#,
94        ] {
95            assert!(
96                serde_json::from_str::<ExecutionBudget>(value).is_err(),
97                "{value}"
98            );
99        }
100        assert_eq!(
101            ExecutionBudget::from_remaining(Duration::from_micros(1999)).remaining(),
102            Duration::from_millis(1)
103        );
104    }
105}