ndb-rails 1.23.3 → 1.25.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: 0ad5aca739eddaf19c833931a7672bd30d0ed6476d0637ce9cd73f4e722bd20f
4
- data.tar.gz: 01cdfb078dc4189b475fe9931fffb4821fb7ca7cdcc7f98a82d3c6cef6fa672d
3
+ metadata.gz: d8de1a2b63acb694b950f2e933f703ba6f8f76a5eaec4a3366a04e94e3a400d8
4
+ data.tar.gz: 5e7777c5cc317c0b2abe8ea99e9cebbd7d91d2213fc27d207a1bc75a17a5de80
5
5
  SHA512:
6
- metadata.gz: 2dc449bf0022b4b14a307e7e525f6642af966dc46cdf9d0d55d97b0986545ddb75befb92417140e9580d6ed5e4dd530d5ac6868d33627c6ae74d99547d60dad5
7
- data.tar.gz: 58a8fc3bde98cde180ea34b7f26b96d0136291df36d1112b8a6e395c88d7f0aaa40a7dc9b416bae2dd8b74b02fcef0b485afe3d8f9865796eaf158643b851d07
6
+ metadata.gz: '0781e2c7d0cff236d507226cf6bf6664fafd6814abab03efabb35e1549c166efdb5b62f7eef0bc7281007b90f78609bdd7c36437e6f6808f4af32b8617ddc5f0'
7
+ data.tar.gz: 30ce0b2dfe60018bd12dddb754fd9e9d412deb26dda7f2004412a13feb6b4d301b6ce8e510150760df2a06791b9911edf220e54774f7541c122e52e4f3ce8db3
data/README.md CHANGED
@@ -487,6 +487,21 @@ assert_streamed OrderEvent, order_id: 42
487
487
  expect(OrderEvent).to have_streamed(order_id: 42)
488
488
  ```
489
489
 
490
+ ## ActionCable
491
+
492
+ `adapter: ndb` in `config/cable.yml` makes ndb the pub/sub of ActionCable, in place of Redis.
493
+
494
+ ```yaml
495
+ # config/cable.yml
496
+ production:
497
+ adapter: ndb
498
+ stream: cable # default "cable"
499
+ max_len: 10000 # default 10 000 (approximate trim on each broadcast)
500
+ channel_prefix: myapp_production
501
+ ```
502
+
503
+ A broadcast appends one entry to the stream. Each process has one thread that reads the stream without a group, so every process gets every broadcast (a fan-out, as Redis PUBLISH/SUBSCRIBE). Delivery is at most once. ActionCable loads the adapter only for `adapter: ndb`: the gem does not need `actioncable` for anything else. A change made by another service (in Go, for example) gets to the browser through an `Ndb::Streams` consumer in the app that calls `ActionCable.server.broadcast`. See [ActionCable](https://ndb.clowk.in/clients/rails#actioncable).
504
+
490
505
  ## Errors
491
506
 
492
507
  The transport and daemon errors are defined by the gem `ndb`. They all live in the `Ndb` module (`Ndb::Error`, `Ndb::NotFound`, ...). For an ActiveRecord-like `rescue`, this gem adds one alias: `Ndb::RecordNotUnique` is `Ndb::UniqueViolation` (the same class). `Ndb::StaleObjectError`, `Ndb::RecordInvalid` and `Ndb::RecordNotSaved` exist only here, and they inherit from `Ndb::Error`. Every error has `code` (the daemon code) and `status` (the HTTP status).
@@ -0,0 +1,201 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "ndb/rails"
4
+
5
+ module ActionCable
6
+ module SubscriptionAdapter
7
+ # The ActionCable adapter on an ndb stream (adapter: ndb in
8
+ # config/cable.yml). A broadcast appends one entry to the stream. Each
9
+ # process has one listener thread that reads the stream without a group,
10
+ # so every process gets every entry, and gives each entry to its local
11
+ # subscribers. As Redis PUBLISH/SUBSCRIBE: at most once, and a process
12
+ # gets only the entries appended after it starts to listen.
13
+ #
14
+ # cable.yml keys: stream (default "cable"), max_len (default 10_000, an
15
+ # approximate trim on each broadcast) and channel_prefix.
16
+ class Ndb < Base
17
+ prepend ChannelPrefix
18
+
19
+ DEFAULT_STREAM = "cable"
20
+ DEFAULT_MAX_LEN = 10_000
21
+
22
+ # Seconds that one read waits for a new entry. shutdown waits at most
23
+ # this long for the thread.
24
+ cattr_accessor :block, default: 5
25
+
26
+ # Seconds that the listener waits after an error before it reads again.
27
+ cattr_accessor :retry_after, default: 1
28
+
29
+ def initialize(*)
30
+ super
31
+
32
+ @listener = nil
33
+ @stream = nil
34
+ end
35
+
36
+ def broadcast(channel, payload)
37
+ doc = { "channel" => channel, "payload" => payload }
38
+
39
+ stream.append(doc, trim: { max_len: max_len, approx: true })
40
+ end
41
+
42
+ def subscribe(channel, callback, success_callback = nil)
43
+ listener.add_subscriber(channel, callback, success_callback)
44
+ end
45
+
46
+ def unsubscribe(channel, callback)
47
+ listener.remove_subscriber(channel, callback)
48
+ end
49
+
50
+ def shutdown
51
+ @listener&.shutdown
52
+ end
53
+
54
+ def stream
55
+ @stream || @server.mutex.synchronize do
56
+ @stream ||= ::Ndb::Rails.client.stream(config_options.fetch(:stream, DEFAULT_STREAM))
57
+ end
58
+ end
59
+
60
+ private
61
+
62
+ def listener
63
+ @listener || @server.mutex.synchronize { @listener ||= Listener.new(self, @server.event_loop) }
64
+ end
65
+
66
+ def max_len
67
+ config_options.fetch(:max_len, DEFAULT_MAX_LEN)
68
+ end
69
+
70
+ def config_options
71
+ @config_options ||= @server.config.cable.deep_symbolize_keys
72
+ end
73
+
74
+ # The subscribers of one process and the thread that reads the stream.
75
+ class Listener < SubscriberMap
76
+ READ_COUNT = 500
77
+
78
+ def initialize(adapter, event_loop)
79
+ super()
80
+
81
+ @adapter = adapter
82
+ @event_loop = event_loop
83
+
84
+ @lock = Mutex.new
85
+ @thread = nil
86
+ @running = false
87
+ @ready = false
88
+ @waiting = []
89
+ end
90
+
91
+ # True when the thread knows where to start: a subscription made
92
+ # after this gets every later broadcast.
93
+ def ready?
94
+ @ready
95
+ end
96
+
97
+ # The success callback runs once the thread is ready. Nothing goes to
98
+ # ndb: the thread reads every entry.
99
+ def add_channel(_channel, on_success)
100
+ @lock.synchronize do
101
+ start
102
+
103
+ next unless on_success
104
+
105
+ if @ready
106
+ @event_loop.post(&on_success)
107
+ else
108
+ @waiting << on_success
109
+ end
110
+ end
111
+ end
112
+
113
+ def invoke_callback(*)
114
+ @event_loop.post { super }
115
+ end
116
+
117
+ def shutdown
118
+ thread = @lock.synchronize do
119
+ @running = false
120
+
121
+ @thread
122
+ end
123
+
124
+ thread&.join
125
+ end
126
+
127
+ private
128
+
129
+ def start
130
+ return if @thread
131
+
132
+ @running = true
133
+ @thread = Thread.new { listen }
134
+ end
135
+
136
+ def running?
137
+ @lock.synchronize { @running }
138
+ end
139
+
140
+ def listen
141
+ after = nil
142
+
143
+ while running?
144
+ begin
145
+ after ||= start_id
146
+ after = read(after)
147
+ rescue StandardError => e
148
+ @adapter.logger.error("ActionCable ndb adapter: #{e.class}: #{e.message}")
149
+
150
+ sleep @adapter.retry_after
151
+ end
152
+ end
153
+ end
154
+
155
+ # The last ID of the stream: the next read gives only the entries
156
+ # appended after it. A stream that does not exist yet starts at "0".
157
+ # "$" on each read would lose an entry appended between two reads.
158
+ def start_id
159
+ last = @adapter.stream.rev_range(count: 1).first
160
+ id = last ? last.id : ::Ndb::Stream::START_ALL
161
+
162
+ ready!
163
+
164
+ id
165
+ rescue ::Ndb::UnknownCollection
166
+ ready!
167
+
168
+ ::Ndb::Stream::START_ALL
169
+ end
170
+
171
+ def ready!
172
+ @lock.synchronize do
173
+ @ready = true
174
+
175
+ @waiting.each { |callback| @event_loop.post(&callback) }
176
+ @waiting.clear
177
+ end
178
+ end
179
+
180
+ # One blocking read. Returns the ID to read after next time.
181
+ def read(after)
182
+ entries = @adapter.stream.read(after: after, count: READ_COUNT, block: @adapter.block)
183
+
184
+ entries.each do |entry|
185
+ after = entry.id
186
+
187
+ next if entry.deleted?
188
+
189
+ broadcast(entry.doc["channel"], entry.doc["payload"])
190
+ end
191
+
192
+ after
193
+ rescue ::Ndb::UnknownCollection
194
+ sleep @adapter.retry_after
195
+
196
+ after
197
+ end
198
+ end
199
+ end
200
+ end
201
+ end
@@ -0,0 +1,76 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Ndb
4
+ # after_commit and after_rollback, as ActiveRecord. They run when the write
5
+ # is durable: after the write itself, or, inside Model.transaction, after
6
+ # the transaction commits. after_rollback runs when the transaction writes
7
+ # nothing (an exception or Ndb::Rollback).
8
+ #
9
+ # after_create_commit { Billing.notify(id) }
10
+ # after_commit :reindex, on: %i[create update]
11
+ module CommitCallbacks
12
+ extend ActiveSupport::Concern
13
+
14
+ included do
15
+ define_callbacks :commit, :rollback
16
+ end
17
+
18
+ class_methods do
19
+ def after_commit(*args, on: nil, **options, &block)
20
+ set_callback(:commit, :after, *args, **on_action(on, options), &block)
21
+ end
22
+
23
+ def after_rollback(*args, on: nil, **options, &block)
24
+ set_callback(:rollback, :after, *args, **on_action(on, options), &block)
25
+ end
26
+
27
+ def after_create_commit(*args, **options, &block)
28
+ after_commit(*args, on: :create, **options, &block)
29
+ end
30
+
31
+ def after_update_commit(*args, **options, &block)
32
+ after_commit(*args, on: :update, **options, &block)
33
+ end
34
+
35
+ def after_save_commit(*args, **options, &block)
36
+ after_commit(*args, on: %i[create update], **options, &block)
37
+ end
38
+
39
+ def after_destroy_commit(*args, **options, &block)
40
+ after_commit(*args, on: :destroy, **options, &block)
41
+ end
42
+
43
+ private
44
+
45
+ def on_action(on, options)
46
+ return options unless on
47
+
48
+ actions = Array(on)
49
+
50
+ options.merge(if: Array(options[:if]) + [-> { actions.include?(@commit_action) }])
51
+ end
52
+ end
53
+
54
+ private
55
+
56
+ # A write of action (:create, :update, :destroy) is done: its commit
57
+ # callbacks run now, or when the transaction it joined ends.
58
+ def committed(action)
59
+ if (tx = RecordTransaction.current)
60
+ tx.on_commit(self, action)
61
+
62
+ return
63
+ end
64
+
65
+ run_commit_callbacks(:commit, action)
66
+ end
67
+
68
+ def run_commit_callbacks(kind, action)
69
+ @commit_action = action
70
+
71
+ run_callbacks(kind)
72
+ ensure
73
+ @commit_action = nil
74
+ end
75
+ end
76
+ end
@@ -29,4 +29,7 @@ module Ndb
29
29
  super("Validation failed: #{record.errors.full_messages.join(', ')}")
30
30
  end
31
31
  end
32
+
33
+ # Raised by sole and find_sole_by when more than one record matches.
34
+ class SoleRecordExceeded < Error; end
32
35
  end
@@ -10,6 +10,9 @@ module Ndb
10
10
 
11
11
  included do
12
12
  define_model_callbacks :save, :create, :update, :destroy
13
+
14
+ include CommitCallbacks
15
+ include RecordWrites
13
16
  end
14
17
 
15
18
  class_methods do
@@ -46,6 +49,7 @@ module Ndb
46
49
  record = new(row.slice(*attribute_names))
47
50
 
48
51
  record.send(:loaded!, version, source)
52
+ record.send(:clear_changes_information)
49
53
  record.load_associations(row) if record.respond_to?(:load_associations)
50
54
 
51
55
  record
@@ -92,8 +96,13 @@ module Ndb
92
96
  return false if validate && !valid?(new_record? ? :create : :update)
93
97
 
94
98
  @expire_in = wire_duration(expire_in)
99
+ action = new_record? ? :create : :update
100
+
101
+ saved = run_callbacks(:save) { action == :create ? create_record : update_record } ? true : false
95
102
 
96
- run_callbacks(:save) { new_record? ? create_record : update_record } ? true : false
103
+ committed(action) if saved
104
+
105
+ saved
97
106
  ensure
98
107
  @expire_in = nil
99
108
  end
@@ -146,6 +155,8 @@ module Ndb
146
155
  @destroyed = true
147
156
  end
148
157
 
158
+ committed(:destroy) if result
159
+
149
160
  result ? self : false
150
161
  end
151
162
 
@@ -30,6 +30,8 @@ module Ndb
30
30
  QUERY_METHODS = %i[
31
31
  where where_raw order limit offset page after group unwind includes lock encrypted find find_by find_by! first last count pluck exists?
32
32
  find_each in_batches sum average minimum maximum to_a each destroy_all delete_all to_ndb
33
+ update_all first! last! take take! sole find_sole_by destroy_by delete_by ids pick none
34
+ reorder rewhere unscope distinct select
33
35
  ].freeze
34
36
 
35
37
  delegate(*QUERY_METHODS, to: :all)
@@ -0,0 +1,182 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Ndb
4
+ # The small writes of ActiveRecord: touch, update_columns, toggle!,
5
+ # update_attribute, insert_all, the counters, the saved changes of Dirty
6
+ # and the cache keys.
7
+ module RecordWrites
8
+ extend ActiveSupport::Concern
9
+
10
+ included do
11
+ define_model_callbacks :touch, only: :after
12
+
13
+ attribute_method_affix prefix: "saved_change_to_", suffix: "?"
14
+ attribute_method_affix prefix: "will_save_change_to_", suffix: "?"
15
+ attribute_method_suffix "_before_last_save"
16
+ end
17
+
18
+ class_methods do
19
+ # Inserts many documents in one _bulk: no validations, no callbacks.
20
+ # Each gets created_at and updated_at. An _id that exists raises
21
+ # Ndb::RecordNotUnique (code duplicate_id), as insert_all! of
22
+ # ActiveRecord.
23
+ def insert_all(rows)
24
+ ensure_collection!
25
+
26
+ now = Conditions.json_value(current_time)
27
+
28
+ docs = rows.map do |attrs|
29
+ doc = upsert_document(attrs)
30
+
31
+ doc["created_at"] ||= now
32
+ doc["updated_at"] ||= now
33
+
34
+ doc
35
+ end
36
+
37
+ Rails.client.bulk(collection_name, docs)
38
+ end
39
+
40
+ alias_method :insert_all!, :insert_all
41
+
42
+ # Adds to number attributes of the documents with these ids in one
43
+ # atomic write, and sets updated_at. Returns the count of matches.
44
+ #
45
+ # Post.update_counters("p1", views: 1, likes: -1)
46
+ def update_counters(id_or_ids, counters)
47
+ ids = Array(id_or_ids)
48
+ inc = counters.to_h { |name, by| [name.to_s, by] }
49
+ ops = { "$inc" => inc, "$set" => { "updated_at" => Conditions.json_value(current_time) } }
50
+
51
+ ndb_update({ primary_key => { "$in" => ids } }, ops, many: true)["matched"]
52
+ end
53
+
54
+ def increment_counter(name, id, by: 1)
55
+ update_counters(id, name => by)
56
+ end
57
+
58
+ def decrement_counter(name, id, by: 1)
59
+ update_counters(id, name => -by)
60
+ end
61
+ end
62
+
63
+ # Sets updated_at, and the named datetime attributes, to now (or time)
64
+ # in one atomic write. No validations, no save callbacks; after_touch
65
+ # runs. Other unsaved changes stay unsaved.
66
+ def touch(*names, time: nil)
67
+ now = time || self.class.current_time
68
+ values = ["updated_at", *names.map(&:to_s)].to_h { |name| [name, now] }
69
+
70
+ write_columns(values)
71
+ run_callbacks(:touch)
72
+
73
+ true
74
+ end
75
+
76
+ # $set of these attributes, cast by type, in one atomic write. No
77
+ # validations, no callbacks, and updated_at does not change.
78
+ def update_columns(attrs)
79
+ write_columns(attrs.to_h { |name, value| [name.to_s, value] })
80
+
81
+ true
82
+ end
83
+
84
+ def update_column(name, value)
85
+ update_columns(name => value)
86
+ end
87
+
88
+ def toggle(attribute)
89
+ public_send("#{attribute}=", !public_send(attribute))
90
+
91
+ self
92
+ end
93
+
94
+ def toggle!(attribute)
95
+ toggle(attribute)
96
+
97
+ update_attribute(attribute, public_send(attribute))
98
+ end
99
+
100
+ # Saves with the callbacks and without the validations.
101
+ def update_attribute(name, value)
102
+ public_send("#{name}=", value)
103
+
104
+ save(validate: false)
105
+ end
106
+
107
+ def saved_changes = previous_changes
108
+
109
+ def saved_change_to_attribute?(name) = attribute_previously_changed?(name.to_s)
110
+
111
+ def saved_change_to_attribute(name) = attribute_previous_change(name.to_s)
112
+
113
+ def attribute_before_last_save(name) = attribute_previously_was(name.to_s)
114
+
115
+ def will_save_change_to_attribute?(name) = attribute_changed?(name.to_s)
116
+
117
+ # "posts/p1", or "posts/new" for a new record. The version is apart, in
118
+ # cache_version, as ActiveRecord with cache versioning.
119
+ def cache_key
120
+ "#{model_name.cache_key}/#{persisted? ? id : 'new'}"
121
+ end
122
+
123
+ # updated_at and the document version: it changes on every write.
124
+ def cache_version
125
+ return unless persisted?
126
+
127
+ [updated_at&.utc&.to_fs(:usec), version].compact.join("-")
128
+ end
129
+
130
+ def cache_key_with_version
131
+ version = cache_version
132
+
133
+ version.present? ? "#{cache_key}-#{version}" : cache_key
134
+ end
135
+
136
+ private
137
+
138
+ def write_columns(values)
139
+ raise RecordNotSaved, "Cannot update a record that is not saved" unless persisted?
140
+
141
+ raise_if_readonly
142
+
143
+ names = values.keys
144
+
145
+ unknown = names - self.class.attribute_names
146
+
147
+ raise ArgumentError, "#{unknown.join(', ')} is not an attribute of #{self.class.name}" if unknown.any?
148
+
149
+ values.each { |name, value| public_send("#{name}=", value) }
150
+
151
+ set = {}
152
+ unset = {}
153
+
154
+ names.each do |name|
155
+ value = json_attribute(name)
156
+
157
+ value.nil? ? unset[name] = true : set[name] = value
158
+ end
159
+
160
+ ops = {}
161
+ ops["$set"] = set unless set.empty?
162
+ ops["$unset"] = unset unless unset.empty?
163
+
164
+ send_columns(ops)
165
+ clear_attribute_changes(names)
166
+ end
167
+
168
+ def send_columns(ops)
169
+ if (tx = current_transaction)
170
+ tx.update(self, ops)
171
+
172
+ return
173
+ end
174
+
175
+ result = holding { self.class.ndb_update({ self.class.primary_key => id }, ops, **lock_options) }
176
+
177
+ raise NotFound.new("#{self.class.name} #{id} was deleted", code: "not_found") if result["matched"].zero?
178
+
179
+ @version = result["doc"]["_v"]
180
+ end
181
+ end
182
+ end
@@ -11,6 +11,7 @@ module Ndb
11
11
  BATCH_SIZE = 1000
12
12
  EMPTY = { where: [].freeze, order: {}.freeze, group: [].freeze }.freeze
13
13
  PRELOADED = Data.define(:rows, :next, :total).new(rows: [].freeze, next: nil, total: nil)
14
+ NONE = PRELOADED.with(total: 0)
14
15
 
15
16
  attr_reader :klass, :values
16
17
 
@@ -44,9 +45,16 @@ module Ndb
44
45
  with(where: [{ "$or" => clauses }])
45
46
  end
46
47
 
48
+ # order(:n), order(n: :desc) or the Active Record String forms "n",
49
+ # "n DESC" and "n asc, m desc". Any other String (a SQL expression)
50
+ # raises ArgumentError.
47
51
  def order(*args)
48
52
  sort = args.each_with_object(values[:order].dup) do |arg, out|
49
- arg.is_a?(Hash) ? arg.each { |f, dir| out[f.to_s] = direction(dir) } : out[arg.to_s] = 1
53
+ case arg
54
+ when Hash then arg.each { |f, dir| out[f.to_s] = direction(dir) }
55
+ when String then out.merge!(parse_order(arg))
56
+ else out[arg.to_s] = 1
57
+ end
50
58
  end
51
59
 
52
60
  with(order: sort)
@@ -109,6 +117,57 @@ module Ndb
109
117
  with(unwind: field.to_s)
110
118
  end
111
119
 
120
+ # The order replaced, not added to: order(:a).reorder(b: :desc).
121
+ def reorder(*args)
122
+ with(order: {}).order(*args)
123
+ end
124
+
125
+ # The where of these attributes replaced: where(n: 1).rewhere(n: 2).
126
+ # Only the equality clauses of these fields are removed.
127
+ def rewhere(attrs)
128
+ keys = alias_id(attrs).keys.map(&:to_s)
129
+ kept = values[:where].map { |clause| clause.except(*keys) }.reject(&:empty?)
130
+
131
+ with(where: kept).where(attrs)
132
+ end
133
+
134
+ UNSCOPE = {
135
+ where: { where: [].freeze }, order: { order: {}.freeze }, limit: { limit: nil }, offset: { offset: nil },
136
+ page: { page: nil, per: nil }, after: { after: nil }, group: { group: [].freeze }, includes: { includes: nil },
137
+ select: { select: nil }, distinct: { distinct: nil }
138
+ }.freeze
139
+
140
+ # The relation without these parts: unscope(:where, :order, :limit...).
141
+ def unscope(*types)
142
+ changes = types.reduce({}) do |out, type|
143
+ out.merge(UNSCOPE.fetch(type.to_sym) { raise ArgumentError, "unscope takes #{UNSCOPE.keys.join(", ")}, got #{type.inspect}" })
144
+ end
145
+
146
+ with(changes)
147
+ end
148
+
149
+ # Makes pluck give each value (or row of values) once.
150
+ def distinct(value = true)
151
+ with(distinct: value)
152
+ end
153
+
154
+ # select(:a, :b): the records with only these attributes loaded (the
155
+ # daemon projection; the primary key is always read). With a block, it
156
+ # is Enumerable#select.
157
+ def select(*fields, &block)
158
+ return super(&block) if block
159
+
160
+ raise ArgumentError, "select needs at least one field" if fields.empty?
161
+
162
+ with(select: fields.map(&:to_s))
163
+ end
164
+
165
+ # An empty relation: it sends no request. to_a is [], count is 0, and
166
+ # update and delete_all write nothing.
167
+ def none
168
+ with(none: true)
169
+ end
170
+
112
171
  # The JSON body that this relation sends to the daemon, as a String,
113
172
  # with no request (like to_sql of ActiveRecord). It is the body of
114
173
  # POST /{collection}/_search; pretty: true gives it on many lines.
@@ -133,6 +192,7 @@ module Ndb
133
192
  query.merge!(window)
134
193
  query["after"] = values[:after] if values[:after]
135
194
  query["lookup"] = klass.lookup_for(values[:includes]) if values[:includes]&.any?
195
+ query["fields"] = ([klass.primary_key] + values[:select]).uniq if values[:select]
136
196
 
137
197
  query
138
198
  end
@@ -153,17 +213,63 @@ module Ndb
153
213
 
154
214
  ops = with_attributes(ops, attrs) unless attrs.empty?
155
215
 
156
- klass.ndb_update(Conditions.combine(values[:where]), with_updated_at(ops), many: true, expire_in: expire_in).fetch("modified")
216
+ where = write_where
217
+
218
+ return 0 unless where
219
+
220
+ klass.ndb_update(where, with_updated_at(ops), many: true, expire_in: expire_in).fetch("modified")
157
221
  end
158
222
 
159
223
  # One daemon delete on every match, no callbacks (same rule as update).
160
224
  # Returns how many. An unfiltered relation is refused by the daemon
161
- # (Ndb::EmptyFilter).
225
+ # (Ndb::EmptyFilter). A limit, offset, page or cursor narrows it to
226
+ # those rows, as for update.
162
227
  def delete_all
163
- klass.ndb_delete(Conditions.combine(values[:where]), many: true).fetch("deleted")
228
+ where = write_where
229
+
230
+ return 0 unless where
231
+
232
+ klass.ndb_delete(where, many: true).fetch("deleted")
164
233
  end
165
234
 
166
235
  alias delete delete_all
236
+ alias update_all update
237
+
238
+ # A new record with the equality attributes of the where, as the
239
+ # scoping of Active Record: Call.where(status: "new").new(caller: "a").
240
+ def new(attrs = {}, &block)
241
+ klass.new(scope_attributes.merge(attrs.transform_keys(&:to_s))).tap { |record| block&.call(record) }
242
+ end
243
+
244
+ alias build new
245
+
246
+ def create(attrs = {}, &)
247
+ new(attrs, &).tap(&:save)
248
+ end
249
+
250
+ def create!(attrs = {}, &)
251
+ new(attrs, &).tap(&:save!)
252
+ end
253
+
254
+ def find_or_initialize_by(attrs, &)
255
+ klass.find_or_initialize_by(scope_attributes.merge(attrs.transform_keys(&:to_s)), &)
256
+ end
257
+
258
+ def find_or_create_by(attrs, &)
259
+ klass.find_or_create_by(scope_attributes.merge(attrs.transform_keys(&:to_s)), &)
260
+ end
261
+
262
+ def find_or_create_by!(attrs, &)
263
+ klass.find_or_create_by!(scope_attributes.merge(attrs.transform_keys(&:to_s)), &)
264
+ end
265
+
266
+ def destroy_by(attrs)
267
+ where(attrs).destroy_all
268
+ end
269
+
270
+ def delete_by(attrs)
271
+ where(attrs).delete_all
272
+ end
167
273
 
168
274
  # Loads the matches and destroys each one, with its callbacks. Returns
169
275
  # the records.
@@ -254,6 +360,43 @@ module Ndb
254
360
  count ? found : found.last
255
361
  end
256
362
 
363
+ def first!
364
+ first || raise(not_found)
365
+ end
366
+
367
+ def last!
368
+ last || raise(not_found)
369
+ end
370
+
371
+ # A record (or count of them) in no given order: the order of the
372
+ # relation, else the order of the daemon.
373
+ def take(count = nil)
374
+ return count ? records.first(count) : records.first if loaded?
375
+
376
+ found = limit(count || 1).to_a
377
+
378
+ count ? found : found.first
379
+ end
380
+
381
+ def take!
382
+ take || raise(not_found)
383
+ end
384
+
385
+ # The one record of the relation: Ndb::NotFound when none,
386
+ # Ndb::SoleRecordExceeded when more than one.
387
+ def sole
388
+ found = limit(2).to_a
389
+
390
+ raise not_found if found.empty?
391
+ raise SoleRecordExceeded, "Wanted only one #{klass.name}" if found.size > 1
392
+
393
+ found.first
394
+ end
395
+
396
+ def find_sole_by(attrs)
397
+ where(attrs).sole
398
+ end
399
+
257
400
  # The relation with its order turned around (asc and desc swap). With no
258
401
  # order, it is the primary key in descending order.
259
402
  def reverse_order
@@ -289,7 +432,18 @@ module Ndb
289
432
  return where(conditions).exists? if conditions.is_a?(Hash)
290
433
  return where(klass.primary_key => conditions).exists? unless conditions == :none
291
434
 
292
- fetch(to_query.slice("query").merge("limit" => 1, "fields" => [klass.primary_key])).rows.any?
435
+ limit = [window["limit"], 1].compact.min
436
+
437
+ return false if limit.zero?
438
+
439
+ fetch(to_query.except("lookup").merge("limit" => limit, "fields" => [klass.primary_key])).rows.any?
440
+ end
441
+
442
+ # The primary keys of the relation, in its order (one request).
443
+ def ids
444
+ return records.map { |record| record.public_send(klass.primary_key) } if loaded?
445
+
446
+ fetch(to_query.except("lookup").merge("fields" => [klass.primary_key])).rows.map { |row| row[klass.primary_key] }
293
447
  end
294
448
 
295
449
  def pluck(*fields)
@@ -298,15 +452,23 @@ module Ndb
298
452
  names = fields.map(&:to_s)
299
453
  rows = fetch(to_query.merge("fields" => names)).rows
300
454
 
301
- rows.map do |row|
455
+ plucked = rows.map do |row|
302
456
  values = names.map { |name| klass.attribute_types[name].cast(row.dig(*name.split("."))) }
303
457
 
304
458
  values.size == 1 ? values.first : values
305
459
  end
460
+
461
+ values[:distinct] ? plucked.uniq : plucked
462
+ end
463
+
464
+ # pluck of the first row: a value, an Array of values, or nil.
465
+ def pick(*fields)
466
+ limit(1).pluck(*fields).first
306
467
  end
307
468
 
308
469
  def count
309
470
  return calculate(:count) unless values[:group].empty? && values[:unwind].nil?
471
+ return ids.size if narrowed?
310
472
 
311
473
  fetch(to_query.slice("query").merge("count" => true, "limit" => 1, "fields" => [klass.primary_key])).total
312
474
  end
@@ -382,9 +544,23 @@ module Ndb
382
544
  private
383
545
 
384
546
  def fetch(body)
547
+ return NONE if values[:none]
548
+
385
549
  sealed_or_plain { klass.ndb_find(body) }
386
550
  end
387
551
 
552
+ def not_found
553
+ NotFound.new("Couldn't find #{klass.name}", code: "not_found")
554
+ end
555
+
556
+ # The fields of the equality clauses of the where (status: "x"), for
557
+ # new and create. Operators ($in, $gte...) are not values.
558
+ def scope_attributes
559
+ values[:where].each_with_object({}) do |clause, out|
560
+ clause.each { |key, value| out[key] = value unless key.start_with?("$") || value.is_a?(Hash) || value.is_a?(Array) }
561
+ end
562
+ end
563
+
388
564
  def sealed_or_plain(&)
389
565
  values[:keep_encrypted] ? Rails.client.keep_encrypted(&) : yield
390
566
  end
@@ -439,6 +615,37 @@ module Ndb
439
615
  values[:limit] || values[:offset] || values[:page]
440
616
  end
441
617
 
618
+ # A window or a cursor: the relation is fewer rows than its where.
619
+ def narrowed?
620
+ windowed? || values[:after]
621
+ end
622
+
623
+ # The filter of update and delete_all: the where, and the ids of the
624
+ # rows when the relation is narrowed (the daemon writes every match of
625
+ # a filter). nil when a narrowed relation has no row.
626
+ def write_where
627
+ return nil if values[:none]
628
+ return Conditions.combine(values[:where]) unless narrowed?
629
+
630
+ found = ids
631
+
632
+ return nil if found.empty?
633
+
634
+ Conditions.combine(values[:where] + [{ klass.primary_key => { "$in" => found } }])
635
+ end
636
+
637
+ ORDER_PART = /\A([\w.]+)(?:\s+(asc|desc))?\z/i
638
+
639
+ def parse_order(text)
640
+ text.split(",").to_h do |part|
641
+ match = ORDER_PART.match(part.strip)
642
+
643
+ raise ArgumentError, "order takes \"field\" or \"field asc|desc\", got #{text.inspect}" unless match
644
+
645
+ [match[1], direction(match[2])]
646
+ end
647
+ end
648
+
442
649
  def direction(value)
443
650
  %w[desc -1].include?(value.to_s.downcase) ? -1 : 1
444
651
  end
@@ -499,7 +706,7 @@ module Ndb
499
706
 
500
707
  def calculate(op, field = nil)
501
708
  key = op.to_s
502
- rows = sealed_or_plain { klass.ndb_aggregate(aggregate_body(op, field)) }.rows
709
+ rows = values[:none] ? [] : sealed_or_plain { klass.ndb_aggregate(aggregate_body(op, field)) }.rows
503
710
 
504
711
  return rows.to_h { |row| [group_key(row["_id"]), row[key]] } unless values[:group].empty?
505
712
 
@@ -53,19 +53,25 @@ module Ndb
53
53
  tx.lock_records(Array(lock), ttl: ttl, wait: wait) if lock
54
54
  result = yield
55
55
  tx.commit!
56
-
57
- result
58
56
  rescue Rollback
59
57
  tx.abort!
58
+ RecordTransaction.current = nil
59
+ tx.run_commit_callbacks(:rollback)
60
60
 
61
- nil
61
+ return nil
62
62
  rescue Exception # rubocop:disable Lint/RescueException
63
63
  tx.abort!
64
+ RecordTransaction.current = nil
65
+ tx.run_commit_callbacks(:rollback)
64
66
 
65
67
  raise
66
68
  ensure
67
69
  RecordTransaction.current = nil
68
70
  end
71
+
72
+ tx.run_commit_callbacks(:commit)
73
+
74
+ result
69
75
  end
70
76
  end
71
77
 
@@ -99,6 +105,7 @@ module Ndb
99
105
  @tokens = []
100
106
  @guarded = {}
101
107
  @locked = {}
108
+ @commits = []
102
109
  end
103
110
 
104
111
  def collection = @klass.collection_name
@@ -152,17 +159,21 @@ module Ndb
152
159
  add({ op: "delete", id: record.id, query: guard(record) }.compact, record)
153
160
  end
154
161
 
162
+ # A save or destroy of the block: its after_commit callbacks run after
163
+ # the commit, its after_rollback callbacks after an abort.
164
+ def on_commit(record, action)
165
+ @commits << [record, action]
166
+ end
167
+
155
168
  def commit!
156
169
  if @ops.empty?
157
170
  release
171
+ else
172
+ results = Rails.client.tx(collection, @ops.map(&:first), locks: @tokens, unlock: true)["results"]
158
173
 
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"]
174
+ @ops.zip(results).each do |(_, record), result|
175
+ record.send(:written_in_transaction!, result["_v"]) if result["_v"]
176
+ end
166
177
  end
167
178
  ensure
168
179
  finish
@@ -173,6 +184,11 @@ module Ndb
173
184
  finish
174
185
  end
175
186
 
187
+ # Runs after the block ends, so a write in a callback is a new write.
188
+ def run_commit_callbacks(kind)
189
+ @commits.each { |record, action| record.send(:run_commit_callbacks, kind, action) }
190
+ end
191
+
176
192
  private
177
193
 
178
194
  def add(op, record)
@@ -2,6 +2,6 @@
2
2
 
3
3
  module Ndb
4
4
  module Rails
5
- VERSION = "1.23.3"
5
+ VERSION = "1.25.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/validations"
13
13
  require "ndb/rails/blob"
14
+ require "ndb/rails/commit_callbacks"
15
+ require "ndb/rails/record_writes"
14
16
  require "ndb/rails/persistence"
15
17
  require "ndb/rails/locking"
16
18
  require "ndb/rails/transactions"
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.23.3
4
+ version: 1.25.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.23.3
46
+ version: 1.25.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.23.3
56
+ version: 1.25.0
57
57
  - - "<"
58
58
  - !ruby/object:Gem::Version
59
59
  version: '2'
@@ -66,10 +66,12 @@ extra_rdoc_files: []
66
66
  files:
67
67
  - LICENSE
68
68
  - README.md
69
+ - lib/action_cable/subscription_adapter/ndb.rb
69
70
  - lib/ndb-rails.rb
70
71
  - lib/ndb/rails.rb
71
72
  - lib/ndb/rails/associations.rb
72
73
  - lib/ndb/rails/blob.rb
74
+ - lib/ndb/rails/commit_callbacks.rb
73
75
  - lib/ndb/rails/configuration.rb
74
76
  - lib/ndb/rails/database_cleaner.rb
75
77
  - lib/ndb/rails/dynamic_finders.rb
@@ -80,6 +82,7 @@ files:
80
82
  - lib/ndb/rails/persistence.rb
81
83
  - lib/ndb/rails/railtie.rb
82
84
  - lib/ndb/rails/record.rb
85
+ - lib/ndb/rails/record_writes.rb
83
86
  - lib/ndb/rails/relation.rb
84
87
  - lib/ndb/rails/rspec.rb
85
88
  - lib/ndb/rails/testing.rb