From ccdbc3ff80b355d6cb398dbd7cf83ce21d2014c5 Mon Sep 17 00:00:00 2001 From: Dennis Kobert Date: Fri, 25 Sep 2026 12:49:05 +0000 Subject: [PATCH] Poll a room as packets arrive, not only per frame: the inbox wakes a future, so a host in a hidden tab answers a join at once instead of once a second --- document/peer-transport/src/lib.rs | 2 +- document/peer-transport/src/room.rs | 117 ++++++++++++++++-- .../messages/portfolio/sync/sync_message.rs | 3 + .../portfolio/sync/sync_message_handler.rs | 58 ++++++++- 4 files changed, 167 insertions(+), 13 deletions(-) diff --git a/document/peer-transport/src/lib.rs b/document/peer-transport/src/lib.rs index 1b9992c542..4777692b12 100644 --- a/document/peer-transport/src/lib.rs +++ b/document/peer-transport/src/lib.rs @@ -8,7 +8,7 @@ mod transport; pub use packet::{PacketError, Role, SyncPacket, SyncPayload}; pub use replica::{Event, Replica, ReplicaError}; -pub use room::Room; +pub use room::{Incoming, Room}; pub use target::{SyncTarget, TargetError}; pub use token::{InvalidSessionToken, SessionToken}; pub use transport::{Transport, TransportEvent, TransportPeerId}; diff --git a/document/peer-transport/src/room.rs b/document/peer-transport/src/room.rs index 21834247c4..d0ec8a389a 100644 --- a/document/peer-transport/src/room.rs +++ b/document/peer-transport/src/room.rs @@ -1,7 +1,11 @@ use crate::packet::{PacketError, SyncPacket}; use crate::transport::{Transport, TransportEvent, TransportPeerId}; -use matchbox_socket::{MessageLoopFuture, PeerState, WebRtcSocket}; -use std::collections::HashMap; +use futures::StreamExt; +use futures::channel::mpsc::UnboundedSender; +use matchbox_socket::{MessageLoopFuture, Packet, PeerState, WebRtcSocket}; +use std::collections::{HashMap, VecDeque}; +use std::sync::{Arc, Mutex}; +use std::task::{Context, Poll, Waker}; const CHANNEL: usize = 0; /// Largest SCTP message every browser accepts. @@ -49,11 +53,54 @@ impl Reassembler { } } +/// Packets that arrived and wait to be polled, and whoever is waiting for them. +#[derive(Debug, Default)] +struct Inbox { + packets: VecDeque<(TransportPeerId, Packet)>, + waker: Option, + /// Set once the socket loop ended: nothing more will arrive. + closed: bool, +} + +fn lock(inbox: &Mutex) -> std::sync::MutexGuard<'_, Inbox> { + inbox.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) +} + +/// A handle onto a room's inbox that resolves when a packet is waiting, so the room is polled as packets +/// arrive rather than once per frame. A hidden browser tab gets about one frame a second, which made a +/// host answer each step of a join a second late while the data channel itself delivered on time. +#[derive(Clone, Debug)] +pub struct Incoming { + inbox: Arc>, +} + +impl Incoming { + /// Resolves to `true` once a packet is waiting, and to `false` once the room's loop has ended and + /// nothing more can arrive, so the caller knows not to wait again. + pub async fn wait(&self) -> bool { + std::future::poll_fn(|cx| self.poll_ready(cx)).await + } + + fn poll_ready(&self, cx: &mut Context<'_>) -> Poll { + let mut inbox = lock(&self.inbox); + if !inbox.packets.is_empty() { + return Poll::Ready(true); + } + if inbox.closed { + return Poll::Ready(false); + } + inbox.waker = Some(cx.waker().clone()); + Poll::Pending + } +} + /// One matchbox room over WebRTC. Packets are split into `[flag][bytes]` chunks; the reliable /// channel is ordered per peer, so the receiver reassembles by appending until the final flag. /// The returned future must be polled continuously by the caller. pub struct Room { socket: WebRtcSocket, + outgoing: UnboundedSender<(TransportPeerId, Packet)>, + inbox: Arc>, incoming: Reassembler, } @@ -63,22 +110,57 @@ impl Room { #[cfg(not(target_family = "wasm"))] let _ = rustls::crypto::ring::default_provider().install_default(); - let (socket, driver) = WebRtcSocket::new_reliable(signaling_url); + let (mut socket, driver) = WebRtcSocket::new_reliable(signaling_url); + let (outgoing, mut received) = socket.take_channel(CHANNEL).expect("a reliable socket has its one channel").split(); + let inbox = Arc::new(Mutex::new(Inbox::default())); + + // Arrivals move into the inbox as they happen and wake whoever waits on it. The forwarder ends with + // the socket loop, which drops its senders when it returns; the loop's result stays the driver's. + let forwarder = { + let inbox = Arc::clone(&inbox); + async move { + while let Some(arrived) = received.next().await { + let mut inbox = lock(&inbox); + inbox.packets.push_back(arrived); + if let Some(waker) = inbox.waker.take() { + waker.wake(); + } + } + let mut inbox = lock(&inbox); + inbox.closed = true; + if let Some(waker) = inbox.waker.take() { + waker.wake(); + } + } + }; + let driver: MessageLoopFuture = Box::pin(async move { + let (result, ()) = futures::join!(driver, forwarder); + result + }); + ( Self { socket, + outgoing, + inbox, incoming: Reassembler::default(), }, driver, ) } - fn send_chunks(&mut self, bytes: &[u8], peers: &[TransportPeerId]) { - let channel = self.socket.channel_mut(CHANNEL); + /// A handle that resolves whenever a packet waits in this room. + pub fn incoming(&self) -> Incoming { + Incoming { inbox: Arc::clone(&self.inbox) } + } + fn send_chunks(&mut self, bytes: &[u8], peers: &[TransportPeerId]) { for frame in frames(bytes) { for &peer in peers { - channel.send(frame.clone(), peer); + // A send only fails once the socket loop has ended, which the loop's own future reports. + if self.outgoing.unbounded_send((peer, frame.clone())).is_err() { + return; + } } } } @@ -111,7 +193,7 @@ impl Transport for Room { }); } - let received: Vec<_> = self.socket.channel_mut(CHANNEL).receive(); + let received: Vec<_> = lock(&self.inbox).packets.drain(..).collect(); for (peer, frame) in received { let Some(bytes) = self.incoming.accept(peer, &frame) else { continue }; @@ -132,11 +214,32 @@ impl Transport for Room { #[cfg(test)] mod tests { use super::*; + use futures::FutureExt; fn peer(byte: u128) -> TransportPeerId { TransportPeerId(uuid::Uuid::from_u128(byte)) } + /// The inbox handle resolves on an arrival and once more when the loop ends, and is pending otherwise, + /// so a poll driven by it runs on packets rather than on frames. + #[test] + fn the_inbox_wakes_on_arrival_and_reports_the_end() { + let inbox = Arc::new(Mutex::new(Inbox::default())); + let incoming = Incoming { inbox: Arc::clone(&inbox) }; + + assert_eq!(incoming.wait().now_or_never(), None, "nothing arrived yet"); + + lock(&inbox).packets.push_back((peer(1), Box::new([FRAME_FINAL, 7]))); + assert_eq!(incoming.wait().now_or_never(), Some(true), "an arrival resolves the wait"); + assert_eq!(incoming.wait().now_or_never(), Some(true), "and keeps it resolved until the inbox is drained"); + + lock(&inbox).packets.clear(); + assert_eq!(incoming.wait().now_or_never(), None, "drained: pending again"); + + lock(&inbox).closed = true; + assert_eq!(incoming.wait().now_or_never(), Some(false), "the end of the loop resolves the wait for good"); + } + /// Push every frame at a reassembler and collect whatever packets come back out. fn round_trip(bytes: &[u8]) -> Vec> { let mut incoming = Reassembler::default(); diff --git a/editor/src/messages/portfolio/sync/sync_message.rs b/editor/src/messages/portfolio/sync/sync_message.rs index 8d21de267d..d1ac00500a 100644 --- a/editor/src/messages/portfolio/sync/sync_message.rs +++ b/editor/src/messages/portfolio/sync/sync_message.rs @@ -13,6 +13,9 @@ pub enum SyncMessage { Leave, /// Per frame: apply what peers sent and answer their requests. Poll, + /// A packet arrived for a document's room: poll it now rather than at the next frame. `generation` + /// names the connection it was armed for, so a wake from an earlier connection is ignored. + Wake { document_id: DocumentId, generation: u32 }, /// A document's working copy mounted; attaches it to a pending join. StorageMounted { document_id: DocumentId }, /// The transport loop of a document's session ended. diff --git a/editor/src/messages/portfolio/sync/sync_message_handler.rs b/editor/src/messages/portfolio/sync/sync_message_handler.rs index 3e3f3c1f8e..0e3bcaab51 100644 --- a/editor/src/messages/portfolio/sync/sync_message_handler.rs +++ b/editor/src/messages/portfolio/sync/sync_message_handler.rs @@ -4,7 +4,7 @@ use crate::messages::prelude::*; use crate::messages::resource_storage::ResourcesHandle; use document_graph_storage::UserId; use graph_craft::application_io::resource::LoadResource; -use peer_transport::{DEFAULT_SIGNALING_SERVER, Event, Room, SessionToken, SyncTarget}; +use peer_transport::{DEFAULT_SIGNALING_SERVER, Event, Incoming, Room, SessionToken, SyncTarget}; use std::collections::HashSet; #[derive(ExtractField)] @@ -14,12 +14,16 @@ pub struct SyncMessageContext<'a> { pub resource_storage: &'a ResourceStorageMessageHandler, } -/// Drives every document's collaborative session: attaches transports, polls them once per frame, -/// and turns remote changes into interface rebuilds. +/// Drives every document's collaborative session: attaches transports, polls them once per frame and as +/// packets arrive, and turns remote changes into interface rebuilds. #[derive(Debug, Default, ExtractField)] pub struct SyncMessageHandler { pending_join: Option, polling: bool, + /// Each connected document's room inbox, tagged with the connection it belongs to. One wake future is in + /// flight per entry: it resolves to a `Wake`, which polls and arms the next one. + incoming: HashMap, + connections: u32, /// Documents whose registry changed remotely since their interface was last rebuilt. dirty: HashSet, /// Documents that just took the host's state on: once their interface follows and the graph has run, the @@ -78,10 +82,12 @@ impl MessageHandler> for SyncMessageHandler }; if let Some(token) = self.pending_join.take() { let (room, driver) = Room::connect(&token.signaling_url(DEFAULT_SIGNALING_SERVER)); + let incoming = room.incoming(); let user = UserId(gdd.session().peer().0); gdd.join(room, user); responses.add(driver_future(document_id, driver)); + self.attach(document_id, incoming, responses); responses.add(PortfolioMessage::UpdateOpenDocumentsList); self.start_polling(responses); } else if gdd.is_shared() && gdd.role().is_none() { @@ -90,19 +96,32 @@ impl MessageHandler> for SyncMessageHandler } } SyncMessage::Leave => { - let Some(gdd) = active_document_id.and_then(|id| documents.get_mut(&id)).and_then(|document| document.storage_mut()) else { + let Some(document_id) = active_document_id else { return }; + let Some(gdd) = documents.get_mut(&document_id).and_then(|document| document.storage_mut()) else { return; }; gdd.leave(); + self.incoming.remove(&document_id); responses.add(PortfolioMessage::UpdateOpenDocumentsList); } SyncMessage::Disconnected { document_id } => { if let Some(gdd) = documents.get_mut(&document_id).and_then(|document| document.storage_mut()) { gdd.leave(); } + self.incoming.remove(&document_id); responses.add(PortfolioMessage::UpdateOpenDocumentsList); } - SyncMessage::Poll => { + SyncMessage::Poll | SyncMessage::Wake { .. } => { + // A wake names the connection it was armed for; one from a connection since left is nothing to act on. + let woken = match message { + SyncMessage::Wake { document_id, generation } => { + if self.incoming.get(&document_id).is_none_or(|(current, _)| *current != generation) { + return; + } + Some(document_id) + } + _ => None, + }; let resources = resource_storage.resources_mut(); for (&document_id, document) in documents.iter_mut() { // Retirement follows the working copy's policy on every document, in a session or not: closed @@ -198,6 +217,11 @@ impl MessageHandler> for SyncMessageHandler // The registry names resources this peer may still have to fetch or resolve. responses.add(PortfolioMessage::ResolveDocumentResources { document_id }); } + + // The inbox was drained above; the next arrival wakes the next poll. + if let Some(document_id) = woken { + self.arm(document_id, responses); + } } SyncMessage::ResourceLoaded { document_id, to, hash, bytes } => { log::debug!("Sending resource {hash} ({} bytes)", bytes.len()); @@ -220,6 +244,7 @@ impl SyncMessageHandler { fn connect_document(&mut self, document_id: DocumentId, gdd: &mut document_format::GddV1, responses: &mut VecDeque) -> Option { let token = SessionToken::for_document(gdd.manifest().document_id); let (room, driver) = Room::connect(&token.signaling_url(DEFAULT_SIGNALING_SERVER)); + let incoming = room.incoming(); let user = UserId(gdd.session().peer().0); if let Err(error) = gdd.connect(room, user) { log::error!("Connecting to the session failed: {error}"); @@ -227,11 +252,34 @@ impl SyncMessageHandler { } self.undecided_since.insert(document_id, now_ms()); responses.add(driver_future(document_id, driver)); + self.attach(document_id, incoming, responses); responses.add(PortfolioMessage::UpdateOpenDocumentsList); self.start_polling(responses); Some(token) } + /// Poll `document_id`'s room as packets arrive, not only per frame: a hidden browser tab gets about one + /// frame a second, which made a host answer each step of a join a second late. The wake rides on the + /// editor's future plumbing, so it works the same on the desktop as in the browser. + fn attach(&mut self, document_id: DocumentId, incoming: Incoming, responses: &mut VecDeque) { + self.connections += 1; + self.incoming.insert(document_id, (self.connections, incoming)); + self.arm(document_id, responses); + } + + /// Put one wake future in flight for `document_id`'s current connection. + fn arm(&mut self, document_id: DocumentId, responses: &mut VecDeque) { + let Some((generation, incoming)) = self.incoming.get(&document_id).cloned() else { return }; + let future = async move { + match incoming.wait().await { + true => Message::Portfolio(PortfolioMessage::Sync(SyncMessage::Wake { document_id, generation })), + // The room's loop ended; its driver reports the disconnection. + false => Message::NoOp, + } + }; + responses.add(future); + } + fn start_polling(&mut self, responses: &mut VecDeque) { if self.polling { return;