ndb-rails 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: d3a73be7cffefc189591409d4ccf13efc25d2fb993c702d694596403dc2e9213
4
- data.tar.gz: 62e49d96aa80f7cffc516daeadbc925fb153d0e79b9cdd612b3f6c285868f9ab
3
+ metadata.gz: b2dd42ff7386e4b2e74d41f59afbd7349e8535caeb9c3a4e366585fff0379d6f
4
+ data.tar.gz: 36b7f7c75176a93b169222e681ded1d401b73833a8c49097c20235431f725bba
5
5
  SHA512:
6
- metadata.gz: 19835a0ec956ecd02a85399a0c586093308cfc1834b2cd7af40e38d80f1ef8c5d43d77e6919e6244ab8e6aa8c4eb593be2fc244604669d1c894c5f9dbf5ccf50
7
- data.tar.gz: 9dfc35aa1ee11d5a96d4980bab48dbc1fe920e1f7d725e8a1298d036feaab92e577bc0facbe2f15bf9bfccf7b5ea546aea267e7b119fed8c03c38e515efdacc0
6
+ metadata.gz: ad8bc303912d5ad086493e560c38e0c60da9ae1ebbe1433d9ba1ade7579466a00722cc07821cb0f983d95d3eb7013431ba7b03c1746d202bac80a957e84e1cca
7
+ data.tar.gz: '08c9aafae94c2f0b7e113d06896ad4dbbc2a7308bf193d446c0f9c6c7f10da99284bd3d0f889ce936ff9661dde749d463069529ed798a8cac53d9aa80d5c1006'
@@ -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
- deleted = self.class.ndb_delete(record_filter)["deleted"]
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
- result = self.class.ndb_update({ self.class.primary_key => id }, { "$inc" => { name => by } })
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
- unless set.empty? && unset.empty? && @expire_in.nil?
313
- result = self.class.ndb_update(record_filter, update_ops(set, unset), expire_in: @expire_in)
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
@@ -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 unwind 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
 
@@ -175,6 +177,22 @@ module Ndb
175
177
  @ttl || (superclass.respond_to?(:ttl) ? superclass.ttl : nil)
176
178
  end
177
179
 
180
+ # An index on 1 to 4 attributes or paths. With one it is `index: true`
181
+ # as a call, for a path that is not an attribute ("items.sku"). With
182
+ # more it is a compound index, in this order: it serves a where with
183
+ # equality on the first attributes and a range on the next one. With
184
+ # unique: true it is a unique key instead (one live document per value
185
+ # or tuple of values; Ndb::RecordNotUnique).
186
+ #
187
+ # index :account_id, :created_at
188
+ # index :account_id, :email, unique: true
189
+ # index "items.sku"
190
+ def index(*names, unique: false)
191
+ raise ArgumentError, "index takes 1 to 4 attributes" unless (1..4).cover?(names.size)
192
+
193
+ (unique ? own_unique : own_indexed) << names.join(",")
194
+ end
195
+
178
196
  def indexed_fields
179
197
  inherited_list(:indexed_fields) | own_indexed
180
198
  end
@@ -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)
@@ -82,6 +91,16 @@ module Ndb
82
91
  with(group: fields.flatten.map(&:to_s))
83
92
  end
84
93
 
94
+ # Makes the aggregates of the relation (count, sum, average, minimum,
95
+ # maximum, with or without group) read one row per element of an array
96
+ # attribute, as $unwind: `Order.unwind(:items).group("items.sku")
97
+ # .sum("items.qty")`. A document with no element gives no row. It is for
98
+ # the aggregates only: reading the records of such a relation raises
99
+ # ArgumentError.
100
+ def unwind(field)
101
+ with(unwind: field.to_s)
102
+ end
103
+
85
104
  # The JSON body that this relation sends to the daemon, as a String,
86
105
  # with no request (like to_sql of ActiveRecord). It is the body of
87
106
  # POST /{collection}/_search; pretty: true gives it on many lines.
@@ -96,6 +115,8 @@ module Ndb
96
115
 
97
116
  # The find body: JSON only, the daemon decides what it means.
98
117
  def to_query
118
+ raise ArgumentError, "unwind is for count, sum, average, minimum and maximum; it does not change the records of a relation" if values[:unwind]
119
+
99
120
  query = {}
100
121
  where = Conditions.combine(values[:where])
101
122
 
@@ -194,7 +215,8 @@ module Ndb
194
215
  # With no order, the order is the primary key (as ActiveRecord does),
195
216
  # so first and last are the two ends of one order. The daemon gives
196
217
  # only count rows (limit), not the whole relation.
197
- def first(count = nil)
218
+ def first(count = nil, &block)
219
+ return lock_found(with(lock: nil).first, &block) if values[:lock] && count.nil?
198
220
  return count ? records.first(count) : records.first if loaded?
199
221
 
200
222
  found = by_key.limit(count || 1).to_a
@@ -222,9 +244,10 @@ module Ndb
222
244
  with(order: sort)
223
245
  end
224
246
 
225
- def find(*ids)
247
+ def find(*ids, &block)
226
248
  ids = ids.flatten
227
249
 
250
+ return lock_one(ids, &block) if values[:lock]
228
251
  return find_one(ids.first) if ids.size == 1 && !ids.first.is_a?(Array)
229
252
 
230
253
  found = where(klass.primary_key => ids).to_a
@@ -233,12 +256,12 @@ module Ndb
233
256
  found
234
257
  end
235
258
 
236
- def find_by(attrs)
237
- where(attrs).first
259
+ def find_by(attrs, &block)
260
+ where(attrs).first(&block)
238
261
  end
239
262
 
240
- def find_by!(attrs)
241
- find_by(attrs) || raise(NotFound.new("Couldn't find #{klass.name}", code: "not_found"))
263
+ def find_by!(attrs, &block)
264
+ find_by(attrs, &block) || raise(NotFound.new("Couldn't find #{klass.name}", code: "not_found"))
242
265
  end
243
266
 
244
267
  def exists?
@@ -259,7 +282,7 @@ module Ndb
259
282
  end
260
283
 
261
284
  def count
262
- return calculate(:count) unless values[:group].empty?
285
+ return calculate(:count) unless values[:group].empty? && values[:unwind].nil?
263
286
 
264
287
  klass.ndb_find(to_query.slice("query").merge("count" => true, "limit" => 1, "fields" => [klass.primary_key])).total
265
288
  end
@@ -303,6 +326,7 @@ module Ndb
303
326
  where = Conditions.combine(values[:where])
304
327
 
305
328
  stages << { "$match" => where } unless where.empty?
329
+ stages << { "$unwind" => "$#{values[:unwind]}" } if values[:unwind]
306
330
  stages << { "$group" => { "_id" => group_id, op.to_s => accumulator(op, field) } }
307
331
 
308
332
  { "pipeline" => stages }
@@ -352,6 +376,28 @@ module Ndb
352
376
  out
353
377
  end
354
378
 
379
+ # find of a relation with lock: one id, locked by the daemon and read in
380
+ # the same step.
381
+ def lock_one(ids, &block)
382
+ raise ArgumentError, "lock.find takes one id" unless ids.size == 1
383
+
384
+ held = klass.ndb_lock(ids.first, **values[:lock])
385
+ record = klass.instantiate_locked(held)
386
+
387
+ block ? record.scoped_lock { yield record } : record
388
+ rescue NotFound
389
+ raise NotFound.new("Couldn't find #{klass.name} with #{klass.primary_key}=#{ids.first}", code: "not_found")
390
+ end
391
+
392
+ # A record that a query found, locked and read again (nil stays nil).
393
+ def lock_found(record, &block)
394
+ return nil unless record
395
+
396
+ record.lock!(**values[:lock])
397
+
398
+ block ? record.scoped_lock { yield record } : record
399
+ end
400
+
355
401
  def find_one(id)
356
402
  where(klass.primary_key => id).first ||
357
403
  raise(NotFound.new("Couldn't find #{klass.name} with #{klass.primary_key}=#{id}", code: "not_found"))
@@ -376,7 +422,7 @@ module Ndb
376
422
 
377
423
  return rows.to_h { |row| [group_key(row["_id"]), row[key]] } unless values[:group].empty?
378
424
 
379
- rows.first&.fetch(key) || (op == :sum ? 0 : nil)
425
+ rows.first&.fetch(key) || (%i[sum count].include?(op) ? 0 : nil)
380
426
  end
381
427
 
382
428
  def group_key(id)
@@ -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
@@ -2,6 +2,6 @@
2
2
 
3
3
  module Ndb
4
4
  module Rails
5
- VERSION = "1.18.2"
5
+ VERSION = "1.20.0"
6
6
  end
7
7
  end
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.18.2
4
+ version: 1.20.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.18.2
46
+ version: 1.20.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.18.2
56
+ version: 1.20.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