| 1 | //! Native editor CRDT operations. In production this crate runs ONLY inside |
| 2 | //! a fuel/memory-limited WebAssembly interpreter, never as a native decoder. |
| 3 | //! The server retains its separate ABI; both modules share the vendored yrs and its patches (native/vendor/yrs-0.23.5/PATCHES.md). |
| 4 | mod projection; |
| 5 | mod operations; |
| 6 | mod structure; |
| 7 | mod display; |
| 8 | mod paste; |
| 9 | mod lists; |
| 10 | mod input_rules; |
| 11 | use serde_json::{json, Value}; |
| 12 | use std::{cell::RefCell, collections::{HashMap, HashSet}, sync::{Arc, Mutex}}; |
| 13 | use yrs::{BranchID, Doc, OffsetKind, Options, ReadTxn, StateVector, Transact, UndoManager, Update, XmlOut, ID}; |
| 14 | use yrs::updates::decoder::{Decode, Decoder, DecoderV1}; |
| 15 | use yrs::updates::encoder::Encode; |
| 16 | |
| 17 | pub struct Editor { |
| 18 | doc: Doc, |
| 19 | undo: UndoManager, |
| 20 | /// The v1 update of every transaction committed while a command runs, |
| 21 | /// exactly what Yjs emits as `doc.on('update')`. |
| 22 | /// Subscribed only while a command runs: applying a peer's update or a |
| 23 | /// whole state must neither encode it again nor keep a copy. |
| 24 | transactions: Arc<Mutex<Vec<Vec<u8>>>>, |
| 25 | /// What the last projection handed out held, and which of its top-level |
| 26 | /// blocks any transaction has touched since, so `projection_delta` |
| 27 | /// re-projects only those. |
| 28 | presented: Arc<Mutex<Presented>>, |
| 29 | } |
| 30 | #[derive(Default)] |
| 31 | struct Presented { |
| 32 | blocks: Option<Vec<ID>>, |
| 33 | touched: HashSet<ID>, |
| 34 | } |
| 35 | fn top_level_id(node: &XmlOut) -> Option<ID> { |
| 36 | match node.id() { BranchID::Nested(id) => Some(id), BranchID::Root(_) => None } |
| 37 | } |
| 38 | impl Editor { |
| 39 | pub fn new(guid: &str, client_id: u64) -> Self { |
| 40 | let mut options = Options::with_guid_and_client_id(guid.into(), client_id); |
| 41 | options.offset_kind = OffsetKind::Utf16; |
| 42 | let doc = Doc::with_options(options); |
| 43 | let root = doc.get_or_insert_xml_fragment("prosemirror"); |
| 44 | let undo = UndoManager::with_scope_and_options(&doc, &root, yrs::undo::Options { |
| 45 | capture_timeout_millis: 0, |
| 46 | tracked_origins: HashSet::from(["native-edit".into()]), |
| 47 | capture_transaction: None, |
| 48 | timestamp: Arc::new(|| 1), |
| 49 | }); |
| 50 | let transactions = Arc::new(Mutex::new(Vec::new())); |
| 51 | let presented = Arc::new(Mutex::new(Presented::default())); |
| 52 | let touched = presented.clone(); |
| 53 | let root_branch = projection::fragment_ptr(&root); |
| 54 | // changed_parent_types lists every changed branch and all its |
| 55 | // ancestors, so the top-level blocks among them are exactly those |
| 56 | // whose content, attributes or descendants this transaction changed. |
| 57 | // After observers, before garbage collection: every listed branch is |
| 58 | // still alive, including one this transaction deleted. |
| 59 | doc.observe_after_transaction_with("docs-presented", move |txn| { |
| 60 | let mut blocks = Vec::new(); |
| 61 | for branch in txn.changed_parent_types() { |
| 62 | let Ok(node) = XmlOut::try_from(*branch) else { continue }; |
| 63 | let parent = match &node { XmlOut::Element(e) => yrs::Xml::parent(e), XmlOut::Text(t) => yrs::Xml::parent(t), XmlOut::Fragment(f) => f.parent() }; |
| 64 | if parent.is_some_and(|parent| projection::branch_eq(parent.as_ptr(), root_branch)) { |
| 65 | if let Some(id) = top_level_id(&node) { blocks.push(id); } |
| 66 | } |
| 67 | } |
| 68 | if !blocks.is_empty() { if let Ok(mut touched) = touched.lock() { touched.touched.extend(blocks); } } |
| 69 | }).expect("no transaction is open while the editor is created"); |
| 70 | Self {doc, undo, transactions, presented} |
| 71 | } |
| 72 | pub fn apply(&self, bytes: &[u8]) -> Result<(), &'static str> { self.apply_origin(bytes, false) } |
| 73 | pub fn apply_local(&self, bytes: &[u8]) -> Result<(), &'static str> { self.apply_origin(bytes, true) } |
| 74 | fn apply_origin(&self, bytes: &[u8], local: bool) -> Result<(), &'static str> { |
| 75 | let updates = decode_updates(bytes)?; |
| 76 | let mut txn = self.doc.transact_mut_with(if local { "native-edit" } else { "remote" }); |
| 77 | for update in updates { txn.apply_update(update).map_err(|_| "invalid_update")?; } |
| 78 | Ok(()) |
| 79 | } |
| 80 | /// Whether every struct and deletion this replica holds is integrated. A |
| 81 | /// state that parks some (a dependency it never received) shows less than |
| 82 | /// it holds, and its stored sequence must not be trusted (#145). |
| 83 | pub fn is_whole(&self) -> bool { |
| 84 | let txn = self.doc.transact(); |
| 85 | txn.store().pending_update().is_none() && txn.store().pending_ds().is_none() |
| 86 | } |
| 87 | /// What this replica holds but cannot integrate, as a canonical string: |
| 88 | /// the id ranges of parked structs and of parked deletions, by client. |
| 89 | /// Empty when whole. Stable across a rebuild from the replica's own |
| 90 | /// snapshot, so a replica can tell parking it has accepted (the server's |
| 91 | /// own) from anything new (#147). |
| 92 | pub fn parked(&self) -> String { |
| 93 | fn render(mut clients: Vec<(u64, Vec<(u32, u32)>)>, out: &mut String) { |
| 94 | clients.sort(); |
| 95 | for (client, ranges) in clients { |
| 96 | out.push_str(&client.to_string()); |
| 97 | for (start, end) in ranges { out.push_str(&format!(" {start}-{end}")); } |
| 98 | out.push(';'); |
| 99 | } |
| 100 | } |
| 101 | let txn = self.doc.transact(); |
| 102 | let store = txn.store(); |
| 103 | let mut out = String::new(); |
| 104 | if let Some(pending) = store.pending_update() { |
| 105 | let structs = yrs::DeleteSet::from(pending.update.insertions(true)); |
| 106 | render(structs.iter().map(|(c, r)| (*c, r.iter().map(|x| (x.start, x.end)).collect())).collect(), &mut out); |
| 107 | } |
| 108 | if let Some(deletes) = store.pending_ds() { |
| 109 | let mut deletes = deletes.clone(); |
| 110 | deletes.squash(); |
| 111 | out.push('|'); |
| 112 | render(deletes.iter().map(|(c, r)| (*c, r.iter().map(|x| (x.start, x.end)).collect())).collect(), &mut out); |
| 113 | } |
| 114 | out |
| 115 | } |
| 116 | pub fn snapshot(&self) -> Vec<u8> { |
| 117 | self.doc.transact().encode_state_as_update_v1(&StateVector::default()) |
| 118 | } |
| 119 | /// The whole document. It also becomes the base `projection_delta` |
| 120 | /// reports changes against. |
| 121 | pub fn projection(&self) -> Value { |
| 122 | let root = self.doc.get_or_insert_xml_fragment("prosemirror"); |
| 123 | let txn = self.doc.transact(); |
| 124 | let mut blocks = Vec::new(); |
| 125 | let children: Vec<Value> = projection::indexed_children(&root, &txn).map(|(_, node)| { |
| 126 | if let Some(id) = top_level_id(&node) { blocks.push(id); } |
| 127 | projection::project(&node, &txn) |
| 128 | }).collect(); |
| 129 | if let Ok(mut presented) = self.presented.lock() { presented.blocks = Some(blocks); presented.touched.clear(); } |
| 130 | json!({"children": children, "canUndo": !self.undo.undo_stack().is_empty(), "canRedo": !self.undo.redo_stack().is_empty()}) |
| 131 | } |
| 132 | /// What changed since the last projection or delta, as edits to its list |
| 133 | /// of top-level blocks: `keep` n unchanged blocks, `remove` n, `insert` |
| 134 | /// these freshly projected blocks. Applied in order to the previous |
| 135 | /// children (`base` long) they give the current ones (`count` long). Only |
| 136 | /// blocks a transaction touched, and new ones, are projected. |
| 137 | pub fn projection_delta(&self) -> Value { |
| 138 | let root = self.doc.get_or_insert_xml_fragment("prosemirror"); |
| 139 | let txn = self.doc.transact(); |
| 140 | let (previous, touched) = match self.presented.lock() { |
| 141 | Ok(mut presented) => (presented.blocks.take().unwrap_or_default(), std::mem::take(&mut presented.touched)), |
| 142 | Err(_) => (Vec::new(), HashSet::new()), |
| 143 | }; |
| 144 | let position: HashMap<ID, usize> = previous.iter().enumerate().map(|(index, id)| (*id, index)).collect(); |
| 145 | let mut ops: Vec<Value> = Vec::new(); |
| 146 | fn count(ops: &mut Vec<Value>, kind: &str, n: usize) { |
| 147 | if n == 0 { return; } |
| 148 | if let Some(last) = ops.last_mut().filter(|last| last[kind].is_u64()) { last[kind] = json!(last[kind].as_u64().unwrap_or(0) + n as u64); } |
| 149 | else { ops.push(json!({kind: n})); } |
| 150 | } |
| 151 | fn insert(ops: &mut Vec<Value>, node: Value) { |
| 152 | match ops.last_mut().and_then(|last| last["insert"].as_array_mut()) { |
| 153 | Some(nodes) => nodes.push(node), |
| 154 | None => ops.push(json!({"insert": [node]})), |
| 155 | } |
| 156 | } |
| 157 | let mut blocks = Vec::new(); |
| 158 | let mut base = 0; |
| 159 | for (_, node) in projection::indexed_children(&root, &txn) { |
| 160 | let id = top_level_id(&node); |
| 161 | if let Some(id) = id { blocks.push(id); } |
| 162 | let unchanged = id.filter(|id| !touched.contains(id)).and_then(|id| position.get(&id).copied()).filter(|at| *at >= base); |
| 163 | match unchanged { |
| 164 | Some(at) => { |
| 165 | count(&mut ops, "remove", at - base); |
| 166 | count(&mut ops, "keep", 1); |
| 167 | base = at + 1; |
| 168 | }, |
| 169 | None => insert(&mut ops, projection::project(&node, &txn)), |
| 170 | } |
| 171 | } |
| 172 | count(&mut ops, "remove", previous.len() - base); |
| 173 | let count = blocks.len(); |
| 174 | if let Ok(mut presented) = self.presented.lock() { presented.blocks = Some(blocks); } |
| 175 | json!({"base": previous.len(), "count": count, "ops": ops, "canUndo": !self.undo.undo_stack().is_empty(), "canRedo": !self.undo.redo_stack().is_empty()}) |
| 176 | } |
| 177 | /// The node and local offset a display range maps to (for tests). |
| 178 | #[doc(hidden)] |
| 179 | pub fn display_locate(&self, at: u32, length: u32) -> Result<(String, u32), &'static str> { display::locate(&self.doc, at, length) } |
| 180 | #[doc(hidden)] |
| 181 | pub fn display_length(&self) -> u32 { display::display_length(&self.doc.get_or_insert_xml_fragment("prosemirror"), &self.doc.transact()) } |
| 182 | pub fn anchor(&self, at: u32) -> Result<Value, &'static str> { display::anchor(&self.doc, at) } |
| 183 | pub fn resolve(&self, anchor: &Value) -> Result<u32, &'static str> { display::resolve(&self.doc, anchor) } |
| 184 | /// Runs one command and returns its update: only what its own |
| 185 | /// transactions inserted and deleted, as the browser sends. Never a |
| 186 | /// state-vector diff, which carries the document's whole delete set, nor |
| 187 | /// anything this replica parks: a transaction's update is written from |
| 188 | /// the block store, so a damaged duplicate never rides on a keystroke |
| 189 | /// (#147; tests/damaged_snapshots.rs). |
| 190 | pub fn command(&mut self, request: &Value) -> Result<Vec<u8>, &'static str> { |
| 191 | self.transactions.lock().map_err(|_| "invalid_command")?.clear(); |
| 192 | let sink = self.transactions.clone(); |
| 193 | let subscription = self.doc.observe_update_v1(move |_, event| { |
| 194 | if let Ok(mut sink) = sink.lock() { sink.push(event.update.clone()); } |
| 195 | }).map_err(|_| "invalid_command")?; |
| 196 | let result = self.execute(request); |
| 197 | drop(subscription); |
| 198 | let updates = std::mem::take(&mut *self.transactions.lock().map_err(|_| "invalid_command")?); |
| 199 | result?; |
| 200 | match updates.len() { |
| 201 | 0 => Ok(Update::new().encode_v1()), |
| 202 | 1 => Ok(updates.into_iter().next().unwrap_or_default()), |
| 203 | _ => { |
| 204 | let decoded = updates.iter().map(|bytes| Update::decode_v1(bytes).map_err(|_| "invalid_update")).collect::<Result<Vec<_>, _>>()?; |
| 205 | Ok(Update::merge_updates(decoded).encode_v1()) |
| 206 | }, |
| 207 | } |
| 208 | } |
| 209 | fn execute(&mut self, request: &Value) -> Result<(), &'static str> { |
| 210 | match request.get("op").and_then(Value::as_str).ok_or("invalid_command")? { |
| 211 | "batch" => { |
| 212 | let commands = request["commands"].as_array().filter(|v| v.len() <= 1000).ok_or("invalid_command")?; |
| 213 | if commands.iter().any(|c| ["batch","undo","redo"].contains(&c["op"].as_str().unwrap_or(""))) { return Err("invalid_command"); } |
| 214 | let mut affected = HashSet::new(); |
| 215 | for command in commands { |
| 216 | let target = lists::normalization_target(&self.doc, command); |
| 217 | self.execute(command)?; |
| 218 | if let Some(id) = target.and_then(|t| lists::normalized_identity(&self.doc, t)) { affected.insert(id); } |
| 219 | } |
| 220 | lists::normalize(&self.doc, &mut affected); |
| 221 | }, |
| 222 | "undo" => { self.undo.undo_blocking(); }, |
| 223 | "redo" => { self.undo.redo_blocking(); }, |
| 224 | "display_autoformat" | "display_revert_rule" | "display_exit_list" => input_rules::execute(&self.doc, request)?, |
| 225 | "list_indent" => lists::execute(&self.doc, request)?, |
| 226 | "display_paste" => paste::execute(&self.doc, request)?, |
| 227 | "display_edit" => display::execute(&self.doc, request)?, |
| 228 | "block" if ["bullet_list","ordered_list"].contains(&request["type"].as_str().unwrap_or("")) && lists::contains(&self.doc, request["node"].as_str().unwrap_or("")) => lists::toggle(&self.doc, request)?, |
| 229 | "block" | "split" | "hard_break" | "join_range" => structure::execute(&self.doc, request)?, |
| 230 | _ => operations::execute(&self.doc, request)?, |
| 231 | } |
| 232 | Ok(()) |
| 233 | } |
| 234 | } |
| 235 | |
| 236 | thread_local! { |
| 237 | static EDITOR: RefCell<Option<Editor>> = const { RefCell::new(None) }; |
| 238 | static OUTPUT: RefCell<Vec<u8>> = const { RefCell::new(Vec::new()) }; |
| 239 | } |
| 240 | |
| 241 | // All pointers are private WASM linear-memory offsets passed by the interpreter. |
| 242 | // No API in this module may be called with native pointers by an Apple process. |
| 243 | #[cfg(target_arch = "wasm32")] |
| 244 | #[no_mangle] |
| 245 | pub extern "C" fn docs_editor_alloc(len: u32) -> u32 { |
| 246 | if len > 8 * 1024 * 1024 + 1 { return 0; } |
| 247 | Box::into_raw(vec![0u8; len as usize].into_boxed_slice()) as *mut u8 as u32 |
| 248 | } |
| 249 | #[cfg(target_arch = "wasm32")] |
| 250 | #[no_mangle] |
| 251 | pub unsafe extern "C" fn docs_editor_free(ptr: u32, len: u32) { |
| 252 | if ptr != 0 { drop(Box::from_raw(std::ptr::slice_from_raw_parts_mut(ptr as *mut u8, len as usize))); } |
| 253 | } |
| 254 | #[cfg(target_arch = "wasm32")] |
| 255 | #[no_mangle] |
| 256 | pub unsafe extern "C" fn docs_editor_call(ptr: u32, len: u32) -> i32 { |
| 257 | let end = (ptr as u64) + (len as u64); |
| 258 | if len > 8 * 1024 * 1024 + 1 || end > (core::arch::wasm32::memory_size(0) * 65536) as u64 { return -1; } |
| 259 | let bytes = std::slice::from_raw_parts(ptr as *const u8, len as usize); |
| 260 | let result = dispatch(bytes); |
| 261 | match result { |
| 262 | Ok(bytes) => { OUTPUT.with(|out| *out.borrow_mut() = bytes); 0 }, |
| 263 | Err(code) => { OUTPUT.with(|out| *out.borrow_mut() = code.as_bytes().to_vec()); -1 }, |
| 264 | } |
| 265 | } |
| 266 | #[cfg(target_arch = "wasm32")] |
| 267 | #[no_mangle] |
| 268 | pub extern "C" fn docs_editor_output_ptr() -> u32 { OUTPUT.with(|out| out.borrow().as_ptr() as u32) } |
| 269 | #[cfg(target_arch = "wasm32")] |
| 270 | #[no_mangle] |
| 271 | pub extern "C" fn docs_editor_output_len() -> u32 { OUTPUT.with(|out| out.borrow().len() as u32) } |
| 272 | |
| 273 | fn decode_updates(mut remaining: &[u8]) -> Result<Vec<Update>, &'static str> { |
| 274 | let mut updates = Vec::new(); |
| 275 | while !remaining.is_empty() { |
| 276 | let mut decoder = DecoderV1::from(remaining); |
| 277 | updates.push(Update::decode(&mut decoder).map_err(|_| "invalid_update")?); |
| 278 | let trailing = decoder.read_to_end().map_err(|_| "invalid_update")?.len(); |
| 279 | if trailing >= remaining.len() { return Err("invalid_update"); } |
| 280 | remaining = &remaining[remaining.len() - trailing..]; |
| 281 | } |
| 282 | Ok(updates) |
| 283 | } |
| 284 | |
| 285 | /// The projection of any document, as `Editor::projection` draws it (its |
| 286 | /// children only): lets tests read a plain yrs peer's own display. |
| 287 | #[doc(hidden)] |
| 288 | pub fn projection_of(doc: &Doc) -> Value { |
| 289 | let root = doc.get_or_insert_xml_fragment("prosemirror"); |
| 290 | let txn = doc.transact(); |
| 291 | json!({"children": projection::children(&root, &txn)}) |
| 292 | } |
| 293 | |
| 294 | pub fn dispatch(bytes: &[u8]) -> Result<Vec<u8>, &'static str> { |
| 295 | // Merge pending writes without constructing a document: pending structs may |
| 296 | // depend on state already held by the server. Snapshotting an empty document |
| 297 | // would silently lose those structs and deletes. |
| 298 | if bytes.first() == Some(&253) { |
| 299 | let updates = decode_updates(&bytes[1..])?; |
| 300 | if updates.is_empty() { return Err("invalid_update"); } |
| 301 | return Ok(Update::merge_updates(updates).encode_v1()); |
| 302 | } |
| 303 | // Binary envelope avoids expanding an 8MiB log into JSON byte numbers. |
| 304 | if matches!(bytes.first(), Some(254 | 255)) { |
| 305 | return EDITOR.with(|cell| { |
| 306 | cell.borrow().as_ref().ok_or("not_open")?.apply_origin(&bytes[1..], bytes[0] == 254)?; |
| 307 | Ok(Vec::new()) |
| 308 | }); |
| 309 | } |
| 310 | let request: Value = serde_json::from_slice(bytes).map_err(|_| "invalid_command")?; |
| 311 | EDITOR.with(|cell| { |
| 312 | let mut state = cell.borrow_mut(); |
| 313 | if request["op"] == "open" { |
| 314 | let guid = request["guid"].as_str().ok_or("invalid_identity")?; |
| 315 | let client = request["client"].as_u64().filter(|v| *v > 0 && *v <= u32::MAX as u64).ok_or("invalid_identity")?; |
| 316 | *state = Some(Editor::new(guid, client)); |
| 317 | return Ok(Vec::new()); |
| 318 | } |
| 319 | let editor = state.as_mut().ok_or("not_open")?; |
| 320 | match request["op"].as_str() { |
| 321 | Some("apply") => { |
| 322 | let bytes = request["bytes"].as_array().ok_or("invalid_update")?.iter() |
| 323 | .map(|v| v.as_u64().filter(|n| *n <= 255).map(|n| n as u8).ok_or("invalid_update")) |
| 324 | .collect::<Result<Vec<_>, _>>()?; |
| 325 | editor.apply(&bytes)?; Ok(Vec::new()) |
| 326 | }, |
| 327 | Some("snapshot") => Ok(editor.snapshot()), |
| 328 | Some("whole") => serde_json::to_vec(&editor.is_whole()).map_err(|_| "invalid_projection"), |
| 329 | Some("parked") => serde_json::to_vec(&editor.parked()).map_err(|_| "invalid_projection"), |
| 330 | Some("anchor") => serde_json::to_vec(&editor.anchor(request["at"].as_u64().and_then(|v| u32::try_from(v).ok()).ok_or("invalid_range")?)?).map_err(|_| "invalid_anchor"), |
| 331 | Some("resolve") => serde_json::to_vec(&editor.resolve(&request["anchor"])?).map_err(|_| "invalid_anchor"), |
| 332 | Some("clients") => serde_json::to_vec(&editor.doc.transact().state_vector().iter().map(|(id, _)| *id).collect::<Vec<_>>()).map_err(|_| "invalid_projection"), |
| 333 | Some("project") => serde_json::to_vec(&editor.projection()).map_err(|_| "invalid_projection"), |
| 334 | Some("project_delta") => serde_json::to_vec(&editor.projection_delta()).map_err(|_| "invalid_projection"), |
| 335 | _ => editor.command(&request), |
| 336 | } |
| 337 | }) |
| 338 | } |
| 339 | |
| 340 | #[cfg(target_arch = "wasm32")] |
| 341 | #[no_mangle] |
| 342 | extern "Rust" fn __getrandom_v03_custom(_dest: *mut u8, _len: usize) -> Result<(), getrandom::Error> { |
| 343 | Err(getrandom::Error::UNSUPPORTED) |
| 344 | } |
| 345 | |