diff --git a/crates/odin-daemon/src/lib.rs b/crates/odin-daemon/src/lib.rs index 7c2f115..40b44c1 100644 --- a/crates/odin-daemon/src/lib.rs +++ b/crates/odin-daemon/src/lib.rs @@ -4,14 +4,15 @@ //! read-only projection, a trusted receive time with any service-owned //! presence, and narrow clock/store/signer implementations. -use std::collections::BTreeMap; +use std::cell::{Cell, Ref, RefCell}; +use std::collections::{BTreeMap, BTreeSet}; use std::path::{Path, PathBuf}; use std::time::{SystemTime, UNIX_EPOCH}; use anyhow::{Context, Result, bail, ensure}; use chrono::{DateTime, SecondsFormat, Utc}; use cultcache_rs::{ - CultCacheEnvelope, CultCacheExpectedEnvelope, DatabaseEntry, SingleFileMessagePackBackingStore, + CacheBackingStore, CultCacheEnvelope, DatabaseEntry, SingleFileMessagePackBackingStore, }; use cultnet_rs::{ GAMECULT_RUNTIME_PRESENCE_HEALTH_SCHEMA, GAMECULT_RUNTIME_PRESENCE_HEALTH_SIGNING_PURPOSE, @@ -29,8 +30,6 @@ use cultnet_rs::{ verify_service_identity_signature_with_public_key, }; -const CAS_ATTEMPTS: usize = 8; - /// Odin's durable high-water mark for one target's correlation sequence. /// /// The correlation's `publisher_sequence` must strictly increase for as long as @@ -195,16 +194,70 @@ impl CultCacheIdunnProjectionSource { impl IdunnProjectionSource for CultCacheIdunnProjectionSource { fn projections(&self, target: &str) -> Result> { - let Some(entries) = self.entries()? else { - return Ok(Vec::new()); - }; - let anchor = provider_anchor(&entries, target)?; + self.snapshot()?.projections(target) + } + + fn projection(&self, incarnation: &IncarnationRef) -> Result> { + self.snapshot()?.projection(incarnation) + } +} + +impl CultCacheIdunnProjectionSource { + /// Read the projection file once. An absent file projects nothing. + pub fn snapshot(&self) -> Result { + if !self.path.is_file() { + return Ok(IdunnProjectionSnapshot { + entries: Vec::new(), + }); + } + SingleFileMessagePackBackingStore::new(&self.path) + .pull_all_read_only_snapshot() + .map(|entries| IdunnProjectionSnapshot { entries }) + .map_err(|error| { + // The store's decode step reports its failures as text, so an + // I/O error in the chain here is from opening or reading the + // file and from nothing the file said. + if error.chain().any(|cause| cause.is::()) { + error.context(ProjectionUnreadable) + } else { + error + } + }) + } +} + +/// One reading of Idunn's projection file. Every lookup made against it is +/// answered from the same bytes, so a pass that refreshes every incarnation +/// reads the file once. +pub struct IdunnProjectionSnapshot { + entries: Vec, +} + +impl IdunnProjectionSnapshot { + /// Every incarnation Idunn projects an Expected for, of every target. Only + /// the keys are read: decoding a record is the refresh of that one + /// incarnation, so a record that will not decode cannot make the list + /// unreadable. A record keyed by anything but an incarnation key is not + /// this contract's and is skipped. + pub fn incarnations(&self) -> BTreeSet { + self.entries + .iter() + .filter(|entry| entry.r#type == IdunnExpectedIncarnationRecord::TYPE) + .filter_map(|entry| IncarnationRef::parse_key(&entry.key)) + .collect() + } +} + +impl IdunnProjectionSource for IdunnProjectionSnapshot { + fn projections(&self, target: &str) -> Result> { + let entries = &self.entries; + let anchor = provider_anchor(entries, target)?; // A record keyed by anything but its own incarnation key is not this // contract's. That includes the target-keyed single slot the previous // projection used; an Idunn still writing that shape projects nothing // this reader will act on, rather than something it will misread. let mut projections = Vec::new(); - for envelope in &entries { + for envelope in entries { if envelope.r#type != IdunnExpectedIncarnationRecord::TYPE { continue; } @@ -215,7 +268,7 @@ impl IdunnProjectionSource for CultCacheIdunnProjectionSource { continue; } projections.push(assemble_projection( - &entries, + entries, anchor.clone(), envelope, &incarnation, @@ -229,40 +282,17 @@ impl IdunnProjectionSource for CultCacheIdunnProjectionSource { /// record under another incarnation's key is that incarnation's fault, and /// never makes this one unreadable. fn projection(&self, incarnation: &IncarnationRef) -> Result> { - let Some(entries) = self.entries()? else { - return Ok(None); - }; + let entries = &self.entries; let Some(envelope) = unique_envelope( - &entries, + entries, IdunnExpectedIncarnationRecord::TYPE, &incarnation.key(), )? else { return Ok(None); }; - let anchor = provider_anchor(&entries, &incarnation.target)?; - assemble_projection(&entries, anchor, envelope, incarnation).map(Some) - } -} - -impl CultCacheIdunnProjectionSource { - fn entries(&self) -> Result>> { - if !self.path.is_file() { - return Ok(None); - } - SingleFileMessagePackBackingStore::new(&self.path) - .pull_all_read_only_snapshot() - .map(Some) - .map_err(|error| { - // The store's decode step reports its failures as text, so an - // I/O error in the chain here is from opening or reading the - // file and from nothing the file said. - if error.chain().any(|cause| cause.is::()) { - error.context(ProjectionUnreadable) - } else { - error - } - }) + let anchor = provider_anchor(entries, &incarnation.target)?; + assemble_projection(entries, anchor, envelope, incarnation).map(Some) } } @@ -410,110 +440,233 @@ pub struct OdinStoreSnapshot { pub trait OdinTopologyStore { fn read(&self, query: OdinStoreQuery) -> Result; - fn compare_exchange( + /// Replace the queried incarnation's correlation, and its presence when + /// one is given. + fn commit( &self, - observed: &OdinStoreSnapshot, + query: &OdinStoreQuery, replacement_presence: Option<&AdmittedPresence>, replacement_correlation: &StoredCorrelation, - ) -> Result; + ) -> Result<()>; fn withdraw_correlation(&self, incarnation: &IncarnationRef) -> Result<()>; /// Claim the next correlation sequence for this target, never returning a - /// value already used. `prior` is the sequence of the currently stored + /// value already published. `prior` is the sequence of the currently stored /// correlation, or 0 when there is none. /// - /// The mark is advanced before the correlation that uses it is published, - /// so a crash in between leaves it ahead. That is the safe direction: - /// sequences may skip, they may never repeat. + /// A sequence is published when the store is flushed. The mark is written + /// in the same atomic write as every correlation that uses it, so the file + /// never holds a correlation ahead of its mark. A sequence reserved and + /// never flushed was never published, and may be claimed again after a + /// restart. fn reserve_publisher_sequence(&self, target: &str, prior: u64) -> Result; } -/// Odin's durable replay and correlation store. It persists existing CultNet -/// documents directly instead of inventing a parallel admission schema. -pub struct CultCacheOdinTopologyStore { - path: PathBuf, +impl OdinTopologyStore for &T { + fn read(&self, query: OdinStoreQuery) -> Result { + (*self).read(query) + } + + fn commit( + &self, + query: &OdinStoreQuery, + replacement_presence: Option<&AdmittedPresence>, + replacement_correlation: &StoredCorrelation, + ) -> Result<()> { + (*self).commit(query, replacement_presence, replacement_correlation) + } + + fn withdraw_correlation(&self, incarnation: &IncarnationRef) -> Result<()> { + (*self).withdraw_correlation(incarnation) + } + + fn reserve_publisher_sequence(&self, target: &str, prior: u64) -> Result { + (*self).reserve_publisher_sequence(target, prior) + } } -impl CultCacheOdinTopologyStore { - pub fn new(path: impl Into) -> Self { - Self { path: path.into() } +/// One record's identity in a CultCache store: its type, then its key. +pub type RecordId = (String, String); + +fn record_id(envelope: &CultCacheEnvelope) -> RecordId { + (envelope.r#type.clone(), envelope.key.clone()) +} + +/// Odin's store, held in memory for as long as Odin holds its write lease. It +/// persists existing CultNet documents directly instead of inventing a +/// parallel admission schema. +/// +/// The file is read once, by [`MemoryOdinTopologyStore::load`] when the lease +/// is granted, and never again while Odin serves: every lookup is answered +/// from memory. The file is Odin's durability checkpoint and Idunn's read-only +/// crossing. It is written by [`MemoryOdinTopologyStore::flush`] and nothing +/// else. +pub struct MemoryOdinTopologyStore { + path: PathBuf, + records: RefCell>, + /// Exactly what the file held when it was loaded or last written. + flushed: RefCell>, + /// The records differ from what was last loaded or written. + dirty: Cell, +} + +impl MemoryOdinTopologyStore { + /// Read the store file under its lock. An absent file is an empty store. + /// Records are loaded as they are stored: one that does not decode is that + /// record's failure, met where the record is used, and never stops the + /// load. + pub fn load(path: impl Into) -> Result { + let path = path.into(); + let flushed = SingleFileMessagePackBackingStore::new(&path).pull_all()?; + let mut records = BTreeMap::new(); + for envelope in &flushed { + if records.insert(record_id(envelope), envelope.clone()).is_some() { + eprintln!( + "Odin's store holds {} {} more than once; the last is kept", + envelope.r#type, envelope.key + ); + } + } + Ok(Self { + path, + records: RefCell::new(records), + flushed: RefCell::new(flushed), + dirty: Cell::new(false), + }) } pub fn path(&self) -> &Path { &self.path } + /// Every record, in the order the file stores them. + pub fn records(&self) -> Ref<'_, BTreeMap> { + self.records.borrow() + } + + /// Store one record in place of any with the same type and key. Storing + /// the record already held changes nothing. + pub fn put(&self, envelope: CultCacheEnvelope) { + let id = record_id(&envelope); + let mut records = self.records.borrow_mut(); + if records.get(&id) != Some(&envelope) { + records.insert(id, envelope); + self.dirty.set(true); + } + } + + fn remove(&self, record_type: &str, key: &str) { + if self + .records + .borrow_mut() + .remove(&(record_type.to_owned(), key.to_owned())) + .is_some() + { + self.dirty.set(true); + } + } + + /// Every incarnation this store holds a correlation for. + pub fn correlated_incarnations(&self) -> BTreeSet { + self.records + .borrow() + .keys() + .filter(|(record_type, _)| record_type == OdinRuntimeTopologyCorrelationRecord::TYPE) + .filter_map(|(_, key)| IncarnationRef::parse_key(key)) + .collect() + } + /// Remove every correlation not keyed by an incarnation. Those were written /// by the previous, target-keyed Odin; nothing reads them under this - /// contract, and left in place `stored_snapshot` would serve them to the - /// Verse as current. Presence records are kept whatever their key: the - /// self publisher sequence is continued from them. - pub fn retire_legacy_correlations(&self) -> Result { - for _ in 0..CAS_ATTEMPTS { - if !self.path.is_file() { - return Ok(0); - } - let entries = - SingleFileMessagePackBackingStore::new(&self.path).pull_all_read_only_snapshot()?; - let retained = entries - .iter() - .filter(|entry| { - !(entry.r#type == OdinRuntimeTopologyCorrelationRecord::TYPE - && IncarnationRef::parse_key(&entry.key).is_none()) - }) - .cloned() - .collect::>(); - let removed = entries.len() - retained.len(); - if removed == 0 { - return Ok(0); - } - if SingleFileMessagePackBackingStore::new(&self.path) - .compare_exchange_snapshot(&entries, &retained)? - { - return Ok(removed); - } + /// contract, and left in place the catalog would serve them to the Verse + /// as current. Presence records are kept whatever their key: the self + /// publisher sequence is continued from them. + pub fn retire_legacy_correlations(&self) -> usize { + let legacy: Vec = self + .records + .borrow() + .keys() + .filter(|(record_type, key)| { + record_type == OdinRuntimeTopologyCorrelationRecord::TYPE + && IncarnationRef::parse_key(key).is_none() + }) + .map(|(_, key)| key.clone()) + .collect(); + for key in &legacy { + self.remove(OdinRuntimeTopologyCorrelationRecord::TYPE, key); } - bail!("Odin topology store changed repeatedly while retiring legacy correlations") + legacy.len() + } + + /// Whether the records differ from what was last loaded or written. + pub fn is_dirty(&self) -> bool { + self.dirty.get() + } + + /// Write every record to the file as one atomic snapshot, if anything + /// changed since the last write; returns whether it wrote. + /// + /// The file must still hold exactly what Odin last loaded or wrote. Anything + /// else was written by another process, and the write is refused with + /// [`ForeignStoreWrite`] rather than made over it. + pub fn flush(&self) -> Result { + if !self.dirty.get() { + return Ok(false); + } + let current: Vec = self.records.borrow().values().cloned().collect(); + if !SingleFileMessagePackBackingStore::new(&self.path) + .compare_exchange_snapshot(&self.flushed.borrow(), ¤t)? + { + return Err(ForeignStoreWrite.into()); + } + *self.flushed.borrow_mut() = current; + self.dirty.set(false); + Ok(true) } } -impl OdinTopologyStore for CultCacheOdinTopologyStore { +/// Odin's store file no longer holds what Odin last loaded or wrote, so another +/// process wrote it. While Odin holds its write lease it is the file's only +/// writer: this is a second writer, and Odin must not write over it. +#[derive(Debug)] +pub struct ForeignStoreWrite; + +impl std::fmt::Display for ForeignStoreWrite { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str("Odin's store file was written by another process") + } +} + +impl std::error::Error for ForeignStoreWrite {} + +impl OdinTopologyStore for MemoryOdinTopologyStore { fn read(&self, mut query: OdinStoreQuery) -> Result { query.dependencies.sort(); query.dependencies.dedup(); - let entries = if self.path.is_file() { - SingleFileMessagePackBackingStore::new(&self.path).pull_all_read_only_snapshot()? - } else { - Vec::new() - }; - let presence_key = - presence_store_key(&query.incarnation, &query.provider_signer_identity_id); - let presence = unique_envelope( - &entries, + let records = self.records.borrow(); + let find = + |record_type: &str, key: &str| records.get(&(record_type.to_owned(), key.to_owned())); + let presence = find( GameCultRuntimePresenceHealthRecord::TYPE, - &presence_key, - )? + &presence_store_key(&query.incarnation, &query.provider_signer_identity_id), + ) .map(decode_presence_envelope) .transpose()?; - let correlation = unique_envelope( - &entries, + let correlation = find( OdinRuntimeTopologyCorrelationRecord::TYPE, &query.incarnation.key(), - )? + ) .map(decode_correlation_envelope) .transpose()?; let mut dependency_correlations = BTreeMap::new(); for dependency in &query.dependencies { - let current = unique_envelope( - &entries, - OdinRuntimeTopologyCorrelationRecord::TYPE, - &dependency.key(), - )? - .map(decode_correlation_envelope) - .transpose()?; + let current = find(OdinRuntimeTopologyCorrelationRecord::TYPE, &dependency.key()) + .map(decode_correlation_envelope) + .transpose()?; dependency_correlations.insert(dependency.clone(), current); } + drop(records); Ok(OdinStoreSnapshot { query, presence, @@ -522,128 +675,50 @@ impl OdinTopologyStore for CultCacheOdinTopologyStore { }) } - fn compare_exchange( + fn commit( &self, - observed: &OdinStoreSnapshot, + query: &OdinStoreQuery, replacement_presence: Option<&AdmittedPresence>, replacement_correlation: &StoredCorrelation, - ) -> Result { - let presence_key = presence_store_key( - &observed.query.incarnation, - &observed.query.provider_signer_identity_id, - ); - let correlation_key = observed.query.incarnation.key(); - let mut conditions = BTreeMap::new(); - insert_condition( - &mut conditions, - CultCacheExpectedEnvelope { - key: presence_key.clone(), - r#type: GameCultRuntimePresenceHealthRecord::TYPE.into(), - current: observed - .presence - .as_ref() - .map(|presence| presence_envelope(&presence_key, presence)), - }, - )?; - insert_condition( - &mut conditions, - CultCacheExpectedEnvelope { - key: correlation_key.clone(), - r#type: OdinRuntimeTopologyCorrelationRecord::TYPE.into(), - current: observed - .correlation - .as_ref() - .map(|correlation| correlation_envelope(&correlation_key, correlation)), - }, - )?; - for (dependency, correlation) in &observed.dependency_correlations { - let key = dependency.key(); - insert_condition( - &mut conditions, - CultCacheExpectedEnvelope { - key: key.clone(), - r#type: OdinRuntimeTopologyCorrelationRecord::TYPE.into(), - current: correlation - .as_ref() - .map(|correlation| correlation_envelope(&key, correlation)), - }, - )?; - } - let mut replacements = vec![correlation_envelope( - &correlation_key, + ) -> Result<()> { + self.put(correlation_envelope( + &query.incarnation.key(), replacement_correlation, - )]; + )); if let Some(presence) = replacement_presence { - replacements.push(presence_envelope(&presence_key, presence)); + self.put(presence_envelope( + &presence_store_key(&query.incarnation, &query.provider_signer_identity_id), + presence, + )); } - if let Some(parent) = self.path.parent() { - std::fs::create_dir_all(parent)?; - } - SingleFileMessagePackBackingStore::new(&self.path) - .compare_exchange(&conditions.into_values().collect::>(), &replacements) + Ok(()) } fn withdraw_correlation(&self, incarnation: &IncarnationRef) -> Result<()> { - let key = incarnation.key(); - for _ in 0..CAS_ATTEMPTS { - if !self.path.is_file() { - return Ok(()); - } - let entries = - SingleFileMessagePackBackingStore::new(&self.path).pull_all_read_only_snapshot()?; - let current = - unique_envelope(&entries, OdinRuntimeTopologyCorrelationRecord::TYPE, &key)?; - let Some(current) = current else { - return Ok(()); - }; - let replacement = entries - .iter() - .filter(|entry| *entry != current) - .cloned() - .collect::>(); - if SingleFileMessagePackBackingStore::new(&self.path) - .compare_exchange_snapshot(&entries, &replacement)? - { - return Ok(()); - } - } - bail!("Odin topology store changed repeatedly while withdrawing correlation") + self.remove(OdinRuntimeTopologyCorrelationRecord::TYPE, &incarnation.key()); + Ok(()) } fn reserve_publisher_sequence(&self, target: &str, prior: u64) -> Result { - for _ in 0..CAS_ATTEMPTS { - let entries = if self.path.is_file() { - SingleFileMessagePackBackingStore::new(&self.path).pull_all_read_only_snapshot()? - } else { - Vec::new() - }; - let current = unique_envelope(&entries, TOPOLOGY_PUBLISHER_WATERMARK_TYPE, target)?; - let stored = current - .map(|envelope| decode_publisher_watermark(target, &envelope.payload)) - .transpose()? - .unwrap_or(0); - // The stored correlation can be ahead of the mark on the first pass - // after this record was introduced, so take whichever is higher. - let next = stored - .max(prior) - .checked_add(1) - .context("Odin topology publisher sequence exhausted")?; - let replacement = publisher_watermark_envelope(target, next, &Utc::now().to_rfc3339())?; - if let Some(parent) = self.path.parent() { - std::fs::create_dir_all(parent)?; - } - if SingleFileMessagePackBackingStore::new(&self.path).compare_exchange( - &[CultCacheExpectedEnvelope { - key: target.into(), - r#type: TOPOLOGY_PUBLISHER_WATERMARK_TYPE.into(), - current: current.cloned(), - }], - &[replacement], - )? { - return Ok(next); - } - } - bail!("Odin topology store changed repeatedly while reserving a publisher sequence") + let stored = self + .records + .borrow() + .get(&(TOPOLOGY_PUBLISHER_WATERMARK_TYPE.to_owned(), target.to_owned())) + .map(|envelope| decode_publisher_watermark(target, &envelope.payload)) + .transpose()? + .unwrap_or(0); + // The stored correlation can be ahead of the mark on the first pass + // after this record was introduced, so take whichever is higher. + let next = stored + .max(prior) + .checked_add(1) + .context("Odin topology publisher sequence exhausted")?; + self.put(publisher_watermark_envelope( + target, + next, + &Utc::now().to_rfc3339(), + )?); + Ok(next) } } @@ -796,184 +871,177 @@ where dependencies: managed_dependency_incarnations(&projection.expected.dependencies), }; - for _ in 0..CAS_ATTEMPTS { - let observed = self.store.read(query.clone())?; - let admitted = self.select_presence(&observed, incoming, authority.as_ref())?; - let dependencies = - self.dependency_evidence(&projection.expected.dependencies, &observed, now)?; - let (presence, mut disagreements, replacement_presence) = match admitted { - SelectedPresence::None => (None, projection_disagreements.clone(), None), - SelectedPresence::Stale(stored) => { - let record = decode_presence(&stored.canonical_bytes)?; - let mut disagreements = projection_disagreements.clone(); - disagreements.push(OdinTopologyDisagreement { - code: "stored-presence-not-current".into(), - expected: projection - .activation - .as_ref() - .map(IdunnRuntimeActivationRecord::canonical_sha256) - .transpose()?, - observed: Some(record.activation_witness_sha256), - }); - (None, disagreements, None) - } - SelectedPresence::Current { - correlation, - replacement, - } => { - let mut disagreements = projection_disagreements.clone(); - disagreements.extend_from_slice(correlation.disagreements()); - (Some(correlation), disagreements, replacement) - } - }; - if let Some(disagreement) = &lease_disagreement { - disagreements.push(disagreement.clone()); - } - if presence.is_none() { + let observed = self.store.read(query)?; + let admitted = self.select_presence(&observed, incoming, authority.as_ref())?; + let dependencies = + self.dependency_evidence(&projection.expected.dependencies, &observed, now)?; + let (presence, mut disagreements, replacement_presence) = match admitted { + SelectedPresence::None => (None, projection_disagreements.clone(), None), + SelectedPresence::Stale(stored) => { + let record = decode_presence(&stored.canonical_bytes)?; + let mut disagreements = projection_disagreements.clone(); disagreements.push(OdinTopologyDisagreement { - code: "signed-presence-missing".into(), - expected: Some("dual-authenticated-runtime-presence".into()), - observed: None, + code: "stored-presence-not-current".into(), + expected: projection + .activation + .as_ref() + .map(IdunnRuntimeActivationRecord::canonical_sha256) + .transpose()?, + observed: Some(record.activation_witness_sha256), }); - disagreements.extend(projection.expected.capabilities.iter().enumerate().map( - |(index, capability)| OdinTopologyDisagreement { - code: format!("expected-capability-{index:03}-missing"), - expected: Some(format!( - "{}/{}/{} capacity>={}", - capability.capability, - capability.schema, - capability.compatibility, - capability.minimum_capacity - )), - observed: None, - }, - )); + (None, disagreements, None) } + SelectedPresence::Current { + correlation, + replacement, + } => { + let mut disagreements = projection_disagreements.clone(); + disagreements.extend_from_slice(correlation.disagreements()); + (Some(correlation), disagreements, replacement) + } + }; + if let Some(disagreement) = &lease_disagreement { + disagreements.push(disagreement.clone()); + } + if presence.is_none() { + disagreements.push(OdinTopologyDisagreement { + code: "signed-presence-missing".into(), + expected: Some("dual-authenticated-runtime-presence".into()), + observed: None, + }); + disagreements.extend(projection.expected.capabilities.iter().enumerate().map( + |(index, capability)| OdinTopologyDisagreement { + code: format!("expected-capability-{index:03}-missing"), + expected: Some(format!( + "{}/{}/{} capacity>={}", + capability.capability, + capability.schema, + capability.compatibility, + capability.minimum_capacity + )), + observed: None, + }, + )); + } - let observed_write_lease = if let Some(presence) = &presence { - correlate_write_lease( - &projection.expected, - lease_sha256.as_deref(), - presence.claim().record().write_lease_sha256.as_deref(), - &presence.claim().record().state, - &mut disagreements, - ) - } else { - None - }; - disagreements.sort_by(|left, right| left.code.cmp(&right.code)); + let observed_write_lease = if let Some(presence) = &presence { + correlate_write_lease( + &projection.expected, + lease_sha256.as_deref(), + presence.claim().record().write_lease_sha256.as_deref(), + &presence.claim().record().state, + &mut disagreements, + ) + } else { + None + }; + disagreements.sort_by(|left, right| left.code.cmp(&right.code)); - let prior = observed - .correlation + let prior = observed + .correlation + .as_ref() + .map(|stored| decode_correlation(&stored.canonical_bytes)) + .transpose()?; + let presence_record = presence.as_ref().map(|value| value.claim().record()); + let ready = presence_record.is_some_and(|record| record.state == "active") + && disagreements.is_empty() + && dependencies + .iter() + .all(|dependency| dependency_permits_ready(&dependency.kind, dependency.ready)); + let mut correlation = OdinRuntimeTopologyCorrelationRecord { + schema_version: ODIN_RUNTIME_TOPOLOGY_CORRELATION_SCHEMA.into(), + target: projection.expected.target.clone(), + expected_projection_sha256: projection.expected.canonical_sha256()?, + expected: true, + current_activation_sha256: projection + .activation .as_ref() - .map(|stored| decode_correlation(&stored.canonical_bytes)) - .transpose()?; - let presence_record = presence.as_ref().map(|value| value.claim().record()); - let ready = presence_record.is_some_and(|record| record.state == "active") - && disagreements.is_empty() - && dependencies - .iter() - .all(|dependency| dependency_permits_ready(&dependency.kind, dependency.ready)); - let mut correlation = OdinRuntimeTopologyCorrelationRecord { - schema_version: ODIN_RUNTIME_TOPOLOGY_CORRELATION_SCHEMA.into(), - target: projection.expected.target.clone(), - expected_projection_sha256: projection.expected.canonical_sha256()?, - expected: true, - current_activation_sha256: projection - .activation - .as_ref() - .map(IdunnRuntimeActivationRecord::canonical_sha256) - .transpose()?, - signed_presence_sha256: presence - .as_ref() - .map(|value| value.claim().signed_presence_sha256().into()), - observed_presence_state: presence_record.map(|record| record.state.clone()), - observed_presence_publisher_sequence: presence_record - .map(|record| record.publisher_sequence), - observed_write_lease_sha256: observed_write_lease, - observed_capabilities: presence_record - .map_or_else(Vec::new, |record| record.capabilities.clone()), - runtime_id: projection.expected.runtime_id.clone(), - runtime_instance_id: projection - .activation - .as_ref() - .map(|activation| activation.runtime_instance_id.clone()), - present: presence.is_some(), - ready, - dependencies, - disagreements, - signer_identity_id: self.signer.identity_id().into(), - // Placeholder. A sequence is only reserved once the facts are - // known to have changed, below; same_correlation_facts compares - // against the prior's sequence regardless of what sits here. - publisher_sequence: prior.as_ref().map_or(0, |record| record.publisher_sequence), - observed_at_unix_millis: now, - signature_algorithm: "ed25519".into(), - signature: Vec::new(), - }; - if let Some(prior) = &prior - && same_correlation_facts(prior, &correlation) - { - return Ok(observed - .correlation - .context("decoded prior correlation disappeared")? - .canonical_bytes); - } - // Reserved only after the dedupe: a refresh that observes nothing - // new must not burn a sequence or fsync the store. Reserved from a - // mark that survives withdrawal, not derived from the stored - // correlation, so a withdrawn correlation does not take the count - // with it. See TOPOLOGY_PUBLISHER_WATERMARK_SCHEMA. - correlation.publisher_sequence = self.store.reserve_publisher_sequence( - &observed.query.incarnation.target, - prior.as_ref().map_or(0, |record| record.publisher_sequence), - )?; - correlation.signature = self - .signer - .sign_correlation(&correlation.unsigned_signature_payload()?)?; - let canonical = correlation.canonical_bytes()?; - correlation.validate_against_expected(&projection.expected, lease_sha256.as_deref())?; - let (signed, unsigned) = - OdinRuntimeTopologyCorrelationRecord::decode_canonical_signed_payload(&canonical)?; - verify_service_identity_signature_with_public_key::< - OdinTopologyIdentity, - OdinRuntimeTopologyCorrelationPurpose, - >( + .map(IdunnRuntimeActivationRecord::canonical_sha256) + .transpose()?, + signed_presence_sha256: presence + .as_ref() + .map(|value| value.claim().signed_presence_sha256().into()), + observed_presence_state: presence_record.map(|record| record.state.clone()), + observed_presence_publisher_sequence: presence_record + .map(|record| record.publisher_sequence), + observed_write_lease_sha256: observed_write_lease, + observed_capabilities: presence_record + .map_or_else(Vec::new, |record| record.capabilities.clone()), + runtime_id: projection.expected.runtime_id.clone(), + runtime_instance_id: projection + .activation + .as_ref() + .map(|activation| activation.runtime_instance_id.clone()), + present: presence.is_some(), + ready, + dependencies, + disagreements, + signer_identity_id: self.signer.identity_id().into(), + // Placeholder. A sequence is only reserved once the facts are + // known to have changed, below; same_correlation_facts compares + // against the prior's sequence regardless of what sits here. + publisher_sequence: prior.as_ref().map_or(0, |record| record.publisher_sequence), + observed_at_unix_millis: now, + signature_algorithm: "ed25519".into(), + signature: Vec::new(), + }; + if let Some(prior) = &prior + && same_correlation_facts(prior, &correlation) + { + return Ok(observed + .correlation + .context("decoded prior correlation disappeared")? + .canonical_bytes); + } + // Reserved only after the dedupe: a refresh that observes nothing + // new must not burn a sequence or change the store. Reserved from a + // mark that survives withdrawal, not derived from the stored + // correlation, so a withdrawn correlation does not take the count + // with it. See TOPOLOGY_PUBLISHER_WATERMARK_SCHEMA. + correlation.publisher_sequence = self.store.reserve_publisher_sequence( + &observed.query.incarnation.target, + prior.as_ref().map_or(0, |record| record.publisher_sequence), + )?; + correlation.signature = self + .signer + .sign_correlation(&correlation.unsigned_signature_payload()?)?; + let canonical = correlation.canonical_bytes()?; + correlation.validate_against_expected(&projection.expected, lease_sha256.as_deref())?; + let (signed, unsigned) = + OdinRuntimeTopologyCorrelationRecord::decode_canonical_signed_payload(&canonical)?; + verify_service_identity_signature_with_public_key::< + OdinTopologyIdentity, + OdinRuntimeTopologyCorrelationPurpose, + >( + self.signer.public_key(), + &unsigned, + &ServiceIdentitySignature { + identity_id: signed.signer_identity_id, + signature: signed.signature, + }, + )?; + if let Some(authority) = &authority { + authenticate_odin_runtime_topology_correlation( + &canonical, + authority, + lease_sha256.as_deref(), self.signer.public_key(), - &unsigned, - &ServiceIdentitySignature { - identity_id: signed.signer_identity_id, - signature: signed.signature, + OdinTopologyAuthenticationContext { + trusted_received_at_unix_millis: now, + maximum_age_millis: self.policy.correlation_maximum_age_millis, + maximum_future_skew_millis: self + .policy + .correlation_maximum_future_skew_millis, }, )?; - if let Some(authority) = &authority { - authenticate_odin_runtime_topology_correlation( - &canonical, - authority, - lease_sha256.as_deref(), - self.signer.public_key(), - OdinTopologyAuthenticationContext { - trusted_received_at_unix_millis: now, - maximum_age_millis: self.policy.correlation_maximum_age_millis, - maximum_future_skew_millis: self - .policy - .correlation_maximum_future_skew_millis, - }, - )?; - } - let stored_correlation = StoredCorrelation { - canonical_bytes: canonical.clone(), - stored_at: rfc3339_millis(now)?, - }; - if self.store.compare_exchange( - &observed, - replacement_presence.as_ref(), - &stored_correlation, - )? { - return Ok(canonical); - } } - bail!("Odin topology store changed repeatedly during correlation") + let stored_correlation = StoredCorrelation { + canonical_bytes: canonical.clone(), + stored_at: rfc3339_millis(now)?, + }; + self.store + .commit(&observed.query, replacement_presence.as_ref(), &stored_correlation)?; + Ok(canonical) } fn select_presence( @@ -1619,22 +1687,6 @@ fn correlation_envelope(target: &str, correlation: &StoredCorrelation) -> CultCa } } -fn insert_condition( - conditions: &mut BTreeMap<(String, String), CultCacheExpectedEnvelope>, - condition: CultCacheExpectedEnvelope, -) -> Result<()> { - let identity = (condition.r#type.clone(), condition.key.clone()); - if let Some(current) = conditions.get(&identity) { - ensure!( - current.current == condition.current, - "store read set is incoherent" - ); - } else { - conditions.insert(identity, condition); - } - Ok(()) -} - fn rfc3339_millis(value: u64) -> Result { let value: i64 = value .try_into() @@ -1891,16 +1943,19 @@ mod tests { } /// A store the target-keyed Odin wrote holds correlations under bare - /// target keys. They are retired; presence history under any key stays. + /// target keys. They are retired from the loaded set; presence history + /// under any key stays. #[test] fn legacy_target_keyed_correlations_are_retired_and_presence_is_kept() -> Result<()> { let world = TestWorld::new()?; let service = world.service("ghostlight", Vec::new(), false)?; let presence = service.signed_presence(1, |_| {})?; - let engine = world.engine(NOW); - let correlation = engine.admit_presence("ghostlight", &presence, NOW)?; - let store = SingleFileMessagePackBackingStore::new(&world.topology_path); - let current = store.pull_all_read_only_snapshot()?; + let correlation = world + .engine(NOW) + .admit_presence("ghostlight", &presence, NOW)?; + assert!(world.store.flush()?); + let file = SingleFileMessagePackBackingStore::new(&world.topology_path); + let current = file.pull_all_read_only_snapshot()?; let mut with_legacy = current.clone(); with_legacy.push(CultCacheEnvelope { key: "ghostlight".into(), @@ -1916,23 +1971,21 @@ mod tests { stored_at: rfc3339_millis(NOW - 1_000)?, schema_id: Some(GAMECULT_RUNTIME_PRESENCE_HEALTH_SCHEMA.into()), }); - ensure!(store.compare_exchange_snapshot(¤t, &with_legacy)?); + ensure!(file.compare_exchange_snapshot(¤t, &with_legacy)?); - let odin_store = CultCacheOdinTopologyStore::new(&world.topology_path); - assert_eq!(odin_store.retire_legacy_correlations()?, 1); - assert_eq!(odin_store.retire_legacy_correlations()?, 0); - let after = store.pull_all_read_only_snapshot()?; - assert!(after.iter().all(|entry| { - entry.r#type != OdinRuntimeTopologyCorrelationRecord::TYPE - || IncarnationRef::parse_key(&entry.key).is_some() + let loaded = MemoryOdinTopologyStore::load(&world.topology_path)?; + assert_eq!(loaded.retire_legacy_correlations(), 1); + assert_eq!(loaded.retire_legacy_correlations(), 0); + let after = loaded.records(); + assert!(after.keys().all(|(record_type, key)| { + record_type != OdinRuntimeTopologyCorrelationRecord::TYPE + || IncarnationRef::parse_key(key).is_some() })); + assert!(after.keys().any(|(_, key)| key == "ghostlight/legacy-signer")); + drop(after); assert!( - after - .iter() - .any(|entry| entry.key == "ghostlight/legacy-signer") - ); - assert!( - engine + world + .engine_on(&loaded, NOW) .current_signed_correlation(&service.incarnation()?)? .is_some() ); @@ -1942,7 +1995,7 @@ mod tests { #[test] fn withdrawing_a_correlation_does_not_reset_its_publisher_sequence() -> Result<()> { let temp = TempDir::new()?; - let store = CultCacheOdinTopologyStore::new(temp.path().join("topology.cc")); + let store = MemoryOdinTopologyStore::load(temp.path().join("topology.cc"))?; assert_eq!(store.reserve_publisher_sequence("heimdall", 0)?, 1); assert_eq!(store.reserve_publisher_sequence("heimdall", 1)?, 2); @@ -1965,6 +2018,36 @@ mod tests { Ok(()) } + /// The store file is read once, when the store is loaded. Replaced behind + /// the loaded store with bytes that do not decode, it changes nothing the + /// store answers: admission, refresh and withdrawal all run from memory. + #[test] + fn a_loaded_store_never_reads_its_file_again() -> Result<()> { + let world = TestWorld::new()?; + let service = world.service("ghostlight", Vec::new(), false)?; + let engine = world.engine(NOW); + let first = engine.admit_presence("ghostlight", &service.signed_presence(1, |_| {})?, NOW)?; + assert!(world.store.flush()?); + + std::fs::write(&world.topology_path, b"not a cultcache store")?; + assert_eq!( + engine.current_signed_correlation(&service.incarnation()?)?, + Some(first) + ); + let second = decode_signed(&engine.admit_presence( + "ghostlight", + &service.signed_presence(2, |_| {})?, + NOW + 1, + )?)?; + assert_eq!(second.publisher_sequence, 2); + assert_eq!( + std::fs::read(&world.topology_path)?, + b"not a cultcache store", + "nothing was written without a flush" + ); + Ok(()) + } + #[derive(Clone, Copy)] struct FixedClock(u64); @@ -2050,6 +2133,7 @@ mod tests { _temp: TempDir, projection_path: PathBuf, topology_path: PathBuf, + store: MemoryOdinTopologyStore, identity_root: PathBuf, idunn_signer: ServiceIdentitySigner, idunn_anchor: ServiceIdentityTrustAnchor, @@ -2066,9 +2150,11 @@ mod tests { let idunn_anchor = idunn_signer.trust_anchor()?; let odin_signer = enroll_service_identity_at::(&identity_root.join("odin.cc"))?; + let topology_path = temp.path().join("odin-topology.cc"); Ok(Self { projection_path: temp.path().join("idunn-projection.cc"), - topology_path: temp.path().join("odin-topology.cc"), + store: MemoryOdinTopologyStore::load(&topology_path)?, + topology_path, identity_root, idunn_signer, idunn_anchor, @@ -2259,18 +2345,15 @@ mod tests { Ok(()) } - fn engine( - &self, - now: u64, - ) -> OdinTopologyAuthority< - CultCacheIdunnProjectionSource, - CultCacheOdinTopologyStore, - &ServiceIdentitySigner, - FixedClock, - > { + fn engine(&self, now: u64) -> TestEngine<'_> { + self.engine_on(&self.store, now) + } + + /// An engine over another store, as a restarted Odin loads one. + fn engine_on<'a>(&'a self, store: &'a MemoryOdinTopologyStore, now: u64) -> TestEngine<'a> { OdinTopologyAuthority::new( CultCacheIdunnProjectionSource::new(&self.projection_path), - CultCacheOdinTopologyStore::new(&self.topology_path), + store, &self.odin_signer, FixedClock(now), self.idunn_anchor.clone(), @@ -2314,6 +2397,13 @@ mod tests { } } + type TestEngine<'a> = OdinTopologyAuthority< + CultCacheIdunnProjectionSource, + &'a MemoryOdinTopologyStore, + &'a ServiceIdentitySigner, + FixedClock, + >; + fn digest(byte: char) -> String { format!("sha256-{}", byte.to_string().repeat(64)) } @@ -2455,19 +2545,9 @@ mod tests { let reused = service.signed_presence(2, |record| record.detail = "different".into())?; assert!(engine.admit_presence("ghostlight", &reused, NOW).is_err()); - let entries = SingleFileMessagePackBackingStore::new(&world.topology_path) - .pull_all_read_only_snapshot()?; - let stored = unique_envelope( - &entries, - GameCultRuntimePresenceHealthRecord::TYPE, - &presence_store_key( - &service.incarnation()?, - &service.projection.expected.expected_signer_identity_id, - ), - )? - .unwrap(); - assert_eq!(stored.payload, sequence_two); - assert_eq!(parse_rfc3339_millis(&stored.stored_at)?, NOW); + let (payload, stored_at) = stored_presence(&world, &service)?; + assert_eq!(payload, sequence_two); + assert_eq!(parse_rfc3339_millis(&stored_at)?, NOW); Ok(()) } @@ -2475,20 +2555,21 @@ mod tests { /// received at `NOW`, beyond the skew window, as on yggdrasil 2026-09-29. const RESTART: u64 = NOW + 10_000; + /// The service's presence as the store holds it: payload and receipt time. + fn stored_presence(world: &TestWorld, service: &TestService) -> Result<(Vec, String)> { + let key = presence_store_key( + &service.incarnation()?, + &service.projection.expected.expected_signer_identity_id, + ); + let records = world.store.records(); + let stored = records + .get(&(GameCultRuntimePresenceHealthRecord::TYPE.to_owned(), key)) + .context("no stored presence")?; + Ok((stored.payload.clone(), stored.stored_at.clone())) + } + fn stored_presence_payload(world: &TestWorld, service: &TestService) -> Result> { - let entries = SingleFileMessagePackBackingStore::new(&world.topology_path) - .pull_all_read_only_snapshot()?; - Ok(unique_envelope( - &entries, - GameCultRuntimePresenceHealthRecord::TYPE, - &presence_store_key( - &service.incarnation()?, - &service.projection.expected.expected_signer_identity_id, - ), - )? - .context("no stored presence")? - .payload - .clone()) + Ok(stored_presence(world, service)?.0) } #[test] @@ -2800,9 +2881,11 @@ mod tests { let first = world .engine(NOW) .admit_presence("ghostlight", &presence, NOW)?; + assert!(world.store.flush()?); + let restarted = MemoryOdinTopologyStore::load(&world.topology_path)?; let after_restart = world - .engine(NOW + 100) + .engine_on(&restarted, NOW + 100) .refresh(&service.incarnation()?)? .unwrap(); assert_eq!(after_restart, first); @@ -2831,12 +2914,11 @@ mod tests { .is_none() ); - let entries = SingleFileMessagePackBackingStore::new(&world.topology_path) - .pull_all_read_only_snapshot()?; - assert!(entries.iter().any(|entry| { + let records = world.store.records(); + assert!(records.values().any(|entry| { entry.r#type == GameCultRuntimePresenceHealthRecord::TYPE && entry.payload == presence })); - assert!(!entries.iter().any(|entry| { + assert!(!records.values().any(|entry| { entry.r#type == OdinRuntimeTopologyCorrelationRecord::TYPE && entry.key.starts_with("ghostlight@") })); diff --git a/crates/odin-daemon/src/main.rs b/crates/odin-daemon/src/main.rs index d7d5c39..92f3c96 100644 --- a/crates/odin-daemon/src/main.rs +++ b/crates/odin-daemon/src/main.rs @@ -12,9 +12,7 @@ use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; use anyhow::{Context, Result, bail, ensure}; use chrono::{DateTime, Utc}; -use cultcache_rs::{ - CultCacheEnvelope, CultCacheExpectedEnvelope, DatabaseEntry, SingleFileMessagePackBackingStore, -}; +use cultcache_rs::{CultCacheEnvelope, DatabaseEntry, SingleFileMessagePackBackingStore}; use cultmesh_rs::{ CultMeshRudpDocumentServer, CultMeshRudpDocumentServerOptions, CultMeshRudpPollOutcome, CultMeshRudpRawDocumentReceipt, CultMeshRudpRawDocumentSink, CultMeshRudpSnapshotQuery, @@ -34,9 +32,9 @@ use cultnet_rs::{ }; use fs2::FileExt; use odin_daemon::{ - AuthenticationPolicy, CultCacheIdunnProjectionSource, CultCacheOdinTopologyStore, - IdunnProjectionSource, IncarnationRef, OdinTopologyAuthority, PresenceAuthorityRefused, - ProjectionUnreadable, SystemClock, + AuthenticationPolicy, CultCacheIdunnProjectionSource, IdunnProjectionSource, IncarnationRef, + MemoryOdinTopologyStore, OdinTopologyAuthority, PresenceAuthorityRefused, ProjectionUnreadable, + SystemClock, }; const TARGET: &str = "odin"; @@ -73,14 +71,6 @@ const PROJECTION_REFRESH_INTERVAL: Duration = Duration::from_millis(250); const IDLE_POLL_INTERVAL: Duration = Duration::from_millis(2); const MAX_RECENT_WARMING_PROOFS: usize = 64; const WARMING_PROOF_LIFETIME_MILLIS: u64 = 60_000; -const CAS_ATTEMPTS: usize = 8; - -type TopologyAuthority = OdinTopologyAuthority< - CultCacheIdunnProjectionSource, - CultCacheOdinTopologyStore, - ServiceIdentitySigner, - SystemClock, ->; /// Relative path of Odin's durable store inside the state root. The recipe's /// `topology` state slot in `deployment/idunn/recipe.toml` is the authority for @@ -110,13 +100,43 @@ struct ProcessWriteLeaseGuard { sha256: String, } +/// Odin's topology authority once its write lease is held: the store it loaded +/// and the credentials that sign for it. An `OdinTopologyAuthority` is built +/// over it for each operation, with the projection read for that operation. +struct Topology { + store: MemoryOdinTopologyStore, + signer: ServiceIdentitySigner, + idunn_anchor: ServiceIdentityTrustAnchor, +} + +impl Topology { + fn authority( + &self, + projections: P, + ) -> OdinTopologyAuthority< + P, + &MemoryOdinTopologyStore, + &ServiceIdentitySigner, + SystemClock, + > { + OdinTopologyAuthority::new( + projections, + &self.store, + &self.signer, + SystemClock, + self.idunn_anchor.clone(), + AuthenticationPolicy::default(), + ) + } +} + struct RuntimeState { options: Options, candidate: SocketAddr, authority_material: RuntimeAuthority, idunn_anchor: Option, topology_signer: Option>, - topology: Option, + topology: Option, write_lease: Option, write_lease_path: PathBuf, recent_warming_proofs: VecDeque<(String, u64)>, @@ -198,14 +218,6 @@ impl RuntimeState { ) })?, )?; - let store_sequence = prior_self_publisher_sequence( - &options.store, - authority_material - .provider_signer - .entry() - .identity_id - .as_str(), - )?; Ok(Self { options, @@ -217,7 +229,7 @@ impl RuntimeState { write_lease: None, write_lease_path: PathBuf::from(required_environment(PROCESS_WRITE_LEASE_ENVIRONMENT)?), recent_warming_proofs: VecDeque::new(), - publisher_sequence: store_sequence, + publisher_sequence: 0, log_gate: RefCell::default(), }) } @@ -246,6 +258,18 @@ impl RuntimeState { if projected.current_lease.as_ref() != Some(&lease.record) { return Ok(false); } + // The one read of the store file while this process lives: from here + // on the working set is in memory, and the file is only written. + let store = MemoryOdinTopologyStore::load(&self.options.store)?; + // Correlations the previous, target-keyed Odin left in this store are + // not this contract's and would otherwise be served to the Verse as + // current. Presence history is kept: the self publisher sequence + // continues from it. + store.retire_legacy_correlations(); + let stored_sequence = prior_self_publisher_sequence( + store.records().values(), + &self.authority_material.provider_signer.entry().identity_id, + ); let signer = self .topology_signer .take() @@ -254,18 +278,28 @@ impl RuntimeState { .idunn_anchor .take() .context("Idunn trust anchor was already consumed")?; + self.publisher_sequence = self.publisher_sequence.max(stored_sequence); self.write_lease = Some(lease); - self.topology = Some(OdinTopologyAuthority::new( - CultCacheIdunnProjectionSource::new(&self.options.idunn_projection), - CultCacheOdinTopologyStore::new(&self.options.store), + self.topology = Some(Topology { + store, signer, - SystemClock, idunn_anchor, - AuthenticationPolicy::default(), - )); + }); Ok(true) } + fn topology(&self) -> Result<&Topology> { + self.topology + .as_ref() + .context("Odin topology authority is absent") + } + + /// Write Odin's store file from the working set, if it changed. + fn flush(&self) -> Result<()> { + self.topology()?.store.flush()?; + Ok(()) + } + fn accept_raw_document(&mut self, receipt: CultMeshRudpRawDocumentReceipt) -> Result<()> { ensure!( self.activated(), @@ -273,10 +307,11 @@ impl RuntimeState { ); validate_raw_document_shape(&receipt.document)?; if receipt.document.schema_id == GAMECULT_RUNTIME_PRESENCE_HEALTH_SCHEMA { - return self - .admit_presence_document(&receipt.document, receipt.received_at_unix_millis); + self.admit_presence_document(&receipt.document, receipt.received_at_unix_millis)?; + } else { + persist_generic_document(&self.topology()?.store, &receipt.document)?; } - persist_generic_document(&self.options.store, &receipt.document) + self.flush() } /// The one admission path for a runtime-presence document, whether a @@ -291,10 +326,13 @@ impl RuntimeState { document.record_key == presence.target, "runtime-presence document key differs from its signed target" ); - self.topology - .as_ref() - .context("Odin topology authority is absent")? - .admit_presence(&presence.target, &document.payload, received_at_unix_millis)?; + let projections = + CultCacheIdunnProjectionSource::new(&self.options.idunn_projection).snapshot()?; + self.topology()?.authority(projections).admit_presence( + &presence.target, + &document.payload, + received_at_unix_millis, + )?; Ok(()) } @@ -423,7 +461,8 @@ impl RuntimeState { self.require_current_write_lease()?; self.require_own_projection()?; let document = self.signed_presence_document("active", detail)?; - self.admit_presence_document(&document, unix_millis()?) + self.admit_presence_document(&document, unix_millis()?)?; + self.flush() } /// Idunn's projection of this process's own incarnation. A failure to @@ -473,31 +512,29 @@ impl RuntimeState { Ok(()) } - fn refresh_all_correlations(&mut self) -> Result<()> { + /// Refresh every incarnation Idunn projects, and every incarnation Odin + /// holds a correlation for, projected or not (the latter are refreshed so + /// their correlations are withdrawn). The projection is read once for the + /// whole pass. + fn refresh_all_correlations(&self) -> Result<()> { self.require_current_write_lease()?; - let topology = self - .topology - .as_ref() - .context("Odin topology authority is absent")?; - let mut incarnations = incarnation_keys( - &self.options.idunn_projection, - IdunnExpectedIncarnationRecord::TYPE, - )?; - incarnations.extend(incarnation_keys( - &self.options.store, - OdinRuntimeTopologyCorrelationRecord::TYPE, - )?); + let topology = self.topology()?; + let projections = + CultCacheIdunnProjectionSource::new(&self.options.idunn_projection).snapshot()?; + let mut incarnations = projections.incarnations(); + incarnations.extend(topology.store.correlated_incarnations()); + let authority = topology.authority(projections); // Each incarnation is refreshed on its own: one whose records cannot be // read is that incarnation's failure, and never stops the others. for incarnation in incarnations { - if let Err(error) = topology.refresh(&incarnation) { + if let Err(error) = authority.refresh(&incarnation) { self.log_repeating( &format!("refresh of incarnation {}", incarnation.key()), format!("failed; the rest are unaffected: {error:#}"), ); } } - Ok(()) + self.flush() } /// The catalog serves what is stored, one record at a time: a record that @@ -510,15 +547,10 @@ impl RuntimeState { &self, query: &CultMeshRudpSnapshotQuery, ) -> Result> { - let entries = if self.options.store.is_file() { - SingleFileMessagePackBackingStore::new(&self.options.store) - .pull_all_read_only_snapshot()? - } else { - Vec::new() - }; + let records = self.topology()?.store.records(); let projections = CultCacheIdunnProjectionSource::new(&self.options.idunn_projection); let mut selected = BTreeMap::new(); - for envelope in &entries { + for envelope in records.values() { let document = match self.public_document(&projections, envelope) { Ok(Some(document)) => document, Ok(None) => continue, @@ -730,10 +762,6 @@ fn main() -> Result<()> { } } - // Correlations the previous, target-keyed Odin left in this store are not - // this contract's and would otherwise be served to the Verse as current. - // Presence history is kept: the self publisher sequence continues from it. - CultCacheOdinTopologyStore::new(&state.borrow().options.store).retire_legacy_correlations()?; // Once serving, only losing the write lease ends Odin (see `survive`). let mut timers = ServingTimers::default(); loop { @@ -1181,12 +1209,11 @@ fn read_process_write_lease(path: &Path) -> Result Result { - if !path.is_file() { - return Ok(0); - } - Ok(SingleFileMessagePackBackingStore::new(path) - .pull_all_read_only_snapshot()? +fn prior_self_publisher_sequence<'a>( + records: impl IntoIterator, + signer_identity_id: &str, +) -> u64 { + records .into_iter() .filter(|entry| { entry.r#type == GameCultRuntimePresenceHealthRecord::TYPE @@ -1207,7 +1234,7 @@ fn prior_self_publisher_sequence(path: &Path, signer_identity_id: &str) -> Resul }) .map(|presence| presence.publisher_sequence) .max() - .unwrap_or(0)) + .unwrap_or(0) } /// The document namespaces providers publish to the rendezvous. A provider's @@ -1263,49 +1290,23 @@ fn is_peer_document_type(document_type: &str) -> bool { }) } -fn persist_generic_document(path: &Path, document: &CultNetRawDocumentRecord) -> Result<()> { +fn persist_generic_document( + store: &MemoryOdinTopologyStore, + document: &CultNetRawDocumentRecord, +) -> Result<()> { let document_type = document_type_for_schema(&document.schema_id)?; ensure!( is_peer_document_type(&document_type), "Odin accepts no {document_type} document from a provider" ); - let replacement = CultCacheEnvelope { + store.put(CultCacheEnvelope { key: document.record_key.clone(), - r#type: document_type.clone(), + r#type: document_type, payload: document.payload.clone(), stored_at: document.stored_at.clone(), schema_id: Some(document.schema_id.clone()), - }; - let store = SingleFileMessagePackBackingStore::new(path); - for _ in 0..CAS_ATTEMPTS { - let entries = if path.is_file() { - store.pull_all_read_only_snapshot()? - } else { - Vec::new() - }; - let mut matches = entries - .iter() - .filter(|entry| entry.r#type == document_type && entry.key == document.record_key); - let current = matches.next().cloned(); - ensure!( - matches.next().is_none(), - "generic CultCache identity is ambiguous" - ); - if current.as_ref() == Some(&replacement) { - return Ok(()); - } - if store.compare_exchange( - &[CultCacheExpectedEnvelope { - key: document.record_key.clone(), - r#type: document_type.clone(), - current, - }], - &[replacement.clone()], - )? { - return Ok(()); - } - } - bail!("Odin catalog changed repeatedly while persisting a provider document") + }); + Ok(()) } fn document_type_for_schema(schema_id: &str) -> Result { @@ -1349,28 +1350,6 @@ fn decode_presence(payload: &[u8]) -> Result Result> { - if !path.is_file() { - return Ok(BTreeSet::new()); - } - Ok(SingleFileMessagePackBackingStore::new(path) - .pull_all_read_only_snapshot()? - .into_iter() - .filter(|entry| entry.r#type == record_type) - .filter_map(|entry| IncarnationRef::parse_key(&entry.key)) - .collect()) -} - fn validate_snapshot_filters(query: &CultMeshRudpSnapshotQuery) -> Result<()> { ensure!( !query.message_id.is_empty() && query.message_id.trim() == query.message_id, @@ -1615,6 +1594,16 @@ mod tests { /// The same world with the production server bound under `options`. fn activated_odin_serving(options: CultMeshRudpDocumentServerOptions) -> Result { + activated_odin_with(options, |_| Ok(Vec::new())) + } + + /// The same world, with Odin's store file holding what `seed` returns when + /// Odin activates. `seed` runs before the lease is granted, with the + /// runtime that is about to activate, so it can sign Odin's own presences. + fn activated_odin_with( + options: CultMeshRudpDocumentServerOptions, + seed: impl FnOnce(&mut RuntimeState) -> Result>, + ) -> Result { let temp = tempfile::tempdir()?; let root = temp.path(); let socket = UdpSocket::bind("127.0.0.1:0")?; @@ -1712,6 +1701,13 @@ mod tests { publisher_sequence: 0, log_gate: RefCell::default(), }; + let seeded = seed(&mut runtime)?; + if !seeded.is_empty() { + ensure!( + SingleFileMessagePackBackingStore::new(&store).compare_exchange_snapshot(&[], &seeded)?, + "test store seed failed" + ); + } // The lease names the Warming presence Odin signed for Idunn's probe. let warming = runtime.signed_presence_document("warming", "test warming")?; @@ -1861,18 +1857,33 @@ mod tests { }) } + /// Every record in Odin's working set. + fn working_set(&self) -> Vec { + let state = self.state.borrow(); + let records = state.topology.as_ref().unwrap().store.records(); + records.values().cloned().collect() + } + + /// Every record in Odin's store file. + fn file_records(&self) -> Result> { + SingleFileMessagePackBackingStore::new(&self.store).pull_all_read_only_snapshot() + } + fn stored_keys(&self, record_type: &str) -> Result> { - Ok(SingleFileMessagePackBackingStore::new(&self.store) - .pull_all_read_only_snapshot()? + Ok(self + .working_set() .into_iter() .filter(|entry| entry.r#type == record_type) .map(|entry| entry.key) .collect()) } - /// Odin's own publisher sequence as it is durably stored. + /// Odin's own publisher sequence as its store holds it. fn stored_sequence(&self) -> Result { - prior_self_publisher_sequence(&self.store, &self.provider_identity_id) + Ok(prior_self_publisher_sequence( + &self.working_set(), + &self.provider_identity_id, + )) } /// Run a peer on its own thread while Odin polls its socket, and nothing @@ -1991,6 +2002,7 @@ mod tests { odin.pass()?; assert!(odin.stored_sequence()? > 0, "the first pass publishes"); + let written = std::fs::read(&odin.store)?; std::fs::write(&odin.store, b"not a cultcache store")?; assert!( odin.state @@ -2014,12 +2026,13 @@ mod tests { ); } - std::fs::remove_file(&odin.store)?; + std::fs::write(&odin.store, written)?; odin.timers = ServingTimers::default(); odin.pass()?; - assert!( - odin.stored_sequence()? > 0, - "the publication after the fault clears lands" + assert_eq!( + odin.file_records()?, + odin.working_set(), + "the write after the fault clears lands" ); Ok(()) } @@ -2235,24 +2248,25 @@ mod tests { /// A stored presence of Odin's own activation that no longer authenticates /// makes its publisher sequence unknowable; the claim is refused, closed. + /// The store is Odin's alone while it serves, so the bad record is in the + /// file when Odin activates. #[test] fn a_stored_presence_that_no_longer_authenticates_ends_odin() -> Result<()> { - let mut odin = activated_odin()?; - odin.pass()?; - // Received two minutes after it was observed: outside the trusted window. - let late = rfc3339_millis(unix_millis()? + 120_000)?; - odin.tamper_store(|entries| { - entries - .into_iter() - .map(|mut entry| { - if entry.r#type == GameCultRuntimePresenceHealthRecord::TYPE { - entry.stored_at = late.clone(); - } - entry - }) - .collect() + let mut odin = activated_odin_with(CultMeshRudpDocumentServerOptions::default(), |runtime| { + let warming = runtime.signed_presence_document("warming", "earlier launch")?; + // Received two minutes after it was observed: outside the trusted window. + Ok(vec![CultCacheEnvelope { + key: format!( + "{}/{}", + self_incarnation(&runtime.authority_material).key(), + runtime.authority_material.provider_signer.entry().identity_id + ), + r#type: GameCultRuntimePresenceHealthRecord::TYPE.into(), + payload: warming.payload, + stored_at: rfc3339_millis(unix_millis()? + 120_000)?, + schema_id: Some(GAMECULT_RUNTIME_PRESENCE_HEALTH_SCHEMA.into()), + }]) })?; - odin.timers = ServingTimers::default(); assert_refused(&odin.pass().unwrap_err()); Ok(()) } @@ -2337,42 +2351,55 @@ mod tests { /// One record that does not decode is skipped where it is met: the catalog /// still serves everything else, and startup still finds Odin's sequence. + /// The records are in the file when Odin activates. #[test] fn records_that_do_not_decode_never_stop_the_catalog_or_startup() -> Result<()> { - let mut odin = activated_odin()?; - odin.pass()?; - let before = odin.stored_sequence()?; - assert!(before > 0); - let stamp = rfc3339_millis(unix_millis()?)?; - let own_signer = odin.provider_identity_id.clone(); - odin.tamper_store(|mut entries| { - for key in [ - "ghost".to_owned(), - format!("{TARGET}@{}/{own_signer}", digest('c')), - ] { - entries.push(CultCacheEnvelope { - key, + const EARLIER: u64 = 41; + let mut odin = activated_odin_with(CultMeshRudpDocumentServerOptions::default(), |runtime| { + let own_signer = runtime + .authority_material + .provider_signer + .entry() + .identity_id + .clone(); + let stamp = rfc3339_millis(unix_millis()?)?; + let bad_presence = |key: String| CultCacheEnvelope { + key, + r#type: GameCultRuntimePresenceHealthRecord::TYPE.into(), + payload: vec![0xc1], + stored_at: stamp.clone(), + schema_id: Some(GAMECULT_RUNTIME_PRESENCE_HEALTH_SCHEMA.into()), + }; + // A presence an earlier incarnation of Odin stored, counted to 41. + runtime.publisher_sequence = EARLIER - 1; + let earlier = runtime.signed_presence_document("warming", "earlier incarnation")?; + runtime.publisher_sequence = 0; + Ok(vec![ + bad_presence("ghost".into()), + bad_presence(format!("{TARGET}@{}/{own_signer}", digest('c'))), + CultCacheEnvelope { + key: format!("{TARGET}@{}/{own_signer}", digest('d')), r#type: GameCultRuntimePresenceHealthRecord::TYPE.into(), - payload: vec![0xc1], + payload: earlier.payload, stored_at: stamp.clone(), schema_id: Some(GAMECULT_RUNTIME_PRESENCE_HEALTH_SCHEMA.into()), - }); - } - entries.push(generic_document().unwrap()); - entries + }, + generic_document()?, + ]) })?; let catalog = odin.catalog()?; assert_eq!( documents_of(&catalog, GAMECULT_RUNTIME_PRESENCE_HEALTH_SCHEMA), 1, - "Odin's own presence is served" + "the presence that decodes is served" ); assert_eq!(documents_of(&catalog, "ghostlight.doc.v1"), 1); + odin.pass()?; assert_eq!( - prior_self_publisher_sequence(&odin.store, &odin.provider_identity_id)?, - before, - "the undecodable presences do not change the sequence Odin continues from" + odin.stored_sequence()?, + EARLIER + 1, + "Odin continues from the sequence it found past the undecodable presences" ); Ok(()) } @@ -2383,10 +2410,7 @@ mod tests { fn a_presence_whose_projection_cannot_be_read_is_skipped_not_fatal() -> Result<()> { let mut odin = activated_odin()?; odin.pass()?; - odin.tamper_store(|mut entries| { - entries.push(generic_document().unwrap()); - entries - })?; + provider_put(&odin, "ghostlight.doc.v1", "doc-1", vec![1])?; odin.tamper_projection(|entries| { entries .into_iter() @@ -2613,8 +2637,7 @@ mod tests { let mut odin = activated_odin()?; odin.pass()?; let before = odin.stored_sequence()?; - let stored_before = - SingleFileMessagePackBackingStore::new(&odin.store).pull_all_read_only_snapshot()?; + let stored_before = odin.working_set(); // Every kind Odin itself stored (its watermark and correlations, found // rather than named), and the kinds Idunn projects to it. @@ -2650,7 +2673,7 @@ mod tests { assert!(format!("{refused:#}").contains("accepts no"), "{refused:#}"); } assert_eq!( - SingleFileMessagePackBackingStore::new(&odin.store).pull_all_read_only_snapshot()?, + odin.working_set(), stored_before, "no refused put touched the store" ); @@ -2672,12 +2695,11 @@ mod tests { let mut odin = activated_odin()?; odin.pass()?; provider_put(&odin, "ghostlight.doc.v1", "doc-1", vec![1])?; - let stored: BTreeSet = - SingleFileMessagePackBackingStore::new(&odin.store) - .pull_all_read_only_snapshot()? - .into_iter() - .map(|entry| entry.r#type) - .collect(); + let stored: BTreeSet = odin + .working_set() + .into_iter() + .map(|entry| entry.r#type) + .collect(); assert!( stored.len() >= 4, "Odin's store holds more than what it serves: {stored:?}" @@ -2912,4 +2934,62 @@ mod tests { assert!(!settle_poll(fault(), &mut since, restart).unwrap()); assert!(settle_poll(fault(), &mut since, restart + POLL_FAILURE_LIMIT).is_err()); } + + // ---- the store file is not working memory ----------------------------- + + /// Once Odin holds its lease, its working set is in memory. Rewriting the + /// store file behind its back changes nothing Odin serves or refreshes; + /// only a restart, which loads the file again, would see it. + #[test] + fn rewriting_the_store_file_behind_odin_changes_nothing_it_serves() -> Result<()> { + let mut odin = activated_odin()?; + provider_put(&odin, "ghostlight.doc.v1", "doc-1", vec![1])?; + odin.pass()?; + let served = odin.catalog()?; + let working = odin.working_set(); + assert_eq!(documents_of(&served, "ghostlight.doc.v1"), 1); + + odin.tamper_store(|entries| { + let mut entries: Vec<_> = entries + .into_iter() + .filter(|entry| entry.r#type == "odin.topology_publisher_watermark") + .collect(); + let mut foreign = generic_document().unwrap(); + foreign.key = "foreign".into(); + entries.push(foreign); + entries + })?; + for _ in 0..3 { + odin.state.borrow().refresh_all_correlations()?; + } + assert_eq!(odin.catalog()?, served); + assert_eq!(odin.working_set(), working); + assert_ne!( + MemoryOdinTopologyStore::load(&odin.store)?.records().len(), + working.len(), + "a restart would load what the file now holds" + ); + Ok(()) + } + + /// Refresh passes and catalog reads never read the store file. With the + /// file replaced by bytes that do not decode, a reader would fail at once; + /// every pass succeeds and logs nothing. + #[test] + fn refresh_passes_and_catalog_reads_never_read_the_store_file() -> Result<()> { + let mut odin = activated_odin()?; + provider_put(&odin, "ghostlight.doc.v1", "doc-1", vec![1])?; + odin.pass()?; + let served = odin.catalog()?; + std::fs::write(&odin.store, b"not a cultcache store")?; + for _ in 0..5 { + odin.state.borrow().refresh_all_correlations()?; + assert_eq!(odin.catalog()?, served); + } + assert!( + odin.state.borrow().log_gate.borrow().seen.is_empty(), + "a pass failed and was logged" + ); + Ok(()) + } }