ndb 1.18.1 → 1.19.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: ee3347a5a29c76514b39b62825b31cbb28e8eb705fb54226b7c775249e0a8821
4
- data.tar.gz: ddc161835f4ee556be3657fbbd8e9d7908be870e48c5c4bcfd1767383a252366
3
+ metadata.gz: 316016d738b80c94ebdb5cfdf4d52346d444fae8961331fc1fd71f952d8da82b
4
+ data.tar.gz: 46df39cb4910b2218f67a9bed9cd84cb7da3dc83ff0cac1a41458ba982493c80
5
5
  SHA512:
6
- metadata.gz: '086c1931a469b269941b52e6b696e54a50a9f44a76c0115ad6426d6489e826ae68a963c0749984c4e22e5abd4f7ce640576bb1487c9bd2868013628837789c67'
7
- data.tar.gz: 390002743d84c0e622be05b7080ebd67049549d939e4e939a821c4e2cb169e31313df0031d6e2fb18b5fafb24595454ea03f838b9187e217d254ca359363ec10
6
+ metadata.gz: f0b5fcacdebaf17de00bff6df4a749ab269f9f537cce48eab5ce16edde181b5132de386baf58ef318bd3e9493434edff7fc58a2fcdefb44a91e606d2c8e52ed4
7
+ data.tar.gz: 6f6398f76ddc297cc7a2d4a2a489ee72407282e2fc213d738fd5f802ff0d5197d57ebc6cf277a84ef71a8d2a312e8f6e13e3ab9b754258cb829054176afd5614
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
@@ -58,9 +58,125 @@ module Ndb
58
58
 
59
59
  # Applies the write operators to the document with this _id (atomic).
60
60
  # guard adds conditions on the same document, such as { _v: 7 }.
61
- def update(id, ops, guard: nil, upsert: false, expire_in: nil)
61
+ def update(id, ops, guard: nil, upsert: false, expire_in: nil, lock: nil)
62
62
  ready!
63
- client.update(name, id, ops, guard: guard, upsert: upsert, expire_in: expire_in)
63
+ client.update(name, id, ops, guard: guard, upsert: upsert, expire_in: expire_in, lock: lock)
64
+ end
65
+
66
+ # The optimistic lock with the retry done for you. Reads the document
67
+ # with this _id, yields it, and writes the fields the block changed (set,
68
+ # or deleted), guarded by the version it read. When another write came
69
+ # first, it reads the document again and yields again, up to retries
70
+ # times; then it raises StaleObjectError. So the block can run more than
71
+ # once: when it has an effect outside ndb, use lock. An exception in the
72
+ # block stops it and nothing is written. A missing document raises
73
+ # NotFound. Returns the document as written.
74
+ #
75
+ # wallets.with_retry("w1") do |w|
76
+ # raise InsufficientFunds if w["balance_cents"] < 500
77
+ #
78
+ # w["balance_cents"] -= 500
79
+ # end
80
+ def with_retry(id, retries: 5, &block)
81
+ retries = [retries, 1].max
82
+
83
+ retries.times do |attempt|
84
+ sleep((attempt * 5 + rand(10)) / 1000.0) if attempt.positive?
85
+
86
+ doc = get(id) or raise NotFound.new("#{name} #{id}", code: "not_found", status: 404)
87
+ written = change(id, doc, guard: { _v: doc["_v"] }, &block)
88
+
89
+ return written if written
90
+ end
91
+
92
+ raise StaleObjectError.new("#{name} #{id} changed on every try", code: "stale_object", status: 409)
93
+ end
94
+
95
+ # The pessimistic lock. Takes the lock of the document, yields it, writes
96
+ # the fields the block changed, and releases the lock. While the block
97
+ # runs, no other caller holds the lock and no other write changes the
98
+ # document: another lock waits (wait, then Locked) and a plain write
99
+ # waits for the release. So the block runs once: use it when the block
100
+ # has an effect outside ndb (a payment, an email). An exception in the
101
+ # block writes nothing and releases the lock. A lock held for longer
102
+ # than ttl is gone: the write raises LockExpired. See Client#lock.
103
+ #
104
+ # payments.lock("p1") do |p|
105
+ # next if p["status"] == "refunded"
106
+ #
107
+ # Gateway.refund(p["charge_id"])
108
+ # p["status"] = "refunded"
109
+ # end
110
+ def lock(id, ttl: nil, wait: nil, &block)
111
+ ready!
112
+ held = client.lock(name, id, ttl: ttl, wait: wait)
113
+
114
+ begin
115
+ change(id, held["doc"], lock: held["token"], &block) or raise NotFound.new("#{name} #{id}", code: "not_found", status: 404)
116
+ ensure
117
+ release(id, held["token"])
118
+ end
119
+ end
120
+
121
+ # A transaction of this collection. With lock: (ids), it first locks
122
+ # those documents, all of them or none, and yields them by _id, read
123
+ # under the lock. The block records the writes with tx.insert, tx.update
124
+ # and tx.delete; they are written when the block ends, all of them or
125
+ # none, and the locks are released.
126
+ #
127
+ # An exception in the block writes nothing and goes on; Ndb::Rollback
128
+ # writes nothing and the call returns nil. A refused commit writes
129
+ # nothing: TxConflict when an update or a delete matches nothing (a
130
+ # missing document, or a stale "_v"), LockExpired when the locks
131
+ # outlived ttl (default 30 s: the time limit of the transaction). wait is
132
+ # how long to wait for a document that another caller holds (then
133
+ # Locked). Reads inside the block see the stored data, not its writes.
134
+ #
135
+ # accounts.transaction(lock: %w[a1 a2], ttl: 5) do |tx, docs|
136
+ # raise Ndb::Rollback if docs["a1"]["balance"] < amount
137
+ #
138
+ # docs["a1"]["balance"] -= amount
139
+ # docs["a2"]["balance"] += amount
140
+ #
141
+ # tx.update(docs["a1"])
142
+ # tx.update(docs["a2"])
143
+ # end
144
+ def transaction(lock: [], ttl: nil, wait: nil)
145
+ ready!
146
+
147
+ tx = Transaction.new
148
+ docs = {}
149
+ tokens = []
150
+
151
+ unless lock.empty?
152
+ held = client.lock_set(name, lock, ttl: ttl, wait: wait)
153
+ tokens << held["token"]
154
+
155
+ held["docs"].each do |doc|
156
+ docs[doc["_id"]] = doc
157
+ tx.locked(doc)
158
+ end
159
+ end
160
+
161
+ begin
162
+ yield tx, docs
163
+ rescue Rollback
164
+ release_set(tokens)
165
+
166
+ return nil
167
+ rescue Exception # rubocop:disable Lint/RescueException
168
+ release_set(tokens)
169
+
170
+ raise
171
+ end
172
+
173
+ if tx.ops.empty?
174
+ release_set(tokens)
175
+
176
+ return nil
177
+ end
178
+
179
+ client.tx(name, tx.ops, locks: tokens, unlock: true)
64
180
  end
65
181
 
66
182
  # The atomic update by query: the first match, or every match with many.
@@ -181,6 +297,43 @@ module Ndb
181
297
  client.ensure_collection(name, definition)
182
298
  @ensured = true
183
299
  end
300
+
301
+ private
302
+
303
+ # Yields doc and writes the top-level fields the block changed, in one
304
+ # update with options (a guard, or the token of a lock). Returns the
305
+ # document as written (doc when nothing changed), or nil when the update
306
+ # matched nothing.
307
+ def change(id, doc, **options)
308
+ before = Marshal.load(Marshal.dump(doc))
309
+
310
+ yield doc
311
+
312
+ ops = lock_changes(before, doc)
313
+ return doc if ops.empty?
314
+
315
+ result = update(id, ops, **options)
316
+
317
+ result["doc"] if result["matched"].positive?
318
+ end
319
+
320
+ # A lock that cannot be released ends with its ttl.
321
+ def release(id, token)
322
+ client.unlock(name, id, token)
323
+ rescue Error
324
+ nil
325
+ end
326
+
327
+ def release_set(tokens)
328
+ tokens.each do |token|
329
+ client.unlock_set(name, token)
330
+ rescue Error
331
+ nil
332
+ end
333
+ end
334
+
335
+ # The $set and $unset of the top-level fields that differ.
336
+ def lock_changes(before, after) = Transaction.changes(before, after)
184
337
  end
185
338
 
186
339
  # 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.1"
4
+ VERSION = "1.19.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.1
4
+ version: 1.19.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: