yrby 0.6.1 → 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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: ba28bef094ec97908a5ce4b01a61aedbbbcd49585c88a47acfbcfe0dab02c5be
4
- data.tar.gz: dae39a894e92836681c0aa73dc54201aecf1d3fa68eaac38496e420579d760b3
3
+ metadata.gz: c7e0200b53061315ddc075bbd337a5d9ead543f99617cac94d53180242a80bbd
4
+ data.tar.gz: 956ec491daabcafc73009e40df573e9c01e5b7587be9d3001d32a7b0a4092f01
5
5
  SHA512:
6
- metadata.gz: de4dedd7b4eb4e14e343b83b20007587cd129cbc0f42ff03f21118043ebced3853b9a2e2c51e77688ba1b8665e058422e24d1cc18d7acfd85fd6c99e435b43b9
7
- data.tar.gz: 93291be948f34edc50c98266e554bd41a2beb7f8e74b1aeab87b19dc41efed425603f0634cefd117f24077b7d4fecf967b3ff4e40614b2276f2ccb40e85b5dc6
6
+ metadata.gz: afae1336b4e184f1ecf1d878202023123cee10fa7ea47642c7f6f2b7d48eee7201f2b2198aed217b08434228904178bddaf3d46058e6da7b5b27ad7450a0ef87
7
+ data.tar.gz: 48a7bd917201e4df0858a08ce0d1eab132fc160a507dc88bfcd1c390cae9a0a8b11a9132894e5f91889f946f69e4366455fb8257e0165c9f1d82da4c367547ed
data/CHANGELOG.md CHANGED
@@ -4,6 +4,39 @@ All notable changes to this project are documented here. The format is based on
4
4
  [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project aims
5
5
  to follow [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
6
 
7
+ ## [0.7.0] - 2026-08-11
8
+
9
+ ### Added
10
+
11
+ - `Y::Decoder` ships in the core gem and loads with `require "y"`. It was
12
+ scaffolded as a separate `yrby-decoder` gem, but it is 66 lines of pure
13
+ Ruby over `Doc#read_text` / `read_xml`, requires the native core either
14
+ way, and the separate gem was never published, so the split left the
15
+ module in no gem at all. The `yrby-decoder` name is retired unused.
16
+
17
+ ### Changed
18
+
19
+ - `Doc#handle_sync_message` answers a SyncStep1 with the doc's full state,
20
+ pending included, matching Y.js's `encodeStateAsUpdate`. It previously
21
+ served integrated-only state. A peer parks a served pending struct the
22
+ same way the doc did and heals it when the missing dependency arrives
23
+ from its sender's ack-driven retransmit. `compacted_state_update` still
24
+ excludes pending, so compaction cannot freeze a gap into a snapshot.
25
+
26
+ ### Fixed
27
+
28
+ - **`Doc#update_advances?` no longer misreads a gappy merged update carrying
29
+ novel content as a no-op.** A crafted frame can hide an internal gap behind
30
+ a Skip block while its post-gap blocks still integrate (yrs plants a Skip
31
+ hole in the store). That moves neither the doc's public state vector nor
32
+ pending, so the probe comparison reported genuinely novel content as
33
+ "doesn't advance"; `update_ready?` accepted the frame and the doc applied
34
+ it, but it was never recorded to the durable log or broadcast. Any
35
+ insertion past the update's own (Skip-capped) `state_vector()` now
36
+ conservatively reports as advancing. Not reachable through standard Yjs
37
+ providers (a client's own updates and diffs are gap-free), so this closes
38
+ a hostile-input hole, not a real-world regression.
39
+
7
40
  ## [0.6.1] - 2026-08-04
8
41
 
9
42
  ### Fixed
@@ -21,16 +54,16 @@ to follow [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
21
54
  ### Added
22
55
 
23
56
  - **Custom render rules for `Y::Lexical` and `Y::ProseMirror`.** Both
24
- renderers now take a block registering rules per node type
57
+ renderers now take a block registering rules per node type:
25
58
  `rules.node "callout", tag: "aside"` for markup-as-data, a Ruby block for
26
- logic plus `nodes:`/`marks:` keywords as the equivalent data form, to
59
+ logic, plus `nodes:`/`marks:` keywords as the equivalent data form, to
27
60
  render node types the pinned schemas don't know or to override how a
28
61
  built-in renders.
29
62
  Declarative rules (`tag`/`attrs`/`text`/`contains`, with templates mixing
30
63
  literals and attribute references) render natively at full speed. Callback
31
64
  rules run a Ruby block per node, receiving its type, attributes,
32
65
  already-rendered children, and `child_types` (its element/block children by
33
- type the structural facts behind gallery counts and nested-list classes).
66
+ type, the structural facts behind gallery counts and nested-list classes).
34
67
  The block runs after the document read has finished, never while the doc is
35
68
  locked, so it can safely read or write the same doc. Blocks are proven
36
69
  sufficient for whole schemas: the gem's own editor schemas (`Y::Lexxy`,
@@ -38,13 +71,13 @@ to follow [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
38
71
  output byte-identical to a live editor's. With no callback rules the
39
72
  render path is unchanged, byte for byte. See "Custom nodes and marks" in
40
73
  the README.
41
- - **`Y::Lexical#node_types` / `Y::ProseMirror#node_types` schema
74
+ - **`Y::Lexical#node_types` / `Y::ProseMirror#node_types`: schema
42
75
  discovery.** Ask a real document which node types it holds and what they
43
76
  look like: counts, attribute names as stored, child types, whether text
44
77
  runs appear, and whether a builtin or one of your rules already handles
45
78
  each ("handled" nil marks what still needs a rule). Editors store names
46
79
  you'd never guess; this is how you find them.
47
- - `Y::RenderRules.escape_text` / `escape_attr` the exact escaping the
80
+ - `Y::RenderRules.escape_text` / `escape_attr`: the exact escaping the
48
81
  native renderers use, for blocks that build markup from stored values
49
82
  (ERB's `html_escape` also rewrites apostrophes, which breaks byte parity
50
83
  with editor output).
@@ -54,15 +87,15 @@ to follow [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
54
87
  - **Lexical rendering is now two classes: `Y::Lexical` (core Lexical) and
55
88
  `Y::Lexxy` (core plus the Lexxy schema as render rules).** Stock Lexical
56
89
  has no canonical serializer, so the editor-specific class carries the
57
- editor's name `Y::Lexxy.new(doc).to_html` is the byte-parity call for
90
+ editor's name; `Y::Lexxy.new(doc).to_html` is the byte-parity call for
58
91
  Lexxy/Rails apps, and `Y::Lexical` is the base any other Lexical editor
59
92
  extends with its own rules. The
60
- native side renders core structure paragraphs, headings, quotes, code,
93
+ native side renders core structure (paragraphs, headings, quotes, code,
61
94
  lists, tables, links, the full text-format model. Lexxy's own node types
62
95
  (attachments, galleries, `early_escape_code`, `horizontal_divider`) and its
63
96
  decorations of core nodes (the table figure wrapper, header-cell styling,
64
97
  the nested-list-item class) are rules applied beneath the app's, on the
65
- same extension API the gem's Lexxy support is the API's first consumer.
98
+ same extension API; the gem's Lexxy support is the API's first consumer.
66
99
  Output is unchanged: the fixture tests still hold `to_html` byte-identical
67
100
  to a live editor's serialized value, now through the extension path. An
68
101
  unknown Lexical container also degrades better: its block children render
@@ -71,8 +104,8 @@ to follow [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
71
104
  ProseMirror) and `Y::Tiptap` (core plus Tiptap's extension nodes as render
72
105
  rules).** `Y::Tiptap.new(doc).to_html` is the byte-parity call for Tiptap
73
106
  apps. The native side renders prosemirror-schema-basic plus the
74
- prosemirror-tables family; Tiptap's extension nodes task lists, mentions,
75
- the details family are `Y::Tiptap::NODES` rules. Marks stay native in the
107
+ prosemirror-tables family; Tiptap's extension nodes (task lists, mentions,
108
+ the details family) are `Y::Tiptap::NODES` rules. Marks stay native in the
76
109
  base class: mark rendering (nesting order, `textStyle` CSS, `code`
77
110
  exclusivity) runs through text-run machinery node rules don't reach, so
78
111
  `Y::ProseMirror` still renders Tiptap's full mark set and `rules.mark`
@@ -83,7 +116,7 @@ to follow [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
83
116
 
84
117
  ### Added
85
118
 
86
- - **`Y::Lexical` render Lexical/Lexxy documents to HTML.**
119
+ - **`Y::Lexical`: render Lexical/Lexxy documents to HTML.**
87
120
  `Y::Lexical.new(doc).to_html` turns a Lexxy document into HTML on the server,
88
121
  with no Node process or headless editor. The output is identical to the HTML
89
122
  a `lexxy-editor` submits to Rails; the tests check it byte-for-byte against a
@@ -101,12 +134,12 @@ to follow [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
101
134
 
102
135
  ### Added
103
136
 
104
- - **`Y::ProseMirror` render ProseMirror/Tiptap documents to HTML.**
137
+ - **`Y::ProseMirror`: render ProseMirror/Tiptap documents to HTML.**
105
138
  `Y::ProseMirror.new(doc).to_html` turns a Tiptap document into HTML on the
106
139
  server, with no Node process or headless editor. The output matches Tiptap's
107
140
  own `getHTML()`; the tests check it byte-for-byte against a document captured
108
141
  from a real editor. It follows `ueberdosis/tiptap-php` and reads both name
109
- styles editors use Tiptap's `bulletList`/`bold` and prosemirror-schema-basic's
142
+ styles editors use: Tiptap's `bulletList`/`bold` and prosemirror-schema-basic's
110
143
  `bullet_list`/`strong`. Covers paragraphs, headings, blockquotes,
111
144
  bullet/ordered/task lists, code blocks, links, images, mentions, details,
112
145
  hard breaks, horizontal rules, tables, text styles (color, font family), and
@@ -122,8 +155,8 @@ Fixes from a full source review.
122
155
 
123
156
  - **`Doc#update_ready?` is now exact.** It previously checked only the
124
157
  per-client clock lower bound, but yrs's real integration gate also requires
125
- every block referenced by an item's origin / right-origin / parent which
126
- routinely belong to *other* clients and post-Skip blocks in a merged update
158
+ every block referenced by an item's origin / right-origin / parent (which
159
+ routinely belong to *other* clients) and post-Skip blocks in a merged update
127
160
  sit above the lower bound. An update could pass the clock check yet park as
128
161
  pending; downstream, `update_advances?` then misread the parked update as an
129
162
  already-applied retry (pending doesn't move a state vector) and the sync
@@ -147,7 +180,7 @@ Fixes from a full source review.
147
180
  ### Changed
148
181
 
149
182
  - `update_advances?` skips its full-document probe when the update carries
150
- blocks beyond the doc's state vector (a novel update trivially advances)
183
+ blocks beyond the doc's state vector (a novel update trivially advances);
151
184
  the common case no longer pays O(doc) per frame.
152
185
  - The gem no longer packages the `yrby-decoder` gem's files (they ship in that
153
186
  gem; the duplicate copy could shadow a newer standalone release), and now
@@ -158,7 +191,7 @@ Fixes from a full source review.
158
191
  ### Fixed
159
192
 
160
193
  - **Sync no longer serves un-integrable pending structs.** When a doc holds a
161
- *pending* struct (a gappy update whose causally-prior update is missing e.g.
194
+ *pending* struct (a gappy update whose causally-prior update is missing, e.g.
162
195
  legacy data recorded before the `update_ready?` gate existed), its integrated
163
196
  state vector is empty but `encode_state_as_update` merges the pending bytes back
164
197
  in. Answering a peer's `SyncStep1` with that state handed the peer content it
@@ -166,18 +199,18 @@ Fixes from a full source review.
166
199
  non-empty-content mismatch drove endless resync traffic (observed as a browser
167
200
  re-sending frames several times a second). `handle_sync_message` now answers
168
201
  `SyncStep1` with **integrated-only** state, so a server never serves a struct it
169
- can't integrate itself. Neutralizes existing poisoned server state on deploy
202
+ can't integrate itself. Neutralizes existing poisoned server state on deploy;
170
203
  no migration needed. The server's own pending is untouched and still heals if
171
204
  the missing dependency later arrives (only then does the content become
172
205
  visible in sync). Live delta relay (`Update` frames) is unchanged.
173
206
 
174
207
  ### Added
175
208
 
176
- - `Doc#pending?` true if the doc holds un-integrable pending structs or a
209
+ - `Doc#pending?`: true if the doc holds un-integrable pending structs or a
177
210
  pending delete set (content waiting on a missing causally-prior update).
178
- - `Doc#compacted_state_update` like `encode_state_as_update` (full state) but
211
+ - `Doc#compacted_state_update`: like `encode_state_as_update` (full state) but
179
212
  **gap-free**: excludes pending structs/delete set. Use it when persisting or
180
- serving state other peers will apply. Non-destructive the doc keeps its
213
+ serving state other peers will apply. Non-destructive; the doc keeps its
181
214
  pending (so it can still heal), and `encode_state_as_update` stays lossless for
182
215
  raw-update recovery.
183
216
 
@@ -195,13 +228,13 @@ Fixes from a full source review.
195
228
  before vs. after a trial apply on an isolated probe: a genuinely new deletion
196
229
  changes it (`true`); an already-applied retry re-encodes identically (`false`).
197
230
  Insert/format-only updates keep the cheaper state-vector path, so only
198
- delete-bearing frames a minority pay for the exact comparison. The exactly-
231
+ delete-bearing frames (a minority) pay for the exact comparison. The exactly-
199
232
  once guarantee is unchanged in the safe direction: a real deletion is never
200
233
  dropped.
201
234
 
202
235
  This lets `yrby-actioncable` (and any caller gating `on_change` on
203
- `update_advances?`) settle a duplicate pure-delete frame as `:applied` acked,
204
- but not stored or relayed so apps no longer need an app-level
236
+ `update_advances?`) settle a duplicate pure-delete frame as `:applied` (acked,
237
+ but not stored or relayed), so apps no longer need an app-level
205
238
  encode-and-compare guard around their durable writes.
206
239
 
207
240
  ## [0.2.2] - 2026-06-30
@@ -212,7 +245,7 @@ Fixes from a full source review.
212
245
  embeds child blocks (list items, table cells, nested lists) as `Y.XmlText`
213
246
  embeds that `get_string` silently drops, so lists and tables previously came
214
247
  back empty. `read_xml` now walks the embeds: text runs build a line, inline
215
- children (links) join it, and nested block children flush and recurse so a
248
+ children (links) join it, and nested block children flush and recurse, so a
216
249
  document with headings, formatted text, links, bullet/numbered/check/nested
217
250
  lists, blockquotes, code blocks and tables extracts every piece of text.
218
251
  Lexical decorator elements (horizontal rule, image) are skipped instead of
@@ -223,17 +256,17 @@ Fixes from a full source review.
223
256
 
224
257
  ### Changed
225
258
  - **Internal:** renamed the native extension crate `y_ruby` → `yrby` (now loads
226
- from `lib/y/yrby.bundle`). No public API change `require "y"` and `Y::Doc`
259
+ from `lib/y/yrby.bundle`). No public API change: `require "y"` and `Y::Doc`
227
260
  are unchanged.
228
261
 
229
262
  ## [0.2.0] - 2026-06-28
230
263
 
231
264
  First release. The public Ruby interface is the top-level module **`Y`**
232
- (`Y::Doc`, `Y::Error`, `Y::VERSION`), loaded with `require "y"` mirroring the
265
+ (`Y::Doc`, `Y::Error`, `Y::VERSION`), loaded with `require "y"`, mirroring the
233
266
  `y-rb` gem's `Y::Doc` interface.
234
267
 
235
268
  ### Added
236
- - Native `Doc#read_text` and `Doc#read_map` readers reconstruct plain text and
269
+ - Native `Doc#read_text` and `Doc#read_map` readers: reconstruct plain text and
237
270
  a JSON map from the stored CRDT state in-process, server-side, with no Node or
238
271
  subprocess.
239
272
 
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
 
data/ext/yrby/src/lib.rs CHANGED
@@ -297,13 +297,13 @@ impl RbDoc {
297
297
  match msg {
298
298
  Message::Sync(sync_msg) => match sync_msg {
299
299
  SyncMessage::SyncStep1(sv) => {
300
- // Respond with SyncStep2 carrying only *integrated*
301
- // state. Never hand a peer un-integrable pending
302
- // structs: the peer would park the same pending
303
- // forever and the state-vector/content mismatch drives
304
- // endless resync traffic. (integrated_update is a no-op
305
- // fast path when nothing is pending.)
306
- let update = integrated_update(doc, &sv)?;
300
+ // Respond with SyncStep2 carrying the doc's full
301
+ // state, pending included, matching Y.js's
302
+ // encodeStateAsUpdate. A peer parks a pending
303
+ // struct exactly as this doc does and heals it
304
+ // when the missing dependency arrives.
305
+ let txn = doc.transact();
306
+ let update = txn.encode_state_as_update_v1(&sv);
307
307
  let response = Message::Sync(SyncMessage::SyncStep2(update));
308
308
  Ok((0, 0, response.encode_v1()))
309
309
  }
@@ -135,6 +135,27 @@ pub(crate) fn update_advances_doc(doc: &Doc, update_bytes: &[u8]) -> Result<bool
135
135
  let update = yrs::Update::decode_v1(update_bytes).map_err(|e| e.to_string())?;
136
136
  let has_deletes = !update.delete_set().is_empty();
137
137
 
138
+ // A merged update can hide an internal gap behind a Skip block, and
139
+ // blocks past the gap can still integrate (yrs plants a Skip hole in the
140
+ // store) when their origins don't need the missing range. That moves
141
+ // neither the doc's public state vector (yrs caps it at the first hole)
142
+ // nor pending: invisible to every comparison below, so genuinely novel
143
+ // content would report "doesn't advance": applied, acked, but never
144
+ // recorded or broadcast. The update's own state_vector() caps at its
145
+ // first Skip the same way, so any insertion past a non-zero cap reveals
146
+ // such a gap: conservatively report it as advancing (record it; a
147
+ // duplicate in the log is harmless, dropped content is not). Standard
148
+ // Yjs providers never emit these frames (a client's own updates and
149
+ // diffs are gap-free), so this guards crafted or pathologically merged
150
+ // input, not a hot path.
151
+ let capped = update.state_vector();
152
+ for (client, ranges) in update.insertions(true).iter() {
153
+ let cap = capped.get(client);
154
+ if cap > 0 && ranges.iter().any(|range| range.end > cap) {
155
+ return Ok(true);
156
+ }
157
+ }
158
+
138
159
  // Fast path: blocks beyond the doc's state vector are content the doc
139
160
  // lacks — the update advances, no probe needed. The common case (a novel
140
161
  // edit) exits here; only retries and ambiguous diffs pay for the probe.
@@ -663,6 +684,48 @@ mod tests {
663
684
  );
664
685
  }
665
686
 
687
+ #[test]
688
+ fn a_gappy_update_with_novel_post_hole_content_advances() {
689
+ // A merged update hiding an internal gap behind a Skip, whose
690
+ // post-hole blocks integrate anyway (their origins don't need the
691
+ // missing range). Integration plants a Skip hole, so neither the
692
+ // public state vector nor pending moves, before the hidden-gap
693
+ // check, the probe comparison reported genuinely novel content as
694
+ // "doesn't advance": update_ready? accepted it, the doc applied it,
695
+ // but it was never recorded or broadcast. Unreachable through
696
+ // standard Yjs providers (a client's own updates and diffs are
697
+ // gap-free); this is a crafted/hostile frame shape.
698
+ let a = Doc::new();
699
+ let t1 = a.get_or_insert_text("one");
700
+ t1.insert(&mut a.transact_mut(), 0, "first");
701
+ let u1 = a
702
+ .transact()
703
+ .encode_state_as_update_v1(&yrs::StateVector::default());
704
+ t1.insert(&mut a.transact_mut(), 5, " second"); // the future hole
705
+ let sv2 = a.transact().state_vector();
706
+ // Novel content on a DIFFERENT root: no dependency on the hole.
707
+ let t3 = a.get_or_insert_text("two");
708
+ t3.insert(&mut a.transact_mut(), 0, "third");
709
+ let u3 = a.transact().encode_state_as_update_v1(&sv2);
710
+
711
+ let server = Doc::new();
712
+ server
713
+ .transact_mut()
714
+ .apply_update(yrs::Update::decode_v1(&u1).unwrap())
715
+ .unwrap();
716
+ // The crafted frame: u1 + u3 merged, u2's range an internal Skip.
717
+ let gappy = yrs::merge_updates_v1([&u1, &u3]).unwrap();
718
+
719
+ assert!(
720
+ update_is_ready(&server, &gappy).unwrap(),
721
+ "sanity: the sync flow would accept and apply this frame"
722
+ );
723
+ assert!(
724
+ update_advances_doc(&server, &gappy).unwrap(),
725
+ "novel content hiding behind a Skip must be recorded, not dropped"
726
+ );
727
+ }
728
+
666
729
  // Build a causal gap: `first` inserts "a", `dependent` inserts "b" after it,
667
730
  // so `dependent` alone parks as pending on a doc that lacks `first`.
668
731
  fn gap_pair() -> (Vec<u8>, Vec<u8>) {
@@ -29,7 +29,7 @@ class DocumentChannel < ApplicationCable::Channel
29
29
  # Everyone is denied until you fill this in. Wire it to your app's auth:
30
30
  # identify current_user on the cable connection, then check they may read
31
31
  # and write this document. Don't lean on on_change raising for access
32
- # control that path exists for store failures.
32
+ # control; that path exists for store failures.
33
33
  def authorized?(_document_key)
34
34
  false
35
35
  end
@@ -5,15 +5,15 @@ require "rails/generators/active_record"
5
5
 
6
6
  module Yrby
7
7
  module Generators
8
- # `bin/rails generate yrby:tables` the migration for the gem-owned
8
+ # `bin/rails generate yrby:tables`: the migration for the gem-owned
9
9
  # document models (Y::Document + Y::DocumentUpdate). Invoked by
10
10
  # yrby:install, and by other gems building on the same storage.
11
11
  #
12
12
  # Template notes (kept here, not in the emitted migration): state is
13
- # 4.gigabytes - 1 (longblob on MySQL a compacted snapshot is the whole
13
+ # 4.gigabytes - 1 (longblob on MySQL; a compacted snapshot is the whole
14
14
  # document; a 16 MB cap would break compaction) and payload is
15
15
  # 16.megabytes - 1 (one update can carry a big paste or a client's
16
- # accumulated offline edits the 64 KB default blob is too small).
16
+ # accumulated offline edits; the 64 KB default blob is too small).
17
17
  # The partial unique index's WHERE only keeps
18
18
  # key-only rows out of the index: uniqueness holds without it, since
19
19
  # unique indexes treat NULLs as distinct on every supported database,
data/lib/y/decoder.rb ADDED
@@ -0,0 +1,64 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "y"
4
+
5
+ module Y
6
+ # Plain-text reconstruction of a stored Yjs document, for search indexing
7
+ # and previews. It reads the text out of the shared type the editor uses
8
+ # (Lexical's `Y.XmlText`, plain `Y.Text`, or ProseMirror's `Y.XmlFragment`)
9
+ # in-process, on the same native extension as `Doc`: no Node, no
10
+ # subprocess.
11
+ #
12
+ # state = doc.encode_state_as_update # opaque CRDT bytes from the store
13
+ # Y::Decoder.text(state) # => "hello world"
14
+ # Y::Decoder.preview(state, 280) # => "hello world…"
15
+ #
16
+ # For full-fidelity HTML, `Y::Lexxy` and `Y::Tiptap` render the document
17
+ # with the editor's own semantics; this module is the cheap plain-text
18
+ # path.
19
+ module Decoder
20
+ class Error < Y::Error; end
21
+
22
+ module_function
23
+
24
+ # Plain text of the document. `field` pins the root key (Lexical: the editor
25
+ # id; ProseMirror: "default"); omit it to use the document's sole root.
26
+ def text(state, field: nil)
27
+ field ||= Y::Doc.new.tap { |d| d.apply_update(state) }.root_names.first
28
+ return "" unless field
29
+
30
+ # A plain `Y.Text` root (a simple shared-text editor) reads straight out.
31
+ # (A yrs root's type is fixed by its first typed access, so each reader
32
+ # gets a fresh doc to try a different shared type against the same state.)
33
+ direct = load(state).read_text(field)
34
+ return normalize(direct) if direct && !direct.strip.empty?
35
+
36
+ # Lexical (each block a sibling `Y.XmlText`) and ProseMirror (blocks are
37
+ # `Y.XmlElement`s) both come back from read_xml as block-per-line markup;
38
+ # strip any element tags to plain text.
39
+ markup = load(state).read_xml(field)
40
+ markup ? normalize(strip_tags(markup)) : ""
41
+ end
42
+
43
+ # A compact, single-line preview for list UIs.
44
+ def preview(state, limit: 280, field: nil)
45
+ body = text(state, field: field).gsub(/\s+/, " ").strip
46
+ body.length > limit ? "#{body[0, limit].rstrip}…" : body
47
+ end
48
+
49
+ def load(state)
50
+ Y::Doc.new.tap { |doc| doc.apply_update(state) }
51
+ end
52
+
53
+ def strip_tags(markup)
54
+ markup.gsub(/<[^>]*>/, " ")
55
+ end
56
+
57
+ def normalize(text)
58
+ text.gsub(/[ \t]+/, " ") # collapse runs of spaces/tabs
59
+ .gsub(/ *\n */, "\n") # trim spaces left around block separators
60
+ .gsub(/\n{3,}/, "\n\n") # cap blank-line runs
61
+ .strip
62
+ end
63
+ end
64
+ end
data/lib/y/version.rb CHANGED
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Y
4
- VERSION = "0.6.1"
4
+ VERSION = "0.7.0"
5
5
  end
data/lib/y.rb CHANGED
@@ -15,6 +15,7 @@ end
15
15
  require_relative "y/rendering"
16
16
  require_relative "y/lexxy"
17
17
  require_relative "y/tiptap"
18
+ require_relative "y/decoder"
18
19
 
19
20
  module Y
20
21
  # Doc, Error, and the protocol module functions are defined in the Rust
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: yrby
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.6.1
4
+ version: 0.7.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - JP Camara
@@ -105,6 +105,7 @@ files:
105
105
  - lib/generators/yrby/tables/tables_generator.rb
106
106
  - lib/generators/yrby/tables/templates/create_y_tables.rb
107
107
  - lib/y.rb
108
+ - lib/y/decoder.rb
108
109
  - lib/y/lexxy.rb
109
110
  - lib/y/rendering.rb
110
111
  - lib/y/tiptap.rb