From 9650bf71975805e0d196741adefe035f8a90f2a2 Mon Sep 17 00:00:00 2001 From: repo-worker-code-k Date: Sun, 8 Nov 2026 05:20:48 -0600 Subject: [PATCH] feat(id): persist event bodies, retrieve by ID, carry in range sync (#4837) Port of PR #7657 commit 8ae8bd294d onto main across the pkgs/id crate split: FORMAT v9 bodies table, EventStore::event_body/stored_body, ingest_with_body, range-sync body carriage. StoreError::MissingBody lands in id-store event_types.rs; the SharedEventStore range_body/range_ingest_with_bodies surface lands in id-store store_traits.rs over the generic EventStoreBackend seam (new stored_body/ingest_events_with_bodies backend methods, delegated by the id-events impl); ingest reconciled with the current flow (body passed through to ingest_event, writer-body retention and device ops unchanged); ported test constructor gains the chat field main added to ChainExt. --- .../id-events/src/event_store/ingest.rs | 199 +++++++++++++++++- .../crates/id-events/src/event_store/mod.rs | 60 +++++- .../crates/id-events/src/event_store/sync.rs | 140 ++++++++++-- pkgs/id/crates/id-store/src/event_types.rs | 7 + pkgs/id/crates/id-store/src/store_traits.rs | 35 ++- 5 files changed, 407 insertions(+), 34 deletions(-) diff --git a/pkgs/id/crates/id-events/src/event_store/ingest.rs b/pkgs/id/crates/id-events/src/event_store/ingest.rs index 61b064d15e..7824548b99 100644 --- a/pkgs/id/crates/id-events/src/event_store/ingest.rs +++ b/pkgs/id/crates/id-events/src/event_store/ingest.rs @@ -100,6 +100,7 @@ use super::waiting_rows::{Hold, Mirror}; use super::{ ACTIONS, APPLIED, CHAINS, Chain, DEVICE_OPS, EVENTS, EventStore, FORKS, ForkProof, HASHES, PROOF_HEADERS, PROOF_IDS, StoreError, corrupt, decode_stored, lowest_proof, position_key, + store_body, store_chain, store_event, store_fork, }; use super::{Ingest, Refusal}; @@ -211,7 +212,7 @@ impl EventStore { Err(refusal) => return Ok(Ingest::Refused(refusal)), } }; - let result = self.ingest_event(event, action.as_ref(), now_ms)?; + let result = self.ingest_event(event, action.as_ref(), body, now_ms)?; if let Some(body) = retain_body && !matches!(result, Ingest::Refused(_)) { @@ -270,7 +271,7 @@ impl EventStore { Ok(event) => event, Err(err) => return Ok(Ingest::Refused(Refusal::Malformed(err.to_string()))), }; - self.ingest_event(event, action, now_ms) + self.ingest_event(event, action, None, now_ms) } /// Runs a decoded event through the store's transaction, with its action. @@ -278,10 +279,12 @@ impl EventStore { &mut self, event: Event, action: Option<&GroupAction>, + body: Option<&[u8]>, now_ms: u64, ) -> Result { self.transact(now_ms, |mirror| { - let (staged, changed) = ingest_in(mirror, event, action, now_ms, Labels::AsStored)?; + let (staged, changed) = + ingest_in(mirror, event, action, body, now_ms, Labels::AsStored)?; Ok((staged.finish(mirror.txn)?, changed)) }) } @@ -301,18 +304,73 @@ impl EventStore { events: Vec, now_ms: u64, ) -> Result, StoreError> { + let events = events.into_iter().map(|event| (event, None)).collect(); + self.ingest_events_inner(events, now_ms) + } + + /// Decides already verified events with their bodies, in order, in one write transaction, + /// as [`EventStore::ingest_events`]. Each body is checked against its event's signed + /// header (BLAKE3 hash and size) before anything is stored: a body that is not the + /// committed one refuses its event in place and stores nothing. This is the range-sync + /// receiver's entry point — sync carries the body of an event whose header commits + /// to one. + pub(crate) fn ingest_events_with_bodies( + &mut self, + events: Vec<(Event, Option>)>, + now_ms: u64, + ) -> Result, StoreError> { + let mut refusals: Vec> = Vec::with_capacity(events.len()); + let mut accepted: Vec<(Event, Option>)> = Vec::with_capacity(events.len()); + for (event, body) in events { + match body { + Some(body) if committed(&event, &body).is_err() => { + refusals.push(Some(Ingest::Refused(Refusal::Malformed( + "the body is not the one the header commits to, by hash and size" + .to_owned(), + )))); + } + body => { + refusals.push(None); + accepted.push((event, body)); + } + } + } + let mut stored = self.ingest_events_inner(accepted, now_ms)?.into_iter(); + let mut outcomes = Vec::with_capacity(refusals.len()); + for refusal in refusals { + outcomes.push(match refusal { + None => stored + .next() + .ok_or_else(|| corrupt("a batch lost an outcome"))?, + Some(refused) => refused, + }); + } + Ok(outcomes) + } + + /// The shared batch path of [`EventStore::ingest_events`] and + /// [`EventStore::ingest_events_with_bodies`]: decides the events in one transaction, + /// storing each event's verified body with it. + fn ingest_events_inner( + &mut self, + events: Vec<(Event, Option>)>, + now_ms: u64, + ) -> Result, StoreError> { + let fork_check: Vec = events.iter().map(|(event, _body)| event.clone()).collect(); self.transact(now_ms, |mirror| { - let labels = if batch_may_fork(mirror, &events)? { + let labels = if batch_may_fork(mirror, &fork_check)? { Labels::AsStored } else { Labels::AtEnd }; - // Batches come from sync, which carries no bodies. A group operation's action is - // attached later, when its body arrives (`attach_action`). + // Bodies are stored with their events, but a group operation's action is not + // derived from a batch body: it is attached later, when the body arrives through + // the production path (`attach_action`). let mut staged = Vec::with_capacity(events.len()); let mut changed = false; - for event in events { - let (outcome, did_change) = ingest_in(mirror, event, None, now_ms, labels)?; + for (event, body) in events { + let (outcome, did_change) = + ingest_in(mirror, event, None, body.as_deref(), now_ms, labels)?; changed |= did_change; staged.push(outcome); } @@ -563,6 +621,7 @@ fn ingest_in( m: &mut Mirror<'_>, event: Event, action: Option<&GroupAction>, + body: Option<&[u8]>, now: u64, labels: Labels, ) -> Result<(Staged, bool), StoreError> { @@ -570,7 +629,7 @@ fn ingest_in( let id = event.id; let author = author_of(&event); let rivals = held_rivals(m.pool, &event); - let settled = settle(m, event, action, &rivals, now, false, labels)?; + let settled = settle(m, event, action, body, &rivals, now, false, labels)?; let attached = matches!(settled, Settled::Duplicate { attached: true }); let changed = expired > 0 || attached @@ -628,6 +687,7 @@ fn settle( m: &mut Mirror<'_>, event: Event, action: Option<&GroupAction>, + body: Option<&[u8]>, rivals: &[Event], now: u64, from_pool: bool, @@ -639,6 +699,9 @@ fn settle( if let Some(action) = action { store_action(m.txn, &id, action)?; } + if let Some(body) = body { + store_body(m.txn, &id, body)?; + } // In a store with no group state every stored event applies, so the label is known // now, whatever the batch does later. Otherwise the label waits for the resolution. let applied = match labels { @@ -663,8 +726,19 @@ fn settle( } Decision::Duplicate => { drop_released(m, &event, from_pool)?; + // A body that arrives after its event was stored header-only is stored now: + // the header commits to it by hash and size, so it is the author's body. + // Storing it counts as attached, so the call commits: a duplicate that + // changed nothing would have its transaction aborted. + let mut stored_body = false; + if let Some(body) = body { + if is_stored(m.txn, &id)? { + store_body(m.txn, &id, body)?; + stored_body = true; + } + } Settled::Duplicate { - attached: attach_action(m.txn, &id, action)?, + attached: attach_action(m.txn, &id, action)? || stored_body, } } Decision::Fork { seq, proof } => { @@ -695,6 +769,9 @@ fn settle( if let Some(action) = action { store_action(m.txn, &id, action)?; } + if let Some(body) = body { + store_body(m.txn, &id, body)?; + } } held(hold) } @@ -704,6 +781,9 @@ fn settle( if let Some(action) = action { store_action(m.txn, &id, action)?; } + if let Some(body) = body { + store_body(m.txn, &id, body)?; + } } held(hold) } @@ -757,7 +837,7 @@ fn drain( let id = event.id; let rivals = held_rivals(m.pool, &event); let action = stored_action(m.txn, &id)?; - match settle(m, event, action.as_ref(), &rivals, now, true, labels)? { + match settle(m, event, action.as_ref(), None, &rivals, now, true, labels)? { Settled::Stored { applied, released } => { // A label that is not read yet keeps the event as a candidate. Its label decides // whether it stays in the list, once the batch has resolved. @@ -1204,6 +1284,103 @@ mod tests { } /// Ingests every event in order, and checks each one was accepted. + /// A signed event whose header commits to `body`, with the production path's + /// extension shape for a plain content event. + fn event_with_body( + key: &SigningKey, + seq: SeqNum, + backlink: Option, + body: &[u8], + ) -> Event { + let ext = ChainExt { + kind: "message".to_owned(), + group: None, + after: Vec::new(), + tag: None, + document: None, + removes: None, + note: None, + link: None, + checkpoint: None, + rotation: None, + chat: None, + }; + sign(key, seq, backlink, Some(body), ext).unwrap() + } + + #[test] + fn test_a_body_is_stored_at_ingest_and_read_back_byte_identically() { + let (_dir, mut store) = open(); + let signer = key(41); + let body = b"generic event body bytes"; + let event = event_with_body(&signer, 0, None, body); + let outcome = store.ingest_with_body(&event.bytes, Some(body), 0).unwrap(); + assert!(matches!(outcome, Ingest::Accepted { .. }), "{outcome:?}"); + assert_eq!(store.event_body(&event.id).unwrap(), body.as_slice()); + } + + #[test] + fn test_a_missing_body_is_a_typed_not_found() { + let (_dir, mut store) = open(); + let signer = key(42); + // A header-only event is stored, but it has no body row. + let plain = event(&signer, 0, None, Vec::new(), "message"); + ingest(&mut store, &plain); + assert!(matches!( + store.event_body(&plain.id), + Err(StoreError::MissingBody { id }) if id == plain.id + )); + // An event the store has never seen is the same typed not-found. + let unseen = event_with_body(&signer, 1, Some(plain.id), b"never arrived"); + assert!(matches!( + store.event_body(&unseen.id), + Err(StoreError::MissingBody { .. }) + )); + } + + #[test] + fn test_a_body_arriving_after_its_header_is_stored() { + let (_dir, mut store) = open(); + let signer = key(43); + let body = b"late body"; + let event = event_with_body(&signer, 0, None, body); + // First stored without its body, then the body arrives with the same header. + let outcome = store.ingest_with_body(&event.bytes, None, 0).unwrap(); + assert!(matches!(outcome, Ingest::Accepted { .. }), "{outcome:?}"); + assert!(matches!( + store.event_body(&event.id), + Err(StoreError::MissingBody { .. }) + )); + let outcome = store.ingest_with_body(&event.bytes, Some(body), 0).unwrap(); + assert!(matches!(outcome, Ingest::Duplicate { .. }), "{outcome:?}"); + assert_eq!(store.event_body(&event.id).unwrap(), body.as_slice()); + } + + #[test] + fn test_a_batch_body_that_is_not_the_committed_one_refuses_its_event() { + let (_dir, mut store) = open(); + let signer = key(44); + let body = b"committed body"; + let event = event_with_body(&signer, 0, None, body); + let outcomes = store + .ingest_events_with_bodies(vec![(event.clone(), Some(b"forged body".to_vec()))], 0) + .unwrap(); + assert!(matches!(outcomes[0], Ingest::Refused(_)), "{outcomes:?}"); + assert!(matches!( + store.event_body(&event.id), + Err(StoreError::MissingBody { .. }) + )); + // The committed body in a batch is stored. + let outcomes = store + .ingest_events_with_bodies(vec![(event.clone(), Some(body.to_vec()))], 0) + .unwrap(); + assert!( + matches!(outcomes[0], Ingest::Accepted { .. }), + "{outcomes:?}" + ); + assert_eq!(store.event_body(&event.id).unwrap(), body.as_slice()); + } + fn ingest_all(store: &mut EventStore, events: &[Event]) { for event in events { assert_eq!( diff --git a/pkgs/id/crates/id-events/src/event_store/mod.rs b/pkgs/id/crates/id-events/src/event_store/mod.rs index 346264e51a..7ab9835eac 100644 --- a/pkgs/id/crates/id-events/src/event_store/mod.rs +++ b/pkgs/id/crates/id-events/src/event_store/mod.rs @@ -7,6 +7,8 @@ //! accepted event is here, including events past a fork point, which are kept //! but not applied. //! - `hashes`: an event's ID to its position. +//! - `bodies`: an event's ID to its body bytes, for the events whose headers commit to a +//! body (see [`EventStore::event_body`]). A header-only event has no row. //! - `chains`: an author to the applied prefix of their chain: the next sequence //! number, the hash of the last applied event, and the frozen flag. //! - `forks`: a fork proof, keyed by its fork point's position: the two headers that conflict at @@ -180,7 +182,7 @@ use id_store::event_types::{be_u64, corrupt, hash_of, seq_num}; pub const TEMP_NAME: &str = "events.redb.tmp"; /// The format row in `meta`. A store with another format is refused. -const FORMAT: &[u8] = b"id.events.store.v8"; +const FORMAT: &[u8] = b"id.events.store.v9"; const FORMAT_KEY: &[u8] = b"format"; const EVENTS: TableDefinition<'static, &'static [u8], &'static [u8]> = @@ -228,6 +230,12 @@ const DEVICE_OPS: TableDefinition<'static, &'static [u8], &'static [u8]> = /// The IDs of the applied events, with an empty value. Written by the resolution. const APPLIED: TableDefinition<'static, &'static [u8], &'static [u8]> = TableDefinition::new("applied"); +/// The body of each event whose header commits to one, by event ID. Written at ingest, +/// when the body is present and verified against the header; read back by +/// [`EventStore::event_body`] and carried by range sync. A header-only event, and an +/// event whose body never arrived, has no row. +const BODIES: TableDefinition<'static, &'static [u8], &'static [u8]> = + TableDefinition::new("bodies"); /// Bytes in a position key: the author, then the sequence number. const POSITION_LEN: usize = 40; @@ -558,6 +566,33 @@ impl EventStore { stored.map(|bytes| decode_stored(bytes.value())).transpose() } + /// The stored body of the event with this ID, byte-identical to the body the author's + /// header commits to. Bodies are stored at ingest when present (see + /// [`EventStore::ingest_with_body`]) and carried by range sync. + /// + /// # Errors + /// + /// Returns [`StoreError::MissingBody`] when the event is header-only, its body never + /// arrived, or no event with this ID is stored; a redb error if the read fails. + pub fn event_body(&self, id: &Hash) -> Result, StoreError> { + let txn = self.db.begin_read()?; + let bodies = txn.open_table(BODIES)?; + match bodies.get(id.as_bytes().as_slice())? { + Some(body) => Ok(body.value().to_vec()), + None => Err(StoreError::MissingBody { id: *id }), + } + } + + /// The stored body of the event with this ID, or `None` when there is none. The range + /// sync sender's view of [`EventStore::event_body`]: a missing body is not an error + /// there, the event simply travels without one, as it did before bodies were carried. + pub(crate) fn stored_body(&self, id: &Hash) -> Result>, StoreError> { + let txn = self.db.begin_read()?; + let bodies = txn.open_table(BODIES)?; + let stored = bodies.get(id.as_bytes().as_slice())?; + Ok(stored.map(|body| body.value().to_vec())) + } + /// The fork proof that freezes `author`'s chain: the one at the author's lowest fork point, if /// the author has forked. Proofs at higher points are kept as well, and this does not return /// them. @@ -1201,6 +1236,7 @@ fn initialize(db: &Database) -> Result<(), StoreError> { txn.open_multimap_table(WAITING_BY_DEP)?; txn.open_table(ACTIONS)?; txn.open_table(APPLIED)?; + txn.open_table(BODIES)?; txn.open_table(BLOCKS)?; let mut meta = txn.open_table(META)?; meta.insert(FORMAT_KEY, FORMAT)?; @@ -1224,6 +1260,7 @@ fn verify_schema(db: &Database) -> Result<(), StoreError> { txn.open_multimap_table(WAITING_BY_DEP).map_err(missing)?; txn.open_table(ACTIONS).map_err(missing)?; txn.open_table(APPLIED).map_err(missing)?; + txn.open_table(BODIES).map_err(missing)?; let meta = txn.open_table(META).map_err(missing)?; match meta.get(FORMAT_KEY)? { Some(found) if found.value() == FORMAT => Ok(()), @@ -1346,6 +1383,15 @@ pub(crate) fn store_event(txn: &WriteTransaction, event: &Event) -> Result<(), S Ok(()) } +/// Stores the verified body of an event, by event ID. The caller has checked the body +/// against the header's commitment (hash and size); a body already stored is replaced by +/// the same bytes, because only the committed body ever passes that check. +pub(crate) fn store_body(txn: &WriteTransaction, id: &Hash, body: &[u8]) -> Result<(), StoreError> { + let mut bodies = txn.open_table(BODIES)?; + bodies.insert(id.as_bytes().as_slice(), body)?; + Ok(()) +} + /// Writes an author's chain row. pub(crate) fn store_chain( txn: &WriteTransaction, @@ -1967,6 +2013,18 @@ impl id_store::store_traits::EventStoreBackend for EventStore { self.ingest_events(events, now_ms) } + fn ingest_events_with_bodies( + &mut self, + events: Vec<(Event, Option>)>, + now_ms: u64, + ) -> Result, StoreError> { + self.ingest_events_with_bodies(events, now_ms) + } + + fn stored_body(&self, id: &Hash) -> Result>, StoreError> { + self.stored_body(id) + } + fn sync_entries(&self) -> Result, StoreError> { self.sync_entries() } diff --git a/pkgs/id/crates/id-events/src/event_store/sync.rs b/pkgs/id/crates/id-events/src/event_store/sync.rs index 4bc0386f9c..f23c42fdda 100644 --- a/pkgs/id/crates/id-events/src/event_store/sync.rs +++ b/pkgs/id/crates/id-events/src/event_store/sync.rs @@ -272,8 +272,16 @@ pub trait RangeStore { /// The bytes of one event, as [`EventStore::sync_bytes`]. fn sync_bytes(&self, id: &Id) -> Result>>; - /// Decides one batch in one write transaction, as [`EventStore::ingest_events`]. - fn ingest_events(&mut self, events: Vec, now_ms: u64) -> Result>; + /// The stored body of one event, as [`EventStore::stored_body`]. + fn sync_body(&self, id: &Id) -> Result>>; + + /// Decides one batch with bodies in one write transaction, as + /// [`EventStore::ingest_events_with_bodies`]. + fn ingest_with_bodies( + &mut self, + events: Vec<(Event, Option>)>, + now_ms: u64, + ) -> Result>; } impl RangeStore for EventStore { @@ -285,8 +293,19 @@ impl RangeStore for EventStore { Ok(EventStore::sync_bytes(self, id)?) } - fn ingest_events(&mut self, events: Vec, now_ms: u64) -> Result> { - Ok(EventStore::ingest_events(self, events, now_ms)?) + fn sync_body(&self, id: &Id) -> Result>> { + Ok(EventStore::stored_body( + self, + &p2panda_core::Hash::from_bytes(*id), + )?) + } + + fn ingest_with_bodies( + &mut self, + events: Vec<(Event, Option>)>, + now_ms: u64, + ) -> Result> { + Ok(EventStore::ingest_events_with_bodies(self, events, now_ms)?) } } @@ -299,8 +318,16 @@ impl RangeStore for Shared { Ok(self.range_bytes(id)?) } - fn ingest_events(&mut self, events: Vec, now_ms: u64) -> Result> { - Ok(self.range_ingest_events(events, now_ms)?) + fn sync_body(&self, id: &Id) -> Result>> { + Ok(self.range_body(id)?) + } + + fn ingest_with_bodies( + &mut self, + events: Vec<(Event, Option>)>, + now_ms: u64, + ) -> Result> { + Ok(self.range_ingest_with_bodies(events, now_ms)?) } } @@ -399,6 +426,43 @@ fn sync_key(position: &[u8], id: &Id) -> Result { Ok(key) } +/// One data-phase record: the event's bytes, then its body when the sender holds one. +/// The event length prefixes the record, so the body is the rest; an absent body is an +/// empty rest. The header commits to the body by hash and size, and the receiver checks +/// the body against that commitment before storing it, so a body can never be attached +/// to the wrong event. +fn encode_record(event: &[u8], body: Option<&[u8]>) -> Result> { + let mut record = Vec::with_capacity(4 + event.len() + body.map_or(0, <[u8]>::len)); + record.extend_from_slice(&u32::try_from(event.len())?.to_be_bytes()); + record.extend_from_slice(event); + if let Some(body) = body { + record.extend_from_slice(body); + } + Ok(record) +} + +/// Splits one data-phase record into the event's bytes and the body it carried, if any. +fn decode_record(record: &[u8]) -> Result<(Vec, Option>)> { + let len: [u8; 4] = record + .get(..4) + .context("a record is shorter than its length prefix")? + .try_into()?; + let len = u32::from_be_bytes(len) as usize; + let event = record + .get(4..4 + len) + .context("a record names more event bytes than it holds")? + .to_vec(); + let body = &record[4 + len..]; + Ok(( + event, + if body.is_empty() { + None + } else { + Some(body.to_vec()) + }, + )) +} + async fn write_frame(send: &mut SendStream, payload: &[u8]) -> Result { ensure!( payload.len() <= range::FRAME_CAP, @@ -527,11 +591,11 @@ fn lock<'a, 'b, S: RangeStore>(store: &'a Mutex<&'b mut S>) -> Result( store: &mut S, - events: Vec, + events: Vec<(Event, Option>)>, now_ms: u64, tally: &mut Tally, ) -> Result<()> { - for outcome in store.ingest_events(events, now_ms)? { + for outcome in store.ingest_with_bodies(events, now_ms)? { tally.add(&outcome); } Ok(()) @@ -669,10 +733,15 @@ async fn run_session( bail!("cut before event {}", sent + 1); } } - let record = lock(&store)? - .sync_bytes(id)? - .context("an offered event is no longer stored")?; - bytes += write_frame(&mut *send, &record).await?; + let (record, body) = { + let guard = lock(&store)?; + let record = guard + .sync_bytes(id)? + .context("an offered event is no longer stored")?; + let body = guard.sync_body(id)?; + (record, body) + }; + bytes += write_frame(&mut *send, &encode_record(&record, body.as_deref())?).await?; } applied.notified().await; bytes += write_frame(&mut *send, APPLIED_FRAME).await?; @@ -734,13 +803,21 @@ async fn receive_data( "peer offers {count} events, and {} are missing here", need.len() ); - let mut pending: Vec = Vec::with_capacity(BATCH_EVENTS); + let mut pending: Vec<(Event, Option>)> = Vec::with_capacity(BATCH_EVENTS); let mut pending_bytes: usize = 0; let mut tally = Tally::default(); for _ in 0..count { let record = read_frame(recv).await?; let record_len = record.len(); - let event = chain::decode(&record)?; + let (event_bytes, body) = decode_record(&record)?; + let event = chain::decode(&event_bytes)?; + if let Some(body) = &body { + ensure!( + event.header.payload_hash == Some(p2panda_core::Hash::digest(body)) + && u32::try_from(body.len()).is_ok_and(|len| len == event.header.payload_size), + "a synced body is not the one the header commits to, by hash and size" + ); + } ensure!( need.remove(event.id.as_bytes()), "an event arrived that was not expected, or arrived twice" @@ -753,7 +830,7 @@ async fn receive_data( flush(store, &mut pending, now_ms, &mut tally, commits)?; pending_bytes = 0; } - pending.push(event); + pending.push((event, body)); pending_bytes += record_len; if pending.len() == BATCH_EVENTS { flush(store, &mut pending, now_ms, &mut tally, commits)?; @@ -766,7 +843,7 @@ async fn receive_data( fn flush( store: &Mutex<&mut S>, - pending: &mut Vec, + pending: &mut Vec<(Event, Option>)>, now_ms: u64, tally: &mut Tally, commits: &Option, @@ -1101,6 +1178,36 @@ mod tests { assert_eq!(da.received + db.received, 0); } + /// Range sync carries the body of an event whose header commits to one: the + /// receiver stores it, verified against the signed header, and reads it back + /// byte-identically. + #[tokio::test(flavor = "multi_thread")] + async fn test_range_sync_carries_event_bodies() { + let (_da, mut a) = open(); + let (_db, mut b) = open(); + let body = b"body carried by sync"; + let events = chain_of(7, 2, body); + for event in &events { + let outcome = a.ingest_with_body(&event.bytes, Some(body), NOW).unwrap(); + assert!(matches!(outcome, Ingest::Accepted { .. }), "{outcome:?}"); + assert_eq!(a.event_body(&event.id).unwrap(), body.as_slice()); + } + let (da, db) = loopback( + &mut a, + &mut b, + Params::default(), + Params::default(), + Cut::Never, + ) + .await + .unwrap(); + da.unwrap(); + db.unwrap(); + for event in &events { + assert_eq!(b.event_body(&event.id).unwrap(), body.as_slice()); + } + } + #[test] fn test_sync_set_holds_stored_events_and_fork_proof_headers_once() { let (_d, mut store) = open(); @@ -1179,6 +1286,7 @@ mod tests { batch.extend(chain_of(n, 1, b"unrelated")); } let mut tally = Tally::default(); + let batch = batch.into_iter().map(|event| (event, None)).collect(); apply_batch(&mut store, batch, NOW, &mut tally).unwrap(); assert_eq!(tally.forks, 1); assert_eq!( diff --git a/pkgs/id/crates/id-store/src/event_types.rs b/pkgs/id/crates/id-store/src/event_types.rs index f9a705b6bd..6f7371b7fc 100644 --- a/pkgs/id/crates/id-store/src/event_types.rs +++ b/pkgs/id/crates/id-store/src/event_types.rs @@ -61,6 +61,13 @@ pub enum StoreError { /// The sequence number that is taken. seq: SeqNum, }, + /// The event has no stored body: it is header-only, its body never arrived, or no event + /// with this ID is stored. The typed not-found of the event-body retrieval API. + #[error("event {id} has no stored body")] + MissingBody { + /// The ID of the event whose body was asked for. + id: Hash, + }, /// A write failed, and the waiting events could not be rebuilt from disk. The store /// refuses further calls. Reopening it rebuilds them. #[error("event store is unusable after a failed write: reopen it")] diff --git a/pkgs/id/crates/id-store/src/store_traits.rs b/pkgs/id/crates/id-store/src/store_traits.rs index c9beb8eaa6..e494a009fe 100644 --- a/pkgs/id/crates/id-store/src/store_traits.rs +++ b/pkgs/id/crates/id-store/src/store_traits.rs @@ -73,6 +73,14 @@ pub trait EventStoreBackend: std::fmt::Debug + Send + Sync + 'static { events: Vec, now_ms: u64, ) -> Result, StoreError>; + /// See `EventStore::ingest_events_with_bodies`. + fn ingest_events_with_bodies( + &mut self, + events: Vec<(Event, Option>)>, + now_ms: u64, + ) -> Result, StoreError>; + /// See `EventStore::stored_body`. + fn stored_body(&self, id: &Hash) -> Result>, StoreError>; /// See `EventStore::sync_entries`. fn sync_entries(&self) -> Result, StoreError>; /// See `EventStore::sync_bytes`. @@ -254,23 +262,38 @@ impl SharedEventStore { self.read(|store| Ok(store.sync_bytes(id)?)) } - /// Decides a batch of received events in one write transaction, under the write - /// lock, taken for this one call. See [`EventStore::ingest_events`]. + /// The stored body of the event with this ID, under the read lock, taken for this + /// one call. See [`EventStore::stored_body`]. /// /// # Errors /// - /// Returns [`TraitStoreError::Store`] for the first mismatch, or a redb error, and + /// Returns [`TraitStoreError::Store`] for a redb or corruption error, and /// [`TraitStoreError::Poisoned`] if another thread panicked while it held the lock. - pub fn range_ingest_events( + pub fn range_body( &self, - events: Vec, + id: &crate::range::Id, + ) -> Result>, TraitStoreError> { + self.read(|store| Ok(store.stored_body(&Hash::from_bytes(*id))?)) + } + + /// Decides a batch of received events with their bodies in one write transaction, + /// under the write lock, taken for this one call. See + /// [`EventStore::ingest_events_with_bodies`]. + /// + /// # Errors + /// + /// Returns [`TraitStoreError::Store`] for a redb error or corruption error, and + /// [`TraitStoreError::Poisoned`] if another thread panicked while it held the lock. + pub fn range_ingest_with_bodies( + &self, + events: Vec<(Event, Option>)>, now_ms: u64, ) -> Result, TraitStoreError> { let mut store = self .inner .write() .map_err(|_err| TraitStoreError::Poisoned)?; - Ok(store.ingest_events(events, now_ms)?) + Ok(store.ingest_events_with_bodies(events, now_ms)?) } /// Checks the store's own rows. See [`EventStore::check_invariants`].