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.
@@ -0,0 +1,503 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+
5
+ module Ndb
6
+ # The stream commands of the redis-rb gem (Redis::Commands::Streams), on ndb
7
+ # streams. Ndb::Client includes it, so an app that uses Redis Streams picks
8
+ # its backend in one place and keeps its calls:
9
+ #
10
+ # STREAMS = ENV["STREAMS_BACKEND"] == "ndb" ? Ndb.connect : Redis.new
11
+ #
12
+ # STREAMS.xadd("orders", { order_id: 42 }, maxlen: 1000)
13
+ #
14
+ # The arguments and the answers have the shapes of redis-rb 5. What is
15
+ # different from Redis:
16
+ #
17
+ # - Values. Redis keeps strings. ndb keeps the JSON value that xadd got
18
+ # (a number stays a number, a nested Hash stays an object). A read gives
19
+ # each value as a String: a string as it is, a number or a boolean with
20
+ # to_s, null as "", a nested value as its JSON text.
21
+ # - A field name cannot start with "_".
22
+ # - One stream for each request. Many keys without block: are one request
23
+ # for each key. Many keys with block: raise Ndb::NotSupported.
24
+ # - Errors are Ndb::Error subclasses, not Redis::CommandError. The message
25
+ # starts as in Redis where an app looks at it ("BUSYGROUP", "NOGROUP").
26
+ # - xclaim has no time: option. xinfo(:stream) has no radix-tree keys.
27
+ module RedisCommands
28
+ # A read with block: 0 waits with no limit, as in Redis. It is a loop of
29
+ # reads that wait this many seconds each.
30
+ FOREVER_STEP = 30
31
+
32
+ # A blocking xread on a stream that does not exist looks for it again
33
+ # after this many seconds.
34
+ MISSING_STEP = 0.5
35
+
36
+ # A read without count: gives up to this many entries for each stream
37
+ # (the most of one ndb read). Redis gives every entry.
38
+ REDIS_READ_COUNT = 10_000
39
+
40
+ # XADD. Returns the ID of the entry (a String), or nil with nomkstream:
41
+ # when the stream does not exist. The values of entry are kept as given.
42
+ def xadd(key, entry, approximate: nil, maxlen: nil, minid: nil, nomkstream: nil, id: "*")
43
+ raise ArgumentError, "can't supply both maxlen and minid" if maxlen && minid
44
+
45
+ trim = { max_len: Integer(maxlen), approx: approximate ? true : false } if maxlen
46
+ trim = { min_id: minid.to_s, approx: approximate ? true : false } if minid
47
+
48
+ doc = entry.to_h.transform_keys(&:to_s)
49
+ entry_id = id.to_s == "*" ? nil : id.to_s
50
+
51
+ stream(key).append(doc, id: entry_id, trim: trim, no_create: nomkstream ? true : false)
52
+ rescue UnknownCollection
53
+ raise unless nomkstream
54
+
55
+ nil
56
+ end
57
+
58
+ # XTRIM. Returns how many entries it deleted.
59
+ def xtrim(key, len_or_id, strategy: "MAXLEN", approximate: false, limit: nil)
60
+ options = { approx: approximate ? true : false, limit: limit }
61
+
62
+ case strategy.to_s.upcase
63
+ when "MAXLEN" then options[:max_len] = Integer(len_or_id)
64
+ when "MINID" then options[:min_id] = len_or_id.to_s
65
+ else raise ArgumentError, "strategy must be MAXLEN or MINID, not #{strategy.inspect}"
66
+ end
67
+
68
+ stream(key).trim(**options)
69
+ rescue UnknownCollection
70
+ 0
71
+ end
72
+
73
+ # XDEL. Returns how many entries it deleted.
74
+ def xdel(key, *ids)
75
+ ids.flatten.sum { |id| stream(key).delete(id) }
76
+ rescue UnknownCollection
77
+ 0
78
+ end
79
+
80
+ # XRANGE. Returns [[id, { "field" => "value" }], ...] in ID order. An ID
81
+ # with "(" in front is not included, as in Redis.
82
+ def xrange(key, start = "-", range_end = "+", count: nil)
83
+ redis_range(key, start, range_end, count, 1)
84
+ end
85
+
86
+ # XREVRANGE: xrange from range_end down to start.
87
+ def xrevrange(key, range_end = "+", start = "-", count: nil)
88
+ redis_range(key, start, range_end, count, -1)
89
+ end
90
+
91
+ # XLEN. 0 for a stream that does not exist.
92
+ def xlen(key)
93
+ stream(key).info.fetch("length")
94
+ rescue UnknownCollection
95
+ 0
96
+ end
97
+
98
+ # XREAD. keys and ids are one value or an Array of each. Returns
99
+ # { "stream" => [[id, fields], ...] } with only the streams that have
100
+ # entries ({} when there is none). block: is in milliseconds (0: no
101
+ # limit) and is for one key only.
102
+ def xread(keys, ids, count: nil, block: nil)
103
+ pairs = redis_stream_pairs(keys, ids, block)
104
+ out = {}
105
+
106
+ pairs.each do |key, id|
107
+ after = id.to_s
108
+
109
+ # A wait with no limit reads in steps: "$" is the last ID before the
110
+ # first step, so an entry added between two steps is not lost.
111
+ after = redis_last_id(key) if after == "$" && !block.nil? && block.to_i <= 0
112
+
113
+ entries = redis_block(block) { |seconds| redis_read(key, after, count || REDIS_READ_COUNT, seconds) }
114
+
115
+ out[key.to_s] = redis_entries(entries) unless entries.empty?
116
+ end
117
+
118
+ out
119
+ end
120
+
121
+ # XGROUP. subcommand is create, setid, destroy, createconsumer or
122
+ # delconsumer. Returns "OK" for create and setid, and a count for the
123
+ # others. create without mkstream: needs a stream that exists.
124
+ def xgroup(subcommand, key, group, id_or_consumer = nil, mkstream: false)
125
+ target = stream(key).group(group)
126
+
127
+ case subcommand.to_s.downcase
128
+ when "create" then redis_group_create(key, group, target, id_or_consumer, mkstream)
129
+ when "setid" then redis_group_setid(key, group, target, id_or_consumer)
130
+ when "destroy" then redis_group_destroy(target)
131
+ when "createconsumer"
132
+ redis_group_errors(key, group) { target.create_consumer(redis_required(id_or_consumer, "consumer")) ? 1 : 0 }
133
+ when "delconsumer"
134
+ redis_group_errors(key, group) { target.delete_consumer(redis_required(id_or_consumer, "consumer")) }
135
+ else
136
+ raise ArgumentError, "unknown xgroup subcommand #{subcommand.inspect}"
137
+ end
138
+ end
139
+
140
+ # XREADGROUP. An ID ">" gives new entries; any other ID gives the pending
141
+ # entries of consumer after that ID (and the key is in the answer also
142
+ # when it has none, as in Redis). A pending entry that was deleted from
143
+ # the stream comes as [id, nil]. block: is in milliseconds (0: no limit),
144
+ # is for one key only, and is not used for a pending read.
145
+ def xreadgroup(group, consumer, keys, ids, count: nil, block: nil, noack: nil)
146
+ pairs = redis_stream_pairs(keys, ids, block)
147
+ out = {}
148
+
149
+ pairs.each do |key, id|
150
+ target = stream(key).group(group)
151
+ pending = id.to_s != ">"
152
+
153
+ entries = redis_group_errors(key, group) do
154
+ if pending
155
+ target.read(consumer, count: count || REDIS_READ_COUNT, pending: true, after: id.to_s)
156
+ else
157
+ redis_block(block) { |seconds| target.read(consumer, count: count || REDIS_READ_COUNT, block: seconds, no_ack: noack ? true : false) }
158
+ end
159
+ end
160
+
161
+ out[key.to_s] = redis_entries(entries) if pending || !entries.empty?
162
+ end
163
+
164
+ out
165
+ end
166
+
167
+ # XACK. Returns how many entries were pending.
168
+ def xack(key, group, *ids)
169
+ stream(key).group(group).ack(*ids)
170
+ rescue UnknownGroup, UnknownCollection
171
+ 0
172
+ end
173
+
174
+ # XCLAIM. min_idle_time and idle: are in milliseconds. Returns
175
+ # [[id, fields], ...], or the IDs with justid: true. Options: idle:,
176
+ # retrycount:, force:, justid:. time: is not supported.
177
+ def xclaim(key, group, consumer, min_idle_time, *ids, **opts)
178
+ redis_claim_options(opts)
179
+
180
+ claimed = redis_group_errors(key, group) do
181
+ stream(key).group(group).claim(
182
+ consumer,
183
+ *ids,
184
+ min_idle: Integer(min_idle_time) / 1000.0,
185
+ idle: opts[:idle] && (opts[:idle].to_i / 1000.0),
186
+ retry_count: opts[:retrycount],
187
+ force: opts[:force] ? true : false,
188
+ just_ids: opts[:justid] ? true : false
189
+ )
190
+ end
191
+
192
+ opts[:justid] ? claimed.entries : redis_entries(claimed.entries)
193
+ end
194
+
195
+ # XAUTOCLAIM. min_idle_time is in milliseconds. Returns
196
+ # { "next" => cursor, "entries" => [[id, fields], ...] } ("entries" are
197
+ # IDs with justid: true). "next" is "0-0" when the scan is complete.
198
+ def xautoclaim(key, group, consumer, min_idle_time, start, count: nil, justid: false)
199
+ claimed = redis_group_errors(key, group) do
200
+ stream(key).group(group).auto_claim(
201
+ consumer,
202
+ min_idle: Integer(min_idle_time) / 1000.0,
203
+ cursor: start.to_s,
204
+ count: count && Integer(count),
205
+ just_ids: justid ? true : false
206
+ )
207
+ end
208
+
209
+ { "next" => claimed.cursor, "entries" => justid ? claimed.entries : redis_entries(claimed.entries) }
210
+ end
211
+
212
+ # XPENDING. xpending(key, group) returns the summary: { "size",
213
+ # "min_entry_id", "max_entry_id", "consumers" => { name => "count" } }.
214
+ # xpending(key, group, start, end, count[, consumer]) returns one Hash
215
+ # for each entry: { "entry_id", "consumer", "elapsed" (ms), "count" }.
216
+ # idle: (milliseconds) keeps only the entries idle for at least this long.
217
+ def xpending(key, group, *args, idle: nil)
218
+ unless [0, 3, 4].include?(args.size)
219
+ raise ArgumentError, "wrong number of arguments (given #{args.size + 2}, expected 2, 5 or 6)"
220
+ end
221
+
222
+ target = stream(key).group(group)
223
+
224
+ redis_group_errors(key, group) do
225
+ next redis_pending_summary(target.pending) if args.empty?
226
+
227
+ start, stop, count, consumer = args
228
+ seconds = idle && (Integer(idle) / 1000.0)
229
+
230
+ rows = target.pending_list(start: start.to_s, stop: stop.to_s, count: Integer(count), consumer: consumer, idle: seconds)
231
+
232
+ rows.map { |row| redis_pending_row(row) }
233
+ end
234
+ end
235
+
236
+ # XINFO. subcommand is stream, groups or consumers (with group). Returns
237
+ # a Hash (stream) or an Array of Hash, with the key names of Redis.
238
+ def xinfo(subcommand, key, group = nil)
239
+ case subcommand.to_s.downcase
240
+ when "stream" then redis_no_key(key) { redis_stream_info(key) }
241
+ when "groups" then redis_no_key(key) { stream(key).groups.map { |row| redis_group_info(row) } }
242
+ when "consumers"
243
+ target = stream(key).group(redis_required(group, "group"))
244
+
245
+ redis_group_errors(key, group) { target.consumers.map { |row| redis_consumer_info(row) } }
246
+ else
247
+ raise ArgumentError, "unknown xinfo subcommand #{subcommand.inspect}"
248
+ end
249
+ end
250
+
251
+ private
252
+
253
+ # The fields of an entry as Redis gives them: every value is a String.
254
+ def redis_fields(doc)
255
+ doc.to_h { |field, value| [field.to_s, redis_value(value)] }
256
+ end
257
+
258
+ def redis_value(value)
259
+ case value
260
+ when String then value
261
+ when Hash, Array then JSON.generate(value)
262
+ else value.to_s
263
+ end
264
+ end
265
+
266
+ # [[id, fields], ...] from Ndb::Entry values. A deleted entry has nil
267
+ # fields.
268
+ def redis_entries(entries)
269
+ entries.map { |entry| [entry.id, entry.deleted? ? nil : redis_fields(entry.doc)] }
270
+ end
271
+
272
+ def redis_range(key, start, stop, count, order)
273
+ low = redis_bound(start, "$gte", "$gt")
274
+ high = redis_bound(stop, "$lte", "$lt")
275
+
276
+ body = { query: { _id: low.merge(high) }, sort: { _id: order } }
277
+ body[:limit] = Integer(count) if count
278
+
279
+ redis_entries(stream(key).entries("_search", body))
280
+ rescue UnknownCollection
281
+ []
282
+ end
283
+
284
+ # One side of a range: "(id" leaves the ID out.
285
+ def redis_bound(id, inclusive, exclusive)
286
+ id = id.to_s
287
+
288
+ return { exclusive => id[1..] } if id.start_with?("(")
289
+
290
+ { inclusive => id }
291
+ end
292
+
293
+ # The [key, id] pairs of xread and xreadgroup.
294
+ def redis_stream_pairs(keys, ids, block)
295
+ keys = Array(keys)
296
+ ids = Array(ids)
297
+
298
+ if keys.size != ids.size
299
+ raise ArgumentError, "Unbalanced list of streams: for each stream key an ID must be specified"
300
+ end
301
+
302
+ if block && keys.size > 1
303
+ raise NotSupported, "ndb reads one stream for each request: block: with #{keys.size} streams is not supported"
304
+ end
305
+
306
+ keys.zip(ids)
307
+ end
308
+
309
+ # Runs the read with its wait in seconds. block is in milliseconds:
310
+ # nil does not wait, 0 waits until there is an entry.
311
+ def redis_block(block)
312
+ return yield(nil) if block.nil?
313
+
314
+ ms = block.to_i
315
+
316
+ return yield(ms / 1000.0) if ms.positive?
317
+
318
+ loop do
319
+ entries = yield(FOREVER_STEP)
320
+
321
+ return entries unless entries.empty?
322
+ end
323
+ end
324
+
325
+ # One xread of one stream. A stream that does not exist has no entries;
326
+ # with a wait, the read looks for the stream until the time ends.
327
+ def redis_read(key, after, count, seconds)
328
+ target = stream(key)
329
+
330
+ if seconds.nil?
331
+ return after == "$" ? [] : redis_missing_empty { target.read(after: after, count: count) }
332
+ end
333
+
334
+ deadline = redis_now + seconds
335
+
336
+ loop do
337
+ left = deadline - redis_now
338
+
339
+ return [] unless left.positive?
340
+
341
+ begin
342
+ return target.read(after: after, count: count, block: left)
343
+ rescue UnknownCollection
344
+ after = Stream::START_ALL if after == "$"
345
+
346
+ sleep [left, MISSING_STEP].min
347
+ end
348
+ end
349
+ end
350
+
351
+ # The last ID of the stream, or START_ALL when it does not exist.
352
+ def redis_last_id(key)
353
+ stream(key).info.fetch("last_id")
354
+ rescue UnknownCollection
355
+ Stream::START_ALL
356
+ end
357
+
358
+ def redis_missing_empty
359
+ yield
360
+ rescue UnknownCollection
361
+ []
362
+ end
363
+
364
+ def redis_now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
365
+
366
+ def redis_group_create(key, group, target, id, mkstream)
367
+ redis_group_errors(key, group, missing_key: !mkstream) do
368
+ target.create(redis_required(id, "id").to_s, no_create: !mkstream)
369
+ end
370
+
371
+ "OK"
372
+ end
373
+
374
+ def redis_group_setid(key, group, target, id)
375
+ redis_group_errors(key, group) { target.set_id(redis_required(id, "id").to_s) }
376
+
377
+ "OK"
378
+ end
379
+
380
+ def redis_group_destroy(target)
381
+ target.destroy
382
+
383
+ 1
384
+ rescue UnknownGroup, UnknownCollection
385
+ 0
386
+ end
387
+
388
+ def redis_required(value, name)
389
+ raise ArgumentError, "#{name} is required for this subcommand" if value.nil?
390
+
391
+ value
392
+ end
393
+
394
+ def redis_claim_options(opts)
395
+ unknown = opts.keys - %i[idle time retrycount force justid]
396
+
397
+ raise ArgumentError, "unknown xclaim options: #{unknown.join(", ")}" unless unknown.empty?
398
+
399
+ raise NotSupported, "xclaim time: is not supported by ndb; use idle: (milliseconds)" if opts[:time]
400
+ end
401
+
402
+ def redis_pending_summary(row)
403
+ consumers = (row["consumers"] || []).to_h { |c| [c["name"], c["count"].to_s] }
404
+
405
+ {
406
+ "size" => row["count"].to_i,
407
+ "min_entry_id" => redis_presence(row["lowest"]),
408
+ "max_entry_id" => redis_presence(row["highest"]),
409
+ "consumers" => consumers
410
+ }
411
+ end
412
+
413
+ def redis_pending_row(row)
414
+ {
415
+ "entry_id" => row["_id"],
416
+ "consumer" => row["consumer"],
417
+ "elapsed" => row["idle_ms"],
418
+ "count" => row["deliveries"]
419
+ }
420
+ end
421
+
422
+ def redis_stream_info(key)
423
+ target = stream(key)
424
+ info = target.info
425
+
426
+ {
427
+ "length" => info["length"],
428
+ "last-generated-id" => redis_id(info["last_id"]),
429
+ "max-deleted-entry-id" => redis_id(info["max_deleted_id"]),
430
+ "entries-added" => info["entries_added"],
431
+ "recorded-first-entry-id" => redis_id(info["first_id"]),
432
+ "groups" => info["groups"],
433
+ "first-entry" => redis_raw_entry(target.range("-", "+", count: 1).first),
434
+ "last-entry" => redis_raw_entry(target.rev_range("+", "-", count: 1).first)
435
+ }
436
+ end
437
+
438
+ # An entry as redis-rb leaves it in xinfo: [id, [field, value, ...]].
439
+ def redis_raw_entry(entry)
440
+ return nil if entry.nil?
441
+
442
+ [entry.id, redis_fields(entry.doc).to_a.flatten(1)]
443
+ end
444
+
445
+ def redis_group_info(row)
446
+ {
447
+ "name" => row["name"],
448
+ "consumers" => row["consumers"],
449
+ "pending" => row["pending"],
450
+ "last-delivered-id" => redis_id(row["last_delivered_id"]),
451
+ "entries-read" => row["entries_read"],
452
+ "lag" => row["lag"]
453
+ }
454
+ end
455
+
456
+ def redis_consumer_info(row)
457
+ {
458
+ "name" => row["name"],
459
+ "pending" => row["pending"],
460
+ "idle" => row["idle_ms"],
461
+ "inactive" => row["inactive_ms"]
462
+ }
463
+ end
464
+
465
+ def redis_presence(value)
466
+ value.to_s.empty? ? nil : value
467
+ end
468
+
469
+ # An ID that ndb does not have yet is "0-0" in Redis.
470
+ def redis_id(value)
471
+ redis_presence(value) || "0-0"
472
+ end
473
+
474
+ # Gives the errors of a group command the message that Redis gives. The
475
+ # class stays the Ndb::Error subclass.
476
+ def redis_group_errors(key, group, missing_key: false)
477
+ yield
478
+ rescue GroupExists => e
479
+ raise redis_error(e, "BUSYGROUP Consumer Group name already exists")
480
+ rescue UnknownCollection => e
481
+ raise redis_error(e, redis_no_key_message) if missing_key
482
+
483
+ raise redis_error(e, "NOGROUP No such key '#{key}' or consumer group '#{group}'")
484
+ rescue UnknownGroup => e
485
+ raise redis_error(e, "NOGROUP No such key '#{key}' or consumer group '#{group}'")
486
+ end
487
+
488
+ def redis_no_key(_key)
489
+ yield
490
+ rescue UnknownCollection => e
491
+ raise redis_error(e, "ERR no such key")
492
+ end
493
+
494
+ def redis_no_key_message
495
+ "ERR The XGROUP subcommand requires the key to exist. " \
496
+ "Note that for CREATE you may want to use the MKSTREAM option to create an empty stream automatically."
497
+ end
498
+
499
+ def redis_error(error, message)
500
+ error.class.new("#{message} (#{error.message})", code: error.code, status: error.status)
501
+ end
502
+ end
503
+ end