1use std::{collections::BTreeMap, fmt};
4
5use kernable_core::proto;
6
7#[derive(Clone, Debug, Default, PartialEq, Eq)]
17pub struct RequestContext {
18 pub sender_tenant: String,
20 pub sender_identity: String,
22 pub sender_account: String,
23 pub sender_session: String,
24 pub on_behalf_of: String,
26 pub expected_version: Option<u64>,
28 pub correlation_id: String,
30 pub causation_id: String,
32 pub trace_id: String,
33 pub bypass_authorization: bool,
35 pub attributes: BTreeMap<String, String>,
36}
37
38impl RequestContext {
39 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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
106pub struct Timestamp(pub i64);
107
108impl Timestamp {
109 pub fn now() -> Timestamp {
112 Timestamp(now_ms())
113 }
114
115 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 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
151pub(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
168pub(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; for day in first..first + 160_707 {
214 let ms = day * 86_400_000 + 45_296_789; 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 assert_eq!(follow.follow("cmd-2").correlation_id, "cmd-1");
260 }
261}