ndb 1.18.2 → 1.20.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: 4f9db0703122bea38c9c978091e3225437018fb992b4b5f9a300f9094d703231
4
- data.tar.gz: 2773287e9c70ccfcf75b8820c7c88b41dbff5b0fe27af9535894bf1a9a5af13a
3
+ metadata.gz: b3e9918b790234da611b8fb2eb56866cf65561d1d676e9ef44b9bf6ca74ca5ad
4
+ data.tar.gz: 7d2db6384e6be36e05c52c694dc7cfe8b8c68ae493c1064dbcd59adb8d32a4a4
5
5
  SHA512:
6
- metadata.gz: 4f178c9e5b6c7c2525c80f0c331b30d8a9cb0b64d2c1e6bad63bd9a247b1c5eaab6c29e9b35117f618b442e69ff77c8aada82479c456d14fc94a75d486e229a7
7
- data.tar.gz: a9db09769ba3b05da5d8fb44f42b0b8cf0a8a8131d20a2bd2799509833ced0dc1d816312984942d1ee512d76e30422d032d334f76adf9483263bcf3c3e9cfee6
6
+ metadata.gz: 94eee2c539adf0c61555630df0d1c4a866ac0da207c7be06d3d43ab0602cf8aa2e0086a7c73c7caf2ec820b3ff2ae5005777552aaebd582f0d3eca3f64bd7c9b
7
+ data.tar.gz: c48e6aed16ebbcacdac096cd5ec557537abc3342d2a5d39578b59b72b6bf9f10e0cfa9f1ab8b496ad0fca2c07b23d638e548d7262f214ae3998a8cbb4003a690
data/lib/ndb/client.rb CHANGED
@@ -135,10 +135,56 @@ module Ndb
135
135
  #
136
136
  # Operators: $set, $setOnInsert, $unset, $inc, $push, $pull, $min, $max
137
137
  # (dot paths work). upsert: true creates the document with this _id.
138
- def update(coll, id, ops, guard: nil, upsert: false, expire_in: nil)
138
+ #
139
+ # lock: the token of a lock on the document (see lock): the write of
140
+ # its holder. update_by, delete and delete_by take it too.
141
+ def update(coll, id, ops, guard: nil, upsert: false, expire_in: nil, lock: nil)
139
142
  body = write_body(update: check_ops(ops), query: guard && Conditions.equality(guard), upsert: upsert, expire_in: expire_in)
140
143
 
141
- json(request("POST", doc_path(coll, "_update", id), body))
144
+ json(request("POST", held(doc_path(coll, "_update", id), lock), body))
145
+ end
146
+
147
+ # POST /{coll}/_lock/{id}: the pessimistic lock of a document. Until
148
+ # unlock, or ttl (seconds or "30s"; default 30 s, up to 5 min), only a
149
+ # write with the token changes the document; a write without it waits.
150
+ # When another caller holds the lock, the call waits up to wait (default
151
+ # 10 s, up to 1 min; 0 does not wait), then raises Locked. Returns
152
+ # {"token", "expires_at", "doc"}. A missing document raises NotFound.
153
+ def lock(coll, id, ttl: nil, wait: nil)
154
+ timeout = wait.is_a?(Numeric) ? [self.timeout, wait + 5].max : nil
155
+
156
+ json(request("POST", doc_path(coll, "_lock", id), write_body(ttl: ttl, wait: wait), timeout: timeout))
157
+ end
158
+
159
+ # POST /{coll}/_lock: the locks of a set of documents, all under one
160
+ # token, or none of them (no deadlock between two sets). ttl and wait as
161
+ # for lock; up to 100 ids. Returns {"token", "expires_at", "docs"}.
162
+ def lock_set(coll, ids, ttl: nil, wait: nil)
163
+ timeout = wait.is_a?(Numeric) ? [self.timeout, wait + 5].max : nil
164
+
165
+ json(request("POST", "#{path(coll)}/_lock", write_body(ids: ids, ttl: ttl, wait: wait), timeout: timeout))
166
+ end
167
+
168
+ # POST /{coll}/_unlock: releases every lock of token. Returns
169
+ # {"unlocked" => n}; a token that holds nothing raises LockExpired.
170
+ def unlock_set(coll, token)
171
+ json(request("POST", "#{path(coll)}/_unlock", { token: token }))
172
+ end
173
+
174
+ # POST /{coll}/_tx: inserts, updates and deletes of one collection in one
175
+ # step, all of them or none. ops: [{op: "insert", doc:}, {op: "update",
176
+ # id:, update:, query:}, {op: "delete", id:, query:}]. locks: the tokens
177
+ # the transaction holds; unlock: true releases them after the call.
178
+ # Returns {"results" => [...]}. An update or a delete that matches
179
+ # nothing raises TxConflict.
180
+ def tx(coll, ops, locks: [], unlock: false)
181
+ json(request("POST", "#{path(coll)}/_tx", write_body(ops: ops, locks: locks, unlock: unlock)))
182
+ end
183
+
184
+ # POST /{coll}/_unlock/{id}: releases the lock of token. A token that
185
+ # holds no lock (expired, released) raises LockExpired.
186
+ def unlock(coll, id, token)
187
+ json(request("POST", doc_path(coll, "_unlock", id), { token: token }))
142
188
  end
143
189
 
144
190
  # POST /{coll}/_update_by_query: the atomic update by query. The daemon
@@ -147,21 +193,21 @@ module Ndb
147
193
  # many: true updates every match and needs _id or an indexed field in
148
194
  # the query. upsert: true creates the document from the equality fields
149
195
  # of the query when nothing matches.
150
- def update_by(coll, query, ops, many: false, upsert: false, expire_in: nil)
196
+ def update_by(coll, query, ops, many: false, upsert: false, expire_in: nil, lock: nil)
151
197
  body = write_body(query: Conditions.equality(query), update: check_ops(ops), many: many, upsert: upsert, expire_in: expire_in)
152
198
 
153
- json(post(coll, "_update_by_query", body))
199
+ json(post(coll, held("_update_by_query", lock), body))
154
200
  end
155
201
 
156
202
  # DELETE /{coll}/_doc/{id}: {"deleted" => 0 | 1}.
157
- def delete(coll, id)
158
- json(request("DELETE", doc_path(coll, "_doc", id), nil))
203
+ def delete(coll, id, lock: nil)
204
+ json(request("DELETE", held(doc_path(coll, "_doc", id), lock), nil))
159
205
  end
160
206
 
161
207
  # POST /{coll}/_delete_by_query: the first match, or every match with
162
208
  # many: true (same rule as update_by). {"deleted" => n}
163
- def delete_by(coll, query, many: false)
164
- json(post(coll, "_delete_by_query", write_body(query: Conditions.equality(query), many: many)))
209
+ def delete_by(coll, query, many: false, lock: nil)
210
+ json(post(coll, held("_delete_by_query", lock), write_body(query: Conditions.equality(query), many: many)))
165
211
  end
166
212
 
167
213
  # Makes a document expire, like EXPIRE in Redis: in: seconds or "30m", or
@@ -344,6 +390,11 @@ module Ndb
344
390
  "/#{escape(coll)}"
345
391
  end
346
392
 
393
+ # target as the write of the holder of a lock (?lock=<token>).
394
+ def held(target, token)
395
+ token ? "#{target}?lock=#{escape(token)}" : target
396
+ end
397
+
347
398
  def escape(segment)
348
399
  URI.encode_www_form_component(segment).gsub("+", "%20")
349
400
  end
@@ -17,10 +17,20 @@ module Ndb
17
17
  def initialize(client, name, definition = {})
18
18
  @client = client
19
19
  @name = name
20
- @definition = definition
20
+ @definition = self.class.normalize(definition)
21
21
  @ensured = false
22
22
  end
23
23
 
24
+ # An entry of indexes or unique that is an Array is a compound index:
25
+ # %w[account_id created_at] becomes "account_id,created_at".
26
+ def self.normalize(definition)
27
+ definition.to_h do |key, value|
28
+ compound = %w[indexes unique].include?(key.to_s) && value.is_a?(Array)
29
+
30
+ [key, compound ? value.map { |entry| entry.is_a?(Array) ? entry.join(",") : entry } : value]
31
+ end
32
+ end
33
+
24
34
  def pattern? = name.include?("*")
25
35
 
26
36
  # A Hash is one document (_doc) and returns {"_id", "_v"}; an Array is
@@ -58,9 +68,125 @@ module Ndb
58
68
 
59
69
  # Applies the write operators to the document with this _id (atomic).
60
70
  # guard adds conditions on the same document, such as { _v: 7 }.
61
- def update(id, ops, guard: nil, upsert: false, expire_in: nil)
71
+ def update(id, ops, guard: nil, upsert: false, expire_in: nil, lock: nil)
62
72
  ready!
63
- client.update(name, id, ops, guard: guard, upsert: upsert, expire_in: expire_in)
73
+ client.update(name, id, ops, guard: guard, upsert: upsert, expire_in: expire_in, lock: lock)
74
+ end
75
+
76
+ # The optimistic lock with the retry done for you. Reads the document
77
+ # with this _id, yields it, and writes the fields the block changed (set,
78
+ # or deleted), guarded by the version it read. When another write came
79
+ # first, it reads the document again and yields again, up to retries
80
+ # times; then it raises StaleObjectError. So the block can run more than
81
+ # once: when it has an effect outside ndb, use lock. An exception in the
82
+ # block stops it and nothing is written. A missing document raises
83
+ # NotFound. Returns the document as written.
84
+ #
85
+ # wallets.with_retry("w1") do |w|
86
+ # raise InsufficientFunds if w["balance_cents"] < 500
87
+ #
88
+ # w["balance_cents"] -= 500
89
+ # end
90
+ def with_retry(id, retries: 5, &block)
91
+ retries = [retries, 1].max
92
+
93
+ retries.times do |attempt|
94
+ sleep((attempt * 5 + rand(10)) / 1000.0) if attempt.positive?
95
+
96
+ doc = get(id) or raise NotFound.new("#{name} #{id}", code: "not_found", status: 404)
97
+ written = change(id, doc, guard: { _v: doc["_v"] }, &block)
98
+
99
+ return written if written
100
+ end
101
+
102
+ raise StaleObjectError.new("#{name} #{id} changed on every try", code: "stale_object", status: 409)
103
+ end
104
+
105
+ # The pessimistic lock. Takes the lock of the document, yields it, writes
106
+ # the fields the block changed, and releases the lock. While the block
107
+ # runs, no other caller holds the lock and no other write changes the
108
+ # document: another lock waits (wait, then Locked) and a plain write
109
+ # waits for the release. So the block runs once: use it when the block
110
+ # has an effect outside ndb (a payment, an email). An exception in the
111
+ # block writes nothing and releases the lock. A lock held for longer
112
+ # than ttl is gone: the write raises LockExpired. See Client#lock.
113
+ #
114
+ # payments.lock("p1") do |p|
115
+ # next if p["status"] == "refunded"
116
+ #
117
+ # Gateway.refund(p["charge_id"])
118
+ # p["status"] = "refunded"
119
+ # end
120
+ def lock(id, ttl: nil, wait: nil, &block)
121
+ ready!
122
+ held = client.lock(name, id, ttl: ttl, wait: wait)
123
+
124
+ begin
125
+ change(id, held["doc"], lock: held["token"], &block) or raise NotFound.new("#{name} #{id}", code: "not_found", status: 404)
126
+ ensure
127
+ release(id, held["token"])
128
+ end
129
+ end
130
+
131
+ # A transaction of this collection. With lock: (ids), it first locks
132
+ # those documents, all of them or none, and yields them by _id, read
133
+ # under the lock. The block records the writes with tx.insert, tx.update
134
+ # and tx.delete; they are written when the block ends, all of them or
135
+ # none, and the locks are released.
136
+ #
137
+ # An exception in the block writes nothing and goes on; Ndb::Rollback
138
+ # writes nothing and the call returns nil. A refused commit writes
139
+ # nothing: TxConflict when an update or a delete matches nothing (a
140
+ # missing document, or a stale "_v"), LockExpired when the locks
141
+ # outlived ttl (default 30 s: the time limit of the transaction). wait is
142
+ # how long to wait for a document that another caller holds (then
143
+ # Locked). Reads inside the block see the stored data, not its writes.
144
+ #
145
+ # accounts.transaction(lock: %w[a1 a2], ttl: 5) do |tx, docs|
146
+ # raise Ndb::Rollback if docs["a1"]["balance"] < amount
147
+ #
148
+ # docs["a1"]["balance"] -= amount
149
+ # docs["a2"]["balance"] += amount
150
+ #
151
+ # tx.update(docs["a1"])
152
+ # tx.update(docs["a2"])
153
+ # end
154
+ def transaction(lock: [], ttl: nil, wait: nil)
155
+ ready!
156
+
157
+ tx = Transaction.new
158
+ docs = {}
159
+ tokens = []
160
+
161
+ unless lock.empty?
162
+ held = client.lock_set(name, lock, ttl: ttl, wait: wait)
163
+ tokens << held["token"]
164
+
165
+ held["docs"].each do |doc|
166
+ docs[doc["_id"]] = doc
167
+ tx.locked(doc)
168
+ end
169
+ end
170
+
171
+ begin
172
+ yield tx, docs
173
+ rescue Rollback
174
+ release_set(tokens)
175
+
176
+ return nil
177
+ rescue Exception # rubocop:disable Lint/RescueException
178
+ release_set(tokens)
179
+
180
+ raise
181
+ end
182
+
183
+ if tx.ops.empty?
184
+ release_set(tokens)
185
+
186
+ return nil
187
+ end
188
+
189
+ client.tx(name, tx.ops, locks: tokens, unlock: true)
64
190
  end
65
191
 
66
192
  # The atomic update by query: the first match, or every match with many.
@@ -181,6 +307,43 @@ module Ndb
181
307
  client.ensure_collection(name, definition)
182
308
  @ensured = true
183
309
  end
310
+
311
+ private
312
+
313
+ # Yields doc and writes the top-level fields the block changed, in one
314
+ # update with options (a guard, or the token of a lock). Returns the
315
+ # document as written (doc when nothing changed), or nil when the update
316
+ # matched nothing.
317
+ def change(id, doc, **options)
318
+ before = Marshal.load(Marshal.dump(doc))
319
+
320
+ yield doc
321
+
322
+ ops = lock_changes(before, doc)
323
+ return doc if ops.empty?
324
+
325
+ result = update(id, ops, **options)
326
+
327
+ result["doc"] if result["matched"].positive?
328
+ end
329
+
330
+ # A lock that cannot be released ends with its ttl.
331
+ def release(id, token)
332
+ client.unlock(name, id, token)
333
+ rescue Error
334
+ nil
335
+ end
336
+
337
+ def release_set(tokens)
338
+ tokens.each do |token|
339
+ client.unlock_set(name, token)
340
+ rescue Error
341
+ nil
342
+ end
343
+ end
344
+
345
+ # The $set and $unset of the top-level fields that differ.
346
+ def lock_changes(before, after) = Transaction.changes(before, after)
184
347
  end
185
348
 
186
349
  # An immutable search on a collection: every step returns a new Query.
data/lib/ndb/errors.rb CHANGED
@@ -24,6 +24,22 @@ module Ndb
24
24
 
25
25
  class Unauthorized < Error; end
26
26
  class NotFound < Error; end
27
+
28
+ # with_retry lost the race on every try, or a model save or destroy
29
+ # matched nothing: the document changed or was deleted since it was read
30
+ # (its "_v" guard did not match).
31
+ class StaleObjectError < Error; end
32
+
33
+ # Another caller holds the lock of the document, and the wait is over.
34
+ class Locked < Error; end
35
+
36
+ # The token holds no lock on the document (it expired or was released):
37
+ # the write is refused.
38
+ class LockExpired < Error; end
39
+
40
+ # An update or a delete of a transaction matched nothing (no such
41
+ # document, or its guard does not match): nothing of it was written.
42
+ class TxConflict < Error; end
27
43
  class UnknownCollection < Error; end
28
44
  class UniqueViolation < Error; end
29
45
  class CatalogConflict < Error; end
@@ -142,6 +158,9 @@ module Ndb
142
158
  "history_truncated" => HistoryTruncated,
143
159
  "ttl_not_enabled" => TtlNotEnabled,
144
160
  "ttl_derived" => TtlDerived,
161
+ "locked" => Locked,
162
+ "lock_expired" => LockExpired,
163
+ "tx_conflict" => TxConflict,
145
164
  "unknown_operator" => UnknownOperator,
146
165
  "no_update" => NoUpdate,
147
166
  "conflicting_update" => ConflictingUpdate,
@@ -0,0 +1,73 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Ndb
4
+ # Raise it in a transaction block to stop it: nothing is written, the
5
+ # locks are released, and the block returns nil (as ActiveRecord::Rollback).
6
+ class Rollback < StandardError; end
7
+
8
+ # The writes of a transaction block of one collection. Nothing is sent
9
+ # until the block ends; then Collection#transaction sends them in one call
10
+ # (POST /{coll}/_tx), all of them or none.
11
+ class Transaction
12
+ SKIP = %w[_id _v _coll].freeze
13
+
14
+ attr_reader :ops
15
+
16
+ def initialize
17
+ @ops = []
18
+ @before = {}
19
+ end
20
+
21
+ # The $set and $unset of the top-level fields that differ.
22
+ def self.changes(before, after)
23
+ set = after.reject { |k, v| SKIP.include?(k) || before.key?(k) && before[k] == v }
24
+ unset = (before.keys - after.keys - SKIP).to_h { |k| [k, ""] }
25
+
26
+ ops = {}
27
+ ops["$set"] = set unless set.empty?
28
+ ops["$unset"] = unset unless unset.empty?
29
+ ops
30
+ end
31
+
32
+ # Records the insert of doc. A doc without _id gets one from the daemon.
33
+ def insert(doc = nil, **fields)
34
+ @ops << { op: "insert", doc: Ndb.deep_stringify(doc || fields) }
35
+
36
+ self
37
+ end
38
+
39
+ # Records the write of doc. A document that the transaction locked gets
40
+ # the fields that changed since the lock; any other gets all its fields,
41
+ # guarded by its "_v": a document that changed since it was read fails
42
+ # the transaction (TxConflict).
43
+ def update(doc)
44
+ doc = Ndb.deep_stringify(doc)
45
+ id = doc["_id"] or raise ArgumentError, "update needs a document with _id"
46
+
47
+ if (before = @before[id])
48
+ ops = self.class.changes(before, doc)
49
+ @before[id] = Marshal.load(Marshal.dump(doc))
50
+ @ops << { op: "update", id: id, update: ops } unless ops.empty?
51
+ else
52
+ op = { op: "update", id: id, update: { "$set" => doc.except(*SKIP) } }
53
+ op[:query] = { "_v" => doc["_v"] } if doc["_v"]
54
+ @ops << op
55
+ end
56
+
57
+ self
58
+ end
59
+
60
+ # Records the delete of the document with this _id. A missing document
61
+ # fails the transaction (TxConflict).
62
+ def delete(id)
63
+ @ops << { op: "delete", id: id }
64
+
65
+ self
66
+ end
67
+
68
+ # Keeps a locked document as it was, for update.
69
+ def locked(doc)
70
+ @before[doc["_id"]] = Marshal.load(Marshal.dump(doc))
71
+ end
72
+ end
73
+ 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.18.2"
4
+ VERSION = "1.20.0"
5
5
  end
data/lib/ndb.rb CHANGED
@@ -7,6 +7,7 @@ require "ndb/conditions"
7
7
  require "ndb/connection"
8
8
  require "ndb/redis_commands"
9
9
  require "ndb/client"
10
+ require "ndb/transaction"
10
11
  require "ndb/collection"
11
12
  require "ndb/stream"
12
13
  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.18.2
4
+ version: 1.20.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - thadeu
@@ -30,6 +30,7 @@ files:
30
30
  - lib/ndb/redis_commands.rb
31
31
  - lib/ndb/stream.rb
32
32
  - lib/ndb/stream_worker.rb
33
+ - lib/ndb/transaction.rb
33
34
  - lib/ndb/version.rb
34
35
  homepage: https://ndb.clowk.in
35
36
  licenses: