1use std::path::{Path, PathBuf};
15
16use lean_ctx_time::{Duration, OffsetDateTime, UtcDateTime};
17use serde::{Deserialize, Serialize};
18use serde_json::Value;
19
20use super::CloudError;
21use super::state::write_private;
22
23pub const CHANNEL_KNOWLEDGE: &str = "knowledge";
24pub const CHANNEL_METRICS: &str = "metrics";
25pub const CHANNEL_RECEIPTS: &str = "receipts";
26pub const CHANNEL_TASKS: &str = "tasks";
28pub const CHANNEL_TASK_EVIDENCE: &str = "task_evidence";
31const CHANNELS: [&str; 5] = [
32 CHANNEL_KNOWLEDGE,
33 CHANNEL_METRICS,
34 CHANNEL_RECEIPTS,
35 CHANNEL_TASKS,
36 CHANNEL_TASK_EVIDENCE,
37];
38
39const MAX_ITEMS: usize = 10_000;
40const MAX_BYTES: u64 = 50 * 1024 * 1024;
41pub const MAX_FAILED: usize = 500;
43pub const MAX_DAMAGED: usize = 20;
45const BACKOFF_START_SECONDS: i64 = 30;
46const BACKOFF_MAX_SECONDS: i64 = 3600;
47const RETRY_AFTER_MAX_SECONDS: i64 = 7 * 24 * 3600;
50
51#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
52pub struct OutboxItem {
53 pub id: String,
54 pub channel: String,
55 pub created_at: String,
56 #[serde(default)]
57 pub attempts: u32,
58 #[serde(default, skip_serializing_if = "Option::is_none")]
59 pub next_attempt_at: Option<String>,
60 #[serde(default, skip_serializing_if = "Option::is_none")]
61 pub last_error: Option<String>,
62 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
65 pub policy_hold: bool,
66 pub payload: Value,
67}
68
69impl OutboxItem {
70 pub fn due(&self, now: UtcDateTime) -> bool {
72 self.next_attempt_at
73 .as_deref()
74 .and_then(|t| OffsetDateTime::parse_from_rfc3339(t).ok())
75 .is_none_or(|at| at.to_utc() <= now)
76 }
77}
78
79#[derive(Debug, Clone, Default, PartialEq, Eq)]
81pub struct OutboxDepth {
82 pub pending: usize,
83 pub failed: usize,
84}
85
86pub struct Outbox {
87 root: PathBuf,
88}
89
90fn valid_channel(channel: &str) -> bool {
91 matches!(
92 channel,
93 CHANNEL_KNOWLEDGE
94 | CHANNEL_METRICS
95 | CHANNEL_RECEIPTS
96 | CHANNEL_TASKS
97 | CHANNEL_TASK_EVIDENCE
98 )
99}
100
101fn stamp(t: UtcDateTime) -> String {
102 t.to_rfc3339_opts(lean_ctx_time::SecondsFormat::Millis, true)
103}
104
105impl Outbox {
106 pub fn at(data_dir: &Path) -> Self {
107 Self {
108 root: data_dir.join("outbox"),
109 }
110 }
111
112 fn dir(&self, channel: &str) -> PathBuf {
113 self.root.join(channel)
114 }
115
116 fn failed_dir(&self, channel: &str) -> PathBuf {
117 self.root.join("failed").join(channel)
118 }
119
120 pub fn enqueue(
122 &self,
123 channel: &str,
124 payload: Value,
125 now: UtcDateTime,
126 ) -> Result<String, CloudError> {
127 if !valid_channel(channel) {
128 return Err(CloudError::Local(format!(
129 "unknown outbox channel {channel:?}"
130 )));
131 }
132 let mut random = [0u8; 8];
133 getrandom::fill(&mut random).map_err(|e| CloudError::Local(format!("random: {e}")))?;
134 let id = format!(
135 "{:013}{}",
136 now.timestamp_millis().max(0),
137 hex::encode(random)
138 );
139 let item = OutboxItem {
140 id: id.clone(),
141 channel: channel.to_string(),
142 created_at: stamp(now),
143 attempts: 0,
144 next_attempt_at: None,
145 last_error: None,
146 policy_hold: false,
147 payload,
148 };
149 let bytes = serde_json::to_vec(&item).map_err(|e| CloudError::Local(e.to_string()))?;
150 self.make_room(channel, bytes.len() as u64)?;
151 write_private(&self.dir(channel), &format!("{id}.json"), &bytes)?;
152 Ok(id)
153 }
154
155 fn files(dir: &Path) -> Vec<(PathBuf, u64)> {
156 let mut files: Vec<(PathBuf, u64)> = std::fs::read_dir(dir)
157 .into_iter()
158 .flatten()
159 .filter_map(Result::ok)
160 .filter(|e| e.file_name().to_string_lossy().ends_with(".json"))
161 .map(|e| (e.path(), e.metadata().map_or(0, |m| m.len())))
162 .collect();
163 files.sort();
164 files
165 }
166
167 fn make_room(&self, channel: &str, incoming: u64) -> Result<(), CloudError> {
168 let channels = CHANNELS;
169 let mut count: usize = channels
170 .iter()
171 .map(|c| Self::files(&self.dir(c)).len())
172 .sum();
173 let mut bytes: u64 = channels
174 .iter()
175 .flat_map(|c| Self::files(&self.dir(c)))
176 .map(|(_, size)| size)
177 .sum();
178 let mut metrics = Self::files(&self.dir(CHANNEL_METRICS)).into_iter();
179 while count + 1 > MAX_ITEMS || bytes + incoming > MAX_BYTES {
180 let Some((oldest, size)) = metrics.next() else {
181 return Err(CloudError::Local(format!(
182 "the Cloud outbox is full; {channel} is kept back until the Cloud is reachable again"
183 )));
184 };
185 let _ = std::fs::remove_file(oldest);
186 count -= 1;
187 bytes = bytes.saturating_sub(size);
188 }
189 Ok(())
190 }
191
192 pub fn list(&self, channel: &str) -> Vec<OutboxItem> {
194 Self::files(&self.dir(channel))
195 .into_iter()
196 .filter_map(|(path, _)| {
197 let parsed = std::fs::read(&path)
198 .ok()
199 .and_then(|b| serde_json::from_slice::<OutboxItem>(&b).ok());
200 if parsed.is_none() {
201 let _ = std::fs::rename(&path, path.with_extension("damaged"));
202 keep_newest(&self.dir(channel), ".damaged", MAX_DAMAGED);
203 }
204 parsed
205 })
206 .collect()
207 }
208
209 pub fn remove(&self, item: &OutboxItem) -> Result<(), CloudError> {
210 match std::fs::remove_file(self.dir(&item.channel).join(format!("{}.json", item.id))) {
211 Ok(()) => Ok(()),
212 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
213 Err(e) => Err(CloudError::Local(format!("outbox: {e}"))),
214 }
215 }
216
217 pub fn update(&self, item: &OutboxItem) -> Result<(), CloudError> {
219 let bytes = serde_json::to_vec(item).map_err(|e| CloudError::Local(e.to_string()))?;
220 write_private(
221 &self.dir(&item.channel),
222 &format!("{}.json", item.id),
223 &bytes,
224 )
225 }
226
227 pub fn retry_later(
230 &self,
231 item: &mut OutboxItem,
232 error: &str,
233 retry_after: Option<u64>,
234 now: UtcDateTime,
235 ) -> Result<(), CloudError> {
236 item.policy_hold = false;
237 self.wait(item, error, retry_after, now)
238 }
239
240 pub fn hold_for_policy(
243 &self,
244 item: &mut OutboxItem,
245 error: &str,
246 retry_after: Option<u64>,
247 now: UtcDateTime,
248 ) -> Result<(), CloudError> {
249 item.policy_hold = true;
250 self.wait(item, error, retry_after, now)
251 }
252
253 pub fn release_policy_holds(&self) -> usize {
256 let mut released = 0;
257 for channel in CHANNELS {
258 for mut item in self.list(channel).into_iter().filter(|i| i.policy_hold) {
259 item.policy_hold = false;
260 item.next_attempt_at = None;
261 if self.update(&item).is_ok() {
262 released += 1;
263 }
264 }
265 }
266 released
267 }
268
269 fn wait(
270 &self,
271 item: &mut OutboxItem,
272 error: &str,
273 retry_after: Option<u64>,
274 now: UtcDateTime,
275 ) -> Result<(), CloudError> {
276 item.attempts = item.attempts.saturating_add(1);
277 let exponent = item.attempts.saturating_sub(1).min(7);
278 let backoff = (BACKOFF_START_SECONDS << exponent).min(BACKOFF_MAX_SECONDS);
279 let mut jitter = [0u8; 2];
280 let _ = getrandom::fill(&mut jitter);
281 let jitter = i64::from(u16::from_le_bytes(jitter)) % (backoff / 4 + 1);
282 let wait = retry_after
283 .map_or(backoff + jitter, |s| i64::try_from(s).unwrap_or(i64::MAX))
284 .clamp(0, RETRY_AFTER_MAX_SECONDS);
285 item.next_attempt_at = Some(stamp(now + Duration::seconds(wait)));
286 item.last_error = Some(error.chars().take(300).collect());
287 self.update(item)
288 }
289
290 pub fn fail(&self, item: &mut OutboxItem, error: &str) -> Result<(), CloudError> {
292 item.last_error = Some(error.chars().take(300).collect());
293 let bytes = serde_json::to_vec(item).map_err(|e| CloudError::Local(e.to_string()))?;
294 write_private(
295 &self.failed_dir(&item.channel),
296 &format!("{}.json", item.id),
297 &bytes,
298 )?;
299 keep_newest(&self.failed_dir(&item.channel), ".json", MAX_FAILED);
300 self.remove(item)
301 }
302
303 pub fn failed(&self, channel: &str) -> Vec<OutboxItem> {
304 Self::files(&self.failed_dir(channel))
305 .into_iter()
306 .filter_map(|(path, _)| {
307 std::fs::read(&path)
308 .ok()
309 .and_then(|b| serde_json::from_slice(&b).ok())
310 })
311 .collect()
312 }
313
314 pub fn depth(&self, channel: &str) -> OutboxDepth {
315 OutboxDepth {
316 pending: Self::files(&self.dir(channel)).len(),
317 failed: Self::files(&self.failed_dir(channel)).len(),
318 }
319 }
320}
321
322fn keep_newest(dir: &Path, suffix: &str, keep: usize) {
325 let mut names: Vec<PathBuf> = std::fs::read_dir(dir)
326 .into_iter()
327 .flatten()
328 .filter_map(Result::ok)
329 .filter(|e| e.file_name().to_string_lossy().ends_with(suffix))
330 .map(|e| e.path())
331 .collect();
332 names.sort();
333 let excess = names.len().saturating_sub(keep);
334 for old in names.drain(..excess) {
335 let _ = std::fs::remove_file(old);
336 }
337}
338
339#[cfg(test)]
340mod tests {
341 use super::*;
342 use serde_json::json;
343
344 fn now() -> UtcDateTime {
345 OffsetDateTime::parse_from_rfc3339("2026-10-20T12:00:00Z")
346 .unwrap()
347 .to_utc()
348 }
349
350 #[test]
351 fn items_survive_reopen_in_order_and_keep_their_ids() {
352 let dir = tempfile::tempdir().unwrap();
353 let outbox = Outbox::at(dir.path());
354 let first = outbox
355 .enqueue(CHANNEL_KNOWLEDGE, json!({"n": 1}), now())
356 .unwrap();
357 let second = outbox
358 .enqueue(
359 CHANNEL_KNOWLEDGE,
360 json!({"n": 2}),
361 now() + Duration::milliseconds(5),
362 )
363 .unwrap();
364 let items = Outbox::at(dir.path()).list(CHANNEL_KNOWLEDGE);
365 assert_eq!(
366 items.iter().map(|i| i.id.clone()).collect::<Vec<_>>(),
367 vec![first, second]
368 );
369 outbox.remove(&items[0]).unwrap();
370 assert_eq!(
371 outbox.depth(CHANNEL_KNOWLEDGE),
372 OutboxDepth {
373 pending: 1,
374 failed: 0
375 }
376 );
377 }
378
379 #[test]
380 fn backoff_grows_and_failures_stay_visible() {
381 let dir = tempfile::tempdir().unwrap();
382 let outbox = Outbox::at(dir.path());
383 outbox.enqueue(CHANNEL_KNOWLEDGE, json!({}), now()).unwrap();
384 let mut item = outbox.list(CHANNEL_KNOWLEDGE).remove(0);
385 outbox
386 .retry_later(&mut item, "offline", None, now())
387 .unwrap();
388 assert!(!item.due(now() + Duration::seconds(29)));
389 assert!(item.due(now() + Duration::seconds(38)));
390 outbox
391 .retry_later(&mut item, "offline", Some(600), now())
392 .unwrap();
393 assert!(!item.due(now() + Duration::seconds(599)));
394 outbox.fail(&mut item, "invalid_request").unwrap();
395 assert_eq!(
396 outbox.depth(CHANNEL_KNOWLEDGE),
397 OutboxDepth {
398 pending: 0,
399 failed: 1
400 }
401 );
402 assert_eq!(
403 outbox.failed(CHANNEL_KNOWLEDGE)[0].last_error.as_deref(),
404 Some("invalid_request")
405 );
406 }
407
408 #[test]
409 fn a_huge_retry_after_is_capped_not_a_panic() {
410 let dir = tempfile::tempdir().unwrap();
411 let outbox = Outbox::at(dir.path());
412 outbox.enqueue(CHANNEL_KNOWLEDGE, json!({}), now()).unwrap();
413 let mut item = outbox.list(CHANNEL_KNOWLEDGE).remove(0);
414 outbox
415 .retry_later(&mut item, "busy", Some(u64::MAX), now())
416 .unwrap();
417 assert!(!item.due(now() + Duration::days(6)));
418 assert!(item.due(now() + Duration::days(7) + Duration::seconds(1)));
419 }
420
421 #[test]
422 fn unknown_channels_are_refused() {
423 let dir = tempfile::tempdir().unwrap();
424 assert!(
425 Outbox::at(dir.path())
426 .enqueue("../x", json!({}), now())
427 .is_err()
428 );
429 }
430}