diff --git a/pkgs/id/src/frames.rs b/pkgs/id/src/frames.rs index 35cb2a1d17..0f3739367e 100644 --- a/pkgs/id/src/frames.rs +++ b/pkgs/id/src/frames.rs @@ -15,8 +15,8 @@ use tokio::io::{AsyncRead, AsyncReadExt as _, AsyncWrite, AsyncWriteExt as _}; /// Largest accepted or emitted frame, in bytes (1 MiB). /// -/// Both transports enforce it: the Iroh frame reader refuses longer frames -/// and the WebSocket has `max_message_size(MAX_FRAME_BYTES)`. +/// The Iroh frame readers refuse longer frames, and every WebSocket endpoint +/// sets `max_message_size(MAX_FRAME_BYTES)`. pub const MAX_FRAME_BYTES: usize = 1024 * 1024; /// Write one frame. diff --git a/pkgs/id/src/web/collab.rs b/pkgs/id/src/web/collab.rs index e1890059ad..8907397530 100644 --- a/pkgs/id/src/web/collab.rs +++ b/pkgs/id/src/web/collab.rs @@ -68,6 +68,7 @@ use super::identity::short_id; use super::markdown::{ markdown_to_prosemirror, plain_text_to_prosemirror, raw_text_to_prosemirror, }; +use crate::frames::MAX_FRAME_BYTES; /// Message type tags for the wire protocol. mod msg { @@ -83,6 +84,9 @@ mod msg { pub const AUTH_OK: u8 = 9; } +/// Maximum number of steps accepted in one client message. +const MAX_STEPS_PER_MESSAGE: usize = 1_000; + /// Query parameters for WebSocket connection. #[derive(Debug, Deserialize)] pub struct WsParams { @@ -626,6 +630,54 @@ fn extract_binary(msg: &Message) -> Option> { } } +/// Apply one versioned client step batch, rejecting oversized batches before +/// changing document history, version, or broadcasting an update. +async fn apply_steps( + doc: &Document, + version: u64, + steps: &[serde_json::Value], + client_id: u64, +) -> Result { + if steps.len() > MAX_STEPS_PER_MESSAGE { + return Err(format!( + "Step batch exceeds maximum of {MAX_STEPS_PER_MESSAGE} steps" + )); + } + + let current_version = doc.version(); + if version != current_version { + return Err(format!( + "Version mismatch: expected {current_version}, got {version}" + )); + } + + let mut doc_steps = doc.steps.write().await; + for step in steps { + doc_steps.push(( + Step { data: step.clone() }, + serde_json::Value::Number(client_id.into()), + )); + } + drop(doc_steps); + + use std::sync::atomic::Ordering; + let new_version = + doc.version.fetch_add(steps.len() as u64, Ordering::SeqCst) + steps.len() as u64; + + let update = CollabMessage::Update { + steps: steps.to_vec(), + client_ids: vec![client_id; steps.len()], + }; + let broadcast_count = doc.broadcast.send(update).unwrap_or(0); + tracing::info!( + "[collab] Broadcast to {} receivers, new version={}", + broadcast_count, + new_version + ); + + Ok(new_version) +} + /// WebSocket upgrade handler for collaborative editing. pub async fn ws_collab_handler( ws: WebSocketUpgrade, @@ -633,16 +685,17 @@ pub async fn ws_collab_handler( Query(params): Query, State(state): State, ) -> impl IntoResponse { - ws.on_upgrade(move |socket| { - handle_collab_socket( - socket, - doc_id, - params.filename, - state.collab, - state.store, - state.identity, - ) - }) + ws.max_message_size(MAX_FRAME_BYTES) + .on_upgrade(move |socket| { + handle_collab_socket( + socket, + doc_id, + params.filename, + state.collab, + state.store, + state.identity, + ) + }) } /// Handle a WebSocket connection for collaborative editing. @@ -999,50 +1052,18 @@ async fn handle_collab_socket( steps.len() ); - // Verify version matches - let current_version = doc.version(); - if version != current_version { - let error_msg = CollabMessage::Error { - error: format!( - "Version mismatch: expected {current_version}, got {version}" - ), - }; - tracing::warn!( - "[collab] Version mismatch: expected {}, got {}", - current_version, - version - ); - let mut sender = sender.lock().await; - let _ = sender.send(Message::Binary(error_msg.encode().into())).await; - continue; - } - - // Apply steps - let mut doc_steps = doc.steps.write().await; - for step in &steps { - doc_steps.push(( - Step { data: step.clone() }, - serde_json::Value::Number(client_id.into()), - )); - } - drop(doc_steps); - - // Increment version - let new_version = - doc.version.fetch_add(steps.len() as u64, Ordering::SeqCst) - + steps.len() as u64; - - // Broadcast to other clients - let update = CollabMessage::Update { - steps: steps.clone(), - client_ids: vec![client_id; steps.len()], + let new_version = match apply_steps(&doc, version, &steps, client_id).await { + Ok(version) => version, + Err(error) => { + tracing::warn!("[collab] Rejected Steps: {}", error); + let error_msg = CollabMessage::Error { error }; + let mut sender = sender.lock().await; + let _ = sender + .send(Message::Binary(error_msg.encode().into())) + .await; + continue; + } }; - let broadcast_count = doc.broadcast.send(update).unwrap_or(0); - tracing::info!( - "[collab] Broadcast to {} receivers, new version={}", - broadcast_count, - new_version - ); // Send ack to sender let ack = CollabMessage::Ack { @@ -1285,6 +1306,45 @@ mod tests { } } + #[allow(clippy::unwrap_used, clippy::panic)] + #[tokio::test] + async fn test_apply_steps_rejects_oversized_batch_without_mutation() { + let doc = Document::new(); + let mut updates = doc.broadcast.subscribe(); + let steps = vec![serde_json::json!({"stepType": "replace"}); MAX_STEPS_PER_MESSAGE + 1]; + + let error = apply_steps(&doc, 0, &steps, 123).await.unwrap_err(); + + assert!(error.contains("1000")); + assert_eq!(doc.version(), 0); + assert!(doc.steps.read().await.is_empty()); + assert!(updates.try_recv().is_err()); + } + + #[allow(clippy::unwrap_used, clippy::panic)] + #[tokio::test] + async fn test_apply_steps_accepts_small_batch_and_broadcasts_update() { + let doc = Document::new(); + let mut updates = doc.broadcast.subscribe(); + let steps = vec![serde_json::json!({"stepType": "replace", "from": 0})]; + + let ack_version = apply_steps(&doc, 0, &steps, 123).await.unwrap(); + + assert_eq!(ack_version, 1); + assert_eq!(doc.version(), 1); + assert_eq!(doc.steps.read().await.len(), 1); + match updates.recv().await.unwrap() { + CollabMessage::Update { + steps: broadcast_steps, + client_ids, + } => { + assert_eq!(broadcast_steps, steps); + assert_eq!(client_ids, vec![123]); + } + other => panic!("Expected Update, got {other:?}"), + } + } + #[allow(clippy::unwrap_used, clippy::panic)] #[test] fn test_collab_message_update_roundtrip() { diff --git a/pkgs/id/src/web/tags_ws.rs b/pkgs/id/src/web/tags_ws.rs index 581ec91ef4..3d083054c5 100644 --- a/pkgs/id/src/web/tags_ws.rs +++ b/pkgs/id/src/web/tags_ws.rs @@ -37,6 +37,7 @@ //! - otherwise — delete the exact `(subject, key, value)` tag (a request with //! no value deletes the value-less key-only tag) +use crate::frames::MAX_FRAME_BYTES; use axum::{ Json, extract::{Query, State, WebSocketUpgrade, ws::Message}, @@ -205,7 +206,8 @@ pub async fn ws_tags_handler( ws: WebSocketUpgrade, State(state): State, ) -> impl IntoResponse { - ws.on_upgrade(move |socket| handle_tags_socket(socket, state)) + ws.max_message_size(MAX_FRAME_BYTES) + .on_upgrade(move |socket| handle_tags_socket(socket, state)) } /// Handle a tag WebSocket connection. diff --git a/pkgs/id/web/src/collab.test.ts b/pkgs/id/web/src/collab.test.ts index b56163973c..fba00cd6d9 100644 --- a/pkgs/id/web/src/collab.test.ts +++ b/pkgs/id/web/src/collab.test.ts @@ -1,6 +1,6 @@ import { Packr, Unpackr } from "msgpackr"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { initCollab } from "./collab"; +import { MAX_STEPS_MESSAGE_BYTES, MAX_STEPS_PER_MESSAGE, initCollab, stepBatch } from "./collab"; // Same MessagePack configuration as collab.ts const packr = new Packr({ useRecords: false, structuredClone: true }); @@ -175,3 +175,57 @@ describe("initCollab token handling (#1463)", () => { conn.disconnect(); }); }); + +describe("stepBatch (client side of the server step cap, #1965)", () => { + it("sends every step when the batch is at or under the cap", () => { + const steps = [1, 2, 3]; + expect(stepBatch(steps)).toEqual([1, 2, 3]); + const atCap = Array.from({ length: MAX_STEPS_PER_MESSAGE }, (_, i) => i); + expect(stepBatch(atCap)).toHaveLength(MAX_STEPS_PER_MESSAGE); + }); + + it("chunks an oversized transaction to the cap, preserving order", () => { + // Indenting >1000 lines legitimately produces >1000 steps; the first + // message must carry only the cap and leave the rest pending, or the + // server rejection wedges the session (Codex P2 on PR #4051). + const steps = Array.from({ length: MAX_STEPS_PER_MESSAGE + 250 }, (_, i) => i); + const batch = stepBatch(steps); + expect(batch).toHaveLength(MAX_STEPS_PER_MESSAGE); + expect(batch[0]).toBe(0); + expect(batch[MAX_STEPS_PER_MESSAGE - 1]).toBe(MAX_STEPS_PER_MESSAGE - 1); + expect(steps).toHaveLength(MAX_STEPS_PER_MESSAGE + 250); + }); + + it("returns an empty batch for no pending steps", () => { + expect(stepBatch([])).toEqual([]); + }); + + it("chunks by encoded size as well as count (Codex P2 on PR #4051)", () => { + // 1,000 small steps fit the count cap, but medium steps can encode to + // far more than the 1 MiB server frame cap; the batch must stop at + // the byte budget and leave the remainder pending, in order. + const stepBytes = 4096; + const steps = Array.from({ length: 1000 }, (_, i) => i); + const batch = stepBatch(steps, () => stepBytes); + const expected = Math.floor(MAX_STEPS_MESSAGE_BYTES / stepBytes); + expect(batch).toHaveLength(expected); + expect(batch[0]).toBe(0); + expect(batch[expected - 1]).toBe(expected - 1); + expect(steps).toHaveLength(1000); + }); + + it("withholds a single step that alone exceeds the byte budget", () => { + // A >1 MiB paste can be one replace step; it can never be sent within + // the server cap, so the batch is empty and the caller keeps the edit + // local instead of triggering a server refusal + reconnect discard. + const steps = ["huge", "later"]; + const batch = stepBatch(steps, (s) => (s === "huge" ? MAX_STEPS_MESSAGE_BYTES + 1 : 1)); + expect(batch).toEqual([]); + }); + + it("includes a first step that exactly fits the byte budget", () => { + const steps = ["exact", "later"]; + const batch = stepBatch(steps, (s) => (s === "exact" ? MAX_STEPS_MESSAGE_BYTES : 1)); + expect(batch).toEqual(["exact"]); + }); +}); diff --git a/pkgs/id/web/src/collab.ts b/pkgs/id/web/src/collab.ts index b313cc6f7e..1b5fb85ee1 100644 --- a/pkgs/id/web/src/collab.ts +++ b/pkgs/id/web/src/collab.ts @@ -60,6 +60,53 @@ const MSG = { const packr = new Packr({ useRecords: false, structuredClone: true }); const unpackr = new Unpackr({ useRecords: false, structuredClone: true }); +/** Per-message step bound, mirroring the server MAX_STEPS_PER_MESSAGE + * (pkgs/id/src/web/collab.rs). A single editor transaction can legitimately + * exceed it - indenting N lines produces N steps (web/src/indent.ts) - so + * the client sends at most this many steps per Steps message and flushes + * the remainder as the server confirms each batch (see the Update handler), + * instead of wedging the session on a rejected oversized batch. */ +export const MAX_STEPS_PER_MESSAGE = 1000; + +/** Wire-size budget for one Steps message, mirroring the server frame cap + * MAX_FRAME_BYTES (1 MiB, pkgs/id/src/frames.rs) minus a reserve for the + * MessagePack envelope ([tag, version, steps, clientID]). The step-count + * cap alone cannot bound the wire size: 1,000 medium steps encode to far + * more than 1 MiB, and the server refuses an over-limit message before + * applying any of it (Codex P2 on PR #4051). */ +export const MAX_STEPS_MESSAGE_BYTES = 1024 * 1024 - 4096; + +/** Encoded size of one step on the wire (MessagePack, same Packr config + * as the send path). */ +export function stepWireSize(step: unknown): number { + return packr.pack(step).byteLength; +} + +/** The next batch of pending steps to send: at most MAX_STEPS_PER_MESSAGE + * steps and at most MAX_STEPS_MESSAGE_BYTES of encoded steps, in order. + * Remaining steps stay unconfirmed and are sent by later flushes. + * Returns an empty batch when the FIRST pending step alone exceeds the + * byte budget: such a step can never be sent within the server cap, and + * splitting it into several wire steps would corrupt prosemirror-collab's + * count-based confirmation (the server echoes applied steps and the + * plugin confirms that many unconfirmed steps). Withholding it keeps the + * edit in the local document instead of having the server reject the + * message and the reconnect path re-initialize the editor from server + * state, silently discarding the edit. */ +export function stepBatch(steps: readonly T[], sizeOf: (step: T) => number = () => 0): T[] { + const batch: T[] = []; + let bytes = 0; + for (const step of steps) { + if (batch.length >= MAX_STEPS_PER_MESSAGE) break; + const size = sizeOf(step); + if (batch.length > 0 && bytes + size > MAX_STEPS_MESSAGE_BYTES) break; + if (batch.length === 0 && size > MAX_STEPS_MESSAGE_BYTES) break; + batch.push(step); + bytes += size; + } + return batch; +} + export interface CollabConnection { ws: WebSocket; docId: string; @@ -197,8 +244,29 @@ export function initCollab( const sendable = getSendableSteps(editorInstance.view); console.log("[collab] sendable:", sendable); if (sendable) { - console.log("[collab] Sending", sendable.steps.length, "steps, version:", sendable.version); - send(MSG.STEPS, sendable.version, sendable.steps, sendable.clientID); + const batch = stepBatch(sendable.steps, stepWireSize); + if (batch.length === 0) { + // The head pending step alone exceeds the wire budget (e.g. a + // >1 MiB paste represented as a single replace step). Do not send + // it: the server would refuse the message and the reconnect path + // would discard the edit. It stays in the local document, + // unconfirmed; surface the wedge instead of losing content. + console.error( + "[collab] Pending step exceeds the", + MAX_STEPS_MESSAGE_BYTES, + "byte message budget and cannot be synced; edit kept locally only.", + ); + return; + } + console.log( + "[collab] Sending", + batch.length, + "of", + sendable.steps.length, + "steps, version:", + sendable.version, + ); + send(MSG.STEPS, sendable.version, batch, sendable.clientID); } }; @@ -290,6 +358,12 @@ export function initCollab( const tr = receiveTransaction(editorInstance.view.state, parsedSteps, clientIDs); editorInstance.view.dispatch(tr); console.log("[collab] Applied transaction, new version:", getVersion(editorInstance.view.state)); + // If this update confirmed one of our batches and more steps are + // still pending (an oversized transaction chunked by stepBatch), + // send the next batch now - no new editor:change event fires for + // a confirmation, so without this the remainder would stall + // until the next local edit. + handleEditorChange(); } catch (err) { // Step application failed — editor state is desynchronized. // Trigger reconnect to get fresh Init + catch-up from server.