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