diff options
Diffstat (limited to 'src/transport')
| -rw-r--r-- | src/transport/mod.rs | 14 | ||||
| -rw-r--r-- | src/transport/paths.rs | 101 | ||||
| -rw-r--r-- | src/transport/traffic.rs | 5 | ||||
| -rw-r--r-- | src/transport/wire.rs | 119 |
4 files changed, 224 insertions, 15 deletions
diff --git a/src/transport/mod.rs b/src/transport/mod.rs index 61abe9c..4189890 100644 --- a/src/transport/mod.rs +++ b/src/transport/mod.rs @@ -114,6 +114,9 @@ pub(crate) enum HeadsSummary { /// of starting the sync over to find out what it lacks. sample: Vec<ChangeHash>, }, + /// Where a document of another kind than Automerge's stands, as that kind's bytes + /// (`docs/document.md`, Passing on): neither heads nor a digest of any. + Kind(Vec<u8>), } /// Where the next sample starts (`HeadsSummary::of`). @@ -144,6 +147,7 @@ impl HeadsSummary { match self { Self::Heads(heads) => digest_of(heads), Self::Digest { digest, .. } => *digest, + Self::Kind(bytes) => Sha256::digest(bytes).into(), } } @@ -151,7 +155,7 @@ impl HeadsSummary { pub(crate) fn heads(&self) -> Option<&[ChangeHash]> { match self { Self::Heads(heads) => Some(heads), - Self::Digest { .. } => None, + Self::Digest { .. } | Self::Kind(_) => None, } } @@ -160,6 +164,7 @@ impl HeadsSummary { match self { Self::Heads(heads) => heads, Self::Digest { sample, .. } => sample, + Self::Kind(_) => &[], } } } @@ -845,6 +850,9 @@ pub(crate) enum SyncBody { /// Instead of a message too large to send in one piece: fetch these changes as a /// blob (`BlobId::Delta`), then sync on. Delta(DeltaSpec), + /// What a document of another kind than Automerge's says, as that kind's bytes + /// (`docs/document.md`, Passing on). + Kind(#[serde(with = "serde_bytes")] Vec<u8>), } /// The changes in the history of `to` but not of `from`: what a peer at `from` lacks of @@ -934,6 +942,10 @@ impl std::fmt::Debug for SyncBody { ) .finish(), Self::Delta(spec) => f.debug_tuple("Delta").field(spec).finish(), + Self::Kind(bytes) => f + .debug_tuple("Kind") + .field(&format!("{} bytes", bytes.len())) + .finish(), } } } diff --git a/src/transport/paths.rs b/src/transport/paths.rs index e2d9ec9..f7a146f 100644 --- a/src/transport/paths.rs +++ b/src/transport/paths.rs @@ -109,7 +109,7 @@ const DOWN_FOR: Duration = Duration::from_secs(60); const PROBE_EVERY: Duration = Duration::from_secs(30); const PROBE_TIMEOUT: Duration = Duration::from_secs(15); const UNANSWERED_DOWN: u32 = 3; -/// How often the probe task looks for paths due. +/// The least time between two looks of the probe task for paths due. const PROBE_TICK: Duration = Duration::from_secs(5); /// Paths this node had a choice of, or sent over, within this long are probed; ones it /// didn't use for twice as long are forgotten. @@ -198,6 +198,29 @@ fn rested(path: &PathState, now: Instant, every: Duration) -> bool { } impl PathState { + /// Whether it was chosen among others, or sent over, within `ACTIVE_FOR`: such a + /// path is probed. + fn active(&self, now: Instant) -> bool { + let lately = |at: Option<Instant>| { + at.is_some_and(|at| now.saturating_duration_since(at) < ACTIVE_FOR) + }; + lately(self.used) || lately(self.carried) + } + + /// From when it may be pinged again (`rested`), pinged every `every`; none where it + /// was never pinged: at once. + fn rested_at(&self, every: Duration) -> Option<Instant> { + match (self.last_probe, self.peer_probe) { + (None, Some(theirs)) => Some(theirs + every), + (None, None) => None, + (Some(ours), Some(theirs)) if theirs > ours => Some(theirs + every), + (Some(ours), Some(theirs)) if ours.saturating_duration_since(theirs) < every * 2 => { + Some(ours + every + every / 2) + } + (Some(ours), _) => Some(ours + every), + } + } + fn is_down(&self, now: Instant) -> bool { self.unanswered >= UNANSWERED_DOWN || self @@ -218,6 +241,9 @@ struct Table { /// long interval is chosen to spare. A busy pair, whose keepalives don't go, still /// gets its paths measured this often. probe_every: Duration, + /// Wakes the task that pings (`Paths::probe`): a path came into use, so one may be + /// due before the task looks next. + wake: Arc<tokio::sync::Notify>, } impl Default for Table { @@ -233,6 +259,7 @@ impl Table { chosen: HashMap::new(), counts: PathCounts::default(), probe_every: PROBE_EVERY.max(keepalive), + wake: Arc::default(), } } @@ -257,7 +284,12 @@ impl Table { } for (address, _) in &usable { if self.paths.len() < MAX_PATHS || self.paths.contains_key(address) { - self.paths.entry(address.clone()).or_default().used = Some(now); + let path = self.paths.entry(address.clone()).or_default(); + let idle = !path.active(now); + path.used = Some(now); + if idle { + self.wake.notify_one(); + } } } } @@ -338,6 +370,8 @@ impl Table { /// A send to `address` failed. fn failed(&mut self, address: &str, now: Instant) { + // What is due next may be sooner now (`next_look`). + self.wake.notify_one(); self.counts.send_failures += 1; if let Some(path) = self.paths.get_mut(address) { path.failed_at = Some(now); @@ -356,7 +390,11 @@ impl Table { } let path = self.paths.entry(address.to_owned()).or_default(); path.failed_at = None; + let idle = !path.active(now); path.carried = Some(now); + if idle { + self.wake.notify_one(); + } } /// The PINGs due now, with their nonces (from `nonce`): to every path chosen among @@ -377,10 +415,7 @@ impl Table { info!(address = %address, "A path stopped answering PINGs; using others"); } } - let lately = |at: Option<Instant>| { - at.is_some_and(|at| now.saturating_duration_since(at) < ACTIVE_FOR) - }; - let active = lately(path.used) || lately(path.carried); + let active = path.active(now); let rested = rested(path, now, self.probe_every); if active && rested && path.probe.is_none() { let nonce = nonce(); @@ -393,6 +428,30 @@ impl Table { due } + /// When `due` may next have something to do, as the paths stand at `now`: a PING + /// out counts as unanswered, a path in use is rested, or one unused for long is + /// forgotten. None while it holds no path. + fn next_look(&self, now: Instant) -> Option<Instant> { + let every = self.probe_every; + self.paths + .values() + .map(|path| { + if let Some((_, sent)) = path.probe { + return sent + PROBE_TIMEOUT; + } + if path.active(now) { + return path.rested_at(every).unwrap_or(now); + } + // Forgotten once unused for twice as long. + [path.used, path.carried, path.last_probe] + .into_iter() + .flatten() + .max() + .map_or(now, |last| last + ACTIVE_FOR * 2) + }) + .min() + } + /// What went to the peer at `addresses` went unanswered: the first, the one in use, /// is suspect (`PathState::suspect`), and each without a PING out gets one now. /// Returns those PINGs, with their nonces (from `nonce`). @@ -402,6 +461,8 @@ impl Table { now: Instant, mut nonce: impl FnMut() -> u64, ) -> Vec<(String, u64)> { + // What is due next may be sooner now (`next_look`). + self.wake.notify_one(); if let Some(first) = addresses.first() && addresses.len() > 1 && let Some(path) = self.paths.get_mut(first) @@ -431,6 +492,8 @@ impl Table { /// path, which its PONG measures, even if it is a peer's only path; `due` then /// doesn't ping it again within `probe_every`. fn pinged(&mut self, address: &str, nonce: u64, now: Instant) { + // What is due next may be sooner now (`next_look`). + self.wake.notify_one(); if self.paths.len() >= MAX_PATHS && !self.paths.contains_key(address) { self.forget_unused(now); if self.paths.len() >= MAX_PATHS { @@ -454,6 +517,8 @@ impl Table { /// The PING with `nonce` to `address` (from `due`) goes now: its round trip counts /// from here, not from when it was found due. fn sending(&mut self, address: &str, nonce: u64, now: Instant) { + // What is due next may be sooner now (`next_look`). + self.wake.notify_one(); if let Some(path) = self.paths.get_mut(address) && let Some((expected, sent)) = &mut path.probe && *expected == nonce @@ -1015,12 +1080,28 @@ impl Paths { sent } - /// Pings the paths due (`Table::due`), every `PROBE_TICK`, until dropped. + /// Pings the paths due (`Table::due`), when the next is (`Table::next_look`), and no + /// more often than every `PROBE_TICK`, so that paths due close together go + /// together; until dropped. What changes when the next is due (a path coming into + /// use, a PING sent otherwise) has it look that up anew. With no path, it + /// waits for one. async fn probe(self: Arc<Self>) { - let mut tick = tokio::time::interval(PROBE_TICK); - tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); + let wake = Arc::clone(&self.table.lock_or_recover().wake); + let mut looked = Instant::now(); loop { - tick.tick().await; + let next = self.table.lock_or_recover().next_look(Instant::now()); + match next { + Some(at) => tokio::select! { + () = tokio::time::sleep_until(at.max(looked + PROBE_TICK)) => {} + // Something changed what is due next: looked up anew. + () = wake.notified() => continue, + }, + None => { + wake.notified().await; + continue; + } + } + looked = Instant::now(); let due = self .table .lock_or_recover() diff --git a/src/transport/traffic.rs b/src/transport/traffic.rs index 33903ca..01bba65 100644 --- a/src/transport/traffic.rs +++ b/src/transport/traffic.rs @@ -225,7 +225,10 @@ fn related(peer: &str, message: &ParsedMessage) -> Option<String> { SyncBody::Delta(spec) => { format!("blob {}", crate::transport::BlobId::Delta(spec.id())) } - SyncBody::Message(_) | SyncBody::Deflated(_) | SyncBody::Changes { .. } => { + SyncBody::Message(_) + | SyncBody::Deflated(_) + | SyncBody::Changes { .. } + | SyncBody::Kind(_) => { return None; } }, diff --git a/src/transport/wire.rs b/src/transport/wire.rs index 79532fb..dda052b 100644 --- a/src/transport/wire.rs +++ b/src/transport/wire.rs @@ -89,6 +89,9 @@ pub(crate) enum WireError { #[error("wire format version {0} (we speak version {VERSION})")] Version(u8), + #[error("a document of another kind than Automerge's, which wire version {0} doesn't say")] + OtherKind(u8), + #[error("unknown message kind {0}")] UnknownKind(u8), @@ -139,6 +142,9 @@ pub(crate) fn encode_in(message: &ParsedMessage, version: u8) -> Result<Vec<u8>, if !(OLDEST..=VERSION).contains(&version) && !proof { return Err(WireError::Version(version)); } + if version < KINDS && of_another_kind(message) { + return Err(WireError::OtherKind(version)); + } let mut payload = vec![version, tag(message.kind())]; // From `KINDS` on, what is a document's kind's goes as bytes (`kinds`); before, as // the messages' own types have it, which are Automerge's. @@ -173,6 +179,24 @@ pub(crate) fn encode_in(message: &ParsedMessage, version: u8) -> Result<Vec<u8>, Ok(payload) } +/// Whether `message` carries what a document of another kind than Automerge's says, +/// which only the versions from `KINDS` on carry. +fn of_another_kind(message: &ParsedMessage) -> bool { + match message { + // A handshake in a version that says no kind is taken for an Automerge + // document's: one of another kind waits for a version that says it. + ParsedMessage::Hello(hello) => hello.kind != crate::document::KIND, + ParsedMessage::HelloReply(reply) => reply.kind != crate::document::KIND, + ParsedMessage::Sync(envelope) => { + matches!(envelope.body, crate::transport::SyncBody::Kind(_)) + } + ParsedMessage::Status(status) | ParsedMessage::StatusReply(status) => { + matches!(status.heads, crate::transport::HeadsSummary::Kind(_)) + } + _ => false, + } +} + /// The payload of `message`, in the newest wire version. #[cfg(test)] pub(crate) fn encode(message: &ParsedMessage) -> Result<Vec<u8>, WireError> { @@ -256,6 +280,10 @@ mod kinds { round_trips: Option<Vec<u8>>, } + /// What the stamp of a document of another kind than Automerge's begins with: an + /// Automerge stamp is a MessagePack array, which begins otherwise. + const OTHER_STAMP: u8 = 0; + /// Where an Automerge document stands, as its bytes have it. struct StampOut<'a>(&'a HeadsSummary); @@ -338,7 +366,11 @@ mod kinds { )? } ParsedMessage::Status(status) | ParsedMessage::StatusReply(status) => { - let stamp = rmp_serde::to_vec(&StampOut(&status.heads))?; + let stamp = match &status.heads { + // Another kind's, after a byte that begins no Automerge stamp. + HeadsSummary::Kind(bytes) => [&[OTHER_STAMP], bytes.as_slice()].concat(), + heads => rmp_serde::to_vec(&StampOut(heads))?, + }; rmp_serde::encode::write( payload, &StatusOut { @@ -437,7 +469,10 @@ mod kinds { /// The STATUS, or the STATUS_REPLY, in `body`. pub(super) fn status(body: &[u8]) -> Result<Status, WireError> { let status: StatusIn = rmp_serde::from_slice(body)?; - let StampIn(heads) = rmp_serde::from_slice(&status.stamp)?; + let heads = match status.stamp.split_first() { + Some((&OTHER_STAMP, bytes)) => HeadsSummary::Kind(bytes.to_vec()), + _ => rmp_serde::from_slice::<StampIn>(&status.stamp)?.0, + }; Ok(Status { heads, epoch: status.epoch, @@ -784,6 +819,11 @@ pub(crate) mod codec { heads.iter().map(|head| Bytes::new(&head.0)).collect(), Bytes::new(&[]), ), + HeadsSummary::Kind(_) => { + return Err(serde::ser::Error::custom( + "where a document of another kind stands, which heads don't say", + )); + } HeadsSummary::Digest { digest, sample } => ( sample.iter().map(|head| Bytes::new(&head.0)).collect(), Bytes::new(digest), @@ -1202,7 +1242,16 @@ mod tests { other => panic!("{other:?}"), }; assert_eq!(read(&hello("another"), KINDS), "another"); - assert_eq!(read(&hello("another"), KINDS - 1), crate::document::KIND); + // The version before says no kind, and one read in it is Automerge's: a + // handshake of another kind doesn't go in it. + assert_eq!( + read(&hello(crate::document::KIND), KINDS - 1), + crate::document::KIND + ); + assert!(matches!( + encode_in(&hello("another"), KINDS - 1), + Err(WireError::OtherKind(_)) + )); assert_eq!( read(&hello(crate::document::KIND), VERSION), crate::document::KIND @@ -1497,6 +1546,70 @@ mod tests { /// The exact bytes of the messages that carry what is a document's kind's, from /// `KINDS` on (`kinds`). If this fails after a change to a message type or a codec, /// the change is a new wire format: bump `VERSION` and take the new bytes. + /// What a document of another kind than Automerge's says goes where Automerge's + /// does, from the version that carries a kind's bytes on; the version before + /// doesn't say it. + #[test] + fn another_kinds_bytes_go_in_sync_and_status() { + let epoch = Epoch { + generation: 0, + id: [0; 32], + }; + let status = ParsedMessage::Status(Status { + heads: HeadsSummary::Kind(vec![0xaa; 4]), + epoch, + epoch_seq: 0, + ready: true, + syncs_with_you: true, + leaving: false, + announcing: false, + reaches: None, + round_trips: None, + }); + let sync = ParsedMessage::Sync(crate::transport::SyncEnvelope { + epoch: crate::transport::EpochTag::of(epoch), + epoch_seq: 0, + body: crate::transport::SyncBody::Kind(vec![5, 6]), + ready: true, + writer: None, + delivered: false, + sent: crate::clock::UnixMillis(8), + signatures: serde_bytes::ByteBuf::new(), + }); + let status_bytes = encode_in(&status, KINDS).unwrap(); + let sync_bytes = encode_in(&sync, KINDS).unwrap(); + assert_eq!( + hex(&status_bytes), + "350399c40500aaaaaaaa9200c420000000000000000000000000000000000000000000000000000000000000000000c3c3c2c2c0c0" + ); + assert_eq!( + hex(&sync_bytes), + "3502979200c408000000000000000000c40c9281a44b696e64c4020506c2c3c008c400" + ); + let ParsedMessage::Status(read) = decode(&status_bytes).unwrap() else { + panic!("no status"); + }; + assert!(matches!(read.heads, HeadsSummary::Kind(bytes) if bytes == vec![0xaa; 4])); + let ParsedMessage::Sync(read) = decode(&sync_bytes).unwrap() else { + panic!("no sync"); + }; + assert!( + matches!(read.body, crate::transport::SyncBody::Kind(bytes) if bytes == vec![5, 6]) + ); + assert!(!read.delivered); + // Two stamps of another kind are the same where their bytes are. + assert_eq!(HeadsSummary::Kind(vec![1]), HeadsSummary::Kind(vec![1])); + assert_ne!(HeadsSummary::Kind(vec![1]), HeadsSummary::Kind(vec![2])); + assert!(matches!( + encode_in(&status, 52), + Err(WireError::OtherKind(52)) + )); + assert!(matches!( + encode_in(&sync, 52), + Err(WireError::OtherKind(52)) + )); + } + #[test] fn golden_bytes_of_kinds() { let epoch = Epoch { |
