ndb-rails 1.14.0 → 1.16.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: efca6fb497fca5f49e1d4d704119345c8542e02f9da65be939bf07a640d123c0
4
- data.tar.gz: 83d2ca5b6a0e065eb734965f720e4671c53929e30d7b6d058a96c0c8937b68ff
3
+ metadata.gz: c96856df23ee63e9d10523b47bc005eeed49da6887db6332e9aefe2b18196256
4
+ data.tar.gz: 05645bb1e8b9d81ce3ec1f585ef5528028a6aa7275583c81520daa7ca3a2d55e
5
5
  SHA512:
6
- metadata.gz: 9aa45a412b9e953aab2a7e0fe3ee77f00b844246e2009d4e267c0c3beea9578f5e61ee9ab2d6de318923cb6d45bdb9915369a0db272df68fb9aac515dec1d73a
7
- data.tar.gz: e9a4a73758be23d8c7cdda5ec780f99b4e252f1d25c207ac4b3ad519cb6dc86cf5a72a330877b1cc9794253645c288ec9df4abbfc3821b2d3d3e76f36fe7963d
6
+ metadata.gz: 46b1111e1866470b32c44bc448de425873e7e5ad55d62cd1c5116e1a0395e1940524d57df5ec84b2c0f32b2d17e7da54214eab5d68ce6cbe5fe0f44db76db842
7
+ data.tar.gz: 7e9886fd8453a9adc401de4e033fad2049e6d62cbc7dfa02d2c845b86dd590621ea41d246d992528d18ff4d2b0d1f304b4b9f03d9b51dd13bbc483349b0ea488
data/README.md CHANGED
@@ -362,6 +362,106 @@ loaded.recording.each_chunk { |chunk| out.write(chunk) } # 1 MiB ranges
362
362
 
363
363
  A blob behaves like a read-only IO (`read`, `each_chunk`, `eof?`, `rewind`). A loaded blob reads the daemon in 1 MiB ranges, so memory stays small. The same content always gives the same reference. You can also use `Ndb::Blob.new(io_or_string, content_type: "audio/wav")`.
364
364
 
365
+ ## Streams
366
+
367
+ A stream is an append-only log with consumer groups, as in Redis Streams. A class in `app/streams` appends to a stream, consumes it, or does both. There is no base class: `include Ndb::Streams`.
368
+
369
+ ```ruby
370
+ # app/streams/order_event.rb: a writer
371
+ class OrderEvent
372
+ include Ndb::Streams
373
+ end
374
+
375
+ OrderEvent.append(order_id: 42) # one entry, returns its ID
376
+ OrderEvent.append([{ order_id: 1 }, { order_id: 2 }]) # many entries, returns their IDs
377
+ OrderEvent.append('{"order_id":42}') # a JSON string
378
+ ```
379
+
380
+ ```ruby
381
+ # app/streams/billing_paid.rb: a consumer
382
+ class BillingPaid
383
+ include Ndb::Streams
384
+
385
+ stream :order_events, group: :billing
386
+
387
+ def perform(event)
388
+ Invoice.create!(order_id: event[:order_id])
389
+ end
390
+ end
391
+ ```
392
+
393
+ Run the consumers:
394
+
395
+ ```sh
396
+ bundle exec ndb streams # every consumer class of app/streams
397
+ bundle exec ndb streams --only BillingPaid -c 4
398
+ bundle exec ndb streams -r ./consumers.rb # without Rails
399
+ ```
400
+
401
+ - **Name.** The stream name comes from the class name, with the ActiveSupport inflections (`OrderEvent` is `order_events`, `Category` is `categories`). `stream :orders` sets it. `stream OrderEvent, group: :billing` takes the stream of another class.
402
+ - **Role.** A class without `perform` is a writer. A class with `perform` is a consumer and needs `group:`. Each group gets every entry one time, so each service has its own group. Two classes with the same group on one stream are an error.
403
+ - **Write.** `append`, with the aliases `enqueue` and `perform_async`. In an ActiveRecord transaction the append waits for the commit (Rails 7.2 or later) and returns `nil`. A rollback drops it.
404
+ - **Read.** `OrderEvent.last`, `last(10)`, `find(id)`, `range(1.hour.ago, Time.now, count: 100)`, `count`.
405
+ - **The event.** `event[:order_id]` (a symbol or a string), `event.to_h`, `event.id`, `event.time`, `event.deliveries`. The payload is JSON: a date comes as a String.
406
+ - **Failure.** An error in `perform` (any exception but a signal or `exit`) leaves the entry pending. It comes again after `claim_idle`, or after the wait of `retry:` (ndb only: `retry: [15.seconds, 1.minute, 10.minutes, 1.hour, 6.hours], max_age: 15.days`). Delivery is at least once, so `perform` must be safe to repeat.
407
+
408
+ The options of `stream`, with their defaults:
409
+
410
+ ```ruby
411
+ stream :order_events,
412
+ group: :billing, # needed with perform
413
+ concurrency: 1, # threads of this class in each process
414
+ max_deliveries: nil, # after N deliveries the entry goes to the dead letter and is acked
415
+ dead_letter: nil, # "<stream>_dead" when max_deliveries or max_age is set; false for none
416
+ claim_idle: 1.minute, # an entry pending this long is tried again
417
+ retry: nil, # waits before each retry ([15, 1.minute, ...], the last repeats) or ->(n) { seconds }
418
+ max_age: nil, # an entry older than this goes to the dead letter (15.days)
419
+ start: :new, # a new group reads new entries only; :all reads from the start
420
+ discard_on: [], # these errors ack the entry without a retry
421
+ max_len: nil, # keep only the newest N entries (a trim on each append)
422
+ retain: nil # delete entries older than this ("30d", or 30.days)
423
+ ```
424
+
425
+ `around_perform` runs a block around each `perform`, on the instance. A subclass gets the config and the blocks of its parent, so an app can have its own `ApplicationStream`.
426
+
427
+ ```ruby
428
+ class ApplicationStream
429
+ include Ndb::Streams
430
+
431
+ around_perform { |event, block| Current.set(tenant: event[:tenant]) { block.call } }
432
+ end
433
+ ```
434
+
435
+ Each thread is a consumer with a stable name: `NDB_CONSUMER` (or the hostname), then `:` and the thread index. After a restart it reads its own pending entries first. Set `NDB_CONSUMER` to a different value in each process that runs on the same host. `SIGTERM` and `SIGINT` stop the process after the current entries.
436
+
437
+ At boot, any process of the app loads `app/streams` and makes the missing groups in a background thread. `config/ndb.yml` can hold the defaults of the command:
438
+
439
+ ```yaml
440
+ production:
441
+ streams:
442
+ concurrency: 4
443
+ only: [BillingPaid]
444
+ ```
445
+
446
+ With Puma, `plugin :ndb` in `config/puma.rb` runs `bundle exec ndb streams` (or `bin/ndb streams`) next to Puma and stops it with Puma. It is on in development only. `NDB_STREAMS_IN_PUMA=true` or `false` sets it.
447
+
448
+ `ActiveSupport::Notifications` gets `append.ndb_streams` (`stream`, `class`, `count`) and `perform.ndb_streams` (`stream`, `group`, `class`, `event`).
449
+
450
+ The `ndb` command of the gem only has `streams`. It gives every other command (`ndb serve`, ...) to the daemon binary of `NDB_BIN`, or to the first native `ndb` executable of `PATH` (not a shim of rbenv, mise or asdf).
451
+
452
+ `ndb streams` logs the retry schedule of each consumer at the start. Inline mode runs `perform` once: a failure raises to the caller, and `retry:` does not apply.
453
+
454
+ `ndb streams` loads `app/streams` itself before it starts, also when the app does not eager load. It does not exit when ndb is down: each thread makes its group and tries again. A second signal in the first 2 seconds of a stop does nothing.
455
+
456
+ In tests, `Ndb::Streams.inline!` makes an append write the entry and then call `perform` of each consumer of the stream, in the same thread. `ndb/rails/minitest` adds `assert_streamed` and `assert_no_streamed`, `ndb/rails/rspec` adds `have_streamed`, and both truncate the streams a test used.
457
+
458
+ ```ruby
459
+ Ndb::Streams.inline!
460
+
461
+ assert_streamed OrderEvent, order_id: 42
462
+ expect(OrderEvent).to have_streamed(order_id: 42)
463
+ ```
464
+
365
465
  ## Errors
366
466
 
367
467
  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).
@@ -15,10 +15,16 @@ module Ndb
15
15
  # ("test2_" for a parallel test worker). nil by default.
16
16
  attr_accessor :collection_prefix
17
17
 
18
+ # The `streams:` block of config/ndb.yml, for `ndb streams`:
19
+ # "concurrency" (the threads of each consumer class) and "only" (the
20
+ # names of the classes to run).
21
+ attr_accessor :streams
22
+
18
23
  def initialize
19
24
  @timeout = 30
20
25
  @pool_size = 16
21
26
  @ready_timeout = 10
27
+ @streams = {}
22
28
  end
23
29
 
24
30
  # Reads config/ndb.yml: one block per environment.
@@ -32,6 +38,7 @@ module Ndb
32
38
  @timeout = settings["timeout"] if settings.key?("timeout")
33
39
  @pool_size = settings["pool_size"] if settings.key?("pool_size")
34
40
  @ready_timeout = settings["ready_timeout"] if settings.key?("ready_timeout")
41
+ @streams = settings["streams"] if settings["streams"].is_a?(Hash)
35
42
 
36
43
  self
37
44
  end
@@ -6,15 +6,18 @@
6
6
  #
7
7
  # Every ActiveSupport::TestCase truncates the ndb collections it used after
8
8
  # each test, and each worker of `parallelize` gets collections of its own.
9
- # A test case opts out with `self.ndb_clean = false`.
9
+ # A test case opts out with `self.ndb_clean = false`. It also gets
10
+ # assert_streamed and assert_no_streamed (see Ndb::Streams::Assertions).
10
11
 
11
12
  require "ndb/rails"
12
13
  require "ndb/rails/testing"
14
+ require "ndb/streams/assertions"
13
15
 
14
16
  Ndb::Testing.worker!(ENV.fetch("TEST_ENV_NUMBER", nil)) if ENV.key?("TEST_ENV_NUMBER")
15
17
 
16
18
  ActiveSupport.on_load(:active_support_test_case) do
17
19
  include Ndb::Testing::Minitest
20
+ include Ndb::Streams::Assertions
18
21
 
19
22
  parallelize_setup { |worker| Ndb::Testing.worker!(worker) } if respond_to?(:parallelize_setup)
20
23
  end
@@ -4,9 +4,10 @@ require "rails/railtie"
4
4
 
5
5
  module Ndb
6
6
  module Rails
7
- # Reads config/ndb.yml (the connection only) and declares the collection
8
- # of every model on boot when the app eager loads (production). In
9
- # development a model declares its collection on first use.
7
+ # Reads config/ndb.yml and declares the collection of every model on
8
+ # boot when the app eager loads (production). In development a model
9
+ # declares its collection on first use. It also loads app/streams and
10
+ # makes the groups of the stream consumers, in a background thread.
10
11
  class Railtie < ::Rails::Railtie
11
12
  initializer "ndb.configure" do |app|
12
13
  path = app.root.join("config", "ndb.yml")
@@ -21,6 +22,8 @@ module Ndb
21
22
  if app.config.eager_load
22
23
  Ndb::Record.descendants.reject(&:abstract_class?).each(&:ensure_collection!)
23
24
  end
25
+
26
+ Ndb::Streams::Boot.start(app)
24
27
  end
25
28
  end
26
29
  end
@@ -25,7 +25,7 @@ module Ndb
25
25
  class << self
26
26
  QUERY_METHODS = %i[
27
27
  where where_raw order limit offset page after group includes find find_by find_by! first last count pluck exists?
28
- find_each in_batches sum average minimum maximum to_a each destroy_all delete_all
28
+ find_each in_batches sum average minimum maximum to_a each destroy_all delete_all to_ndb
29
29
  ].freeze
30
30
 
31
31
  delegate(*QUERY_METHODS, to: :all)
@@ -82,6 +82,18 @@ module Ndb
82
82
  with(group: fields.flatten.map(&:to_s))
83
83
  end
84
84
 
85
+ # The JSON body that this relation sends to the daemon, as a String,
86
+ # with no request (like to_sql of ActiveRecord). It is the body of
87
+ # POST /{collection}/_search; pretty: true gives it on many lines.
88
+ #
89
+ # Call.where(status: "failed").order(created_at: :desc).limit(10).to_ndb
90
+ # # => {"query":{"status":"failed"},"sort":{"created_at":-1},"limit":10,"versions":true}
91
+ def to_ndb(pretty: false)
92
+ body = to_query.merge("versions" => true)
93
+
94
+ pretty ? JSON.pretty_generate(body) : JSON.generate(body)
95
+ end
96
+
85
97
  # The find body: JSON only, the daemon decides what it means.
86
98
  def to_query
87
99
  query = {}
@@ -178,20 +190,38 @@ module Ndb
178
190
  @result.next
179
191
  end
180
192
 
181
- # The last record (or count of them) of the loaded records, in the
182
- # order of the relation.
183
- def last(count = nil)
184
- count ? records.last(count) : records.last
185
- end
186
-
193
+ # The first record (or count of them), in the order of the relation.
194
+ # With no order, the order is the primary key (as ActiveRecord does),
195
+ # so first and last are the two ends of one order. The daemon gives
196
+ # only count rows (limit), not the whole relation.
187
197
  def first(count = nil)
188
198
  return count ? records.first(count) : records.first if loaded?
189
199
 
190
- found = limit(count || 1).to_a
200
+ found = by_key.limit(count || 1).to_a
191
201
 
192
202
  count ? found : found.first
193
203
  end
194
204
 
205
+ # The last record (or count of them, in the order of the relation). The
206
+ # order is turned around and the daemon gives only count rows; a
207
+ # relation with a limit, an offset or a page is loaded instead, because
208
+ # its last row depends on that window.
209
+ def last(count = nil)
210
+ return count ? records.last(count) : records.last if loaded? || windowed?
211
+
212
+ found = by_key.reverse_order.limit(count || 1).to_a.reverse
213
+
214
+ count ? found : found.last
215
+ end
216
+
217
+ # The relation with its order turned around (asc and desc swap). With no
218
+ # order, it is the primary key in descending order.
219
+ def reverse_order
220
+ sort = by_key.values[:order].transform_values { |dir| -dir }
221
+
222
+ with(order: sort)
223
+ end
224
+
195
225
  def find(*ids)
196
226
  ids = ids.flatten
197
227
 
@@ -293,6 +323,17 @@ module Ndb
293
323
  with(where: values[:where] + [clause])
294
324
  end
295
325
 
326
+ # The relation, ordered by the primary key when it has no order.
327
+ def by_key
328
+ return self unless values[:order].empty?
329
+
330
+ with(order: { klass.primary_key => 1 })
331
+ end
332
+
333
+ def windowed?
334
+ values[:limit] || values[:offset] || values[:page]
335
+ end
336
+
296
337
  def direction(value)
297
338
  %w[desc -1].include?(value.to_s.downcase) ? -1 : 1
298
339
  end
@@ -6,14 +6,18 @@
6
6
  #
7
7
  # Each example truncates the ndb collections it used. `ndb_clean: false`
8
8
  # on an example or a group skips it. Under parallel_tests each process gets
9
- # collections of its own (TEST_ENV_NUMBER).
9
+ # collections of its own (TEST_ENV_NUMBER). The examples also get the
10
+ # have_streamed matcher: expect(OrderEvent).to have_streamed(order_id: 42).
10
11
 
11
12
  require "ndb/rails"
12
13
  require "ndb/rails/testing"
14
+ require "ndb/streams/assertions"
13
15
 
14
16
  Ndb::Testing.worker!(ENV.fetch("TEST_ENV_NUMBER", nil)) if ENV.key?("TEST_ENV_NUMBER")
15
17
 
16
18
  RSpec.configure do |config|
19
+ config.include Ndb::Streams::Assertions
20
+
17
21
  config.after do |example|
18
22
  Ndb::Testing.clean! unless example.metadata[:ndb_clean] == false
19
23
  end
@@ -2,6 +2,6 @@
2
2
 
3
3
  module Ndb
4
4
  module Rails
5
- VERSION = "1.14.0"
5
+ VERSION = "1.16.0"
6
6
  end
7
7
  end
data/lib/ndb/rails.rb CHANGED
@@ -13,6 +13,7 @@ require "ndb/rails/blob"
13
13
  require "ndb/rails/persistence"
14
14
  require "ndb/rails/associations"
15
15
  require "ndb/rails/record"
16
+ require "ndb/streams"
16
17
 
17
18
  module Ndb
18
19
  module Rails
@@ -0,0 +1,81 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Ndb
4
+ module Streams
5
+ # Test helpers. ndb/rails/minitest adds the assertions to
6
+ # ActiveSupport::TestCase; ndb/rails/rspec adds the have_streamed matcher.
7
+ #
8
+ # assert_streamed OrderEvent, order_id: 42
9
+ # assert_no_streamed OrderEvent
10
+ # expect(OrderEvent).to have_streamed(order_id: 42)
11
+ module Assertions
12
+ # The most entries a check reads, from the newest.
13
+ LIMIT = 1000
14
+
15
+ # The entries of the stream of klass whose payload has these fields.
16
+ # Values are compared as JSON, so a symbol is equal to its string.
17
+ def self.matching(klass, subset)
18
+ wanted = JSON.parse(JSON.generate(subset))
19
+
20
+ klass.last(LIMIT).select do |event|
21
+ payload = event.to_h
22
+
23
+ wanted.all? { |key, value| payload.key?(key) && payload[key] == value }
24
+ end
25
+ end
26
+
27
+ def self.describe(klass, subset)
28
+ fields = subset.empty? ? "an entry" : "an entry with #{subset.inspect}"
29
+
30
+ "#{fields} in the stream #{klass.stream_name.inspect}"
31
+ end
32
+
33
+ # Passes when the stream of klass has an entry with these fields (any
34
+ # entry, when there are no fields). Returns the matching events.
35
+ def assert_streamed(klass, **subset)
36
+ found = Assertions.matching(klass, subset)
37
+
38
+ assert !found.empty?, "Expected #{Assertions.describe(klass, subset)}, found none (#{klass.count} entries)"
39
+
40
+ found
41
+ end
42
+
43
+ # Passes when the stream of klass has no entry with these fields.
44
+ def assert_no_streamed(klass, **subset)
45
+ found = Assertions.matching(klass, subset)
46
+
47
+ assert found.empty?, "Expected no #{Assertions.describe(klass, subset)}, found #{found.size}"
48
+ end
49
+
50
+ # The RSpec matcher: expect(OrderEvent).to have_streamed(order_id: 42)
51
+ def have_streamed(**subset)
52
+ Matcher.new(subset)
53
+ end
54
+
55
+ # A matcher with the protocol of RSpec. It needs no RSpec to load.
56
+ class Matcher
57
+ def initialize(subset)
58
+ @subset = subset
59
+ end
60
+
61
+ def matches?(klass)
62
+ @klass = klass
63
+
64
+ !Assertions.matching(klass, @subset).empty?
65
+ end
66
+
67
+ def description
68
+ "have streamed #{@subset.inspect}"
69
+ end
70
+
71
+ def failure_message
72
+ "expected #{Assertions.describe(@klass, @subset)}, found none (#{@klass.count} entries)"
73
+ end
74
+
75
+ def failure_message_when_negated
76
+ "expected no #{Assertions.describe(@klass, @subset)}, found one"
77
+ end
78
+ end
79
+ end
80
+ end
81
+ end
@@ -0,0 +1,63 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Ndb
4
+ module Streams
5
+ # The work at the boot of an app: load app/streams and make the missing
6
+ # groups, in a background thread, so the boot never waits for ndb.
7
+ module Boot
8
+ ATTEMPTS = 5
9
+
10
+ class << self
11
+ # Returns the thread. backoff: seconds before the second attempt;
12
+ # it doubles after each one.
13
+ def start(app = Streams.rails_app, attempts: ATTEMPTS, backoff: 1)
14
+ Thread.new do
15
+ Thread.current.name = "ndb-streams-boot"
16
+
17
+ run(app, attempts: attempts, backoff: backoff)
18
+ end
19
+ end
20
+
21
+ # True when the groups are there. A failure is a warning, not an
22
+ # error: the runner makes the groups again when it starts.
23
+ def run(app, attempts: ATTEMPTS, backoff: 1)
24
+ load_classes(app)
25
+
26
+ attempt = 1
27
+
28
+ begin
29
+ Streams.ensure_groups!
30
+
31
+ true
32
+ rescue Ndb::Error => e
33
+ if attempt < attempts
34
+ sleep(backoff * (2**(attempt - 1)))
35
+
36
+ attempt += 1
37
+
38
+ retry
39
+ end
40
+
41
+ Streams.logger.warn("ndb streams: the groups were not made at boot (#{e.class}: #{e.message})")
42
+
43
+ false
44
+ end
45
+ rescue StandardError, ScriptError => e
46
+ Streams.logger.warn("ndb streams: the boot failed (#{e.class}: #{e.message})")
47
+
48
+ false
49
+ end
50
+
51
+ private
52
+
53
+ def load_classes(app)
54
+ return unless app
55
+
56
+ return Streams.load_app!(app) unless app.respond_to?(:executor)
57
+
58
+ app.executor.wrap { Streams.load_app!(app) }
59
+ end
60
+ end
61
+ end
62
+ end
63
+ end