ndb-rails 1.25.1 → 1.26.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: f12c45cfd6db4e1cc280b045d4677761c069d21b676c27efc57876f60033da46
4
- data.tar.gz: cbffdc5bc06920462c2fdad7cc23124544c0ac3345d3386dd23478cee95c24b1
3
+ metadata.gz: '07749aaa7f0f402aa0e37067a748d35d501645bd13fde8a4ead4e75a086645fc'
4
+ data.tar.gz: '01208bdd9c56eb941a8bdf7f5892b5c74a924351af152c9d8051e01d6044d688'
5
5
  SHA512:
6
- metadata.gz: 83e340f3b33b1513223f745812ac2ef1fbbc9cb745a7a0bd6bd36978c222164c315ed4fff20dbea4ec8444033754b05541e70f0a3bc11fadb804dc1880330048
7
- data.tar.gz: a59d2c6213578b48068cf6951b4e8f3412f4d7ec5ac909b7f63ad23580b01a0ee26add121fc2625c8b02e9b2f31978190e05f4fd97be63615cb8b8f3e7599100
6
+ metadata.gz: cff2a0958984ce985fa153a65707e9ca47ddb3ab975f29a34f3f33fa91e4a3a582d7b5b9408e533009966d974af0aead5e40fce8b525b858d1e93efa370a8011
7
+ data.tar.gz: 2ceb1315f0a406fc61eb79f7429df96543c2f15cd603b2a070e8ae1770f8d9b0aa3cca51aefd3b07f52fb0d2b75b56b0cadd0b1ddc7f696ca59e449b1c65b5fd
data/README.md CHANGED
@@ -502,6 +502,26 @@ production:
502
502
 
503
503
  A broadcast appends one entry to the stream. Each process has one thread that reads the stream without a group, so every process gets every broadcast (a fan-out, as Redis PUBLISH/SUBSCRIBE). Delivery is at most once. ActionCable loads the adapter only for `adapter: ndb`: the gem does not need `actioncable` for anything else. A change made by another service (in Go, for example) gets to the browser through an `Ndb::Streams` consumer in the app that calls `ActionCable.server.broadcast`. See [ActionCable](https://ndb.clowk.in/clients/rails#actioncable).
504
504
 
505
+ ## Turbo Streams
506
+
507
+ With turbo-rails in the app, the railtie loads `Ndb::Turbo` (the gem does not need turbo-rails). Every record has a GlobalID, so `turbo_stream_from @domain` works as with ActiveRecord.
508
+
509
+ ```erb
510
+ <%= turbo_refreshes_with method: :morph, scroll: :preserve %>
511
+ <%= turbo_stream_from @domain %>
512
+ ```
513
+
514
+ ```ruby
515
+ Ndb::Turbo.refresh(domain) # where the data changes
516
+ Ndb::Turbo.refresh("credits", account.id) # the stream "credits:<id>"
517
+
518
+ class Domain < Ndb::Record
519
+ broadcasts_live_refreshes # refresh after each commit
520
+ end
521
+ ```
522
+
523
+ `Ndb::Turbo.refresh` sends at most one refresh per stream every `Ndb::Turbo.window` seconds (2; 0 in the test environment, so a test can count the broadcasts). The first call goes at once, and the calls inside the window leave one refresh for its end, so the page shows the last change. The window is per process. A failed refresh only writes a warning to the log. See [Turbo Streams](https://ndb.clowk.in/clients/rails#turbo-streams).
524
+
505
525
  ## Errors
506
526
 
507
527
  The transport and daemon errors are defined by the gem `ndb`. They all live in the `Ndb` module (`Ndb::Error`, `Ndb::NotFound`, ...). For an ActiveRecord-like `rescue`, this gem adds one alias: `Ndb::RecordNotUnique` is `Ndb::UniqueViolation` (the same class). `Ndb::StaleObjectError`, `Ndb::RecordInvalid` and `Ndb::RecordNotSaved` exist only here, and they inherit from `Ndb::Error`. Every error has `code` (the daemon code) and `status` (the HTTP status).
@@ -547,7 +567,7 @@ ndb -config /nonexistent.yml -data-dir "$(mktemp -d)" -unix /tmp/ndb-test.sock
547
567
  Ndb::Rails.configure { |c| c.socket = "/tmp/ndb-test.sock" }
548
568
  ```
549
569
 
550
- Use a new collection name per test (`self.collection_name = ...`). Run the suite with `bundle exec rake test` in `sdk/rails`. Its Gemfile uses the gem `ndb` from `../ruby`.
570
+ Use a new collection name per test (`self.collection_name = ...`). Run the suite with `bundle exec rake test` in `sdk/rails` (`test:core` without turbo-rails, then `test:turbo` in its own process). Its Gemfile uses the gem `ndb` from `../ruby`.
551
571
 
552
572
  ## License
553
573
 
@@ -8,6 +8,7 @@ module Ndb
8
8
  # boot when the app eager loads (production). In development a model
9
9
  # declares its collection on first use. It also loads app/streams and
10
10
  # makes the groups of the stream consumers, in a background thread.
11
+ # With turbo-rails in the app, it loads Ndb::Turbo before the models.
11
12
  class Railtie < ::Rails::Railtie
12
13
  initializer "ndb.configure" do |app|
13
14
  path = app.root.join("config", "ndb.yml")
@@ -18,6 +19,10 @@ module Ndb
18
19
  end
19
20
  end
20
21
 
22
+ initializer "ndb.turbo" do
23
+ require "ndb/turbo" if defined?(::Turbo::Engine)
24
+ end
25
+
21
26
  config.after_initialize do |app|
22
27
  if app.config.eager_load
23
28
  Ndb::Record.descendants.reject(&:abstract_class?).each(&:ensure_collection!)
@@ -16,6 +16,10 @@ module Ndb
16
16
  include Transactions
17
17
  include Associations
18
18
 
19
+ # to_global_id and to_gid_param, as an ActiveRecord model. The locator
20
+ # calls find(id). turbo-rails names the stream of a record by it.
21
+ include GlobalID::Identification if defined?(::GlobalID::Identification)
22
+
19
23
  extend ActiveSupport::DescendantsTracker
20
24
  extend DynamicFinders
21
25
 
@@ -2,6 +2,6 @@
2
2
 
3
3
  module Ndb
4
4
  module Rails
5
- VERSION = "1.25.1"
5
+ VERSION = "1.26.0"
6
6
  end
7
7
  end
data/lib/ndb/rails.rb CHANGED
@@ -4,6 +4,14 @@ require "active_model"
4
4
  require "active_support/all"
5
5
  require "ndb"
6
6
 
7
+ # GlobalID comes with Rails. When it is there, every record has one (see
8
+ # Ndb::Record); the gem works without it.
9
+ begin
10
+ require "globalid"
11
+ rescue LoadError
12
+ nil
13
+ end
14
+
7
15
  require "ndb/rails/version"
8
16
  require "ndb/rails/errors"
9
17
  require "ndb/rails/configuration"
data/lib/ndb/turbo.rb ADDED
@@ -0,0 +1,147 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "ndb/rails"
4
+
5
+ module Ndb
6
+ # Turbo Streams helpers. They need turbo-rails, which is not a dependency
7
+ # of the gem: the railtie loads this file when the app has turbo-rails, or
8
+ # `require "ndb/turbo"` loads it.
9
+ #
10
+ # refresh tells the open pages of a stream to refresh (a Turbo refresh,
11
+ # a morph with turbo_refreshes_with), at most once per window: a burst of
12
+ # changes gives one refresh at once and one at the end of the window, so
13
+ # the last change always shows. Each stream has its own window, in each
14
+ # process.
15
+ #
16
+ # Ndb::Turbo.refresh(domain) # the stream of a record (its GlobalID)
17
+ # Ndb::Turbo.refresh("credits", account.id) # the stream "credits:<id>"
18
+ module Turbo
19
+ DEFAULT_WINDOW = 2
20
+
21
+ # A call forgets the streams whose window is over when it knows more
22
+ # than this many.
23
+ PRUNE_AT = 1_000
24
+
25
+ @lock = Mutex.new
26
+ @last = {}
27
+ @pending = {}
28
+ @window = nil
29
+
30
+ class << self
31
+ attr_writer :window
32
+
33
+ # Seconds between two refreshes of one stream: 2, and 0 in the test
34
+ # environment (each call sends one, so a test can count them).
35
+ def window
36
+ @window || (test_env? ? 0 : DEFAULT_WINDOW)
37
+ end
38
+
39
+ # Sends a Turbo refresh to the stream of the streamables, now or at
40
+ # the end of the window. It never raises: an error goes to the log.
41
+ def refresh(*streamables)
42
+ name = ::Turbo::StreamsChannel.send(:stream_name_from, streamables)
43
+ wait = reserve(name)
44
+
45
+ return if wait.nil?
46
+
47
+ wait.positive? ? later(name, streamables, wait) : broadcast(name, streamables)
48
+ rescue StandardError => e
49
+ Streams.logger.warn("ndb turbo: the refresh failed: #{e.class}: #{e.message}")
50
+ end
51
+
52
+ # Forgets every window (for the tests).
53
+ def reset!
54
+ @lock.synchronize do
55
+ @last.clear
56
+ @pending.clear
57
+ end
58
+ end
59
+
60
+ private
61
+
62
+ # 0 to send now, the seconds to wait for a trailing refresh, or nil
63
+ # when a trailing refresh of the stream is already pending.
64
+ def reserve(name)
65
+ @lock.synchronize do
66
+ now = clock
67
+ wait = @last.fetch(name, -Float::INFINITY) + window.to_f - now
68
+
69
+ prune(now) if @last.size >= PRUNE_AT
70
+
71
+ if wait <= 0
72
+ @last[name] = now
73
+
74
+ 0
75
+ elsif @pending[name]
76
+ nil
77
+ else
78
+ @pending[name] = true
79
+
80
+ wait
81
+ end
82
+ end
83
+ end
84
+
85
+ def later(name, streamables, wait)
86
+ Thread.new do
87
+ sleep wait
88
+
89
+ @lock.synchronize do
90
+ @pending.delete(name)
91
+ @last[name] = clock
92
+ end
93
+
94
+ broadcast(name, streamables)
95
+ end
96
+ end
97
+
98
+ # A failed broadcast never fails the work that made the change.
99
+ def broadcast(name, streamables)
100
+ ::Turbo::StreamsChannel.broadcast_refresh_to(*streamables)
101
+ rescue StandardError => e
102
+ Streams.logger.warn("ndb turbo: the refresh of #{name} failed: #{e.class}: #{e.message}")
103
+ end
104
+
105
+ def prune(now)
106
+ limit = window.to_f
107
+
108
+ @last.delete_if { |name, at| at + limit <= now && !@pending[name] }
109
+ end
110
+
111
+ def test_env?
112
+ return ::Rails.env.test? if defined?(::Rails) && ::Rails.respond_to?(:env)
113
+
114
+ ENV["RAILS_ENV"] == "test" || ENV["RACK_ENV"] == "test"
115
+ end
116
+
117
+ def clock = Process.clock_gettime(Process::CLOCK_MONOTONIC)
118
+ end
119
+
120
+ # The model macro. After each commit (create, update, destroy) the open
121
+ # pages of the record refresh, or the pages of the streams that the
122
+ # block gives (it runs on the record).
123
+ #
124
+ # class Domain < Ndb::Record
125
+ # broadcasts_live_refreshes
126
+ # end
127
+ #
128
+ # class Usage < Ndb::Record
129
+ # broadcasts_live_refreshes { ["credits", account_id] }
130
+ # end
131
+ module Broadcasts
132
+ extend ActiveSupport::Concern
133
+
134
+ class_methods do
135
+ def broadcasts_live_refreshes(&streams)
136
+ after_commit do
137
+ streamables = streams ? Array.wrap(instance_exec(&streams)) : [self]
138
+
139
+ Ndb::Turbo.refresh(*streamables)
140
+ end
141
+ end
142
+ end
143
+ end
144
+ end
145
+
146
+ Record.include(Turbo::Broadcasts)
147
+ end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: ndb-rails
3
3
  version: !ruby/object:Gem::Version
4
- version: 1.25.1
4
+ version: 1.26.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - thadeu
@@ -43,7 +43,7 @@ dependencies:
43
43
  requirements:
44
44
  - - ">="
45
45
  - !ruby/object:Gem::Version
46
- version: 1.25.1
46
+ version: 1.26.0
47
47
  - - "<"
48
48
  - !ruby/object:Gem::Version
49
49
  version: '2'
@@ -53,7 +53,7 @@ dependencies:
53
53
  requirements:
54
54
  - - ">="
55
55
  - !ruby/object:Gem::Version
56
- version: 1.25.1
56
+ version: 1.26.0
57
57
  - - "<"
58
58
  - !ruby/object:Gem::Version
59
59
  version: '2'
@@ -99,6 +99,7 @@ files:
99
99
  - lib/ndb/streams/perform.rb
100
100
  - lib/ndb/streams/puma_plugin.rb
101
101
  - lib/ndb/streams/runner.rb
102
+ - lib/ndb/turbo.rb
102
103
  - lib/puma/plugin/ndb.rb
103
104
  homepage: https://ndb.clowk.in
104
105
  licenses: