Repository navigation
fix(id): bound collab WebSocket input (#1965) #4051
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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,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" | ||
| )); | ||
| } | ||
|
|
||
| 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) | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
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 Useful? React with 👍 / 👎.
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fixed in cea81a3 (client side,
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. | ||
|
|
@@ -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() { | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Selecting and indenting more than 1,000 code lines produces one step per line (
web/src/indent.ts:152-156), buthandleEditorChangeinweb/src/collab.tssends 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 👍 / 👎.
There was a problem hiding this comment.
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.
handleEditorChangeinpkgs/id/web/src/collab.tsnow sends at mostMAX_STEPS_PER_MESSAGE(1000, mirroring the server constant in collab.rs) per Steps message via the newstepBatch()helper; the remaining steps stay unconfirmed, and the Update handler flushes the next batch as soon asreceiveTransactionconfirms the previous one (noeditor:changeevent 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
stepBatchcases incollab.test.ts(at-cap, oversized chunking with order preserved, empty) — vitestcollab.test.ts6/6 pass,tsc --noEmitclean. 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_mutationandtest_apply_steps_accepts_small_batch_and_broadcasts_updateboth pass.