ndb 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: 93cdea704230998affb631c26c1e58c25fb7780d04931dbc9a922c939f24de99
4
- data.tar.gz: ee1d7ba1a796530dda545c5076aab587b4512cab13c47d3eba4290e19d1c992e
3
+ metadata.gz: 428c791af144a97e500ad55b220418af96665d17bf445292a9f35fc527b2634f
4
+ data.tar.gz: 7391f3da195c98022a27c6fae0302cf4bdbe80b3c0ea2d331fe1147f491f7503
5
5
  SHA512:
6
- metadata.gz: 845cb4a57d3637bbe59978997f123c0ece7b6bbbc39136499e5e3e315384db3a4f80b4554a7e4c1d7f61b3f36b1f6e2517023f8406307ff23f463b2ec41fa6aa
7
- data.tar.gz: 5cb673f8fb02a3c10be40af8b084997dd12ce21aab3f09ce0ad0ca5c8fb4e2dd9b041c5f86527e56f958166ac4eab9d69f029b5b949130638e5e3eb9b386e43d
6
+ metadata.gz: e54954a33518b2d8356c8e1cc0047f068b6827cf6e3f95096518d2edae93bf4dd4f8ec3168010ac2672acad5f01f2fa23dc2cef7ef394d4b105afb4c2a1b1d25
7
+ data.tar.gz: 244c15ef535531816a6f480d2ced513eec7984f59ed0ecd19c96c7661d1806fbedd4a146854c1539ff9b036f9650a61d92f345488825797af4423db7387f3b56
data/README.md CHANGED
@@ -316,6 +316,198 @@ end
316
316
  - `HistoryTruncated` means the WAL files for the position were deleted (`wal_retention`).
317
317
  - A watch holds one connection until it ends. It is retried only for the initial open, never in the middle of a stream.
318
318
 
319
+ ## Streams
320
+
321
+ A stream is an append-only log with consumer groups, with the behavior of
322
+ Redis Streams (see [Streams](../../docs/dev/streams.md)). An entry is a Hash
323
+ with any fields.
324
+
325
+ ```ruby
326
+ orders = ndb.stream("orders")
327
+
328
+ id = orders.append({ order: 42, total: 99.9 }) # "1731164400000-0"
329
+ ids = orders.append_many([{ order: 43 }, { order: 44 }]) # one fsync
330
+ orders.append({ order: 45 }, trim: { max_len: 10_000, approx: true })
331
+
332
+ entries = orders.range("-", "+", count: 100) # XRANGE; entries[0].id, .time, .doc
333
+ orders.info # length, first and last ID, groups
334
+ ```
335
+
336
+ A worker in a group. It reads its own pending entries first, then new ones
337
+ (waiting up to `block` seconds). A block that returns acks the entry; a
338
+ block that raises any exception (also `NotImplementedError`) leaves it
339
+ pending, but a signal or `exit` goes on. The worker also claims the entries
340
+ other workers left idle. An entry delivered `max_deliveries` times goes to
341
+ the dead-letter stream as `{stream, group, id, deliveries, doc}`, is acked,
342
+ and `on_error` gets an `Ndb::PoisonMessage`. An own pending entry that
343
+ crashed the process `max_deliveries` times goes there at the next start,
344
+ without the block:
345
+
346
+ ```ruby
347
+ group = orders.group("billing")
348
+ group.ensure(Ndb::Stream::START_NEW) # or Ndb::Stream::START_ALL
349
+
350
+ worker = group.worker(
351
+ "worker-1",
352
+ count: 100,
353
+ claim_idle: 60,
354
+ max_deliveries: 5,
355
+ dead_letter: "orders_dead",
356
+ on_error: ->(error) { warn error.message }
357
+ ) { |entry| charge(entry.doc) }
358
+
359
+ trap("TERM") { worker.stop }
360
+
361
+ worker.run # blocks until worker.stop; worker.start runs it in a Thread
362
+ ```
363
+
364
+ `worker.stop` ends the loop after the current read (at most `block`
365
+ seconds). `group.work("worker-1", stop: -> { done }, **options) { |entry| ... }`
366
+ is the same loop in one call: it ends when the `stop` callable returns true.
367
+ Delivery is at least once: make the work safe to repeat. Run many workers
368
+ with different consumer names to share the work. A failed read goes to
369
+ `on_error` and is tried again after a backoff (0.1 s, doubled up to 5 s),
370
+ also when the group or the stream does not exist yet (`Ndb::UnknownGroup`,
371
+ `Ndb::UnknownCollection`): a worker that starts before its group waits for
372
+ it. Only `stop` ends the worker.
373
+
374
+ The calls one by one, when you need your own loop:
375
+
376
+ | Redis | Ruby |
377
+ |---|---|
378
+ | `XGROUP CREATE` | `group.create(Ndb::Stream::START_NEW)` / `group.ensure` |
379
+ | `XGROUP SETID` / `DESTROY` | `group.set_id(id)` / `group.destroy` |
380
+ | `XREADGROUP ... >` | `group.read("w1", count: 100, block: 5)` |
381
+ | `XREADGROUP ... 0` | `group.read("w1", pending: true)` |
382
+ | `XACK` | `group.ack(*ids)` |
383
+ | `XPENDING` | `group.pending` / `group.pending_list(idle: 60)` |
384
+ | `XCLAIM` / `XAUTOCLAIM` | `group.claim("w2", *ids, min_idle: 60)` / `group.auto_claim("w2", min_idle: 60, cursor: "0-0", count: 100)` |
385
+ | `XCLAIM ... IDLE` / `RETRYCOUNT` / `FORCE` / `JUSTID` | `group.claim("w2", *ids, idle: 90, retry_count: 5, force: true, just_ids: true)` |
386
+ | `XTRIM` | `orders.trim(max_len: 1000)` / `orders.trim(min_id: id)` |
387
+ | `XDEL` | `orders.delete(id)` |
388
+ | `XREVRANGE` | `orders.rev_range("+", "-", count: 10)` |
389
+ | `XREAD` | `orders.read(after: "0", count: 100, block: 5)` (`after: "$"`: only new entries) |
390
+ | `XINFO GROUPS` / `CONSUMERS` | `orders.groups` / `group.consumers` |
391
+
392
+ A read with `block` waits longer than the client `timeout`: the read timeout
393
+ of that one request is `block` + 5 seconds.
394
+
395
+ ### Delayed retry (ndb only)
396
+
397
+ With `retry:`, a worker gives a failed entry back to the group after a wait
398
+ that grows with its delivery count (`nack`). The entry has no owner while it
399
+ waits: a restart does not take it early, and any worker of the group takes
400
+ it when it is due. `max_age:` sends an entry older than that to the dead
401
+ letter (with `"reason" => "max_age"`), with no retry. The fsw-esl schedule
402
+ (try 1: 15 s, tries 2-5: 1 min, 6-11: 10 min, 12-23: 1 h, then 6 h):
403
+
404
+ ```ruby
405
+ group.work(
406
+ "w1",
407
+ retry: Ndb::Stream.tiers(
408
+ { wait: 15, up_to: 1 }, # try 1: 15 s
409
+ { wait: 60, up_to: 5 }, # tries 2 to 5: 1 min
410
+ { wait: 600, up_to: 11 }, # tries 6 to 11: 10 min
411
+ { wait: 3600, up_to: 23 }, # tries 12 to 23: 1 h
412
+ { wait: 21_600 } # then 6 h
413
+ ),
414
+ max_age: 15 * 86_400, # 15 days
415
+ dead_letter: "postcall_jobs_dead"
416
+ ) { |entry| post_call(entry.doc) }
417
+ ```
418
+
419
+ `retry:` also takes a callable `->(deliveries) { seconds }`, or an Array
420
+ with one wait for each try (`[15, 60, 600]`, the last one repeats). `due_every:` (1 s with `retry:`) is how often
421
+ the worker claims the due entries. The calls one by one:
422
+
423
+ | ndb only | Ruby |
424
+ |---|---|
425
+ | `nack` | `group.nack("w1", *ids, delay: 60)` (seconds; returns the count) |
426
+ | due claim | `group.claim_due("w2", cursor: "0-0", count: 100)` (an `Ndb::Claimed`) |
427
+ | pending | `group.pending["waiting"]`, `group.pending_list(due: true)`, each row `"retry_at"` (a `Time` or `nil`) |
428
+
429
+ A dead letter entry has `"reason"`: `"max_deliveries"` or `"max_age"`.
430
+
431
+ ## Redis Streams commands
432
+
433
+ `Ndb::Client` has the stream commands of the [redis-rb](https://github.com/redis/redis-rb)
434
+ gem (`Ndb::RedisCommands`), with the same arguments and the same answers as
435
+ redis-rb 5. An app that uses Redis Streams picks its backend in one place
436
+ and keeps its calls:
437
+
438
+ ```ruby
439
+ # config/initializers/streams.rb: the factory of the app
440
+ STREAMS = ENV["STREAMS_BACKEND"] == "ndb" ? Ndb.connect : Redis.new
441
+
442
+ STREAMS.xadd("orders", { order_id: 42 }, maxlen: 1000) # "1731164400000-0"
443
+ STREAMS.xgroup(:create, "orders", "billing", "$", mkstream: true) # "OK"
444
+ STREAMS.xreadgroup("billing", "w1", "orders", ">", count: 10, block: 5000) # { "orders" => [[id, { "order_id" => "42" }]] }
445
+ STREAMS.xack("orders", "billing", id) # 1
446
+ ```
447
+
448
+ Times are in milliseconds, as in redis-rb (`block:`, `min_idle_time`,
449
+ `idle:`).
450
+
451
+ | Method | Answer |
452
+ |---|---|
453
+ | `xadd(key, entry, approximate: nil, maxlen: nil, minid: nil, nomkstream: nil, id: "*")` | the ID (a String); `nil` with `nomkstream:` and no stream |
454
+ | `xlen(key)` | Integer (0 for no stream) |
455
+ | `xrange(key, start = "-", range_end = "+", count: nil)` | `[[id, { "field" => "value" }], ...]`; `"(id"` leaves the ID out |
456
+ | `xrevrange(key, range_end = "+", start = "-", count: nil)` | the same, from the highest ID |
457
+ | `xread(keys, ids, count: nil, block: nil)` | `{ "stream" => [[id, fields], ...] }`, only the streams with entries; `{}` for none |
458
+ | `xdel(key, *ids)` | how many it deleted |
459
+ | `xtrim(key, len_or_id, strategy: "MAXLEN", approximate: false, limit: nil)` | how many it deleted (`strategy: "MINID"` with an ID) |
460
+ | `xgroup(subcommand, key, group, id_or_consumer = nil, mkstream: false)` | `create`, `setid`: `"OK"`; `destroy`, `createconsumer`: 1 or 0; `delconsumer`: the pending count |
461
+ | `xreadgroup(group, consumer, keys, ids, count: nil, block: nil, noack: nil)` | as `xread`. `">"`: new entries. An ID (`"0"`): the pending entries of the consumer after it; the key is in the answer also with `[]`, and a deleted entry is `[id, nil]` |
462
+ | `xack(key, group, *ids)` | how many were pending |
463
+ | `xpending(key, group)` | `{ "size" => 2, "min_entry_id" => id, "max_entry_id" => id, "consumers" => { "w1" => "2" } }` |
464
+ | `xpending(key, group, start, end, count, consumer = nil, idle: nil)` | `[{ "entry_id" => id, "consumer" => "w1", "elapsed" => 1200, "count" => 1 }, ...]` |
465
+ | `xclaim(key, group, consumer, min_idle_time, *ids, idle:, retrycount:, force:, justid:)` | `[[id, fields], ...]`; the IDs with `justid: true` |
466
+ | `xautoclaim(key, group, consumer, min_idle_time, start, count: nil, justid: false)` | `{ "next" => "0-0", "entries" => [[id, fields], ...] }`; `"entries"` are IDs with `justid: true` |
467
+ | `xinfo(:stream, key)` | `{ "length", "last-generated-id", "max-deleted-entry-id", "entries-added", "recorded-first-entry-id", "groups", "first-entry", "last-entry" }`; an entry is `[id, [field, value, ...]]` |
468
+ | `xinfo(:groups, key)` | `[{ "name", "consumers", "pending", "last-delivered-id", "entries-read", "lag" }, ...]` |
469
+ | `xinfo(:consumers, key, group)` | `[{ "name", "pending", "idle", "inactive" }, ...]` |
470
+
471
+ The differences from Redis:
472
+
473
+ - **Values.** Redis keeps strings. ndb keeps the JSON value that `xadd` got:
474
+ a number stays a number and a nested Hash stays an object, so a query or
475
+ an index can use it. A read gives every value as a String, as Redis does:
476
+ a string as it is, a number or a boolean with `to_s` (`42` is `"42"`),
477
+ `nil` as `""`, and a nested value as its JSON text
478
+ (`{ city: "Recife" }` is `'{"city":"Recife"}'`). redis-rb refuses a nested
479
+ value in `xadd`; ndb takes it. Field names become Strings.
480
+ - **Field names.** A name that starts with `_` is reserved (`_id`, `_ts`).
481
+ - **Many streams.** ndb reads one stream for each request. `xread` and
482
+ `xreadgroup` with many keys and no `block:` send one request for each key,
483
+ in order. With `block:` and more than one key they raise
484
+ `Ndb::NotSupported`.
485
+ - **`block: 0`** waits with no limit, as in Redis: it is a loop of reads of
486
+ 30 seconds each. A blocking `xread` on a stream that does not exist looks
487
+ for the stream every 0.5 seconds until the time ends.
488
+ - **Errors** are `Ndb::Error` subclasses, not `Redis::CommandError`: rescue
489
+ both in code that runs on the two backends. The message starts as in
490
+ Redis, and the daemon message follows in parentheses:
491
+
492
+ | Case | Class | Message starts with |
493
+ |---|---|---|
494
+ | `xgroup(:create)` on a group that exists | `Ndb::GroupExists` | `BUSYGROUP` |
495
+ | a group command on a group or a stream that does not exist | `Ndb::UnknownGroup`, `Ndb::UnknownCollection` | `NOGROUP` |
496
+ | `xgroup(:create)` without `mkstream:` and no stream | `Ndb::UnknownCollection` | `ERR The XGROUP subcommand requires the key to exist` |
497
+ | `xinfo(:stream)` or `xinfo(:groups)` with no stream | `Ndb::UnknownCollection` | `ERR no such key` |
498
+
499
+ A different number of keys and IDs is an `ArgumentError`, sent before any
500
+ request.
501
+ - **`xclaim`** has `idle:`, `retrycount:`, `force:` and `justid:`. `time:`
502
+ raises `Ndb::NotSupported` (use `idle:`); any other option is an
503
+ `ArgumentError`.
504
+ - **`xinfo(:stream)`** has no `radix-tree-keys` and `radix-tree-nodes`, and
505
+ there is no `FULL` form.
506
+ - A trim or a delete keeps the pending references, as up to Redis 8.0.
507
+ `xautoclaim` and `xclaim` drop the pending IDs whose entry is gone.
508
+ - These are methods of `Ndb::Client`. There is no `multi`, `pipelined` or
509
+ other Redis command.
510
+
319
511
  ## Blobs
320
512
 
321
513
  Large values live in the blob store. A document keeps only a reference.
@@ -403,6 +595,8 @@ All errors inherit from `Ndb::Error`, which has `code` (the daemon code) and `st
403
595
  | `WatchLagged` | `watch_lagged` |
404
596
  | `HistoryTruncated` | `history_truncated` |
405
597
  | `TtlNotEnabled`, `TtlDerived` | `ttl_not_enabled`, `ttl_derived` |
598
+ | `NotAStream`, `InvalidStreamID`, `StreamIDTooSmall` (all `StreamError`) | `not_a_stream`, `invalid_stream_id`, `stream_id_too_small` |
599
+ | `UnknownGroup`, `GroupExists` | `unknown_group`, `group_exists` |
406
600
  | `ConnectionError` | cannot reach the daemon. Subclasses: `ConnectError` (nothing was sent), `TimeoutError` |
407
601
 
408
602
  Any other code (for example `unknown_route`, `pattern_read_only`) is a plain `Ndb::Error`. A response that is not a daemon error has the code `http_status`.
@@ -430,6 +624,13 @@ ndb = Ndb.connect("unix:///tmp/ndb-test.sock")
430
624
 
431
625
  Use a new collection name per test. Run the suite with `bundle exec rake test` in `sdk/ruby`.
432
626
 
627
+ The cases of the Redis Streams commands (`test/redis_commands_test.rb`) also run on a real Redis, to prove that the answers have the same shape, when `NDB_REDIS_ADDR` is set and the `redis` gem loads (it is not a dependency of this gem; without them the cases are skipped). They use their own keys and never flush the server:
628
+
629
+ ```sh
630
+ docker run -d --rm --name ndb-redis-rb -p 6391:6379 redis:7.4
631
+ NDB_REDIS_ADDR=redis://127.0.0.1:6391 bundle exec rake test
632
+ ```
633
+
433
634
  ## License
434
635
 
435
636
  MIT.
data/exe/ndb ADDED
@@ -0,0 +1,187 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ # The `ndb` command of the gem.
5
+ #
6
+ # bundle exec ndb streams [-r file] [-e env] [--only A,B] [-c N]
7
+ #
8
+ # runs the stream consumers of the app (the classes with
9
+ # `include Ndb::Streams`, from the ndb-rails gem). Every other command
10
+ # (serve, bench, -h, ...) goes to the ndb daemon binary, so the gem does not
11
+ # hide it when the two have the same name in PATH.
12
+
13
+ require "optparse"
14
+
15
+ module NdbCommand
16
+ RAILS_ENTRY = "config/environment.rb"
17
+ INSTALL_URL = "https://ndb.clowk.in"
18
+
19
+ EXIT_USAGE = 2
20
+ EXIT_NO_DAEMON = 127
21
+
22
+ # Set before the exec of the daemon. When this script runs again with it,
23
+ # the binary it found was a stub that came back to it (a version-manager
24
+ # shim): it stops, so it does not exec itself forever.
25
+ EXEC_MARKER = "NDB_GEM_EXEC"
26
+
27
+ # The first bytes of a native executable: ELF, and Mach-O (32 and 64 bit,
28
+ # both byte orders, and the universal format).
29
+ NATIVE_MAGIC = [
30
+ "\x7FELF".b,
31
+ "\xFE\xED\xFA\xCE".b, "\xFE\xED\xFA\xCF".b,
32
+ "\xCE\xFA\xED\xFE".b, "\xCF\xFA\xED\xFE".b,
33
+ "\xCA\xFE\xBA\xBE".b
34
+ ].freeze
35
+
36
+ # An error in the arguments or the setup of `ndb streams`: a message and
37
+ # exit 2. Other errors (in the boot of the app) keep their backtrace.
38
+ class UsageError < StandardError; end
39
+
40
+ module_function
41
+
42
+ def run(argv)
43
+ return streams(argv.drop(1)) if argv.first == "streams"
44
+
45
+ daemon(argv)
46
+ end
47
+
48
+ # ndb streams: loads the app, then runs the consumers until a signal.
49
+ def streams(argv)
50
+ options = parse(argv)
51
+
52
+ return 0 if options[:done]
53
+
54
+ ENV["RAILS_ENV"] = options[:environment] if options[:environment]
55
+
56
+ $stdout.sync = true
57
+
58
+ load_app(options[:require])
59
+ load_streams
60
+
61
+ Ndb::Streams.run(only: options[:only], concurrency: options[:concurrency])
62
+
63
+ 0
64
+ rescue OptionParser::ParseError, UsageError => e
65
+ usage_error(e)
66
+ rescue StandardError => e
67
+ raise unless config_error?(e)
68
+
69
+ usage_error(e)
70
+ end
71
+
72
+ def usage_error(error)
73
+ warn("ndb streams: #{error.message}")
74
+
75
+ EXIT_USAGE
76
+ end
77
+
78
+ # A wrong stream config of a class (no group, two classes on one group,
79
+ # an --only name that is not a class): a message, not a backtrace.
80
+ def config_error?(error)
81
+ defined?(Ndb::Streams::ConfigurationError) && error.is_a?(Ndb::Streams::ConfigurationError)
82
+ end
83
+
84
+ def parse(argv)
85
+ options = {}
86
+
87
+ parser = OptionParser.new do |opts|
88
+ opts.banner = "Usage: ndb streams [options]"
89
+
90
+ opts.on("-r", "--require PATH", "File that loads the stream classes (without Rails)") { |path| options[:require] = path }
91
+ opts.on("-e", "--environment NAME", "Environment name (RAILS_ENV)") { |name| options[:environment] = name }
92
+ opts.on("--only A,B", Array, "Run only these consumer classes") { |names| options[:only] = names }
93
+ opts.on("-c", "--concurrency N", Integer, "Threads of each consumer class") { |n| options[:concurrency] = n }
94
+
95
+ opts.on("-h", "--help", "Print this help") do
96
+ puts opts
97
+
98
+ options[:done] = true
99
+ end
100
+ end
101
+
102
+ rest = parser.parse(argv)
103
+
104
+ raise UsageError, "unexpected argument: #{rest.first}" unless rest.empty?
105
+ raise UsageError, "concurrency must be greater than 0" if options[:concurrency] && options[:concurrency] < 1
106
+
107
+ options
108
+ end
109
+
110
+ # The Rails app loads first, so its own config is there. -r loads a file
111
+ # more (or the classes, without Rails).
112
+ def load_app(path)
113
+ rails = File.exist?(RAILS_ENTRY)
114
+
115
+ raise UsageError, "no #{RAILS_ENTRY} here: use -r to load the stream classes" unless rails || path
116
+
117
+ require File.expand_path(RAILS_ENTRY) if rails
118
+ require File.expand_path(path) if path
119
+ end
120
+
121
+ def load_streams
122
+ require "ndb/streams"
123
+ rescue LoadError => e
124
+ raise unless e.path == "ndb/streams"
125
+
126
+ raise UsageError, "ndb streams needs the ndb-rails gem: add `gem \"ndb-rails\"` to the Gemfile"
127
+ end
128
+
129
+ # Replaces this process with the daemon binary and the same arguments.
130
+ def daemon(argv)
131
+ if ENV[EXEC_MARKER] == "1"
132
+ warn("ndb: the ndb binary found in PATH runs this script again (a shim of a version manager?).")
133
+ warn("Set NDB_BIN to the path of the ndb daemon binary.")
134
+
135
+ return EXIT_NO_DAEMON
136
+ end
137
+
138
+ binary = daemon_binary
139
+
140
+ if binary
141
+ ENV[EXEC_MARKER] = "1"
142
+
143
+ exec(binary, *argv)
144
+ end
145
+
146
+ warn("ndb: the ndb daemon binary is not installed (the gem only has `ndb streams`).")
147
+ warn("Install it: curl -fsSL #{INSTALL_URL}/install | sh")
148
+ warn("Or set NDB_BIN to the path of the binary.")
149
+
150
+ EXIT_NO_DAEMON
151
+ end
152
+
153
+ # NDB_BIN, or the first `ndb` of PATH that is a native executable (not
154
+ # this script, a binstub, or a shim of rbenv, mise or asdf).
155
+ def daemon_binary(env = ENV)
156
+ given = env["NDB_BIN"].to_s
157
+
158
+ return given unless given.empty?
159
+
160
+ env["PATH"].to_s.split(File::PATH_SEPARATOR).each do |dir|
161
+ next if dir.empty? || shims?(dir)
162
+
163
+ candidate = File.join(dir, "ndb")
164
+
165
+ return candidate if daemon?(candidate)
166
+ end
167
+
168
+ nil
169
+ end
170
+
171
+ def shims?(dir)
172
+ File.basename(dir) == "shims" || dir.include?("/shims/")
173
+ end
174
+
175
+ def daemon?(path)
176
+ return false unless File.file?(path) && File.executable?(path)
177
+ return false if File.realpath(path) == File.realpath(__FILE__)
178
+
179
+ head = File.binread(path, 4).to_s
180
+
181
+ NATIVE_MAGIC.include?(head)
182
+ rescue SystemCallError
183
+ false
184
+ end
185
+ end
186
+
187
+ exit(NdbCommand.run(ARGV))
data/lib/ndb/client.rb CHANGED
@@ -14,6 +14,9 @@ module Ndb
14
14
  # reads the answers; it has no query semantics. Ndb::Collection is the
15
15
  # friendlier layer on top of it.
16
16
  class Client
17
+ # The x* commands of redis-rb (xadd, xreadgroup, ...) on ndb streams.
18
+ include RedisCommands
19
+
17
20
  DEFAULT_SOCKET = "/run/ndb/ndb.sock"
18
21
 
19
22
  attr_reader :pool, :endpoint
@@ -43,6 +46,31 @@ module Ndb
43
46
  Collection.new(self, name, definition)
44
47
  end
45
48
 
49
+ # A stream (Redis Streams model) with its groups. See Ndb::Stream.
50
+ def stream(name)
51
+ Stream.new(self, name)
52
+ end
53
+
54
+ # One request to a stream route: /{coll}/{action} with a JSON body (nil:
55
+ # none). It returns the parsed JSON, or an Array of rows for an NDJSON
56
+ # answer. timeout (seconds) replaces the read timeout of this request.
57
+ def stream_request(method, coll, action, body, timeout: nil)
58
+ target = action.to_s.empty? ? path(coll) : "#{path(coll)}/#{action}"
59
+ response = request(method, target, body, timeout: timeout)
60
+
61
+ return ndjson(response.body) if response.headers["content-type"].to_s.include?("ndjson")
62
+
63
+ body = response.body.to_s.strip
64
+
65
+ body.empty? ? nil : JSON.parse(body)
66
+ end
67
+
68
+ # The timeout of the connections of this client, in seconds.
69
+ def timeout = @pool.timeout
70
+
71
+ # A path segment escaped for a URL (a group or consumer name).
72
+ def escape_segment(segment) = escape(segment)
73
+
46
74
  # POST /{coll}/_search: body is { "query", "sort", "fields", "limit",
47
75
  # "skip", "after", "count", ... }. Returns a Page.
48
76
  def search(coll, body = {})
@@ -320,15 +348,15 @@ module Ndb
320
348
  "#{path(coll)}/#{action}/#{escape(id)}"
321
349
  end
322
350
 
323
- def request(method, target, body, headers: {}, wait: true)
351
+ def request(method, target, body, headers: {}, wait: true, timeout: nil)
324
352
  payload = encode(body)
325
353
  headers = authorize(headers)
326
354
 
327
355
  safe = idempotent?(method, target) && !payload.respond_to?(:read)
328
- timeout = wait ? @ready_timeout : 0
356
+ ready = wait ? @ready_timeout : 0
329
357
 
330
- with_ready_retry(idempotent: safe, timeout: timeout) do
331
- response = @pool.with { |conn| conn.request(method, target, payload, headers: headers, idempotent: safe) }
358
+ with_ready_retry(idempotent: safe, timeout: ready) do
359
+ response = @pool.with { |conn| conn.request(method, target, payload, headers: headers, idempotent: safe, timeout: timeout) }
332
360
 
333
361
  raise_api_error(response) if response.status >= 300
334
362
 
@@ -105,12 +105,18 @@ module Ndb
105
105
  # body is a String, or an IO that is sent chunked and never retried. A
106
106
  # dropped reused connection is sent again only when idempotent is true
107
107
  # (a read): a write may already have been processed.
108
- def request(method, target, body, headers: {}, idempotent: false)
108
+ #
109
+ # timeout replaces the read timeout for this one request (a blocking
110
+ # stream read waits longer than the default). A read timeout
111
+ # (IO::TimeoutError) raises Ndb::TimeoutError and is never sent again.
112
+ def request(method, target, body, headers: {}, idempotent: false, timeout: nil)
109
113
  reused = !@socket.nil?
110
114
 
111
115
  begin
112
116
  send_request(method, target, body, headers)
113
- read_response
117
+ read_within(timeout)
118
+ rescue IO::TimeoutError
119
+ raise
114
120
  rescue EOFError, Errno::EPIPE, Errno::ECONNRESET, IOError
115
121
  close
116
122
 
@@ -120,14 +126,14 @@ module Ndb
120
126
 
121
127
  retry
122
128
  end
123
- rescue SystemCallError, EOFError, IOError => e
129
+ rescue IO::TimeoutError
124
130
  close
125
131
 
126
- raise ConnectionError, "cannot reach ndb at #{@endpoint}: #{e.message}"
127
- rescue IO::TimeoutError
132
+ raise TimeoutError, "ndb did not answer within #{timeout || @timeout}s"
133
+ rescue SystemCallError, EOFError, IOError => e
128
134
  close
129
135
 
130
- raise TimeoutError, "ndb did not answer within #{@timeout}s"
136
+ raise ConnectionError, "cannot reach ndb at #{@endpoint}: #{e.message}"
131
137
  end
132
138
 
133
139
  # Sends the request and yields the body of a 2xx response chunk by chunk,
@@ -147,10 +153,10 @@ module Ndb
147
153
  each_body_chunk(response_headers, &)
148
154
 
149
155
  Response.new(code, response_headers, nil)
150
- rescue SystemCallError, EOFError, IOError => e
151
- raise ConnectionError, "cannot reach ndb at #{@endpoint}: #{e.message}"
152
156
  rescue IO::TimeoutError
153
157
  raise TimeoutError, "ndb did not answer within #{@timeout}s"
158
+ rescue SystemCallError, EOFError, IOError => e
159
+ raise ConnectionError, "cannot reach ndb at #{@endpoint}: #{e.message}"
154
160
  ensure
155
161
  close
156
162
  end
@@ -196,6 +202,20 @@ module Ndb
196
202
  @socket.write("0\r\n\r\n")
197
203
  end
198
204
 
205
+ # Reads the response with a longer read timeout, then sets the default
206
+ # back for the next request on this connection.
207
+ def read_within(timeout)
208
+ return read_response unless timeout && @socket.respond_to?(:timeout=)
209
+
210
+ @socket.timeout = timeout
211
+
212
+ begin
213
+ read_response
214
+ ensure
215
+ @socket.timeout = @timeout if @socket
216
+ end
217
+ end
218
+
199
219
  def read_response
200
220
  status = @socket.gets("\r\n") or raise EOFError
201
221
  headers = read_headers
@@ -261,7 +281,7 @@ module Ndb
261
281
  # A small thread-safe pool: one connection per in-flight request, idle
262
282
  # ones are kept for keep-alive. It drops its connections after a fork.
263
283
  class Pool
264
- attr_reader :created
284
+ attr_reader :created, :timeout
265
285
 
266
286
  def initialize(endpoint, timeout:, size:)
267
287
  @endpoint = endpoint
@@ -273,16 +293,21 @@ module Ndb
273
293
  @pid = Process.pid
274
294
  end
275
295
 
296
+ # A connection goes back to the pool open only when the block ended
297
+ # with no raise. Any other end (an error, Timeout, Thread#kill) can
298
+ # leave an answer not read on it, so it is closed first.
276
299
  def with
277
300
  conn = checkout
301
+ ok = false
278
302
 
279
303
  begin
280
- yield conn
281
- rescue StandardError
282
- conn.close
304
+ result = yield conn
305
+ ok = true
283
306
 
284
- raise
307
+ result
285
308
  ensure
309
+ conn.close unless ok
310
+
286
311
  checkin(conn)
287
312
  end
288
313
  end
data/lib/ndb/errors.rb CHANGED
@@ -103,6 +103,21 @@ module Ndb
103
103
  # A bug or a disk error in the daemon; the message is in its log.
104
104
  class Internal < Error; end
105
105
 
106
+ # A stream route on a collection that is not a stream, a bad entry ID, or
107
+ # an append ID not greater than the last one.
108
+ class StreamError < Error; end
109
+ class NotAStream < StreamError; end
110
+
111
+ # A write route of every collection on a stream: add entries with append,
112
+ # delete them one by one or with a trim.
113
+ class StreamAppendOnly < StreamError; end
114
+ class InvalidStreamID < StreamError; end
115
+ class StreamIDTooSmall < StreamError; end
116
+
117
+ # The stream group does not exist, or a create names one that does.
118
+ class UnknownGroup < StreamError; end
119
+ class GroupExists < StreamError; end
120
+
106
121
  # The daemon error code -> the Ruby class.
107
122
  CODE_TO_ERROR = {
108
123
  "unauthorized" => Unauthorized,
@@ -150,6 +165,7 @@ module Ndb
150
165
  "pattern_too_wide" => InvalidPattern,
151
166
  "not_supported" => NotSupported,
152
167
  "invalid_blob_ref" => InvalidBlobRef,
168
+ "invalid_range" => InvalidBlobRef,
153
169
  "unknown_route" => UnknownRoute,
154
170
  "method_not_allowed" => UnknownRoute,
155
171
  "group_limit_exceeded" => GroupLimitExceeded,
@@ -158,7 +174,13 @@ module Ndb
158
174
  "invalid_position" => InvalidPosition,
159
175
  "closed" => Closed,
160
176
  "stopping" => Closed,
161
- "internal" => Internal
177
+ "internal" => Internal,
178
+ "not_a_stream" => NotAStream,
179
+ "stream_append_only" => StreamAppendOnly,
180
+ "invalid_stream_id" => InvalidStreamID,
181
+ "stream_id_too_small" => StreamIDTooSmall,
182
+ "unknown_group" => UnknownGroup,
183
+ "group_exists" => GroupExists
162
184
  }.freeze
163
185
 
164
186
  def self.error_for(code, message, status)