diff --git a/crates/collab/src/diff_tests.rs b/crates/collab/src/diff_tests.rs index 4aafc891c..32edaba7c 100644 --- a/crates/collab/src/diff_tests.rs +++ b/crates/collab/src/diff_tests.rs @@ -77,7 +77,8 @@ fn an_edit_past_the_review_limits_is_refused_but_a_snapshot_clamps() { // A snapshot holding settings over the limits (an old file's) opens clamped to what fits: // the preset, grid and disabled rules exactly as saved, the lists to the limit. let snap = diff(&Replica::new(Document::without_pages("")), &b).unwrap().changes; - let (r2, left_out) = Replica::from_snapshot_leaving_out(&snap).unwrap(); + let (r2, left_out, clamped) = Replica::from_snapshot_leaving_out(&snap).unwrap(); + assert!(clamped, "the settings needed clamping, and the caller is told"); assert_eq!(left_out, 0, "nothing needed leaving out"); let cfg = &r2.document().design_review; assert_eq!(cfg.preset, DesignPreset::Strict, "the preset survives"); @@ -98,7 +99,8 @@ fn an_edit_with_too_many_disabled_rules_is_refused_and_a_snapshot_truncates_them assert!(err.contains("200 disabled rules pass the 64 limit `design.configure` keeps"), "{err}"); // A snapshot with a longer list opens with the ones that fit, not without the settings. let snap = diff(&Replica::new(Document::without_pages("")), &b).unwrap().changes; - let (r2, left_out) = Replica::from_snapshot_leaving_out(&snap).unwrap(); + let (r2, left_out, clamped) = Replica::from_snapshot_leaving_out(&snap).unwrap(); + assert!(clamped); assert_eq!(left_out, 0, "nothing needed leaving out"); let cfg = &r2.document().design_review; assert_eq!(cfg.disabled.len(), MAX_DISABLED, "the list keeps its first {MAX_DISABLED}"); diff --git a/crates/collab/src/docprops.rs b/crates/collab/src/docprops.rs index abdf8f3c8..ae7299511 100644 --- a/crates/collab/src/docprops.rs +++ b/crates/collab/src/docprops.rs @@ -403,28 +403,18 @@ pub(crate) fn apply(doc: &mut Document, change: &Change) -> Result apply_indexed(doc, change, &mut Index::default()) } -/// The review-settings lists that hold more than this build keeps, as (what, how many, the cap). -fn review_lists_over_limit(c: &figcraft_doc::DesignReview) -> Vec<(&'static str, usize, usize)> { - [ - ("radii", c.radii.len(), figcraft_doc::MAX_RADII), - ("brand colours", c.brand.len(), figcraft_doc::MAX_BRAND_COLORS), - ("disabled rules", c.disabled.len(), figcraft_doc::MAX_DISABLED), - ] - .into_iter() - .filter(|(_, have, max)| have > max) - .collect() -} - -/// Clamp the review settings a snapshot carries to the limits this build keeps, in place: an -/// older or looser snapshot may hold longer radii, brand or disabled lists, and the file opens -/// with what fits — the preset, grid and the rest of each list exactly as saved. An ordinary edit -/// is refused instead (`apply_indexed`), and a peer that can't read the settings at all gets them -/// left out of what the server sends (`Change::without_design_review`). -pub(crate) fn clamp_snapshot_design_review(changes: &mut Vec) { +/// Clamp the review settings a snapshot carries to the limits this build keeps, in place, and say +/// whether it changed them: an older or looser snapshot may hold longer radii, brand or disabled +/// lists, and the file opens with what fits — the preset, grid and the rest of each list exactly +/// as saved. An ordinary edit is refused instead (`apply_indexed`), and a peer that can't read the +/// settings at all gets them left out of what the server sends +/// (`Change::without_design_review`). +pub(crate) fn clamp_snapshot_design_review(changes: &mut Vec) -> bool { + let mut clamped_any = false; for c in changes { if let Change::SetDoc { prop: DocProp::DesignReview, value } = c && let Ok(config) = value.read::("design review") - && !review_lists_over_limit(&config).is_empty() + && !config.over_limits().is_empty() { let mut clamped = config; clamped.radii.truncate(figcraft_doc::MAX_RADII); @@ -432,9 +422,11 @@ pub(crate) fn clamp_snapshot_design_review(changes: &mut Vec) { clamped.disabled.truncate(figcraft_doc::MAX_DISABLED); if let Ok(v) = Json::of(&clamped) { *value = v; + clamped_any = true; } } } + clamped_any } /// Apply a document-level change, with the keyed lists' positions kept in `index` between the @@ -449,7 +441,7 @@ pub(crate) fn apply_indexed(doc: &mut Document, change: &Change, index: &mut Ind // path clamps it (`clamp_snapshot_design_review`). if *prop == DocProp::DesignReview { let config: figcraft_doc::DesignReview = value.read("design review")?; - if let Some((what, have, max)) = review_lists_over_limit(&config).first() { + if let Some((what, have, max)) = config.over_limits().first() { return Err(Error::Invalid(format!("design review: {have} {what} pass the {max} limit `design.configure` keeps"))); } } diff --git a/crates/collab/src/reconnect_tests.rs b/crates/collab/src/reconnect_tests.rs index a5998feea..af13b5042 100644 --- a/crates/collab/src/reconnect_tests.rs +++ b/crates/collab/src/reconnect_tests.rs @@ -291,6 +291,91 @@ fn random_drops_and_reconnects_converge() { assert!(snapshots > 0, "no reconnect needed a snapshot"); } +/// A session saved by a build with larger review limits restores with them clamped. Its saved +/// batches still hold the value past the limits, so a resuming client catches up with the +/// snapshot: replaying the log would hand it a change this build refuses. +#[test] +fn a_restored_session_with_clamped_settings_catches_up_by_snapshot() { + use crate::change::{Change, DocProp, Json}; + use figcraft_doc::{DesignReview, MAX_RADII}; + + let mut s = Server::new(base(), "tok", Limits::default()); + let mut a = join(&mut s); + // `b` joined but misses the review batch: it resumes from the log, which is where the old + // build's over-limit value still sits. + let mut b = join(&mut s); + let m = edit(&mut a, |d| d.design_review.grid = 8.0).unwrap(); + let out = s.receive(a.id(), m); + deliver(&mut a, &out); + b.disconnect(); + let mut state = s.state().unwrap(); + assert_eq!(state.log.len(), 1, "the review batch is in the log"); + + // An older build wrote more radii than this one keeps, in the snapshot and in the batch. + let wide = DesignReview { grid: 8.0, radii: (0..MAX_RADII + 8).map(|i| i as f64).collect(), ..Default::default() }; + let value = Json::of(&wide).unwrap(); + for c in state.snapshot.iter_mut().chain(state.log.iter_mut().flat_map(|a| a.changes.iter_mut())) { + if let Change::SetDoc { prop: DocProp::DesignReview, value: v } = c { + *v = value.clone(); + } + } + + let mut restored = Server::restore(state, "tok", Limits::default()).unwrap(); + assert_eq!(restored.document().design_review.radii.len(), MAX_RADII, "the snapshot keeps what fits"); + let ClientMsg::Hello(h) = b.reconnect(hello()) else { panic!() }; + let (id, out) = restored.join(h).unwrap(); + assert_eq!(id, b.id(), "a reconnecting client keeps its id"); + assert!( + matches!(&out[0], Outgoing::To(_, ServerMsg::Welcome { catch_up: CatchUp::Snapshot(_), .. })), + "a clamped session hands out the snapshot, not a batch past the limits: {out:?}" + ); + deliver(&mut b, &out); + assert_eq!(b.seq(), restored.seq()); + assert_eq!(b.document().design_review.radii.len(), MAX_RADII, "the client takes what the session has"); + // The client that already had the batch catches up with the same snapshot, so both sides + // agree on the clamped value. + let ClientMsg::Hello(h) = a.reconnect(hello()) else { panic!() }; + let (_, out) = restored.join(h).unwrap(); + deliver(&mut a, &out); + assert_eq!(a.document(), b.document()); +} + +/// The same fixture inside the limits keeps resuming from the log: the snapshot catch-up above is +/// for settings this build had to change, not for review settings as such. +#[test] +fn a_restored_session_within_the_limits_resumes_from_the_log() { + use crate::change::{Change, DocProp, Json}; + use figcraft_doc::DesignReview; + + let mut s = Server::new(base(), "tok", Limits::default()); + let mut a = join(&mut s); + let mut b = join(&mut s); + let m = edit(&mut a, |d| d.design_review.grid = 8.0).unwrap(); + let out = s.receive(a.id(), m); + deliver(&mut a, &out); + b.disconnect(); + let mut state = s.state().unwrap(); + let narrow = DesignReview { grid: 8.0, radii: (0..20).map(|i| i as f64).collect(), ..Default::default() }; + let value = Json::of(&narrow).unwrap(); + for c in state.snapshot.iter_mut().chain(state.log.iter_mut().flat_map(|a| a.changes.iter_mut())) { + if let Change::SetDoc { prop: DocProp::DesignReview, value: v } = c { + *v = value.clone(); + } + } + + let mut restored = Server::restore(state, "tok", Limits::default()).unwrap(); + assert_eq!(restored.document().design_review.radii.len(), 20, "the snapshot needs no clamping"); + let ClientMsg::Hello(h) = b.reconnect(hello()) else { panic!() }; + let (_, out) = restored.join(h).unwrap(); + assert!( + matches!(&out[0], Outgoing::To(_, ServerMsg::Welcome { catch_up: CatchUp::Delta(_), .. })), + "a session that needed no clamping resumes from its log: {out:?}" + ); + deliver(&mut b, &out); + assert_eq!(b.seq(), restored.seq()); + assert_eq!(b.document().design_review.radii.len(), 20); +} + #[test] fn resume_needs_the_issued_secret() { let mut s = Server::new(base(), "tok", Limits { max_peers: 2, ..Limits::default() }); diff --git a/crates/collab/src/replica.rs b/crates/collab/src/replica.rs index b7cfb2752..eee844eb5 100644 --- a/crates/collab/src/replica.rs +++ b/crates/collab/src/replica.rs @@ -72,22 +72,24 @@ impl Replica { /// Rebuild a replica from a [`snapshot`](Self::snapshot). pub fn from_snapshot(changes: &[Change]) -> Result { - Self::from_snapshot_leaving_out(changes).map(|(r, _)| r) + Self::from_snapshot_leaving_out(changes).map(|(r, _, _)| r) } /// [`from_snapshot`](Self::from_snapshot), and how many image entries it left out: a /// snapshot saved before the image checks may hold one they refuse, and opens without it. /// Review settings past the current limits are clamped to them, not dropped (see - /// [`docprops::clamp_snapshot_design_review`]). - pub(crate) fn from_snapshot_leaving_out(changes: &[Change]) -> Result<(Replica, usize), Error> { + /// [`docprops::clamp_snapshot_design_review`]); the last value says whether that happened, + /// because a session whose settings had to be clamped can no longer replay its saved batches + /// for clients that resume (they hold the value past the limits). + pub(crate) fn from_snapshot_leaving_out(changes: &[Change]) -> Result<(Replica, usize, bool), Error> { let mut r = Replica { doc: Document::without_pages(""), positions: Positions::new() }; let mut changes = changes.to_vec(); - docprops::clamp_snapshot_design_review(&mut changes); + let clamped = docprops::clamp_snapshot_design_review(&mut changes); let left_out = r.apply_kept(&mut changes, Change::is_image)?; if r.doc.pages.is_empty() { return Err(Error::Invalid("a snapshot needs a page".into())); } - Ok((r, left_out)) + Ok((r, left_out, clamped)) } /// Apply `changes` strictly. When they don't apply together — history written under older diff --git a/crates/collab/src/server.rs b/crates/collab/src/server.rs index 58ad309bb..638491aaf 100644 --- a/crates/collab/src/server.rs +++ b/crates/collab/src/server.rs @@ -175,7 +175,7 @@ impl Server { /// reconnect with their ids). A log that doesn't lead up to the sequence number is dropped /// (clients then catch up with a snapshot). pub fn restore(state: SessionState, token: impl Into, limits: Limits) -> Result { - let (replica, left_out) = Replica::from_snapshot_leaving_out(&state.snapshot)?; + let (replica, left_out, review_clamped) = Replica::from_snapshot_leaving_out(&state.snapshot)?; let mut server = Server::new(replica.document().clone(), token, limits); server.state = replica; server.session = state.session; @@ -195,9 +195,11 @@ impl Server { // History saved before the image checks may hold image entries they refuse. The snapshot // opens without them, and a saved log putting images may give a resuming client other // bytes under a key it holds, which this state can't check: either way resuming clients - // catch up with the snapshot. + // catch up with the snapshot. The same holds for review settings this build had to clamp: + // a saved batch still carries the value past the limits, and a resuming client would + // refuse it, so the clamped snapshot is what everyone catches up with. let puts_images = state.log.iter().flat_map(|a| &a.changes).any(Change::is_image); - server.resync = left_out > 0 || puts_images; + server.resync = left_out > 0 || puts_images || review_clamped; if contiguous && state.log.last().is_none_or(|a| a.seq == state.seq) { for a in state.log { server.remember(a);