Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
320 changes: 318 additions & 2 deletions pkgs/id/crates/id-store/src/admission.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1122,7 +1122,7 @@ pub trait PolicyEpochSource: Send + Sync {
/// never a torn record — and a reader in another process sees the
/// same. This is the durable adapter behind the admission gate's
/// commit-time reauthorization (issue #17179, slice 1); the ledger
/// and outbox durable adapters are the follow-on slices.
/// adapter is slice 2 and the outbox journal adapter is slice 3.
#[derive(Debug)]
pub struct FilePolicyEpochSource {
path: PathBuf,
Expand Down Expand Up @@ -1566,7 +1566,7 @@ fn ledger_parse_record(line: &str) -> Result<(OperationId, LedgerEntry), String>
/// file (issue #17179, slice 2): the production counterpart of
/// [`MemoryOperationLedger`], and the ledger half of this issue
/// (the policy-epoch source is slice 1; the outbox journal
/// adapter is the follow-on slice).
/// adapter is slice 3).
///
/// Every [`OperationLedger::record`] appends one full entry
/// snapshot as a single line and fsyncs before returning, so a
Expand Down Expand Up @@ -1680,6 +1680,322 @@ impl OperationLedger for FileOperationLedger {
}
}

// ---------------------------------------------------------------------------
// Durable outbox journal (issue #17179, slice 3)
// ---------------------------------------------------------------------------

/// Halts on a durable outbox record that cannot be trusted,
/// mirroring [`ledger_fail_closed`]: the [`OutboxJournal`] trait
/// has no error channel, and the alternatives are all worse than
/// stopping — dropping a pending record silently breaks
/// at-least-once delivery (a committed side-effect would never be
/// retried), and inventing one risks duplicate delivery the
/// receiver did not dedupe against a real stable ID. An operator
/// repairs or removes the record and restarts.
#[allow(clippy::panic)]
fn outbox_fail_closed(problem: String) -> ! {
panic!("durable admission outbox (issue #17179) is unusable: {problem}")
}

fn outbox_encode_pending(pending: &PendingDelivery) -> String {
let receipt = &pending.event.receipt;
let mut line = String::from("adm-outbox-v1 kind=pending");
line.push_str(&format!(
" evid={}",
ledger_hex_encode(pending.event_id.as_bytes())
));
line.push_str(&format!(
" hook={}",
ledger_hex_encode(pending.hook_id.as_str().as_bytes())
));
line.push_str(&format!(
" op={}",
ledger_hex_encode(pending.event.operation_id.as_str().as_bytes())
));
line.push_str(&format!(
" env={}",
ledger_content_id_text(pending.event.envelope_id.content_id())
));
line.push_str(&format!(
" pay={}",
ledger_content_id_text(receipt.payload_id().content_id())
));
line.push_str(&format!(
" signer={}",
ledger_hex_encode(receipt.signer_id().as_bytes())
));
line.push_str(&format!(
" tenant={}",
ledger_hex_encode(receipt.tenant_scope().as_bytes())
));
line.push_str(&format!(" plen={}", receipt.payload_length()));
line.push_str(&format!(" attempts={}", pending.attempts));
line.push_str(&format!(
" err={}",
ledger_hex_encode(pending.last_error.as_bytes())
));
line.push_str(&format!(" ann={}", pending.event.annotations.len()));
for annotation in &pending.event.annotations {
line.push_str(&format!(
" ans={}",
ledger_hex_encode(annotation.namespace().as_bytes())
));
line.push_str(&format!(
" akey={}",
ledger_hex_encode(annotation.key().as_bytes())
));
line.push_str(&format!(
" aval={}",
ledger_hex_encode(annotation.value())
));
}
line
}

fn outbox_encode_cleared(event_id: &str, hook_id: &HookId) -> String {
format!(
"adm-outbox-v1 kind=cleared evid={} hook={}",
ledger_hex_encode(event_id.as_bytes()),
ledger_hex_encode(hook_id.as_str().as_bytes())
)
}

fn outbox_parse_record(
line: &str,
) -> Result<(bool, (String, HookId), Option<PendingDelivery>), String> {
let tokens: Vec<&str> = line.split(' ').collect();
if tokens.first() != Some(&"adm-outbox-v1") {
return Err(format!("record does not start with adm-outbox-v1: {line:?}"));
}
let mut pos = 1;
let kind = ledger_next(&tokens, &mut pos, "kind")?;
let event_id = ledger_text_field(&tokens, &mut pos, "evid")?;
let hook_id = HookId::new(ledger_text_field(&tokens, &mut pos, "hook")?)
.map_err(|error| format!("recorded hook ID is invalid: {error}"))?;
let key = (event_id.clone(), hook_id);
match kind {
"cleared" => {
if pos != tokens.len() {
return Err(format!(
"record has {} unexpected trailing tokens",
tokens.len() - pos
));
}
Ok((false, key, None))
}
"pending" => {
let operation_id = OperationId::new(ledger_text_field(&tokens, &mut pos, "op")?)
.map_err(|error| format!("recorded operation ID is invalid: {error}"))?;
let envelope_id = EnvelopeId::from_content_id(ledger_parse_content_id(
ledger_next(&tokens, &mut pos, "env")?,
)?);
let payload_id = PayloadId::from_content_id(ledger_parse_content_id(
ledger_next(&tokens, &mut pos, "pay")?,
)?);
let signer_id = ledger_text_field(&tokens, &mut pos, "signer")?;
let tenant_scope = ledger_text_field(&tokens, &mut pos, "tenant")?;
let payload_length: u64 = ledger_next(&tokens, &mut pos, "plen")?
.parse()
.map_err(|_| "recorded payload length is not a number".to_owned())?;
let receipt = AdmissionReceipt::from_recorded(
envelope_id.clone(),
payload_id,
signer_id,
tenant_scope,
payload_length,
);
let attempts: u32 = ledger_next(&tokens, &mut pos, "attempts")?
.parse()
.map_err(|_| "recorded attempts count is not a number".to_owned())?;
let last_error = ledger_text_field(&tokens, &mut pos, "err")?;
let annotation_count: usize = ledger_next(&tokens, &mut pos, "ann")?
.parse()
.map_err(|_| "recorded annotation count is not a number".to_owned())?;
let mut annotations = Vec::with_capacity(annotation_count);
for _ in 0..annotation_count {
let namespace = ledger_text_field(&tokens, &mut pos, "ans")?;
let key = ledger_text_field(&tokens, &mut pos, "akey")?;
let value_hex = ledger_next(&tokens, &mut pos, "aval")?;
let value = ledger_hex_decode(value_hex)
.ok_or_else(|| format!("annotation value {value_hex:?} is not hex"))?;
annotations.push(
Annotation::new(namespace, key, value)
.map_err(|error| format!("recorded annotation is invalid: {error}"))?,
);
}
if pos != tokens.len() {
return Err(format!(
"record has {} unexpected trailing tokens",
tokens.len() - pos
));
}
let pending = PendingDelivery {
event_id: event_id.clone(),
hook_id: key.1.clone(),
event: OutboxEvent {
event_id,
operation_id,
envelope_id,
receipt,
annotations,
},
last_error,
attempts,
};
Ok((true, key, Some(pending)))
}
other => Err(format!("unknown outbox record kind {other:?}")),
}
}

/// A durable [`OutboxJournal`] backed by one append-only log
/// file (issue #17179, slice 3): the production counterpart of
/// [`MemoryOutboxJournal`], completing this issue's adapter set
/// (the policy-epoch source is slice 1; the operation ledger is
/// slice 2).
///
/// Every mutation appends one line and fsyncs before returning:
/// [`OutboxJournal::record_pending`] appends a full pending
/// snapshot, [`OutboxJournal::clear`] appends a tombstone.
/// [`OutboxJournal::pending`] folds the log in order —
/// last-record-wins per (event ID, hook ID), tombstones remove —
/// so a delivery that failed before a restart is still pending
/// after it (at-least-once survives the process), a retry's
/// updated attempt count replaces the earlier snapshot instead
/// of duplicating the delivery (dedupe on replay, by the same
/// stable ID the receiver dedupes on), and a cleared delivery
/// never resurrects. Records are never edited or deleted, so
/// the log is also the audit trail of delivery attempts.
///
/// Fail-closed, per the parent oracle: a missing file is an
/// empty journal (nothing was ever recorded pending), but a
/// file that exists and cannot be read or parsed in full halts
/// the process via [`outbox_fail_closed`] rather than guessing
/// at delivery state — see that function for why the trait
/// leaves no safer option.
///
/// One journal object serializes its own reads and writes; the
/// format assumes a single writing process at a time (the same
/// assumption the ledger adapter makes), with readers in other
/// processes seeing every fsynced record.
#[derive(Debug)]
pub struct FileOutboxJournal {
path: PathBuf,
access_lock: Mutex<()>,
}

impl FileOutboxJournal {
/// A journal over the log at `path`. The file is neither
/// created nor read until first use: a missing file is the
/// empty journal, not an implicit state.
pub fn new(path: impl Into<PathBuf>) -> Self {
Self {
path: path.into(),
access_lock: Mutex::new(()),
}
}

/// The path of the outbox log.
#[must_use]
pub fn path(&self) -> &Path {
&self.path
}

fn load(&self) -> BTreeMap<(String, HookId), PendingDelivery> {
let content = match fs::read_to_string(&self.path) {
Ok(content) => content,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
return BTreeMap::new();
}
Err(error) => {
outbox_fail_closed(format!(
"cannot read outbox record at {}: {error}",
self.path.display()
));
}
};
let mut pending = BTreeMap::new();
for (index, line) in content.lines().enumerate() {
match outbox_parse_record(line) {
Ok((true, key, Some(delivery))) => {
pending.insert(key, delivery);
}
Ok((false, key, None)) => {
pending.remove(&key);
}
Ok(_) => {
outbox_fail_closed(format!(
"outbox record at {} line {} is inconsistent",
self.path.display(),
index + 1
));
}
Err(problem) => {
outbox_fail_closed(format!(
"outbox record at {} line {} is corrupt: {problem}",
self.path.display(),
index + 1
));
}
}
}
pending
}

fn append(&self, line: &str) {
// Never append to a log that does not parse in full: the
// fold must stay trustworthy for every later reader.
let _ = self.load();
let mut line = line.to_owned();
line.push('\n');
let appended = (|| -> Result<(), std::io::Error> {
let mut file = fs::OpenOptions::new()
.create(true)
.append(true)
.open(&self.path)?;
std::io::Write::write_all(&mut file, line.as_bytes())?;
file.sync_all()
})();
if let Err(error) = appended {
outbox_fail_closed(format!(
"cannot append outbox record at {}: {error}",
self.path.display()
));
}
}
}

impl OutboxJournal for FileOutboxJournal {
fn record_pending(&self, pending: PendingDelivery) {
let _guard = self
.access_lock
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
self.append(&outbox_encode_pending(&pending));
}

fn pending(&self) -> Vec<PendingDelivery> {
let _guard = self
.access_lock
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
self.load().into_values().collect()
}

fn clear(&self, event_id: &str, hook_id: &HookId) {
let _guard = self
.access_lock
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
if self
.load()
.contains_key(&(event_id.to_owned(), hook_id.clone()))
{
self.append(&outbox_encode_cleared(event_id, hook_id));
}
}
}

#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
Expand Down
Loading