ndb-rails 1.24.0 → 1.25.1

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: 49cf1194840830bc05ef3ab2cb78db49f6c13056b116dbfd168c17867d942132
4
- data.tar.gz: 0753e2a3968e06ad58584f89242fb2766840b2a84333e3006bf884f373a8d0d3
3
+ metadata.gz: f12c45cfd6db4e1cc280b045d4677761c069d21b676c27efc57876f60033da46
4
+ data.tar.gz: cbffdc5bc06920462c2fdad7cc23124544c0ac3345d3386dd23478cee95c24b1
5
5
  SHA512:
6
- metadata.gz: 0d05b4c532f3653def1630087bce411e99126dbc0fe62085b833021ebcd113d7e1767630132920024960fc31761c65e02d08f8f5d2630ba61b3fafc07f5b9cef
7
- data.tar.gz: f488d217b85c8860804af096ef8b445aa165fe28a35b70b2fde597af1713cb5de4577e566587baddaa592e35ad49f9ac46a89ef1deda2ac11f1938ca45c6fea3
6
+ metadata.gz: 83e340f3b33b1513223f745812ac2ef1fbbc9cb745a7a0bd6bd36978c222164c315ed4fff20dbea4ec8444033754b05541e70f0a3bc11fadb804dc1880330048
7
+ data.tar.gz: a59d2c6213578b48068cf6951b4e8f3412f4d7ec5ac909b7f63ad23580b01a0ee26add121fc2625c8b02e9b2f31978190e05f4fd97be63615cb8b8f3e7599100
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
@@ -51,9 +51,9 @@ module Ndb
51
51
  def order(*args)
52
52
  sort = args.each_with_object(values[:order].dup) do |arg, out|
53
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
54
+ when Hash then arg.each { |f, dir| out[field_name(f)] = direction(dir) }
55
+ when String then parse_order(arg).each { |f, dir| out[field_name(f)] = dir }
56
+ else out[field_name(arg)] = 1
57
57
  end
58
58
  end
59
59
 
@@ -104,7 +104,7 @@ module Ndb
104
104
  end
105
105
 
106
106
  def group(*fields)
107
- with(group: fields.flatten.map(&:to_s))
107
+ with(group: fields.flatten.map { |field| field_name(field) })
108
108
  end
109
109
 
110
110
  # Makes the aggregates of the relation (count, sum, average, minimum,
@@ -159,7 +159,7 @@ module Ndb
159
159
 
160
160
  raise ArgumentError, "select needs at least one field" if fields.empty?
161
161
 
162
- with(select: fields.map(&:to_s))
162
+ with(select: fields.map { |field| field_name(field) })
163
163
  end
164
164
 
165
165
  # An empty relation: it sends no request. to_a is [], count is 0, and
@@ -449,7 +449,7 @@ module Ndb
449
449
  def pluck(*fields)
450
450
  raise ArgumentError, "pluck needs at least one field" if fields.empty?
451
451
 
452
- names = fields.map(&:to_s)
452
+ names = fields.map { |field| field_name(field) }
453
453
  rows = fetch(to_query.merge("fields" => names)).rows
454
454
 
455
455
  plucked = rows.map do |row|
@@ -600,6 +600,14 @@ module Ndb
600
600
  attrs.transform_keys { |key| key.to_s == "id" ? klass.primary_key : key }
601
601
  end
602
602
 
603
+ # One field name of pluck, pick, select, order or group: id is _id here too, unless the
604
+ # model has its own id attribute.
605
+ def field_name(field)
606
+ name = field.to_s
607
+
608
+ name == "id" && !klass.attribute_names.include?("id") ? klass.primary_key : name
609
+ end
610
+
603
611
  def add_clause(clause)
604
612
  with(where: values[:where] + [clause])
605
613
  end
@@ -2,6 +2,6 @@
2
2
 
3
3
  module Ndb
4
4
  module Rails
5
- VERSION = "1.24.0"
5
+ VERSION = "1.25.1"
6
6
  end
7
7
  end
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.24.0
4
+ version: 1.25.1
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.24.0
46
+ version: 1.25.1
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.24.0
56
+ version: 1.25.1
57
57
  - - "<"
58
58
  - !ruby/object:Gem::Version
59
59
  version: '2'
@@ -66,6 +66,7 @@ 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