Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions pkgs/id/src/frames.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
166 changes: 113 additions & 53 deletions pkgs/id/src/web/collab.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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 {
Expand Down Expand Up @@ -626,23 +630,72 @@ fn extract_binary(msg: &Message) -> Option<Vec<u8>> {
}
}

/// 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<u64, String> {
if steps.len() > MAX_STEPS_PER_MESSAGE {
return Err(format!(
"Step batch exceeds maximum of {MAX_STEPS_PER_MESSAGE} steps"
));
Comment on lines +641 to +644

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Chunk legitimate editor transactions before enforcing the step limit

Selecting and indenting more than 1,000 code lines produces one step per line (web/src/indent.ts:152-156), but handleEditorChange in web/src/collab.ts sends all pending steps without chunking. This new rejection leaves those steps unconfirmed, and the client's error handler only recovers from version-mismatch/desynchronization errors. Every subsequent edit therefore resends the oversized pending batch and is rejected again, blocking synchronization for the rest of the editor session. Coordinate this server limit with client-side batching so legitimate large transactions can still synchronize.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in e3e95d4 — client-side batching, as suggested. handleEditorChange in pkgs/id/web/src/collab.ts now sends at most MAX_STEPS_PER_MESSAGE (1000, mirroring the server constant in collab.rs) per Steps message via the new stepBatch() helper; the remaining steps stay unconfirmed, and the Update handler flushes the next batch as soon as receiveTransaction confirms the previous one (no editor:change event fires for a confirmation, so without the flush the remainder would stall until the next local edit). A legitimate >1000-step transaction (e.g. indenting >1000 lines) now syncs in successive batches instead of wedging the session on the rejection.

Tests: 3 new stepBatch cases in collab.test.ts (at-cap, oversized chunking with order preserved, empty) — vitest collab.test.ts 6/6 pass, tsc --noEmit clean. The deferred server-side regression tests now run locally too: cargo test --lib --features web test_apply_steps — test_apply_steps_rejects_oversized_batch_without_mutation and test_apply_steps_accepts_small_batch_and_broadcasts_update both pass.

}

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,
Path(doc_id): Path<String>,
Query(params): Query<WsParams>,
State(state): State<super::AppState>,
) -> 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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Guard oversized edits before sending bounded messages

When a user pastes more than 1 MiB of text, ProseMirror can represent the insertion as a single replace step, so the new count-based stepBatch() still sends a message exceeding this limit. The server rejects it before applying the edit, and the client's reconnect path in web/src/collab.ts destroys the existing editor and initializes it from server state, silently discarding the paste. Coordinate the transport limit with client-side encoded-size handling, including individual oversized steps, so legitimate edits are split safely or rejected locally without losing their content.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in cea81a3 (client side, pkgs/id/web/src/collab.ts):

  • stepBatch is now size-aware, not just count-aware: it also stops at MAX_STEPS_MESSAGE_BYTES (the 1 MiB server frame cap minus an envelope reserve), measuring each step with the exact MessagePack encoder the send path uses. A batch of medium steps can no longer encode past the cap and be refused whole. Tests cover size chunking, the exact-fit boundary, and the oversized-first-step case.
  • A single step that alone exceeds the budget (the >1 MiB paste case) yields an empty batch, and handleEditorChange withholds it with an error log instead of sending it: the edit stays in the local document rather than being refused by the server and silently discarded by the reconnect re-init.

One part is deliberately not done by splitting steps on the wire: prosemirror-collab confirms unconfirmed steps by count from the server's echo, so turning one local step into several wire steps would corrupt confirmation bookkeeping. True chunked sync of a single oversized insertion has to happen at dispatch time in the editor (several transactions), which is a separate change — filed as a follow-up issue (linked below) rather than improvised here.

.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.
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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() {
Expand Down
4 changes: 3 additions & 1 deletion pkgs/id/src/web/tags_ws.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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},
Expand Down Expand Up @@ -205,7 +206,8 @@ pub async fn ws_tags_handler(
ws: WebSocketUpgrade,
State(state): State<AppState>,
) -> 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.
Expand Down
56 changes: 55 additions & 1 deletion pkgs/id/web/src/collab.test.ts
Original file line number Diff line number Diff line change
@@ -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 });
Expand Down Expand Up @@ -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"]);
});
});
Loading
Loading