diff --git a/pkgs/id/src/directory_view.rs b/pkgs/id/src/directory_view.rs index 5ad452c036..753e10bc8e 100644 --- a/pkgs/id/src/directory_view.rs +++ b/pkgs/id/src/directory_view.rs @@ -1753,6 +1753,7 @@ pub fn render_text(view: &DirectoryView) -> String { mod tests { use super::*; use crate::artifact::HomeServer; + use crate::envelope_outbox::{MAX_FINISHED_ENTRIES, Outcome}; use ed25519_dalek::SigningKey; fn node() -> String { @@ -1927,6 +1928,70 @@ mod tests { ); } + #[test] + fn deliveries_keeps_the_newest_finished_entries_and_all_pending_entries() { + let dir = tempfile::tempdir().unwrap(); + let mut outbox = Outbox::open(dir.path().join("outbox.jsonl")).unwrap(); + let total_finished = MAX_FINISHED_ENTRIES + 3; + + for index in 0..total_finished { + let id = format!("delivery-{index:03}"); + let envelope = Envelope { + kind: EnvelopeKind::FriendRequest, + from: "ann".to_owned(), + to: format!("recipient-{index:03}"), + audience: "club".to_owned(), + id: id.clone(), + request: None, + at: 0, + signature: "00".to_owned(), + }; + outbox.enqueue(&node(), envelope).unwrap(); + outbox.record(&id, 0, Outcome::Delivered).unwrap(); + } + + for id in ["pending-now", "pending-later"] { + outbox + .enqueue( + &node(), + Envelope { + kind: EnvelopeKind::FriendRequest, + from: "ann".to_owned(), + to: id.to_owned(), + audience: "club".to_owned(), + id: id.to_owned(), + request: None, + at: 0, + signature: "00".to_owned(), + }, + ) + .unwrap(); + } + outbox + .record("pending-later", 0, Outcome::Retry("down".to_owned())) + .unwrap(); + + let shown = deliveries(&outbox, "admin"); + assert_eq!(shown.len(), MAX_FINISHED_ENTRIES + 2); + assert_eq!( + shown + .iter() + .filter(|delivery| delivery.status == "delivered") + .count(), + MAX_FINISHED_ENTRIES + ); + assert_eq!( + shown + .iter() + .filter(|delivery| delivery.status == "not yet delivered") + .count(), + 2 + ); + assert!(!shown.iter().any(|delivery| delivery.to == "recipient-000")); + assert!(shown.iter().any(|delivery| delivery.to == "pending-now")); + assert!(shown.iter().any(|delivery| delivery.to == "pending-later")); + } + #[test] fn the_admin_sees_every_detail_and_member() { let s = sample(); diff --git a/pkgs/id/src/envelope_outbox.rs b/pkgs/id/src/envelope_outbox.rs index 787b85d466..8a769703bd 100644 --- a/pkgs/id/src/envelope_outbox.rs +++ b/pkgs/id/src/envelope_outbox.rs @@ -5,10 +5,12 @@ //! on open, so an entry that was not finished survives a restart. A line cut //! short by a crash was never acknowledged, so it is dropped on open. -use std::collections::BTreeMap; +use std::collections::{BTreeMap, VecDeque}; +#[cfg(unix)] +use std::fs::File; use std::fs::{self, OpenOptions}; use std::io::{self, Write}; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use anyhow::{Context, Result, anyhow, ensure}; use serde::{Deserialize, Serialize}; @@ -23,6 +25,8 @@ use crate::envelope_net::deliver; /// Deliveries attempted before an envelope is given up. pub const MAX_ATTEMPTS: u32 = 12; +/// The maximum number of newest finished entries retained by the outbox. +pub const MAX_FINISHED_ENTRIES: usize = 100; const BASE_DELAY_MS: u64 = 60_000; const MAX_DELAY_MS: u64 = 6 * 60 * 60 * 1000; @@ -115,10 +119,15 @@ enum Record { } /// The queue, keyed by envelope ID. +/// +/// It retains the newest [`MAX_FINISHED_ENTRIES`] finished entries by finish +/// order, along with every unfinished entry. When replay drops older finished +/// entries, the journal is compacted on open. #[derive(Debug)] pub struct Outbox { path: PathBuf, entries: BTreeMap, + finished_order: VecDeque, } impl Outbox { @@ -132,6 +141,7 @@ impl Outbox { let mut outbox = Self { path: path.into(), entries: BTreeMap::new(), + finished_order: VecDeque::new(), }; let bytes = match fs::read(&outbox.path) { Ok(bytes) => bytes, @@ -139,6 +149,7 @@ impl Outbox { Err(error) => return Err(error).context("reading the envelope outbox"), }; let mut kept = 0; + let mut dropped_finished = false; for (number, line) in bytes.split_inclusive(|byte| *byte == b'\n').enumerate() { if !line.ends_with(b"\n") { // The final line has no newline: a crash cut the append @@ -161,7 +172,7 @@ impl Outbox { } match serde_json::from_str::(text.trim_end()) { Ok(record) => { - outbox.apply(record).with_context(|| { + dropped_finished |= outbox.apply(record).with_context(|| { format!("envelope outbox line {} is refused", number + 1) })?; kept += line.len(); @@ -179,6 +190,9 @@ impl Outbox { .open(&outbox.path)? .set_len(kept as u64)?; } + if dropped_finished { + outbox.compact_journal()?; + } Ok(outbox) } @@ -304,10 +318,13 @@ impl Outbox { .open(&self.path)?; file.write_all(line.as_bytes())?; file.sync_data()?; - self.apply(record) + self.apply(record)?; + Ok(()) } - fn apply(&mut self, record: Record) -> Result<()> { + /// Applies a record and reports whether it evicted a finished entry. + fn apply(&mut self, record: Record) -> Result { + let mut dropped_finished = false; match record { Record::Queued { target, envelope } => { self.insert_queued(target, Payload::Envelope(envelope))?; @@ -376,6 +393,14 @@ impl Outbox { entry.attempts = attempts; entry.finish = Some(outcome); entry.last_error = detail; + self.finished_order.retain(|finished_id| finished_id != &id); + self.finished_order.push_back(id); + if self.finished_order.len() > MAX_FINISHED_ENTRIES { + if let Some(oldest) = self.finished_order.pop_front() { + self.entries.remove(&oldest); + dropped_finished = true; + } + } } Record::Withdrawn { id } => { let entry = self @@ -386,12 +411,110 @@ impl Outbox { entry.attempts == 0 && entry.finish.is_none(), "envelope {id} was already attempted" ); + self.finished_order.retain(|finished_id| finished_id != &id); self.entries.remove(&id); } } + Ok(dropped_finished) + } + + /// Rewrites the journal as a snapshot of the retained entries. + fn compact_journal(&self) -> Result<()> { + let mut temporary_path = self.path.as_os_str().to_owned(); + temporary_path.push(".compact.tmp"); + let temporary_path = PathBuf::from(temporary_path); + let permissions = fs::metadata(&self.path)?.permissions(); + let mut file = OpenOptions::new() + .create(true) + .truncate(true) + .write(true) + .open(&temporary_path) + .context("creating the compacted envelope outbox")?; + + for record in self.compact_records()? { + serde_json::to_writer(&mut file, &record)?; + file.write_all(b"\n")?; + } + fs::set_permissions(&temporary_path, permissions)?; + file.sync_all()?; + drop(file); + replace_journal(&temporary_path, &self.path) + .context("replacing the envelope outbox with its compacted journal")?; + + #[cfg(unix)] + { + let parent = self + .path + .parent() + .filter(|parent| !parent.as_os_str().is_empty()) + .unwrap_or_else(|| Path::new(".")); + File::open(parent)?.sync_all()?; + } Ok(()) } + /// Builds a replayable snapshot while preserving the finish-order queue. + fn compact_records(&self) -> Result> { + // NOTE: the snapshot must satisfy the same replay validation as a + // live journal (see `apply`): every `Attempted` record increments + // the attempt count by exactly one, and a `Finished` record carries + // the count after its final attempt. A snapshot therefore replays + // an entry's attempt count incrementally (`push_attempt_history`) + // instead of jumping straight to the final count. + let mut records = Vec::with_capacity(self.entries.len() * 2); + for entry in self.entries.values() { + records.push(match &entry.payload { + Payload::Envelope(envelope) => Record::Queued { + target: entry.target.clone(), + envelope: envelope.clone(), + }, + Payload::Artifact(artifact) => Record::QueuedArtifact { + target: entry.target.clone(), + artifact: artifact.clone(), + }, + }); + } + + // Pending entries have no finish-order significance, so their retry + // state can be replayed before the finished entries. + for (id, entry) in &self.entries { + if entry.finish.is_none() + && (entry.attempts > 0 || entry.next_at != 0 || entry.last_error.is_some()) + { + push_attempt_increments(&mut records, id, entry.attempts); + if entry.attempts > 0 { + records.push(Record::Attempted { + id: id.clone(), + attempts: entry.attempts, + next_at: entry.next_at, + error: entry.last_error.clone().unwrap_or_default(), + }); + } + } + } + + for id in &self.finished_order { + let entry = self + .entries + .get(id) + .with_context(|| format!("finished entry {id} is missing during compaction"))?; + // The `Finished` record itself carries the final attempt count, + // so only the increments below it are replayed as `Attempted`. + // A finished entry's `next_at` is inert (`due` skips finished + // entries), so the increments use a placeholder. + push_attempt_increments(&mut records, id, entry.attempts); + records.push(Record::Finished { + id: id.clone(), + attempts: entry.attempts, + outcome: entry + .finish + .context("finished-order entry has no finish during compaction")?, + detail: entry.last_error.clone(), + }); + } + Ok(records) + } + fn insert_queued(&mut self, target: String, payload: Payload) -> Result<()> { // The live path checks the target in the enqueue verbs // before committing; replay must hold the same line, or a journal @@ -421,6 +544,48 @@ impl Outbox { } } +/// Pushes placeholder `Attempted` records for the counts `1..below`, so a +/// compacted snapshot replays an entry's attempt count one increment at a +/// time, as replay validation requires. The caller pushes the final record +/// (the real `Attempted` for a pending entry, or the `Finished` record) +/// itself; placeholders carry no retry state. +fn push_attempt_increments(records: &mut Vec, id: &str, below: u32) { + for attempts in 1..below { + records.push(Record::Attempted { + id: id.to_owned(), + attempts, + next_at: 0, + error: String::new(), + }); + } +} + +/// Replaces the journal at `destination` with the compacted file at +/// `temporary`, as atomically as the platform allows. +#[cfg(not(windows))] +fn replace_journal(temporary: &Path, destination: &Path) -> io::Result<()> { + // rename(2) replaces an existing destination atomically. + fs::rename(temporary, destination) +} + +/// Replaces the journal at `destination` with the compacted file at +/// `temporary`, as atomically as the platform allows. +#[cfg(windows)] +fn replace_journal(temporary: &Path, destination: &Path) -> io::Result<()> { + // `fs::rename` cannot replace an existing file on Windows, and the + // journal always exists by the time compaction runs, so a plain rename + // would fail every compaction there (Copilot review on PR #4710). + // Remove-then-rename is the fallback: it is NOT atomic — a crash + // between the two calls leaves the journal missing and only the + // `.compact.tmp` file behind — but compaction only runs after a full + // successful replay, and the alternative on Windows is that + // compaction (and with it `Outbox::open`) never succeeds at all. + if destination.exists() { + fs::remove_file(destination)?; + } + fs::rename(temporary, destination) +} + /// Delivers every envelope due at `now`, recording each outcome as it happens. /// /// The lock is released while a delivery is in flight, so enqueueing is not @@ -634,6 +799,105 @@ mod tests { assert!(reopened.entry("e1").unwrap().last_error.is_none()); } + #[test] + fn runtime_retains_the_newest_finished_entries_in_finish_order() { + let dir = tempfile::tempdir().unwrap(); + let mut outbox = Outbox::open(path(&dir)).unwrap(); + let total = MAX_FINISHED_ENTRIES + 5; + + for index in 0..total { + let id = format!("e{index:03}"); + outbox.enqueue(&target(), envelope(&id)).unwrap(); + } + for index in (0..total).step_by(2).chain((1..total).step_by(2)) { + let id = format!("e{index:03}"); + outbox.record(&id, NOW, Outcome::Delivered).unwrap(); + } + + assert_eq!( + outbox + .entries() + .filter(|entry| entry.finish.is_some()) + .count(), + MAX_FINISHED_ENTRIES + ); + for oldest in [0, 2, 4, 6, 8] { + assert!(outbox.entry(&format!("e{oldest:03}")).is_none()); + } + assert!(outbox.entry("e001").is_some()); + assert!(outbox.entry("e104").is_some()); + + outbox.enqueue(&target(), envelope("pending")).unwrap(); + assert_eq!(outbox.entries().count(), MAX_FINISHED_ENTRIES + 1); + assert_eq!(outbox.due(NOW), vec!["pending".to_owned()]); + } + + #[test] + fn replay_compacts_finished_history_and_preserves_state_and_finish_order() { + let dir = tempfile::tempdir().unwrap(); + let journal = path(&dir); + let mut outbox = Outbox::open(&journal).unwrap(); + let total = MAX_FINISHED_ENTRIES + 5; + + for index in 0..total { + let id = format!("e{index:03}"); + outbox.enqueue(&target(), envelope(&id)).unwrap(); + } + for index in (0..total).step_by(2).chain((1..total).step_by(2)) { + let id = format!("e{index:03}"); + outbox.record(&id, NOW, Outcome::Delivered).unwrap(); + } + outbox.enqueue(&target(), envelope("pending-now")).unwrap(); + outbox + .enqueue(&target(), envelope("pending-later")) + .unwrap(); + outbox + .record("pending-later", NOW, Outcome::Retry("down".to_owned())) + .unwrap(); + + let expected_entries = outbox.entries.clone(); + let expected_due_now = outbox.due(NOW); + let expected_due_later = outbox.due(NOW + MINUTE); + drop(outbox); + + // A parseable record without its trailing newline is still a torn tail; + // open must truncate it before compacting the completed history. + let mut file = OpenOptions::new().append(true).open(&journal).unwrap(); + file.write_all(queued_line("torn").as_bytes()).unwrap(); + drop(file); + + let reopened = Outbox::open(&journal).unwrap(); + assert_eq!(reopened.entries, expected_entries); + assert_eq!(reopened.due(NOW), expected_due_now); + assert_eq!(reopened.due(NOW + MINUTE), expected_due_later); + assert!(reopened.entry("torn").is_none()); + + let compacted = fs::read_to_string(&journal).unwrap(); + assert!(compacted.ends_with('\n')); + assert!(!compacted.contains("e000")); + assert!(!compacted.contains("e002")); + assert!(compacted.contains("e001")); + assert!(compacted.contains("pending-later")); + drop(reopened); + + let mut reopened_again = Outbox::open(&journal).unwrap(); + assert_eq!(reopened_again.entries, expected_entries); + assert_eq!(reopened_again.due(NOW), expected_due_now); + assert_eq!(reopened_again.due(NOW + MINUTE), expected_due_later); + assert_eq!(fs::read_to_string(&journal).unwrap(), compacted); + + // Compaction must keep the relative finish order so the next finish + // evicts the oldest entry that survived the first cap. + reopened_again + .enqueue(&target(), envelope("next-finish")) + .unwrap(); + reopened_again + .record("next-finish", NOW, Outcome::Delivered) + .unwrap(); + assert!(reopened_again.entry("e010").is_none()); + assert!(reopened_again.entry("e001").is_some()); + } + #[test] fn a_withdrawn_envelope_is_gone_and_stays_gone() { let dir = tempfile::tempdir().unwrap();