diff --git a/arc/sync.md b/arc/sync.md index ea55d55df01d6b44d34ed298bf25eff32fbe46d6..8c9be492de561b6eb293de03b61ef3424d8cc189 100644 --- a/arc/sync.md +++ b/arc/sync.md @@ -128,8 +128,11 @@ section. Uncertainty is handled explicitly. A publication attempt is recorded before the first network byte. If the reply is lost, the attempt confirms only when the remote holds its revisions (or every page it changed, as it changed them). -Otherwise it waits as `AwaitingConfirmation`, and `release` resolves it -explicitly: it exports a recovery archive first, then republishes or abandons. +Otherwise it waits as `AwaitingConfirmation`. A Live Share host lands a batch at +most once, as it looks for the batch's revisions before applying it, so the next +step sends it the same batch again. Any other remote, where a late write could land +a second copy, waits for `release`, which exports a recovery archive first, then +republishes or abandons. ## Merging diff --git a/crates/notebook/README.md b/crates/notebook/README.md index 76c5e5926b7975b303403317fdc1eb182e140a2f..cca453712e71f4c92abb59e39e3d1eb119347eb5 100644 --- a/crates/notebook/README.md +++ b/crates/notebook/README.md @@ -164,9 +164,11 @@ merges back. Publication attempts are recorded before network I/O. An attempt confirms only when the remote holds its revisions, or every page it changed as it changed them, -followed by `Remote::confirm`; otherwise it stays `AwaitingConfirmation` and is never -replayed. `release(id, archive, Resolution)` exports the queue first, then -publishes the batch again (`Mine`) or abandons every unpublished edit (`Theirs`). +followed by `Remote::confirm`; otherwise it stays `AwaitingConfirmation`. A remote that +accepts edits (a Live Share host) lands a batch at most once, so the next step sends it the +same batch again; any other remote never gets it again unreviewed. +`release(id, archive, Resolution)` exports the queue first, then publishes the batch again +(`Mine`) or abandons every unpublished edit (`Theirs`). A durable `Published` receipt survives reopening. A schema-14 cache is converted when opened: it is exported to diff --git a/crates/notebook/src/background.rs b/crates/notebook/src/background.rs index b7eac704e8b3ad15fd27cba885ce013d941bb8b1..d41f06e1c9741fc340852683b713e3e31aa424db 100644 --- a/crates/notebook/src/background.rs +++ b/crates/notebook/src/background.rs @@ -1105,6 +1105,19 @@ impl Remote for Discovered<'_, R> { self.remote.confirm(base) } + fn accepts_edits(&self) -> bool { + self.remote.accepts_edits() + } + + fn publish_edits( + &mut self, + transaction: &onestore::Transaction, + edits: &[crate::PendingEdit], + revisions: &std::collections::BTreeMap, + ) -> std::result::Result<(), onestore::CommitError> { + self.remote.publish_edits(transaction, edits, revisions) + } + fn versions(&mut self) -> io::Result> { self.remote.versions() } diff --git a/crates/notebook/src/live/share.rs b/crates/notebook/src/live/share.rs index d0fd3c305336cd2eb48a06fa597342f95be619aa..ff981ca97260110ec28bf6cbea7911ce158946ef 100644 --- a/crates/notebook/src/live/share.rs +++ b/crates/notebook/src/live/share.rs @@ -14,7 +14,7 @@ use crate::{Error, Result, background::Reports, discover, session::Storage}; use onestore::{CommitError, CommitState, RevisionIndex, Stamp, Store, Transaction}; use sha2::{Digest, Sha256}; use std::{ - collections::{BTreeMap, HashMap}, + collections::{BTreeMap, HashMap, HashSet}, io, path::PathBuf, sync::{ @@ -294,6 +294,9 @@ struct Served { puts: Mutex>>, guests: Mutex>, writers: Mutex>>, + /// The revisions guests' batches landed as, by page: OneNote's Optimize drops one a + /// later revision supersedes, and a batch sent again must still find it. + landed: Mutex>, /// Hears the paths guests changed, as the host's own notebook should. host: Mutex>, /// The share's room, to tell guests what changed. @@ -1848,6 +1851,8 @@ pub struct HostedRemote { path: String, /// The stamp last asked for, which an image the guest holds may already have. seen: Option, + /// The host refused the last batch, so the next step reads its image before sending + /// edits. A stamp clears it, as an uncertain batch goes again regardless. rejected: bool, #[cfg(target_arch = "wasm32")] pending: Option, @@ -1914,6 +1919,7 @@ impl crate::Remote for HostedRemote { } fn stamp(&mut self) -> io::Result { + self.rejected = false; let stamp = self.guest.stamp(&self.path)?; self.seen = Some(stamp.clone()); Ok(stamp) @@ -2159,6 +2165,7 @@ mod tests { puts: Mutex::default(), guests: Mutex::default(), writers: Mutex::default(), + landed: Mutex::default(), host: Mutex::default(), room: Mutex::default(), }); diff --git a/crates/notebook/src/live/share/batch.rs b/crates/notebook/src/live/share/batch.rs index d7d95501d9a7549fc0db3a68411beb4d32a2f005..ae5d2228e18bed5bf836345732550277e7858d3e 100644 --- a/crates/notebook/src/live/share/batch.rs +++ b/crates/notebook/src/live/share/batch.rs @@ -114,9 +114,10 @@ impl Served { let mut image = Arc::clone(&before); let mut combined: Option = None; let mut accepted = Vec::new(); + let mut landing = Vec::new(); for batch in waiting { match self.prepare_batch(path, &image, &batch) { - Ok(Some(transaction)) => { + Ok((Some(transaction), revisions)) => { let mut next = (*image).clone(); let extended = transaction @@ -131,6 +132,7 @@ impl Served { match extended { Ok(()) => { image = Arc::new(next); + landing.extend(revisions); accepted.push(batch); } Err(error) => { @@ -138,7 +140,7 @@ impl Served { } } } - Ok(None) => accepted.push(batch), + Ok((None, _)) => accepted.push(batch), Err(error) => { let _ = batch.reply.send(failed(0, error)); } @@ -166,6 +168,7 @@ impl Served { }), }; if result.is_ok() { + self.landed.lock().unwrap().extend(landing); self.tell_delta(path, &before, &image, None); self.keep(path, Arc::clone(&image)); self.changed(&[path.to_owned()]); @@ -194,7 +197,7 @@ impl Served { path: &str, image: &[u8], batch: &Waiting, - ) -> Result> { + ) -> Result<(Option, BTreeMap)> { if !self.guests.lock().unwrap().contains_key(&batch.peer) { return Err(refused( io::ErrorKind::PermissionDenied, @@ -219,14 +222,15 @@ impl Served { } let store = Store::parse(image)?; let index = RevisionIndex::parse(&store)?; + let landed = self.landed.lock().unwrap(); if edits.revisions.iter().all(|(space, revision)| { - index - .spaces - .get(space) - .is_some_and(|space| space.revisions.contains_key(revision)) + landed.contains(&(*space, *revision)) + || (index.spaces.get(space)) + .is_some_and(|space| space.revisions.contains_key(revision)) }) { - return Ok(None); + return Ok((None, edits.revisions)); } + drop(landed); let names = edits .revisions .iter() @@ -306,7 +310,7 @@ impl Served { "The batch needs a guest's commit", )); } - Ok(transaction) + Ok((transaction, edits.revisions)) } } @@ -333,6 +337,7 @@ mod tests { puts: Mutex::default(), guests: Mutex::default(), writers: Mutex::default(), + landed: Mutex::default(), host: Mutex::default(), room: Mutex::default(), }); @@ -461,6 +466,132 @@ mod tests { assert_eq!(served.writers.lock().unwrap().len(), 1); } + /// OneNote's Optimize drops a revision a later one superseded, as the page-versions + /// corpus shows; a batch sent again after its revision went that way is not applied + /// again. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_batch_whose_revision_optimize_dropped_lands_once() { + let directory = tempfile::tempdir().unwrap(); + let folder = directory.path().join("notebook"); + std::fs::create_dir(&folder).unwrap(); + let path = "Garden.one"; + let base = onestore::create_section(path, "Original text", "Fixture").unwrap(); + std::fs::write(folder.join(path), &base).unwrap(); + let served = Arc::new(Served { + storage: crate::session::Notebook::open(&folder, directory.path().join("cache")) + .unwrap() + .into_storage(), + images: Mutex::default(), + snapshots: Mutex::default(), + puts: Mutex::default(), + guests: Mutex::default(), + writers: Mutex::default(), + landed: Mutex::default(), + host: Mutex::default(), + room: Mutex::default(), + }); + let peer = [1; 16]; + let (line, _outbound) = mpsc::channel(); + let (queue, _requests) = mpsc::sync_channel(1); + served.guests.lock().unwrap().insert( + peer, + Admitted { + hello: Arc::new(Hello { + peer, + ..Hello::new("Guest".into(), None).unwrap() + }), + line: crate::live::Line(line), + queue, + starts: BURST, + counted: Instant::now(), + held: Vec::new(), + }, + ); + let store = Store::parse(&base).unwrap(); + let index = RevisionIndex::parse(&store).unwrap(); + let document = onestore::document::Document::parse(&index).unwrap(); + let (space, text) = document + .spaces + .iter() + .find_map(|(space, object)| { + object.revisions[&object.contexts[&ExGuid::default()]] + .nodes + .iter() + .find_map(|(id, node)| { + matches!(node.kind, onestore::document::Kind::RichText { .. }) + .then_some((*space, *id)) + }) + }) + .unwrap(); + let typed = |range: std::ops::Range, with: &str| Edit { + at: 134_000_000_000_000_000, + ops: vec![Op::Page { + space, + op: PageOp::Text { + text, + range, + with: with.into(), + }, + }], + }; + let arena = Arena::default(); + let mut section = Section::open(&arena, base.clone()).unwrap(); + section.apply("Guest", &typed(13..13, "X")).unwrap(); + let transaction = section.seal().unwrap().unwrap(); + let request = Request { + path: path.into(), + stamp: Some(transaction.base().into()), + bytes: Some( + encode( + &Edits { + edits: vec![("Guest".into(), typed(13..13, "X"))], + revisions: section.newest().filter(|(at, _)| *at == space).collect(), + }, + LIMIT, + ) + .unwrap(), + ), + ..Request::default() + }; + assert!( + served + .batch(&peer, request.clone()) + .unwrap() + .failure + .is_none() + ); + + // The host deletes what the batch typed, and Optimize keeps the page's newest + // revision alone: the file holds neither the text nor the batch's revision. + let arena = Arena::default(); + let mut optimized = Section::open(&arena, base.clone()).unwrap(); + optimized.apply("Guest", &typed(13..13, "X")).unwrap(); + optimized.apply("Host", &typed(13..14, "")).unwrap(); + let mut image = base; + optimized + .seal() + .unwrap() + .unwrap() + .apply(&mut image) + .unwrap(); + std::fs::write(folder.join(path), &image).unwrap(); + let replayed = served.batch(&peer, request).unwrap(); + assert!(replayed.failure.is_none(), "{:?}", replayed.failure); + let stored = std::fs::read(folder.join(path)).unwrap(); + let arena = Arena::default(); + let section = Section::open(&arena, stored).unwrap(); + let texts: Vec = (section.page(space).unwrap().objects.iter()) + .filter_map(|object| match object { + PageObject::Outline(outline) => Some(outline.paragraphs.iter()), + _ => None, + }) + .flatten() + .filter_map(|paragraph| Some(paragraph.text()?.text.text().to_owned())) + .collect(); + assert_eq!(texts, ["Original text"]); + } + #[test] fn attachment_encoding_stops_at_the_upload_budget() { let id = ExGuid { diff --git a/crates/notebook/src/live/share/handover_tests.rs b/crates/notebook/src/live/share/handover_tests.rs index feb9c7813e796dd970ff9dd16c1939f6910b2ef9..d46d64cda29f8c57d4c79587f28fd553b7ca908c 100644 --- a/crates/notebook/src/live/share/handover_tests.rs +++ b/crates/notebook/src/live/share/handover_tests.rs @@ -438,6 +438,7 @@ fn served() -> (tempfile::TempDir, Arc) { puts: Mutex::default(), guests: Mutex::default(), writers: Mutex::default(), + landed: Mutex::default(), host: Mutex::default(), room: Mutex::default(), }); diff --git a/crates/notebook/src/live/share/membership.rs b/crates/notebook/src/live/share/membership.rs index 3254d7ab3c7ba828e61a33eb1512a2f9b7b4a041..f4776b8279d2ce10a743c0d685ce0ab484aefded 100644 --- a/crates/notebook/src/live/share/membership.rs +++ b/crates/notebook/src/live/share/membership.rs @@ -52,6 +52,7 @@ impl Host { puts: Mutex::default(), guests: Mutex::default(), writers: Mutex::default(), + landed: Mutex::default(), host: Mutex::default(), room: Mutex::default(), }), diff --git a/crates/notebook/src/live/share/web.rs b/crates/notebook/src/live/share/web.rs index cd5fcc65644f462a18d4666f0120958100f20471..b6f01cddc528ab9cd5e0c344e8440a92af2a6632 100644 --- a/crates/notebook/src/live/share/web.rs +++ b/crates/notebook/src/live/share/web.rs @@ -90,6 +90,7 @@ impl crate::Remote for HostedRemote { } fn stamp(&mut self) -> io::Result { + self.rejected = false; let (guest, path) = (self.guest.clone(), self.path.clone()); let result = self .operation(async move { diff --git a/crates/notebook/src/sync.rs b/crates/notebook/src/sync.rs index 6a6d825211aeb740e97001bc94b67385f8054999..0ecc05109ca7d86f6d3a6daad75ceba040d5cec8 100644 --- a/crates/notebook/src/sync.rs +++ b/crates/notebook/src/sync.rs @@ -27,6 +27,8 @@ pub trait Remote { fn accepts_edits(&self) -> bool { false } + /// Where the remote accepts edits, a batch published again with the same revisions, + /// however its first attempt ended, lands at most once. fn publish_edits( &mut self, transaction: &Transaction, @@ -223,7 +225,7 @@ impl Replica { /// Publishes the oldest unpublished batch, rebasing the queue first when the remote /// changed. Reads the remote image only when its stamp moved; network I/O holds /// synchronization ownership without holding the cache mutex. Uncertain attempts are - /// never replayed. + /// replayed only to a remote that accepts edits. /// Versions the remote keeps beside the file merge into it first, each published as one /// more revision and then retired (`resolve.rs`). pub fn sync_once(&self, remote: &mut impl Remote) -> Result { @@ -281,6 +283,19 @@ impl Replica { let observed = awaited(remote, Remote::stamp) .await .map_err(Error::RemoteIo)?; + let replay = match &state.blocked { + Some(blocked) if self.section.key.is_none() && remote.accepts_edits() => { + working::sealed(&*self.lock()?)? + .filter(|sealed| sealed.batch == blocked.batch) + .and_then(|sealed| sealed.transaction) + } + _ => None, + }; + if let (Some(blocked), Some(transaction)) = (&state.blocked, replay) { + return self + .publish_sealed(remote, blocked.batch, transaction, true, true, Vec::new()) + .await; + } if let Some(blocked) = &state.blocked && observed == *state.remote.as_ref().unwrap_or(&state.base) { @@ -419,8 +434,8 @@ impl Replica { changed, }); }; - let id = newest(&*self.lock()?, batch)?; let Some(transaction) = transaction else { + let id = newest(&*self.lock()?, batch)?; // Edits that changed nothing are published once the remote's image is durable. let base = base::base_stamp(&*self.lock()?)?; if let Err(error) = awaited(remote, |remote| remote.confirm(&base)).await { @@ -441,6 +456,24 @@ impl Replica { .execute("UPDATE batches SET attempted=0 WHERE id=?1", [batch])?; return Err(error.into()); } + self.publish_sealed(remote, batch, transaction, batched, false, changed) + .await + } + + /// Publishes the attempted `batch` sealed as `transaction`, rebasing on the remote's + /// image after where `batched`; `changed` holds the pages a rebase already changed. An + /// attempt made `again` stays uncertain until the remote takes it, as the first may + /// still land. + async fn publish_sealed( + &self, + remote: &mut impl Remote, + batch: i64, + transaction: Transaction, + batched: bool, + again: bool, + mut changed: Vec, + ) -> Result { + let id = newest(&*self.lock()?, batch)?; let published = if self.section.key.is_none() && remote.accepts_edits() { let (edits, revisions) = { let connection = self.lock()?; @@ -461,7 +494,7 @@ impl Replica { }; match published { Ok(()) => {} - Err(error) if error.state == CommitState::NotCommitted => { + Err(error) if error.state == CommitState::NotCommitted && !again => { self.lock()? .execute("UPDATE batches SET attempted=0 WHERE id=?1", [batch])?; return Err(error.into()); diff --git a/crates/notebook/tests/live_batch.rs b/crates/notebook/tests/live_batch.rs index e03bc5b4596da76878314e9f8ca3470418ecb9e1..6f5cd8723131b8aea0817f6ec2e8918d8434706e 100644 --- a/crates/notebook/tests/live_batch.rs +++ b/crates/notebook/tests/live_batch.rs @@ -207,34 +207,6 @@ fn edit_receipts_survive_guest_and_host_process_death() { stopped_at_boundary(&root); } let mut remote = HostedRemote::new(&guest, "Garden.one"); - if boundary == "unsent" { - let attempted = replica.status(id).unwrap(); - assert!(matches!( - attempted, - Some(EditStatus::AwaitingConfirmation { .. }) - )); - let pending = replica.pending().unwrap(); - let snapshot = replica.snapshot().unwrap(); - let original = std::fs::read(root.join("Garden/Garden.one")).unwrap(); - for _ in 0..3 { - replica.sync_once(&mut remote).unwrap(); - assert_eq!(replica.status(id).unwrap(), attempted); - assert_eq!(replica.pending().unwrap(), pending); - assert_eq!(replica.snapshot().unwrap(), snapshot); - assert_eq!( - std::fs::read(root.join("Garden/Garden.one")).unwrap(), - original - ); - } - let archive = root.join("before-review.sqlite"); - replica - .release(id, &archive, notebook::Resolution::Mine) - .unwrap(); - let archive = notebook::Recovery::open(archive).unwrap(); - assert_eq!(archive.status(id).unwrap(), attempted); - assert_eq!(archive.pending().unwrap(), pending); - assert_eq!(archive.snapshot().unwrap(), snapshot); - } for _ in 0..5 { replica.sync_once(&mut remote).unwrap(); if matches!( @@ -421,29 +393,6 @@ fn edit_receipts_survive_guest_and_host_process_death() { assert!(replica.pending().unwrap().is_empty()); assert_eq!(replica.snapshot().unwrap(), result); drop(replica); - if boundary == "unsent" { - let archive = notebook::Recovery::open(root.join("before-review.sqlite")).unwrap(); - assert!(matches!( - archive.status(id).unwrap(), - Some(EditStatus::AwaitingConfirmation { .. }) - )); - assert_eq!(archive.pending().unwrap()[0].id, id); - assert_eq!(archive.pending().unwrap().len(), 1); - assert_eq!( - body(&archive.snapshot().unwrap()).2, - format!("{content}{INSERTION}") - ); - let database = rusqlite::Connection::open(root.join("before-review.sqlite")).unwrap(); - assert_eq!( - database - .query_row("PRAGMA integrity_check", [], |row| row.get::<_, String>(0)) - .unwrap(), - "ok" - ); - println!( - "unsent: cold uncertainty retained; explicit Mine review archived the original queue before publication" - ); - } let database = rusqlite::Connection::open(&database).unwrap(); assert_eq!( database @@ -535,3 +484,195 @@ fn concurrent_batches_keep_receipts_and_rebase_later_keystrokes() { let mut section = onestore::Section::open(&arena, result).unwrap(); assert!(section.conflicts().unwrap().is_empty()); } + +/// A batch whose request the relay loses with the guest's connection is uncertain; once the +/// guest is back, the host hears it again and it lands once. +#[test] +fn a_batch_lost_on_the_way_lands_once_the_guest_is_back() { + use notebook::{EditStatus, Error, Remote, live::share::Guest}; + use onestore::{CommitError, CommitState}; + + let directory = tempfile::tempdir().unwrap(); + let folder = notebook(directory.path()); + let url = relay(Default::default()); + let sharing = Sharing::new("").unwrap(); + let host = host(&folder, &directory.path().join("host"), &sharing, &url); + let welcome = + notebook::live::share::join(hello("Grace"), &code(&host), "", None, Some(&url)).unwrap(); + let relay = PresenceRelay::new(&url, &welcome.room); + let guest = Guest::start( + hello("Grace"), + welcome.share, + welcome.secret, + None, + Some(&relay.url), + || {}, + ) + .unwrap(); + until("the host was never met", || guest.host().is_some()); + let file = folder.join("Garden.one"); + let original = std::fs::read(&file).unwrap(); + let (space, text, _) = server::text(&original); + let typed = |with: &str| Edit { + at: 134_000_000_000_000_000, + ops: vec![Op::Page { + space, + op: PageOp::Text { + text, + range: 0..0, + with: with.into(), + }, + }], + }; + let replica = Replica::open_or_create(directory.path().join("grace.sqlite"), None, || { + Ok(original.clone()) + }) + .unwrap(); + let remote = std::cell::RefCell::new(HostedRemote::new(&guest, "Garden.one")); + let first = replica.apply("Grace", typed("A")).unwrap(); + until("the first edit was never published", || { + let _ = replica.sync_once(&mut *remote.borrow_mut()); + matches!( + replica.status(first).unwrap(), + Some(EditStatus::Published { .. }) + ) + }); + until("the host's stamp was never known without asking", || { + let before = relay.state.lock().unwrap().access_bytes; + remote.borrow_mut().stamp().unwrap(); + relay.state.lock().unwrap().access_bytes == before + }); + + relay.state.lock().unwrap().swallow = true; + let second = replica.apply("Grace", typed("B")).unwrap(); + assert!(matches!( + replica.sync_once(&mut *remote.borrow_mut()), + Err(Error::Remote(CommitError { + state: CommitState::Unknown, + .. + })) + )); + assert!(matches!( + replica.status(second).unwrap(), + Some(EditStatus::AwaitingConfirmation { .. }) + )); + // OneNote on the host holds the section as the batch comes again, and lets it go. The + // app's sync worker keeps its remote after such a refusal. + let held = std::fs::File::open(&file).unwrap(); + held.lock_shared().unwrap(); + let remote = std::cell::RefCell::new(HostedRemote::new(&guest, "Garden.one")); + until( + "the host never refused the batch while OneNote held it", + || { + matches!( + replica.sync_once(&mut *remote.borrow_mut()), + Err(Error::Remote(CommitError { + state: CommitState::NotCommitted, + .. + })) + ) + }, + ); + drop(held); + until("the uncertain batch never landed", || { + let _ = replica.sync_once(&mut *remote.borrow_mut()); + matches!( + replica.status(second).unwrap(), + Some(EditStatus::Published { .. }) + ) + }); + assert_eq!( + server::text(&std::fs::read(&file).unwrap()).2, + "BAOriginal text" + ); +} + +/// A section closed while its batch is uncertain sends the batch again from the +/// background, which keeps a notebook's closed sections in sync. +#[test] +fn a_closed_section_s_uncertain_batch_lands_from_the_background() { + use notebook::{ + EditStatus, Error, Remote, + live::share::Guest, + session::{Background, Notebook}, + }; + use onestore::{CommitError, CommitState}; + + let directory = tempfile::tempdir().unwrap(); + let folder = notebook(directory.path()); + let url = relay(Default::default()); + let sharing = Sharing::new("").unwrap(); + let host = host(&folder, &directory.path().join("host"), &sharing, &url); + let welcome = + notebook::live::share::join(hello("Grace"), &code(&host), "", None, Some(&url)).unwrap(); + let relay = PresenceRelay::new(&url, &welcome.room); + let guest = Guest::start( + hello("Grace"), + welcome.share, + welcome.secret, + None, + Some(&relay.url), + || {}, + ) + .unwrap(); + until("the host was never met", || guest.host().is_some()); + let mut notebook = + Notebook::open_hosted(Arc::clone(&guest), directory.path().join("grace")).unwrap(); + let file = folder.join("Garden.one"); + let original = std::fs::read(&file).unwrap(); + let (space, text, _) = server::text(&original); + let path = notebook.replica_path("Garden.one").unwrap(); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + let replica = Replica::open_or_create(&path, None, || Ok(original.clone())).unwrap(); + let typed = |with: &str| Edit { + at: 134_000_000_000_000_000, + ops: vec![Op::Page { + space, + op: PageOp::Text { + text, + range: 0..0, + with: with.into(), + }, + }], + }; + let first = replica.apply("Grace", typed("A")).unwrap(); + until("the first edit was never published", || { + let _ = replica.sync_once(&mut HostedRemote::new(&guest, "Garden.one")); + matches!( + replica.status(first).unwrap(), + Some(EditStatus::Published { .. }) + ) + }); + until("the host's stamp was never known without asking", || { + let before = relay.state.lock().unwrap().access_bytes; + HostedRemote::new(&guest, "Garden.one").stamp().unwrap(); + relay.state.lock().unwrap().access_bytes == before + }); + relay.state.lock().unwrap().swallow = true; + let id = replica.apply("Grace", typed("B")).unwrap(); + assert!(matches!( + replica.sync_once(&mut HostedRemote::new(&guest, "Garden.one")), + Err(Error::Remote(CommitError { + state: CommitState::Unknown, + .. + })) + )); + drop(replica); + let background = Background::hosted(Arc::clone(&guest), || {}).unwrap(); + background.watch(notebook.replicas()); + // As the app does, the background is woken whenever the guest meets its host again. + let reached = std::cell::Cell::new(guest.host().is_some()); + until("the closed section's batch never landed", || { + let now = guest.host().is_some(); + if now && !reached.replace(now) { + background.wake(); + } + server::text(&std::fs::read(&file).unwrap()).2 == "BAOriginal text" + }); + background.stop(); + let replica = Replica::open(&path).unwrap(); + assert!(matches!( + replica.status(id).unwrap(), + Some(EditStatus::Published { .. }) + )); +} diff --git a/crates/notebook/tests/support/live.rs b/crates/notebook/tests/support/live.rs index 213fdcf509b71121edcebced1b5eb893f69df4fc..37b7cbb050cd208138665b6e5ac12f6df45847a6 100644 --- a/crates/notebook/tests/support/live.rs +++ b/crates/notebook/tests/support/live.rs @@ -168,6 +168,8 @@ pub struct RelayState { pub blocked: bool, pub access_connections: usize, pub access_bytes: usize, + /// The next bytes a guest sends for access are lost, and their connection with them. + pub swallow: bool, sockets: Vec<(bool, std::net::TcpStream)>, stopped: bool, } @@ -237,7 +239,12 @@ impl PresenceRelay { break; } if !presence { - counted.lock().unwrap().access_bytes += length; + let mut counted = counted.lock().unwrap(); + if std::mem::take(&mut counted.swallow) { + let _ = from.shutdown(Shutdown::Both); + break; + } + counted.access_bytes += length; } if to.write_all(&bytes[..length]).is_err() { break;