canvist_collab 0.2.1

Yjs collaboration for canvist documents: a step-to-yrs binding, the y-sync protocol, awareness, and shared undo
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
//! Structural changes: array deltas become block removals, moves, and
//! insertions.
//!
//! Each array delta is turned into removed blocks plus inserted maps, each
//! anchored after the item that precedes it in the final array. Anchors
//! instead of indices let the changes apply in any order: moves out of
//! removed containers first, then removals, then insertions, each placed
//! after its nearest anchor already in the model.
//!
//! A removed block reinserted in the same transaction with identical content
//! is a move (Yjs has no move, so peers move blocks by deleting and copying
//! them), and is applied as `MoveBlocks` so carets inside it survive.

use canvist_model::BlockId;
use canvist_model::BlockTree;
use canvist_model::Document;
use canvist_model::Step;
use rustc_hash::FxHashMap;
use rustc_hash::FxHashSet;
use yrs::Array;
use yrs::ID;
use yrs::Out;
use yrs::ReadTxn;

use super::Remote;
use super::Repair;
use super::descendants;
use super::record::ArrayOp;
use crate::CollabError;
use crate::claims::Claim;
use crate::claims::Owners;
use crate::local::map_ref;
use crate::local::subtree_ids;
use crate::registry::Owner;
use crate::registry::Registration;
use crate::registry::Registry;
use crate::registry::branch_id;
use crate::tree::Parent;
use crate::tree::Reader;

/// What the array deltas of one transaction do.
#[derive(Debug, Default)]
pub(crate) struct Plan {
	/// Shown blocks whose maps were deleted, in delta order.
	removed: Vec<BlockId>,
	/// Inserted maps, in delta order.
	inserts: Vec<Insert>,
}

/// One inserted block map.
#[derive(Clone, Copy, Debug)]
struct Insert {
	parent: Option<BlockId>,
	map: ID,
	anchor: Anchor,
}

/// The item an inserted map follows in its final array.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Anchor {
	/// The start of the array.
	Start,
	/// The block map with this item id.
	After(ID),
}

/// Whose children an array holds.
#[derive(Clone, Copy, Debug)]
enum Holder {
	/// The root array.
	Root,
	/// The child array of a shown container.
	Block(BlockId),
}

impl Holder {
	fn parent(self) -> Option<BlockId> {
		match self {
			Self::Root => None,
			Self::Block(block) => Some(block),
		}
	}
}

/// What one item of an array walk is.
enum Item {
	/// A block map inserted in this transaction.
	Inserted(ID),
	/// The map of a shown block.
	Shown(BlockId, ID),
	/// Anything the model does not show.
	Unmirrored,
}

/// An inserted map, read.
struct Read {
	insert: Insert,
	tree: Option<BlockTree>,
	registration: Registration,
}

/// Consecutive insertions into one parent, applied as one step.
#[derive(Default)]
struct Batch {
	parent: Option<BlockId>,
	index: usize,
	last: Option<ID>,
	trees: Vec<BlockTree>,
	registrations: Vec<Registration>,
}

/// How incoming maps that carry the same block id are told apart.
pub(crate) enum Incoming<'a> {
	/// Scanned: the map with the smallest item id wins.
	Scanned(&'a Owners),
	/// Not scanned: ids are assumed unique, and a repeat is only noted so
	/// the caller can scan and read again.
	Unique {
		seen: FxHashSet<BlockId>,
		repeated: bool,
	},
}

impl Incoming<'_> {
	pub(crate) fn unique() -> Self {
		Self::Unique {
			seen: FxHashSet::default(),
			repeated: false,
		}
	}

	/// Whether `map` is the incoming map that owns `id`.
	fn owns(&mut self, id: BlockId, map: &ID) -> bool {
		match self {
			Self::Scanned(owners) => owners.get(id) == Some(map),
			Self::Unique { seen, repeated } => {
				let first = seen.insert(id);
				*repeated |= !first;
				first
			}
		}
	}
}

/// Claims for maps read during a remote transaction: among the incoming
/// maps the smallest item id wins, and an incoming winner also beats an
/// existing block with a larger map id unless that block is being removed
/// anyway or contains the insertion point.
pub(crate) struct RemoteClaims<'a> {
	doc: &'a Document,
	registry: &'a Registry,
	incoming: Incoming<'a>,
	doomed: &'a FxHashSet<BlockId>,
	/// The parent the map being read is inserted into.
	pub(crate) target: Option<BlockId>,
	/// Existing blocks that lost their id to an incoming map.
	pub(crate) evicted: Vec<BlockId>,
}

impl<'a> RemoteClaims<'a> {
	pub(crate) fn new(
		doc: &'a Document,
		registry: &'a Registry,
		(incoming, doomed): (Incoming<'a>, &'a FxHashSet<BlockId>),
	) -> Self {
		Self {
			doc,
			registry,
			incoming,
			doomed,
			target: None,
			evicted: Vec::new(),
		}
	}

	/// Whether two incoming maps carried the same block id.
	pub(crate) fn repeated(&self) -> bool {
		matches!(self.incoming, Incoming::Unique { repeated: true, .. })
	}

	fn contains_target(&self, block: BlockId) -> bool {
		self.target
			.is_some_and(|target| target == block || self.doc.is_ancestor(block, target))
	}
}

impl Claim for RemoteClaims<'_> {
	fn claim(&mut self, id: BlockId, map: &ID) -> bool {
		if !self.incoming.owns(id, map) {
			return false;
		}

		let Some(existing) = self.registry.block(id) else {
			return true;
		};

		if self.doomed.contains(&id) || self.evicted.contains(&id) || existing.map == *map {
			return true;
		}

		if *map < existing.map && !self.contains_target(id) {
			self.evicted.push(id);

			return true;
		}

		false
	}
}

impl<T: ReadTxn> Remote<'_, '_, T> {
	/// Add one array record to the plan.
	pub(super) fn plan_array(
		&mut self,
		array: Option<ID>,
		ops: &[ArrayOp],
		(inserted, removed): (&FxHashSet<ID>, &FxHashSet<ID>),
		plan: &mut Plan,
	) -> Result<(), CollabError> {
		let Some(holder) = self.holder(array) else {
			return Ok(());
		};
		let parent = holder.parent();

		if self.registry.is_mirrored(parent) {
			self.plan_delta(parent, ops, plan)
		} else {
			self.plan_walk(parent, (inserted, removed), plan)
		}
	}

	/// Whose children `array` holds, or `None` for arrays the model does not
	/// mirror, such as the children of a hidden block.
	fn holder(&self, array: Option<ID>) -> Option<Holder> {
		let Some(array) = array else {
			return Some(Holder::Root);
		};

		match self.registry.owner(&array)? {
			Owner::Children(block) => Some(Holder::Block(block)),
			_ => None,
		}
	}

	/// Plan from the delta, which lines up with the model's children.
	fn plan_delta(
		&mut self,
		parent: Option<BlockId>,
		ops: &[ArrayOp],
		plan: &mut Plan,
	) -> Result<(), CollabError> {
		let children = self.tx.doc().children(parent).to_vec();
		let mut cursor = 0;
		let mut anchor = Anchor::Start;

		for op in ops {
			match op {
				ArrayOp::Retain(len) => {
					cursor += *len as usize;
					anchor = self.anchor_at(&children, cursor)?;
				}
				ArrayOp::Remove(len) => {
					let end = cursor + *len as usize;
					let removed = children.get(cursor..end).ok_or(CollabError::Diverged)?;
					plan.removed.extend_from_slice(removed);
					cursor = end;
				}
				ArrayOp::Insert(items) => {
					anchor = self.plan_inserts(parent, items, anchor, plan);
				}
			}
		}

		Ok(())
	}

	/// The anchor after the first `count` of `children`.
	fn anchor_at(&self, children: &[BlockId], count: usize) -> Result<Anchor, CollabError> {
		let last = count
			.checked_sub(1)
			.and_then(|index| children.get(index))
			.and_then(|&block| self.registry.block(block))
			.ok_or(CollabError::Diverged)?;

		Ok(Anchor::After(last.map))
	}

	/// Plan the inserted `items`, the first following `anchor`, and return
	/// the anchor after them. Items that are not block maps stay unmirrored.
	fn plan_inserts(
		&mut self,
		parent: Option<BlockId>,
		items: &[Option<ID>],
		mut anchor: Anchor,
		plan: &mut Plan,
	) -> Anchor {
		for item in items {
			let Some(map) = *item else {
				self.registry.adjust_unmirrored(parent, 1);
				continue;
			};

			plan.inserts.push(Insert {
				parent,
				map,
				anchor,
			});
			anchor = Anchor::After(map);
		}

		anchor
	}

	/// Plan by walking the final array, for arrays holding hidden items that
	/// the delta's positions count but the model does not.
	fn plan_walk(
		&mut self,
		parent: Option<BlockId>,
		(inserted, removed): (&FxHashSet<ID>, &FxHashSet<ID>),
		plan: &mut Plan,
	) -> Result<(), CollabError> {
		let array = self.array(parent)?;
		let mut kept = FxHashSet::default();
		let mut anchor = Anchor::Start;
		let mut unmirrored = 0;

		for item in array.iter(self.txn) {
			match self.classify(&item, inserted) {
				Item::Inserted(map) => {
					plan.inserts.push(Insert {
						parent,
						map,
						anchor,
					});
					anchor = Anchor::After(map);
				}
				Item::Shown(block, map) => {
					kept.insert(block);
					anchor = Anchor::After(map);
				}
				Item::Unmirrored => unmirrored += 1,
			}
		}

		for map in removed {
			self.registry.forget_hidden(map);
		}

		self.registry.set_unmirrored(parent, unmirrored);
		let children = self.tx.doc().children(parent);
		plan.removed
			.extend(children.iter().filter(|block| !kept.contains(block)));
		Ok(())
	}

	/// What an item of a walked array is to the plan.
	fn classify(&self, item: &Out, inserted: &FxHashSet<ID>) -> Item {
		let Some(map) = (match item {
			Out::YMap(map) => branch_id(map),
			_ => None,
		}) else {
			return Item::Unmirrored;
		};

		if inserted.contains(&map) {
			return Item::Inserted(map);
		}

		self.registry
			.block_of_map(&map)
			.map_or(Item::Unmirrored, |block| Item::Shown(block, map))
	}

	/// Apply the plan: moves, then removals, then insertions.
	pub(super) fn execute(&mut self, plan: Plan) -> Result<(), CollabError> {
		let Plan { removed, inserts } = plan;
		let mut doomed = FxHashSet::default();

		for &block in &removed {
			doomed.extend(descendants(self.tx.doc(), block));
		}

		let mut anchors: FxHashMap<ID, Anchor> = inserts
			.iter()
			.map(|insert| (insert.map, insert.anchor))
			.collect();
		let (reads, evicted) = self.read_inserts(&inserts, &doomed);
		let rest = self.apply_moves(reads, &mut doomed, &anchors)?;

		for block in removed {
			if doomed.contains(&block) && self.tx.doc().contains(block) {
				self.remove_block(block)?;
			}
		}

		for block in evicted {
			let Some(found) = self.registry.block(block) else {
				continue;
			};
			let anchor = self.anchor_in_array(found.parent, &found.map, &anchors)?;
			anchors.insert(found.map, anchor);
			self.evict(block)?;
		}

		let mut batch = Batch::default();

		for read in rest {
			self.insert(&mut batch, read, &anchors)?;
		}

		self.flush(&mut batch)
	}

	/// Apply the reads that re-insert a removed block unchanged as moves,
	/// sparing them from removal, and return the others.
	fn apply_moves(
		&mut self,
		reads: Vec<Read>,
		doomed: &mut FxHashSet<BlockId>,
		anchors: &FxHashMap<ID, Anchor>,
	) -> Result<Vec<Read>, CollabError> {
		let mut rest = Vec::with_capacity(reads.len());

		for read in reads {
			let Some(tree) = read
				.tree
				.as_ref()
				.filter(|tree| self.unchanged(tree, doomed))
			else {
				rest.push(read);
				continue;
			};

			let moved = subtree_ids(std::slice::from_ref(tree));
			doomed.retain(|id| !moved.contains(id));
			self.move_block(read, anchors)?;
		}

		Ok(rest)
	}

	/// Read every inserted map whose parent survives.
	///
	/// Incoming maps almost never share a block id, so the first pass assumes
	/// they don't and only notes a repeat. Only then are they scanned for the
	/// smallest item id per block id and read again, which keeps the common
	/// case to one pass over the new maps.
	fn read_inserts(
		&self,
		inserts: &[Insert],
		doomed: &FxHashSet<BlockId>,
	) -> (Vec<Read>, Vec<BlockId>) {
		let (reads, claims) = self.read_with(inserts, doomed, Incoming::unique());

		if !claims.repeated() {
			return (reads, claims.evicted);
		}

		let mut owners = Owners::default();

		for insert in inserts {
			if let Some(map) = map_ref(self.txn, &insert.map) {
				let parent = self.parent_kind(insert.parent);
				owners.scan(&map, parent, self.txn, self.schema);
			}
		}

		let (reads, claims) = self.read_with(inserts, doomed, Incoming::Scanned(&owners));
		(reads, claims.evicted)
	}

	fn read_with<'c>(
		&'c self,
		inserts: &[Insert],
		doomed: &'c FxHashSet<BlockId>,
		incoming: Incoming<'c>,
	) -> (Vec<Read>, RemoteClaims<'c>) {
		let doc = self.tx.doc();
		let mut claims = RemoteClaims::new(doc, self.registry, (incoming, doomed));
		let mut reads = Vec::with_capacity(inserts.len());

		for &insert in inserts {
			let survives = insert
				.parent
				.is_none_or(|parent| doc.contains(parent) && !doomed.contains(&parent));
			let Some(map) = map_ref(self.txn, &insert.map).filter(|_| survives) else {
				continue;
			};
			claims.target = insert.parent;
			let parent = Parent {
				id: insert.parent,
				kind: self.parent_kind(insert.parent),
			};
			let mut registration = Registration::default();
			let mut reader = Reader {
				txn: self.txn,
				schema: self.schema,
				claims: &mut claims,
			};

			let tree = reader.block(&map, parent, &mut registration);
			reads.push(Read {
				insert,
				tree,
				registration,
			});
		}

		(reads, claims)
	}

	/// Whether `tree` re-inserts a removed block unchanged.
	fn unchanged(&self, tree: &BlockTree, doomed: &FxHashSet<BlockId>) -> bool {
		doomed.contains(&tree.id) && self.tx.doc().tree(tree.id).as_ref() == Some(tree)
	}

	fn move_block(
		&mut self,
		read: Read,
		anchors: &FxHashMap<ID, Anchor>,
	) -> Result<(), CollabError> {
		let Some(tree) = &read.tree else {
			return Ok(());
		};
		let doc = self.tx.doc();
		let parent = doc
			.block(tree.id)
			.ok_or(CollabError::NotShared(tree.id))?
			.parent();
		let index = doc
			.index_in_parent(tree.id)
			.ok_or(CollabError::NotShared(tree.id))?;
		let to_parent = read.insert.parent;
		let mut to_index = self.resolve(to_parent, read.insert.anchor, anchors);

		if parent == to_parent && index < to_index {
			to_index -= 1;
		}

		self.tx.step(Step::MoveBlocks {
			parent,
			index,
			count: 1,
			to_parent,
			to_index,
		})?;
		self.registry
			.remove(&subtree_ids(std::slice::from_ref(tree)));
		self.repair_losers(&read.registration);
		self.registry.register(read.registration);
		Ok(())
	}

	/// Place one read map, batching consecutive insertions.
	fn insert(
		&mut self,
		batch: &mut Batch,
		read: Read,
		anchors: &FxHashMap<ID, Anchor>,
	) -> Result<(), CollabError> {
		let Read {
			insert,
			tree,
			registration,
		} = read;
		self.repairs.extend(
			registration
				.losers
				.iter()
				.map(|&(map, parent)| Repair { parent, map }),
		);

		let Some(tree) = tree else {
			self.registry.insert_hidden(insert.map, insert.parent);

			return Ok(());
		};

		let continues = batch.parent == insert.parent
			&& batch.last.is_some()
			&& insert.anchor == batch.last.map_or(Anchor::Start, Anchor::After);

		if !continues {
			self.flush(batch)?;
			batch.parent = insert.parent;
			batch.index = self.resolve(insert.parent, insert.anchor, anchors);
		}

		batch.last = Some(insert.map);
		batch.trees.push(tree);
		batch.registrations.push(registration);
		Ok(())
	}

	fn flush(&mut self, batch: &mut Batch) -> Result<(), CollabError> {
		if batch.trees.is_empty() {
			return Ok(());
		}

		self.tx.step(Step::InsertBlocks {
			parent: batch.parent,
			index: batch.index,
			blocks: std::mem::take(&mut batch.trees),
		})?;

		for registration in batch.registrations.drain(..) {
			self.registry.register(registration);
		}

		batch.last = None;
		Ok(())
	}

	/// The model index just after the nearest placed item `anchor` leads to.
	fn resolve(
		&self,
		parent: Option<BlockId>,
		mut anchor: Anchor,
		anchors: &FxHashMap<ID, Anchor>,
	) -> usize {
		let doc = self.tx.doc();

		for _ in 0..=anchors.len() {
			let Anchor::After(map) = anchor else {
				return 0;
			};
			let placed = self
				.registry
				.block_of_map(&map)
				.filter(|&block| {
					doc.block(block)
						.is_some_and(|found| found.parent() == parent)
				})
				.and_then(|block| doc.index_in_parent(block));

			if let Some(index) = placed {
				return index + 1;
			}

			match anchors.get(&map) {
				Some(next) => anchor = *next,
				None => return 0,
			}
		}

		0
	}

	/// The anchor of `map` in the final children array of `parent`: the
	/// nearest map before it that is shown or inserted in this transaction.
	///
	/// Maps inserted in this transaction may anchor after `map`, so the
	/// anchor has to come from the final array. The model cannot give it:
	/// `map`'s block still sits where it was before the transaction, ahead of
	/// insertions that precede it in the final array.
	fn anchor_in_array(
		&self,
		parent: Option<BlockId>,
		map: &ID,
		anchors: &FxHashMap<ID, Anchor>,
	) -> Result<Anchor, CollabError> {
		let mut anchor = Anchor::Start;

		for item in self.array(parent)?.iter(self.txn) {
			let Some(found) = (match item {
				Out::YMap(found) => branch_id(&found),
				_ => None,
			}) else {
				continue;
			};

			if found == *map {
				return Ok(anchor);
			}

			if anchors.contains_key(&found) || self.registry.block_of_map(&found).is_some() {
				anchor = Anchor::After(found);
			}
		}

		Err(CollabError::Diverged)
	}
}