ndb-rails 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 +4 -4
- data/lib/ndb/rails/errors.rb +0 -4
- data/lib/ndb/rails/locking.rb +177 -0
- data/lib/ndb/rails/persistence.rb +64 -4
- data/lib/ndb/rails/record.rb +3 -1
- data/lib/ndb/rails/relation.rb +39 -6
- data/lib/ndb/rails/transactions.rb +207 -0
- data/lib/ndb/rails/version.rb +1 -1
- data/lib/ndb/rails.rb +2 -0
- metadata +5 -3
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: 25e6a965ea121ec28f1111ab71a468f8a39f181c9576e75f2ef77c4d426eecfb
|
|
4
|
+
data.tar.gz: 4a580bf13a810470ed2bcb8a316d9c0c2b839c1a0b11346f9d6791d3b06fc541
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: 80b1e74f3e9995ed5e3b445fa1e070bbf4298650f3d49a6b3cc176a3af6387c3cb4d8b6494db240584645993eb0ce3db90ac37b4ed5e113a3e3440c698a1df20
|
|
7
|
+
data.tar.gz: 2c021ef1b4032469d5cd8b5b2a0ca301deb3832bca610c0857dccc8593d5747de455da934c9db444d03d9a6fc580bf13dd1a22c5a0583608e3b767e4dafe8026
|
data/lib/ndb/rails/errors.rb
CHANGED
|
@@ -5,10 +5,6 @@ module Ndb
|
|
|
5
5
|
# rescue of either name catches the same error.
|
|
6
6
|
RecordNotUnique = UniqueViolation
|
|
7
7
|
|
|
8
|
-
# A save or destroy matched nothing: the record changed or was deleted
|
|
9
|
-
# since it was loaded (its "_v" guard did not match).
|
|
10
|
-
class StaleObjectError < Error; end
|
|
11
|
-
|
|
12
8
|
# Raised by destroy! when a before_destroy callback aborts.
|
|
13
9
|
class RecordNotDestroyed < Error
|
|
14
10
|
attr_reader :record
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Ndb
|
|
4
|
+
# The pessimistic lock of a record, like `lock` and `with_lock` of
|
|
5
|
+
# ActiveRecord. The daemon keeps the lock (POST /{coll}/_lock/{id}): until
|
|
6
|
+
# it is released, only this record writes the document. Another lock of
|
|
7
|
+
# the same document waits (wait, then Ndb::Locked), and a write from any
|
|
8
|
+
# other place waits for the release. ActiveRecord releases a lock at the
|
|
9
|
+
# end of its transaction; ndb has no transaction, so a lock ends:
|
|
10
|
+
#
|
|
11
|
+
# - at the end of the block: `Account.lock.find(id) { |a| ... }` and
|
|
12
|
+
# `account.with_lock { |a| ... }`;
|
|
13
|
+
# - without a block, at the first save or destroy of the record (also
|
|
14
|
+
# when it raises), or at `unlock!`;
|
|
15
|
+
# - after ttl in any case (default 30 s), so a process that dies holds
|
|
16
|
+
# nothing. A save after the ttl raises Ndb::LockExpired.
|
|
17
|
+
#
|
|
18
|
+
# The block runs once. Use the lock when the code has an effect outside
|
|
19
|
+
# ndb (a payment, an email); use with_retry when it only changes the record.
|
|
20
|
+
module Locking
|
|
21
|
+
extend ActiveSupport::Concern
|
|
22
|
+
|
|
23
|
+
class_methods do
|
|
24
|
+
# POST /{coll}/_lock/{id}, see Ndb::Client#lock.
|
|
25
|
+
def ndb_lock(id, **options)
|
|
26
|
+
ensure_collection!
|
|
27
|
+
|
|
28
|
+
Rails.client.lock(collection_name, id, **options)
|
|
29
|
+
end
|
|
30
|
+
|
|
31
|
+
# POST /{coll}/_lock, see Ndb::Client#lock_set.
|
|
32
|
+
def ndb_lock_set(ids, **options)
|
|
33
|
+
ensure_collection!
|
|
34
|
+
|
|
35
|
+
Rails.client.lock_set(collection_name, ids, **options)
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
# The record of a lock answer, holding the lock.
|
|
39
|
+
def instantiate_locked(held)
|
|
40
|
+
record = instantiate(held["doc"])
|
|
41
|
+
|
|
42
|
+
record.send(:hold!, held["token"])
|
|
43
|
+
|
|
44
|
+
record
|
|
45
|
+
end
|
|
46
|
+
end
|
|
47
|
+
|
|
48
|
+
# Takes the lock and reads the record again, like ActiveRecord lock!.
|
|
49
|
+
# Unsaved changes are dropped. ttl and wait: see Ndb::Client#lock.
|
|
50
|
+
def lock!(ttl: nil, wait: nil)
|
|
51
|
+
raise RecordNotSaved, "Cannot lock a record that is not saved" unless persisted?
|
|
52
|
+
|
|
53
|
+
held = self.class.ndb_lock(id, **{ ttl: ttl, wait: wait }.compact)
|
|
54
|
+
|
|
55
|
+
refresh_from!(held["doc"])
|
|
56
|
+
|
|
57
|
+
if (tx = current_transaction)
|
|
58
|
+
tx.joined(self, held["token"])
|
|
59
|
+
else
|
|
60
|
+
hold!(held["token"])
|
|
61
|
+
end
|
|
62
|
+
|
|
63
|
+
self
|
|
64
|
+
end
|
|
65
|
+
|
|
66
|
+
# Releases the lock. A lock that is gone already (expired) is not an
|
|
67
|
+
# error.
|
|
68
|
+
def unlock!
|
|
69
|
+
token = @lock_token
|
|
70
|
+
@lock_token = nil
|
|
71
|
+
@lock_scoped = false
|
|
72
|
+
|
|
73
|
+
Rails.client.unlock(self.class.collection_name, id, token) if token
|
|
74
|
+
|
|
75
|
+
self
|
|
76
|
+
rescue LockExpired
|
|
77
|
+
self
|
|
78
|
+
end
|
|
79
|
+
|
|
80
|
+
def locked?
|
|
81
|
+
!@lock_token.nil?
|
|
82
|
+
end
|
|
83
|
+
|
|
84
|
+
# Takes the lock, yields the record, and releases the lock at the end of
|
|
85
|
+
# the block, also on an exception. Save inside the block. Returns the
|
|
86
|
+
# record.
|
|
87
|
+
def with_lock(ttl: nil, wait: nil)
|
|
88
|
+
lock!(ttl: ttl, wait: wait)
|
|
89
|
+
scoped_lock { yield self }
|
|
90
|
+
end
|
|
91
|
+
|
|
92
|
+
# Runs the block with the lock kept until its end (a save inside does
|
|
93
|
+
# not release it), then releases.
|
|
94
|
+
def scoped_lock
|
|
95
|
+
@lock_scoped = true
|
|
96
|
+
|
|
97
|
+
yield
|
|
98
|
+
|
|
99
|
+
self
|
|
100
|
+
ensure
|
|
101
|
+
unlock!
|
|
102
|
+
end
|
|
103
|
+
|
|
104
|
+
# A save or destroy that raises ends a lock held without a block, as an
|
|
105
|
+
# exception ends a transaction in ActiveRecord. A save that returns false
|
|
106
|
+
# (not valid) keeps it: fix the record and save again, or unlock!.
|
|
107
|
+
%i[save save! update update! destroy destroy! delete increment! decrement!].each do |name|
|
|
108
|
+
define_method(name) do |*args, **options, &block|
|
|
109
|
+
super(*args, **options, &block)
|
|
110
|
+
rescue StandardError
|
|
111
|
+
release_after_error
|
|
112
|
+
|
|
113
|
+
raise
|
|
114
|
+
end
|
|
115
|
+
end
|
|
116
|
+
|
|
117
|
+
private
|
|
118
|
+
|
|
119
|
+
# Reads the record again from a document of a lock answer.
|
|
120
|
+
def refresh_from!(doc)
|
|
121
|
+
fresh = self.class.instantiate(doc)
|
|
122
|
+
|
|
123
|
+
@attributes = fresh.instance_variable_get(:@attributes)
|
|
124
|
+
@version = fresh.version
|
|
125
|
+
@associations = nil
|
|
126
|
+
|
|
127
|
+
clear_changes_information
|
|
128
|
+
end
|
|
129
|
+
|
|
130
|
+
# A lock that a transaction holds: the transaction releases it.
|
|
131
|
+
def hold_in_transaction!(token)
|
|
132
|
+
@lock_token = token
|
|
133
|
+
@lock_scoped = true
|
|
134
|
+
end
|
|
135
|
+
|
|
136
|
+
def written_in_transaction!(version)
|
|
137
|
+
@version = version
|
|
138
|
+
end
|
|
139
|
+
|
|
140
|
+
def leave_transaction!
|
|
141
|
+
@lock_token = nil
|
|
142
|
+
@lock_scoped = false
|
|
143
|
+
end
|
|
144
|
+
|
|
145
|
+
def release_after_error
|
|
146
|
+
unlock! if @lock_token && !@lock_scoped
|
|
147
|
+
rescue Error
|
|
148
|
+
@lock_token = nil
|
|
149
|
+
end
|
|
150
|
+
|
|
151
|
+
def hold!(token)
|
|
152
|
+
@lock_token = token
|
|
153
|
+
@lock_scoped = false
|
|
154
|
+
end
|
|
155
|
+
|
|
156
|
+
# The options of a write of this record: its lock token when it holds one.
|
|
157
|
+
def lock_options
|
|
158
|
+
@lock_token ? { lock: @lock_token } : {}
|
|
159
|
+
end
|
|
160
|
+
|
|
161
|
+
# Runs a write of this record. A lock that expired is forgotten, so the
|
|
162
|
+
# record is a plain record again after the error.
|
|
163
|
+
def holding
|
|
164
|
+
yield
|
|
165
|
+
rescue LockExpired
|
|
166
|
+
@lock_token = nil
|
|
167
|
+
@lock_scoped = false
|
|
168
|
+
|
|
169
|
+
raise
|
|
170
|
+
end
|
|
171
|
+
|
|
172
|
+
# A write outside a block ends the lock, as a commit does.
|
|
173
|
+
def written_with_lock
|
|
174
|
+
unlock! if @lock_token && !@lock_scoped
|
|
175
|
+
end
|
|
176
|
+
end
|
|
177
|
+
end
|
|
@@ -195,6 +195,35 @@ module Ndb
|
|
|
195
195
|
add_to!(attribute, -by)
|
|
196
196
|
end
|
|
197
197
|
|
|
198
|
+
# The optimistic lock with the retry done for you. Reads the document
|
|
199
|
+
# again, yields the record, and saves it, guarded by the version it read.
|
|
200
|
+
# When another write came first (Ndb::StaleObjectError), it reads the
|
|
201
|
+
# document again and yields again, up to retries times; then it raises
|
|
202
|
+
# the error. So the block can run more than once: when it has an effect
|
|
203
|
+
# outside ndb, use with_lock. An exception in the block stops it and
|
|
204
|
+
# nothing is written. Returns the record. Nothing waits on the daemon.
|
|
205
|
+
#
|
|
206
|
+
# wallet.with_retry do |w|
|
|
207
|
+
# raise InsufficientFunds if w.balance_cents < 500
|
|
208
|
+
#
|
|
209
|
+
# w.balance_cents -= 500
|
|
210
|
+
# end
|
|
211
|
+
def with_retry(retries: 5)
|
|
212
|
+
retries = [retries, 1].max
|
|
213
|
+
|
|
214
|
+
retries.times do |attempt|
|
|
215
|
+
sleep((attempt * 5 + rand(10)) / 1000.0) if attempt.positive?
|
|
216
|
+
|
|
217
|
+
reload
|
|
218
|
+
yield self
|
|
219
|
+
save!
|
|
220
|
+
|
|
221
|
+
return self
|
|
222
|
+
rescue StaleObjectError
|
|
223
|
+
raise if attempt == retries - 1
|
|
224
|
+
end
|
|
225
|
+
end
|
|
226
|
+
|
|
198
227
|
# Reads the document again, like ActiveRecord reload: the attributes,
|
|
199
228
|
# the version and the associations (they load again on next use).
|
|
200
229
|
def reload
|
|
@@ -243,9 +272,17 @@ module Ndb
|
|
|
243
272
|
end
|
|
244
273
|
|
|
245
274
|
def delete_record
|
|
246
|
-
|
|
275
|
+
if (tx = current_transaction)
|
|
276
|
+
tx.delete(self)
|
|
277
|
+
|
|
278
|
+
return
|
|
279
|
+
end
|
|
280
|
+
|
|
281
|
+
deleted = holding { self.class.ndb_delete(record_filter, **lock_options) }["deleted"]
|
|
247
282
|
|
|
248
283
|
raise StaleObjectError.new("#{self.class.name} #{id} changed or was deleted", code: "stale_object") if deleted.zero?
|
|
284
|
+
|
|
285
|
+
written_with_lock
|
|
249
286
|
end
|
|
250
287
|
|
|
251
288
|
def add_to!(attribute, by)
|
|
@@ -254,7 +291,15 @@ module Ndb
|
|
|
254
291
|
raise RecordNotSaved, "Cannot update a record that is not saved" unless persisted?
|
|
255
292
|
raise ArgumentError, "#{name} is not an attribute of #{self.class.name}" unless self.class.attribute_names.include?(name)
|
|
256
293
|
|
|
257
|
-
|
|
294
|
+
if (tx = current_transaction)
|
|
295
|
+
tx.update(self, { "$inc" => { name => by } })
|
|
296
|
+
public_send("#{name}=", (public_send(name) || 0) + by)
|
|
297
|
+
clear_attribute_changes([name])
|
|
298
|
+
|
|
299
|
+
return self
|
|
300
|
+
end
|
|
301
|
+
|
|
302
|
+
result = holding { self.class.ndb_update({ self.class.primary_key => id }, { "$inc" => { name => by } }, **lock_options) }
|
|
258
303
|
|
|
259
304
|
raise NotFound.new("#{self.class.name} #{id} was deleted", code: "not_found") if result["matched"].zero?
|
|
260
305
|
|
|
@@ -296,6 +341,16 @@ module Ndb
|
|
|
296
341
|
|
|
297
342
|
def create_record
|
|
298
343
|
run_callbacks(:create) do
|
|
344
|
+
if (tx = current_transaction)
|
|
345
|
+
raise ArgumentError, "expire_in is not supported inside a transaction" if @expire_in
|
|
346
|
+
|
|
347
|
+
self.id ||= Ndb.new_id
|
|
348
|
+
tx.insert(self, insert_document)
|
|
349
|
+
loaded!(nil)
|
|
350
|
+
|
|
351
|
+
next true
|
|
352
|
+
end
|
|
353
|
+
|
|
299
354
|
result = self.class.ndb_insert(insert_document, expire_in: @expire_in)
|
|
300
355
|
|
|
301
356
|
self.id = result["_id"] if id.nil?
|
|
@@ -309,8 +364,12 @@ module Ndb
|
|
|
309
364
|
run_callbacks(:update) do
|
|
310
365
|
set, unset = changed_fields
|
|
311
366
|
|
|
312
|
-
|
|
313
|
-
|
|
367
|
+
if (tx = current_transaction)
|
|
368
|
+
raise ArgumentError, "expire_in is not supported inside a transaction" if @expire_in
|
|
369
|
+
|
|
370
|
+
tx.update(self, update_ops(set, unset)) unless set.empty? && unset.empty?
|
|
371
|
+
elsif !(set.empty? && unset.empty? && @expire_in.nil?)
|
|
372
|
+
result = holding { self.class.ndb_update(record_filter, update_ops(set, unset), expire_in: @expire_in, **lock_options) }
|
|
314
373
|
|
|
315
374
|
raise StaleObjectError.new("#{self.class.name} #{id} changed or was deleted", code: "stale_object") if result["matched"].zero?
|
|
316
375
|
|
|
@@ -318,6 +377,7 @@ module Ndb
|
|
|
318
377
|
end
|
|
319
378
|
|
|
320
379
|
changes_applied
|
|
380
|
+
written_with_lock
|
|
321
381
|
|
|
322
382
|
true
|
|
323
383
|
end
|
data/lib/ndb/rails/record.rb
CHANGED
|
@@ -10,6 +10,8 @@ module Ndb
|
|
|
10
10
|
include ActiveModel::Dirty
|
|
11
11
|
include ActiveModel::Serializers::JSON
|
|
12
12
|
include Persistence
|
|
13
|
+
include Locking
|
|
14
|
+
include Transactions
|
|
13
15
|
include Associations
|
|
14
16
|
|
|
15
17
|
extend ActiveSupport::DescendantsTracker
|
|
@@ -24,7 +26,7 @@ module Ndb
|
|
|
24
26
|
|
|
25
27
|
class << self
|
|
26
28
|
QUERY_METHODS = %i[
|
|
27
|
-
where where_raw order limit offset page after group includes find find_by find_by! first last count pluck exists?
|
|
29
|
+
where where_raw order limit offset page after group includes lock find find_by find_by! first last count pluck exists?
|
|
28
30
|
find_each in_batches sum average minimum maximum to_a each destroy_all delete_all to_ndb
|
|
29
31
|
].freeze
|
|
30
32
|
|
data/lib/ndb/rails/relation.rb
CHANGED
|
@@ -56,6 +56,15 @@ module Ndb
|
|
|
56
56
|
with(limit: count)
|
|
57
57
|
end
|
|
58
58
|
|
|
59
|
+
# Makes find, find_by and first take the pessimistic lock of the record
|
|
60
|
+
# they return, like ActiveRecord lock: `Account.lock.find(id)`. With a
|
|
61
|
+
# block, the record is yielded and the lock ends with the block; without
|
|
62
|
+
# one, it ends at the first save or destroy, or at unlock!. See
|
|
63
|
+
# Ndb::Locking. ttl and wait: see Ndb::Client#lock.
|
|
64
|
+
def lock(ttl: nil, wait: nil)
|
|
65
|
+
with(lock: { ttl: ttl, wait: wait }.compact)
|
|
66
|
+
end
|
|
67
|
+
|
|
59
68
|
# Loads associations with the rows, in the same call (the daemon
|
|
60
69
|
# lookup): includes(:customer, items: :product).
|
|
61
70
|
def includes(*names)
|
|
@@ -194,7 +203,8 @@ module Ndb
|
|
|
194
203
|
# With no order, the order is the primary key (as ActiveRecord does),
|
|
195
204
|
# so first and last are the two ends of one order. The daemon gives
|
|
196
205
|
# only count rows (limit), not the whole relation.
|
|
197
|
-
def first(count = nil)
|
|
206
|
+
def first(count = nil, &block)
|
|
207
|
+
return lock_found(with(lock: nil).first, &block) if values[:lock] && count.nil?
|
|
198
208
|
return count ? records.first(count) : records.first if loaded?
|
|
199
209
|
|
|
200
210
|
found = by_key.limit(count || 1).to_a
|
|
@@ -222,9 +232,10 @@ module Ndb
|
|
|
222
232
|
with(order: sort)
|
|
223
233
|
end
|
|
224
234
|
|
|
225
|
-
def find(*ids)
|
|
235
|
+
def find(*ids, &block)
|
|
226
236
|
ids = ids.flatten
|
|
227
237
|
|
|
238
|
+
return lock_one(ids, &block) if values[:lock]
|
|
228
239
|
return find_one(ids.first) if ids.size == 1 && !ids.first.is_a?(Array)
|
|
229
240
|
|
|
230
241
|
found = where(klass.primary_key => ids).to_a
|
|
@@ -233,12 +244,12 @@ module Ndb
|
|
|
233
244
|
found
|
|
234
245
|
end
|
|
235
246
|
|
|
236
|
-
def find_by(attrs)
|
|
237
|
-
where(attrs).first
|
|
247
|
+
def find_by(attrs, &block)
|
|
248
|
+
where(attrs).first(&block)
|
|
238
249
|
end
|
|
239
250
|
|
|
240
|
-
def find_by!(attrs)
|
|
241
|
-
find_by(attrs) || raise(NotFound.new("Couldn't find #{klass.name}", code: "not_found"))
|
|
251
|
+
def find_by!(attrs, &block)
|
|
252
|
+
find_by(attrs, &block) || raise(NotFound.new("Couldn't find #{klass.name}", code: "not_found"))
|
|
242
253
|
end
|
|
243
254
|
|
|
244
255
|
def exists?
|
|
@@ -352,6 +363,28 @@ module Ndb
|
|
|
352
363
|
out
|
|
353
364
|
end
|
|
354
365
|
|
|
366
|
+
# find of a relation with lock: one id, locked by the daemon and read in
|
|
367
|
+
# the same step.
|
|
368
|
+
def lock_one(ids, &block)
|
|
369
|
+
raise ArgumentError, "lock.find takes one id" unless ids.size == 1
|
|
370
|
+
|
|
371
|
+
held = klass.ndb_lock(ids.first, **values[:lock])
|
|
372
|
+
record = klass.instantiate_locked(held)
|
|
373
|
+
|
|
374
|
+
block ? record.scoped_lock { yield record } : record
|
|
375
|
+
rescue NotFound
|
|
376
|
+
raise NotFound.new("Couldn't find #{klass.name} with #{klass.primary_key}=#{ids.first}", code: "not_found")
|
|
377
|
+
end
|
|
378
|
+
|
|
379
|
+
# A record that a query found, locked and read again (nil stays nil).
|
|
380
|
+
def lock_found(record, &block)
|
|
381
|
+
return nil unless record
|
|
382
|
+
|
|
383
|
+
record.lock!(**values[:lock])
|
|
384
|
+
|
|
385
|
+
block ? record.scoped_lock { yield record } : record
|
|
386
|
+
end
|
|
387
|
+
|
|
355
388
|
def find_one(id)
|
|
356
389
|
where(klass.primary_key => id).first ||
|
|
357
390
|
raise(NotFound.new("Couldn't find #{klass.name} with #{klass.primary_key}=#{id}", code: "not_found"))
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Ndb
|
|
4
|
+
# A write of a transaction block that cannot join it: a record of another
|
|
5
|
+
# collection. Nothing of the block is sent.
|
|
6
|
+
class TransactionError < Error; end
|
|
7
|
+
|
|
8
|
+
# The transaction of one collection, as `transaction` of ActiveRecord:
|
|
9
|
+
#
|
|
10
|
+
# Account.transaction(lock: [from, to], ttl: 5) do
|
|
11
|
+
# raise Ndb::Rollback if from.balance < amount
|
|
12
|
+
#
|
|
13
|
+
# from.update!(balance: from.balance - amount)
|
|
14
|
+
# to.update!(balance: to.balance + amount)
|
|
15
|
+
# end
|
|
16
|
+
#
|
|
17
|
+
# Inside the block, save, update, create, destroy, increment! and
|
|
18
|
+
# decrement! run their validations and callbacks as always, but send
|
|
19
|
+
# nothing: the writes are collected and go in one call at the end of the
|
|
20
|
+
# block (POST /{coll}/_tx), all of them or none. Then the records get their
|
|
21
|
+
# new versions and the locks are released.
|
|
22
|
+
#
|
|
23
|
+
# - An exception in the block writes nothing and goes on. Ndb::Rollback
|
|
24
|
+
# writes nothing, and the block returns nil. The records keep the values
|
|
25
|
+
# set in the block (ActiveRecord does not undo them either).
|
|
26
|
+
# - A refused commit writes nothing: Ndb::TxConflict when a record changed
|
|
27
|
+
# since it was read (its "_v") or is gone, Ndb::LockExpired when the
|
|
28
|
+
# locks outlived ttl (the time limit of the transaction).
|
|
29
|
+
# - lock: takes the locks of those records (or ids) in one call, all or
|
|
30
|
+
# none, and reads the records again under the lock. `lock!` inside the
|
|
31
|
+
# block also joins the transaction (one call per record; sort them).
|
|
32
|
+
# - Reads inside the block see the stored data, not the writes of the
|
|
33
|
+
# block.
|
|
34
|
+
# - One collection: a write of another model raises Ndb::TransactionError.
|
|
35
|
+
# A nested block joins the outer one.
|
|
36
|
+
module Transactions
|
|
37
|
+
extend ActiveSupport::Concern
|
|
38
|
+
|
|
39
|
+
class_methods do
|
|
40
|
+
def transaction(lock: nil, ttl: nil, wait: nil)
|
|
41
|
+
outer = RecordTransaction.current
|
|
42
|
+
|
|
43
|
+
if outer
|
|
44
|
+
outer.check!(self)
|
|
45
|
+
|
|
46
|
+
return yield
|
|
47
|
+
end
|
|
48
|
+
|
|
49
|
+
tx = RecordTransaction.new(self)
|
|
50
|
+
RecordTransaction.current = tx
|
|
51
|
+
|
|
52
|
+
begin
|
|
53
|
+
tx.lock_records(Array(lock), ttl: ttl, wait: wait) if lock
|
|
54
|
+
result = yield
|
|
55
|
+
tx.commit!
|
|
56
|
+
|
|
57
|
+
result
|
|
58
|
+
rescue Rollback
|
|
59
|
+
tx.abort!
|
|
60
|
+
|
|
61
|
+
nil
|
|
62
|
+
rescue Exception # rubocop:disable Lint/RescueException
|
|
63
|
+
tx.abort!
|
|
64
|
+
|
|
65
|
+
raise
|
|
66
|
+
ensure
|
|
67
|
+
RecordTransaction.current = nil
|
|
68
|
+
end
|
|
69
|
+
end
|
|
70
|
+
end
|
|
71
|
+
|
|
72
|
+
private
|
|
73
|
+
|
|
74
|
+
# The transaction that this record's writes join, or nil.
|
|
75
|
+
def current_transaction
|
|
76
|
+
tx = RecordTransaction.current
|
|
77
|
+
|
|
78
|
+
tx&.check!(self.class)
|
|
79
|
+
|
|
80
|
+
tx
|
|
81
|
+
end
|
|
82
|
+
end
|
|
83
|
+
|
|
84
|
+
# The state of one Model.transaction block: the writes, the records they
|
|
85
|
+
# belong to, and the lock tokens.
|
|
86
|
+
class RecordTransaction
|
|
87
|
+
KEY = :ndb_record_transaction
|
|
88
|
+
|
|
89
|
+
def self.current = Thread.current[KEY]
|
|
90
|
+
|
|
91
|
+
def self.current=(tx)
|
|
92
|
+
Thread.current[KEY] = tx
|
|
93
|
+
end
|
|
94
|
+
|
|
95
|
+
def initialize(klass)
|
|
96
|
+
@klass = klass
|
|
97
|
+
@ops = []
|
|
98
|
+
@records = []
|
|
99
|
+
@tokens = []
|
|
100
|
+
@guarded = {}
|
|
101
|
+
@locked = {}
|
|
102
|
+
end
|
|
103
|
+
|
|
104
|
+
def collection = @klass.collection_name
|
|
105
|
+
|
|
106
|
+
def check!(klass)
|
|
107
|
+
return if klass.collection_name == collection
|
|
108
|
+
|
|
109
|
+
raise TransactionError.new("a transaction of #{collection} cannot write #{klass.collection_name}", code: "transaction_error")
|
|
110
|
+
end
|
|
111
|
+
|
|
112
|
+
# Takes the locks of records (or ids) in one call and reads the records
|
|
113
|
+
# again under the lock.
|
|
114
|
+
def lock_records(list, ttl:, wait:)
|
|
115
|
+
return if list.empty?
|
|
116
|
+
|
|
117
|
+
ids = list.map { |r| r.respond_to?(:id) ? r.id : r }
|
|
118
|
+
held = @klass.ndb_lock_set(ids, **{ ttl: ttl, wait: wait }.compact)
|
|
119
|
+
|
|
120
|
+
@tokens << held["token"]
|
|
121
|
+
|
|
122
|
+
by_id = held["docs"].to_h { |doc| [doc[@klass.primary_key], doc] }
|
|
123
|
+
|
|
124
|
+
list.each do |record|
|
|
125
|
+
next unless record.respond_to?(:id)
|
|
126
|
+
|
|
127
|
+
record.send(:refresh_from!, by_id.fetch(record.id))
|
|
128
|
+
joined(record, held["token"])
|
|
129
|
+
end
|
|
130
|
+
|
|
131
|
+
ids.each { |id| @locked[id] = true }
|
|
132
|
+
end
|
|
133
|
+
|
|
134
|
+
# A lock! of a record inside the block.
|
|
135
|
+
def joined(record, token)
|
|
136
|
+
@tokens << token unless @tokens.include?(token)
|
|
137
|
+
@locked[record.id] = true
|
|
138
|
+
@records << record unless @records.include?(record)
|
|
139
|
+
|
|
140
|
+
record.send(:hold_in_transaction!, token)
|
|
141
|
+
end
|
|
142
|
+
|
|
143
|
+
def insert(record, doc)
|
|
144
|
+
add({ op: "insert", doc: doc }, record)
|
|
145
|
+
end
|
|
146
|
+
|
|
147
|
+
def update(record, ops)
|
|
148
|
+
add({ op: "update", id: record.id, update: ops, query: guard(record) }.compact, record)
|
|
149
|
+
end
|
|
150
|
+
|
|
151
|
+
def delete(record)
|
|
152
|
+
add({ op: "delete", id: record.id, query: guard(record) }.compact, record)
|
|
153
|
+
end
|
|
154
|
+
|
|
155
|
+
def commit!
|
|
156
|
+
if @ops.empty?
|
|
157
|
+
release
|
|
158
|
+
|
|
159
|
+
return
|
|
160
|
+
end
|
|
161
|
+
|
|
162
|
+
results = Rails.client.tx(collection, @ops.map(&:first), locks: @tokens, unlock: true)["results"]
|
|
163
|
+
|
|
164
|
+
@ops.zip(results).each do |(_, record), result|
|
|
165
|
+
record.send(:written_in_transaction!, result["_v"]) if result["_v"]
|
|
166
|
+
end
|
|
167
|
+
ensure
|
|
168
|
+
finish
|
|
169
|
+
end
|
|
170
|
+
|
|
171
|
+
def abort!
|
|
172
|
+
release
|
|
173
|
+
finish
|
|
174
|
+
end
|
|
175
|
+
|
|
176
|
+
private
|
|
177
|
+
|
|
178
|
+
def add(op, record)
|
|
179
|
+
@ops << [op, record]
|
|
180
|
+
@records << record unless @records.include?(record)
|
|
181
|
+
end
|
|
182
|
+
|
|
183
|
+
# The "_v" guard of the first write of a record that the transaction
|
|
184
|
+
# did not lock: a record that changed since it was read fails the
|
|
185
|
+
# commit. The later writes of the same record come after it in the same
|
|
186
|
+
# step, so they need none.
|
|
187
|
+
def guard(record)
|
|
188
|
+
return nil if @locked[record.id] || @guarded[record.id] || record.version.nil?
|
|
189
|
+
|
|
190
|
+
@guarded[record.id] = true
|
|
191
|
+
|
|
192
|
+
{ "_v" => record.version }
|
|
193
|
+
end
|
|
194
|
+
|
|
195
|
+
def release
|
|
196
|
+
@tokens.each do |token|
|
|
197
|
+
Rails.client.unlock_set(collection, token)
|
|
198
|
+
rescue Error
|
|
199
|
+
nil
|
|
200
|
+
end
|
|
201
|
+
end
|
|
202
|
+
|
|
203
|
+
def finish
|
|
204
|
+
@records.each { |record| record.send(:leave_transaction!) }
|
|
205
|
+
end
|
|
206
|
+
end
|
|
207
|
+
end
|
data/lib/ndb/rails/version.rb
CHANGED
data/lib/ndb/rails.rb
CHANGED
|
@@ -11,6 +11,8 @@ require "ndb/rails/dynamic_finders"
|
|
|
11
11
|
require "ndb/rails/relation"
|
|
12
12
|
require "ndb/rails/blob"
|
|
13
13
|
require "ndb/rails/persistence"
|
|
14
|
+
require "ndb/rails/locking"
|
|
15
|
+
require "ndb/rails/transactions"
|
|
14
16
|
require "ndb/rails/associations"
|
|
15
17
|
require "ndb/rails/record"
|
|
16
18
|
require "ndb/streams"
|
metadata
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
--- !ruby/object:Gem::Specification
|
|
2
2
|
name: ndb-rails
|
|
3
3
|
version: !ruby/object:Gem::Version
|
|
4
|
-
version: 1.
|
|
4
|
+
version: 1.19.0
|
|
5
5
|
platform: ruby
|
|
6
6
|
authors:
|
|
7
7
|
- thadeu
|
|
@@ -43,7 +43,7 @@ dependencies:
|
|
|
43
43
|
requirements:
|
|
44
44
|
- - ">="
|
|
45
45
|
- !ruby/object:Gem::Version
|
|
46
|
-
version: 1.
|
|
46
|
+
version: 1.19.0
|
|
47
47
|
- - "<"
|
|
48
48
|
- !ruby/object:Gem::Version
|
|
49
49
|
version: '2'
|
|
@@ -53,7 +53,7 @@ dependencies:
|
|
|
53
53
|
requirements:
|
|
54
54
|
- - ">="
|
|
55
55
|
- !ruby/object:Gem::Version
|
|
56
|
-
version: 1.
|
|
56
|
+
version: 1.19.0
|
|
57
57
|
- - "<"
|
|
58
58
|
- !ruby/object:Gem::Version
|
|
59
59
|
version: '2'
|
|
@@ -74,6 +74,7 @@ files:
|
|
|
74
74
|
- lib/ndb/rails/database_cleaner.rb
|
|
75
75
|
- lib/ndb/rails/dynamic_finders.rb
|
|
76
76
|
- lib/ndb/rails/errors.rb
|
|
77
|
+
- lib/ndb/rails/locking.rb
|
|
77
78
|
- lib/ndb/rails/minitest.rb
|
|
78
79
|
- lib/ndb/rails/persistence.rb
|
|
79
80
|
- lib/ndb/rails/railtie.rb
|
|
@@ -81,6 +82,7 @@ files:
|
|
|
81
82
|
- lib/ndb/rails/relation.rb
|
|
82
83
|
- lib/ndb/rails/rspec.rb
|
|
83
84
|
- lib/ndb/rails/testing.rb
|
|
85
|
+
- lib/ndb/rails/transactions.rb
|
|
84
86
|
- lib/ndb/rails/version.rb
|
|
85
87
|
- lib/ndb/streams.rb
|
|
86
88
|
- lib/ndb/streams/assertions.rb
|