diff --git a/pkgs/id/src/commands/serve.rs b/pkgs/id/src/commands/serve.rs index 9f8e2eedb2..9e7956a43e 100644 --- a/pkgs/id/src/commands/serve.rs +++ b/pkgs/id/src/commands/serve.rs @@ -827,6 +827,28 @@ pub async fn cmd_serve(opts: ServeOptions) -> Result<()> { Some(crate::access::blobs_events(access.clone())), ); + // The node's own event store, shared between the web layer and /id-sync/1 + // range sync (#792). Serve opens it once, on the same directory the web + // state would open (the `events` sibling of the identity database), and + // hands the one instance to both: the store admits a single opener, and a + // second store over the same directory would diverge from the one the web + // layer publishes ProseMirror save revisions into. Only opened when the + // web UI is on — that is the store whose revisions replicate, and opening + // it unconditionally would change the local CLI's access to the directory + // while serve runs. + #[cfg(feature = "web")] + let event_events: Option>> = if web { + let identity_db_path = std::path::Path::new(KEY_FILE).with_file_name(".identity.redb"); + let events_dir = identity_db_path.with_file_name(crate::local_events::DIR_NAME); + let events = crate::local_events::LocalEvents::open( + &events_dir, + p2panda_core::SigningKey::from_bytes(&key.to_bytes()), + )?; + Some(Arc::new(tokio::sync::Mutex::new(events))) + } else { + None + }; + // Every world lives in one hub, shared by the Iroh protocol and the web // bridge. The default world opens now so a bad journal fails startup. #[cfg(feature = "world")] @@ -916,6 +938,14 @@ pub async fn cmd_serve(opts: ServeOptions) -> Result<()> { .accept(BLOBS_ALPN, blobs) .accept(iroh_gossip::net::GOSSIP_ALPN, gossip.clone()) .accept(iroh_docs::net::ALPN, docs.clone()); + #[cfg(feature = "web")] + let router_builder = match &event_events { + Some(events) => router_builder.accept( + crate::event_store::sync::ALPN, + crate::event_sync::EventSyncProtocol::new(Arc::clone(events)), + ), + None => router_builder, + }; #[cfg(feature = "world")] let router_builder = match &world_hub { Some(hub) => router_builder @@ -941,6 +971,43 @@ pub async fn cmd_serve(opts: ServeOptions) -> Result<()> { let router_builder = router_builder.accept(crate::world_ssh::SSH_TUNNEL_ALPN, ssh_tunnel); let router = router_builder.spawn(); + // Offer a sync session to every discovered peer, on an interval: a save on + // either node is discoverable on the other after the next session (#792). + // Peers that do not serve /id-sync/1 fail the dial, which is logged at debug + // and otherwise ignored — accepting sessions above is what serves the rest. + #[cfg(feature = "web")] + let _event_sync_handle = event_events.clone().map(|events| { + status!("event sync: /id-sync/1 enabled (the web event store)"); + let endpoint = router.endpoint().clone(); + let discovery = peer_discovery.clone(); + let gate = crate::event_sync::open_gate(); + tokio::spawn(async move { + loop { + tokio::time::sleep(crate::event_sync::SYNC_INTERVAL).await; + for peer in discovery.peers() { + let peer_id = peer.announcement.node_id; + if peer_id == endpoint.id() { + continue; + } + match crate::event_sync::sync_with_peer(&endpoint, peer_id, &events, &gate) + .await + { + Ok(outcome) if outcome.sent + outcome.received > 0 => { + info!( + "event sync: {peer_id}: sent {} received {}", + outcome.sent, outcome.received + ); + } + Ok(_) => {} + Err(error) => { + debug!("event sync: session with {peer_id} failed: {error:#}"); + } + } + } + } + }) + }); + if !no_gossip { // Resolve effective config from defaults + CLI flags let config = resolve_config( @@ -1108,18 +1175,37 @@ pub async fn cmd_serve(opts: ServeOptions) -> Result<()> { #[cfg(feature = "web")] let _web_handle = if let Some(listener) = web_listener { let identity_db_path = std::path::Path::new(KEY_FILE).with_file_name(".identity.redb"); - let web_router = crate::web::web_router( - store_handle.clone(), - Some(peer_discovery.clone()), - node_id.to_string(), - Arc::clone(&tag_store), - key.to_bytes(), - identity_db_path, - crate::web::WebSecurity::for_bind(bind, web_token.clone(), &[]), - world_hub.clone(), - web_cookie_secure, - ) - .await?; + let web_router = match &event_events { + Some(events) => { + crate::web::web_router_with_local_events( + store_handle.clone(), + Some(peer_discovery.clone()), + node_id.to_string(), + Arc::clone(&tag_store), + key.to_bytes(), + identity_db_path, + crate::web::WebSecurity::for_bind(bind, web_token.clone(), &[]), + world_hub.clone(), + web_cookie_secure, + Arc::clone(events), + ) + .await? + } + None => { + crate::web::web_router( + store_handle.clone(), + Some(peer_discovery.clone()), + node_id.to_string(), + Arc::clone(&tag_store), + key.to_bytes(), + identity_db_path, + crate::web::WebSecurity::for_bind(bind, web_token.clone(), &[]), + world_hub.clone(), + web_cookie_secure, + ) + .await? + } + }; let actual_port = web_port.unwrap_or(port); let shown_host = if bind.is_unspecified() || bind.is_loopback() { "localhost".to_owned() @@ -1178,6 +1264,11 @@ pub async fn cmd_serve(opts: ServeOptions) -> Result<()> { remove_serve_lock().await?; router.shutdown().await?; #[cfg(feature = "web")] + if let Some(sync_task) = _event_sync_handle { + sync_task.abort(); + let _ = sync_task.await; + } + #[cfg(feature = "web")] if let Some(web_task) = _web_handle { web_task.abort(); let _ = web_task.await; diff --git a/pkgs/id/src/event_store/sync.rs b/pkgs/id/src/event_store/sync.rs index 688546ba40..1806980179 100644 --- a/pkgs/id/src/event_store/sync.rs +++ b/pkgs/id/src/event_store/sync.rs @@ -1,7 +1,7 @@ //! Range sync over the event store, on `/id-sync/1`. //! //! 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 sequence number, and the ID (see [`super::range`]). A session has four 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. @@ -10,6 +10,13 @@ //! 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. +//! 4. **Completion.** Each side, once it has applied what it received, sends one completion +//! frame (see [`APPLIED_FRAME`]), and ends the session only after reading the peer's. +//! A side that has returned therefore knows the peer applied what it sent: closing the +//! connection at that point cannot discard events the peer has received into its stream +//! buffers but not yet decided. Without the frame, the side that finishes first can +//! close while its last events are still in flight, and the peer's session dies with +//! the connection — the intermittent replication loss #792's two-node test caught. //! //! K, T, the frame budget and the session budget are local. The frame budget only has to stay //! under the frame cap. A session reads at most its session budget in reconciliation, and ends @@ -52,6 +59,10 @@ const POSITION_LEN: usize = 40; /// The application close code when the pull policy refuses the peer. [`Cut`] closes with 1. const CLOSE_PULL_REFUSED: u32 = 2; +/// The payload of the completion frame (phase 4): a side writes it once it has applied +/// everything it received, and reads the peer's before ending the session. +const APPLIED_FRAME: &[u8] = b"applied"; + /// A range session read past its session budget during reconciliation. /// /// It is raised before the frame that would pass the budget is buffered, so `read` never exceeds @@ -495,6 +506,13 @@ async fn run( Cut::Never | Cut::AfterFlights(_) => None, }; + // The completion handshake (phase 4): the receiving half signals once it has + // applied what it received; only then does the sending half write its completion + // frame, and the receiving half ends the session only after reading the peer's. + // `notify_one` stores its permit, so a signal sent before the sending half waits + // is not lost. + let applied = tokio::sync::Notify::new(); + let sending = async { let count = u32::try_from(offers.len())?; let mut bytes = write_frame(&mut send, &count.to_be_bytes()).await?; @@ -513,37 +531,27 @@ async fn run( .context("an offered event is no longer stored")?; bytes += write_frame(&mut send, &record).await?; } + applied.notified().await; + bytes += write_frame(&mut send, APPLIED_FRAME).await?; send.finish()?; anyhow::Ok(bytes) }; let receiving = async { - let count_frame = read_frame(&mut recv).await?; - let count: [u8; 4] = count_frame - .as_slice() - .try_into() - .map_err(|_err| anyhow!("count frame is not 4 bytes"))?; - let count = u32::from_be_bytes(count) as usize; + let received = receive_data(&mut recv, &store, &mut need, now_ms, &commits).await; + // Signal on every exit, error included: the sending half waits for this + // signal before it can finish, and a failed receive must not hold the + // session open until its deadline. + applied.notify_one(); + let (count, tally) = received?; + // Applied: this side's completion frame is now released; wait for the + // peer's — the session ends only once the peer has applied what this + // side sent. + let completion = read_frame(&mut recv).await?; ensure!( - count == need.len(), - "peer offers {count} events, and {} are missing here", - need.len() + completion == APPLIED_FRAME, + "the peer ended its data phase without a completion frame" ); - 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 event = chain::decode(&record)?; - ensure!( - need.remove(event.id.as_bytes()), - "an event arrived that was not expected, or arrived twice" - ); - pending.push(event); - if pending.len() == BATCH_EVENTS { - flush(&store, &mut pending, now_ms, &mut tally, &commits)?; - } - } - flush(&store, &mut pending, now_ms, &mut tally, &commits)?; anyhow::Ok((count, tally)) }; @@ -560,6 +568,45 @@ async fn run( Ok(out) } +/// The receiving half of the data phase: reads the peer's count frame and that many +/// event frames, deciding each batch as it fills, and returns how many events arrived +/// and how they were decided. The caller owns the completion handshake (phase 4). +async fn receive_data( + recv: &mut RecvStream, + store: &Mutex<&mut EventStore>, + need: &mut HashSet, + now_ms: u64, + commits: &Option, +) -> Result<(usize, Tally)> { + let count_frame = read_frame(recv).await?; + let count: [u8; 4] = count_frame + .as_slice() + .try_into() + .map_err(|_err| anyhow!("count frame is not 4 bytes"))?; + let count = u32::from_be_bytes(count) as usize; + ensure!( + count == need.len(), + "peer offers {count} events, and {} are missing here", + need.len() + ); + let mut pending: Vec = Vec::with_capacity(BATCH_EVENTS); + let mut tally = Tally::default(); + for _ in 0..count { + let record = read_frame(recv).await?; + let event = chain::decode(&record)?; + ensure!( + need.remove(event.id.as_bytes()), + "an event arrived that was not expected, or arrived twice" + ); + pending.push(event); + if pending.len() == BATCH_EVENTS { + flush(store, &mut pending, now_ms, &mut tally, commits)?; + } + } + flush(store, &mut pending, now_ms, &mut tally, commits)?; + Ok((count, tally)) +} + fn flush( store: &Mutex<&mut EventStore>, pending: &mut Vec, diff --git a/pkgs/id/src/event_sync.rs b/pkgs/id/src/event_sync.rs new file mode 100644 index 0000000000..56e8f84b53 --- /dev/null +++ b/pkgs/id/src/event_sync.rs @@ -0,0 +1,297 @@ +//! `/id-sync/1` sessions for the node's own event store, as served by `id serve` (#792). +//! +//! The session itself is the range sync in [`crate::event_store::sync`]: reconciliation, +//! then both sides send the events the other lacks, and the receiving store's own ingest +//! verifies and decides each one — a tampered or unsigned event is refused by +//! [`crate::event_store::EventStore::ingest`], never applied. This module is only the +//! iroh plumbing around it: the accepting protocol handler, the dialling helper, and +//! the pull gate `serve` uses. +//! +//! The store these sessions serve is the *same* [`LocalEvents`] instance the web layer +//! publishes ProseMirror save revisions into. `serve` opens that store once and shares +//! the `Arc>` between the web state and this handler, so there is no +//! second, divergent store: a revision saved through the web UI is in the sync set of +//! the next session, and a revision that arrives by sync is in the history the web UI +//! reads. Sharing the instance (rather than opening the same directory twice) is also +//! the only option: the store's database admits one opener at a time. +//! +//! The pull gate is [`PullPolicy::Open`], the documented default for sync: `id serve` +//! does not read a per-world pull policy from config yet, and there is no world whose +//! membership this store belongs to. An open gate never consults membership, so the +//! [`WorldAccess`] it carries is a formality that is never read. + +use std::sync::Arc; +use std::time::Duration; + +use anyhow::Result; +use iroh::endpoint::Connection; +use iroh::protocol::{AcceptError, ProtocolHandler}; +use iroh::{Endpoint, EndpointAddr}; +use iroh_base::EndpointId; +use tokio::sync::Mutex; + +use crate::blob_gate::WorldAccess; +use crate::event_store::sync::{ALPN, Outcome}; +use crate::local_events::LocalEvents; +use crate::pull_policy::{PullGate, PullPolicy}; + +/// How long one sync session may run before it is abandoned. Both sides use it, so a +/// silent peer ends the session instead of holding the shared store. +pub const SESSION_DEADLINE: Duration = Duration::from_secs(60); + +/// How often `serve` offers a sync session to each peer it has discovered. +pub const SYNC_INTERVAL: Duration = Duration::from_secs(30); + +/// How long the accepting side waits, after a completed session, for the dialer +/// to close the connection before it lets the router close it instead (see +/// `EventSyncProtocol::accept`). +const CLOSE_WAIT: Duration = Duration::from_secs(5); + +/// Membership answers for a gate that never asks. [`PullPolicy::Open`] admits every +/// peer without reading membership (see the module docs), so these answers are never +/// used; the type exists only because a [`PullGate`] is built over a [`WorldAccess`]. +#[derive(Debug)] +struct NoWorlds; + +impl WorldAccess for NoWorlds { + fn is_current_member(&self, _world: &str, _requester: &EndpointId) -> bool { + false + } + + fn worlds_referencing(&self, _hash: &iroh_blobs::Hash) -> Vec { + Vec::new() + } +} + +/// The pull gate for the node's own event store: open, per the module docs. +#[must_use] +pub fn open_gate() -> PullGate { + PullGate::new(PullPolicy::Open, "local-events", Arc::new(NoWorlds)) +} + +/// Serves range-sync sessions over the node's shared [`LocalEvents`] store. +/// Register it with `Router::builder(..).accept(ALPN, EventSyncProtocol::new(events))`, +/// where `events` is the same instance the web layer publishes into. +#[derive(Clone)] +pub struct EventSyncProtocol { + events: Arc>, + gate: PullGate, +} + +impl std::fmt::Debug for EventSyncProtocol { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("EventSyncProtocol") + .field("gate", &self.gate) + .finish_non_exhaustive() + } +} + +impl EventSyncProtocol { + /// Serves `events` under an open pull gate. + #[must_use] + pub fn new(events: Arc>) -> Self { + Self { + events, + gate: open_gate(), + } + } +} + +impl ProtocolHandler for EventSyncProtocol { + async fn accept(&self, conn: Connection) -> Result<(), AcceptError> { + let peer = conn.remote_id(); + // The lock is held for the whole session: the store takes `&mut`, and the web + // layer's saves queue behind a session the way they queue behind each other. + // Sessions are bounded by SESSION_DEADLINE, so the wait is bounded too. + let mut events = self.events.lock().await; + let completed = match events + .sync_session(&conn, false, SESSION_DEADLINE, &self.gate) + .await + { + Ok(outcome) => { + tracing::debug!( + "event sync: session with {peer}: sent {} received {} accepted {} duplicates {} waiting {} refused {}", + outcome.sent, + outcome.received, + outcome.accepted, + outcome.duplicates, + outcome.waiting, + outcome.refused + ); + true + } + Err(error) => { + tracing::debug!("event sync: session with {peer} ended: {error:#}"); + false + } + }; + if completed { + // The session's last frame is the completion frame the dialer ends + // its session on. Returning now would let the router close the + // connection before the dialer has read it, discarding the frame + // and failing its otherwise-complete session — so, like + // `ArtifactPullProtocol`, wait for the dialer to close first. The + // wait is bounded: the store lock is held here, and a dialer that + // never closes must not hold it (or this handler) forever. + let _ = tokio::time::timeout(CLOSE_WAIT, conn.closed()).await; + } + Ok(()) + } +} + +/// Dials `peer` and runs one range-sync session over the shared store, as initiator. +/// +/// # Errors +/// +/// Returns an error if the peer cannot be reached, breaks the protocol, or the session +/// does not finish within [`SESSION_DEADLINE`]. +pub async fn sync_with_peer( + endpoint: &Endpoint, + peer: impl Into, + events: &Arc>, + gate: &PullGate, +) -> Result { + let conn = crate::connectivity::connect(endpoint, peer, ALPN).await?; + let outcome = { + let mut events = events.lock().await; + events + .sync_session(&conn, true, SESSION_DEADLINE, gate) + .await + }; + conn.close(0_u32.into(), b"done"); + outcome +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +mod tests { + use std::net::{Ipv4Addr, SocketAddr}; + use std::path::Path; + + use iroh::endpoint::{RelayMode, presets}; + use iroh::protocol::Router; + use p2panda_core::SigningKey; + + use super::*; + + fn node(dir: &Path, byte: u8) -> Arc> { + let events = LocalEvents::open(dir, SigningKey::from_bytes(&[byte; 32])).unwrap(); + Arc::new(Mutex::new(events)) + } + + async fn endpoint() -> Endpoint { + Endpoint::builder(presets::Minimal) + .relay_mode(RelayMode::Disabled) + .bind() + .await + .unwrap() + } + + /// `ep`'s address on its loopback sockets, so a peer dials it without a relay or + /// discovery. + fn loopback(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() + }; + iroh::TransportAddr::Ip(SocketAddr::new(ip, addr.port())) + }), + ) + } + + /// Waits until `events` can read `id`'s history. A session's return on the + /// dialling side does not imply the accepting side has finished applying what + /// it received (its handler runs as its own task), so tests wait for the + /// applied state itself — the same convergence serve reaches on its next + /// interval. + async fn wait_for_history(events: &Arc>, id: p2panda_core::Hash) { + for _ in 0..1200 { + if events.lock().await.history(id).is_ok() { + return; + } + tokio::time::sleep(Duration::from_millis(50)).await; + } + panic!("the accepting side never applied {id}"); + } + + /// The #792 acceptance test: a document revision published (saved) on node A is + /// discoverable from node B's history after one sync session, where B serves the + /// protocol exactly as `serve` registers it and A dials with the production helper. + #[tokio::test(flavor = "multi_thread")] + async fn test_a_save_on_one_node_is_discoverable_on_the_other_after_sync() { + let dir_a = tempfile::tempdir().unwrap(); + let dir_b = tempfile::tempdir().unwrap(); + let a = node(dir_a.path(), 1); + let b = node(dir_b.path(), 2); + + // A saves a document: the web layer's publish into its LocalEvents. + let published = { + let mut a = a.lock().await; + a.publish("text/plain", b"hello from A", &[]).unwrap() + }; + // B has never seen it. + assert!(b.lock().await.history(published.id).is_err()); + + let server = endpoint().await; + let router = Router::builder(server.clone()) + .accept(ALPN, EventSyncProtocol::new(b.clone())) + .spawn(); + let client = endpoint().await; + let outcome = sync_with_peer(&client, loopback(&server), &a, &open_gate()) + .await + .unwrap(); + assert!( + outcome.sent >= 1, + "A sent nothing in the session: {outcome:?}" + ); + + // B discovers the signed revision in the document's history. + wait_for_history(&b, published.id).await; + let history = b.lock().await.history(published.id).unwrap(); + assert!( + history.iter().any(|entry| entry.id() == published.id), + "B's history does not hold A's revision: {history:?}" + ); + + router.shutdown().await.unwrap(); + client.close().await; + server.close().await; + } + + /// A second session between two stores that already agree sends nothing either + /// way: what arrived by sync is not sent back as new. + #[tokio::test(flavor = "multi_thread")] + async fn test_a_second_session_between_equal_stores_sends_nothing() { + let dir_a = tempfile::tempdir().unwrap(); + let dir_b = tempfile::tempdir().unwrap(); + let a = node(dir_a.path(), 3); + let b = node(dir_b.path(), 4); + let published = { + let mut a = a.lock().await; + a.publish("text/plain", b"one revision", &[]).unwrap() + }; + + let server = endpoint().await; + let router = Router::builder(server.clone()) + .accept(ALPN, EventSyncProtocol::new(b.clone())) + .spawn(); + let client = endpoint().await; + sync_with_peer(&client, loopback(&server), &a, &open_gate()) + .await + .unwrap(); + wait_for_history(&b, published.id).await; + let second = sync_with_peer(&client, loopback(&server), &a, &open_gate()) + .await + .unwrap(); + assert_eq!(second.sent, 0, "the second session re-sent events"); + assert_eq!(second.received, 0, "the second session re-received events"); + + router.shutdown().await.unwrap(); + client.close().await; + server.close().await; + } +} diff --git a/pkgs/id/src/lib.rs b/pkgs/id/src/lib.rs index 8fdb23e8f6..5b1975c2b6 100644 --- a/pkgs/id/src/lib.rs +++ b/pkgs/id/src/lib.rs @@ -181,6 +181,7 @@ pub mod envelope_net; #[cfg(feature = "world")] pub mod envelope_outbox; pub mod event_store; +pub mod event_sync; pub mod fileops; pub mod frames; pub mod groups; diff --git a/pkgs/id/src/local_events.rs b/pkgs/id/src/local_events.rs index 33d3a27e05..d84873faea 100644 --- a/pkgs/id/src/local_events.rs +++ b/pkgs/id/src/local_events.rs @@ -5,9 +5,11 @@ //! [`EventStore::ingest`], the path sync uses. The store checks the signature and applies the event. //! So these events are signed, unlike the group log's (P6.7a), which trusts the caller's name. //! -//! The store stands in for sync. The CLI opens one store directory, named by `--event-store`, and -//! nodes on one machine that share the directory see each other's events, as they share the group -//! log. Nothing here moves events between machines. +//! The CLI opens one store directory, named by `--event-store`, and nodes on one machine that +//! share the directory see each other's events, as they share the group log. Between machines, +//! `id serve` moves the events: it shares this store with the `/id-sync/1` range-sync sessions +//! in [`crate::event_sync`], so a revision one node signs into its store is in the sync set the +//! next session carries to a peer (#792). //! //! The reads walk every applied event, which is fine for the CLI and is not an index. The document //! and tag rules are the ones in [`crate::documents`] and [`crate::tag_claims`]. @@ -155,6 +157,34 @@ impl LocalEvents { Ok(Self { store, key }) } + /// Runs one range-sync session over `conn` against this node's store: the session + /// [`crate::event_store::sync::sync_over`] drives, with this store as its sync set. + /// `initiator` is the side that dialed. Every event that arrives is decided by the + /// store's own ingest, so a tampered or unsigned event is refused, never applied. + /// + /// # Errors + /// + /// Returns an error if the peer breaks the protocol, the session passes `deadline`, + /// `gate` refuses the peer, or the store fails. + pub async fn sync_session( + &mut self, + conn: &iroh::endpoint::Connection, + initiator: bool, + deadline: std::time::Duration, + gate: &crate::pull_policy::PullGate, + ) -> Result { + crate::event_store::sync::sync_over( + &mut self.store, + conn, + initiator, + crate::event_store::range::Params::default(), + now_ms(), + deadline, + gate, + ) + .await + } + /// The account the node's events are signed as. #[must_use] pub fn author(&self) -> AuthorKey { diff --git a/pkgs/id/src/web/mod.rs b/pkgs/id/src/web/mod.rs index 18a6a65590..6ae412ddde 100644 --- a/pkgs/id/src/web/mod.rs +++ b/pkgs/id/src/web/mod.rs @@ -197,7 +197,31 @@ impl AppState { &events_dir, p2panda_core::SigningKey::from_bytes(&secret_key), )?)); + Self::with_local_events( + store, + peers, + node_id, + tag_store, + secret_key, + identity_db_path, + local_events, + ) + .await + } + /// Create a new application state over a `local_events` store the caller already + /// opened and shares — `id serve` shares one instance between this state and the + /// `/id-sync/1` sync handler, so revisions saved here are the revisions sync + /// carries, with no second opener on the store's directory (#792). + pub async fn with_local_events( + store: Store, + peers: Option, + node_id: String, + tag_store: Arc, + secret_key: [u8; 32], + identity_db_path: std::path::PathBuf, + local_events: Arc>, + ) -> anyhow::Result { Ok(Self { store, collab: Arc::new(CollabState::new()), @@ -287,7 +311,7 @@ pub async fn web_router( world: Option, cookie_secure: bool, ) -> anyhow::Result { - let mut state = AppState::new( + let state = AppState::new( store, peers, node_id, @@ -296,18 +320,54 @@ pub async fn web_router( identity_db_path, ) .await?; + Ok(finish_router(state, security, world, cookie_secure)) +} + +/// Like [`web_router`], but over a caller-opened, shared `local_events` store (see +/// [`AppState::with_local_events`]). +#[allow(clippy::too_many_arguments)] +pub async fn web_router_with_local_events( + store: Store, + peers: Option, + node_id: String, + tag_store: Arc, + secret_key: [u8; 32], + identity_db_path: std::path::PathBuf, + security: WebSecurity, + world: Option, + cookie_secure: bool, + local_events: Arc>, +) -> anyhow::Result { + let state = AppState::with_local_events( + store, + peers, + node_id, + tag_store, + secret_key, + identity_db_path, + local_events, + ) + .await?; + Ok(finish_router(state, security, world, cookie_secure)) +} + +/// Applies the world/cookie settings and the security layer to a built state. +fn finish_router( + mut state: AppState, + security: WebSecurity, + world: Option, + cookie_secure: bool, +) -> Router { state.world = world; state.cookie_secure = cookie_secure; let security = WebSecurity { cookie_secure, ..security }; - Ok( - create_router(state).layer(axum::middleware::from_fn_with_state( - Arc::new(security), - security::guard, - )), - ) + create_router(state).layer(axum::middleware::from_fn_with_state( + Arc::new(security), + security::guard, + )) } #[cfg(test)]