yrby 0.6.1 → 0.7.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/README.md CHANGED
@@ -2,13 +2,43 @@
2
2
 
3
3
  [![CI](https://github.com/jpcamara/yrby/actions/workflows/ci.yml/badge.svg)](https://github.com/jpcamara/yrby/actions/workflows/ci.yml)
4
4
 
5
- Collaborative editing for Rails, backed by [y-crdt](https://github.com/y-crdt/y-crdt)
6
- (the Rust library behind Y.js). Your Rails server speaks the y-websocket sync
7
- protocol directly, so there's no separate Node process hosting the Y.js
8
- documents. Pronounced "yer-bee".
5
+ yrby (pronounced "yer-bee") makes Rails a real Yjs backend. It binds
6
+ [y-crdt](https://github.com/y-crdt/y-crdt), the Rust engine behind Y.js, into
7
+ Ruby, and builds the rest of the stack around it: a sync server for Action
8
+ Cable and AnyCable, a browser provider, and server-side reading and rendering
9
+ of the documents. Real-time collaboration in a Rails app with no Node process
10
+ anywhere in the path.
9
11
 
10
12
  ![Two people typing on separate lines of the same document, each keystroke synced through a Rails server, seen from a third browser with labeled carets](docs/images/collab.gif)
11
13
 
14
+ On the server, `yrby-rails` implements the full y-websocket protocol
15
+ (document sync plus presence) as a channel concern. Its delivery contract is
16
+ stricter than the usual Yjs servers: every update is ack-tracked and durably
17
+ recorded before it is acknowledged or broadcast to anyone. Replaying your
18
+ store always rebuilds the document, across any number of processes.
19
+ ([Delivery guarantees](#delivery-guarantees))
20
+
21
+ In the browser, `yrby-client`'s `ActionCableProvider` connects anything that
22
+ speaks Yjs. The demo app runs four rich text editors, and CI drives each one
23
+ in real Chrome: Tiptap, [Lexxy](https://www.npmjs.com/package/lexxy-realtime),
24
+ Rhino Editor, and CodeMirror. The same channel also syncs Yjs shapes with no
25
+ editor at all: a whiteboard on a `Y.Map`, a kanban board on a `Y.Array`, a
26
+ co-filled form. ([Editors](#editors))
27
+
28
+ In Ruby, the documents are readable without a browser. `Doc#read_text` and
29
+ `Doc#read_map` reconstruct contents for search, validation, and exports.
30
+ `Y::Tiptap` and `Y::Lexxy` render a document to HTML byte-identical to the
31
+ editor's own serializer, take rules for your app's custom nodes, and drop
32
+ straight into ActionText. ([Rendering to HTML](#rendering-to-html))
33
+
34
+ Underneath, the core is built for a production Rails deployment. A `Doc` is
35
+ thread-safe across Puma and ActionCable threads. Native CRDT work runs with
36
+ the GVL released, so it parallelizes on MRI. Incoming frames are validated
37
+ before anything processes them, and multi-process and AnyCable setups are
38
+ tested end to end. ([Thread Safety](#thread-safety))
39
+
40
+ The whole server side of a collaborative document is one channel:
41
+
12
42
  ```ruby
13
43
  class DocumentChannel < ApplicationCable::Channel
14
44
  include Y::ActionCable
@@ -21,31 +51,36 @@ class DocumentChannel < ApplicationCable::Channel
21
51
  end
22
52
  ```
23
53
 
24
- On the browser, use the `ActionCableProvider` from the
25
- [`yrby-client`](https://www.npmjs.com/package/yrby-client) npm package.
26
- Integrates with any editor that includes Y.js support, such as Tiptap, ProseMirror
27
- and [Lexxy](https://www.npmjs.com/package/lexxy-realtime).
28
-
29
- ## Usage
30
-
31
- Install the gem and npm package:
54
+ Install the gem and the npm package:
32
55
 
33
56
  ```
34
- gem install yrby-actioncable # depends on yrby
57
+ gem install yrby-rails # depends on yrby
35
58
  npm install yrby-client
36
59
  ```
37
60
 
38
- ## What you get
39
-
40
- - A thread-safe Ruby `Doc` you can share across Ruby threads/fibers, and native CRDT work
41
- runs with the GVL released.
42
- - The y-websocket protocol (document sync plus awareness/presence) as a
43
- one-include ActionCable concern.
44
- - Authoritative record-before-distribute semantics: each document change can be
45
- recorded durably before it goes out to anyone.
46
- - Optional server-side reads: `Doc#read_text` and `Doc#read_map` reconstruct a
47
- document's contents in Ruby - no Node process - for search, exports, validation,
48
- or server-side rendering.
61
+ ## Contents
62
+
63
+ - [Scope](#scope)
64
+ - [Durability and delivery](#durability-and-delivery)
65
+ - [What about yrb?](#what-about-yrb)
66
+ - [Testing](#testing)
67
+ - [Install](#install)
68
+ - [Docs](#docs)
69
+ - [Editors](#editors)
70
+ - [Usage](#usage)
71
+ - [Doc (Low-Level Document Sync)](#doc-low-level-document-sync)
72
+ - [Reading document contents](#reading-document-contents)
73
+ - [Pending structs and gap-free state](#pending-structs-and-gap-free-state)
74
+ - [Rendering to HTML](#rendering-to-html)
75
+ - [Protocol codec (module functions)](#protocol-codec-module-functions)
76
+ - [ActionCable Integration](#actioncable-integration)
77
+ - [Thread Safety](#thread-safety)
78
+ - [Parallelism (GVL release)](#parallelism-gvl-release)
79
+ - [Message Type Constants](#message-type-constants)
80
+ - [Sync Flow](#sync-flow)
81
+ - [Development](#development)
82
+ - [License](#license)
83
+ - [Acknowledgments](#acknowledgments)
49
84
 
50
85
  ## Scope
51
86
 
@@ -63,17 +98,16 @@ guarantees, correctness, and thread safety.
63
98
 
64
99
  Towards that goal, `yrby` adds opinionated defaults on top of normal Yjs syncing:
65
100
 
66
- - Built-in update acknowledgement: the `ActionCableProvider` in `yrby-client` will continue to
67
- send updates until an ack is received from the server. [`yrby-actioncable`](https://rubygems.org/gems/yrby-actioncable)
68
- only sends an ack when applying an update is successful. The goal is at-least-once delivery,
69
- and because CRDTs are idempotent a duplicate update is effectively a no-op.
70
- - Gap detection in document updates: before applying an update and sending an ack to the client,
71
- `yrby` checks whether the update results in any causal gap. Ie, an update comes through
72
- which depends on a previous update that is not yet present in the document. This can result in
73
- a document stuck with "pending" updates, which will _never_ apply if the missing update is not sent.
74
- To avoid this, `yrby` does not apply the update, and starts a new y-protocol sync with the client.
75
- That will cause the client to synchronize its document with the server, sending through any updates
76
- that may have been missed
101
+ - Built-in update acknowledgement: the `ActionCableProvider` in `yrby-client` keeps
102
+ sending an update until the server acks it, and [`yrby-rails`](https://rubygems.org/gems/yrby-rails)
103
+ only acks once the update is durably recorded. That gives you at-least-once
104
+ delivery, and because CRDT updates are idempotent a duplicate is a no-op.
105
+ - Gap awareness: an update can arrive before another update it depends on (a
106
+ "causal gap"). `yrby` records and acks it like any other, and the document
107
+ heals on its own once the missing update arrives; its sender keeps
108
+ retransmitting it until it is acked. `Doc#pending?` and the `on_gap` hook
109
+ tell you when a document is waiting on a missing update.
110
+ ([Causal gaps](#causal-gaps))
77
111
 
78
112
  ## What about [yrb](https://github.com/y-crdt/yrb)?
79
113
 
@@ -147,8 +181,8 @@ editor's own serializer. Each page is a working integration to copy from:
147
181
  | [Rhino Editor](https://github.com/KonnorRogers/rhino-editor) (Tiptap 3) | `@tiptap/extension-collaboration` + `-caret` | [`rhino.js`](examples/actioncable-demo/frontend/src/rhino.js) |
148
182
  | [CodeMirror 6](https://codemirror.net) | `y-codemirror.next` | [`codemirror.js`](examples/actioncable-demo/frontend/src/codemirror.js) |
149
183
 
150
- The demo also syncs plain Yjs shapes with no editor at all a whiteboard
151
- on a `Y.Map`, a kanban board on a `Y.Array`, a co-filled form over the
184
+ The demo also syncs plain Yjs shapes with no editor at all (a whiteboard
185
+ on a `Y.Map`, a kanban board on a `Y.Array`, a co-filled form) over the
152
186
  same channel. The demo README's "Using this in your own app" section has
153
187
  the integration recipe, and its `NoteMaterializer` shows how to render a
154
188
  document to ActionText server-side with `Y::Tiptap` or `Y::Lexxy`.
@@ -173,17 +207,19 @@ doc.compacted_state_update # => full update, gap-free (excludes pending)
173
207
  # Applying updates
174
208
  doc.apply_update(update_bytes) # apply raw V1 update
175
209
  doc.pending? # => true if holding un-integrable pending structs
210
+ doc.update_ready?(update) # => true if update would integrate cleanly (no gap)
211
+ doc.update_advances?(update) # => true if update moves integrated state forward
176
212
 
177
213
  # Sync protocol
178
214
  doc.sync_step1 # => SyncStep1 message (this doc's state vector)
179
215
  doc.handle_sync_message(data) # => [msg_type, sync_type, response]; answers a
180
- # peer's SyncStep1 with an integrated-only
181
- # SyncStep2 (never serves pending structs)
216
+ # peer's SyncStep1 with full state (lossless,
217
+ # pending included, like Y.js)
182
218
  ```
183
219
 
184
220
  ### Reading document contents
185
221
 
186
- Reconstruct a document server-side search, exports, emails, SSR with no
222
+ Reconstruct a document server-side (search, exports, emails, SSR) with no
187
223
  Node process:
188
224
 
189
225
  ```ruby
@@ -199,16 +235,18 @@ update), yrs parks it as a **pending** struct: the integrated state vector stays
199
235
  empty, but the pending block is held as a recovery buffer and heals if the
200
236
  missing dependency later arrives. `Doc#pending?` reports this.
201
237
 
202
- Pending structs are *not* document state, so they must not cross the sync
203
- boundary a peer that receives one can't integrate it and gets stuck. Two
204
- guarantees keep serving safe:
238
+ Pending structs travel like any other state. `handle_sync_message` answers
239
+ `SyncStep1` with the doc's full state, pending included, just like Y.js's
240
+ `encodeStateAsUpdate`: a peer parks the pending struct the same way this doc
241
+ did and heals it the same way. The one place pending must not go is a
242
+ compacted snapshot:
205
243
 
206
- - `handle_sync_message` answers `SyncStep1` with **integrated-only** state, so a
207
- server never serves a struct it can't integrate itself (this is automatic).
208
- - `Doc#compacted_state_update` gives you the same gap-free full-state update for
209
- when you persist or hand off state yourself. It's non-destructive (the doc
210
- keeps its pending), while `encode_state_as_update` stays lossless so you can
211
- still preserve the raw pending bytes for recovery.
244
+ - `Doc#compacted_state_update` returns a gap-free full-state update for
245
+ compaction. Folding a log into one blob would otherwise freeze an
246
+ un-integrable struct into the base state forever. It's non-destructive: the
247
+ doc keeps its pending.
248
+ - `encode_state_as_update` stays lossless, so persistence and serving keep
249
+ the raw pending bytes and the gap can still heal.
212
250
 
213
251
  ### Rendering to HTML
214
252
 
@@ -231,7 +269,7 @@ tiptap.to_html("content") # or another XML root
231
269
  The output matches Tiptap's own `getHTML()`, checked byte-for-byte in the tests
232
270
  against a document captured from a real editor. It follows
233
271
  [`tiptap-php`](https://github.com/ueberdosis/tiptap-php) and reads both name
234
- styles editors use Tiptap's `bulletList`/`bold` and prosemirror-schema-basic's
272
+ styles editors use: Tiptap's `bulletList`/`bold` and prosemirror-schema-basic's
235
273
  `bullet_list`/`strong`.
236
274
 
237
275
  It covers paragraphs, headings, blockquotes, bullet/ordered/task lists, code
@@ -241,8 +279,8 @@ as semantic `<table><tbody>`, without the column-width styling Tiptap's editor
241
279
  view adds.
242
280
 
243
281
  The support is layered like the Lexical side: `Y::ProseMirror` covers core
244
- ProseMirror natively prosemirror-schema-basic plus the prosemirror-tables
245
- family and Tiptap's extension nodes (task lists, mentions, the details
282
+ ProseMirror natively (prosemirror-schema-basic plus the prosemirror-tables
283
+ family) and Tiptap's extension nodes (task lists, mentions, the details
246
284
  family) are `Y::Tiptap`'s rule set (`Y::Tiptap::NODES`), built on the
247
285
  extension API below. Marks stay in the base: mark rendering (nesting order,
248
286
  `textStyle` CSS, `code` exclusivity) runs through native text-run machinery
@@ -259,8 +297,8 @@ lexxy.to_html("notepad") # or another XML root
259
297
 
260
298
  The HTML is identical to what a `lexxy-editor` submits to Rails (its `value`).
261
299
  The tests check this byte-for-byte against a document captured from a real
262
- editor. Stock Lexical has no canonical serializer every editor configures
263
- its own so the editor-specific class carries the editor's name, and
300
+ editor. Stock Lexical has no canonical serializer (every editor configures
301
+ its own), so the editor-specific class carries the editor's name, and
264
302
  `Y::Lexical` is the core-Lexical base: paragraphs, headings, quotes, code,
265
303
  lists, tables, links, and the full text-format model, for any other Lexical
266
304
  editor to extend with rules.
@@ -273,14 +311,14 @@ mentions both emit `<action-text-attachment>` elements that ActionText can
273
311
  re-render).
274
312
 
275
313
  Internally that support is layered: `Y::Lexical` covers core Lexical
276
- structure natively, and everything Lexxy adds its node types (attachments,
314
+ structure natively, and everything Lexxy adds, its node types (attachments,
277
315
  galleries) and its decorations of core nodes (the table wrapper, header-cell
278
- styling, nested-list classes) is `Y::Lexxy`'s rule set
316
+ styling, nested-list classes), is `Y::Lexxy`'s rule set
279
317
  (`Y::Lexxy::NODES`), built on the extension API below. The gem's own Lexxy
280
318
  support is the API's first consumer: an app rule for one of those types
281
319
  simply replaces it.
282
320
 
283
- In both renderers an unknown node keeps its content text and nested blocks
321
+ In both renderers an unknown node keeps its content: text and nested blocks
284
322
  fall back to readable markup rather than disappearing.
285
323
 
286
324
  #### Custom nodes and marks
@@ -290,7 +328,7 @@ their own node types. Both renderers take rules for them. A rule is checked
290
328
  before the built-in schema, so it can add a node type or replace how a
291
329
  built-in renders.
292
330
 
293
- Rules register in a block one `rules.node` call per type. A declarative
331
+ Rules register in a block, one `rules.node` call per type. A declarative
294
332
  rule is markup as data, rendered natively:
295
333
 
296
334
  ```ruby
@@ -304,14 +342,14 @@ end
304
342
  `tag` names the element. `attrs` values are templates: a string is a literal,
305
343
  a symbol reads that attribute off the node, an array concatenates both kinds;
306
344
  an attribute that resolves empty is left out. `text` (same template form)
307
- emits literal text content. `contains` declares what lives inside the node `:inline` (formatted text,
308
- the default), `:blocks` (child block nodes a container), or `:none` (a
345
+ emits literal text content. `contains` declares what lives inside the node: `:inline` (formatted text,
346
+ the default), `:blocks` (child block nodes, a container), or `:none` (a
309
347
  leaf). `void: true` skips the closing tag.
310
348
 
311
349
  You don't have to guess any of those names or shapes. Editors store types
312
350
  and attributes under names you'd never predict (Rhino's strike mark is
313
351
  `rhino-strike`; Lexical prefixes its own props `__`), so ask a real
314
- document instead make one in your editor using your custom node, then:
352
+ document instead: make one in your editor using your custom node, then:
315
353
 
316
354
  ```ruby
317
355
  Y::Tiptap.new(doc).node_types
@@ -336,25 +374,25 @@ lexical = Y::Lexical.new(doc) do |rules|
336
374
  end
337
375
  ```
338
376
 
339
- The block gets the node's type, its stored attributes, `node.content` the
340
- children, already rendered to HTML and `node.child_types`, the node's
377
+ The block gets the node's type, its stored attributes, `node.content` (the
378
+ children, already rendered to HTML), and `node.child_types`, the node's
341
379
  element/block children by type, in document order. `child_types` answers the
342
380
  structural questions attributes can't: how many images a gallery holds, or
343
381
  whether a list item carries a nested list. Whatever the block returns is
344
382
  spliced into the output as-is: it's trusted HTML, so escape any values you
345
- interpolate. To set the content mode for a callback, give the node both
383
+ interpolate. To set the content mode for a callback, give the node both:
346
384
  `rules.node "embed", contains: :blocks do |node| ... end`.
347
385
 
348
386
  Callbacks never run while the document is locked. The render finishes first
349
387
  (inside one read transaction, GVL released), then the blocks run and their
350
- output is spliced in so a callback can safely read or even write the same
388
+ output is spliced in, so a callback can safely read or even write the same
351
389
  doc. With no callback rules, `to_html` skips the splicing entirely.
352
390
 
353
391
  Blocks are the escape hatch for everything the declarative form can't say,
354
392
  and they're proven sufficient: `Y::Lexxy` and `Y::Tiptap` are themselves
355
- built on this API (`lib/y/lexxy.rb`, `lib/y/tiptap.rb`) simple nodes as
393
+ built on this API (`lib/y/lexxy.rb`, `lib/y/tiptap.rb`): simple nodes as
356
394
  declarative hashes, everything with logic as plain methods mapped by node
357
- type (a `Method` responds to `call` like any lambda) and the fixture tests
395
+ type (a `Method` responds to `call` like any lambda), and the fixture tests
358
396
  hold their output byte-identical to a live editor's.
359
397
 
360
398
  The ProseMirror side also takes custom marks:
@@ -371,7 +409,7 @@ for a built-in mark name (`"bold"`) replaces its built-in tag.
371
409
 
372
410
  ##### Worked examples
373
411
 
374
- A video-embed node from an app's Tiptap extension a type the pinned schema
412
+ A video-embed node from an app's Tiptap extension, a type the pinned schema
375
413
  has never heard of:
376
414
 
377
415
  ```ruby
@@ -398,7 +436,7 @@ tiptap = Y::Tiptap.new(doc) do |rules|
398
436
  end
399
437
  ```
400
438
 
401
- Overriding a shipped rule rendering Lexxy uploads as real image markup
439
+ Overriding a shipped rule: rendering Lexxy uploads as real image markup
402
440
  instead of the `<action-text-attachment>` elements ActionText re-renders:
403
441
 
404
442
  ```ruby
@@ -414,7 +452,7 @@ lexxy = Y::Lexxy.new(doc) do |rules|
414
452
  end
415
453
  ```
416
454
 
417
- Markup that depends on structure `node.child_types` lists the node's
455
+ Markup that depends on structure: `node.child_types` lists the node's
418
456
  element/block children in document order, so a layout container can size
419
457
  itself by its column count while the columns themselves stay declarative:
420
458
 
@@ -427,7 +465,7 @@ tiptap = Y::Tiptap.new(doc) do |rules|
427
465
  end
428
466
  ```
429
467
 
430
- Content-aware overrides dropping the empty paragraphs an editor keeps
468
+ Content-aware overrides: dropping the empty paragraphs an editor keeps
431
469
  around the cursor, since `node.content` arrives already rendered:
432
470
 
433
471
  ```ruby
@@ -438,10 +476,10 @@ lexical = Y::Lexical.new(doc) do |rules|
438
476
  end
439
477
  ```
440
478
 
441
- For a larger reference, the gem's own editor schemas ship this way see
479
+ For a larger reference, the gem's own editor schemas ship this way; see
442
480
  `Y::Lexxy::NODES` in `lib/y/lexxy.rb` (declarative hashes for the simple
443
- nodes, a plain method per node that needs logic galleries, list items,
444
- header cells, both attachment types mapped with `method(:name)`) and
481
+ nodes, a plain method per node that needs logic (galleries, list items,
482
+ header cells, both attachment types) mapped with `method(:name)`) and
445
483
  `Y::Tiptap::NODES` in `lib/y/tiptap.rb` (task lists, mentions, the details
446
484
  family).
447
485
 
@@ -449,7 +487,7 @@ family).
449
487
 
450
488
  Classifying and unwrapping wire frames is stateless, so it's exposed as
451
489
  `Y` module functions rather than a class. The server never holds presence
452
- or document state to route a frame presence lives in the browser clients, and
490
+ or document state to route a frame; presence lives in the browser clients, and
453
491
  the server only relays awareness frames opaquely.
454
492
 
455
493
  ```ruby
@@ -470,28 +508,35 @@ bin/rails db:migrate
470
508
  The models ship in the gem, the way Action Text owns
471
509
  `ActionText::RichText`:
472
510
 
473
- - **`Y::Document`** one row per document, addressed two ways: by `key`
474
- (what a channel addresses one opaque, unique string, sometimes
511
+ - **`Y::Document`**: one row per document, addressed two ways: by `key`
512
+ (what a channel addresses; one opaque, unique string, sometimes
475
513
  app-supplied, never parsed) and, optionally, by polymorphic `record` +
476
514
  `name` (which model attribute it backs; `name` is the attribute name,
477
- `"body"` one document per attribute per record, the
515
+ `"body"`; one document per attribute per record, the
478
516
  ActionText::RichText scheme). Key-only documents leave the binding nil.
479
517
  Either side can arrive first: `Y::Document.for(record, name)` finds or
480
518
  creates the binding, derives a readable key (`post/1/body`), and adopts
481
519
  a key-only row already holding that key, so a channel writing first and
482
520
  a binding created later converge on one document. The row also holds
483
- the merged `state` snapshot CRDT state only; derived data (rendered
521
+ the merged `state` snapshot, CRDT state only; derived data (rendered
484
522
  HTML, search text) is the application's job, typically in the channel's
485
523
  on_change. `.load_state(key)` / `.append(key, update)` are the store
486
524
  calls the generated channel uses.
487
- - **`Y::DocumentUpdate`** the uncompacted tail: one delta per row,
525
+ - **`Y::DocumentUpdate`**: the uncompacted tail, one delta per row,
488
526
  compacted into `state` and deleted once the tail reaches `compact_every`
489
527
  (default 64). Loading reads the snapshot plus the current tail; an
490
528
  empty tail returns `state` directly. Compaction serializes on a
491
- per-document row lock and skips causally-gapped rows they're
529
+ per-document row lock and skips causally-gapped rows; they're
492
530
  quarantined until they heal rather than compacted into state or
493
531
  deleted. Destroying a document deletes its updates with it.
494
532
 
533
+ Encrypted storage: `Y::EncryptedDocument` stores `state` and update
534
+ payloads through Active Record encryption on the same tables, the way
535
+ `ActionText::EncryptedRichText` does. Point the channel's
536
+ `on_load`/`on_change` at it instead and configure your app's encryption
537
+ keys. Use one access path per document: rows written encrypted read back
538
+ as ciphertext through the plain classes.
539
+
495
540
  The migration creates `y_documents` and `y_document_updates`. To rename
496
541
  them, edit the generated migration and point `Y::Document.table_name` /
497
542
  `Y::DocumentUpdate.table_name` at the new names in an initializer.
@@ -501,8 +546,7 @@ answered, and they can point at anything.
501
546
 
502
547
  `include Y::ActionCable` (from the `yrby-rails` gem) is the channel
503
548
  integration: the y-websocket protocol (document sync +
504
- awareness/presence) over ActionCable. (`include Y::ActionCable::Sync`
505
- keeps working and has the same effect.)
549
+ awareness/presence) over ActionCable.
506
550
 
507
551
  ```ruby
508
552
  # app/channels/document_channel.rb
@@ -530,8 +574,8 @@ end
530
574
  ```
531
575
 
532
576
  The concern is store-backed. A handshake is answered from `on_load`; document
533
- changes are checked against that durable state, recorded through `on_change`,
534
- then broadcast. Nothing authoritative is kept in ActionCable process memory, so
577
+ changes are recorded through `on_change`, then broadcast. Nothing
578
+ authoritative is kept in ActionCable process memory, so
535
579
  AnyCable RPC workers, Puma workers, and separate dynos can all handle messages
536
580
  for the same document as long as they share the same store and cable adapter.
537
581
 
@@ -549,16 +593,18 @@ no single client can relay garbage that breaks the others in a room.
549
593
 
550
594
  #### Delivery guarantees
551
595
 
552
- The contract is the same at every scale one process, or hundreds across many
596
+ The contract is the same at every scale: one process, or hundreds across many
553
597
  servers:
554
598
 
555
599
  - **The document always converges.** CRDT updates are commutative and
556
600
  idempotent, so out-of-order, duplicate, or concurrent delivery all converge to
557
601
  the same correct document. This needs no coordination and holds everywhere.
558
- - **The durable log never goes gappy.** An update is recorded only once its
559
- causal dependencies are already in the store (checked against `on_load`); a
560
- causally-incomplete update triggers a resync instead, so the log always
561
- rebuilds cleanly.
602
+ - **An acked update is durable, even one that arrived out of order.** An
603
+ update with a missing dependency is recorded and acked like any other, and
604
+ parks as pending in the document. That missing dependency is an update some
605
+ client still holds unacked, so that client keeps retransmitting it until
606
+ the server records it, and the gap closes. The ack loop is the guarantee.
607
+ See [Causal gaps](#causal-gaps).
562
608
  - **`on_change` is at-least-once, and the durable guarantee is that replaying the
563
609
  log reconstructs the document.** Every update triggers `on_change` before it's acked or
564
610
  broadcast (record-before-distribute). If exactly-once updates matter for you, **you
@@ -568,13 +614,13 @@ servers:
568
614
  There is no negative-ack: the client simply never receives the ack, keeps the
569
615
  update pending, and retransmits on its timer/reconnect. This is built for
570
616
  *transient* failures (the store is briefly down → a retry lands). A block that
571
- raises *deterministically* a validation that always fails for this edit
617
+ raises *deterministically* (a validation that always fails for this edit)
572
618
  will be retried forever, since nothing tells the client to stop. Enforce hard
573
619
  rejections before the edit reaches `on_change` (channel authorization in
574
620
  `subscribed`), not by raising inside it.
575
621
  - **An over-cap frame is dropped the same silent way.** A frame larger than
576
- `max_frame_bytes` (default 8 MiB) is dropped before decoding no ack, no
577
- broadcast to bound the work a client can force. For a genuine document
622
+ `max_frame_bytes` (default 8 MiB) is dropped before decoding (no ack, no
623
+ broadcast) to bound the work a client can force. For a genuine document
578
624
  update that means the same implicit rejection as above: unacked, retransmitted
579
625
  forever. Normal typing never approaches the cap, but a large paste, an embedded
580
626
  image, or a big initial `SyncStep2` can. The drop is logged (`warn` for
@@ -584,6 +630,85 @@ servers:
584
630
  genuinely-too-big content upstream rather than relying on the cap to reject it
585
631
  gracefully.
586
632
 
633
+ #### Causal gaps
634
+
635
+ Yjs updates can arrive out of order: an update can reach the server before
636
+ another update it depends on. yrby treats that as normal. The update is
637
+ recorded and acked like any other, parks as a pending struct in the document,
638
+ and integrates on its own the moment the missing dependency lands. The write
639
+ path never rebuilds the document; it appends, relays, and acks, so a gapped
640
+ update costs the same as any other.
641
+
642
+ Serving is lossless too, like any Yjs server. `handle_sync_message` serves
643
+ full state, pending included, so a peer parks the same pending struct and
644
+ heals it the same way. Healing needs no special machinery: the missing
645
+ dependency is an update its sender still holds unacked, and at-least-once
646
+ retransmission delivers it. Only compaction excludes pending
647
+ (`compacted_state_update`), because folding a log must not freeze an
648
+ un-integrable struct into the base state.
649
+
650
+ The bundled `Y::Document` store handles all of this. If you write your own
651
+ store, keep two things in mind:
652
+
653
+ **1. Load losslessly, and tolerate duplicates.** `on_load` should return
654
+ state that preserves pending: `encode_state_as_update`, or a replay of the
655
+ raw append log. Don't compact with `compacted_state_update` while
656
+ `doc.pending?`; that strips the pending struct and the acked edit inside it.
657
+ (`Y::Document` quarantines pending rows for exactly this reason.) A lost ack
658
+ also means a client resends an update the store already has. Replay converges
659
+ anyway, because CRDT apply is idempotent, so deduping is optional. If log
660
+ size matters, dedup by content hash:
661
+
662
+ ```ruby
663
+ class DocumentStore
664
+ # append tolerates duplicates: a re-delivered update upserts to a no-op.
665
+ def append(key, update)
666
+ Revision.upsert({ doc_key: key, update_hash: Digest::SHA256.hexdigest(update), update: update },
667
+ unique_by: %i[doc_key update_hash])
668
+ end
669
+
670
+ # load is lossless: replay the raw log so a pending struct is preserved and
671
+ # heals when its dependency arrives.
672
+ def load(key)
673
+ updates = Revision.where(doc_key: key).order(:id).pluck(:update)
674
+ return nil if updates.empty?
675
+
676
+ doc = Y::Doc.new
677
+ updates.each { |u| doc.apply_update(u) }
678
+ doc.encode_state_as_update # lossless: keeps pending
679
+ end
680
+
681
+ # optional compaction: only when there is no open gap, or you would drop it.
682
+ def compact(key)
683
+ doc = Y::Doc.new
684
+ Revision.where(doc_key: key).order(:id).pluck(:update).each { |u| doc.apply_update(u) }
685
+ return if doc.pending? # a gap is open; compacting now would drop it
686
+ # ... replace the log with a single revision holding doc.compacted_state_update ...
687
+ end
688
+ end
689
+ ```
690
+
691
+ **2. Watch for gaps that never heal.** An open gap is quiet: the edit sits
692
+ as pending, invisible in the document, until its dependency arrives. Normally
693
+ that resolves itself. The sender retransmits the missing update until it is
694
+ acked, and every join or reconnect handshake has the client send everything
695
+ the server hasn't integrated, so any client holding the dependency supplies
696
+ it just by connecting. The gap worth alerting on is one no live client can
697
+ supply, and that is what the `on_gap` hook surfaces. It fires with the
698
+ document key whenever a document is loaded to serve state and a gap is still
699
+ open. Use it to emit a metric (a pending-document count, or the age of the
700
+ oldest open gap) so a stuck gap is visible. Gaps are also logged at `info`,
701
+ and errors raised in the hook are swallowed so observability can never break
702
+ frame handling.
703
+
704
+ ```ruby
705
+ class DocumentChannel < ApplicationCable::Channel
706
+ include Y::ActionCable
707
+
708
+ on_gap { |key| StatsD.increment("yrby.gap", tags: ["doc:#{key}"]) }
709
+ end
710
+ ```
711
+
587
712
  #### Multi-process deployments
588
713
 
589
714
  Most Rails apps run several processes, and any of them might serve a given document.
@@ -643,12 +768,86 @@ duplicate record replays to the same document.
643
768
  The demo wires `on_change` to a durable Postgres-backed log by default, and checks
644
769
  end to end that the log alone rebuilds the document.
645
770
 
771
+ #### Ephemeral documents (no database)
772
+
773
+ `on_load` and `on_change` are plain blocks, and nothing requires them to touch
774
+ a database. For documents that don't need to outlive their session (a
775
+ scratchpad, live form state, a draft you only persist on submit) the store
776
+ can be connection state that travels with each request:
777
+
778
+ ```ruby
779
+ class ScratchpadChannel < ApplicationCable::Channel
780
+ include Y::ActionCable
781
+
782
+ on_load { |key| @doc_state }
783
+
784
+ on_change do |key, update|
785
+ doc = Y::Doc.new
786
+ doc.apply_update(@doc_state) if @doc_state
787
+ doc.apply_update(update)
788
+ @doc_state = doc.compacted_state_update
789
+ end
790
+
791
+ def subscribed = sync_subscribed(params[:id])
792
+ def receive(data) = sync_receive(data, params[:id])
793
+ end
794
+ ```
795
+
796
+ On AnyCable the channel object doesn't survive between messages, so an
797
+ instance variable won't hold. Declare the store as channel state instead
798
+ (`state_attr_accessor` comes from anycable-rails) and Base64 it, because that
799
+ state is serialized as JSON into each RPC exchange with `anycable-go`:
800
+
801
+ ```ruby
802
+ class ScratchpadChannel < ApplicationCable::Channel
803
+ include Y::ActionCable
804
+
805
+ state_attr_accessor :doc_state
806
+
807
+ on_load { |key| doc_state && Base64.strict_decode64(doc_state) }
808
+
809
+ on_change do |key, update|
810
+ doc = Y::Doc.new
811
+ doc.apply_update(Base64.strict_decode64(doc_state)) if doc_state
812
+ doc.apply_update(update)
813
+ self.doc_state = Base64.strict_encode64(doc.compacted_state_update)
814
+ end
815
+
816
+ def subscribed = sync_subscribed(params[:id])
817
+ def receive(data) = sync_receive(data, params[:id])
818
+ end
819
+ ```
820
+
821
+ Both hooks run in the channel instance (`instance_exec`), so they can use
822
+ anything the channel can, and `sync_receive` rebuilds the document from
823
+ `on_load` on every update, which is what lets the store live on the
824
+ connection. On Action Cable the channel instance lasts as long as the
825
+ connection, so an instance variable is the whole store. Merging into
826
+ `compacted_state_update` keeps it one blob instead of a growing update log.
827
+
828
+ The store is per connection, which shapes what this fits. A single writer gets
829
+ the full delivery contract with no database anywhere. With several people
830
+ editing at once, one client's update can depend on edits its own connection
831
+ has never seen; that update records as pending, and the next handshake with
832
+ that client (which always holds the full document) supplies the missing state
833
+ and heals it. The document still converges; heavy concurrent editing just
834
+ parks more pending between handshakes than a shared store would. On
835
+ AnyCable, keep the payload in mind too: the blob travels with every message,
836
+ so that variant suits small documents, not long manuscripts.
837
+
838
+ Durability is the connection plus the browsers. A reconnecting client re-seeds
839
+ an empty server through the ordinary sync handshake, so the document survives
840
+ server restarts as long as some client still has it. For ephemeral documents
841
+ shared across clients on a single-process deployment, the same two hooks over
842
+ a class-level `Concurrent::Map` work instead; that version stops being
843
+ coherent the moment you scale past one process.
844
+
646
845
  #### Reliable delivery (acks)
647
846
 
648
847
  yrby document delivery is ack-tracked. Browser document updates carry an
649
- `"id"`, and the server replies `{ "ack": <id> }` once `on_change` has succesfully fired.
650
- A causally-gapped update is not acked; the server sends a resync request, and
651
- the client keeps the update queued until it lands.
848
+ `"id"`, and the server replies `{ "ack": <id> }` once `on_change` has
849
+ successfully fired. Every decodable document update is recorded and acked,
850
+ including one that arrives out of order.
652
851
 
653
852
  ```
654
853
  client -> server { "update": "<base64 update>", "id": 42 }
@@ -662,13 +861,13 @@ one `{ ack: id }` cumulatively confirms everything up to it. Because CRDT apply
662
861
  is idempotent, a resend that already landed is a harmless no-op that just
663
862
  re-acks. Awareness stays ephemeral and is not acked.
664
863
 
665
- Presence (cursors, selections) is owned by the browser clients the server
864
+ Presence (cursors, selections) is owned by the browser clients; the server
666
865
  never sets or holds presence state, it only relays awareness frames opaquely.
667
866
  See `yrby-client` for the client-side awareness API.
668
867
 
669
868
  ## Thread Safety
670
869
 
671
- A `Doc` is safe to share across Ruby threads used concurrently from Puma
870
+ A `Doc` is safe to share across Ruby threads, used concurrently from Puma
672
871
  workers, ActionCable connection threads, or background jobs without external
673
872
  locking.
674
873