diff --git a/pkgs/id/src/event_store/range.rs b/pkgs/id/src/event_store/range.rs index 83f0c1240e..2e080534cf 100644 --- a/pkgs/id/src/event_store/range.rs +++ b/pkgs/id/src/event_store/range.rs @@ -40,10 +40,12 @@ pub type Id = [u8; 32]; pub const DEFAULT_K: usize = 16; /// The default leaf threshold. pub const DEFAULT_T: usize = 16; -/// The largest frame the transport accepts, in bytes. -pub const FRAME_CAP: usize = 16 << 20; -/// The default byte budget for one frame: a quarter of the cap, so one frame is never near it. -pub const DEFAULT_FRAME_BUDGET: usize = 4 << 20; +/// The largest frame the sync stream carries. The stream is the world transport's, which caps a +/// frame at `MAX_FRAME_BYTES` (1 MiB). `log_sync`'s test checks that the two agree. The S7 harness +/// ran with 16 MiB, and chunking is the same at either size. +pub const FRAME_CAP: usize = 1 << 20; +/// The default byte budget for one frame: half the cap, so a frame is never near it. +pub const DEFAULT_FRAME_BUDGET: usize = FRAME_CAP / 2; /// The smallest budget that fits an entry. const MIN_FRAME_BUDGET: usize = 256; /// Bytes reserved in a frame for its `more` flag and its entry count. @@ -683,9 +685,9 @@ mod tests { } #[test] - fn test_params_default_is_k16_t16_with_the_four_mib_budget() { + fn test_params_default_is_k16_t16_with_half_the_frame_cap() { let p = Params::default(); - assert_eq!((p.k(), p.t(), p.frame_budget()), (16, 16, 4 << 20)); + assert_eq!((p.k(), p.t(), p.frame_budget()), (16, 16, FRAME_CAP / 2)); } #[test] diff --git a/pkgs/id/src/event_store/sync.rs b/pkgs/id/src/event_store/sync.rs index 4979ca4fbf..55a9b0031d 100644 --- a/pkgs/id/src/event_store/sync.rs +++ b/pkgs/id/src/event_store/sync.rs @@ -1,24 +1,29 @@ -//! Range sync over the event store, on `/id-sync/1`. +//! Range sync over the event store: the method that `/id-sync/1` runs after the handshake. //! -//! The sync set is every stored event and every fork proof header, one key each: the author, -//! the sequence number, and the ID (see [`super::range`]). A session has three phases: +//! The handshake is [`crate::log_sync`]'s: the initiator sends a `Request` with the topic and the +//! method it chose, and the responder answers. When both agree on range, [`run_range`] runs on the +//! stream they share. The sync set is the topic's authors' events, the same authors LogSync +//! resolves (see [`SharedEventStore::range_entries`]): each stored event and each fork proof header, +//! one key each (see [`super::range`]). A session has three phases: //! -//! 1. **Reconciliation.** Messages alternate as flights of frames until one side answers with -//! only skips. The dialer opens the stream and sends the full range's fingerprint. -//! 2. **Data.** Each side knows the symmetric difference, so it knows what the peer lacks and -//! what it holds that the peer lacks. Each side sends its events in key order: a count -//! frame, then one frame per event. Both sides send at once. -//! 3. **Apply.** The receiver verifies each event, checks it was expected, and decides the -//! events in batches, in one write transaction per batch, as the store's ingest does. +//! 1. **Reconciliation.** Messages alternate as flights of frames until one side answers with only +//! skips. The initiator sends the full range's fingerprint first. +//! 2. **Data.** Each side knows the symmetric difference, so it knows what the peer lacks. Each +//! side sends the events it has that the peer lacks, in key order: a count frame, then one +//! frame per event. Both sides send at once. +//! 3. **Apply.** The receiver verifies each event, checks that it was expected, and decides the +//! events in batches. A batch is one write transaction, and a fork in it is an outcome like any +//! other, so the events after it are decided too (P3.1a). //! -//! K and T are local. The frame budget is local too: it only has to stay under the frame cap. +//! K, T, and the frame budget are local. The peer never sees them. use std::collections::HashSet; -use std::sync::{Mutex, MutexGuard}; use anyhow::{Context, Result, anyhow, bail, ensure}; -use iroh::endpoint::{Connection, RecvStream, SendStream}; +use iroh::endpoint::SendStream; +use p2panda_core::Hash; use redb::{ReadableDatabase, ReadableTable}; +use tokio::sync::mpsc; use super::range::{ self, Entry, Id, Key, Params, Party, all_skip, check_bounds, decode_frame, frames, @@ -28,10 +33,15 @@ use super::{ position_key, }; use crate::chain::{self, Event}; +use crate::store_traits::SharedEventStore; use crate::waiting::AuthorKey; -/// The protocol ID. The wire version only; K and T are not in it. -pub const ALPN: &[u8] = b"/id-sync/1"; +/// Bytes in a position key: the author, then the sequence number. +const POSITION_LEN: usize = 40; + +/// The receiving half of a sync stream, as the handshake's reader task delivers it: whole frames, +/// or the error that ended the stream. +pub(crate) type Inbound = mpsc::Receiver, String>>; /// The most messages one side writes in reconciliation before it gives up. const MAX_FLIGHTS: u32 = 10_000; @@ -39,9 +49,6 @@ const MAX_FLIGHTS: u32 = 10_000; /// Events the receiver decides in one write transaction. const BATCH_EVENTS: usize = 256; -/// Bytes in a position key: the author, then the sequence number. -const POSITION_LEN: usize = 40; - /// What one session did on this side. #[derive(Debug, Default, Clone, PartialEq, Eq)] pub struct Outcome { @@ -80,7 +87,7 @@ struct Tally { } impl Tally { - fn add(&mut self, outcome: &Ingest) { + const fn add(&mut self, outcome: &Ingest) { match outcome { Ingest::Accepted { .. } => self.accepted += 1, Ingest::Duplicate { .. } => self.duplicates += 1, @@ -91,234 +98,53 @@ impl Tally { } } -/// Where to cut the connection, for the interruption test. The cut closes the connection. +/// Where to cut a session, for the interruption test. A cut finishes this side's send half early, +/// so the peer reads what was sent and then sees the stream end, and this session returns an error. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) enum Cut { /// No cut. Never, - /// Close before this side writes message `n + 1`. + /// Cut before this side writes message `n + 1`. AfterFlights(u32), - /// Close before this side writes event `n + 1`. + /// Cut before this side writes event `n + 1`. AfterRecords(usize), } -/// Runs one range session over an open connection. The dialer opens the stream and passes -/// `initiator = true`. `now_ms` is the clock the store's waiting rules use. +/// Runs one range session on the stream a `Request` agreed on. `initiator` sends the first +/// message. `now_ms` is the clock the store's waiting rules use. The session syncs the events of +/// `topic`'s authors on this side, as LogSync does. /// /// # Errors /// -/// Returns an error if the peer breaks the protocol, a frame is malformed or too large, an -/// event fails verification, the session does not end within the flight limit, or the -/// connection fails. -pub async fn sync_over( - store: &mut EventStore, - conn: &Connection, - initiator: bool, - params: Params, - now_ms: u64, -) -> Result { - run(store, conn, initiator, params, now_ms, Cut::Never).await -} - -impl EventStore { - /// The sync set, sorted by key: each stored event, and each fork proof header, once. - /// - /// # Errors - /// - /// Returns a redb error if the read fails, or [`StoreError::Corrupt`]. - pub(crate) fn sync_entries(&self) -> Result, StoreError> { - let txn = self.db.begin_read()?; - let hashes = txn.open_table(HASHES)?; - let forks = txn.open_table(FORKS)?; - let mut entries: Vec<(Key, Id)> = Vec::new(); - for row in hashes.iter()? { - let (id, position) = row?; - let id = id_of(id.value())?; - entries.push((sync_key(position.value(), &id)?, id)); - } - for row in forks.iter()? { - let (_author, proof) = row?; - let proof = decode_proof(proof.value())?; - for header in [&proof.first, &proof.second] { - let author = *header.header.verifying_key.as_bytes(); - let position = position_key(&author, header.header.seq_num); - let id = *header.id.as_bytes(); - entries.push((sync_key(&position, &id)?, id)); - } - } - entries.sort_unstable_by_key(|e| e.0); - entries.dedup_by(|a, b| a.0 == b.0); - Ok(entries) - } - - /// The encoded bytes of the event with this ID, if the store holds it as a stored event or as - /// a current fork proof header. - /// - /// # Errors - /// - /// Returns a redb error if the read fails, or [`StoreError::Corrupt`]. - pub(crate) fn sync_bytes(&self, id: &Id) -> Result>, StoreError> { - let txn = self.db.begin_read()?; - let hashes = txn.open_table(HASHES)?; - if let Some(position) = hashes.get(id.as_slice())? { - let events = txn.open_table(EVENTS)?; - let stored = events.get(position.value())?; - return Ok(stored.map(|bytes| bytes.value().to_vec())); - } - let proof_ids = txn.open_table(PROOF_IDS)?; - let Some(author) = proof_ids.get(id.as_slice())? else { - return Ok(None); - }; - let author: AuthorKey = author - .value() - .try_into() - .map_err(|_err| corrupt("a proof ID names no author"))?; - let forks = txn.open_table(FORKS)?; - let Some(row) = forks.get(author.as_slice())? else { - return Ok(None); - }; - let proof = decode_proof(row.value())?; - Ok([proof.first, proof.second] - .into_iter() - .find(|header| header.id.as_bytes() == id) - .map(|header| header.bytes)) - } -} - -fn id_of(bytes: &[u8]) -> Result { - bytes - .try_into() - .map_err(|_err| corrupt("an event ID is not 32 bytes")) -} - -/// The sync key of an event: its position (author and sequence number), then its ID. -fn sync_key(position: &[u8], id: &Id) -> Result { - if position.len() != POSITION_LEN { - return Err(corrupt("a position key has the wrong length")); - } - let mut key = [0u8; range::KEY_LEN]; - key[..POSITION_LEN].copy_from_slice(position); - key[POSITION_LEN..].copy_from_slice(id); - Ok(key) -} - -async fn write_frame(send: &mut SendStream, payload: &[u8]) -> Result { - ensure!( - payload.len() <= range::FRAME_CAP, - "frame of {} bytes is over the cap", - payload.len() - ); - let len = u32::try_from(payload.len())?; - send.write_all(&len.to_be_bytes()).await?; - send.write_all(payload).await?; - Ok(4 + payload.len()) -} - -async fn read_frame(recv: &mut RecvStream) -> Result> { - let mut len = [0u8; 4]; - recv.read_exact(&mut len).await?; - let len = u32::from_be_bytes(len) as usize; - ensure!(len <= range::FRAME_CAP, "frame announces {len} bytes"); - let mut buf = vec![0u8; len]; - recv.read_exact(&mut buf).await?; - Ok(buf) -} - -/// Writes one message as frames, or closes the connection if the cut is due. -async fn write_flight( - send: &mut SendStream, - conn: &Connection, - out: &mut Outcome, - msg: &[Entry], +/// Returns an error if the peer breaks the protocol, a frame is malformed or too large, an event +/// fails verification, the session does not end within the flight limit, or the stream fails. +#[allow(clippy::too_many_arguments)] +pub(crate) async fn run_range( + store: &SharedEventStore, + topic: Hash, params: Params, - cut: Cut, -) -> Result<()> { - if cut == Cut::AfterFlights(out.flights) { - conn.close(1u32.into(), b"cut"); - bail!("cut before flight {}", out.flights + 1); - } - for frame in frames(msg, params.frame_budget())? { - out.control_bytes += write_frame(send, &frame).await?; - } - out.flights += 1; - Ok(()) -} - -/// Reads frames until one without the `more` flag, and returns the message's entries. -async fn read_flight(recv: &mut RecvStream) -> Result> { - let mut entries = Vec::new(); - loop { - let (more, mut part) = decode_frame(&read_frame(recv).await?)?; - entries.append(&mut part); - if !more { - break; - } - } - check_bounds(&entries)?; - Ok(entries) -} - -/// Locks the store for one step. The lock is never held across an await. -fn lock<'a, 'b>( - store: &'a Mutex<&'b mut EventStore>, -) -> Result> { - store - .lock() - .map_err(|_err| anyhow!("the event store lock is poisoned")) -} - -/// Decides one batch in one write transaction, and tallies each outcome. A fork is an outcome -/// like any other: it is recorded, and the events after it in the batch are still decided. Only -/// an error from the store ends the batch, and then nothing in it commits. -fn apply_batch( - store: &mut EventStore, - events: Vec, now_ms: u64, - tally: &mut Tally, -) -> Result<()> { - for outcome in store.ingest_events(events, now_ms)? { - tally.add(&outcome); - } - Ok(()) -} - -async fn run( - store: &mut EventStore, - conn: &Connection, initiator: bool, - params: Params, - now_ms: u64, + send: &mut SendStream, + inbound: &mut Inbound, cut: Cut, ) -> Result { - let (mut send, mut recv) = if initiator { - conn.open_bi().await? - } else { - conn.accept_bi().await? - }; + let party = Party::new(store.range_entries(&topic)?)?; let mut out = Outcome::default(); - let party = Party::new(store.sync_entries()?)?; - // 1. Reconciliation. The same loop as S7's session, with each message as frames. + // 1. Reconciliation, the same loop as S7's session, with each message as frames. let mut learned: Vec = Vec::new(); if initiator { - write_flight( - &mut send, - conn, - &mut out, - &[party.full_range()], - params, - cut, - ) - .await?; + write_flight(send, &mut out, &[party.full_range()], params, cut).await?; } loop { - let incoming = read_flight(&mut recv).await?; + let incoming = read_flight(inbound).await?; if all_skip(&incoming) { break; } let reply = party.respond(&incoming, params, &mut learned); let last = all_skip(&reply); - write_flight(&mut send, conn, &mut out, &reply, params, cut).await?; + write_flight(send, &mut out, &reply, params, cut).await?; if last { break; } @@ -343,27 +169,25 @@ async fn run( .copied() .collect(); out.learned = learned; - let store = Mutex::new(store); let sending = async { let count = u32::try_from(offers.len())?; - let mut bytes = write_frame(&mut send, &count.to_be_bytes()).await?; + let mut bytes = send_frame(send, &count.to_be_bytes()).await?; for (sent, id) in offers.iter().enumerate() { if cut == Cut::AfterRecords(sent) { - conn.close(1u32.into(), b"cut"); + end_early(send); bail!("cut before event {}", sent + 1); } - let record = lock(&store)? + let record = store .sync_bytes(id)? .context("an offered event is no longer stored")?; - bytes += write_frame(&mut send, &record).await?; + bytes += send_frame(send, &record).await?; } - send.finish()?; anyhow::Ok(bytes) }; let receiving = async { - let count_frame = read_frame(&mut recv).await?; + let count_frame = next_frame(inbound).await?; let count: [u8; 4] = count_frame .as_slice() .try_into() @@ -377,7 +201,7 @@ async fn run( let mut pending: Vec = Vec::with_capacity(BATCH_EVENTS); let mut tally = Tally::default(); for _ in 0..count { - let record = read_frame(&mut recv).await?; + let record = next_frame(inbound).await?; let event = chain::decode(&record)?; ensure!( need.remove(event.id.as_bytes()), @@ -385,10 +209,10 @@ async fn run( ); pending.push(event); if pending.len() == BATCH_EVENTS { - flush(&store, &mut pending, now_ms, &mut tally)?; + apply_batch(store, std::mem::take(&mut pending), now_ms, &mut tally)?; } } - flush(&store, &mut pending, now_ms, &mut tally)?; + apply_batch(store, pending, now_ms, &mut tally)?; anyhow::Ok((count, tally)) }; @@ -405,71 +229,211 @@ async fn run( Ok(out) } -fn flush( - store: &Mutex<&mut EventStore>, - pending: &mut Vec, +/// Decides one batch in one write transaction, and tallies each outcome. A fork is an outcome +/// like any other: it is recorded, and the events after it are still decided. Only an error from +/// the store ends the batch, and then nothing in it commits. +fn apply_batch( + store: &SharedEventStore, + events: Vec, now_ms: u64, tally: &mut Tally, ) -> Result<()> { - if pending.is_empty() { - return Ok(()); + for outcome in store.ingest_events(events, now_ms)? { + tally.add(&outcome); + } + Ok(()) +} + +/// Writes one message as frames, or finishes the stream early if the cut is due. +async fn write_flight( + send: &mut SendStream, + out: &mut Outcome, + msg: &[Entry], + params: Params, + cut: Cut, +) -> Result<()> { + if cut == Cut::AfterFlights(out.flights) { + end_early(send); + bail!("cut before message {}", out.flights + 1); + } + for frame in frames(msg, params.frame_budget())? { + out.control_bytes += send_frame(send, &frame).await?; + } + out.flights += 1; + Ok(()) +} + +/// Reads frames until one without the `more` flag, and returns the message's entries. +async fn read_flight(inbound: &mut Inbound) -> Result> { + let mut entries = Vec::new(); + loop { + let (more, mut part) = decode_frame(&next_frame(inbound).await?)?; + entries.append(&mut part); + if !more { + break; + } + } + check_bounds(&entries)?; + Ok(entries) +} + +/// Writes one frame, and returns its size on the wire, with the length prefix. The frame is one +/// write, so a cancelled caller never leaves half of it on the stream. +async fn send_frame(send: &mut SendStream, payload: &[u8]) -> Result { + ensure!( + payload.len() <= range::FRAME_CAP, + "frame of {} bytes is over the cap", + payload.len() + ); + let len = u32::try_from(payload.len())?; + let mut framed = Vec::with_capacity(4 + payload.len()); + framed.extend_from_slice(&len.to_be_bytes()); + framed.extend_from_slice(payload); + send.write_all(&framed).await?; + Ok(framed.len()) +} + +/// The next whole frame from the peer. +async fn next_frame(inbound: &mut Inbound) -> Result> { + match inbound.recv().await { + Some(Ok(frame)) => Ok(frame), + Some(Err(error)) => Err(anyhow!(error)), + None => Err(anyhow!("the sync stream ended")), + } +} + +/// Finishes this side's send half early. The peer reads what was sent, then the stream ends, as +/// it would after an interruption. A reset would be wrong here: QUIC discards the data a reader +/// has not yet taken when a stream is reset. +fn end_early(send: &mut SendStream) { + let _ = send.finish(); +} + +impl SharedEventStore { + /// The bytes of the event with `id`, if the store holds it as an event or a fork proof header. + pub(crate) fn sync_bytes(&self, id: &Id) -> Result>> { + Ok(self.read(|store| Ok(store.sync_bytes(id)?))?) + } +} + +impl EventStore { + /// The sync set, sorted by key: each stored event, and each fork proof header, once. + /// + /// # Errors + /// + /// Returns a redb error if the read fails, or [`StoreError::Corrupt`]. + pub(crate) fn sync_entries(&self) -> Result, StoreError> { + let txn = self.db.begin_read()?; + let hashes = txn.open_table(HASHES)?; + let forks = txn.open_table(FORKS)?; + let mut entries: Vec<(Key, Id)> = Vec::new(); + for row in hashes.iter()? { + let (id, position) = row?; + let id = id_of(id.value())?; + entries.push((sync_key(position.value(), &id)?, id)); + } + for row in forks.iter()? { + let (_author, proof) = row?; + let proof = decode_proof(proof.value())?; + for header in [&proof.first, &proof.second] { + let author = *header.header.verifying_key.as_bytes(); + let position = position_key(&author, header.header.seq_num); + let id = *header.id.as_bytes(); + entries.push((sync_key(&position, &id)?, id)); + } + } + entries.sort_unstable_by_key(|e| e.0); + entries.dedup_by(|a, b| a.0 == b.0); + Ok(entries) } - let events = std::mem::take(pending); - let mut guard = lock(store)?; - apply_batch(&mut guard, events, now_ms, tally) + + /// The encoded bytes of the event with this ID, if the store holds it as a stored event or as + /// a current fork proof header. + /// + /// # Errors + /// + /// Returns a redb error if the read fails, or [`StoreError::Corrupt`]. + pub(crate) fn sync_bytes(&self, id: &Id) -> Result>, StoreError> { + let txn = self.db.begin_read()?; + let hashes = txn.open_table(HASHES)?; + if let Some(position) = hashes.get(id.as_slice())? { + let events = txn.open_table(EVENTS)?; + let stored = events.get(position.value())?; + return Ok(stored.map(|bytes| bytes.value().to_vec())); + } + let proof_ids = txn.open_table(PROOF_IDS)?; + let Some(author) = proof_ids.get(id.as_slice())? else { + return Ok(None); + }; + let author: AuthorKey = author + .value() + .try_into() + .map_err(|_err| corrupt("a proof ID names no author"))?; + let forks = txn.open_table(FORKS)?; + let Some(row) = forks.get(author.as_slice())? else { + return Ok(None); + }; + let proof = decode_proof(row.value())?; + Ok([proof.first, proof.second] + .into_iter() + .find(|header| header.id.as_bytes() == id) + .map(|header| header.bytes)) + } +} + +fn id_of(bytes: &[u8]) -> Result { + bytes + .try_into() + .map_err(|_err| corrupt("an event ID is not 32 bytes")) +} + +/// The sync key of an event: its position (author and sequence number), then its ID. +fn sync_key(position: &[u8], id: &Id) -> Result { + if position.len() != POSITION_LEN { + return Err(corrupt("a position key has the wrong length")); + } + let mut key = [0u8; range::KEY_LEN]; + key[..POSITION_LEN].copy_from_slice(position); + key[POSITION_LEN..].copy_from_slice(id); + Ok(key) } #[cfg(test)] #[allow(clippy::unwrap_used, clippy::expect_used)] mod tests { + use std::net::Ipv4Addr; use std::time::Duration; + use iroh::endpoint::{Endpoint, presets}; + use iroh::{EndpointAddr, RelayMode, TransportAddr}; + use p2panda_core::SigningKey; + use super::*; use crate::chain::ChainExt; + use crate::event_store::EventStore; + use crate::log_sync::Frames; use crate::waiting::WaitingLimits; - use p2panda_core::{Hash, SigningKey}; - - use iroh::endpoint::{Endpoint, presets}; - use iroh::{EndpointAddr, RelayMode, TransportAddr}; - use std::net::Ipv4Addr; const NOW: u64 = 1_000_000_000; - /// An endpoint on localhost, with no relay and no address lookup. Dialed by address only. - async fn endpoint(alpns: Vec>) -> Result { - Ok(Endpoint::builder(presets::Minimal) - .alpns(alpns) - .relay_mode(RelayMode::Disabled) - .bind() - .await?) - } + /// The topic every test event belongs to, so each one is in the sync set. + const TOPIC_BYTES: [u8; 1] = [1]; - /// The address of `ep` on localhost: every bound socket, with an unspecified IP replaced by - /// the loopback address. - fn loopback_addr(ep: &Endpoint) -> EndpointAddr { - EndpointAddr::from_parts( - ep.id(), - ep.bound_sockets().iter().map(|addr| { - let ip = if addr.ip().is_unspecified() { - Ipv4Addr::LOCALHOST.into() - } else { - addr.ip() - }; - TransportAddr::Ip(std::net::SocketAddr::new(ip, addr.port())) - }), - ) + fn topic() -> Hash { + Hash::digest(TOPIC_BYTES) } - fn open() -> (tempfile::TempDir, EventStore) { + fn open() -> (tempfile::TempDir, SharedEventStore) { let dir = tempfile::tempdir().unwrap(); let store = EventStore::open(dir.path(), WaitingLimits::default(), NOW).unwrap(); - (dir, store) + (dir, SharedEventStore::new(store)) } fn signer(n: u64) -> SigningKey { SigningKey::from_bytes(Hash::digest(n.to_be_bytes()).as_bytes()) } - /// The first `len` events of chain `n`. Each names the one before, and has a body if `body`. + /// The first `len` events of chain `n`, in the topic. Each names the one before, and carries + /// `body`. fn chain_of(n: u64, len: u32, body: &[u8]) -> Vec { let key = signer(n); let mut events: Vec = Vec::new(); @@ -477,7 +441,7 @@ mod tests { let backlink = events.last().map(|e| e.id); let ext = ChainExt { kind: "message".to_owned(), - group: None, + group: Some(topic()), after: Vec::new(), }; events.push(chain::sign(&key, seq, backlink, Some(body), ext).unwrap()); @@ -486,7 +450,7 @@ mod tests { } /// Stores `events` in order, and checks each one is applied. - fn fill(store: &mut EventStore, events: &[Event]) { + fn fill(store: &SharedEventStore, events: &[Event]) { let outcomes = store.ingest_events(events.to_vec(), NOW).unwrap(); assert!( outcomes @@ -496,32 +460,63 @@ mod tests { ); } - /// The chains of `lengths` (chain number, length), with a prefix of each chain stored. - fn populate(store: &mut EventStore, lengths: &[(u64, u32)]) { + /// The chains of `lengths` (chain number, length), each with a prefix stored. + fn populate(store: &SharedEventStore, lengths: &[(u64, u32)]) { for &(n, len) in lengths { fill(store, &chain_of(n, len, b"body")); } } - fn ids(store: &EventStore) -> HashSet { + /// Every sync key and ID the store holds, whatever the topic. + fn ids(store: &SharedEventStore) -> HashSet { store - .sync_entries() + .read(|s| Ok(s.sync_entries()?)) .unwrap() .into_iter() - .map(|e| e.1) + .map(|entry| entry.1) .collect() } - /// Runs one session on each side of a loopback connection. The dialer is `a`. Both sessions - /// run in this task, so each store is borrowed only by its own session. + /// The symmetric difference of two stores' IDs. + fn difference(a: &SharedEventStore, b: &SharedEventStore) -> HashSet { + let (a, b) = (ids(a), ids(b)); + a.symmetric_difference(&b).copied().collect() + } + + async fn endpoint(alpns: Vec>) -> Result { + Ok(Endpoint::builder(presets::Minimal) + .alpns(alpns) + .relay_mode(RelayMode::Disabled) + .bind() + .await?) + } + + /// The address of `ep` on localhost, so a peer dials it without a relay or discovery. + fn loopback_addr(ep: &Endpoint) -> EndpointAddr { + EndpointAddr::from_parts( + ep.id(), + ep.bound_sockets().iter().map(|addr| { + let ip = if addr.ip().is_unspecified() { + Ipv4Addr::LOCALHOST.into() + } else { + addr.ip() + }; + TransportAddr::Ip(std::net::SocketAddr::new(ip, addr.port())) + }), + ) + } + + /// Runs a range session on each side of a loopback stream. `a` dials and `b` accepts. Both run + /// in this task, each store borrowed only by its own session, and the whole exchange has a + /// deadline, so it cannot hang. async fn loopback( - a: &mut EventStore, - b: &mut EventStore, + a: &SharedEventStore, + b: &SharedEventStore, pa: Params, pb: Params, cut: Cut, ) -> Result<(Result, Result)> { - let server = endpoint(vec![ALPN.to_vec()]).await?; + let server = endpoint(vec![crate::log_sync::SYNC_ALPN.to_vec()]).await?; let client = endpoint(vec![]).await?; let target = loopback_addr(&server); let accepting = async { @@ -530,12 +525,38 @@ mod tests { .await .context("endpoint closed before a connection")?; let conn = incoming.await?; - let out = run(b, &conn, false, pb, NOW, Cut::Never).await; + let (send, recv) = conn.accept_bi().await?; + let mut frames = Frames::new(send, recv); + let out = run_range( + b, + topic(), + pb, + NOW, + false, + &mut frames.send, + &mut frames.inbound, + Cut::Never, + ) + .await; + frames.finish().await; anyhow::Ok((out, conn)) }; let dialing = async { - let conn = client.connect(target, ALPN).await?; - let out = run(a, &conn, true, pa, NOW, cut).await; + let conn = client.connect(target, crate::log_sync::SYNC_ALPN).await?; + let (send, recv) = conn.open_bi().await?; + let mut frames = Frames::new(send, recv); + let out = run_range( + a, + topic(), + pa, + NOW, + true, + &mut frames.send, + &mut frames.inbound, + cut, + ) + .await; + frames.finish().await; anyhow::Ok((out, conn)) }; let (dialed, accepted) = tokio::time::timeout(Duration::from_secs(300), async { @@ -552,29 +573,14 @@ mod tests { Ok((dialer_out, acceptor_out)) } - /// The symmetric difference of two stores' IDs. - fn difference(a: &EventStore, b: &EventStore) -> HashSet { - let (a, b) = (ids(a), ids(b)); - a.symmetric_difference(&b).copied().collect() - } - #[tokio::test(flavor = "multi_thread")] async fn test_empty_store_is_readable_and_two_empty_stores_agree() { - let (_da, mut a) = open(); - let (_db, mut b) = open(); - assert!( - a.sync_entries().unwrap().is_empty(), - "a fresh store reads as empty" - ); - let (da, db) = loopback( - &mut a, - &mut b, - Params::default(), - Params::default(), - Cut::Never, - ) - .await - .unwrap(); + let (_da, a) = open(); + let (_db, b) = open(); + assert!(ids(&a).is_empty(), "a fresh store reads as empty"); + let (da, db) = loopback(&a, &b, Params::default(), Params::default(), Cut::Never) + .await + .unwrap(); let (da, db) = (da.unwrap(), db.unwrap()); assert_eq!(da.flights, 1); assert_eq!(db.flights, 1); @@ -584,9 +590,9 @@ mod tests { #[test] fn test_sync_set_holds_stored_events_and_fork_proof_headers_once() { - let (_d, mut store) = open(); + let (_d, store) = open(); let events = chain_of(1, 3, b"x"); - fill(&mut store, &events); + fill(&store, &events); // A rival at sequence 1: a different body, so a different ID, at a stored position. let rival = chain::sign( &signer(1), @@ -595,20 +601,18 @@ mod tests { Some(b"other"), ChainExt { kind: "message".to_owned(), - group: None, + group: Some(topic()), after: Vec::new(), }, ) .unwrap(); let outcome = store.ingest_events(vec![rival.clone()], NOW).unwrap(); assert!(matches!(outcome[0], Ingest::Fork { .. }), "{outcome:?}"); - let sync = store.sync_entries().unwrap(); // The stored events (0, 1, and 2 voided above the fork point), and the rival, which is // now a proof header. The stored event at sequence 1 is also a proof header, so it is // listed once. - let set: HashSet = sync.iter().map(|e| e.1).collect(); - assert_eq!(set.len(), 4); - assert!(set.contains(rival.id.as_bytes())); + assert_eq!(ids(&store).len(), 4); + assert!(ids(&store).contains(rival.id.as_bytes())); assert_eq!( store.sync_bytes(rival.id.as_bytes()).unwrap().unwrap(), rival.bytes @@ -624,9 +628,8 @@ mod tests { /// decided, and the fork is recorded. #[test] fn test_a_fork_in_a_batch_is_isolated() { - let (_d, mut store) = open(); - let original = chain_of(1, 1, b"x"); - fill(&mut store, &original); + let (_d, store) = open(); + fill(&store, &chain_of(1, 1, b"x")); let rival = chain::sign( &signer(1), 0, @@ -634,7 +637,7 @@ mod tests { Some(b"rival"), ChainExt { kind: "message".to_owned(), - group: None, + group: Some(topic()), after: Vec::new(), }, ) @@ -644,29 +647,44 @@ mod tests { batch.extend(chain_of(n, 1, b"unrelated")); } let mut tally = Tally::default(); - apply_batch(&mut store, batch, NOW, &mut tally).unwrap(); + apply_batch(&store, batch, NOW, &mut tally).unwrap(); assert_eq!(tally.forks, 1); assert_eq!( tally.accepted, 20, "the 20 unrelated events survive the fork" ); // The original, the rival that proves the fork, and the 20 unrelated events. - assert_eq!(store.sync_entries().unwrap().len(), 22); + assert_eq!(ids(&store).len(), 22); } - /// Prefix lengths of two sides' chains, so each side holds some events the other lacks. - fn lengths(seed: u32) -> (Vec<(u64, u32)>, Vec<(u64, u32)>) { - let a = (1..=24u64) - .map(|c| (c, (c as u32 * (7 + seed)) % 19)) - .collect(); - let b = (1..=24u64) - .map(|c| (c, (c as u32 * (5 + seed) + 3) % 23)) - .collect(); - (a, b) + /// Only the topic's authors are offered: an author with no event in the topic stays home. + #[tokio::test(flavor = "multi_thread")] + async fn test_range_offers_only_the_topics_authors() { + let (_da, a) = open(); + let (_db, b) = open(); + fill(&a, &chain_of(1, 3, b"in")); + // Chain 2 is in a different group, so it is not in the topic. + let other = Hash::digest([2_u8]); + let key = signer(2); + let mut outside: Vec = Vec::new(); + for seq in 0..3 { + let backlink = outside.last().map(|e| e.id); + let ext = ChainExt { + kind: "message".to_owned(), + group: Some(other), + after: Vec::new(), + }; + outside.push(chain::sign(&key, seq, backlink, None, ext).unwrap()); + } + fill(&a, &outside); + let (da, _db) = loopback(&a, &b, Params::default(), Params::default(), Cut::Never) + .await + .unwrap(); + let da = da.unwrap(); + assert_eq!(da.sent, 3, "only the topic's chain is offered"); + assert_eq!(ids(&b).len(), 3); } - /// Loopback sessions over iroh, with K and T on each side. Both stores end equal, and each - /// side learns the exact symmetric difference, with no duplicate and no refusal. #[tokio::test(flavor = "multi_thread")] async fn test_loopback_converges_for_mixed_k_and_t() { let cases = [ @@ -676,18 +694,24 @@ mod tests { (32, 1, 2, 4), ]; for (seed, (ka, ta, kb, tb)) in cases.into_iter().enumerate() { - let (la, lb) = lengths(seed as u32); - let (_da, mut a) = open(); - let (_db, mut b) = open(); - populate(&mut a, &la); - populate(&mut b, &lb); + // Prefix lengths of each side's chains, so each side holds events the other lacks. + let seed = seed as u32; + let la: Vec<(u64, u32)> = (1..=24u64) + .map(|c| (c, (c as u32 * (7 + seed)) % 19)) + .collect(); + let lb: Vec<(u64, u32)> = (1..=24u64) + .map(|c| (c, (c as u32 * (5 + seed) + 3) % 23)) + .collect(); + let (a, b) = (open().1, open().1); + populate(&a, &la); + populate(&b, &lb); let truth = difference(&a, &b); let union: HashSet = ids(&a).union(&ids(&b)).copied().collect(); let label = format!("A K={ka} T={ta}, B K={kb} T={tb}"); let (da, db) = loopback( - &mut a, - &mut b, + &a, + &b, Params::new(ka, ta).unwrap(), Params::new(kb, tb).unwrap(), Cut::Never, @@ -720,16 +744,16 @@ mod tests { /// missing events, with no duplicate. #[tokio::test(flavor = "multi_thread")] async fn test_an_interrupted_session_restarts_without_duplicates() { - let (_da, mut a) = open(); - let (_db, mut b) = open(); - populate(&mut a, &[(1, 300), (2, 300)]); + let (_da, a) = open(); + let (_db, b) = open(); + populate(&a, &[(1, 300), (2, 300)]); let total = ids(&a); // A cuts after 400 events. B has decided one full batch of 256, and the other 144 died // with the session. let (first_a, first_b) = loopback( - &mut a, - &mut b, + &a, + &b, Params::default(), Params::default(), Cut::AfterRecords(400), @@ -737,22 +761,17 @@ mod tests { .await .unwrap(); assert!(first_a.is_err(), "the cut ends the dialer's session"); - assert!(first_b.is_err(), "the acceptor sees the connection close"); + assert!(first_b.is_err(), "the acceptor sees the stream end"); assert_eq!( ids(&b).len(), BATCH_EVENTS, "only the whole batch was committed" ); - let (second_a, second_b) = loopback( - &mut a, - &mut b, - Params::default(), - Params::default(), - Cut::Never, - ) - .await - .unwrap(); + let (second_a, second_b) = + loopback(&a, &b, Params::default(), Params::default(), Cut::Never) + .await + .unwrap(); let (second_a, second_b) = (second_a.unwrap(), second_b.unwrap()); assert_eq!(ids(&a), total); assert_eq!(ids(&b), total, "the restart completes the store"); @@ -765,27 +784,22 @@ mod tests { assert_eq!(second_a.accepted, 0); } - /// P3.1c on a real store: a store above the 524,288-event limit bootstraps into an empty one - /// in both directions. The ID reply alone is 17.6 MB, over the 16 MiB frame cap, so it has to - /// be chunked. Signing 550,000 events is slow in debug builds, so run it on demand: - /// `cargo test --release -- --ignored test_bootstrap_above_the_frame_limit`. + /// Bootstrap over many frames, in both directions: a 4 KiB budget splits every ID reply. #[tokio::test(flavor = "multi_thread")] - #[ignore = "signs 550,000 events; run with --release --ignored"] - async fn test_bootstrap_above_the_frame_limit_on_a_real_store() { - let chains: Vec<(u64, u32)> = (1..=1100).map(|c| (c, 500)).collect(); + async fn test_bootstrap_over_many_frames_in_both_directions_on_real_stores() { + let budget = Params::default().with_frame_budget(4096).unwrap(); + let chains: Vec<(u64, u32)> = (1..=30).map(|c| (c, 40)).collect(); for full_dials in [true, false] { - let (_df, mut full) = open(); - let (_de, mut empty) = open(); - populate(&mut full, &chains); + let (_df, full) = open(); + let (_de, empty) = open(); + populate(&full, &chains); let total = ids(&full); - assert_eq!(total.len(), 550_000); - let params = Params::default(); let (dialer, acceptor) = if full_dials { - loopback(&mut full, &mut empty, params, params, Cut::Never) + loopback(&full, &empty, budget, budget, Cut::Never) .await .unwrap() } else { - loopback(&mut empty, &mut full, params, params, Cut::Never) + loopback(&empty, &full, budget, budget, Cut::Never) .await .unwrap() }; @@ -797,31 +811,37 @@ mod tests { }; assert_eq!(ids(&empty), total, "{label}"); assert_eq!(ids(&full), total, "{label}"); + // Chunking adds frames, not messages, so the control bytes show the split: 1,200 IDs + // are 38 KB, which is many 4 KiB frames. assert!( - dialer.control_bytes + acceptor.control_bytes > range::FRAME_CAP, - "{label}: the reply is above one frame" + dialer.control_bytes + acceptor.control_bytes > 4 * 4096, + "{label}: the ID replies were split into frames" ); assert_eq!(dialer.duplicates + acceptor.duplicates, 0, "{label}"); } } - /// Bootstrap of a store whose sync set needs many frames: a 4 KiB budget splits every ID - /// reply, and each direction converges. + /// P3.1c on a real store: a store above the 524,288-event limit bootstraps into an empty one + /// in both directions. The ID reply alone is 17.6 MB, far over one frame, so it has to be + /// chunked. Signing 550,000 events is slow in debug builds, so run it on demand: + /// `cargo test --release -- --ignored test_bootstrap_above_the_frame_limit`. #[tokio::test(flavor = "multi_thread")] - async fn test_bootstrap_over_many_frames_in_both_directions_on_real_stores() { - let budget = Params::default().with_frame_budget(4096).unwrap(); - let chains: Vec<(u64, u32)> = (1..=30).map(|c| (c, 40)).collect(); + #[ignore = "signs 550,000 events; run with --release --ignored"] + async fn test_bootstrap_above_the_frame_limit_on_a_real_store() { + let chains: Vec<(u64, u32)> = (1..=1100).map(|c| (c, 500)).collect(); for full_dials in [true, false] { - let (_df, mut full) = open(); - let (_de, mut empty) = open(); - populate(&mut full, &chains); + let (_df, full) = open(); + let (_de, empty) = open(); + populate(&full, &chains); let total = ids(&full); + assert_eq!(total.len(), 550_000); + let params = Params::default(); let (dialer, acceptor) = if full_dials { - loopback(&mut full, &mut empty, budget, budget, Cut::Never) + loopback(&full, &empty, params, params, Cut::Never) .await .unwrap() } else { - loopback(&mut empty, &mut full, budget, budget, Cut::Never) + loopback(&empty, &full, params, params, Cut::Never) .await .unwrap() }; @@ -833,11 +853,9 @@ mod tests { }; assert_eq!(ids(&empty), total, "{label}"); assert_eq!(ids(&full), total, "{label}"); - // Chunking adds frames, not messages, so the control bytes show the split: 1,200 IDs - // are 38 KB, which is many 4 KiB frames. assert!( - dialer.control_bytes + acceptor.control_bytes > 4 * 4096, - "{label}: the ID replies were split into frames" + dialer.control_bytes + acceptor.control_bytes > range::FRAME_CAP, + "{label}: the reply is above one frame" ); assert_eq!(dialer.duplicates + acceptor.duplicates, 0, "{label}"); } diff --git a/pkgs/id/src/log_sync.rs b/pkgs/id/src/log_sync.rs index 4b9421469c..c1696fe479 100644 --- a/pkgs/id/src/log_sync.rs +++ b/pkgs/id/src/log_sync.rs @@ -43,6 +43,8 @@ use tokio::time::timeout; use crate::chain::ChainExt; use crate::connectivity::connect; use crate::event_store::Ingest; +use crate::event_store::range::Params; +use crate::event_store::sync::{Cut, run_range}; use crate::store_traits::{ChainLog, SharedEventStore}; use crate::sync_method::{Answer, Request, SyncMethod, SyncStats, SyncSupport, choose}; use crate::world::unix_ms; @@ -94,6 +96,9 @@ pub enum SyncError { /// `LogSync` failed. #[error("LogSync: {0}")] LogSync(String), + /// Range sync failed. + #[error("range sync: {0}")] + Range(String), } /// What one side did with the events it received in a session. @@ -131,8 +136,9 @@ pub struct Outcome { pub method: SyncMethod, /// What this side stored. pub received: Tally, - /// `LogSync`'s counts for the session. `sent_operations` is what this side sent. - pub metrics: LogSyncMetrics, + /// `LogSync`'s counts for the session. `sent_operations` is what this side sent. `None` for + /// range sync, which has its own counts in [`crate::event_store::sync::Outcome`]. + pub metrics: Option, } /// Serves sync sessions on [`SYNC_ALPN`]. Register it with @@ -209,7 +215,7 @@ pub async fn sync_with( } Answer::Refuse => return Err(SyncError::Refused(method)), } - let outcome = run_agreed(store, topic, method, &mut frames).await?; + let outcome = run_agreed(store, topic, method, &mut frames, true).await?; frames.finish().await; conn.close(0_u32.into(), b"done"); Ok(outcome) @@ -243,7 +249,7 @@ pub async fn answer( return Err(SyncError::Refused(request.method)); } frames.send_message(&Answer::Agree(request.method)).await?; - let outcome = run_agreed(store, request.topic, request.method, &mut frames).await?; + let outcome = run_agreed(store, request.topic, request.method, &mut frames, false).await?; frames.finish().await; Ok(outcome) }; @@ -253,19 +259,54 @@ pub async fn answer( } } -/// Runs the method both sides agreed to. +/// Runs the method both sides agreed to. `initiator` is true on the dialing side, which sends the +/// first message of a range session. async fn run_agreed( store: &SharedEventStore, topic: Hash, method: SyncMethod, frames: &mut Frames, + initiator: bool, ) -> Result { match method { SyncMethod::Log => run_log_sync(store, topic, frames).await, - SyncMethod::Range => Err(SyncError::NotWired(method)), + SyncMethod::Range => run_range_session(store, topic, initiator, frames).await, } } +/// Runs range sync (P3.1) on the agreed stream, with the local defaults for K, T, and the budget. +async fn run_range_session( + store: &SharedEventStore, + topic: Hash, + initiator: bool, + frames: &mut Frames, +) -> Result { + let outcome = run_range( + store, + topic, + Params::default(), + unix_ms(), + initiator, + &mut frames.send, + &mut frames.inbound, + Cut::Never, + ) + .await + .map_err(|error| SyncError::Range(format!("{error:#}")))?; + let count = |n: usize| u32::try_from(n).unwrap_or(u32::MAX); + Ok(Outcome { + method: SyncMethod::Range, + received: Tally { + accepted: count(outcome.accepted), + duplicates: count(outcome.duplicates), + held: count(outcome.waiting), + refused: count(outcome.refused), + forks: count(outcome.forks), + }, + metrics: None, + }) +} + /// Runs `p2panda-sync`'s `LogSync` for the logs of `topic`, on `frames`. /// /// The logs are the topic's authors on this side, as `TopicStore::resolve` gives them. An author @@ -328,20 +369,20 @@ async fn run_log_sync( Ok(Outcome { method: SyncMethod::Log, received: tally, - metrics, + metrics: Some(metrics), }) } /// One stream pair. A task of its own reads the receive half and forwards whole frames over a /// channel, so a read is never cancelled midway, whatever the caller selects over. -struct Frames { - send: SendStream, - inbound: mpsc::Receiver, String>>, +pub(crate) struct Frames { + pub(crate) send: SendStream, + pub(crate) inbound: mpsc::Receiver, String>>, reader: JoinHandle<()>, } impl Frames { - fn new(send: SendStream, mut recv: RecvStream) -> Self { + pub(crate) fn new(send: SendStream, mut recv: RecvStream) -> Self { let (tx, inbound) = mpsc::channel(8); let reader = tokio::spawn(async move { loop { @@ -388,7 +429,7 @@ impl Frames { /// connection. This runs after `LogSync` has finished on both sides, so everything each side needs /// has already arrived. A read error here is the peer closing the connection, which is not a /// failure of the session. - async fn finish(mut self) { + pub(crate) async fn finish(mut self) { let _ = self.send.finish(); while let Some(frame) = self.inbound.recv().await { if frame.is_err() { @@ -416,7 +457,7 @@ mod tests { use super::*; use crate::chain::{Event, sign}; use crate::event_store::EventStore; - use crate::sync_method::{Estimate, LogSyncOnly}; + use crate::sync_method::{Estimate, LogAndRange, LogSyncOnly, PeerHistory}; use crate::waiting::WaitingLimits; const DEADLINE: Duration = Duration::from_secs(30); @@ -589,7 +630,11 @@ mod tests { "no event is inserted twice" ); assert_eq!(outcome.received.refused + answered.received.refused, 0); - assert_eq!(outcome.metrics.sent_operations, 5, "B sent carol 0 to 4"); + assert_eq!( + outcome.metrics.clone().unwrap_or_default().sent_operations, + 5, + "B sent carol 0 to 4" + ); let all = [&alice, &bob, &carol]; let (a_state, b_state) = (applied(&store_a, &all, 4), applied(&store_b, &all, 4)); @@ -617,7 +662,7 @@ mod tests { let again_answered = results.recv().await.unwrap().unwrap(); assert_eq!(again.received, Tally::default()); assert_eq!(again_answered.received, Tally::default()); - assert_eq!(again.metrics.sent_operations, 0); + assert_eq!(again.metrics.clone().unwrap_or_default().sent_operations, 0); } #[tokio::test] @@ -777,7 +822,10 @@ mod tests { assert_eq!(answered.received.duplicates, 1, "seq 1 is a proof header"); assert_eq!(answered.received.refused, 1, "seq 2 is past the fork point"); assert_eq!(answered.received.accepted, 5, "every event of y arrives"); - assert_eq!(outcome.metrics.sent_operations, 7); + assert_eq!( + outcome.metrics.clone().unwrap_or_default().sent_operations, + 7 + ); let refs = [&y]; assert_eq!(applied(&store_a, &refs, 4), applied(&store_b, &refs, 4)); assert!( @@ -917,4 +965,198 @@ mod tests { ); assert_eq!(applied(&store_b, &[&alice], 2), before, "nothing moved"); } + + /// The responder for both methods: the production [`answer`], with each session's result sent + /// to the test. + #[derive(Debug)] + struct CaptureAll { + store: SharedEventStore, + results: mpsc::UnboundedSender>, + } + + impl ProtocolHandler for CaptureAll { + async fn accept(&self, conn: Connection) -> Result<(), AcceptError> { + while let Ok((send, recv)) = conn.accept_bi().await { + let result = answer(&self.store, &LogAndRange, send, recv, DEADLINE).await; + let _ = self.results.send(result); + } + Ok(()) + } + } + + /// Serves `store` for both methods on loopback. + async fn responder_for_both( + store: &SharedEventStore, + ) -> ( + Endpoint, + Router, + mpsc::UnboundedReceiver>, + ) { + let ep = endpoint().await; + let (results, rx) = mpsc::unbounded_channel(); + let handler = CaptureAll { + store: store.clone(), + results, + }; + let router = Router::builder(ep.clone()) + .accept(SYNC_ALPN, handler) + .spawn(); + (ep, router, rx) + } + + /// Thirty authors with three events each, all in `topic`. `a` has all of them. `b` has all + /// but the last event of author 7, so the two stores differ by one event. + fn thirty_authors(a: &SharedEventStore, b: &SharedEventStore, topic: Hash) { + for n in 1..=30u8 { + let events = chain_of(&key(n), 3, topic); + ingest_all(a, &events); + if n == 7 { + ingest_all(b, &events[..2]); + } else { + ingest_all(b, &events); + } + } + } + + /// The estimate for a peer that synced one event ago, with `difference` events apart. + fn synced_once(difference: u64) -> PeerHistory { + PeerHistory { + last_completed_sync_ms: Some(1), + changed_since_sync: difference, + } + } + + /// Thirty chains and one difference is range by the rule, so the choice is range. Two stores + /// run range over the wire and converge, and each side answers with the method it was asked. + #[tokio::test] + async fn test_two_stores_choose_range_and_converge() { + let topic = group(1); + let (_da, store_a) = open(); + let (_db, store_b) = open(); + thirty_authors(&store_a, &store_b, topic); + + let estimate = store_b.estimate(&topic, &synced_once(1)).unwrap(); + assert_eq!(choose(&estimate), SyncMethod::Range); + let (server, _router, mut results) = responder_for_both(&store_a).await; + let client = endpoint().await; + let outcome = tokio::time::timeout( + DEADLINE, + sync_with( + &client, + loopback(&server), + &store_b, + topic, + &estimate, + DEADLINE, + ), + ) + .await + .expect("the session has a deadline") + .unwrap(); + let answered = results.recv().await.unwrap().unwrap(); + + assert_eq!(outcome.method, SyncMethod::Range); + assert_eq!( + answered.method, + SyncMethod::Range, + "both sides ran range sync" + ); + assert_eq!( + outcome.received.accepted, 1, + "B lacked author 7's last event" + ); + assert_eq!(answered.received.accepted, 0, "A lacked nothing"); + assert_eq!( + outcome.received.duplicates + answered.received.duplicates, + 0 + ); + assert_eq!(outcome.received.refused + answered.received.refused, 0); + assert_eq!( + store_a.range_entries(&topic).unwrap(), + store_b.range_entries(&topic).unwrap(), + "both stores hold the same events" + ); + } + + /// A peer never synced with is LogSync by the rule, so this session runs LogSync and converges + /// the same stores. + #[tokio::test] + async fn test_two_stores_choose_log_and_converge() { + let topic = group(1); + let (_da, store_a) = open(); + let (_db, store_b) = open(); + thirty_authors(&store_a, &store_b, topic); + + let estimate = store_b.estimate(&topic, &PeerHistory::default()).unwrap(); + assert_eq!(choose(&estimate), SyncMethod::Log); + let (server, _router, mut results) = responder_for_both(&store_a).await; + let client = endpoint().await; + let outcome = tokio::time::timeout( + DEADLINE, + sync_with( + &client, + loopback(&server), + &store_b, + topic, + &estimate, + DEADLINE, + ), + ) + .await + .expect("the session has a deadline") + .unwrap(); + let answered = results.recv().await.unwrap().unwrap(); + + assert_eq!(outcome.method, SyncMethod::Log); + assert_eq!(answered.method, SyncMethod::Log, "both sides ran LogSync"); + assert_eq!(outcome.received.accepted, 1); + assert_eq!(outcome.received.duplicates, 0); + assert_eq!( + store_a.range_entries(&topic).unwrap(), + store_b.range_entries(&topic).unwrap(), + "both stores hold the same events" + ); + } + + /// The selector reads the estimate, not a fixed rule: the same store chooses range for one + /// difference and LogSync for two, and the chain count comes from the store. + #[test] + fn test_the_store_estimate_drives_the_choice() { + let topic = group(1); + let (_d, store) = open(); + for n in 1..=30u8 { + ingest_all(&store, &chain_of(&key(n), 1, topic)); + } + assert_eq!( + store + .estimate(&topic, &synced_once(1)) + .unwrap() + .chain_count(), + 30 + ); + assert_eq!( + choose(&store.estimate(&topic, &synced_once(1)).unwrap()), + SyncMethod::Range, + "one difference over thirty chains is range" + ); + assert_eq!( + choose(&store.estimate(&topic, &synced_once(2)).unwrap()), + SyncMethod::Log, + "two differences is above 0.035 of thirty chains" + ); + assert_eq!( + choose(&store.estimate(&topic, &PeerHistory::default()).unwrap()), + SyncMethod::Log, + "a peer never synced with is LogSync" + ); + } + + /// The range sync frame cap matches the stream's: a range frame is never refused by the reader. + #[test] + fn test_the_range_frame_cap_is_the_sync_streams_cap() { + assert_eq!( + crate::event_store::range::FRAME_CAP, + crate::world_session::MAX_FRAME_BYTES + ); + } } diff --git a/pkgs/id/src/store_traits.rs b/pkgs/id/src/store_traits.rs index 53c9dff826..5470ef8696 100644 --- a/pkgs/id/src/store_traits.rs +++ b/pkgs/id/src/store_traits.rs @@ -22,7 +22,7 @@ //! (`vendor/`) whose store dependency has no SQLite default, so the build has no SQLite. //! `test_the_lock_has_no_sqlite_with_logsync_wired` fails if SQLite returns. -use std::collections::{BTreeMap, BTreeSet, VecDeque}; +use std::collections::{BTreeMap, BTreeSet, HashSet, VecDeque}; use std::future::{Future, ready}; use std::pin::Pin; use std::sync::{Arc, RwLock}; @@ -37,7 +37,9 @@ use p2panda_store::topics::TopicStore; use serde::{Deserialize, Serialize}; use crate::chain::Event; +use crate::event_store::range::{Id, Key}; use crate::event_store::{EventStore, Ingest, StoreError}; +use crate::sync_method::{Estimate, PeerHistory}; use crate::waiting::AuthorKey; /// Entries read per page. A page takes the read lock once, so a stream never holds the lock @@ -117,6 +119,70 @@ impl SharedEventStore { self.read(|store| Ok(store.check_invariants()?)) } + /// Verifies and applies decoded events, in order, in one write transaction. See + /// [`EventStore::ingest_events`]. Range sync (P3.1) writes its batches through this. + /// + /// # Errors + /// + /// Returns [`TraitStoreError::Store`] for a redb or corruption error, and + /// [`TraitStoreError::Poisoned`] if another thread panicked while it held the lock. + pub(crate) fn ingest_events( + &self, + events: Vec, + now_ms: u64, + ) -> Result, TraitStoreError> { + let mut store = self + .inner + .write() + .map_err(|_err| TraitStoreError::Poisoned)?; + Ok(store.ingest_events(events, now_ms)?) + } + + /// The range sync set of `topic`: the sorted keys of the stored events and fork proof headers + /// of the authors LogSync resolves for the topic (see [`TopicStore::resolve`]). + /// + /// # Errors + /// + /// Returns a redb error if the read fails, or [`TraitStoreError::Store`]. + pub(crate) fn range_entries(&self, topic: &Hash) -> Result, TraitStoreError> { + let authors: HashSet = self + .authors_in(topic)? + .keys() + .map(|author| *author.as_bytes()) + .collect(); + self.read(|store| { + Ok(store + .sync_entries()? + .into_iter() + .filter(|(key, _)| { + key[..32] + .try_into() + .is_ok_and(|author: AuthorKey| authors.contains(&author)) + }) + .collect()) + }) + } + + /// The estimate that [`choose`] needs for a session on `topic`. The chain count is the + /// number of authors LogSync resolves for the topic, read from the store. The difference and + /// the last completed sync come from `history`, which the caller keeps. + /// + /// # Errors + /// + /// Returns a redb error if the read fails, or [`TraitStoreError::Store`]. + pub fn estimate( + &self, + topic: &Hash, + history: &PeerHistory, + ) -> Result { + let chains = u64::try_from(self.authors_in(topic)?.len()).unwrap_or(u64::MAX); + Ok(Estimate { + chains, + difference: history.changed_since_sync, + last_completed_sync_ms: history.last_completed_sync_ms, + }) + } + /// Runs `op` under the read lock. pub(crate) fn read( &self, diff --git a/pkgs/id/src/sync_method.rs b/pkgs/id/src/sync_method.rs index b7b43d30af..bfa17cf818 100644 --- a/pkgs/id/src/sync_method.rs +++ b/pkgs/id/src/sync_method.rs @@ -13,9 +13,9 @@ //! The initiator chooses, and sends its choice in a [`Request`]. The responder answers with an //! [`Answer`]: it agrees to run that method, or refuses it. It never chooses for the session. //! -//! The rule is written against [`SyncStats`], so range sync's index can supply the numbers when -//! it merges. [`SyncSupport`] is the same kind of seam for the answer: range sync adds itself when -//! it merges, and until then a responder refuses range requests. +//! The rule reads [`SyncStats`]. [`Estimate`] is its plain form, and `SharedEventStore::estimate` +//! fills it from the store. [`SyncSupport`] is the seam for the answer: a node that serves range +//! registers [`LogAndRange`], and a responder with [`LogSyncOnly`] refuses range requests. use std::fmt::Debug; @@ -97,7 +97,7 @@ pub trait SyncSupport: Debug + Send + Sync { fn supports(&self, method: SyncMethod) -> bool; } -/// Runs `LogSync` only. Range sync (P3.1) adds itself here when it merges. +/// Runs `LogSync` only. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct LogSyncOnly; @@ -107,6 +107,28 @@ impl SyncSupport for LogSyncOnly { } } +/// Runs both methods: `LogSync`, and range sync (P3.1). This is the support a node registers +/// when it serves sync. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct LogAndRange; + +impl SyncSupport for LogAndRange { + fn supports(&self, method: SyncMethod) -> bool { + matches!(method, SyncMethod::Log | SyncMethod::Range) + } +} + +/// What this node remembers about one peer: the inputs to the estimate besides the chain count. +/// The caller keeps it. Nothing stores it yet, so it lasts as long as the caller does. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct PeerHistory { + /// When the last sync with the peer completed, in Unix milliseconds. `None` before the first. + pub last_completed_sync_ms: Option, + /// Events this node created, or received from the peer, since that sync. A lower bound of the + /// difference, because the peer's new events are unknown before the exchange. + pub changed_since_sync: u64, +} + /// The initiator's first frame: the topic it syncs, and the method it chose. #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct Request {