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.
data/lib/ndb/stream.rb ADDED
@@ -0,0 +1,363 @@
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, Group#auto_claim and Group#claim_due. cursor
25
+ # is where the next scan starts ("0-0" when the scan is complete; nil for
26
+ # claim).
27
+ # deleted holds the pending IDs whose entry is no longer in the stream.
28
+ Claimed = Data.define(:cursor, :entries, :deleted)
29
+
30
+ # A stream: an append-only log with consumer groups, with the behavior of
31
+ # Redis Streams (see docs/dev/streams.md). Get one with client.stream(name).
32
+ # It sends nothing until the first call.
33
+ class Stream
34
+ # The group reads only the entries appended after it ($).
35
+ START_NEW = "$"
36
+
37
+ # The group reads every entry of the stream (0).
38
+ START_ALL = "0"
39
+
40
+ # A blocking read waits this many seconds more than block before the
41
+ # client gives up on the answer.
42
+ BLOCK_MARGIN = 5
43
+
44
+ attr_reader :client, :name
45
+
46
+ # The time of an entry ID (its ms part), or nil for a bad ID.
47
+ def self.id_time(id)
48
+ ms, _, seq = id.to_s.partition("-")
49
+
50
+ return nil if seq.empty? || !ms.match?(/\A\d+\z/)
51
+
52
+ time_of_ms(ms.to_i)
53
+ end
54
+
55
+ # The Time of a Unix time in milliseconds, or nil for nil.
56
+ def self.time_of_ms(ms)
57
+ return nil if ms.nil?
58
+
59
+ Time.at(ms / 1000, ms % 1000, :millisecond).utc
60
+ end
61
+
62
+ def initialize(client, name)
63
+ @client = client
64
+ @name = name
65
+ end
66
+
67
+ # Makes the stream, or checks that name is one. append and Group#create
68
+ # make it too; create is for a stream with options (indexes, retention).
69
+ def create(definition = {})
70
+ call("PUT", "", definition.merge(stream: true))
71
+ end
72
+
73
+ # Adds one entry and returns its ID (XADD). id: "<ms>-<seq>" or
74
+ # "<ms>-*" (default "*": the daemon makes it). trim: a Hash as in #trim,
75
+ # run after the append. no_create: true raises UnknownCollection when the
76
+ # stream does not exist.
77
+ def append(doc, id: nil, trim: nil, no_create: false)
78
+ body = append_body({ doc: doc }, id, trim, no_create)
79
+
80
+ call("POST", "_streams/append", body).fetch("_id")
81
+ end
82
+
83
+ # Adds the entries in order, with one fsync for all, and returns their
84
+ # IDs. id: applies to the first entry.
85
+ def append_many(docs, id: nil, trim: nil, no_create: false)
86
+ body = append_body({ docs: docs }, id, trim, no_create)
87
+
88
+ call("POST", "_streams/append", body).fetch("ids")
89
+ end
90
+
91
+ # Deletes old entries and returns how many (XTRIM). max_len: keeps the
92
+ # newest N entries; min_id: deletes the entries with a lower ID.
93
+ # approx: true deletes only whole blocks of 1 024 entries; limit caps
94
+ # the count with approx.
95
+ def trim(max_len: nil, min_id: nil, approx: false, limit: nil)
96
+ body = trim_body(max_len: max_len, min_id: min_id, approx: approx, limit: limit)
97
+
98
+ call("POST", "_streams/trim", body).fetch("deleted")
99
+ end
100
+
101
+ # The state of the stream (XINFO STREAM): "length", "first_id",
102
+ # "last_id", "entries_added", "max_deleted_id", "groups".
103
+ def info
104
+ call("GET", "_streams", nil)
105
+ end
106
+
107
+ # The groups of the stream (XINFO GROUPS): one Hash per group with
108
+ # "name", "consumers", "pending", "last_delivered_id", "entries_read",
109
+ # "lag" (nil when it cannot be known).
110
+ def groups
111
+ call("GET", "_streams/groups", nil) || []
112
+ end
113
+
114
+ # Up to count entries with an ID from start to stop, both included, in
115
+ # ID order (XRANGE). "-" and "+" are the lowest and the highest ID.
116
+ def range(start = "-", stop = "+", count: nil)
117
+ range_of(start, stop, count, 1)
118
+ end
119
+
120
+ # range from stop down to start (XREVRANGE).
121
+ def rev_range(stop = "+", start = "-", count: nil)
122
+ range_of(start, stop, count, -1)
123
+ end
124
+
125
+ # Up to count entries with an ID greater than after, in ID order, without
126
+ # a group (XREAD). after is an ID ("0": from the start) or "$": only the
127
+ # entries appended after the request starts. block (seconds, a Float is
128
+ # fine) waits for an entry when there is none. To read on, give the last
129
+ # ID of the answer as after (not "$" again). Returns an Array of Entry.
130
+ def read(after: START_ALL, count: nil, block: nil, fields: nil)
131
+ body = { after: after, count: count, fields: fields }.compact
132
+
133
+ entries("_streams/read", body, **block_options(body, block))
134
+ end
135
+
136
+ # Removes one entry by ID (XDEL). Returns 1, or 0 when it is not there.
137
+ def delete(id)
138
+ call("DELETE", "_doc/#{@client.escape_segment(id)}", nil).fetch("deleted")
139
+ end
140
+
141
+ # The consumer group name of the stream. It sends nothing.
142
+ def group(name)
143
+ Group.new(self, name)
144
+ end
145
+
146
+ # One request to /{stream}/{action}. A Hash, an Array of rows, or nil.
147
+ def call(method, action, body, timeout: nil)
148
+ @client.stream_request(method, @name, action, body, timeout: timeout)
149
+ end
150
+
151
+ # The entries of a request whose answer is rows.
152
+ def entries(action, body, timeout: nil)
153
+ rows = call("POST", action, body, timeout: timeout) || []
154
+
155
+ rows.map { |row| Entry.from(row) }
156
+ end
157
+
158
+ # Puts block (seconds) in body as block_ms. Returns the options of the
159
+ # request: a read timeout long enough for the wait.
160
+ def block_options(body, block)
161
+ block_ms = block ? (block * 1000).round : 0
162
+
163
+ return {} unless block_ms.positive?
164
+
165
+ body[:block_ms] = block_ms
166
+
167
+ { timeout: [@client.timeout, block + BLOCK_MARGIN].max }
168
+ end
169
+
170
+ private
171
+
172
+ def append_body(body, id, trim, no_create)
173
+ body[:id] = id if id
174
+ body[:trim] = trim_body(**trim) if trim
175
+ body[:no_create] = true if no_create
176
+
177
+ body
178
+ end
179
+
180
+ def trim_body(max_len: nil, min_id: nil, approx: false, limit: nil)
181
+ body = { max_len: max_len, min_id: min_id, limit: limit }.compact
182
+ body[:approx] = true if approx
183
+
184
+ body
185
+ end
186
+
187
+ def range_of(start, stop, count, order)
188
+ body = { query: { _id: { "$gte" => start, "$lte" => stop } }, sort: { _id: order } }
189
+ body[:limit] = count if count
190
+
191
+ entries("_search", body)
192
+ end
193
+ end
194
+
195
+ # One consumer group of a stream. Each entry goes to one consumer of the
196
+ # group and stays pending until it is acked.
197
+ class Group
198
+ BLOCK_MARGIN = Stream::BLOCK_MARGIN
199
+
200
+ attr_reader :stream, :name
201
+
202
+ def initialize(stream, name)
203
+ @stream = stream
204
+ @name = name
205
+ end
206
+
207
+ # Makes the group (XGROUP CREATE ... MKSTREAM). start is Stream::START_NEW
208
+ # ("$"), Stream::START_ALL ("0") or an ID. A group that exists raises
209
+ # GroupExists. no_create: true raises UnknownCollection when the stream
210
+ # does not exist.
211
+ def create(start = Stream::START_NEW, no_create: false)
212
+ body = { start: start }
213
+ body[:no_create] = true if no_create
214
+
215
+ @stream.call("PUT", path, body)
216
+ end
217
+
218
+ # Makes the group, or does nothing when it exists.
219
+ def ensure(start = Stream::START_NEW)
220
+ create(start)
221
+ rescue GroupExists
222
+ nil
223
+ end
224
+
225
+ # Moves the last delivered ID of the group (XGROUP SETID).
226
+ def set_id(id)
227
+ @stream.call("POST", path("setid"), { id: id })
228
+ end
229
+
230
+ # Deletes the group and its pending entries (XGROUP DESTROY).
231
+ def destroy
232
+ @stream.call("DELETE", path, nil)
233
+ end
234
+
235
+ # Makes a consumer. True when it is new. A read makes the consumer too.
236
+ def create_consumer(consumer)
237
+ @stream.call("PUT", path("consumers", consumer), nil).fetch("created")
238
+ end
239
+
240
+ # Deletes a consumer and its pending entries. Returns how many it held
241
+ # (XGROUP DELCONSUMER).
242
+ def delete_consumer(consumer)
243
+ @stream.call("DELETE", path("consumers", consumer), nil).fetch("pending")
244
+ end
245
+
246
+ # The consumers of the group (XINFO CONSUMERS): "name", "pending",
247
+ # "idle_ms", "inactive_ms".
248
+ def consumers
249
+ @stream.call("GET", path("consumers"), nil) || []
250
+ end
251
+
252
+ # Gives entries to consumer (XREADGROUP): new ones by default, which
253
+ # become pending for consumer. pending: true gives its own pending ones
254
+ # with an ID greater than after. block (seconds, a Float is fine) waits
255
+ # for a new entry when there is none. Returns an Array of Entry.
256
+ def read(consumer, count: nil, block: nil, pending: false, after: nil, no_ack: false, fields: nil)
257
+ body = { consumer: consumer, count: count, after: after, fields: fields }.compact
258
+ body[:pending] = true if pending
259
+ body[:no_ack] = true if no_ack
260
+
261
+ @stream.entries(path("read"), body, **@stream.block_options(body, block))
262
+ end
263
+
264
+ # Ends the work on the entries. Returns how many were pending (XACK). An
265
+ # ID that is not pending counts 0.
266
+ def ack(*ids)
267
+ ids = ids.flatten
268
+
269
+ return 0 if ids.empty?
270
+
271
+ @stream.call("POST", path("ack"), { ids: ids }).fetch("acked")
272
+ end
273
+
274
+ # Gives entries back to the group after delay seconds (a Float is
275
+ # fine), for a retry (ndb only). Returns how many it gave back: only the
276
+ # IDs pending for consumer count. The entry stays pending with no owner
277
+ # ("consumer" "") until its retry time, and its delivery count does not
278
+ # change. After the retry time, any consumer takes it with #claim_due
279
+ # (or #claim). delay 0 makes it due at once; the most is 30 days.
280
+ def nack(consumer, *ids, delay: 0)
281
+ ids = ids.flatten
282
+
283
+ return 0 if ids.empty?
284
+
285
+ body = { consumer: consumer, ids: ids, delay_ms: (delay * 1000).round }
286
+
287
+ @stream.call("POST", path("nack"), body).fetch("nacked")
288
+ end
289
+
290
+ # The pending list in short (XPENDING): "count", "lowest", "highest",
291
+ # "consumers" ([{"name", "count"}]), and "waiting" (ndb only): the
292
+ # nacked entries whose retry time has not come.
293
+ def pending
294
+ @stream.call("POST", path("pending"), {})
295
+ end
296
+
297
+ # Pending entries in ID order (XPENDING with a range). Each one is a Hash
298
+ # with "_id", "consumer", "idle_ms", "deliveries" and "retry_at" (ndb
299
+ # only): the retry time (a Time) of a nacked entry, or nil. A nacked
300
+ # entry has "consumer" "". idle: seconds; only the entries idle for at
301
+ # least this long. due: true gives only the nacked entries whose retry
302
+ # time passed; false only the ones that still wait (ndb only).
303
+ def pending_list(start: "-", stop: "+", count: 100, consumer: nil, idle: nil, due: nil)
304
+ body = { start: start, end: stop, count: count, consumer: consumer, due: due }.compact
305
+ body[:idle_ms] = (idle * 1000).round if idle && idle.positive?
306
+
307
+ rows = @stream.call("POST", path("pending"), body) || []
308
+
309
+ rows.each { |row| row["retry_at"] = Stream.time_of_ms(row["retry_at"]) }
310
+ end
311
+
312
+ # Moves the entries idle for at least min_idle seconds to consumer
313
+ # (XCLAIM). Each one gets one more delivery. Returns a Claimed.
314
+ # idle: (seconds) sets the idle time of the entries; retry_count: sets
315
+ # their delivery count; force: true also takes an ID that is not pending.
316
+ # just_ids: true gives IDs (Strings) as entries, and the delivery count
317
+ # does not change.
318
+ def claim(consumer, *ids, min_idle: 0, idle: nil, retry_count: nil, force: false, just_ids: false)
319
+ body = { consumer: consumer, min_idle_ms: (min_idle * 1000).round, ids: ids.flatten }
320
+ body[:idle_ms] = (idle * 1000).round if idle
321
+ body[:retry_count] = retry_count if retry_count
322
+ body[:force] = true if force
323
+
324
+ claim_with(body, just_ids)
325
+ end
326
+
327
+ # Scans the pending list from cursor and moves up to count entries idle
328
+ # for at least min_idle seconds to consumer (XAUTOCLAIM). just_ids: as
329
+ # in #claim.
330
+ def auto_claim(consumer, min_idle: 0, cursor: "0-0", count: nil, just_ids: false)
331
+ body = { consumer: consumer, min_idle_ms: (min_idle * 1000).round, cursor: cursor, count: count }.compact
332
+
333
+ claim_with(body, just_ids)
334
+ end
335
+
336
+ # Scans the nacked entries from cursor and moves up to count of the ones
337
+ # whose retry time passed to consumer (ndb only). It looks only at the
338
+ # nacked entries, not at the entries in flight at live workers, so a
339
+ # worker can call it often. just_ids: as in #claim.
340
+ def claim_due(consumer, cursor: "0-0", count: nil, just_ids: false)
341
+ body = { consumer: consumer, due: true, cursor: cursor, count: count }.compact
342
+
343
+ claim_with(body, just_ids)
344
+ end
345
+
346
+ private
347
+
348
+ def path(*parts)
349
+ segments = ["_streams", "groups", @name, *parts].map { |part| @stream.client.escape_segment(part) }
350
+
351
+ segments.join("/")
352
+ end
353
+
354
+ def claim_with(body, just_ids = false)
355
+ body[:just_ids] = true if just_ids
356
+
357
+ out = @stream.call("POST", path("claim"), body)
358
+ entries = (out["entries"] || []).map { |row| row.is_a?(Hash) ? Entry.from(row) : row }
359
+
360
+ Claimed.new(cursor: out["cursor"], entries: entries, deleted: out["deleted"] || [])
361
+ end
362
+ end
363
+ end