ndb-rails 1.14.0 → 1.16.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.
@@ -0,0 +1,221 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Ndb
4
+ module Streams
5
+ # The class methods that `include Ndb::Streams` adds.
6
+ module ClassMethods
7
+ ENSURE_LOCK = Mutex.new
8
+
9
+ # A subclass starts with the config of its parent.
10
+ def inherited(subclass)
11
+ super
12
+
13
+ subclass.instance_variable_set(:@ndb_stream_name, @ndb_stream_name)
14
+ subclass.instance_variable_set(:@ndb_stream_config, @ndb_stream_config)
15
+ subclass.instance_variable_set(:@ndb_around_performs, @ndb_around_performs)
16
+
17
+ Streams.register(subclass)
18
+ end
19
+
20
+ # Sets the stream of the class and its options:
21
+ #
22
+ # stream :orders, group: :billing, concurrency: 2, max_deliveries: 5
23
+ # stream :orders, group: :billing, retry: [15, 1.minute, 10.minutes], max_age: 15.days
24
+ # stream OrderEvent, group: :billing # the stream of another class
25
+ #
26
+ # See Options::DEFAULTS for the options.
27
+ def stream(name = nil, **options)
28
+ config = Options.normalize(options)
29
+
30
+ @ndb_stream_name = name.respond_to?(:stream_name) ? name.stream_name : name.to_s unless name.nil?
31
+ @ndb_stream_config = (@ndb_stream_config || {}).merge(config).freeze
32
+
33
+ nil
34
+ end
35
+
36
+ # Runs the block around each `perform`, on the instance. The block
37
+ # calls `block.call` to go on.
38
+ #
39
+ # around_perform { |event, block| Tenant.with(event[:tenant]) { block.call } }
40
+ def around_perform(&hook)
41
+ raise ArgumentError, "around_perform needs a block" unless hook
42
+
43
+ @ndb_around_performs = [*@ndb_around_performs, hook].freeze
44
+
45
+ nil
46
+ end
47
+
48
+ def around_performs
49
+ @ndb_around_performs || []
50
+ end
51
+
52
+ # The name from `stream`, or from the class name (OrderEvent is
53
+ # "order_events"). The name from the class is kept after the first
54
+ # call.
55
+ def stream_name
56
+ @ndb_stream_name || (@ndb_default_stream_name ||= Options.default_name(self))
57
+ end
58
+
59
+ # Every option with its value. dead_letter is "<stream>_dead" when
60
+ # max_deliveries or max_age is set.
61
+ def stream_options
62
+ options = Options::DEFAULTS.merge(@ndb_stream_config || {})
63
+ buries = options[:max_deliveries] || options[:max_age]
64
+
65
+ options[:dead_letter] = "#{stream_name}_dead" if options[:dead_letter].nil? && buries
66
+ options[:dead_letter] = nil if options[:dead_letter] == false
67
+
68
+ options
69
+ end
70
+
71
+ # True for a class with a `perform` instance method.
72
+ def stream_consumer?
73
+ method_defined?(:perform) || private_method_defined?(:perform)
74
+ end
75
+
76
+ # The class in a message.
77
+ def stream_label
78
+ name || "a class of the stream #{@ndb_stream_name.inspect}"
79
+ end
80
+
81
+ # The low-level stream (Ndb::Stream) of the class.
82
+ def ndb_stream
83
+ Streams.client.stream("#{Streams.prefix}#{stream_name}")
84
+ end
85
+
86
+ # The low-level group (Ndb::Group) of a consumer class.
87
+ def stream_group
88
+ group = stream_options[:group]
89
+
90
+ raise MissingGroup, "#{stream_label} has no group: add `stream :#{stream_name}, group: :a_name`" if group.nil?
91
+
92
+ ndb_stream.group(group)
93
+ end
94
+
95
+ # Adds one entry (a Hash) and returns its ID, or many entries (an
96
+ # Array of Hash) and returns their IDs. A JSON string is parsed first.
97
+ # In an ActiveRecord transaction the append waits for the commit and
98
+ # returns nil; a rollback drops it.
99
+ def append(payload)
100
+ docs, many = Options.payload(payload)
101
+
102
+ return [] if docs.empty?
103
+
104
+ result = nil
105
+
106
+ Streams.after_commit { result = write_entries(docs, many) }
107
+
108
+ result
109
+ end
110
+
111
+ alias enqueue append
112
+ alias perform_async append
113
+
114
+ # Runs perform on one payload now, in this thread, with no request:
115
+ # nothing is written to ndb and nothing is acked. It takes the path of
116
+ # a delivery (the Rails reloader, around_perform, discard_on) and
117
+ # returns the value of perform (nil when discard_on took the error).
118
+ # For a test, or one entry by hand in a console.
119
+ #
120
+ # The payload is a Hash, a JSON string or the fields as keywords. The
121
+ # names that start with _ are not payload fields (they are reserved in
122
+ # a stream): _id is the entry ID of the event, _deliveries its count.
123
+ #
124
+ # PostCallJob.perform_now(call_id: 42)
125
+ # PostCallJob.perform_now({ "call_id" => 42 }, _id: "1731163600000-0", _deliveries: 3)
126
+ # PostCallJob.perform_now('{"call_id":42}')
127
+ def perform_now(payload = nil, **fields)
128
+ raise ArgumentError, "#{stream_label} has no perform: perform_now runs a consumer" unless stream_consumer?
129
+
130
+ meta = fields.select { |key, _| key.to_s.start_with?("_") }
131
+ fields = fields.reject { |key, _| meta.key?(key) }
132
+ docs, many = Options.payload(payload.nil? ? fields : payload)
133
+
134
+ raise ArgumentError, "perform_now takes one entry, not an Array" if many
135
+
136
+ unknown = meta.keys.map(&:to_s) - %w[_id _deliveries]
137
+
138
+ raise ArgumentError, "perform_now: unknown option #{unknown.first}" if unknown.any?
139
+
140
+ id = meta[:_id] || "#{Process.clock_gettime(Process::CLOCK_REALTIME, :millisecond)}-0"
141
+ payload = JSON.parse(JSON.generate(docs.first)).reject { |key, _| key.start_with?("_") }
142
+ event = Event.new(id: id.to_s, payload: payload, deliveries: meta.fetch(:_deliveries, 1))
143
+
144
+ Perform.now(self, event)
145
+ end
146
+
147
+ # The newest entry, or nil. With n: the n newest entries, oldest first.
148
+ def last(count = nil)
149
+ events = read_events { |stream| stream.rev_range(count: count || 1) }
150
+
151
+ count ? events.reverse : events.first
152
+ end
153
+
154
+ # The entry with this ID, or nil.
155
+ def find(id)
156
+ read_events { |stream| stream.range(id.to_s, id.to_s, count: 1) }.first
157
+ end
158
+
159
+ # The entries from `from` to `to`, both included, oldest first. Each
160
+ # one is an ID or a Time. The defaults are the two ends of the stream.
161
+ def range(from = "-", to = "+", count: nil)
162
+ start = Options.range_id(from, :from)
163
+ stop = Options.range_id(to, :to)
164
+
165
+ read_events { |stream| stream.range(start, stop, count: count) }
166
+ end
167
+
168
+ # How many entries the stream has.
169
+ def count
170
+ ndb_stream.info.fetch("length")
171
+ rescue Ndb::UnknownCollection
172
+ 0
173
+ end
174
+
175
+ # Makes the stream with its retention, one time for each client. A
176
+ # stream without `retain` is made by the first append.
177
+ def ensure_stream!
178
+ retain = stream_options[:retain]
179
+
180
+ return if retain.nil?
181
+
182
+ stream = ndb_stream
183
+ key = [stream.client, stream.name, retain]
184
+
185
+ return if @ndb_stream_ensured == key
186
+
187
+ ENSURE_LOCK.synchronize do
188
+ stream.create(retention: retain)
189
+
190
+ @ndb_stream_ensured = key
191
+ end
192
+ end
193
+
194
+ private
195
+
196
+ def read_events
197
+ yield(ndb_stream).map { |entry| Event.from_entry(entry) }
198
+ rescue Ndb::UnknownCollection
199
+ []
200
+ end
201
+
202
+ def write_entries(docs, many)
203
+ ensure_stream!
204
+
205
+ stream = ndb_stream
206
+ max_len = stream_options[:max_len]
207
+ trim = max_len ? { max_len: max_len } : nil
208
+
209
+ Ndb::Testing.touch(stream.name) if Ndb.const_defined?(:Testing)
210
+
211
+ ids = Streams.instrument("append.ndb_streams", stream: stream_name, class: self, count: docs.size) do
212
+ many ? stream.append_many(docs, trim: trim) : [stream.append(docs.first, trim: trim)]
213
+ end
214
+
215
+ Perform.inline(stream_name, ids, docs) if Streams.inline?
216
+
217
+ many ? ids : ids.first
218
+ end
219
+ end
220
+ end
221
+ end
@@ -0,0 +1,14 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Ndb
4
+ module Streams
5
+ # A class with a wrong stream config.
6
+ class ConfigurationError < ArgumentError; end
7
+
8
+ # A class has `perform` but its `stream` has no `group:`.
9
+ class MissingGroup < ConfigurationError; end
10
+
11
+ # Two consumer classes use the same group on one stream.
12
+ class DuplicateGroup < ConfigurationError; end
13
+ end
14
+ end
@@ -0,0 +1,59 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Ndb
4
+ module Streams
5
+ # One entry of a stream, as `perform` and the read methods give it.
6
+ #
7
+ # event[:order_id] # one field, by symbol or string
8
+ # event.to_h # the payload, without "_id" and "_ts"
9
+ # event.id # "<ms>-<seq>"
10
+ # event.time # the Time of the ID
11
+ # event.deliveries # 1 on the first delivery
12
+ class Event
13
+ attr_reader :id
14
+
15
+ # How many times the group delivered this entry: 1 on the first
16
+ # delivery. nil for an entry that came from a read without a group
17
+ # (last, find, range).
18
+ attr_reader :deliveries
19
+
20
+ def self.from_entry(entry, deliveries: nil)
21
+ new(id: entry.id, payload: entry.doc || {}, deliveries: deliveries)
22
+ end
23
+
24
+ def initialize(id:, payload:, deliveries: nil)
25
+ @id = id
26
+ @payload = payload
27
+ @deliveries = deliveries
28
+ end
29
+
30
+ def [](key)
31
+ @payload[key.to_s]
32
+ end
33
+
34
+ def key?(key)
35
+ @payload.key?(key.to_s)
36
+ end
37
+
38
+ # A copy of the payload. With ActiveSupport, symbols and strings read
39
+ # the same key.
40
+ def to_h
41
+ return @payload.with_indifferent_access if @payload.respond_to?(:with_indifferent_access)
42
+
43
+ @payload.dup
44
+ end
45
+
46
+ def time
47
+ Ndb::Stream.id_time(@id)
48
+ end
49
+
50
+ def ==(other)
51
+ other.is_a?(Event) && other.id == @id && other.to_h == to_h
52
+ end
53
+
54
+ def inspect
55
+ "#<#{self.class.name} id=#{@id.inspect} #{@payload.inspect}>"
56
+ end
57
+ end
58
+ end
59
+ end
@@ -0,0 +1,190 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Ndb
4
+ module Streams
5
+ # The options of `stream`: their defaults and their checks.
6
+ module Options
7
+ DEFAULTS = {
8
+ group: nil,
9
+ concurrency: 1,
10
+ max_deliveries: nil,
11
+ dead_letter: nil,
12
+ claim_idle: 60.0,
13
+ retry: nil,
14
+ max_age: nil,
15
+ start: :new,
16
+ discard_on: [].freeze,
17
+ max_len: nil,
18
+ retain: nil
19
+ }.freeze
20
+
21
+ STARTS = %i[new all].freeze
22
+
23
+ # The highest sequence of an ID: the end of one millisecond.
24
+ MAX_SEQ = (2**64) - 1
25
+
26
+ class << self
27
+ # The options as the gem keeps them. An unknown key or a bad value
28
+ # raises ArgumentError.
29
+ def normalize(options)
30
+ unknown = options.keys - DEFAULTS.keys
31
+
32
+ unless unknown.empty?
33
+ raise ArgumentError, "unknown stream option: #{unknown.map(&:inspect).join(', ')} (known: #{DEFAULTS.keys.join(', ')})"
34
+ end
35
+
36
+ options.to_h { |key, value| [key, send(key, value)] }
37
+ end
38
+
39
+ # "order_events" for OrderEvent, "billing_order_events" for
40
+ # Billing::OrderEvent, "categories" for Category. The words come from
41
+ # the ActiveSupport inflections (the gem requires them), so an
42
+ # inflection of the app (config/initializers/inflections.rb) applies.
43
+ def default_name(klass)
44
+ name = klass.name
45
+
46
+ raise ConfigurationError, "a class without a name needs `stream :name`" if name.nil?
47
+
48
+ name.gsub("::", "_").underscore.pluralize
49
+ end
50
+
51
+ # Hash: one entry. Array of Hash: many entries. String: JSON of one
52
+ # of the two. Returns [docs, many].
53
+ def payload(value)
54
+ case value
55
+ when Hash
56
+ [[value], false]
57
+ when Array
58
+ bad = value.find { |doc| !doc.is_a?(Hash) }
59
+
60
+ raise ArgumentError, "each entry of a stream is a Hash, not #{bad.class}" if bad
61
+
62
+ [value, true]
63
+ when String
64
+ payload(parse(value))
65
+ else
66
+ raise ArgumentError, "a stream payload is a Hash, an Array of Hash or a JSON string, not #{value.class}"
67
+ end
68
+ end
69
+
70
+ # A Time or an ID as an ID of a range. edge is :from or :to.
71
+ def range_id(value, edge)
72
+ return value.to_s unless value.respond_to?(:to_time) && !value.is_a?(String)
73
+
74
+ time = value.to_time
75
+ ms = (time.to_i * 1000) + (time.nsec / 1_000_000)
76
+
77
+ edge == :from ? "#{ms}-0" : "#{ms}-#{MAX_SEQ}"
78
+ end
79
+
80
+ private
81
+
82
+ def parse(json)
83
+ parsed = JSON.parse(json)
84
+
85
+ return parsed if parsed.is_a?(Hash) || parsed.is_a?(Array)
86
+
87
+ raise ArgumentError, "the JSON of a stream payload is an object or an array"
88
+ rescue JSON::ParserError => e
89
+ raise ArgumentError, "the stream payload is not JSON: #{e.message}"
90
+ end
91
+
92
+ def group(value)
93
+ value&.to_s
94
+ end
95
+
96
+ def concurrency(value)
97
+ positive_integer(:concurrency, value)
98
+ end
99
+
100
+ def max_deliveries(value)
101
+ value.nil? ? nil : positive_integer(:max_deliveries, value)
102
+ end
103
+
104
+ def max_len(value)
105
+ value.nil? ? nil : positive_integer(:max_len, value)
106
+ end
107
+
108
+ # false: no dead letter stream.
109
+ def dead_letter(value)
110
+ return value if value.nil? || value == false
111
+
112
+ value.to_s
113
+ end
114
+
115
+ # Seconds: a number or an ActiveSupport duration.
116
+ def claim_idle(value)
117
+ return nil if value.nil?
118
+
119
+ raise ArgumentError, "claim_idle is a number of seconds or a duration, not #{value.inspect}" unless value.respond_to?(:to_f) && !value.is_a?(String)
120
+
121
+ value.to_f
122
+ end
123
+
124
+ # The retry schedule: an Array of waits (seconds or durations; the
125
+ # last one repeats) is an Ndb::Stream::Tiers; a callable
126
+ # ->(deliveries) { seconds } stays as it is. nil: a failed entry
127
+ # waits claim_idle.
128
+ def retry(value)
129
+ return nil if value.nil?
130
+ return value if value.respond_to?(:call)
131
+
132
+ unless value.is_a?(Array)
133
+ raise ArgumentError, "retry is an Array of waits or a callable ->(deliveries) { seconds }, not #{value.inspect}"
134
+ end
135
+
136
+ Ndb::Stream.tiers(*value.map { |wait| wait.is_a?(Hash) ? wait : seconds(:retry, wait) })
137
+ end
138
+
139
+ # Seconds: a number or an ActiveSupport duration, greater than 0.
140
+ def max_age(value)
141
+ return nil if value.nil?
142
+
143
+ age = seconds(:max_age, value)
144
+
145
+ raise ArgumentError, "max_age is greater than 0, not #{value.inspect}" unless age.positive?
146
+
147
+ age
148
+ end
149
+
150
+ def seconds(name, value)
151
+ return value.to_f if value.respond_to?(:to_f) && !value.is_a?(String)
152
+
153
+ raise ArgumentError, "#{name} takes numbers of seconds or durations, not #{value.inspect}"
154
+ end
155
+
156
+ def start(value)
157
+ value = value.to_sym if value.respond_to?(:to_sym)
158
+
159
+ raise ArgumentError, "start is :new or :all, not #{value.inspect}" unless STARTS.include?(value)
160
+
161
+ value
162
+ end
163
+
164
+ def discard_on(value)
165
+ classes = Array(value)
166
+ bad = classes.find { |klass| !(klass.is_a?(Class) && klass <= Exception) }
167
+
168
+ raise ArgumentError, "discard_on takes exception classes, not #{bad.inspect}" if bad
169
+
170
+ classes.freeze
171
+ end
172
+
173
+ # The retention of the daemon: "30d" as it is, a number or a
174
+ # duration as seconds.
175
+ def retain(value)
176
+ return nil if value.nil?
177
+ return value if value.is_a?(String)
178
+
179
+ "#{positive_integer(:retain, value.to_i)}s"
180
+ end
181
+
182
+ def positive_integer(name, value)
183
+ return value if value.is_a?(Integer) && value.positive?
184
+
185
+ raise ArgumentError, "#{name} is an integer greater than 0, not #{value.inspect}"
186
+ end
187
+ end
188
+ end
189
+ end
190
+ end
@@ -0,0 +1,84 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Ndb
4
+ module Streams
5
+ # Runs `perform` of a consumer class on one event.
6
+ module Perform
7
+ class << self
8
+ # A new instance for each event, in the Rails reloader when there
9
+ # is an app (so a changed class is loaded again in development),
10
+ # with the around_perform blocks around it. The options come from
11
+ # the class of now (Streams.current). An error of `discard_on` is
12
+ # logged and the call returns :discarded, so the entry is acked.
13
+ # Any other error goes to the caller.
14
+ def call(klass, event)
15
+ run(klass, event).first
16
+ end
17
+
18
+ # perform_now: the same path as a delivery, and the value that
19
+ # perform returns (nil when discarded).
20
+ def now(klass, event)
21
+ run(klass, event).last
22
+ end
23
+
24
+ # Inline mode: gives the new entries to each consumer of the stream.
25
+ # The first call loads app/streams, so a consumer is there also
26
+ # before the boot thread loads it.
27
+ def inline(stream_name, ids, docs)
28
+ Streams.load_classes_once!
29
+
30
+ consumers = Streams.consumers_of(stream_name)
31
+
32
+ return if consumers.empty?
33
+
34
+ ids.zip(docs).each do |id, doc|
35
+ consumers.each do |klass|
36
+ event = Event.new(id: id, payload: JSON.parse(JSON.generate(doc)), deliveries: 1)
37
+
38
+ call(klass, event)
39
+ end
40
+ end
41
+ end
42
+
43
+ private
44
+
45
+ # Returns [:done, value of perform] or [:discarded, nil].
46
+ def run(klass, event)
47
+ wrap do
48
+ klass = Streams.current(klass)
49
+ options = klass.stream_options
50
+ payload = { stream: klass.stream_name, group: options[:group], class: klass, event: event }
51
+
52
+ begin
53
+ value = Streams.instrument("perform.ndb_streams", payload) { chain(klass, event).call }
54
+
55
+ [:done, value]
56
+ rescue *options[:discard_on] => e
57
+ Streams.logger.warn("ndb streams: #{klass.stream_label} discarded #{event.id}: #{e.class}: #{e.message}")
58
+
59
+ [:discarded, nil]
60
+ end
61
+ end
62
+ end
63
+
64
+ def wrap(&block)
65
+ app = Streams.rails_app
66
+
67
+ return app.reloader.wrap(&block) if app.respond_to?(:reloader)
68
+ return app.executor.wrap(&block) if app.respond_to?(:executor)
69
+
70
+ block.call
71
+ end
72
+
73
+ def chain(klass, event)
74
+ instance = klass.new
75
+ perform = -> { instance.send(:perform, event) }
76
+
77
+ klass.around_performs.reverse.inject(perform) do |inner, hook|
78
+ -> { instance.instance_exec(event, inner, &hook) }
79
+ end
80
+ end
81
+ end
82
+ end
83
+ end
84
+ end
@@ -0,0 +1,56 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Ndb
4
+ module Streams
5
+ # The logic of `plugin :ndb`, so that it can be tested without Puma.
6
+ # lib/puma/plugin/ndb.rb connects it to Puma.
7
+ module PumaPlugin
8
+ ON = %w[1 true yes on].freeze
9
+ OFF = %w[0 false no off].freeze
10
+
11
+ # Seconds the consumers get to end their current entries at a stop.
12
+ STOP_TIMEOUT = 30
13
+
14
+ class << self
15
+ # NDB_STREAMS_IN_PUMA turns the plugin on or off. Without it, the
16
+ # plugin runs only in development.
17
+ def enabled?(env = ENV)
18
+ value = env["NDB_STREAMS_IN_PUMA"].to_s.strip.downcase
19
+
20
+ return environment(env) == "development" if value.empty?
21
+ return true if ON.include?(value)
22
+ return false if OFF.include?(value)
23
+
24
+ raise ArgumentError, "NDB_STREAMS_IN_PUMA must be true or false, not #{env['NDB_STREAMS_IN_PUMA']}"
25
+ end
26
+
27
+ def environment(env = ENV)
28
+ %w[RAILS_ENV RACK_ENV APP_ENV].each do |key|
29
+ value = env[key].to_s.strip
30
+
31
+ return value unless value.empty?
32
+ end
33
+
34
+ "development"
35
+ end
36
+
37
+ # The options of Process.spawn: a new process group, so the signal
38
+ # of a Ctrl-C in the terminal does not also go to the child. The
39
+ # child gets only the TERM of the plugin (one signal: a clean stop).
40
+ def spawn_options
41
+ { pgroup: true }
42
+ end
43
+
44
+ # The binstub of the app when it has one, or the command of the gem
45
+ # with Bundler.
46
+ def command(root = Dir.pwd)
47
+ binstub = File.join(root, "bin", "ndb")
48
+
49
+ return [Gem.ruby, binstub, "streams"] if File.exist?(binstub)
50
+
51
+ %w[bundle exec ndb streams]
52
+ end
53
+ end
54
+ end
55
+ end
56
+ end