yrby 0.9.0 → 0.10.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.
@@ -23,8 +23,8 @@ use crate::nogvl;
23
23
  use crate::shared::{
24
24
  any_to_ruby, block_text, char_len, delete_span, element_index, embedded_xml_text_index,
25
25
  embedded_xml_texts, end_or_units, ends_with_xml_text, guarded, hash_pairs, identity,
26
- insert_index, resolve, ruby_to_invalue, to_in, to_map_prelim, to_units, InValue, Position,
27
- MAX_NESTING, ORIGIN,
26
+ insert_index, resolve, ruby_to_invalue, to_in, to_map_prelim, to_units, write, InValue,
27
+ Position, MAX_NESTING,
28
28
  };
29
29
  use crate::yrb_error;
30
30
 
@@ -166,10 +166,9 @@ impl RbXmlText {
166
166
  let ruby = Ruby::get().map_err(|e| yrb_error(e.to_string()))?;
167
167
  let iv = ruby_to_invalue(&ruby, value)?;
168
168
  let (doc, id) = (&self.doc, &self.id);
169
- guarded(move || {
170
- let mut txn = doc.transact_mut_with(ORIGIN);
171
- let x = resolve::<XmlTextRef, _>(&txn, id).ok_or("the block no longer exists")?;
172
- x.insert_attribute(&mut txn, key, to_in(iv));
169
+ write(doc, move |txn| {
170
+ let x = resolve::<XmlTextRef, _>(txn, id).ok_or("the block no longer exists")?;
171
+ x.insert_attribute(txn, key, to_in(iv));
173
172
  Ok(())
174
173
  })?;
175
174
  Ok(value)
@@ -180,11 +179,10 @@ impl RbXmlText {
180
179
  fn insert(&self, index: i64, chunk: String) -> Result<String, Error> {
181
180
  let (doc, id) = (&self.doc, &self.id);
182
181
  let text = chunk.clone();
183
- guarded(move || {
184
- let mut txn = doc.transact_mut_with(ORIGIN);
185
- let x = resolve::<XmlTextRef, _>(&txn, id).ok_or("the block no longer exists")?;
186
- let at = end_or_units(&txn, &x, index);
187
- x.insert(&mut txn, at, &text);
182
+ write(doc, move |txn| {
183
+ let x = resolve::<XmlTextRef, _>(txn, id).ok_or("the block no longer exists")?;
184
+ let at = end_or_units(txn, &x, index);
185
+ x.insert(txn, at, &text);
188
186
  Ok(())
189
187
  })?;
190
188
  Ok(chunk)
@@ -198,16 +196,15 @@ impl RbXmlText {
198
196
  let ruby = Ruby::get().map_err(|e| yrb_error(e.to_string()))?;
199
197
  let iv = ruby_to_invalue(&ruby, value)?;
200
198
  let (doc, id) = (&self.doc, &self.id);
201
- guarded(move || {
202
- let mut txn = doc.transact_mut_with(ORIGIN);
203
- let x = resolve::<XmlTextRef, _>(&txn, id).ok_or("the block no longer exists")?;
204
- let at = to_units(&txn, &x, insert_index(index, char_len(&txn, &x)));
199
+ write(doc, move |txn| {
200
+ let x = resolve::<XmlTextRef, _>(txn, id).ok_or("the block no longer exists")?;
201
+ let at = to_units(txn, &x, insert_index(index, char_len(txn, &x)));
205
202
  match iv {
206
203
  InValue::Map(entries) => {
207
- x.insert_embed(&mut txn, at, to_map_prelim(entries));
204
+ x.insert_embed(txn, at, to_map_prelim(entries));
208
205
  }
209
206
  InValue::Any(a) => {
210
- x.insert_embed(&mut txn, at, a);
207
+ x.insert_embed(txn, at, a);
211
208
  }
212
209
  }
213
210
  Ok(())
@@ -263,13 +260,12 @@ impl RbXmlText {
263
260
  /// negative index counts from the end, and the length stops at the end.
264
261
  fn delete(&self, index: i64, length: i64) -> Result<(), Error> {
265
262
  let (doc, id) = (&self.doc, &self.id);
266
- guarded(move || {
267
- let mut txn = doc.transact_mut_with(ORIGIN);
268
- let x = resolve::<XmlTextRef, _>(&txn, id).ok_or("the block no longer exists")?;
269
- if let Some((from, to)) = delete_span(index, length, char_len(&txn, &x)) {
270
- let (from, to) = (to_units(&txn, &x, from), to_units(&txn, &x, to));
263
+ write(doc, move |txn| {
264
+ let x = resolve::<XmlTextRef, _>(txn, id).ok_or("the block no longer exists")?;
265
+ if let Some((from, to)) = delete_span(index, length, char_len(txn, &x)) {
266
+ let (from, to) = (to_units(txn, &x, from), to_units(txn, &x, to));
271
267
  if to > from {
272
- x.remove_range(&mut txn, from, to - from);
268
+ x.remove_range(txn, from, to - from);
273
269
  }
274
270
  }
275
271
  Ok(())
@@ -279,12 +275,11 @@ impl RbXmlText {
279
275
  /// Remove everything: markers, text, and embedded blocks.
280
276
  fn clear(&self) -> Result<(), Error> {
281
277
  let (doc, id) = (&self.doc, &self.id);
282
- guarded(move || {
283
- let mut txn = doc.transact_mut_with(ORIGIN);
284
- let x = resolve::<XmlTextRef, _>(&txn, id).ok_or("the block no longer exists")?;
285
- let len = x.len(&txn);
278
+ write(doc, move |txn| {
279
+ let x = resolve::<XmlTextRef, _>(txn, id).ok_or("the block no longer exists")?;
280
+ let len = x.len(txn);
286
281
  if len > 0 {
287
- x.remove_range(&mut txn, 0, len);
282
+ x.remove_range(txn, 0, len);
288
283
  }
289
284
  Ok(())
290
285
  })
@@ -300,13 +295,12 @@ impl RbXmlText {
300
295
  let attributes = hash_pairs(&ruby, attributes)?;
301
296
  let content = Piece::read_all(&ruby, content, 0)?;
302
297
  let (doc, id) = (&self.doc, &self.id);
303
- let block = guarded(move || {
304
- let mut txn = doc.transact_mut_with(ORIGIN);
305
- let x = resolve::<XmlTextRef, _>(&txn, id).ok_or("the block no longer exists")?;
306
- let count = embedded_xml_texts(&txn, &x).len() as u32;
298
+ let block = write(doc, move |txn| {
299
+ let x = resolve::<XmlTextRef, _>(txn, id).ok_or("the block no longer exists")?;
300
+ let count = embedded_xml_texts(txn, &x).len() as u32;
307
301
  let ordinal = insert_index(n, count);
308
- let at = embedded_xml_text_index(&txn, &x, ordinal).unwrap_or_else(|| x.len(&txn));
309
- let child = Piece::Block(attributes, content).write(&mut txn, &x, at);
302
+ let at = embedded_xml_text_index(txn, &x, ordinal).unwrap_or_else(|| x.len(txn));
303
+ let child = Piece::Block(attributes, content).write(txn, &x, at);
310
304
  // The block's identity, not the block: see `Child`.
311
305
  Ok(identity(&child.expect("a block piece writes a block")))
312
306
  })?;
@@ -331,19 +325,18 @@ impl RbXmlText {
331
325
  let ruby = Ruby::get().map_err(|e| yrb_error(e.to_string()))?;
332
326
  let content = Piece::read_all(&ruby, content, 0)?;
333
327
  let (doc, id) = (&self.doc, &self.id);
334
- guarded(move || {
335
- let mut txn = doc.transact_mut_with(ORIGIN);
336
- let x = resolve::<XmlTextRef, _>(&txn, id).ok_or("the block no longer exists")?;
328
+ write(doc, move |txn| {
329
+ let x = resolve::<XmlTextRef, _>(txn, id).ok_or("the block no longer exists")?;
337
330
  if clear {
338
- let len = x.len(&txn);
331
+ let len = x.len(txn);
339
332
  if len > 0 {
340
- x.remove_range(&mut txn, 0, len);
333
+ x.remove_range(txn, 0, len);
341
334
  }
342
335
  }
343
- let mut at = x.len(&txn);
336
+ let mut at = x.len(txn);
344
337
  for piece in content {
345
- piece.write(&mut txn, &x, at);
346
- at = x.len(&txn);
338
+ piece.write(txn, &x, at);
339
+ at = x.len(txn);
347
340
  }
348
341
  Ok(())
349
342
  })
@@ -358,15 +351,14 @@ impl RbXmlText {
358
351
  let ruby = Ruby::get().map_err(|e| yrb_error(e.to_string()))?;
359
352
  let marker = hash_pairs(&ruby, marker)?;
360
353
  let (doc, id) = (&rb_self.doc, &rb_self.id);
361
- guarded(move || {
362
- let mut txn = doc.transact_mut_with(ORIGIN);
363
- let x = resolve::<XmlTextRef, _>(&txn, id).ok_or("the block no longer exists")?;
364
- let mut at = x.len(&txn);
365
- if at == 0 || ends_with_xml_text(&txn, &x) {
366
- x.insert_embed(&mut txn, at, to_map_prelim(marker));
354
+ write(doc, move |txn| {
355
+ let x = resolve::<XmlTextRef, _>(txn, id).ok_or("the block no longer exists")?;
356
+ let mut at = x.len(txn);
357
+ if at == 0 || ends_with_xml_text(txn, &x) {
358
+ x.insert_embed(txn, at, to_map_prelim(marker));
367
359
  at += 1;
368
360
  }
369
- x.insert(&mut txn, at, &text);
361
+ x.insert(txn, at, &text);
370
362
  Ok(())
371
363
  })?;
372
364
  Ok(rb_self)
@@ -376,16 +368,15 @@ impl RbXmlText {
376
368
  /// last). Returns whether there was one.
377
369
  fn delete_xml_text(&self, n: i64) -> Result<bool, Error> {
378
370
  let (doc, id) = (&self.doc, &self.id);
379
- guarded(move || {
380
- let mut txn = doc.transact_mut_with(ORIGIN);
381
- let x = resolve::<XmlTextRef, _>(&txn, id).ok_or("the block no longer exists")?;
382
- let count = embedded_xml_texts(&txn, &x).len() as u32;
371
+ write(doc, move |txn| {
372
+ let x = resolve::<XmlTextRef, _>(txn, id).ok_or("the block no longer exists")?;
373
+ let count = embedded_xml_texts(txn, &x).len() as u32;
383
374
  let Some(at) =
384
- element_index(n, count).and_then(|n| embedded_xml_text_index(&txn, &x, n))
375
+ element_index(n, count).and_then(|n| embedded_xml_text_index(txn, &x, n))
385
376
  else {
386
377
  return Ok(false);
387
378
  };
388
- x.remove_range(&mut txn, at, 1);
379
+ x.remove_range(txn, at, 1);
389
380
  Ok(true)
390
381
  })
391
382
  }
@@ -9,6 +9,7 @@ module Yrby
9
9
  # migration. The models and Y::DocumentChannel ship in the gem, so that is
10
10
  # the only file it generates by default. Pass --channel to also generate
11
11
  # an application channel for custom authorization or room-keyed documents.
12
+ # In an import-map app it also pins the JavaScript the gem ships.
12
13
  class InstallGenerator < ::Rails::Generators::Base
13
14
  source_root File.expand_path("templates", __dir__)
14
15
  class_option :channel, type: :boolean, default: false, desc: "Generate a custom DocumentChannel"
@@ -21,6 +22,39 @@ module Yrby
21
22
  invoke "yrby:tables"
22
23
  end
23
24
 
25
+ # Each shared module has one pin, so the page loads one copy of it:
26
+ #
27
+ # - yrby-client and yrby-client/element point at one file, so the page
28
+ # has one session store and one <yrby-document> class.
29
+ # - yjs is one copy, because Yjs checks constructors with instanceof.
30
+ # The app's editor binding imports it through this pin too.
31
+ # - @rails/actioncable is Rails' own file. <yrby-document> loads it for
32
+ # its default consumer.
33
+ #
34
+ # A pin the app already has is left alone, so re-running the generator
35
+ # adds only what is missing.
36
+ IMPORTMAP_PINS = {
37
+ "yrby-client" => "yrby/yrby-client.js",
38
+ "yrby-client/element" => "yrby/yrby-client.js",
39
+ "yjs" => "yrby/yjs.js",
40
+ "@rails/actioncable" => "actioncable.esm.js"
41
+ }.freeze
42
+
43
+ def add_importmap_pins
44
+ importmap = File.join(destination_root, "config/importmap.rb")
45
+ return unless File.exist?(importmap)
46
+
47
+ existing = File.read(importmap)
48
+ missing = IMPORTMAP_PINS.reject { |name, _| existing.match?(/^\s*pin\s+["']#{Regexp.escape(name)}["']/) }
49
+ return if missing.empty?
50
+
51
+ append_to_file "config/importmap.rb", <<~RUBY
52
+
53
+ # yrby. One pin per shared module, so the page loads one copy of each.
54
+ #{missing.map { |name, path| %(pin "#{name}", to: "#{path}") }.join("\n")}
55
+ RUBY
56
+ end
57
+
24
58
  def show_next_steps
25
59
  say <<~NEXT
26
60
 
@@ -32,9 +66,11 @@ module Yrby
32
66
 
33
67
  <%= collaborative_document_tag @post, :body %>
34
68
 
35
- 3. Install the yrby-client npm package. The tag renders an
36
- element that connects automatically. Once it syncs, your code
37
- gets the document and can bind it to any Yjs editor:
69
+ 3. Load yrby-client. With import maps, the generator added pins.
70
+ With a bundler, install the yrby-client and yjs npm packages.
71
+ The tag renders an element that connects automatically. Once
72
+ it syncs, your code gets the document and can bind it to any
73
+ Yjs editor:
38
74
 
39
75
  import "yrby-client/element"
40
76
 
data/lib/y/array.rb ADDED
@@ -0,0 +1,17 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Y
4
+ # Inside module Y, `Array` is this class.
5
+ class Array
6
+ # Insert a new Y.Text holding `content` at `index` and return a live
7
+ # Y::Text for it. Indexes work as in `insert`: -1 appends.
8
+ def insert_text(index, content = "")
9
+ native_insert_text(index, content)
10
+ end
11
+
12
+ # Append a new Y.Text holding `content` and return a live Y::Text for it.
13
+ def push_text(content = "")
14
+ insert_text(-1, content)
15
+ end
16
+ end
17
+ end
@@ -22,10 +22,10 @@ module Y
22
22
  # this to return before it acknowledges or broadcasts the change.
23
23
  def append(update) = document_row.append(update)
24
24
 
25
- # A signed grant for this document, what a page or a Ruby client
26
- # subscribes with. It's a signed GlobalID scoped to this attribute, and
27
- # Y::Collaborative.locate turns it back into the record. Pass
28
- # expires_in: to limit how long it lasts. Without it GlobalID's own
25
+ # A signed grant for this document, what a page, a Ruby client, or a
26
+ # Y::Collaborator subscribes with. It's a signed GlobalID scoped to this
27
+ # attribute, and Y::Collaborative.locate turns it back into the record.
28
+ # Pass expires_in: to limit how long it lasts. Without it GlobalID's own
29
29
  # default applies, which is one month under Rails. The option goes
30
30
  # through only when it's given, because an explicit nil would mean
31
31
  # "never expire".
@@ -35,15 +35,16 @@ module Y
35
35
  record.to_sgid(**options).to_s
36
36
  end
37
37
 
38
- # The channel that accepts this document's grant. A gem with its own
39
- # grants and channel, such as lexxy-realtime, returns its own document
40
- # with both.
41
- def channel = "Y::DocumentChannel"
38
+ # The channel that accepts this document's grant: the one the model
39
+ # declared with has_collaborative_document, or Y::DocumentChannel. A
40
+ # gem with its own grants and channel, such as lexxy-realtime, returns
41
+ # its own document with both.
42
+ def channel = record.class.collaborative_document_options.dig(name, :channel) || "Y::DocumentChannel"
42
43
 
43
44
  # Edits the document from Ruby the way a browser does: yields the
44
45
  # current document, records what the block changed, and broadcasts it so
45
46
  # open editors apply it. Returns the update, or nil when the block
46
- # changed nothing.
47
+ # wrote nothing.
47
48
  #
48
49
  # post.collaborative_document(:body).edit do |doc|
49
50
  # Y::Lexxy.append_paragraph(doc, "Reviewed by ops.")
@@ -18,10 +18,10 @@ module Y
18
18
  #
19
19
  # The grant and channel come from record.collaborative_document(name), so
20
20
  # the tag works for any gem that returns its own document, such as
21
- # lexxy-realtime. Pass channel: for an app's own Y::DocumentChannel
22
- # subclass. The grant is scoped to this record and attribute. Only render
23
- # the tag on pages where
24
- # the user may edit the record, because by default anyone holding the
21
+ # lexxy-realtime. An app's own Y::DocumentChannel subclass is named where
22
+ # the model declares the attribute, with has_collaborative_document's
23
+ # channel:. The grant is scoped to this record and attribute. Only render
24
+ # the tag on pages where the user may edit the record, because by default anyone holding the
25
25
  # grant can open the document. To also check the user's current
26
26
  # permissions when they subscribe, use Y::DocumentChannel.authorize_document.
27
27
  #
@@ -61,12 +61,13 @@ module Y
61
61
  end
62
62
 
63
63
  class_methods do
64
- # Declares how one attribute's document is stored. The shipped channel
65
- # and Ruby reads both follow it, and undeclared attributes use plain
66
- # Y::Document.
67
- def has_collaborative_document(name, encrypted: false) # rubocop:disable Naming/PredicatePrefix
64
+ # Declares how one attribute's document is stored, and the channel that
65
+ # serves it: an app's own Y::DocumentChannel subclass, by name. The
66
+ # shipped channel and Ruby reads both follow it. Undeclared attributes
67
+ # use plain Y::Document and Y::DocumentChannel.
68
+ def has_collaborative_document(name, encrypted: false, channel: nil) # rubocop:disable Naming/PredicatePrefix
68
69
  self.collaborative_document_options = collaborative_document_options.merge(
69
- name.to_s => { encrypted: encrypted }.freeze
70
+ name.to_s => { encrypted: encrypted, channel: channel&.to_s }.freeze
70
71
  ).freeze
71
72
  end
72
73
 
data/lib/y/doc.rb CHANGED
@@ -4,17 +4,43 @@ module Y
4
4
  # Ruby-side conveniences over the native document.
5
5
  class Doc
6
6
  # Runs the block, which edits this document through handles, and returns
7
- # the update its writes produced, or nil when the document didn't change.
8
- # The document has the edit either way. The update is what a process
9
- # saves and broadcasts, one call per chunk as it streams into a document.
7
+ # an update with every local write no edit has returned yet, or nil when
8
+ # there's nothing to send. The document has the writes either way. The
9
+ # update is what a process saves and broadcasts, one call per chunk as it
10
+ # streams into a document.
10
11
  #
11
- # The update holds everything the document gained while the block ran,
12
- # so a write another thread or peer made meanwhile is in it too. Applying
13
- # an update twice changes nothing, so that only adds bytes.
12
+ # The document keeps every local write until an edit returns it, so none
13
+ # is left out: a write made outside an edit, from another thread or
14
+ # fiber, or in a block that raised comes with the next edit's update. An
15
+ # update applied from a peer is never in it, and doesn't wait for the
16
+ # block. Each edit takes everything unsent at once, so the updates edits
17
+ # return have no gaps between them. An edit inside another, including one
18
+ # in a fiber or thread the outer block starts, returns what it took and
19
+ # leaves it for the outer edit to return again. Once the outer edit
20
+ # returns, a thread it started edits on its own.
21
+ #
22
+ # So send every update an edit returns. An edit in a thread the block
23
+ # didn't start, such as a pool thread, isn't nested: it takes the outer
24
+ # block's writes too, and they're sent only if its update is.
25
+ #
26
+ # An exception raised as `edit` returns, such as a Thread#raise or a
27
+ # signal trap, loses the update the edit took. A caller that must send
28
+ # every update masks interrupts around `edit` and doesn't raise from a
29
+ # trap.
14
30
  def edit
15
- before = native_snapshot
16
- yield self
17
- native_update_since(before)
31
+ # The edits running in this fiber, inherited by the fibers and threads
32
+ # their blocks start. Each is `[doc]` until it ends, then empty.
33
+ outer = (Fiber[:yrby_editing] || []).reject(&:empty?)
34
+ nested = outer.any? { |running| running.include?(self) }
35
+ running = [self]
36
+ Fiber[:yrby_editing] = [*outer, running]
37
+ begin
38
+ yield self
39
+ ensure
40
+ running.clear
41
+ Fiber[:yrby_editing] = outer
42
+ end
43
+ take_unsent(nested)
18
44
  end
19
45
 
20
46
  # The ordinal of the top-level block a position falls in, or nil at the
@@ -32,5 +58,22 @@ module Y
32
58
  def find(anchor)
33
59
  native_find(anchor.position, anchor.root)
34
60
  end
61
+
62
+ private
63
+
64
+ # An interrupt that arrives during the take is raised once the masked
65
+ # block ends, and the taken update goes back to the document first, for
66
+ # the next edit to return. A nested edit has already put it back.
67
+ def take_unsent(nested)
68
+ taken = nil
69
+ Thread.handle_interrupt(Object => :never) do
70
+ taken = native_take_unsent
71
+ native_keep_unsent(taken) if taken && nested
72
+ end
73
+ taken
74
+ rescue Exception # rubocop:disable Lint/RescueException -- an interrupt is any exception
75
+ native_keep_unsent(taken) if taken && !nested
76
+ raise
77
+ end
35
78
  end
36
79
  end
data/lib/y/map.rb ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Y
4
+ class Map
5
+ # Store a new Y.Text holding `content` at `key`, replacing what was
6
+ # there, and return a live Y::Text for it. `map[key] = "..."` stores a
7
+ # plain string instead, and the last write to it wins.
8
+ def set_text(key, content = "")
9
+ native_set_text(key, content)
10
+ end
11
+ end
12
+ end