ndb 1.14.0 → 1.15.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: 8e76e86a39acdebcdcd4945f3a22e05618d97e9545d4031283d4acf032ec35a5
4
+ data.tar.gz: ed2d63708606a6cd50e8538786f4c771667a9992cdca8f8dbec6f68de3cf4fcb
5
5
  SHA512:
6
- metadata.gz: 845cb4a57d3637bbe59978997f123c0ece7b6bbbc39136499e5e3e315384db3a4f80b4554a7e4c1d7f61b3f36b1f6e2517023f8406307ff23f463b2ec41fa6aa
7
- data.tar.gz: 5cb673f8fb02a3c10be40af8b084997dd12ce21aab3f09ce0ad0ca5c8fb4e2dd9b041c5f86527e56f958166ac4eab9d69f029b5b949130638e5e3eb9b386e43d
6
+ metadata.gz: de0d0131d7a650df702c6911f7aa6c844a1e049600bba3aa7d0632bb5fe0b2301bc322d95cb359e6061d562f0dcc2200a79649bb7ed8f079eb0bc8e56d8a750f
7
+ data.tar.gz: fca5c27619cc7bf26d4b1899cdcbd58e45909b1b5c6e67d93faec70cc49c6ca5b05182d5802af08f3354e21482372e3594271aaba44f6ded48933c6413fcd56e
data/README.md CHANGED
@@ -316,6 +316,73 @@ 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 leaves it pending. The worker also claims the entries
339
+ other workers left idle. An entry delivered `max_deliveries` times goes to
340
+ the dead-letter stream as `{stream, group, id, deliveries, doc}`, is acked,
341
+ and `on_error` gets an `Ndb::PoisonMessage`:
342
+
343
+ ```ruby
344
+ group = orders.group("billing")
345
+ group.ensure(Ndb::Stream::START_NEW) # or Ndb::Stream::START_ALL
346
+
347
+ worker = group.worker(
348
+ "worker-1",
349
+ count: 100,
350
+ claim_idle: 60,
351
+ max_deliveries: 5,
352
+ dead_letter: "orders_dead",
353
+ on_error: ->(error) { warn error.message }
354
+ ) { |entry| charge(entry.doc) }
355
+
356
+ trap("TERM") { worker.stop }
357
+
358
+ worker.run # blocks until worker.stop; worker.start runs it in a Thread
359
+ ```
360
+
361
+ `worker.stop` ends the loop after the current read (at most `block`
362
+ seconds). `group.work("worker-1", stop: -> { done }, **options) { |entry| ... }`
363
+ is the same loop in one call: it ends when the `stop` callable returns true.
364
+ Delivery is at least once: make the work safe to repeat. Run many workers
365
+ with different consumer names to share the work.
366
+
367
+ The calls one by one, when you need your own loop:
368
+
369
+ | Redis | Ruby |
370
+ |---|---|
371
+ | `XGROUP CREATE` | `group.create(Ndb::Stream::START_NEW)` / `group.ensure` |
372
+ | `XGROUP SETID` / `DESTROY` | `group.set_id(id)` / `group.destroy` |
373
+ | `XREADGROUP ... >` | `group.read("w1", count: 100, block: 5)` |
374
+ | `XREADGROUP ... 0` | `group.read("w1", pending: true)` |
375
+ | `XACK` | `group.ack(*ids)` |
376
+ | `XPENDING` | `group.pending` / `group.pending_list(idle: 60)` |
377
+ | `XCLAIM` / `XAUTOCLAIM` | `group.claim("w2", *ids, min_idle: 60)` / `group.auto_claim("w2", min_idle: 60, cursor: "0-0", count: 100)` |
378
+ | `XTRIM` | `orders.trim(max_len: 1000)` / `orders.trim(min_id: id)` |
379
+ | `XDEL` | `orders.delete(id)` |
380
+ | `XREVRANGE` | `orders.rev_range("+", "-", count: 10)` |
381
+ | `XINFO GROUPS` / `CONSUMERS` | `orders.groups` / `group.consumers` |
382
+
383
+ A read with `block` waits longer than the client `timeout`: the read timeout
384
+ of that one request is `block` + 5 seconds.
385
+
319
386
  ## Blobs
320
387
 
321
388
  Large values live in the blob store. A document keeps only a reference.
@@ -403,6 +470,8 @@ All errors inherit from `Ndb::Error`, which has `code` (the daemon code) and `st
403
470
  | `WatchLagged` | `watch_lagged` |
404
471
  | `HistoryTruncated` | `history_truncated` |
405
472
  | `TtlNotEnabled`, `TtlDerived` | `ttl_not_enabled`, `ttl_derived` |
473
+ | `NotAStream`, `InvalidStreamID`, `StreamIDTooSmall` (all `StreamError`) | `not_a_stream`, `invalid_stream_id`, `stream_id_too_small` |
474
+ | `UnknownGroup`, `GroupExists` | `unknown_group`, `group_exists` |
406
475
  | `ConnectionError` | cannot reach the daemon. Subclasses: `ConnectError` (nothing was sent), `TimeoutError` |
407
476
 
408
477
  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`.
data/lib/ndb/client.rb CHANGED
@@ -43,6 +43,31 @@ module Ndb
43
43
  Collection.new(self, name, definition)
44
44
  end
45
45
 
46
+ # A stream (Redis Streams model) with its groups. See Ndb::Stream.
47
+ def stream(name)
48
+ Stream.new(self, name)
49
+ end
50
+
51
+ # One request to a stream route: /{coll}/{action} with a JSON body (nil:
52
+ # none). It returns the parsed JSON, or an Array of rows for an NDJSON
53
+ # answer. timeout (seconds) replaces the read timeout of this request.
54
+ def stream_request(method, coll, action, body, timeout: nil)
55
+ target = action.to_s.empty? ? path(coll) : "#{path(coll)}/#{action}"
56
+ response = request(method, target, body, timeout: timeout)
57
+
58
+ return ndjson(response.body) if response.headers["content-type"].to_s.include?("ndjson")
59
+
60
+ body = response.body.to_s.strip
61
+
62
+ body.empty? ? nil : JSON.parse(body)
63
+ end
64
+
65
+ # The timeout of the connections of this client, in seconds.
66
+ def timeout = @pool.timeout
67
+
68
+ # A path segment escaped for a URL (a group or consumer name).
69
+ def escape_segment(segment) = escape(segment)
70
+
46
71
  # POST /{coll}/_search: body is { "query", "sort", "fields", "limit",
47
72
  # "skip", "after", "count", ... }. Returns a Page.
48
73
  def search(coll, body = {})
@@ -320,15 +345,15 @@ module Ndb
320
345
  "#{path(coll)}/#{action}/#{escape(id)}"
321
346
  end
322
347
 
323
- def request(method, target, body, headers: {}, wait: true)
348
+ def request(method, target, body, headers: {}, wait: true, timeout: nil)
324
349
  payload = encode(body)
325
350
  headers = authorize(headers)
326
351
 
327
352
  safe = idempotent?(method, target) && !payload.respond_to?(:read)
328
- timeout = wait ? @ready_timeout : 0
353
+ ready = wait ? @ready_timeout : 0
329
354
 
330
- with_ready_retry(idempotent: safe, timeout: timeout) do
331
- response = @pool.with { |conn| conn.request(method, target, payload, headers: headers, idempotent: safe) }
355
+ with_ready_retry(idempotent: safe, timeout: ready) do
356
+ response = @pool.with { |conn| conn.request(method, target, payload, headers: headers, idempotent: safe, timeout: timeout) }
332
357
 
333
358
  raise_api_error(response) if response.status >= 300
334
359
 
@@ -105,12 +105,15 @@ 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).
111
+ def request(method, target, body, headers: {}, idempotent: false, timeout: nil)
109
112
  reused = !@socket.nil?
110
113
 
111
114
  begin
112
115
  send_request(method, target, body, headers)
113
- read_response
116
+ read_within(timeout)
114
117
  rescue EOFError, Errno::EPIPE, Errno::ECONNRESET, IOError
115
118
  close
116
119
 
@@ -196,6 +199,20 @@ module Ndb
196
199
  @socket.write("0\r\n\r\n")
197
200
  end
198
201
 
202
+ # Reads the response with a longer read timeout, then sets the default
203
+ # back for the next request on this connection.
204
+ def read_within(timeout)
205
+ return read_response unless timeout && @socket.respond_to?(:timeout=)
206
+
207
+ @socket.timeout = timeout
208
+
209
+ begin
210
+ read_response
211
+ ensure
212
+ @socket.timeout = @timeout if @socket
213
+ end
214
+ end
215
+
199
216
  def read_response
200
217
  status = @socket.gets("\r\n") or raise EOFError
201
218
  headers = read_headers
@@ -261,7 +278,7 @@ module Ndb
261
278
  # A small thread-safe pool: one connection per in-flight request, idle
262
279
  # ones are kept for keep-alive. It drops its connections after a fork.
263
280
  class Pool
264
- attr_reader :created
281
+ attr_reader :created, :timeout
265
282
 
266
283
  def initialize(endpoint, timeout:, size:)
267
284
  @endpoint = endpoint
data/lib/ndb/errors.rb CHANGED
@@ -103,6 +103,17 @@ 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
+ class InvalidStreamID < StreamError; end
111
+ class StreamIDTooSmall < StreamError; end
112
+
113
+ # The stream group does not exist, or a create names one that does.
114
+ class UnknownGroup < StreamError; end
115
+ class GroupExists < StreamError; end
116
+
106
117
  # The daemon error code -> the Ruby class.
107
118
  CODE_TO_ERROR = {
108
119
  "unauthorized" => Unauthorized,
@@ -158,7 +169,12 @@ module Ndb
158
169
  "invalid_position" => InvalidPosition,
159
170
  "closed" => Closed,
160
171
  "stopping" => Closed,
161
- "internal" => Internal
172
+ "internal" => Internal,
173
+ "not_a_stream" => NotAStream,
174
+ "invalid_stream_id" => InvalidStreamID,
175
+ "stream_id_too_small" => StreamIDTooSmall,
176
+ "unknown_group" => UnknownGroup,
177
+ "group_exists" => GroupExists
162
178
  }.freeze
163
179
 
164
180
  def self.error_for(code, message, status)
data/lib/ndb/stream.rb ADDED
@@ -0,0 +1,285 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Ndb
4
+ # One entry of a stream. id is "<ms>-<seq>", time is the ms of the id,
5
+ # doc is the Hash without "_id" and "_ts". A deleted entry was pending, but
6
+ # it is no longer in the stream (a trim or a delete); its doc is nil.
7
+ Entry = Data.define(:id, :time, :doc, :deleted, :raw) do
8
+ def deleted? = deleted
9
+
10
+ # The entry from one row of the daemon.
11
+ def self.from(row)
12
+ id = row["_id"]
13
+
14
+ if row["_deleted"]
15
+ return new(id: id, time: Stream.id_time(id), doc: nil, deleted: true, raw: row)
16
+ end
17
+
18
+ doc = row.reject { |key, _| key == "_id" || key == "_ts" }
19
+
20
+ new(id: id, time: Stream.id_time(id), doc: doc, deleted: false, raw: row)
21
+ end
22
+ end
23
+
24
+ # The answer of Group#claim and Group#auto_claim. cursor is where the next
25
+ # auto_claim starts ("0-0" when the scan is complete; nil for claim).
26
+ # deleted holds the pending IDs whose entry is no longer in the stream.
27
+ Claimed = Data.define(:cursor, :entries, :deleted)
28
+
29
+ # A stream: an append-only log with consumer groups, with the behavior of
30
+ # Redis Streams (see docs/dev/streams.md). Get one with client.stream(name).
31
+ # It sends nothing until the first call.
32
+ class Stream
33
+ # The group reads only the entries appended after it ($).
34
+ START_NEW = "$"
35
+
36
+ # The group reads every entry of the stream (0).
37
+ START_ALL = "0"
38
+
39
+ attr_reader :client, :name
40
+
41
+ # The time of an entry ID (its ms part), or nil for a bad ID.
42
+ def self.id_time(id)
43
+ ms, _, seq = id.to_s.partition("-")
44
+
45
+ return nil if seq.empty? || !ms.match?(/\A\d+\z/)
46
+
47
+ Time.at(ms.to_i / 1000, ms.to_i % 1000, :millisecond).utc
48
+ end
49
+
50
+ def initialize(client, name)
51
+ @client = client
52
+ @name = name
53
+ end
54
+
55
+ # Makes the stream, or checks that name is one. append and Group#create
56
+ # make it too; create is for a stream with options (indexes, retention).
57
+ def create(definition = {})
58
+ call("PUT", "", definition.merge(stream: true))
59
+ end
60
+
61
+ # Adds one entry and returns its ID (XADD). id: "<ms>-<seq>" or
62
+ # "<ms>-*" (default "*": the daemon makes it). trim: a Hash as in #trim,
63
+ # run after the append. no_create: true raises UnknownCollection when the
64
+ # stream does not exist.
65
+ def append(doc, id: nil, trim: nil, no_create: false)
66
+ body = append_body({ doc: doc }, id, trim, no_create)
67
+
68
+ call("POST", "_streams/append", body).fetch("_id")
69
+ end
70
+
71
+ # Adds the entries in order, with one fsync for all, and returns their
72
+ # IDs. id: applies to the first entry.
73
+ def append_many(docs, id: nil, trim: nil, no_create: false)
74
+ body = append_body({ docs: docs }, id, trim, no_create)
75
+
76
+ call("POST", "_streams/append", body).fetch("ids")
77
+ end
78
+
79
+ # Deletes old entries and returns how many (XTRIM). max_len: keeps the
80
+ # newest N entries; min_id: deletes the entries with a lower ID.
81
+ # approx: true deletes only whole blocks of 1 024 entries; limit caps
82
+ # the count with approx.
83
+ def trim(max_len: nil, min_id: nil, approx: false, limit: nil)
84
+ body = trim_body(max_len: max_len, min_id: min_id, approx: approx, limit: limit)
85
+
86
+ call("POST", "_streams/trim", body).fetch("deleted")
87
+ end
88
+
89
+ # The state of the stream (XINFO STREAM): "length", "first_id",
90
+ # "last_id", "entries_added", "max_deleted_id", "groups".
91
+ def info
92
+ call("GET", "_streams", nil)
93
+ end
94
+
95
+ # The groups of the stream (XINFO GROUPS): one Hash per group with
96
+ # "name", "consumers", "pending", "last_delivered_id", "entries_read",
97
+ # "lag" (nil when it cannot be known).
98
+ def groups
99
+ call("GET", "_streams/groups", nil) || []
100
+ end
101
+
102
+ # Up to count entries with an ID from start to stop, both included, in
103
+ # ID order (XRANGE). "-" and "+" are the lowest and the highest ID.
104
+ def range(start = "-", stop = "+", count: nil)
105
+ range_of(start, stop, count, 1)
106
+ end
107
+
108
+ # range from stop down to start (XREVRANGE).
109
+ def rev_range(stop = "+", start = "-", count: nil)
110
+ range_of(start, stop, count, -1)
111
+ end
112
+
113
+ # Removes one entry by ID (XDEL). Returns 1, or 0 when it is not there.
114
+ def delete(id)
115
+ call("DELETE", "_doc/#{@client.escape_segment(id)}", nil).fetch("deleted")
116
+ end
117
+
118
+ # The consumer group name of the stream. It sends nothing.
119
+ def group(name)
120
+ Group.new(self, name)
121
+ end
122
+
123
+ # One request to /{stream}/{action}. A Hash, an Array of rows, or nil.
124
+ def call(method, action, body, timeout: nil)
125
+ @client.stream_request(method, @name, action, body, timeout: timeout)
126
+ end
127
+
128
+ # The entries of a request whose answer is rows.
129
+ def entries(action, body, timeout: nil)
130
+ rows = call("POST", action, body, timeout: timeout) || []
131
+
132
+ rows.map { |row| Entry.from(row) }
133
+ end
134
+
135
+ private
136
+
137
+ def append_body(body, id, trim, no_create)
138
+ body[:id] = id if id
139
+ body[:trim] = trim_body(**trim) if trim
140
+ body[:no_create] = true if no_create
141
+
142
+ body
143
+ end
144
+
145
+ def trim_body(max_len: nil, min_id: nil, approx: false, limit: nil)
146
+ body = { max_len: max_len, min_id: min_id, limit: limit }.compact
147
+ body[:approx] = true if approx
148
+
149
+ body
150
+ end
151
+
152
+ def range_of(start, stop, count, order)
153
+ body = { query: { _id: { "$gte" => start, "$lte" => stop } }, sort: { _id: order } }
154
+ body[:limit] = count if count
155
+
156
+ entries("_search", body)
157
+ end
158
+ end
159
+
160
+ # One consumer group of a stream. Each entry goes to one consumer of the
161
+ # group and stays pending until it is acked.
162
+ class Group
163
+ # A blocking read waits this many seconds more than block before the
164
+ # client gives up on the answer.
165
+ BLOCK_MARGIN = 5
166
+
167
+ attr_reader :stream, :name
168
+
169
+ def initialize(stream, name)
170
+ @stream = stream
171
+ @name = name
172
+ end
173
+
174
+ # Makes the group (XGROUP CREATE ... MKSTREAM). start is Stream::START_NEW
175
+ # ("$"), Stream::START_ALL ("0") or an ID. A group that exists raises
176
+ # GroupExists.
177
+ def create(start = Stream::START_NEW)
178
+ @stream.call("PUT", path, { start: start })
179
+ end
180
+
181
+ # Makes the group, or does nothing when it exists.
182
+ def ensure(start = Stream::START_NEW)
183
+ create(start)
184
+ rescue GroupExists
185
+ nil
186
+ end
187
+
188
+ # Moves the last delivered ID of the group (XGROUP SETID).
189
+ def set_id(id)
190
+ @stream.call("POST", path("setid"), { id: id })
191
+ end
192
+
193
+ # Deletes the group and its pending entries (XGROUP DESTROY).
194
+ def destroy
195
+ @stream.call("DELETE", path, nil)
196
+ end
197
+
198
+ # Makes a consumer. True when it is new. A read makes the consumer too.
199
+ def create_consumer(consumer)
200
+ @stream.call("PUT", path("consumers", consumer), nil).fetch("created")
201
+ end
202
+
203
+ # Deletes a consumer and its pending entries. Returns how many it held
204
+ # (XGROUP DELCONSUMER).
205
+ def delete_consumer(consumer)
206
+ @stream.call("DELETE", path("consumers", consumer), nil).fetch("pending")
207
+ end
208
+
209
+ # The consumers of the group (XINFO CONSUMERS): "name", "pending",
210
+ # "idle_ms", "inactive_ms".
211
+ def consumers
212
+ @stream.call("GET", path("consumers"), nil) || []
213
+ end
214
+
215
+ # Gives entries to consumer (XREADGROUP): new ones by default, which
216
+ # become pending for consumer. pending: true gives its own pending ones
217
+ # with an ID greater than after. block (seconds, a Float is fine) waits
218
+ # for a new entry when there is none. Returns an Array of Entry.
219
+ def read(consumer, count: nil, block: nil, pending: false, after: nil, no_ack: false, fields: nil)
220
+ body = { consumer: consumer, count: count, after: after, fields: fields }.compact
221
+ body[:pending] = true if pending
222
+ body[:no_ack] = true if no_ack
223
+
224
+ block_ms = block ? (block * 1000).round : 0
225
+ body[:block_ms] = block_ms if block_ms.positive?
226
+
227
+ timeout = block_ms.positive? ? [@stream.client.timeout, block + BLOCK_MARGIN].max : nil
228
+
229
+ @stream.entries(path("read"), body, timeout: timeout)
230
+ end
231
+
232
+ # Ends the work on the entries. Returns how many were pending (XACK). An
233
+ # ID that is not pending counts 0.
234
+ def ack(*ids)
235
+ ids = ids.flatten
236
+
237
+ return 0 if ids.empty?
238
+
239
+ @stream.call("POST", path("ack"), { ids: ids }).fetch("acked")
240
+ end
241
+
242
+ # The pending list in short (XPENDING): "count", "lowest", "highest",
243
+ # "consumers" ([{"name", "count"}]).
244
+ def pending
245
+ @stream.call("POST", path("pending"), {})
246
+ end
247
+
248
+ # Pending entries in ID order (XPENDING with a range). Each one is a Hash
249
+ # with "_id", "consumer", "idle_ms", "deliveries". idle: seconds; only
250
+ # the entries idle for at least this long.
251
+ def pending_list(start: "-", stop: "+", count: 100, consumer: nil, idle: nil)
252
+ body = { start: start, end: stop, count: count, consumer: consumer }.compact
253
+ body[:idle_ms] = (idle * 1000).round if idle && idle.positive?
254
+
255
+ @stream.call("POST", path("pending"), body) || []
256
+ end
257
+
258
+ # Moves the entries idle for at least min_idle seconds to consumer
259
+ # (XCLAIM). Each one gets one more delivery. Returns a Claimed.
260
+ def claim(consumer, *ids, min_idle: 0)
261
+ claim_with(consumer: consumer, min_idle_ms: (min_idle * 1000).round, ids: ids.flatten)
262
+ end
263
+
264
+ # Scans the pending list from cursor and moves up to count entries idle
265
+ # for at least min_idle seconds to consumer (XAUTOCLAIM).
266
+ def auto_claim(consumer, min_idle: 0, cursor: "0-0", count: nil)
267
+ claim_with({ consumer: consumer, min_idle_ms: (min_idle * 1000).round, cursor: cursor, count: count }.compact)
268
+ end
269
+
270
+ private
271
+
272
+ def path(*parts)
273
+ segments = ["_streams", "groups", @name, *parts].map { |part| @stream.client.escape_segment(part) }
274
+
275
+ segments.join("/")
276
+ end
277
+
278
+ def claim_with(body)
279
+ out = @stream.call("POST", path("claim"), body)
280
+ entries = (out["entries"] || []).map { |row| Entry.from(row) }
281
+
282
+ Claimed.new(cursor: out["cursor"], entries: entries, deleted: out["deleted"] || [])
283
+ end
284
+ end
285
+ end
@@ -0,0 +1,245 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Ndb
4
+ # The error on_error gets for a poison message: an entry delivered
5
+ # max_deliveries times. It was sent to the dead letter and acked.
6
+ class PoisonMessage < Error
7
+ attr_reader :entry, :deliveries
8
+
9
+ def initialize(message, entry:, deliveries:)
10
+ super(message, code: "poison_message")
11
+
12
+ @entry = entry
13
+ @deliveries = deliveries
14
+ end
15
+ end
16
+
17
+ # A worker of a group: it runs the block on each entry. A block that
18
+ # returns acks the entry; a block that raises leaves it pending, and a
19
+ # worker of the group claims it again after claim_idle.
20
+ #
21
+ # worker = orders.group("billing").worker("w1", max_deliveries: 5) { |e| charge(e.doc) }
22
+ # thread = worker.start # or worker.run, which blocks
23
+ # worker.stop # ends the loop after the current read
24
+ #
25
+ # Delivery is at least once: the work on an entry must be safe to repeat.
26
+ class Worker
27
+ attr_reader :group, :consumer
28
+
29
+ # count: the most entries per read (10). block: how long a read waits
30
+ # for new entries, in seconds (5). claim_idle: entries pending this
31
+ # long, of any consumer, are claimed and tried again (60; nil or a
32
+ # negative value turns the claim off). claim_every: how often to look
33
+ # for them (claim_idle / 2, at least 1). max_deliveries: an entry
34
+ # delivered this many times goes to dead_letter (a stream name) and is
35
+ # acked; nil is no limit. on_error: a callable that gets the errors that
36
+ # do not stop the worker (a failed read, a raise in the block, a
37
+ # PoisonMessage).
38
+ def initialize(group, consumer, count: 10, block: 5, claim_idle: 60, claim_every: nil, max_deliveries: nil, dead_letter: nil, on_error: nil, &handler)
39
+ raise ArgumentError, "a worker needs a block" unless handler
40
+
41
+ @group = group
42
+ @consumer = consumer
43
+ @handler = handler
44
+
45
+ @count = count
46
+ @block = block
47
+ @claim_idle = claim_idle && claim_idle.positive? ? claim_idle : nil
48
+ @claim_every = claim_every || [(@claim_idle || 0) / 2.0, 1].max
49
+ @max_deliveries = max_deliveries
50
+ @dead_letter = dead_letter
51
+ @on_error = on_error
52
+
53
+ @stopped = false
54
+ end
55
+
56
+ # Runs the loop in this thread until #stop. It:
57
+ #
58
+ # 1. reads its own pending entries first (the ones it took before a
59
+ # restart and did not ack), and does the work on them;
60
+ # 2. reads new entries, waiting up to block for them;
61
+ # 3. acks the entries the block did without a raise, in one call;
62
+ # 4. every claim_every, claims the entries idle for claim_idle, and
63
+ # sends the ones delivered max_deliveries times to dead_letter.
64
+ def run
65
+ work_pending
66
+
67
+ next_claim = now + @claim_every
68
+ backoff = 0
69
+
70
+ until stopped?
71
+ if @claim_idle && now >= next_claim
72
+ work_idle
73
+
74
+ next_claim = now + @claim_every
75
+ end
76
+
77
+ wait = @claim_idle ? [@block, next_claim - now].min : @block
78
+
79
+ begin
80
+ entries = @group.read(@consumer, count: @count, block: [wait, 0.001].max)
81
+ rescue Ndb::Error => e
82
+ report(e)
83
+
84
+ backoff = [[backoff * 2, 0.1].max, 5].min
85
+
86
+ pause(backoff)
87
+
88
+ next
89
+ end
90
+
91
+ backoff = 0
92
+
93
+ handle(entries)
94
+ end
95
+
96
+ nil
97
+ end
98
+
99
+ # Runs the loop in a new Thread and returns it.
100
+ def start
101
+ Thread.new { run }
102
+ end
103
+
104
+ # Asks the loop to end. It ends after the current read (at most block
105
+ # seconds) and the work on the entries of that read.
106
+ def stop
107
+ @stopped = true
108
+ end
109
+
110
+ def stopped? = @stopped
111
+
112
+ private
113
+
114
+ def now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
115
+
116
+ def pause(seconds)
117
+ deadline = now + seconds
118
+
119
+ sleep 0.01 while !stopped? && now < deadline
120
+ end
121
+
122
+ def report(error)
123
+ @on_error&.call(error)
124
+ end
125
+
126
+ # The consumer's own pending entries, in ID order. An entry that fails
127
+ # stays pending; the loop moves past it.
128
+ def work_pending
129
+ after = "0"
130
+
131
+ until stopped?
132
+ entries = @group.read(@consumer, count: @count, pending: true, after: after)
133
+
134
+ return if entries.empty?
135
+
136
+ handle(entries)
137
+
138
+ after = entries.last.id
139
+ end
140
+ end
141
+
142
+ # Claims the idle entries of the group. The poison ones go to the dead
143
+ # letter; the others run again.
144
+ def work_idle
145
+ idle = @group.pending_list(idle: @claim_idle, count: @count)
146
+
147
+ return if idle.empty?
148
+
149
+ deliveries = idle.to_h { |p| [p["_id"], p["deliveries"]] }
150
+ claimed = @group.claim(@consumer, deliveries.keys, min_idle: @claim_idle)
151
+
152
+ retry_entries = claimed.entries.reject do |entry|
153
+ n = deliveries[entry.id]
154
+
155
+ next false unless @max_deliveries && n >= @max_deliveries
156
+
157
+ bury(entry, n)
158
+
159
+ true
160
+ end
161
+
162
+ handle(retry_entries)
163
+ rescue Ndb::Error => e
164
+ report(e)
165
+ end
166
+
167
+ # Sends a poison entry to the dead letter, acks it, then reports it.
168
+ def bury(entry, deliveries)
169
+ stream = @group.stream
170
+
171
+ if @dead_letter
172
+ dead = { stream: stream.name, group: @group.name, id: entry.id, deliveries: deliveries, doc: entry.doc }
173
+
174
+ stream.client.stream(@dead_letter).append(dead)
175
+ end
176
+
177
+ @group.ack(entry.id)
178
+
179
+ report(PoisonMessage.new("poison message: #{stream.name}/#{@group.name} #{entry.id} after #{deliveries} deliveries", entry: entry, deliveries: deliveries))
180
+ rescue Ndb::Error => e
181
+ report(e)
182
+ end
183
+
184
+ # Runs the block on each entry and acks the ones that worked, in one
185
+ # call. A deleted entry is acked without the block.
186
+ def handle(entries)
187
+ done = []
188
+
189
+ entries.each do |entry|
190
+ break if stopped?
191
+
192
+ if entry.deleted?
193
+ done << entry.id
194
+
195
+ next
196
+ end
197
+
198
+ begin
199
+ @handler.call(entry)
200
+
201
+ done << entry.id
202
+ rescue StandardError => e
203
+ report(e)
204
+ end
205
+ end
206
+
207
+ return if done.empty?
208
+
209
+ begin
210
+ @group.ack(done)
211
+ rescue Ndb::Error => e
212
+ report(e)
213
+ end
214
+ end
215
+ end
216
+
217
+ class Group
218
+ # A Worker of this group as consumer, with the block as the handler. See
219
+ # Worker#initialize for the options.
220
+ def worker(consumer, **options, &handler)
221
+ Worker.new(self, consumer, **options, &handler)
222
+ end
223
+
224
+ # Runs a worker in this thread until it is stopped. Pass stop: a callable
225
+ # that returns true to end the loop (it is checked after each read), or
226
+ # build one with #worker and call Worker#stop from another thread.
227
+ def work(consumer, stop: nil, **options, &handler)
228
+ worker = Worker.new(self, consumer, **options, &handler)
229
+
230
+ return worker.run unless stop
231
+
232
+ watcher = Thread.new do
233
+ sleep 0.05 until stop.call || worker.stopped?
234
+
235
+ worker.stop
236
+ end
237
+
238
+ begin
239
+ worker.run
240
+ ensure
241
+ watcher.kill
242
+ end
243
+ end
244
+ end
245
+ end
data/lib/ndb/version.rb CHANGED
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Ndb
4
- VERSION = "1.14.0"
4
+ VERSION = "1.15.0"
5
5
  end
data/lib/ndb.rb CHANGED
@@ -7,3 +7,5 @@ require "ndb/conditions"
7
7
  require "ndb/connection"
8
8
  require "ndb/client"
9
9
  require "ndb/collection"
10
+ require "ndb/stream"
11
+ require "ndb/stream_worker"
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: ndb
3
3
  version: !ruby/object:Gem::Version
4
- version: 1.14.0
4
+ version: 1.15.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - thadeu
@@ -25,6 +25,8 @@ files:
25
25
  - lib/ndb/connection.rb
26
26
  - lib/ndb/errors.rb
27
27
  - lib/ndb/id.rb
28
+ - lib/ndb/stream.rb
29
+ - lib/ndb/stream_worker.rb
28
30
  - lib/ndb/version.rb
29
31
  homepage: https://ndb.clowk.in
30
32
  licenses: