Skip to main content

kernable/
context.rs

1//! The request context, times and IDs.
2
3use std::{collections::BTreeMap, fmt};
4
5use kernable_core::proto;
6
7/// Who sends a request and in which context: signed with the command and stored with every
8/// event it causes; signed with file and cache requests too, for middlewares to check. `attributes` are business data only, never security decisions.
9///
10/// Set a default for a connection with [`crate::Options::context`], or one per request with
11/// [`crate::Submit::context`], [`crate::Query::context`], [`crate::Files::context`] and
12/// [`crate::Cache::context`]. Inside a listener's handler,
13/// submit follow-up commands with `ctx.follow()` ([`crate::ListenerContext::follow`]). All
14/// fields default to empty; set the ones you need:
15/// `RequestContext { sender_identity: "customer-7".into(), expected_version: Some(3), ..Default::default() }`.
16#[derive(Clone, Debug, Default, PartialEq, Eq)]
17pub struct RequestContext {
18    /// The tenant the sender belongs to.
19    pub sender_tenant: String,
20    /// Who sends the request, e.g. a user or service ID; middlewares check permissions on it.
21    pub sender_identity: String,
22    pub sender_account: String,
23    pub sender_session: String,
24    /// Authorize as this identity of the target tenant; the sender stays the real principal.
25    pub on_behalf_of: String,
26    /// Reject the command (`version_mismatch`) unless the aggregate is at this version.
27    pub expected_version: Option<u64>,
28    /// Shared by everything one original request causes; defaults to the command ID.
29    pub correlation_id: String,
30    /// The command that caused this one.
31    pub causation_id: String,
32    pub trace_id: String,
33    /// Privileged: only keys granted `privileged` for it may set it.
34    pub bypass_authorization: bool,
35    pub attributes: BTreeMap<String, String>,
36}
37
38impl RequestContext {
39    /// A context for a command caused by command `command_id` with this context: same sender
40    /// and correlation, without an expected version or privileges.
41    pub(crate) fn follow(&self, command_id: &str) -> RequestContext {
42        RequestContext {
43            expected_version: None,
44            bypass_authorization: false,
45            correlation_id: if self.correlation_id.is_empty() {
46                command_id.to_owned()
47            } else {
48                self.correlation_id.clone()
49            },
50            causation_id: command_id.to_owned(),
51            ..self.clone()
52        }
53    }
54
55    pub(crate) fn to_wire(&self) -> proto::RequestContext {
56        proto::RequestContext {
57            sender_tenant: self.sender_tenant.clone(),
58            sender_identity: self.sender_identity.clone(),
59            sender_account: self.sender_account.clone(),
60            sender_session: self.sender_session.clone(),
61            on_behalf_of: self.on_behalf_of.clone(),
62            expected_version: self.expected_version,
63            correlation_id: self.correlation_id.clone(),
64            causation_id: self.causation_id.clone(),
65            trace_id: self.trace_id.clone(),
66            bypass_authorization: self.bypass_authorization,
67            attributes: self
68                .attributes
69                .iter()
70                .map(|(key, value)| proto::Attribute {
71                    key: key.clone(),
72                    value: value.clone(),
73                })
74                .collect(),
75        }
76    }
77
78    pub(crate) fn from_wire(c: Option<&proto::RequestContext>) -> RequestContext {
79        let Some(c) = c else {
80            return RequestContext::default();
81        };
82        RequestContext {
83            sender_tenant: c.sender_tenant.clone(),
84            sender_identity: c.sender_identity.clone(),
85            sender_account: c.sender_account.clone(),
86            sender_session: c.sender_session.clone(),
87            on_behalf_of: c.on_behalf_of.clone(),
88            expected_version: c.expected_version,
89            correlation_id: c.correlation_id.clone(),
90            causation_id: c.causation_id.clone(),
91            trace_id: c.trace_id.clone(),
92            bypass_authorization: c.bypass_authorization,
93            attributes: c
94                .attributes
95                .iter()
96                .map(|a| (a.key.clone(), a.value.clone()))
97                .collect(),
98        }
99    }
100}
101
102/// A point in time in milliseconds since the epoch, shown as RFC 3339 in UTC with
103/// milliseconds (`2026-10-27T09:00:00.000Z`), like JavaScript's `toISOString()`: format it
104/// with `to_string()`. `Timestamp(ms)` makes one from milliseconds; the default is the epoch.
105#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
106pub struct Timestamp(pub i64);
107
108impl Timestamp {
109    /// The current time. In a command handler, use `ctx.now()` instead
110    /// ([`crate::CommandContext::now`]), which is the same every time the command runs.
111    pub fn now() -> Timestamp {
112        Timestamp(now_ms())
113    }
114
115    /// Milliseconds since the Unix epoch.
116    pub fn millis(self) -> i64 {
117        self.0
118    }
119}
120
121impl fmt::Display for Timestamp {
122    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
123        let (days, ms) = (self.0.div_euclid(86_400_000), self.0.rem_euclid(86_400_000));
124        // Civil date from days since 1970-01-01 (Howard Hinnant's algorithm).
125        let z = days + 719_468;
126        let era = z.div_euclid(146_097);
127        let doe = z.rem_euclid(146_097);
128        let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
129        let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
130        let mp = (5 * doy + 2) / 153;
131        let day = doy - (153 * mp + 2) / 5 + 1;
132        let month = if mp < 10 { mp + 3 } else { mp - 9 };
133        let year = yoe + era * 400 + i64::from(month <= 2);
134        write!(
135            f,
136            "{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}.{:03}Z",
137            ms / 3_600_000,
138            ms / 60_000 % 60,
139            ms / 1000 % 60,
140            ms % 1000
141        )
142    }
143}
144
145pub(crate) fn now_ms() -> i64 {
146    std::time::SystemTime::now()
147        .duration_since(std::time::UNIX_EPOCH)
148        .map_or(0, |d| d.as_millis() as i64)
149}
150
151/// A request's `issued_at`: now, but later than every one this process issued before. Two calls
152/// in the same millisecond would otherwise carry the same signature, and the kernel refuses the
153/// second as a replay.
154pub(crate) fn issued_now() -> i64 {
155    use std::sync::atomic::{AtomicI64, Ordering::Relaxed};
156    static LAST: AtomicI64 = AtomicI64::new(0);
157    let now = now_ms();
158    let mut last = LAST.load(Relaxed);
159    loop {
160        let next = now.max(last + 1);
161        match LAST.compare_exchange_weak(last, next, Relaxed, Relaxed) {
162            Ok(_) => return next,
163            Err(seen) => last = seen,
164        }
165    }
166}
167
168/// A random UUID (version 4).
169pub(crate) fn random_id() -> String {
170    let mut b = [0u8; 16];
171    getrandom::fill(&mut b).expect("OS randomness unavailable");
172    b[6] = (b[6] & 0x0f) | 0x40;
173    b[8] = (b[8] & 0x3f) | 0x80;
174    let h = hex::encode(b);
175    format!(
176        "{}-{}-{}-{}-{}",
177        &h[..8],
178        &h[8..12],
179        &h[12..16],
180        &h[16..20],
181        &h[20..]
182    )
183}
184
185#[cfg(test)]
186mod tests {
187    use super::*;
188
189    #[test]
190    fn timestamps_read_like_iso_strings() {
191        assert_eq!(Timestamp(0).to_string(), "1970-01-01T00:00:00.000Z");
192        assert_eq!(
193            Timestamp(1_793_091_600_123).to_string(),
194            "2026-10-27T09:00:00.123Z"
195        );
196        assert_eq!(
197            Timestamp(951_782_400_000).to_string(),
198            "2000-02-29T00:00:00.000Z"
199        );
200    }
201
202    #[test]
203    fn every_day_from_1960_to_2400_is_written_as_the_calendar_has_it() {
204        let leap = |y: i64| (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
205        let length = |y: i64, m: i64| match m {
206            2 if leap(y) => 29,
207            2 => 28,
208            4 | 6 | 9 | 11 => 30,
209            _ => 31,
210        };
211        let (mut y, mut m, mut d) = (1960, 1, 1);
212        let first = -3653; // 1960-01-01, days before 1970-01-01
213        for day in first..first + 160_707 {
214            let ms = day * 86_400_000 + 45_296_789; // 12:34:56.789
215            let expected = format!("{y:04}-{m:02}-{d:02}T12:34:56.789Z");
216            assert_eq!(Timestamp(ms).to_string(), expected);
217            d += 1;
218            if d > length(y, m) {
219                (d, m) = (1, m + 1);
220                if m > 12 {
221                    (m, y) = (1, y + 1);
222                }
223            }
224        }
225        assert_eq!((y, m, d), (2400, 1, 1));
226    }
227
228    #[test]
229    fn ids_are_version_4_uuids() {
230        for _ in 0..1000 {
231            let id = random_id();
232            assert_eq!(id.len(), 36);
233            assert_eq!(&id[14..15], "4", "{id}");
234            assert!("89ab".contains(&id[19..20]), "{id}");
235        }
236    }
237
238    #[test]
239    fn a_follow_up_keeps_sender_and_correlation_but_no_expected_version_or_privileges() {
240        let request = RequestContext {
241            sender_identity: "svc-1".into(),
242            expected_version: Some(3),
243            bypass_authorization: true,
244            trace_id: "tr-1".into(),
245            ..Default::default()
246        };
247        let follow = request.follow("cmd-1");
248        assert_eq!(
249            follow,
250            RequestContext {
251                sender_identity: "svc-1".into(),
252                trace_id: "tr-1".into(),
253                correlation_id: "cmd-1".into(),
254                causation_id: "cmd-1".into(),
255                ..Default::default()
256            }
257        );
258        // An existing correlation is kept.
259        assert_eq!(follow.follow("cmd-2").correlation_id, "cmd-1");
260    }
261}