ndb 1.15.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: 8e76e86a39acdebcdcd4945f3a22e05618d97e9545d4031283d4acf032ec35a5
4
- data.tar.gz: ed2d63708606a6cd50e8538786f4c771667a9992cdca8f8dbec6f68de3cf4fcb
3
+ metadata.gz: 428c791af144a97e500ad55b220418af96665d17bf445292a9f35fc527b2634f
4
+ data.tar.gz: 7391f3da195c98022a27c6fae0302cf4bdbe80b3c0ea2d331fe1147f491f7503
5
5
  SHA512:
6
- metadata.gz: de0d0131d7a650df702c6911f7aa6c844a1e049600bba3aa7d0632bb5fe0b2301bc322d95cb359e6061d562f0dcc2200a79649bb7ed8f079eb0bc8e56d8a750f
7
- data.tar.gz: fca5c27619cc7bf26d4b1899cdcbd58e45909b1b5c6e67d93faec70cc49c6ca5b05182d5802af08f3354e21482372e3594271aaba44f6ded48933c6413fcd56e
6
+ metadata.gz: e54954a33518b2d8356c8e1cc0047f068b6827cf6e3f95096518d2edae93bf4dd4f8ec3168010ac2672acad5f01f2fa23dc2cef7ef394d4b105afb4c2a1b1d25
7
+ data.tar.gz: 244c15ef535531816a6f480d2ced513eec7984f59ed0ecd19c96c7661d1806fbedd4a146854c1539ff9b036f9650a61d92f345488825797af4423db7387f3b56
data/README.md CHANGED
@@ -335,10 +335,13 @@ orders.info # length, first and last ID, groups
335
335
 
336
336
  A worker in a group. It reads its own pending entries first, then new ones
337
337
  (waiting up to `block` seconds). A block that returns acks the entry; a
338
- block that raises leaves it pending. The worker also claims the entries
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
339
340
  other workers left idle. An entry delivered `max_deliveries` times goes to
340
341
  the dead-letter stream as `{stream, group, id, deliveries, doc}`, is acked,
341
- and `on_error` gets an `Ndb::PoisonMessage`:
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:
342
345
 
343
346
  ```ruby
344
347
  group = orders.group("billing")
@@ -362,7 +365,11 @@ worker.run # blocks until worker.stop; worker.start runs it in a Thread
362
365
  seconds). `group.work("worker-1", stop: -> { done }, **options) { |entry| ... }`
363
366
  is the same loop in one call: it ends when the `stop` callable returns true.
364
367
  Delivery is at least once: make the work safe to repeat. Run many workers
365
- with different consumer names to share the work.
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.
366
373
 
367
374
  The calls one by one, when you need your own loop:
368
375
 
@@ -375,14 +382,132 @@ The calls one by one, when you need your own loop:
375
382
  | `XACK` | `group.ack(*ids)` |
376
383
  | `XPENDING` | `group.pending` / `group.pending_list(idle: 60)` |
377
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)` |
378
386
  | `XTRIM` | `orders.trim(max_len: 1000)` / `orders.trim(min_id: id)` |
379
387
  | `XDEL` | `orders.delete(id)` |
380
388
  | `XREVRANGE` | `orders.rev_range("+", "-", count: 10)` |
389
+ | `XREAD` | `orders.read(after: "0", count: 100, block: 5)` (`after: "$"`: only new entries) |
381
390
  | `XINFO GROUPS` / `CONSUMERS` | `orders.groups` / `group.consumers` |
382
391
 
383
392
  A read with `block` waits longer than the client `timeout`: the read timeout
384
393
  of that one request is `block` + 5 seconds.
385
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
+
386
511
  ## Blobs
387
512
 
388
513
  Large values live in the blob store. A document keeps only a reference.
@@ -499,6 +624,13 @@ ndb = Ndb.connect("unix:///tmp/ndb-test.sock")
499
624
 
500
625
  Use a new collection name per test. Run the suite with `bundle exec rake test` in `sdk/ruby`.
501
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
+
502
634
  ## License
503
635
 
504
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
@@ -107,13 +107,16 @@ module Ndb
107
107
  # (a read): a write may already have been processed.
108
108
  #
109
109
  # timeout replaces the read timeout for this one request (a blocking
110
- # stream read waits longer than the default).
110
+ # stream read waits longer than the default). A read timeout
111
+ # (IO::TimeoutError) raises Ndb::TimeoutError and is never sent again.
111
112
  def request(method, target, body, headers: {}, idempotent: false, timeout: nil)
112
113
  reused = !@socket.nil?
113
114
 
114
115
  begin
115
116
  send_request(method, target, body, headers)
116
117
  read_within(timeout)
118
+ rescue IO::TimeoutError
119
+ raise
117
120
  rescue EOFError, Errno::EPIPE, Errno::ECONNRESET, IOError
118
121
  close
119
122
 
@@ -123,14 +126,14 @@ module Ndb
123
126
 
124
127
  retry
125
128
  end
126
- rescue SystemCallError, EOFError, IOError => e
129
+ rescue IO::TimeoutError
127
130
  close
128
131
 
129
- raise ConnectionError, "cannot reach ndb at #{@endpoint}: #{e.message}"
130
- rescue IO::TimeoutError
132
+ raise TimeoutError, "ndb did not answer within #{timeout || @timeout}s"
133
+ rescue SystemCallError, EOFError, IOError => e
131
134
  close
132
135
 
133
- raise TimeoutError, "ndb did not answer within #{@timeout}s"
136
+ raise ConnectionError, "cannot reach ndb at #{@endpoint}: #{e.message}"
134
137
  end
135
138
 
136
139
  # Sends the request and yields the body of a 2xx response chunk by chunk,
@@ -150,10 +153,10 @@ module Ndb
150
153
  each_body_chunk(response_headers, &)
151
154
 
152
155
  Response.new(code, response_headers, nil)
153
- rescue SystemCallError, EOFError, IOError => e
154
- raise ConnectionError, "cannot reach ndb at #{@endpoint}: #{e.message}"
155
156
  rescue IO::TimeoutError
156
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}"
157
160
  ensure
158
161
  close
159
162
  end
@@ -290,16 +293,21 @@ module Ndb
290
293
  @pid = Process.pid
291
294
  end
292
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.
293
299
  def with
294
300
  conn = checkout
301
+ ok = false
295
302
 
296
303
  begin
297
- yield conn
298
- rescue StandardError
299
- conn.close
304
+ result = yield conn
305
+ ok = true
300
306
 
301
- raise
307
+ result
302
308
  ensure
309
+ conn.close unless ok
310
+
303
311
  checkin(conn)
304
312
  end
305
313
  end
data/lib/ndb/errors.rb CHANGED
@@ -107,6 +107,10 @@ module Ndb
107
107
  # an append ID not greater than the last one.
108
108
  class StreamError < Error; end
109
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
110
114
  class InvalidStreamID < StreamError; end
111
115
  class StreamIDTooSmall < StreamError; end
112
116
 
@@ -161,6 +165,7 @@ module Ndb
161
165
  "pattern_too_wide" => InvalidPattern,
162
166
  "not_supported" => NotSupported,
163
167
  "invalid_blob_ref" => InvalidBlobRef,
168
+ "invalid_range" => InvalidBlobRef,
164
169
  "unknown_route" => UnknownRoute,
165
170
  "method_not_allowed" => UnknownRoute,
166
171
  "group_limit_exceeded" => GroupLimitExceeded,
@@ -171,6 +176,7 @@ module Ndb
171
176
  "stopping" => Closed,
172
177
  "internal" => Internal,
173
178
  "not_a_stream" => NotAStream,
179
+ "stream_append_only" => StreamAppendOnly,
174
180
  "invalid_stream_id" => InvalidStreamID,
175
181
  "stream_id_too_small" => StreamIDTooSmall,
176
182
  "unknown_group" => UnknownGroup,