yrby 0.8.1 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
data/ext/yrby/src/lib.rs CHANGED
@@ -1,14 +1,21 @@
1
1
  use magnus::{
2
- function, method, prelude::*, Error, ExceptionClass, IntoValue, RArray, RString, Ruby,
2
+ function, method, prelude::*, Error, ExceptionClass, IntoValue, RArray, RHash, RString, Ruby,
3
3
  TryConvert, Value,
4
4
  };
5
- use yrs::sync::{Message, SyncMessage};
5
+ use std::cell::RefCell;
6
+
7
+ use yrs::sync::{Awareness, Message, SyncMessage};
6
8
  use yrs::updates::decoder::Decode;
7
9
  use yrs::updates::encoder::Encode;
8
- use yrs::{Doc, GetString, ReadTxn, Transact};
10
+ use yrs::{DeepObservable, Doc, GetString, ReadTxn, Text, Transact};
9
11
 
12
+ mod array;
13
+ mod map;
10
14
  mod protocol;
11
15
  mod read;
16
+ mod shared;
17
+ mod text;
18
+ mod xml_text;
12
19
  use lexical_yjs_html as lexical_html;
13
20
  use prosemirror_yjs_html as prosemirror_html;
14
21
  use protocol::{
@@ -26,7 +33,49 @@ pub(crate) use yjs_html_core as render_rules;
26
33
  /// interior-mutability wrapper (RefCell and friends): every method opens and
27
34
  /// closes its transaction within a single call.
28
35
  #[magnus::wrap(class = "Y::Doc", free_immediately, size)]
29
- struct RbDoc(Doc);
36
+ struct RbDoc(Doc, Unsent);
37
+
38
+ /// The updates of this document's own transactions that no `Doc#edit` has
39
+ /// returned yet. Every transaction but a peer's lands here when it commits,
40
+ /// after yrs is done changing the document, whichever thread or fiber made
41
+ /// it and whether or not an edit was running. So no local write is left out.
42
+ /// They're merged only when an edit takes them, so until then the document
43
+ /// holds the bytes of every local write.
44
+ type Unsent = std::sync::Arc<std::sync::Mutex<Vec<Vec<u8>>>>;
45
+
46
+ /// `Unsent`'s list. A push or a take holds it only briefly, so taking it
47
+ /// with the GVL held never waits long.
48
+ fn lock(unsent: &Unsent) -> std::sync::MutexGuard<'_, Vec<Vec<u8>>> {
49
+ unsent
50
+ .lock()
51
+ .unwrap_or_else(|poisoned| poisoned.into_inner())
52
+ }
53
+
54
+ /// How many updates `merge_unsent` merges at once.
55
+ const MERGE_FAN_IN: usize = 16;
56
+
57
+ /// The updates merged into one, a few at a time and then the results again.
58
+ /// One merge of them all costs time quadratic in how many there are.
59
+ fn merge_unsent(updates: &[Vec<u8>]) -> Result<Vec<u8>, String> {
60
+ let mut level: Vec<Vec<u8>> = match updates {
61
+ [update] => return Ok(update.clone()),
62
+ _ => merge_chunks(updates)?,
63
+ };
64
+ while level.len() > 1 {
65
+ level = merge_chunks(&level)?;
66
+ }
67
+ Ok(level.pop().unwrap_or_default())
68
+ }
69
+
70
+ fn merge_chunks(updates: &[Vec<u8>]) -> Result<Vec<Vec<u8>>, String> {
71
+ updates
72
+ .chunks(MERGE_FAN_IN)
73
+ .map(|chunk| match chunk {
74
+ [update] => Ok(update.clone()),
75
+ _ => yrs::merge_updates_v1(chunk).map_err(|e| e.to_string()),
76
+ })
77
+ .collect()
78
+ }
30
79
 
31
80
  /// Compile-time proof that the wrapped Doc is thread-safe. If a future yrs
32
81
  /// upgrade makes Doc lose Send/Sync, this fails the build instead of silently
@@ -37,6 +86,10 @@ fn assert_thread_safe() {
37
86
  is_send_sync::<Doc>();
38
87
  is_send_sync::<RbLexical>();
39
88
  is_send_sync::<RbProseMirror>();
89
+ is_send_sync::<map::RbMap>();
90
+ is_send_sync::<array::RbArray>();
91
+ is_send_sync::<text::RbText>();
92
+ is_send_sync::<xml_text::RbXmlText>();
40
93
  }
41
94
 
42
95
  /// Run `f` with the GVL (Global VM Lock) released, so other Ruby threads,
@@ -60,7 +113,17 @@ fn assert_thread_safe() {
60
113
  ///
61
114
  /// Panics inside the closure are caught and re-raised (resumed) after the GVL
62
115
  /// is reacquired, where magnus converts them to Ruby exceptions.
63
- fn nogvl<F, R>(f: F) -> R
116
+ ///
117
+ /// Interrupts (Thread#raise, Thread#kill, Timeout) come back as the error.
118
+ /// `rb_thread_call_without_gvl` would raise one before or after the closure,
119
+ /// and Ruby's raise jumps over Rust frames without running their
120
+ /// destructors. With `RB_NOGVL_INTR_FAIL` Ruby never raises here: it skips
121
+ /// the closure when an interrupt is already pending, and then the closure
122
+ /// runs with the GVL held. After it, `thread_check_ints` makes the check
123
+ /// `rb_thread_call_without_gvl` makes, as a `Result`. That check also
124
+ /// re-arms interrupts still queued behind the first, so a thread that only
125
+ /// calls into yrby still gets a kill queued behind a raise.
126
+ pub(crate) fn nogvl<F, R>(f: F) -> Result<R, Error>
64
127
  where
65
128
  F: FnOnce() -> R + Send,
66
129
  R: Send,
@@ -88,17 +151,23 @@ where
88
151
  result: None,
89
152
  };
90
153
  unsafe {
91
- rb_sys::rb_thread_call_without_gvl(
154
+ rb_sys::rb_nogvl(
92
155
  Some(callback::<F, R>),
93
156
  &mut ctx as *mut Ctx<F, R> as *mut c_void,
94
157
  None,
95
158
  std::ptr::null_mut(),
159
+ rb_sys::RB_NOGVL_INTR_FAIL as _,
96
160
  );
97
161
  }
98
- match ctx.result.expect("nogvl callback did not run") {
162
+ if let Some(func) = ctx.func.take() {
163
+ ctx.result = Some(catch_unwind(AssertUnwindSafe(func)));
164
+ }
165
+ let result = match ctx.result.expect("nogvl callback did not run") {
99
166
  Ok(result) => result,
100
167
  Err(panic) => resume_unwind(panic),
101
- }
168
+ };
169
+ Ruby::get().unwrap().thread_check_ints()?;
170
+ Ok(result)
102
171
  }
103
172
 
104
173
  /// Helper to create a binary Ruby string from bytes. Called only with the GVL
@@ -119,7 +188,7 @@ fn copy_bytes(s: RString) -> Vec<u8> {
119
188
  /// native decode/apply failures surface as a project-specific error rather than
120
189
  /// a generic RuntimeError. Falls back to RuntimeError only if the class somehow
121
190
  /// can't be resolved.
122
- fn yrb_error(msg: String) -> Error {
191
+ pub(crate) fn yrb_error(msg: String) -> Error {
123
192
  let ruby = Ruby::get().unwrap();
124
193
  let class = ruby
125
194
  .eval::<ExceptionClass>("Y::Error")
@@ -133,28 +202,48 @@ fn yrb_error(msg: String) -> Error {
133
202
 
134
203
  impl RbDoc {
135
204
  /// Create a new Doc with an optional client_id
205
+ ///
206
+ /// The document counts text in UTF-16 units, as Yjs does, so positions
207
+ /// agree with every editor's. The Ruby handles convert to characters.
136
208
  fn new(args: &[Value]) -> Result<Self, Error> {
137
- let doc = if args.is_empty() {
138
- Doc::new()
209
+ let mut options = if args.is_empty() {
210
+ yrs::Options::default()
139
211
  } else {
140
212
  let client_id: u64 = TryConvert::try_convert(args[0])?;
141
- Doc::with_client_id(client_id)
213
+ yrs::Options::with_client_id(yrs::block::ClientID::new(client_id))
142
214
  };
143
- Ok(RbDoc(doc))
215
+ options.offset_kind = yrs::OffsetKind::Utf16;
216
+ let doc = Doc::with_options(options);
217
+ let unsent = Unsent::default();
218
+ let sink = unsent.clone();
219
+ doc.observe_update_v1("yrby-unsent", move |txn, event| {
220
+ if shared::is_remote(txn.origin()) {
221
+ return;
222
+ }
223
+ lock(&sink).push(event.update.clone());
224
+ })
225
+ .map_err(|e| yrb_error(e.to_string()))?;
226
+ Ok(RbDoc(doc, unsent))
227
+ }
228
+
229
+ /// The id this document writes its own edits under. Presence for the same
230
+ /// writer uses it too, so editors tie a caret to its author's edits.
231
+ fn client_id(&self) -> u64 {
232
+ self.0.client_id().get()
144
233
  }
145
234
 
146
- fn encode_state_vector(&self) -> RString {
235
+ fn encode_state_vector(&self) -> Result<RString, Error> {
147
236
  let doc = &self.0;
148
237
  let sv = nogvl(move || {
149
238
  let txn = doc.transact();
150
239
  txn.state_vector().encode_v1()
151
- });
152
- binary_string(&sv)
240
+ })?;
241
+ Ok(binary_string(&sv))
153
242
  }
154
243
 
155
244
  /// Names of the document's root types, so a content reader can find the one
156
245
  /// holding text without knowing it up front.
157
- fn root_names(&self) -> Vec<String> {
246
+ fn root_names(&self) -> Result<Vec<String>, Error> {
158
247
  let doc = &self.0;
159
248
  nogvl(move || {
160
249
  doc.transact()
@@ -164,7 +253,7 @@ impl RbDoc {
164
253
  })
165
254
  }
166
255
 
167
- fn read_text(&self, name: String) -> Option<String> {
256
+ fn read_text(&self, name: String) -> Result<Option<String>, Error> {
168
257
  let doc = &self.0;
169
258
  nogvl(move || {
170
259
  // Exactly ONE transaction per call. Opening a second while the
@@ -178,7 +267,7 @@ impl RbDoc {
178
267
  /// Text of an XML-shaped root, one top-level block per line. The walk +
179
268
  /// block-join logic lives in `read::xml_blocks_text` (pure, Rust-tested);
180
269
  /// this just opens the transaction and resolves the root.
181
- fn read_xml(&self, name: String) -> Option<String> {
270
+ fn read_xml(&self, name: String) -> Result<Option<String>, Error> {
182
271
  let doc = &self.0;
183
272
  nogvl(move || {
184
273
  let txn = doc.transact();
@@ -191,7 +280,7 @@ impl RbDoc {
191
280
  /// recursive). Complements read_text/read_xml for structured shared state.
192
281
  /// Callers parse the JSON (e.g. `JSON.parse(doc.read_map("state"))`). The
193
282
  /// serialization lives in `read::map_json` (pure, Rust-tested).
194
- fn read_map(&self, name: String) -> Option<String> {
283
+ fn read_map(&self, name: String) -> Result<Option<String>, Error> {
195
284
  let doc = &self.0;
196
285
  nogvl(move || {
197
286
  let txn = doc.transact();
@@ -205,7 +294,7 @@ impl RbDoc {
205
294
  /// array: a board's cards, a sheet's rows. Callers parse the JSON (e.g.
206
295
  /// `JSON.parse(doc.read_array("cards"))`). The serialization lives in
207
296
  /// `read::array_json` (pure, Rust-tested).
208
- fn read_array(&self, name: String) -> Option<String> {
297
+ fn read_array(&self, name: String) -> Result<Option<String>, Error> {
209
298
  let doc = &self.0;
210
299
  nogvl(move || {
211
300
  let txn = doc.transact();
@@ -218,7 +307,7 @@ impl RbDoc {
218
307
  /// set: content that couldn't integrate because a causally-prior update is
219
308
  /// missing. Such content is a recovery buffer, not document state; it heals if
220
309
  /// the missing dependency later arrives. A pure read.
221
- fn pending(&self) -> bool {
310
+ fn pending(&self) -> Result<bool, Error> {
222
311
  let doc = &self.0;
223
312
  nogvl(move || has_pending(doc))
224
313
  }
@@ -231,11 +320,163 @@ impl RbDoc {
231
320
  /// stays lossless for raw-update recovery.)
232
321
  fn compacted_state_update(&self) -> Result<RString, Error> {
233
322
  let doc = &self.0;
234
- let update = nogvl(move || integrated_update(doc, &yrs::StateVector::default()))
323
+ let update = nogvl(move || integrated_update(doc, &yrs::StateVector::default()))?
235
324
  .map_err(yrb_error)?;
236
325
  Ok(binary_string(&update))
237
326
  }
238
327
 
328
+ /// A live `Y::Array` handle to the root array named `name` (created if
329
+ /// absent). Writes through it mutate the document and sync to every peer.
330
+ fn get_array(&self, name: String) -> Result<array::RbArray, Error> {
331
+ array::root_array(&self.0, name)
332
+ }
333
+
334
+ /// A live `Y::Text` handle to the root text named `name` (created if
335
+ /// absent). This is what an agent appends into.
336
+ fn get_text(&self, name: String) -> Result<text::RbText, Error> {
337
+ text::root_text(&self.0, name)
338
+ }
339
+
340
+ /// A live `Y::XmlText` handle to the root xml text named `name` (created
341
+ /// if absent). Rich-text editors keep their document here; this is how a
342
+ /// Ruby process writes a paragraph into one.
343
+ fn get_xml_text(&self, name: String) -> Result<xml_text::RbXmlText, Error> {
344
+ xml_text::root_xml_text(&self.0, name)
345
+ }
346
+
347
+ /// A live `Y::Map` handle to the root map named `name` (created if absent).
348
+ /// Unlike `read_map` (a JSON snapshot), the returned handle reads and *writes*
349
+ /// the actual shared map, with the same thread-safety guarantees as the Doc.
350
+ fn get_map(&self, name: String) -> Result<map::RbMap, Error> {
351
+ map::root_map(&self.0, name)
352
+ }
353
+
354
+ /// Apply `update` and report which blocks of the root `XmlText` named
355
+ /// `root` it touched, as ordinals: a change inside a block, a block
356
+ /// added, or a block removed (the ordinal it had). Ordinals count the
357
+ /// root's `XmlText` blocks, as `xml_text(n)` does, so a divider or an
358
+ /// image above a block doesn't shift it. This is what lets a process
359
+ /// following a document react to the part that changed.
360
+ fn apply_update_changes(&self, update: RString, root: String) -> Result<RArray, Error> {
361
+ let bytes = copy_bytes(update);
362
+ let doc = &self.0;
363
+ let changed = nogvl(move || -> Result<Vec<u32>, String> {
364
+ // One transaction from the snapshot of the blocks to the commit,
365
+ // under an origin of its own: another write can't change the
366
+ // blocks in between, and its events don't count.
367
+ let key = shared::remote_key();
368
+ let mut txn = doc.transact_mut_with(key.clone());
369
+ let fragment = yrs::WriteTxn::get_or_insert_xml_fragment(&mut txn, root.as_str());
370
+ let branch: &yrs::branch::Branch = fragment.as_ref();
371
+ let target = yrs::XmlTextRef::from(yrs::branch::BranchPtr::from(branch));
372
+ let hits = std::sync::Arc::new(std::sync::Mutex::new(Vec::<u32>::new()));
373
+ let sink = hits.clone();
374
+ let root_ref = target.clone();
375
+ let before = Children::of(&txn, &target);
376
+ let ours = key.clone();
377
+ target.observe_deep(key.clone(), move |txn, events| {
378
+ if txn.origin() != Some(&ours) {
379
+ return;
380
+ }
381
+ let children = Children::of(txn, &root_ref);
382
+ let mut hits = sink.lock().unwrap();
383
+ for event in events.iter() {
384
+ match event.path().front() {
385
+ Some(&yrs::types::PathSegment::Index(i)) if children.is_block(i) => {
386
+ hits.push(children.ordinal(i))
387
+ }
388
+ Some(_) => {}
389
+ None => root_positions(txn, event, &before, &children, &mut hits),
390
+ }
391
+ }
392
+ });
393
+ let applied = yrs::Update::decode_v1(&bytes)
394
+ .map_err(|e| e.to_string())
395
+ .and_then(|parsed| txn.apply_update(parsed).map_err(|e| e.to_string()));
396
+ // Committing runs the observer.
397
+ drop(txn);
398
+ target.unobserve_deep(key);
399
+ applied?;
400
+ let mut out = hits.lock().unwrap().clone();
401
+ out.sort_unstable();
402
+ out.dedup();
403
+ Ok(out)
404
+ })?
405
+ .map_err(yrb_error)?;
406
+ let ruby = Ruby::get().map_err(|e| yrb_error(e.to_string()))?;
407
+ let array = ruby.ary_new();
408
+ for i in changed {
409
+ array.push(i)?;
410
+ }
411
+ Ok(array)
412
+ }
413
+
414
+ /// The ordinal of the top-level block of the root `XmlText` named `root`
415
+ /// that a relative position (an anchor's, or the `{type, tname, item,
416
+ /// assoc}` hash a peer carries as a caret) falls in, or nil. This is how
417
+ /// a process knows which block a person is writing in.
418
+ fn block_at(&self, position: RHash, root: String) -> Result<Option<u32>, Error> {
419
+ let ruby = Ruby::get().map_err(|e| yrb_error(e.to_string()))?;
420
+ let sticky = sticky_from_ruby(&ruby, position)?;
421
+ let doc = &self.0;
422
+ nogvl(move || {
423
+ let txn = doc.transact();
424
+ let target = sticky.get_offset(&txn)?.branch;
425
+ let root_ref = shared::root_xml_text(&txn, root.as_str())?;
426
+ shared::embedded_xml_texts(&txn, &root_ref)
427
+ .iter()
428
+ .position(|block| contains_branch(&txn, block, target))
429
+ .map(|ordinal| ordinal as u32)
430
+ })
431
+ }
432
+
433
+ /// The block an anchor's position names, as a live handle, or nil once
434
+ /// the block is gone.
435
+ fn find(&self, position: RHash, root: String) -> Result<Option<xml_text::RbXmlText>, Error> {
436
+ let ruby = Ruby::get().map_err(|e| yrb_error(e.to_string()))?;
437
+ let sticky = sticky_from_ruby(&ruby, position)?;
438
+ let (doc, name) = (&self.0, root.as_str());
439
+ let id = nogvl(move || {
440
+ let txn = doc.transact();
441
+ let branch = sticky.get_offset(&txn)?.branch;
442
+ let id = shared::identity(&yrs::XmlTextRef::from(branch));
443
+ let is_block = matches!(id, yrs::branch::BranchID::Root(_))
444
+ || matches!(branch.type_ref(), yrs::types::TypeRef::XmlText);
445
+ let in_root = shared::identity(&yrs::XmlTextRef::from(shared::top(branch)))
446
+ == yrs::branch::BranchID::Root(name.into());
447
+ (is_block && in_root && shared::resolve::<yrs::XmlTextRef, _>(&txn, &id).is_some())
448
+ .then_some(id)
449
+ })?;
450
+ Ok(id.map(|id| xml_text::handle(&self.0, id, root)))
451
+ }
452
+
453
+ /// Every update in `Unsent`, merged into one, or nil for none. Taking them
454
+ /// empties it, and writes made meanwhile wait for the next take. The
455
+ /// merge runs without the GVL. If it fails, or an interrupt comes back
456
+ /// with it (a signal trap can raise even where `Thread.handle_interrupt`
457
+ /// masks), the updates go back ahead of those writes.
458
+ fn take_unsent(&self) -> Result<Option<RString>, Error> {
459
+ let taken = std::mem::take(&mut *lock(&self.1));
460
+ if taken.is_empty() {
461
+ return Ok(None);
462
+ }
463
+ match nogvl(|| merge_unsent(&taken)).and_then(|merged| merged.map_err(yrb_error)) {
464
+ Ok(merged) => Ok(Some(binary_string(&merged))),
465
+ Err(error) => {
466
+ let mut unsent = lock(&self.1);
467
+ let since = std::mem::replace(&mut *unsent, taken);
468
+ unsent.extend(since);
469
+ Err(error)
470
+ }
471
+ }
472
+ }
473
+
474
+ /// Put a taken update back ahead of anything written since, for the next
475
+ /// take to return again.
476
+ fn keep_unsent(&self, update: RString) {
477
+ lock(&self.1).insert(0, copy_bytes(update));
478
+ }
479
+
239
480
  /// Encode state as update (optionally diffed against a state vector)
240
481
  fn encode_state_as_update(&self, args: &[Value]) -> Result<RString, Error> {
241
482
  let sv_bytes: Option<Vec<u8>> = if args.is_empty() {
@@ -252,7 +493,7 @@ impl RbDoc {
252
493
  };
253
494
  let txn = doc.transact();
254
495
  Ok(txn.encode_state_as_update_v1(&sv))
255
- })
496
+ })?
256
497
  .map_err(yrb_error)?;
257
498
  Ok(binary_string(&update))
258
499
  }
@@ -262,9 +503,9 @@ impl RbDoc {
262
503
  let doc = &self.0;
263
504
  nogvl(move || -> Result<(), String> {
264
505
  let update = yrs::Update::decode_v1(&update_bytes).map_err(|e| e.to_string())?;
265
- let mut txn = doc.transact_mut();
506
+ let mut txn = doc.transact_mut_with(shared::REMOTE);
266
507
  txn.apply_update(update).map_err(|e| e.to_string())
267
- })
508
+ })?
268
509
  .map_err(yrb_error)
269
510
  }
270
511
 
@@ -274,7 +515,7 @@ impl RbDoc {
274
515
  fn update_ready(&self, update: RString) -> Result<bool, Error> {
275
516
  let update_bytes = copy_bytes(update);
276
517
  let doc = &self.0;
277
- nogvl(move || update_is_ready(doc, &update_bytes)).map_err(yrb_error)
518
+ nogvl(move || update_is_ready(doc, &update_bytes))?.map_err(yrb_error)
278
519
  }
279
520
 
280
521
  /// True if applying `update` would change the document (it carries new
@@ -283,18 +524,18 @@ impl RbDoc {
283
524
  fn update_advances(&self, update: RString) -> Result<bool, Error> {
284
525
  let update_bytes = copy_bytes(update);
285
526
  let doc = &self.0;
286
- nogvl(move || update_advances_doc(doc, &update_bytes)).map_err(yrb_error)
527
+ nogvl(move || update_advances_doc(doc, &update_bytes))?.map_err(yrb_error)
287
528
  }
288
529
 
289
530
  /// Sync step 1: Create a sync message with our state vector
290
- fn sync_step1(&self) -> RString {
531
+ fn sync_step1(&self) -> Result<RString, Error> {
291
532
  let doc = &self.0;
292
533
  let encoded = nogvl(move || {
293
534
  let txn = doc.transact();
294
535
  let sv = txn.state_vector();
295
536
  Message::Sync(SyncMessage::SyncStep1(sv)).encode_v1()
296
- });
297
- binary_string(&encoded)
537
+ })?;
538
+ Ok(binary_string(&encoded))
298
539
  }
299
540
 
300
541
  /// Handle a Sync or Awareness message, returning
@@ -325,7 +566,7 @@ impl RbDoc {
325
566
  // Apply the update
326
567
  let update =
327
568
  yrs::Update::decode_v1(&update_bytes).map_err(|e| e.to_string())?;
328
- let mut txn = doc.transact_mut();
569
+ let mut txn = doc.transact_mut_with(shared::REMOTE);
329
570
  txn.apply_update(update).map_err(|e| e.to_string())?;
330
571
  Ok((0, 1, Vec::new()))
331
572
  }
@@ -333,7 +574,7 @@ impl RbDoc {
333
574
  // Apply the update
334
575
  let update =
335
576
  yrs::Update::decode_v1(&update_bytes).map_err(|e| e.to_string())?;
336
- let mut txn = doc.transact_mut();
577
+ let mut txn = doc.transact_mut_with(shared::REMOTE);
337
578
  txn.apply_update(update).map_err(|e| e.to_string())?;
338
579
  Ok((0, 2, Vec::new()))
339
580
  }
@@ -343,7 +584,7 @@ impl RbDoc {
343
584
  // protocol; reject rather than pretend to handle them.
344
585
  _ => Err("unsupported message type".to_string()),
345
586
  }
346
- })
587
+ })?
347
588
  .map_err(yrb_error)?;
348
589
 
349
590
  Ok((msg_type, sync_type, binary_string(&response)))
@@ -396,7 +637,7 @@ impl RbLexical {
396
637
  let txn = doc.transact();
397
638
  let fragment = txn.get_xml_fragment(name.as_str())?;
398
639
  lexical_html::render_segments(&txn, &fragment, rules)
399
- });
640
+ })?;
400
641
  segments_result(segments)
401
642
  }
402
643
 
@@ -410,7 +651,7 @@ impl RbLexical {
410
651
  let txn = doc.transact();
411
652
  let fragment = txn.get_xml_fragment(name.as_str())?;
412
653
  lexical_html::collect_node_types(&txn, &fragment)
413
- });
654
+ })?;
414
655
  let ruby = Ruby::get().unwrap();
415
656
  match map {
416
657
  None => Ok(ruby.qnil().as_value()),
@@ -476,7 +717,7 @@ impl RbProseMirror {
476
717
  let txn = doc.transact();
477
718
  let fragment = txn.get_xml_fragment(name.as_str())?;
478
719
  prosemirror_html::render_segments(&txn, &fragment, rules)
479
- });
720
+ })?;
480
721
  segments_result(segments)
481
722
  }
482
723
 
@@ -490,7 +731,7 @@ impl RbProseMirror {
490
731
  let txn = doc.transact();
491
732
  let fragment = txn.get_xml_fragment(name.as_str())?;
492
733
  prosemirror_html::collect_node_types(&txn, &fragment)
493
- });
734
+ })?;
494
735
  let ruby = Ruby::get().unwrap();
495
736
  match map {
496
737
  None => Ok(ruby.qnil().as_value()),
@@ -598,7 +839,7 @@ fn wrap_update(update: RString) -> RString {
598
839
  /// 2 = sync step2/update (a document change: record/apply/relay)
599
840
  /// 3 = awareness (presence: relay)
600
841
  /// 4 = awareness query (a request: respond, do not relay)
601
- fn message_kind(data: RString) -> u8 {
842
+ fn message_kind(data: RString) -> Result<u8, Error> {
602
843
  let data_bytes = copy_bytes(data);
603
844
  nogvl(move || classify_message(&data_bytes))
604
845
  }
@@ -609,7 +850,7 @@ fn message_kind(data: RString) -> u8 {
609
850
  /// awareness update). The store-backed path records this exact delta before relay.
610
851
  fn update_from_message(data: RString) -> Result<Option<RString>, Error> {
611
852
  let data_bytes = copy_bytes(data);
612
- let merged = nogvl(move || merged_doc_update(&data_bytes)).map_err(yrb_error)?;
853
+ let merged = nogvl(move || merged_doc_update(&data_bytes))?.map_err(yrb_error)?;
613
854
  Ok(merged.map(|b| binary_string(&b)))
614
855
  }
615
856
 
@@ -617,6 +858,335 @@ fn update_from_message(data: RString) -> Result<Option<RString>, Error> {
617
858
  // Module Initialization
618
859
  // ============================================================================
619
860
 
861
+ /// A root's children in order: the document index each starts at and
862
+ /// whether it is an `XmlText` block. Ordinals count only those, as
863
+ /// `xml_text(n)` does; a divider or an image is a child but not a block.
864
+ struct Children(Vec<(u32, bool)>);
865
+
866
+ impl Children {
867
+ fn of<T: ReadTxn>(txn: &T, root: &yrs::XmlTextRef) -> Self {
868
+ let mut at = 0;
869
+ let mut children = Vec::new();
870
+ for d in root.diff(txn, yrs::types::text::YChange::identity) {
871
+ let (len, block) = match &d.insert {
872
+ yrs::Out::Any(yrs::Any::String(s)) => (s.encode_utf16().count() as u32, false),
873
+ yrs::Out::YXmlText(_) => (1, true),
874
+ _ => (1, false),
875
+ };
876
+ children.push((at, block));
877
+ at += len;
878
+ }
879
+ Children(children)
880
+ }
881
+
882
+ /// How many blocks come before document index `index`: the ordinal of a
883
+ /// block there.
884
+ fn ordinal(&self, index: u32) -> u32 {
885
+ self.0
886
+ .iter()
887
+ .filter(|(at, block)| *block && *at < index)
888
+ .count() as u32
889
+ }
890
+
891
+ fn is_block(&self, index: u32) -> bool {
892
+ self.0.iter().any(|(at, block)| *block && *at == index)
893
+ }
894
+
895
+ /// How many blocks start in `from..to`.
896
+ fn blocks_in(&self, from: u32, to: u32) -> u32 {
897
+ self.0
898
+ .iter()
899
+ .filter(|(at, block)| *block && (from..to).contains(at))
900
+ .count() as u32
901
+ }
902
+ }
903
+
904
+ /// A presence handle a Ruby process can use to appear as a live collaborator.
905
+ ///
906
+ /// Wraps a yrs `Awareness`. `set_local_state` takes a JSON string (the shape the
907
+ /// editor renders, e.g. `{"name":"Agent","color":"#7c3aed"}`) and returns the
908
+ /// y-protocol awareness frame to broadcast. Browsers subscribed to the document
909
+ /// apply it as another participant. `clear_local_state` returns the frame that
910
+ /// removes this presence. The bytes are the same wire format Yjs and
911
+ /// y-protocols use, so no client change is needed.
912
+ #[magnus::wrap(class = "Y::Awareness", free_immediately, size)]
913
+ struct RbAwareness(RefCell<Awareness>);
914
+
915
+ impl RbAwareness {
916
+ fn new(args: &[Value]) -> Result<Self, Error> {
917
+ let doc = if args.is_empty() || args[0].is_nil() {
918
+ Doc::new()
919
+ } else {
920
+ let client_id: u64 = TryConvert::try_convert(args[0])?;
921
+ Doc::with_client_id(client_id)
922
+ };
923
+ Ok(RbAwareness(RefCell::new(Awareness::new(doc))))
924
+ }
925
+
926
+ /// This presence's client id, stable for the life of the handle.
927
+ fn client_id(&self) -> u64 {
928
+ self.0.borrow().client_id().get()
929
+ }
930
+
931
+ /// Set this client's presence from a JSON string and return the awareness
932
+ /// frame to broadcast.
933
+ fn set_local_state(&self, json: String) -> Result<RString, Error> {
934
+ let value: serde_json::Value = serde_json::from_str(&json)
935
+ .map_err(|e| yrb_error(format!("Y::Awareness state must be JSON: {e}")))?;
936
+ let mut awareness = self.0.borrow_mut();
937
+ awareness
938
+ .set_local_state(value)
939
+ .map_err(|e| yrb_error(e.to_string()))?;
940
+ Self::frame(&awareness)
941
+ }
942
+
943
+ /// Remove this client's presence and return the frame that tells peers to
944
+ /// drop it: an entry with the next clock and a null state, as y-protocols
945
+ /// encodes a removal. yrs's own clean just forgets the client, and a
946
+ /// frame built from that says nothing, so peers would wait for a timeout.
947
+ fn clear_local_state(&self) -> Result<RString, Error> {
948
+ let mut awareness = self.0.borrow_mut();
949
+ let id = awareness.client_id();
950
+ let clock = awareness
951
+ .iter()
952
+ .find(|(client, _)| *client == id)
953
+ .map(|(_, state)| state.clock)
954
+ .unwrap_or(0);
955
+ awareness.clean_local_state();
956
+ let mut clients = std::collections::HashMap::new();
957
+ clients.insert(
958
+ id,
959
+ yrs::sync::awareness::AwarenessUpdateEntry {
960
+ clock: clock + 1,
961
+ json: "null".into(),
962
+ },
963
+ );
964
+ let update = yrs::sync::awareness::AwarenessUpdate { clients };
965
+ Ok(binary_string(&Message::Awareness(update).encode_v1()))
966
+ }
967
+
968
+ /// Apply a presence frame from another client (the bytes a browser or
969
+ /// another process broadcast). Returns false for a frame that is not an
970
+ /// awareness message.
971
+ fn apply_update(&self, frame: RString) -> Result<bool, Error> {
972
+ let bytes = copy_bytes(frame);
973
+ let message = Message::decode_v1(&bytes).map_err(|e| yrb_error(e.to_string()))?;
974
+ match message {
975
+ Message::Awareness(update) => {
976
+ self.0
977
+ .borrow_mut()
978
+ .apply_update(update)
979
+ .map_err(|e| yrb_error(e.to_string()))?;
980
+ Ok(true)
981
+ }
982
+ _ => Ok(false),
983
+ }
984
+ }
985
+
986
+ /// Every client's state, as `{ client_id => state }`, the state being the
987
+ /// JSON each client set (parsed), or nil for a client that cleared it.
988
+ /// Each client's awareness clock. A client renews its state every few
989
+ /// seconds with a higher clock, so a clock that stops moving means the
990
+ /// client is gone without having said so. A mirror uses this to time
991
+ /// peers out the way browser clients do.
992
+ fn clocks(&self) -> Result<RHash, Error> {
993
+ let awareness = self.0.borrow();
994
+ let ruby = Ruby::get().map_err(|e| yrb_error(e.to_string()))?;
995
+ let out = ruby.hash_new();
996
+ for (client, state) in awareness.iter() {
997
+ out.aset(client.get(), state.clock)?;
998
+ }
999
+ Ok(out)
1000
+ }
1001
+
1002
+ fn states(&self) -> Result<RHash, Error> {
1003
+ let ruby = Ruby::get().map_err(|e| yrb_error(e.to_string()))?;
1004
+ let entries: Vec<(u64, Option<String>)> = self
1005
+ .0
1006
+ .borrow()
1007
+ .iter()
1008
+ .map(|(id, state)| (id.get(), state.data.as_ref().map(|d| d.to_string())))
1009
+ .collect();
1010
+ let out = ruby.hash_new();
1011
+ for (id, data) in entries {
1012
+ let value: Value = match data {
1013
+ Some(json) => {
1014
+ let parsed: serde_json::Value = serde_json::from_str(&json)
1015
+ .map_err(|e| yrb_error(format!("presence state is not JSON: {e}")))?;
1016
+ json_to_ruby(&ruby, &parsed)
1017
+ }
1018
+ None => ruby.qnil().as_value(),
1019
+ };
1020
+ out.aset(id, value)?;
1021
+ }
1022
+ Ok(out)
1023
+ }
1024
+
1025
+ fn frame(awareness: &Awareness) -> Result<RString, Error> {
1026
+ let update = awareness.update().map_err(|e| yrb_error(e.to_string()))?;
1027
+ Ok(binary_string(&Message::Awareness(update).encode_v1()))
1028
+ }
1029
+ }
1030
+
1031
+ /// For an event on the root sequence itself (blocks added or removed), the
1032
+ /// ordinals affected. A delta walks the root as it was (`before`): retained
1033
+ /// and removed children advance through it, inserted ones through the root
1034
+ /// as it is now (`after`). An added block reports its new ordinal, a removed
1035
+ /// one the ordinal it had, and a divider or image reports nothing.
1036
+ fn root_positions(
1037
+ txn: &yrs::TransactionMut,
1038
+ event: &yrs::types::Event,
1039
+ before: &Children,
1040
+ after: &Children,
1041
+ hits: &mut Vec<u32>,
1042
+ ) {
1043
+ use yrs::types::{Change, Delta, Event};
1044
+ let (mut old, mut new) = (0u32, 0u32);
1045
+ let added = |item: &yrs::Out, new: &mut u32, hits: &mut Vec<u32>| {
1046
+ if matches!(item, yrs::Out::YXmlText(_)) {
1047
+ hits.push(after.ordinal(*new));
1048
+ }
1049
+ *new += match item {
1050
+ yrs::Out::Any(yrs::Any::String(s)) => s.encode_utf16().count() as u32,
1051
+ _ => 1,
1052
+ };
1053
+ };
1054
+ let removed = |old: u32, n: u32, hits: &mut Vec<u32>| {
1055
+ let first = before.ordinal(old);
1056
+ hits.extend(first..first + before.blocks_in(old, old + n));
1057
+ };
1058
+ match event {
1059
+ Event::XmlFragment(e) => {
1060
+ for change in e.delta(txn) {
1061
+ match change {
1062
+ Change::Retain(n) => (old, new) = (old + n, new + n),
1063
+ Change::Added(items) => {
1064
+ for item in items {
1065
+ added(item, &mut new, hits);
1066
+ }
1067
+ }
1068
+ Change::Removed(n) => {
1069
+ removed(old, *n, hits);
1070
+ old += n;
1071
+ }
1072
+ }
1073
+ }
1074
+ }
1075
+ Event::XmlText(e) => {
1076
+ for delta in e.delta(txn) {
1077
+ match delta {
1078
+ Delta::Retain(n, _) => (old, new) = (old + n, new + n),
1079
+ Delta::Inserted(item, _) => added(item, &mut new, hits),
1080
+ Delta::Deleted(n) => {
1081
+ removed(old, *n, hits);
1082
+ old += n;
1083
+ }
1084
+ }
1085
+ }
1086
+ }
1087
+ _ => {}
1088
+ }
1089
+ }
1090
+
1091
+ /// Whether `branch` is `block` itself or embedded anywhere inside it.
1092
+ fn contains_branch<T: ReadTxn>(
1093
+ txn: &T,
1094
+ block: &yrs::XmlTextRef,
1095
+ branch: yrs::branch::BranchPtr,
1096
+ ) -> bool {
1097
+ let this: &yrs::branch::Branch = block.as_ref();
1098
+ if yrs::branch::BranchPtr::from(this) == branch {
1099
+ return true;
1100
+ }
1101
+ for d in block.diff(txn, yrs::types::text::YChange::identity) {
1102
+ if let yrs::Out::YXmlText(child) = &d.insert {
1103
+ if contains_branch(txn, child, branch) {
1104
+ return true;
1105
+ }
1106
+ }
1107
+ }
1108
+ false
1109
+ }
1110
+
1111
+ fn hash_get(ruby: &Ruby, h: RHash, key: &str) -> Option<Value> {
1112
+ h.get(ruby.to_symbol(key))
1113
+ .or_else(|| h.get(key))
1114
+ .filter(|v| !v.is_nil())
1115
+ }
1116
+
1117
+ /// A yrs sticky index from the `{type, tname, item, assoc}` hash Yjs uses.
1118
+ fn sticky_from_ruby(ruby: &Ruby, position: RHash) -> Result<yrs::StickyIndex, Error> {
1119
+ use yrs::{Assoc, IndexScope, StickyIndex};
1120
+ let assoc = match hash_get(ruby, position, "assoc") {
1121
+ Some(v) => {
1122
+ let n: i64 = TryConvert::try_convert(v)?;
1123
+ if n < 0 {
1124
+ Assoc::Before
1125
+ } else {
1126
+ Assoc::After
1127
+ }
1128
+ }
1129
+ None => Assoc::After,
1130
+ };
1131
+ let id_of = |key: &str| -> Result<Option<yrs::block::ID>, Error> {
1132
+ let Some(v) = hash_get(ruby, position, key) else {
1133
+ return Ok(None);
1134
+ };
1135
+ let h = RHash::from_value(v).ok_or_else(|| yrb_error(format!("{key} must be a hash")))?;
1136
+ let client: u64 = TryConvert::try_convert(
1137
+ hash_get(ruby, h, "client").ok_or_else(|| yrb_error("missing client".into()))?,
1138
+ )?;
1139
+ let clock: u32 = TryConvert::try_convert(
1140
+ hash_get(ruby, h, "clock").ok_or_else(|| yrb_error("missing clock".into()))?,
1141
+ )?;
1142
+ Ok(Some(yrs::block::ID::new(
1143
+ yrs::block::ClientID::new(client),
1144
+ clock,
1145
+ )))
1146
+ };
1147
+ if let Some(item) = id_of("item")? {
1148
+ return Ok(StickyIndex::from_id(item, assoc));
1149
+ }
1150
+ if let Some(ty) = id_of("type")? {
1151
+ return Ok(StickyIndex::new(IndexScope::Nested(ty), assoc));
1152
+ }
1153
+ match hash_get(ruby, position, "tname") {
1154
+ Some(v) => {
1155
+ let name: String = TryConvert::try_convert(v)?;
1156
+ Ok(StickyIndex::new(IndexScope::Root(name.into()), assoc))
1157
+ }
1158
+ None => Err(yrb_error("a position needs item, type, or tname".into())),
1159
+ }
1160
+ }
1161
+
1162
+ /// serde_json to Ruby, for presence states.
1163
+ fn json_to_ruby(ruby: &Ruby, v: &serde_json::Value) -> Value {
1164
+ match v {
1165
+ serde_json::Value::Null => ruby.qnil().as_value(),
1166
+ serde_json::Value::Bool(b) => b.into_value_with(ruby),
1167
+ serde_json::Value::Number(n) => match (n.as_i64(), n.as_u64()) {
1168
+ (Some(i), _) => i.into_value_with(ruby),
1169
+ (None, Some(u)) => u.into_value_with(ruby),
1170
+ _ => n.as_f64().unwrap_or(0.0).into_value_with(ruby),
1171
+ },
1172
+ serde_json::Value::String(s) => s.as_str().into_value_with(ruby),
1173
+ serde_json::Value::Array(a) => {
1174
+ let arr = ruby.ary_new();
1175
+ for x in a {
1176
+ let _ = arr.push(json_to_ruby(ruby, x));
1177
+ }
1178
+ arr.as_value()
1179
+ }
1180
+ serde_json::Value::Object(o) => {
1181
+ let h = ruby.hash_new();
1182
+ for (k, x) in o {
1183
+ let _ = h.aset(k.as_str(), json_to_ruby(ruby, x));
1184
+ }
1185
+ h.as_value()
1186
+ }
1187
+ }
1188
+ }
1189
+
620
1190
  #[magnus::init]
621
1191
  fn init(ruby: &Ruby) -> Result<(), Error> {
622
1192
  let module = ruby.define_module("Y")?;
@@ -637,6 +1207,15 @@ fn init(ruby: &Ruby) -> Result<(), Error> {
637
1207
  method!(RbDoc::encode_state_as_update, -1),
638
1208
  )?;
639
1209
  doc_class.define_method("apply_update", method!(RbDoc::apply_update, 1))?;
1210
+ doc_class.define_method("client_id", method!(RbDoc::client_id, 0))?;
1211
+ doc_class.define_method(
1212
+ "apply_update_changes",
1213
+ method!(RbDoc::apply_update_changes, 2),
1214
+ )?;
1215
+ doc_class.define_private_method("native_block_at", method!(RbDoc::block_at, 2))?;
1216
+ doc_class.define_private_method("native_find", method!(RbDoc::find, 2))?;
1217
+ doc_class.define_private_method("native_take_unsent", method!(RbDoc::take_unsent, 0))?;
1218
+ doc_class.define_private_method("native_keep_unsent", method!(RbDoc::keep_unsent, 1))?;
640
1219
  doc_class.define_method("root_names", method!(RbDoc::root_names, 0))?;
641
1220
  doc_class.define_method("read_text", method!(RbDoc::read_text, 1))?;
642
1221
  doc_class.define_method("read_xml", method!(RbDoc::read_xml, 1))?;
@@ -647,6 +1226,10 @@ fn init(ruby: &Ruby) -> Result<(), Error> {
647
1226
  "compacted_state_update",
648
1227
  method!(RbDoc::compacted_state_update, 0),
649
1228
  )?;
1229
+ doc_class.define_method("get_map", method!(RbDoc::get_map, 1))?;
1230
+ doc_class.define_method("get_array", method!(RbDoc::get_array, 1))?;
1231
+ doc_class.define_method("get_text", method!(RbDoc::get_text, 1))?;
1232
+ doc_class.define_method("get_xml_text", method!(RbDoc::get_xml_text, 1))?;
650
1233
  doc_class.define_method("update_ready?", method!(RbDoc::update_ready, 1))?;
651
1234
  doc_class.define_method("update_advances?", method!(RbDoc::update_advances, 1))?;
652
1235
  doc_class.define_method("sync_step1", method!(RbDoc::sync_step1, 0))?;
@@ -666,6 +1249,24 @@ fn init(ruby: &Ruby) -> Result<(), Error> {
666
1249
  prosemirror_class.define_method("to_html", method!(RbProseMirror::native_to_html, -1))?;
667
1250
  prosemirror_class.define_method("node_types", method!(RbProseMirror::node_types, -1))?;
668
1251
 
1252
+ let awareness_class = module.define_class("Awareness", ruby.class_object())?;
1253
+ awareness_class.define_singleton_method("new", function!(RbAwareness::new, -1))?;
1254
+ awareness_class.define_method("client_id", method!(RbAwareness::client_id, 0))?;
1255
+ awareness_class.define_method("set_local_state", method!(RbAwareness::set_local_state, 1))?;
1256
+ awareness_class.define_method(
1257
+ "clear_local_state",
1258
+ method!(RbAwareness::clear_local_state, 0),
1259
+ )?;
1260
+ awareness_class.define_method("apply_update", method!(RbAwareness::apply_update, 1))?;
1261
+ awareness_class.define_method("states", method!(RbAwareness::states, 0))?;
1262
+ awareness_class.define_method("clocks", method!(RbAwareness::clocks, 0))?;
1263
+
1264
+ // Live shared-type handles.
1265
+ map::define(ruby, module)?;
1266
+ array::define(ruby, module)?;
1267
+ text::define(ruby, module)?;
1268
+ xml_text::define(ruby, module)?;
1269
+
669
1270
  // Stateless protocol codec, as Y module functions.
670
1271
  module.define_module_function("wrap_update", function!(wrap_update, 1))?;
671
1272
  module.define_module_function("message_kind", function!(message_kind, 1))?;
@@ -680,3 +1281,358 @@ fn init(ruby: &Ruby) -> Result<(), Error> {
680
1281
 
681
1282
  Ok(())
682
1283
  }
1284
+
1285
+ #[cfg(test)]
1286
+ mod tests {
1287
+ //! Each method on `Y::Doc`, `Y::Doc::Recording`, `Y::Awareness`, and the
1288
+ //! two renderers, called as Ruby calls it. The handles' methods belong to
1289
+ //! their own modules, so these tests write through yrs, under the
1290
+ //! handles' origin where that matters.
1291
+ use super::*;
1292
+ use crate::shared::test_support::rb;
1293
+ use rb_sys_test_helpers::ruby_test;
1294
+ use yrs::{Any, MapPrelim, Text, Xml, XmlTextPrelim, XmlTextRef};
1295
+
1296
+ fn new_doc() -> RbDoc {
1297
+ RbDoc::new(&[]).unwrap()
1298
+ }
1299
+
1300
+ /// Append to the root text `name` as a handle does: under its origin.
1301
+ fn push(doc: &RbDoc, name: &str, chunk: &str) {
1302
+ let text = doc.0.get_or_insert_text(name);
1303
+ let mut txn = doc.0.transact_mut_with(shared::ORIGIN);
1304
+ let at = text.len(&txn);
1305
+ text.insert(&mut txn, at, chunk);
1306
+ }
1307
+
1308
+ fn update(doc: &RbDoc) -> RString {
1309
+ doc.encode_state_as_update(&[]).unwrap()
1310
+ }
1311
+
1312
+ fn update_since(doc: &RbDoc, state_vector: RString) -> RString {
1313
+ doc.encode_state_as_update(&[state_vector.as_value()])
1314
+ .unwrap()
1315
+ }
1316
+
1317
+ fn root(doc: &RbDoc) -> XmlTextRef {
1318
+ doc.0.get_or_insert_xml_fragment("root");
1319
+ shared::root_xml_text(&doc.0.transact(), "root").unwrap()
1320
+ }
1321
+
1322
+ /// Add a Lexical paragraph to `root` before its `at`-th child.
1323
+ fn paragraph(doc: &RbDoc, at: u32, words: &str) {
1324
+ let root = root(doc);
1325
+ let mut txn = doc.0.transact_mut();
1326
+ let block = root.insert_embed(&mut txn, at, XmlTextPrelim::new(""));
1327
+ block.insert_attribute(&mut txn, "__type", "paragraph");
1328
+ let node = MapPrelim::from_iter([
1329
+ ("__type", Any::from("text")),
1330
+ ("__format", Any::from(0)),
1331
+ ("__style", Any::from("")),
1332
+ ("__mode", Any::from(0)),
1333
+ ("__detail", Any::from(0)),
1334
+ ]);
1335
+ block.insert_embed(&mut txn, 0, node);
1336
+ block.insert(&mut txn, 1, words);
1337
+ }
1338
+
1339
+ fn lexical_doc(paragraphs: &[&str]) -> RbDoc {
1340
+ let doc = new_doc();
1341
+ for (n, words) in paragraphs.iter().enumerate() {
1342
+ paragraph(&doc, n as u32, words);
1343
+ }
1344
+ doc
1345
+ }
1346
+
1347
+ fn remove_child(doc: &RbDoc, at: u32) {
1348
+ root(doc).remove_range(&mut doc.0.transact_mut(), at, 1);
1349
+ }
1350
+
1351
+ #[ruby_test]
1352
+ fn a_doc_writes_under_the_client_id_it_was_given() {
1353
+ let doc = RbDoc::new(&[rb(42_u64)]).unwrap();
1354
+ assert_eq!(doc.client_id(), 42);
1355
+ assert_ne!(new_doc().client_id(), new_doc().client_id());
1356
+ }
1357
+
1358
+ #[ruby_test]
1359
+ fn an_update_carries_state_from_one_doc_to_another() {
1360
+ let doc = new_doc();
1361
+ push(&doc, "t", "hello");
1362
+ let peer = new_doc();
1363
+ peer.apply_update(update(&doc)).unwrap();
1364
+ assert_eq!(
1365
+ peer.read_text("t".into()).unwrap().as_deref(),
1366
+ Some("hello")
1367
+ );
1368
+ assert_eq!(
1369
+ copy_bytes(peer.encode_state_vector().unwrap()),
1370
+ copy_bytes(doc.encode_state_vector().unwrap())
1371
+ );
1372
+ }
1373
+
1374
+ #[ruby_test]
1375
+ fn an_update_since_a_state_vector_holds_only_what_is_new() {
1376
+ let doc = new_doc();
1377
+ push(&doc, "t", "one");
1378
+ let peer = new_doc();
1379
+ peer.apply_update(update(&doc)).unwrap();
1380
+ push(&doc, "t", " two");
1381
+ let diff = update_since(&doc, peer.encode_state_vector().unwrap());
1382
+ let fresh = new_doc();
1383
+ fresh.apply_update(diff).unwrap();
1384
+ assert!(
1385
+ fresh.pending().unwrap(),
1386
+ "the diff leaves out the first write"
1387
+ );
1388
+ peer.apply_update(diff).unwrap();
1389
+ assert_eq!(
1390
+ peer.read_text("t".into()).unwrap().as_deref(),
1391
+ Some("one two")
1392
+ );
1393
+ }
1394
+
1395
+ fn take(doc: &RbDoc) -> Option<RString> {
1396
+ doc.take_unsent().unwrap()
1397
+ }
1398
+
1399
+ #[ruby_test]
1400
+ fn local_writes_wait_to_be_taken_and_a_peers_never_do() {
1401
+ let doc = new_doc();
1402
+ push(&doc, "t", "mine");
1403
+ let mine = take(&doc).expect("a local write waits");
1404
+ assert!(take(&doc).is_none(), "taking empties it");
1405
+
1406
+ let peer = new_doc();
1407
+ peer.apply_update(mine).unwrap();
1408
+ peer.handle_sync_message(wrap_update(mine)).unwrap();
1409
+ peer.apply_update_changes(mine, "root".into()).unwrap();
1410
+ assert!(take(&peer).is_none(), "applied updates are a peer's");
1411
+ assert_eq!(peer.read_text("t".into()).unwrap().as_deref(), Some("mine"));
1412
+ }
1413
+
1414
+ #[ruby_test]
1415
+ fn unsent_updates_merge_into_one_that_carries_them_all() {
1416
+ let doc = new_doc();
1417
+ for n in 0..300 {
1418
+ push(&doc, "t", &n.to_string());
1419
+ }
1420
+ let fresh = new_doc();
1421
+ fresh.apply_update(take(&doc).unwrap()).unwrap();
1422
+ assert_eq!(
1423
+ fresh.read_text("t".into()).unwrap(),
1424
+ doc.read_text("t".into()).unwrap()
1425
+ );
1426
+ assert!(!fresh.pending().unwrap());
1427
+ }
1428
+
1429
+ #[ruby_test]
1430
+ fn a_kept_update_is_taken_again_with_what_came_after() {
1431
+ let doc = new_doc();
1432
+ push(&doc, "t", "inner");
1433
+ doc.keep_unsent(take(&doc).unwrap());
1434
+ push(&doc, "t", " outer");
1435
+ let fresh = new_doc();
1436
+ fresh.apply_update(take(&doc).unwrap()).unwrap();
1437
+ assert_eq!(
1438
+ fresh.read_text("t".into()).unwrap().as_deref(),
1439
+ Some("inner outer")
1440
+ );
1441
+ }
1442
+
1443
+ #[ruby_test]
1444
+ fn unsent_updates_stay_when_the_merge_fails() {
1445
+ let doc = new_doc();
1446
+ push(&doc, "t", "kept");
1447
+ doc.1.lock().unwrap().push(vec![255]);
1448
+ assert!(doc.take_unsent().is_err());
1449
+ doc.1.lock().unwrap().pop();
1450
+ let fresh = new_doc();
1451
+ fresh.apply_update(take(&doc).unwrap()).unwrap();
1452
+ assert_eq!(
1453
+ fresh.read_text("t".into()).unwrap().as_deref(),
1454
+ Some("kept")
1455
+ );
1456
+ }
1457
+
1458
+ #[ruby_test]
1459
+ fn a_malformed_update_raises() {
1460
+ assert!(new_doc()
1461
+ .apply_update(binary_string(&[0xff, 0xff]))
1462
+ .is_err());
1463
+ }
1464
+
1465
+ #[ruby_test]
1466
+ fn reads_return_each_kind_of_root_and_nil_for_a_missing_one() {
1467
+ let doc = lexical_doc(&["one", "two"]);
1468
+ push(&doc, "t", "hi");
1469
+ doc.0.get_or_insert_map("m");
1470
+ let mut names = doc.root_names().unwrap();
1471
+ names.sort();
1472
+ assert_eq!(names, vec!["m", "root", "t"]);
1473
+ assert_eq!(doc.read_text("t".into()).unwrap().as_deref(), Some("hi"));
1474
+ assert_eq!(doc.read_map("m".into()).unwrap().as_deref(), Some("{}"));
1475
+ assert_eq!(
1476
+ doc.read_xml("root".into()).unwrap().as_deref(),
1477
+ Some("one\ntwo")
1478
+ );
1479
+ assert_eq!(doc.read_array("missing".into()).unwrap(), None);
1480
+ }
1481
+
1482
+ #[ruby_test]
1483
+ fn an_update_missing_its_dependency_is_pending_until_it_arrives() {
1484
+ let source = new_doc();
1485
+ push(&source, "t", "a");
1486
+ let first = update(&source);
1487
+ let after_first = source.encode_state_vector().unwrap();
1488
+ push(&source, "t", "b");
1489
+ let second = update_since(&source, after_first);
1490
+
1491
+ let doc = new_doc();
1492
+ assert!(!doc.update_ready(second).unwrap());
1493
+ assert!(doc.update_advances(second).unwrap());
1494
+ doc.apply_update(second).unwrap();
1495
+ assert!(doc.pending().unwrap());
1496
+ assert_eq!(doc.read_text("t".into()).unwrap(), None);
1497
+ let compacted = copy_bytes(doc.compacted_state_update().unwrap());
1498
+ assert!(compacted.len() < copy_bytes(update(&doc)).len());
1499
+
1500
+ doc.apply_update(first).unwrap();
1501
+ assert!(!doc.pending().unwrap());
1502
+ assert_eq!(doc.read_text("t".into()).unwrap().as_deref(), Some("ab"));
1503
+ assert!(!doc.update_advances(second).unwrap());
1504
+ }
1505
+
1506
+ #[ruby_test]
1507
+ fn a_sync_step1_answered_by_a_peer_brings_the_doc_up_to_date() {
1508
+ let doc = new_doc();
1509
+ push(&doc, "t", "hello");
1510
+ let peer = new_doc();
1511
+ let (kind, step, reply) = doc.handle_sync_message(peer.sync_step1().unwrap()).unwrap();
1512
+ assert_eq!((kind, step), (0, 0));
1513
+ let (kind, step, nothing) = peer.handle_sync_message(reply).unwrap();
1514
+ assert_eq!((kind, step), (0, 1));
1515
+ assert!(copy_bytes(nothing).is_empty());
1516
+ assert_eq!(
1517
+ peer.read_text("t".into()).unwrap().as_deref(),
1518
+ Some("hello")
1519
+ );
1520
+ }
1521
+
1522
+ #[ruby_test]
1523
+ fn handle_sync_message_applies_an_update_and_rejects_garbage() {
1524
+ let doc = new_doc();
1525
+ push(&doc, "t", "hi");
1526
+ let peer = new_doc();
1527
+ assert_eq!(
1528
+ peer.handle_sync_message(wrap_update(update(&doc)))
1529
+ .unwrap()
1530
+ .1,
1531
+ 2
1532
+ );
1533
+ assert_eq!(peer.read_text("t".into()).unwrap().as_deref(), Some("hi"));
1534
+ assert!(peer.handle_sync_message(binary_string(&[9, 9])).is_err());
1535
+ }
1536
+
1537
+ #[ruby_test]
1538
+ fn apply_update_changes_reports_the_blocks_an_update_touched() {
1539
+ let doc = lexical_doc(&["one", "two", "three"]);
1540
+ let peer = new_doc();
1541
+ peer.apply_update(update(&doc)).unwrap();
1542
+ let before = peer.encode_state_vector().unwrap();
1543
+ paragraph(&peer, 1, "new");
1544
+ remove_child(&peer, 3);
1545
+ let changed = doc
1546
+ .apply_update_changes(update_since(&peer, before), "root".into())
1547
+ .unwrap();
1548
+ assert_eq!(changed.as_value().inspect(), "[1, 2]");
1549
+ assert_eq!(
1550
+ doc.read_xml("root".into()).unwrap().as_deref(),
1551
+ Some("one\nnew\ntwo")
1552
+ );
1553
+ }
1554
+
1555
+ #[ruby_test]
1556
+ fn a_block_position_finds_its_block_as_others_come_and_go() {
1557
+ let doc = lexical_doc(&["one", "two"]);
1558
+ let ruby = Ruby::get().unwrap();
1559
+ let root = root(&doc);
1560
+ let position = {
1561
+ let txn = doc.0.transact();
1562
+ let blocks = shared::embedded_xml_texts(&txn, &root);
1563
+ let sticky = yrs::StickyIndex::from_type(&txn, &blocks[1], yrs::Assoc::After);
1564
+ shared::Position::new(sticky).to_ruby(&ruby).unwrap()
1565
+ };
1566
+ paragraph(&doc, 0, "zero");
1567
+ assert_eq!(doc.block_at(position, "root".into()).unwrap(), Some(2));
1568
+ let found = doc.find(position, "root".into()).unwrap();
1569
+ assert!(found.is_some());
1570
+ assert!(doc.find(position, "elsewhere".into()).unwrap().is_none());
1571
+ remove_child(&doc, 2);
1572
+ assert!(doc.find(position, "root".into()).unwrap().is_none());
1573
+ }
1574
+
1575
+ #[ruby_test]
1576
+ fn children_count_blocks_but_not_other_embeds() {
1577
+ let doc = lexical_doc(&["one"]);
1578
+ root(&doc).insert_embed(&mut doc.0.transact_mut(), 0, Any::from(true));
1579
+ paragraph(&doc, 2, "two");
1580
+ let root = root(&doc);
1581
+ let txn = doc.0.transact();
1582
+ let children = Children::of(&txn, &root);
1583
+ assert!(!children.is_block(0));
1584
+ assert!(children.is_block(1));
1585
+ assert_eq!(children.ordinal(2), 1);
1586
+ assert_eq!(children.blocks_in(0, 3), 2);
1587
+ }
1588
+
1589
+ #[ruby_test]
1590
+ fn awareness_frames_carry_presence_between_clients() {
1591
+ let agent = RbAwareness::new(&[rb(7_u64)]).unwrap();
1592
+ let browser = RbAwareness::new(&[]).unwrap();
1593
+ assert_eq!(agent.client_id(), 7);
1594
+ let frame = agent.set_local_state(r#"{"name":"Agent"}"#.into()).unwrap();
1595
+ assert!(browser.apply_update(frame).unwrap());
1596
+ let states = browser.states().unwrap().as_value().inspect();
1597
+ assert!(states.contains(r#"7 => {"name" => "Agent"}"#), "{states}");
1598
+ assert!(!browser.clocks().unwrap().is_empty());
1599
+
1600
+ assert!(browser
1601
+ .apply_update(agent.clear_local_state().unwrap())
1602
+ .unwrap());
1603
+ let states = browser.states().unwrap().as_value().inspect();
1604
+ assert!(!states.contains("Agent"), "{states}");
1605
+ }
1606
+
1607
+ #[ruby_test]
1608
+ fn awareness_refuses_a_state_that_is_not_json_and_ignores_other_frames() {
1609
+ let awareness = RbAwareness::new(&[]).unwrap();
1610
+ assert!(awareness.set_local_state("{nope".into()).is_err());
1611
+ assert!(!awareness
1612
+ .apply_update(new_doc().sync_step1().unwrap())
1613
+ .unwrap());
1614
+ }
1615
+
1616
+ #[ruby_test]
1617
+ fn the_lexical_renderer_renders_a_lexical_doc_and_skips_a_missing_root() {
1618
+ let doc = lexical_doc(&["hello"]);
1619
+ let lexical = RbLexical::native_new(&doc, "{}".into()).unwrap();
1620
+ assert_eq!(
1621
+ lexical.native_to_html(&[]).unwrap().inspect(),
1622
+ r#""<p>hello</p>""#
1623
+ );
1624
+ let types = lexical.node_types(&[]).unwrap().inspect();
1625
+ assert!(types.contains("paragraph"), "{types}");
1626
+ assert!(lexical.native_to_html(&[rb("missing")]).unwrap().is_nil());
1627
+ assert!(lexical.native_to_html(&[rb("a"), rb("b")]).is_err());
1628
+ }
1629
+
1630
+ #[ruby_test]
1631
+ fn the_prosemirror_renderer_skips_a_missing_root_and_refuses_bad_rules() {
1632
+ let doc = new_doc();
1633
+ let prosemirror = RbProseMirror::native_new(&doc, "{}".into()).unwrap();
1634
+ assert!(prosemirror.native_to_html(&[]).unwrap().is_nil());
1635
+ assert!(prosemirror.node_types(&[]).unwrap().is_nil());
1636
+ assert!(RbProseMirror::native_new(&doc, "not json".into()).is_err());
1637
+ }
1638
+ }