yrby 0.6.0 → 0.7.0

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.
Files changed (31) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +73 -28
  3. data/Cargo.lock +29 -0
  4. data/README.md +352 -103
  5. data/ext/yrby/Cargo.toml +3 -0
  6. data/ext/yrby/crates/html-core/Cargo.toml +15 -0
  7. data/ext/yrby/{src/render_rules.rs → crates/html-core/src/lib.rs} +6 -0
  8. data/ext/yrby/crates/lexical-html/Cargo.toml +16 -0
  9. data/ext/yrby/{src/lexical_html.rs → crates/lexical-html/src/lib.rs} +14 -10
  10. data/ext/yrby/crates/prosemirror-html/Cargo.toml +16 -0
  11. data/ext/yrby/{src/prosemirror_html.rs → crates/prosemirror-html/src/lib.rs} +14 -10
  12. data/ext/yrby/src/lib.rs +10 -10
  13. data/ext/yrby/src/protocol.rs +63 -0
  14. data/ext/yrby/src/read.rs +3 -3
  15. data/ext/yrby/target/debug/build/clang-sys-e3ae45bd384f74c3/out/common.rs +355 -0
  16. data/ext/yrby/target/debug/build/clang-sys-e3ae45bd384f74c3/out/dynamic.rs +276 -0
  17. data/ext/yrby/target/debug/build/clang-sys-e3ae45bd384f74c3/out/macros.rs +49 -0
  18. data/ext/yrby/target/debug/build/rb-sys-4407948463231c4f/out/bindings-0.9.128-mri-arm64-darwin23-3.4.7.rs +8934 -0
  19. data/ext/yrby/target/debug/build/rb-sys-dbeea42737529c2d/out/bindings-0.9.128-mri-arm64-darwin23-3.4.7.rs +8934 -0
  20. data/ext/yrby/target/debug/build/serde-58ea0ee887cc2602/out/private.rs +6 -0
  21. data/ext/yrby/target/debug/build/serde_core-41f407c21c1f205e/out/private.rs +5 -0
  22. data/ext/yrby/target/debug/build/thiserror-0f1416a82ff26f22/out/private.rs +5 -0
  23. data/lib/generators/yrby/install/install_generator.rb +44 -0
  24. data/lib/generators/yrby/install/templates/document_channel.rb +36 -0
  25. data/lib/generators/yrby/tables/tables_generator.rb +41 -0
  26. data/lib/generators/yrby/tables/templates/create_y_tables.rb +24 -0
  27. data/lib/y/decoder.rb +64 -0
  28. data/lib/y/lexxy.rb +25 -4
  29. data/lib/y/version.rb +1 -1
  30. data/lib/y.rb +1 -0
  31. metadata +21 -5
data/README.md CHANGED
@@ -2,48 +2,85 @@
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.
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.
11
+
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)
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:
9
41
 
10
42
  ```ruby
11
43
  class DocumentChannel < ApplicationCable::Channel
12
- include Y::ActionCable::Sync
44
+ include Y::ActionCable
13
45
 
14
- on_load { |key| MyStore.load(key) }
15
- on_change { |key, update| MyStore.append(key, update) }
46
+ on_load { |key| Y::Document.load_state(key) }
47
+ on_change { |key, update| Y::Document.append(key, update) }
16
48
 
17
49
  def subscribed = sync_subscribed(params[:id])
18
50
  def receive(data) = sync_receive(data, params[:id])
19
51
  end
20
52
  ```
21
53
 
22
- On the browser, use the `ActionCableProvider` from the
23
- [`yrby-client`](https://www.npmjs.com/package/yrby-client) npm package.
24
- Integrates with any editor that includes Y.js support, such as Tiptap, ProseMirror
25
- and [Lexxy](https://www.npmjs.com/package/lexxy-realtime).
26
-
27
- ## Usage
28
-
29
- Install the gem and npm package:
54
+ Install the gem and the npm package:
30
55
 
31
56
  ```
32
- gem install yrby-actioncable # depends on yrby
57
+ gem install yrby-rails # depends on yrby
33
58
  npm install yrby-client
34
59
  ```
35
60
 
36
- ## What you get
37
-
38
- - A thread-safe Ruby `Doc` you can share across Ruby threads/fibers, and native CRDT work
39
- runs with the GVL released.
40
- - The y-websocket protocol (document sync plus awareness/presence) as a
41
- one-include ActionCable concern.
42
- - Authoritative record-before-distribute semantics: each document change can be
43
- recorded durably before it goes out to anyone.
44
- - Optional server-side reads: `Doc#read_text` and `Doc#read_map` reconstruct a
45
- document's contents in Ruby - no Node process - for search, exports, validation,
46
- 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)
47
84
 
48
85
  ## Scope
49
86
 
@@ -59,19 +96,18 @@ and `Doc#read_map` reconstruct it server-side, in Ruby.
59
96
  The surface is intentionally small, but the focus is durability, resiliency, delivery
60
97
  guarantees, correctness, and thread safety.
61
98
 
62
- Towards that goal, `yrby` adds capabilities that stand out even in the Yjs ecosystem:
99
+ Towards that goal, `yrby` adds opinionated defaults on top of normal Yjs syncing:
63
100
 
64
- - Built-in update acknowledgement: the `ActionCableProvider` in `yrby-client` will continue to
65
- send updates until an ack is received from the server. [`yrby-actioncable`](https://rubygems.org/gems/yrby-actioncable)
66
- only sends an ack when applying an update is successful. The goal is at-least-once delivery,
67
- and because CRDTs are idempotent a duplicate update is effectively a no-op.
68
- - Gap detection in document updates: before applying an update and sending an ack to the client,
69
- `yrby` checks whether the update results in any causal gap. Ie, an update comes through
70
- which depends on a previous update that is not yet present in the document. This can result in
71
- a document stuck with "pending" updates, which will _never_ apply if the missing update is not sent.
72
- To avoid this, `yrby` does not apply the update, and starts a new y-protocol sync with the client.
73
- That will cause the client to synchronize its document with the server, sending through any updates
74
- 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))
75
111
 
76
112
  ## What about [yrb](https://github.com/y-crdt/yrb)?
77
113
 
@@ -101,8 +137,9 @@ Issues and PRs are welcome.
101
137
  # Core CRDT + protocol primitives:
102
138
  gem "yrby"
103
139
 
104
- # For the Rails/ActionCable server concern (Y::ActionCable::Sync):
105
- gem "yrby-actioncable"
140
+ # For the Rails side (the sync channel, document models, the generator).
141
+ # Formerly yrby-actioncable; that name stops at 0.3.1.
142
+ gem "yrby-rails"
106
143
  ```
107
144
 
108
145
  Requires Ruby 3.4 or newer. The release workflow builds precompiled gems for
@@ -144,8 +181,8 @@ editor's own serializer. Each page is a working integration to copy from:
144
181
  | [Rhino Editor](https://github.com/KonnorRogers/rhino-editor) (Tiptap 3) | `@tiptap/extension-collaboration` + `-caret` | [`rhino.js`](examples/actioncable-demo/frontend/src/rhino.js) |
145
182
  | [CodeMirror 6](https://codemirror.net) | `y-codemirror.next` | [`codemirror.js`](examples/actioncable-demo/frontend/src/codemirror.js) |
146
183
 
147
- The demo also syncs plain Yjs shapes with no editor at all a whiteboard
148
- 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
149
186
  same channel. The demo README's "Using this in your own app" section has
150
187
  the integration recipe, and its `NoteMaterializer` shows how to render a
151
188
  document to ActionText server-side with `Y::Tiptap` or `Y::Lexxy`.
@@ -170,17 +207,19 @@ doc.compacted_state_update # => full update, gap-free (excludes pending)
170
207
  # Applying updates
171
208
  doc.apply_update(update_bytes) # apply raw V1 update
172
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
173
212
 
174
213
  # Sync protocol
175
214
  doc.sync_step1 # => SyncStep1 message (this doc's state vector)
176
215
  doc.handle_sync_message(data) # => [msg_type, sync_type, response]; answers a
177
- # peer's SyncStep1 with an integrated-only
178
- # SyncStep2 (never serves pending structs)
216
+ # peer's SyncStep1 with full state (lossless,
217
+ # pending included, like Y.js)
179
218
  ```
180
219
 
181
220
  ### Reading document contents
182
221
 
183
- Reconstruct a document server-side search, exports, emails, SSR with no
222
+ Reconstruct a document server-side (search, exports, emails, SSR) with no
184
223
  Node process:
185
224
 
186
225
  ```ruby
@@ -196,16 +235,18 @@ update), yrs parks it as a **pending** struct: the integrated state vector stays
196
235
  empty, but the pending block is held as a recovery buffer and heals if the
197
236
  missing dependency later arrives. `Doc#pending?` reports this.
198
237
 
199
- Pending structs are *not* document state, so they must not cross the sync
200
- boundary a peer that receives one can't integrate it and gets stuck. Two
201
- 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:
202
243
 
203
- - `handle_sync_message` answers `SyncStep1` with **integrated-only** state, so a
204
- server never serves a struct it can't integrate itself (this is automatic).
205
- - `Doc#compacted_state_update` gives you the same gap-free full-state update for
206
- when you persist or hand off state yourself. It's non-destructive (the doc
207
- keeps its pending), while `encode_state_as_update` stays lossless so you can
208
- 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.
209
250
 
210
251
  ### Rendering to HTML
211
252
 
@@ -228,7 +269,7 @@ tiptap.to_html("content") # or another XML root
228
269
  The output matches Tiptap's own `getHTML()`, checked byte-for-byte in the tests
229
270
  against a document captured from a real editor. It follows
230
271
  [`tiptap-php`](https://github.com/ueberdosis/tiptap-php) and reads both name
231
- 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
232
273
  `bullet_list`/`strong`.
233
274
 
234
275
  It covers paragraphs, headings, blockquotes, bullet/ordered/task lists, code
@@ -238,8 +279,8 @@ as semantic `<table><tbody>`, without the column-width styling Tiptap's editor
238
279
  view adds.
239
280
 
240
281
  The support is layered like the Lexical side: `Y::ProseMirror` covers core
241
- ProseMirror natively prosemirror-schema-basic plus the prosemirror-tables
242
- 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
243
284
  family) are `Y::Tiptap`'s rule set (`Y::Tiptap::NODES`), built on the
244
285
  extension API below. Marks stay in the base: mark rendering (nesting order,
245
286
  `textStyle` CSS, `code` exclusivity) runs through native text-run machinery
@@ -256,8 +297,8 @@ lexxy.to_html("notepad") # or another XML root
256
297
 
257
298
  The HTML is identical to what a `lexxy-editor` submits to Rails (its `value`).
258
299
  The tests check this byte-for-byte against a document captured from a real
259
- editor. Stock Lexical has no canonical serializer every editor configures
260
- 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
261
302
  `Y::Lexical` is the core-Lexical base: paragraphs, headings, quotes, code,
262
303
  lists, tables, links, and the full text-format model, for any other Lexical
263
304
  editor to extend with rules.
@@ -270,14 +311,14 @@ mentions both emit `<action-text-attachment>` elements that ActionText can
270
311
  re-render).
271
312
 
272
313
  Internally that support is layered: `Y::Lexical` covers core Lexical
273
- structure natively, and everything Lexxy adds its node types (attachments,
314
+ structure natively, and everything Lexxy adds, its node types (attachments,
274
315
  galleries) and its decorations of core nodes (the table wrapper, header-cell
275
- styling, nested-list classes) is `Y::Lexxy`'s rule set
316
+ styling, nested-list classes), is `Y::Lexxy`'s rule set
276
317
  (`Y::Lexxy::NODES`), built on the extension API below. The gem's own Lexxy
277
318
  support is the API's first consumer: an app rule for one of those types
278
319
  simply replaces it.
279
320
 
280
- 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
281
322
  fall back to readable markup rather than disappearing.
282
323
 
283
324
  #### Custom nodes and marks
@@ -287,7 +328,7 @@ their own node types. Both renderers take rules for them. A rule is checked
287
328
  before the built-in schema, so it can add a node type or replace how a
288
329
  built-in renders.
289
330
 
290
- 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
291
332
  rule is markup as data, rendered natively:
292
333
 
293
334
  ```ruby
@@ -301,14 +342,14 @@ end
301
342
  `tag` names the element. `attrs` values are templates: a string is a literal,
302
343
  a symbol reads that attribute off the node, an array concatenates both kinds;
303
344
  an attribute that resolves empty is left out. `text` (same template form)
304
- emits literal text content. `contains` declares what lives inside the node `:inline` (formatted text,
305
- 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
306
347
  leaf). `void: true` skips the closing tag.
307
348
 
308
349
  You don't have to guess any of those names or shapes. Editors store types
309
350
  and attributes under names you'd never predict (Rhino's strike mark is
310
351
  `rhino-strike`; Lexical prefixes its own props `__`), so ask a real
311
- 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:
312
353
 
313
354
  ```ruby
314
355
  Y::Tiptap.new(doc).node_types
@@ -333,25 +374,25 @@ lexical = Y::Lexical.new(doc) do |rules|
333
374
  end
334
375
  ```
335
376
 
336
- The block gets the node's type, its stored attributes, `node.content` the
337
- 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
338
379
  element/block children by type, in document order. `child_types` answers the
339
380
  structural questions attributes can't: how many images a gallery holds, or
340
381
  whether a list item carries a nested list. Whatever the block returns is
341
382
  spliced into the output as-is: it's trusted HTML, so escape any values you
342
- 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:
343
384
  `rules.node "embed", contains: :blocks do |node| ... end`.
344
385
 
345
386
  Callbacks never run while the document is locked. The render finishes first
346
387
  (inside one read transaction, GVL released), then the blocks run and their
347
- 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
348
389
  doc. With no callback rules, `to_html` skips the splicing entirely.
349
390
 
350
391
  Blocks are the escape hatch for everything the declarative form can't say,
351
392
  and they're proven sufficient: `Y::Lexxy` and `Y::Tiptap` are themselves
352
- 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
353
394
  declarative hashes, everything with logic as plain methods mapped by node
354
- 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
355
396
  hold their output byte-identical to a live editor's.
356
397
 
357
398
  The ProseMirror side also takes custom marks:
@@ -368,7 +409,7 @@ for a built-in mark name (`"bold"`) replaces its built-in tag.
368
409
 
369
410
  ##### Worked examples
370
411
 
371
- 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
372
413
  has never heard of:
373
414
 
374
415
  ```ruby
@@ -395,7 +436,7 @@ tiptap = Y::Tiptap.new(doc) do |rules|
395
436
  end
396
437
  ```
397
438
 
398
- Overriding a shipped rule rendering Lexxy uploads as real image markup
439
+ Overriding a shipped rule: rendering Lexxy uploads as real image markup
399
440
  instead of the `<action-text-attachment>` elements ActionText re-renders:
400
441
 
401
442
  ```ruby
@@ -411,7 +452,7 @@ lexxy = Y::Lexxy.new(doc) do |rules|
411
452
  end
412
453
  ```
413
454
 
414
- 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
415
456
  element/block children in document order, so a layout container can size
416
457
  itself by its column count while the columns themselves stay declarative:
417
458
 
@@ -424,7 +465,7 @@ tiptap = Y::Tiptap.new(doc) do |rules|
424
465
  end
425
466
  ```
426
467
 
427
- Content-aware overrides dropping the empty paragraphs an editor keeps
468
+ Content-aware overrides: dropping the empty paragraphs an editor keeps
428
469
  around the cursor, since `node.content` arrives already rendered:
429
470
 
430
471
  ```ruby
@@ -435,10 +476,10 @@ lexical = Y::Lexical.new(doc) do |rules|
435
476
  end
436
477
  ```
437
478
 
438
- 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
439
480
  `Y::Lexxy::NODES` in `lib/y/lexxy.rb` (declarative hashes for the simple
440
- nodes, a plain method per node that needs logic galleries, list items,
441
- 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
442
483
  `Y::Tiptap::NODES` in `lib/y/tiptap.rb` (task lists, mentions, the details
443
484
  family).
444
485
 
@@ -446,7 +487,7 @@ family).
446
487
 
447
488
  Classifying and unwrapping wire frames is stateless, so it's exposed as
448
489
  `Y` module functions rather than a class. The server never holds presence
449
- 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
450
491
  the server only relays awareness frames opaquely.
451
492
 
452
493
  ```ruby
@@ -457,31 +498,84 @@ Y.wrap_update(update_bytes) # => wrap a raw doc update as a sync Update frame
457
498
 
458
499
  ### ActionCable Integration
459
500
 
460
- `Y::ActionCable::Sync` (from the `yrby-actioncable` gem) is a channel
461
- concern that implements the full y-websocket protocol (document sync +
462
- awareness/presence) over ActionCable:
501
+ In a Rails app, one generator creates the channel and the migration:
502
+
503
+ ```bash
504
+ bin/rails generate yrby:install
505
+ bin/rails db:migrate
506
+ ```
507
+
508
+ The models ship in the gem, the way Action Text owns
509
+ `ActionText::RichText`:
510
+
511
+ - **`Y::Document`**: one row per document, addressed two ways: by `key`
512
+ (what a channel addresses; one opaque, unique string, sometimes
513
+ app-supplied, never parsed) and, optionally, by polymorphic `record` +
514
+ `name` (which model attribute it backs; `name` is the attribute name,
515
+ `"body"`; one document per attribute per record, the
516
+ ActionText::RichText scheme). Key-only documents leave the binding nil.
517
+ Either side can arrive first: `Y::Document.for(record, name)` finds or
518
+ creates the binding, derives a readable key (`post/1/body`), and adopts
519
+ a key-only row already holding that key, so a channel writing first and
520
+ a binding created later converge on one document. The row also holds
521
+ the merged `state` snapshot, CRDT state only; derived data (rendered
522
+ HTML, search text) is the application's job, typically in the channel's
523
+ on_change. `.load_state(key)` / `.append(key, update)` are the store
524
+ calls the generated channel uses.
525
+ - **`Y::DocumentUpdate`**: the uncompacted tail, one delta per row,
526
+ compacted into `state` and deleted once the tail reaches `compact_every`
527
+ (default 64). Loading reads the snapshot plus the current tail; an
528
+ empty tail returns `state` directly. Compaction serializes on a
529
+ per-document row lock and skips causally-gapped rows; they're
530
+ quarantined until they heal rather than compacted into state or
531
+ deleted. Destroying a document deletes its updates with it.
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
+
540
+ The migration creates `y_documents` and `y_document_updates`. To rename
541
+ them, edit the generated migration and point `Y::Document.table_name` /
542
+ `Y::DocumentUpdate.table_name` at the new names in an initializer.
543
+
544
+ Storage is swappable: the channel only needs `on_load` and `on_change`
545
+ answered, and they can point at anything.
546
+
547
+ `include Y::ActionCable` (from the `yrby-rails` gem) is the channel
548
+ integration: the y-websocket protocol (document sync +
549
+ awareness/presence) over ActionCable.
463
550
 
464
551
  ```ruby
465
552
  # app/channels/document_channel.rb
466
553
  class DocumentChannel < ApplicationCable::Channel
467
- include Y::ActionCable::Sync
554
+ include Y::ActionCable
468
555
 
469
- on_load { |key| MyStore.load(key) } # source of truth
470
- on_change { |key, update| MyStore.append(key, update) } # durable record
556
+ on_load { |key| Y::Document.load_state(key) } # rebuild from storage
557
+ on_change { |key, update| Y::Document.append(key, update) } # record, then broadcast
471
558
 
472
559
  def subscribed
560
+ return reject unless authorized?(params[:id])
561
+
473
562
  sync_subscribed params[:id]
474
563
  end
475
564
 
476
565
  def receive(data)
477
566
  sync_receive(data, params[:id])
478
567
  end
568
+
569
+ private
570
+
571
+ # Everyone is denied until you wire this to your app's auth.
572
+ def authorized?(_document_key) = false
479
573
  end
480
574
  ```
481
575
 
482
576
  The concern is store-backed. A handshake is answered from `on_load`; document
483
- changes are checked against that durable state, recorded through `on_change`,
484
- 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
485
579
  AnyCable RPC workers, Puma workers, and separate dynos can all handle messages
486
580
  for the same document as long as they share the same store and cable adapter.
487
581
 
@@ -499,16 +593,18 @@ no single client can relay garbage that breaks the others in a room.
499
593
 
500
594
  #### Delivery guarantees
501
595
 
502
- 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
503
597
  servers:
504
598
 
505
599
  - **The document always converges.** CRDT updates are commutative and
506
600
  idempotent, so out-of-order, duplicate, or concurrent delivery all converge to
507
601
  the same correct document. This needs no coordination and holds everywhere.
508
- - **The durable log never goes gappy.** An update is recorded only once its
509
- causal dependencies are already in the store (checked against `on_load`); a
510
- causally-incomplete update triggers a resync instead, so the log always
511
- 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).
512
608
  - **`on_change` is at-least-once, and the durable guarantee is that replaying the
513
609
  log reconstructs the document.** Every update triggers `on_change` before it's acked or
514
610
  broadcast (record-before-distribute). If exactly-once updates matter for you, **you
@@ -518,13 +614,13 @@ servers:
518
614
  There is no negative-ack: the client simply never receives the ack, keeps the
519
615
  update pending, and retransmits on its timer/reconnect. This is built for
520
616
  *transient* failures (the store is briefly down → a retry lands). A block that
521
- raises *deterministically* a validation that always fails for this edit
617
+ raises *deterministically* (a validation that always fails for this edit)
522
618
  will be retried forever, since nothing tells the client to stop. Enforce hard
523
619
  rejections before the edit reaches `on_change` (channel authorization in
524
620
  `subscribed`), not by raising inside it.
525
621
  - **An over-cap frame is dropped the same silent way.** A frame larger than
526
- `max_frame_bytes` (default 8 MiB) is dropped before decoding no ack, no
527
- 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
528
624
  update that means the same implicit rejection as above: unacked, retransmitted
529
625
  forever. Normal typing never approaches the cap, but a large paste, an embedded
530
626
  image, or a big initial `SyncStep2` can. The drop is logged (`warn` for
@@ -534,6 +630,85 @@ servers:
534
630
  genuinely-too-big content upstream rather than relying on the cap to reject it
535
631
  gracefully.
536
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
+
537
712
  #### Multi-process deployments
538
713
 
539
714
  Most Rails apps run several processes, and any of them might serve a given document.
@@ -571,7 +746,7 @@ It is up to you to durably record it:
571
746
 
572
747
  ```ruby
573
748
  class DocumentChannel < ApplicationCable::Channel
574
- include Y::ActionCable::Sync
749
+ include Y::ActionCable
575
750
 
576
751
  # ...
577
752
 
@@ -593,12 +768,86 @@ duplicate record replays to the same document.
593
768
  The demo wires `on_change` to a durable Postgres-backed log by default, and checks
594
769
  end to end that the log alone rebuilds the document.
595
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
+
596
845
  #### Reliable delivery (acks)
597
846
 
598
847
  yrby document delivery is ack-tracked. Browser document updates carry an
599
- `"id"`, and the server replies `{ "ack": <id> }` once `on_change` has succesfully fired.
600
- A causally-gapped update is not acked; the server sends a resync request, and
601
- 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.
602
851
 
603
852
  ```
604
853
  client -> server { "update": "<base64 update>", "id": 42 }
@@ -612,13 +861,13 @@ one `{ ack: id }` cumulatively confirms everything up to it. Because CRDT apply
612
861
  is idempotent, a resend that already landed is a harmless no-op that just
613
862
  re-acks. Awareness stays ephemeral and is not acked.
614
863
 
615
- Presence (cursors, selections) is owned by the browser clients the server
864
+ Presence (cursors, selections) is owned by the browser clients; the server
616
865
  never sets or holds presence state, it only relays awareness frames opaquely.
617
866
  See `yrby-client` for the client-side awareness API.
618
867
 
619
868
  ## Thread Safety
620
869
 
621
- 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
622
871
  workers, ActionCable connection threads, or background jobs without external
623
872
  locking.
624
873