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
6 changes: 3 additions & 3 deletions pkgs/id/src/world/actor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -251,7 +251,7 @@ pub(crate) enum WorldCommand {
reply: oneshot::Sender<
Result<(
String,
JournalSnapshot,
JournalSnapshotSource,
broadcast::Receiver<ReplicationUpdate>,
)>,
>,
Expand Down Expand Up @@ -1622,8 +1622,8 @@ impl WorldActor {
self.journal
.as_mut()
.ok_or_else(|| anyhow::anyhow!("world has no durable journal"))
.and_then(|journal| journal.replication_snapshot())
.map(|snapshot| (world_id, snapshot, updates))
.and_then(|journal| journal.replication_snapshot_source())
.map(|snapshot_source| (world_id, snapshot_source, updates))
};
let _ = reply.send(result);
}
Expand Down
2 changes: 1 addition & 1 deletion pkgs/id/src/world/handle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ impl WorldHandle {
&self,
) -> Result<(
String,
JournalSnapshot,
JournalSnapshotSource,
broadcast::Receiver<ReplicationUpdate>,
)> {
let (reply, response) = oneshot::channel();
Expand Down
72 changes: 72 additions & 0 deletions pkgs/id/src/world/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
//! counts are local to the hosting node and need not converge across partitions.

use std::collections::{BTreeMap, BTreeSet, VecDeque};
use std::io::Read;

use anyhow::{Context, Result, bail, ensure};
use rand::RngExt as _;
Expand Down Expand Up @@ -1074,6 +1075,15 @@ pub trait WorldJournal: Send + 'static {
bail!("this journal cannot provide a replication snapshot")
}

/// Capture a lightweight, readable source for the initial replication
/// feed. Durable file journals should pin the file and its current length
/// here, then defer reading the bytes until the network layer requests it.
/// Journals that cannot provide a deferred source should leave this
/// unsupported rather than materializing the full image in the actor.
fn replication_snapshot_source(&mut self) -> Result<JournalSnapshotSource> {
bail!("this journal cannot provide a deferred replication snapshot source")
}

/// Current journal header version, when the implementation can report it.
fn replication_header_version(&self) -> Option<u32> {
None
Expand Down Expand Up @@ -1101,6 +1111,68 @@ pub struct JournalSnapshot {
pub bytes: Vec<u8>,
}

/// A captured snapshot reader. File-backed journals keep only a pinned file
/// handle and the captured byte length in the actor; the network layer reads
/// the bytes after the actor has resumed handling commands.
pub struct JournalSnapshotSource {
/// Version in the journal's `Created` header.
pub header_version: u32,
/// Number of bytes belonging to this captured image.
pub byte_len: u64,
reader: Box<dyn Read + Send>,
}

impl std::fmt::Debug for JournalSnapshotSource {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("JournalSnapshotSource")
.field("header_version", &self.header_version)
.field("byte_len", &self.byte_len)
.finish_non_exhaustive()
}
}

impl JournalSnapshotSource {
pub(crate) fn from_reader<R>(header_version: u32, byte_len: u64, reader: R) -> Self
where
R: Read + Send + 'static,
{
Self {
header_version,
byte_len,
reader: Box::new(reader),
}
}

/// Read exactly the captured image. This consumes the source, so its file
/// handle and the resulting byte buffer have one clear owner at a time.
///
/// # Errors
///
/// If the source cannot be read completely, is too large for this target,
/// or does not end at a journal-entry boundary.
pub fn read(self) -> Result<JournalSnapshot> {
let capacity = usize::try_from(self.byte_len).context("journal snapshot is too large")?;
let mut bytes = Vec::with_capacity(capacity);
self.reader
.take(self.byte_len)
.read_to_end(&mut bytes)
.context("read captured journal snapshot")?;
ensure!(
bytes.len() == capacity,
"captured journal snapshot changed while reading"
);
ensure!(
bytes.is_empty() || bytes.ends_with(b"\n"),
"captured journal snapshot has an unterminated final entry"
);
Ok(JournalSnapshot {
header_version: self.header_version,
bytes,
})
}
}

/// A durable change delivered to replication subscribers.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ReplicationUpdate {
Expand Down
38 changes: 25 additions & 13 deletions pkgs/id/src/world_replication_net.rs
Original file line number Diff line number Diff line change
Expand Up @@ -117,18 +117,28 @@ async fn serve_stream(
.lease(request.world.as_deref(), None)
.await
.map_err(|error| anyhow::anyhow!("open replication world: {}", error.message()))?;
let (world_id, snapshot, mut updates) = lease.service().world().replication_feed().await?;
let (world_id, snapshot_source, mut updates) =
lease.service().world().replication_feed().await?;
let source = *signing_key.verifying_key().as_bytes();
let (mut cursor, mut header_version, mut prev_frame_digest) = send_snapshot(
&mut send,
signing_key,
&world_id,
source,
request.session_nonce,
&snapshot,
[0; 32],
)
.await?;
// Only the pinned file handle and captured length crossed the actor
// boundary. Read the initial image on the blocking pool, then confine its
// owned bytes to this transfer so they are dropped before following
// updates for the lifetime of the stream.
let (mut cursor, mut header_version, mut prev_frame_digest) = {
let snapshot = tokio::task::spawn_blocking(move || snapshot_source.read())
.await
.context("initial replication snapshot read task")??;
send_snapshot(
&mut send,
signing_key,
&world_id,
source,
request.session_nonce,
snapshot,
[0; 32],
)
.await?
};

loop {
match updates.recv().await {
Expand Down Expand Up @@ -161,7 +171,7 @@ async fn serve_stream(
&world_id,
source,
request.session_nonce,
&reset,
reset,
prev_frame_digest,
)
.await?;
Expand Down Expand Up @@ -191,13 +201,15 @@ fn ensure_nonce(nonce: &[u8; 16]) -> Result<()> {
Ok(())
}

// Take ownership of each snapshot so its journal buffer cannot escape into
// the long-lived update loop after the transfer has been sent.
async fn send_snapshot(
send: &mut SendStream,
signing_key: &SigningKey,
world_id: &str,
source: [u8; 32],
nonce: [u8; 16],
snapshot: &JournalSnapshot,
snapshot: JournalSnapshot,
mut prev_frame_digest: [u8; 32],
) -> Result<(ReplicationCursor, u32, [u8; 32])> {
let chunks = split_entry_payload(&snapshot.bytes).context("split journal snapshot")?;
Expand Down
57 changes: 52 additions & 5 deletions pkgs/id/src/world_store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,23 @@ impl WorldJournal for FileJournal {
})
}

fn replication_snapshot_source(&mut self) -> Result<crate::world::JournalSnapshotSource> {
// Open a separate descriptor while the actor still owns the journal.
// It pins the current inode across compaction, and the captured length
// excludes appends that happen after the actor returns to its loop.
let file = File::open(&self.path)
.with_context(|| format!("open world journal snapshot {}", self.path.display()))?;
let byte_len = file
.metadata()
.with_context(|| format!("stat world journal snapshot {}", self.path.display()))?
.len();
Ok(crate::world::JournalSnapshotSource::from_reader(
self.version,
byte_len,
file,
))
}

fn replication_header_version(&self) -> Option<u32> {
Some(self.version)
}
Expand Down Expand Up @@ -689,19 +706,26 @@ mod tests {
.await
.unwrap();
let world = service.world();
let (world_id, first, mut first_updates) = world.replication_feed().await.unwrap();
let (second_world_id, second, mut second_updates) = world.replication_feed().await.unwrap();
let (world_id, first_source, mut first_updates) = world.replication_feed().await.unwrap();
let (second_world_id, second_source, mut second_updates) =
world.replication_feed().await.unwrap();
let durable_bytes = std::fs::read(dir.path().join("journal.jsonl")).unwrap();
assert_eq!(world_id, "lobby");
assert_eq!(second_world_id, world_id);
assert_eq!(first, second);
assert_eq!(first.bytes, durable_bytes);
assert!(first.bytes.ends_with(b"\n"));
assert_eq!(first_source.header_version, second_source.header_version);
assert_eq!(first_source.byte_len, durable_bytes.len() as u64);

// The actor is free to append before the network materializes either
// source. The captured length still bounds both snapshots to this cut.
world
.set_isolation(Authority::Admin, Isolation::Unisolated)
.await
.unwrap();
let first = first_source.read().unwrap();
let second = second_source.read().unwrap();
assert_eq!(first, second);
assert_eq!(first.bytes, durable_bytes);
assert!(first.bytes.ends_with(b"\n"));
for update in [
first_updates.recv().await.unwrap(),
second_updates.recv().await.unwrap(),
Expand Down Expand Up @@ -748,6 +772,29 @@ mod tests {
assert_eq!(std::fs::read(&path).unwrap(), expected);
}

#[test]
fn replication_snapshot_source_is_pinned_and_reads_only_its_captured_length() {
let dir = TempDir::new().unwrap();
let path = dir.path().join("journal.jsonl");
let (mut journal, entries) = FileJournal::open(&path, "lobby").unwrap();
journal
.append(&JournalEntry::Isolation {
isolation: Isolation::Unisolated,
})
.unwrap();
let expected = std::fs::read(&path).unwrap();
let source = journal.replication_snapshot_source().unwrap();
assert_eq!(source.byte_len, expected.len() as u64);

// Replacing the path after capture must not redirect the reader to a
// compacted image; the source owns the old inode and captured length.
journal.compact(&entries).unwrap();
let snapshot = source.read().unwrap();
assert_eq!(snapshot.bytes, expected);
assert!(snapshot.bytes.ends_with(b"\n"));
assert_ne!(std::fs::read(&path).unwrap(), snapshot.bytes);
}

#[tokio::test]
async fn isolation_survives_a_restart() {
let dir = TempDir::new().unwrap();
Expand Down