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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
115 changes: 103 additions & 12 deletions pkgs/id/src/commands/serve.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Arc<tokio::sync::Mutex<crate::local_events::LocalEvents>>> = 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")]
Expand Down Expand Up @@ -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
Expand All @@ -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(
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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;
Expand Down
97 changes: 72 additions & 25 deletions pkgs/id/src/event_store/sync.rs
Original file line number Diff line number Diff line change
@@ -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.
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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?;
Expand All @@ -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?;
Comment on lines +545 to +546

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Send the applied acknowledgment only after successful ingestion

If receive_data fails—for example, because the receiving store cannot commit a batch after running out of disk space—this notification still releases the sending half to write APPLIED_FRAME before the error is propagated. In a one-way transfer, the sender can consequently receive that acknowledgment and report a successful session even though the receiving node did not persist its revisions. Separate failure cancellation from successful completion so an ingestion error terminates the session without acknowledging application.

Useful? React with 👍 / 👎.

// 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<Event> = 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))
};

Expand All @@ -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<Id>,
now_ms: u64,
commits: &Option<CommitSignal>,
) -> 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<Event> = 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<Event>,
Expand Down
Loading
Loading