anway 0.2.0-x86_64-linux-gnu → 0.4.0-x86_64-linux-gnu

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: 435216428e491fe5a0320e60b049afee90a75d2ad61e31aedfc3dc0e4adec05f
4
- data.tar.gz: efd65b40da6043a2951b43eb3b29f001b3da0eb949ebd16ef15879a10e107a07
3
+ metadata.gz: 2dc92ff0ab7b743fa243aa78cdd186860e1a564be584d110a73ea0a8708293d4
4
+ data.tar.gz: 0ecd6eac6ffdfb8f445e6a3ceed7fe550f128f9bb7e0eca488625e6713827340
5
5
  SHA512:
6
- metadata.gz: e9f228b69dfddcaa7d1287ee17bc9558a8f6b12c2993b2f775240f16d2eef34313452852aeda65e52df1a0a9341e47692b14a3ea045d5c53236bdd9692a1049c
7
- data.tar.gz: 073fd564bcc42053954fb43503286ed63f2a6fd4520dd430c2f200e07236ec4e854ab00b6a6a8eebd8cd97bc684ec254f65afd0878981a3b888662fbaa57ed27
6
+ metadata.gz: 06b4dd95b906fcaa6cc5625213ac95356621f9cd5a2ae99d8e2d201aea3fadf0b70d8091036de21e4d446f2dadbf167ada2573906a3ceac675c9563ffc850daa
7
+ data.tar.gz: b68fa05cec43691113b31df2b398fa67c36cf3bec0f5c4641815379bca6737804a5667f14985b350cb54ec990ba8d512c0ae0e8a607dc118499d472f21e49e2d
data/README.md CHANGED
@@ -98,30 +98,98 @@ console:
98
98
  class WelcomeJob
99
99
  include Anway::Worker
100
100
 
101
- job_type 'email.send'
102
- job_options queue: 'mailers', retry: 5
101
+ anway_options event: 'email.welcome', retry: 5
102
+ anway_options topics: %w[user.created], queue: 'mailers'
103
103
 
104
- def perform(address)
104
+ def perform(user_id)
105
105
  # ...
106
106
  end
107
107
  end
108
108
 
109
- WelcomeJob.perform_async('a@b.com')
110
- WelcomeJob.perform_in(300, 'a@b.com')
111
- WelcomeJob.set(queue: 'low').perform_async('a@b.com')
109
+ WelcomeJob.perform_async(1)
110
+ WelcomeJob.perform_in(300, 1)
111
+ WelcomeJob.set(queue: 'low', unique_for: 60).perform_async(1)
112
112
  ```
113
113
 
114
- - `job_type` is optional. The default is the class name. Use a name when a worker in another language runs the job.
115
- - `job_options` accepts `queue`, `retry`, `reserve_for`, `backtrace`, and `custom`, such as `custom: { unique_for: 600 }`.
114
+ - `anway_options` declares the options of the class. You can call it more than once. An unknown key raises `ArgumentError`.
115
+ - `event` is the name of what the job handles. It goes to the server as the job type. The default is the class name. Use a name when a worker in another language runs the job.
116
+ - Two classes with the same event raise `ArgumentError`. A worker has one class for each event.
117
+ - A subclass inherits all options except `event` and `topics`.
118
+ - `set` changes the options for one push. It takes the push keys below.
116
119
  - Args must be JSON types with string hash keys. Symbols, times, and objects raise `ArgumentError`.
117
120
  - Delivery is at least once, so jobs must be idempotent.
118
121
 
119
- To send a job that a worker in any language runs:
122
+ ### Options
123
+
124
+ All Anway clients use the same keys. The gem translates them to the fields of the protocol.
125
+
126
+ | Key | Sent as | Note |
127
+ |---|---|---|
128
+ | `event` | `jobtype` | The default is the class name. Only in `anway_options`. |
129
+ | `queue` | `queue` | The default is `default`. |
130
+ | `retry` | `retry` | The server default is 25. `0` discards the job at the first failure. `-1` sends it to the Dead set at once. |
131
+ | `reserve_for` | `reserve_for` | Seconds. |
132
+ | `backtrace` | `backtrace` | Lines. The default for a class is 30. |
133
+ | `at` | `at` | A time to run later. Only for a push. |
134
+ | `unique_for` | `custom.unique_for` | Seconds. |
135
+ | `unique_until` | `custom.unique_until` | `success` or `start`. |
136
+ | `expires_in` | `custom.expires_in` | Seconds. |
137
+ | `expires_at` | `custom.expires_at` | A time. The gem sends it as RFC 3339. |
138
+ | `track` | `custom.track` | `true` sends `1`. |
139
+ | `on_dead` | `custom.on_dead` | `{ event:, queue: }`. When the job dies, the server pushes a job of this event. |
140
+ | `custom` | `custom` | The keys of your app. A key above wins over a key with the same name here. |
141
+ | `topics` | One `SUBSCRIBE` for each topic | Only in `anway_options`. See [Topics](#topics). |
142
+
143
+ When a class has more than one option set, the sets merge in call order:
144
+
145
+ - A single value, such as `queue` or `retry`: the last set that has it wins.
146
+ - `topics`: the topics of all sets add up, in order, with no duplicates.
147
+ - `custom`: the hashes merge, and a later key wins.
148
+
149
+ `set` merges with the options of the class by the same rules. `WelcomeJob.anway_options`, with no keys, returns the merged options.
150
+
151
+ To send a job that a worker in any language runs, give the event and the same push keys:
120
152
 
121
153
  ```ruby
122
- Anway.push('image.resize', [42], queue: 'media')
154
+ Anway.push('image.resize', [42], queue: 'media', expires_in: 600)
155
+ Anway::Job.new('email.welcome', [1], unique_for: 60, queue: 'low')
123
156
  ```
124
157
 
158
+ ## Topics
159
+
160
+ A topic sends one event to many queues. Each subscription of the topic gets one copy of the event, as a normal job in its own queue. Topics need server v0.3.0 or later.
161
+
162
+ ```ruby
163
+ class BroadcastMessage
164
+ include Anway::Worker
165
+
166
+ anway_options topics: %w[chat.message], queue: 'realtime'
167
+
168
+ def perform(message)
169
+ # ...
170
+ end
171
+ end
172
+
173
+ Anway.publish('chat.message', [{ 'room' => 'general', 'body' => 'hi' }], id: 'msg-42')
174
+ # => #<data Anway::Client::Published event="msg-42", jobs=3, duplicate=false>
175
+ ```
176
+
177
+ - Each topic in `topics` makes one subscription. The copies have the `event` of the class as their job type, and the `queue`, `retry`, and `reserve_for` of the class.
178
+ - The worker sends `SUBSCRIBE` for each subscription when it starts, before its first fetch. Without a queue list, it also fetches the subscription queues. With a list, it logs a warning for a subscription queue that is not in the list.
179
+ - With an `id`, a second publish of the same id within `unique_for` seconds (default one day) makes no job, and the reply has `duplicate: true`.
180
+ - The server adds `topic` and `event` to `custom` of each copy. Use `job.custom['event']` to make the handler idempotent.
181
+ - An event with no subscription goes to the Dead set, and the reply has `jobs: 0`.
182
+
183
+ The client has the same commands:
184
+
185
+ ```ruby
186
+ client.publish('chat.message', [{ 'body' => 'hi' }], id: 'msg-42', unique_for: 3600, custom: { 'source' => 'web' })
187
+ client.subscribe('chat.message', queue: 'realtime', event: 'BroadcastMessage', retry: 3, reserve_for: 60)
188
+ client.unsubscribe('chat.message', queue: 'realtime', event: 'BroadcastMessage')
189
+ ```
190
+
191
+ [docs/topics.md](docs/topics.md) explains the chat example with three apps, the options, the tests, and problems.
192
+
125
193
  ## Rails
126
194
 
127
195
  ```ruby
@@ -160,7 +228,7 @@ config.enable_reloading = ENV["ANWAY_WORKER"].blank?
160
228
 
161
229
  | Flag | Default | Purpose |
162
230
  |---|---|---|
163
- | `-q`, `--queues` | Queues of the job classes, and `default` | Queues in order, as `name` or `name:weight` |
231
+ | `-q`, `--queues` | Queues of the job classes and of their subscriptions, and `default` | Queues in order, as `name` or `name:weight` |
164
232
  | `-c`, `--concurrency` | `10` | Job threads |
165
233
  | `-t`, `--timeout` | `25` | Seconds for jobs to finish at a stop |
166
234
  | `-r`, `--require` | `config/environment.rb` | File that loads the jobs. Required outside Rails. |
@@ -225,20 +293,25 @@ Keep the database pool at the concurrency value or more. A job queue with no wor
225
293
  require 'anway/testing'
226
294
 
227
295
  Anway::Testing.fake!
228
- WelcomeJob.perform_async('a@b.com')
296
+ WelcomeJob.perform_async(1)
229
297
  Anway::Testing.jobs.size
230
298
  Anway::Testing.drain
231
299
 
300
+ Anway.publish('chat.message', [{ 'body' => 'hi' }])
301
+ Anway::Testing.events.last['topic']
302
+
232
303
  Anway::Testing.inline!
233
304
  ```
234
305
 
306
+ In inline mode, `Anway.publish` runs one copy in each job class of the app that subscribes to the topic.
307
+
235
308
  ## Client
236
309
 
237
310
  `Anway::Client` has the operations of [anway-go](https://github.com/thadeu/anway-go), in snake_case. It is safe for threads and for forks.
238
311
 
239
312
  ```ruby
240
313
  client = Anway::Client.new('tcp://localhost:7419')
241
- client.push(Anway::Job.new('email.send', ['a@b.com']))
314
+ client.push(Anway::Job.new('email.welcome', [1]))
242
315
  ```
243
316
 
244
317
  The error kinds are `Anway::NotUnique`, `Anway::Closed`, `Anway::ServerError`, and `Anway::ConnectionError`. A failed call does not resend.
@@ -8,7 +8,9 @@ module Anway
8
8
  class ActiveJobWrapper
9
9
  include Anway::Worker
10
10
 
11
- job_type 'ActiveJob'
11
+ EVENT = 'ActiveJob'
12
+
13
+ anway_options event: EVENT
12
14
 
13
15
  def perform(data)
14
16
  ActiveJob::Base.execute(data)
@@ -49,14 +51,14 @@ module ActiveJob
49
51
  # Each push has a new id. A retry_on attempt keeps its job_id while the
50
52
  # first attempt is still reserved, and the server rejects a repeated id.
51
53
  # custom.wrapped names the job class, so that the console shows it, as
52
- # Sidekiq does.
54
+ # Sidekiq does. The options are the push keys of the input contract.
53
55
  def push(job, options)
54
56
  options = options.merge(queue: job.queue_name, backtrace: BACKTRACE, custom: { 'wrapped' => job.class.name })
55
57
 
56
58
  # retry_on owns the attempts, so its final error goes to the dead set.
57
59
  options[:retry] = DEAD_SET if job.class.anway_retry_on
58
60
 
59
- pushed = Anway::Job.new('ActiveJob', [job.serialize.as_json], **options)
61
+ pushed = Anway::Job.new(Anway::ActiveJobWrapper::EVENT, [job.serialize.as_json], **options)
60
62
 
61
63
  job.provider_job_id = pushed.jid
62
64
 
data/lib/anway/cli.rb CHANGED
@@ -199,11 +199,14 @@ module Anway
199
199
  Signal.trap('TTIN') { runner.dump }
200
200
  end
201
201
 
202
- # Without a list, the worker uses the queues of its job classes.
202
+ # Without a list, the worker uses the queues of its job classes and of
203
+ # their subscriptions. With a list, the runner logs a warning for each
204
+ # subscription queue that is not in it.
203
205
  def queues
204
206
  return @options[:queues] if @options[:queues]
205
207
 
206
- names = Worker.classes.map { |klass| klass.job_options[:queue]&.to_s }
208
+ names = Worker.classes.map { |klass| klass.anway_options[:queue]&.to_s }
209
+ names.concat(Worker.subscriptions.map(&:queue))
207
210
  names.concat(active_job_queues)
208
211
 
209
212
  [*names.compact, 'default'].uniq
data/lib/anway/client.rb CHANGED
@@ -16,6 +16,10 @@ module Anway
16
16
  # count that the server wants, or nil.
17
17
  Heartbeat = Data.define(:state, :concurrency)
18
18
 
19
+ # The PUBLISH reply: the event id, the number of copies, and true when the
20
+ # server already had an event with this id.
21
+ Published = Data.define(:event, :jobs, :duplicate)
22
+
19
23
  # A blank URL uses ANWAY_URL, then the local default.
20
24
  def initialize(url = nil, pool_size: 8, timeout: 10, tls: nil, wid: nil, labels: [], identity: {})
21
25
  @endpoint = parse_url(url || ENV.fetch('ANWAY_URL', nil) || DEFAULT_URL)
@@ -102,14 +106,44 @@ module Anway
102
106
 
103
107
  # The command is "kill", "discard", "requeue", or "clear".
104
108
  # The target is "retries", "scheduled", or "dead".
105
- def mutate(command, target, jobtype: nil, jids: nil, regexp: nil)
106
- filter = { jobtype: jobtype, jids: jids, regexp: regexp }.compact
109
+ def mutate(command, target, event: nil, jids: nil, regexp: nil)
110
+ filter = { jobtype: event, jids: jids, regexp: regexp }.compact
107
111
 
108
112
  call('MUTATE', { cmd: command, target: target, filter: filter })
109
113
 
110
114
  true
111
115
  end
112
116
 
117
+ # Sends one event to each subscription of the topic. With an id, a second
118
+ # publish of the same id within unique_for seconds makes no job, and the
119
+ # reply has duplicate true. Returns a Published.
120
+ def publish(topic, args = [], id: nil, unique_for: nil, custom: nil)
121
+ Job.validate_args!(args)
122
+
123
+ event = { topic: topic, args: args, id: id, unique_for: unique_for, custom: custom&.transform_keys(&:to_s) }
124
+ data = JSON.parse(call('PUBLISH', event.compact))
125
+
126
+ Published.new(event: data['event'], jobs: data['jobs'], duplicate: data['duplicate'] == true)
127
+ end
128
+
129
+ # Each event of the topic makes one job in queue, with event as its job
130
+ # type. A second call with the same topic, queue, and event sets new retry
131
+ # and reserve_for.
132
+ def subscribe(topic, queue:, event:, retry: nil, reserve_for: nil)
133
+ options = { retry: binding.local_variable_get(:retry), reserve_for: reserve_for }
134
+
135
+ call('SUBSCRIBE', { topic: topic, queue: queue, jobtype: event, **options }.compact)
136
+
137
+ true
138
+ end
139
+
140
+ # A missing subscription is not an error.
141
+ def unsubscribe(topic, queue:, event:)
142
+ call('UNSUBSCRIBE', { topic: topic, queue: queue, jobtype: event })
143
+
144
+ true
145
+ end
146
+
113
147
  def batch_new(success: nil, complete: nil, parent_bid: nil, description: nil)
114
148
  definition = {
115
149
  success: success&.to_h, complete: complete&.to_h, parent_bid: parent_bid, description: description
data/lib/anway/job.rb CHANGED
@@ -3,6 +3,7 @@
3
3
  require 'json'
4
4
  require 'securerandom'
5
5
  require 'time'
6
+ require_relative 'options'
6
7
 
7
8
  module Anway
8
9
  class Job
@@ -10,6 +11,31 @@ module Anway
10
11
 
11
12
  attr_accessor :jid, :type, :args, :custom, *ATTRIBUTES.map(&:to_sym)
12
13
 
14
+ # Other languages read job args, so only JSON types with string hash keys
15
+ # are valid. Topic events use the same rule.
16
+ def self.validate_args!(args)
17
+ raise ArgumentError, "job args must be an array: #{args.inspect}" unless args.is_a?(Array)
18
+
19
+ validate_json!(args)
20
+ end
21
+
22
+ def self.validate_json!(value)
23
+ case value
24
+ when nil, true, false, String, Integer, Float
25
+ nil
26
+ when Array
27
+ value.each { |item| validate_json!(item) }
28
+ when Hash
29
+ value.each do |key, item|
30
+ raise ArgumentError, "job hash keys must be strings: #{key.inspect}" unless key.is_a?(String)
31
+
32
+ validate_json!(item)
33
+ end
34
+ else
35
+ raise ArgumentError, "job args must be JSON types: #{value.inspect}"
36
+ end
37
+ end
38
+
13
39
  def self.from_hash(hash)
14
40
  job = allocate
15
41
 
@@ -23,24 +49,30 @@ module Anway
23
49
  job
24
50
  end
25
51
 
26
- # Options: queue, retry, reserve_for, backtrace, at, custom, jid.
27
- def initialize(type, args = [], **options)
28
- validate_json!(args)
52
+ # The event goes on the wire as jobtype. The options are the push keys of
53
+ # the input contract (Anway::Options::PUSH). An unknown key raises
54
+ # ArgumentError. jid is optional, and the default is a new random id.
55
+ def initialize(event, args = [], jid: nil, **options)
56
+ self.class.validate_json!(args)
57
+
58
+ Options.check!(options, Options::PUSH)
59
+
60
+ fields = Options.wire(options)
29
61
 
30
- @jid = options[:jid] || SecureRandom.hex(12)
31
- @type = type
62
+ @jid = jid || SecureRandom.hex(12)
63
+ @type = event
32
64
  @args = args
33
- @queue = options[:queue]&.to_s
34
- @retry = options[:retry]
35
- @reserve_for = options[:reserve_for]
36
- @backtrace = options[:backtrace]
37
- @custom = options[:custom]&.transform_keys(&:to_s)
38
65
 
39
- run_at(options[:at]) if options[:at]
66
+ @queue = fields['queue']
67
+ @retry = fields['retry']
68
+ @reserve_for = fields['reserve_for']
69
+ @backtrace = fields['backtrace']
70
+ @at = fields['at']
71
+ @custom = fields['custom']
40
72
  end
41
73
 
42
74
  def run_at(time)
43
- @at = time.to_time.utc.iso8601(9)
75
+ @at = Options.time(time)
44
76
 
45
77
  self
46
78
  end
@@ -57,25 +89,5 @@ module Anway
57
89
  **ATTRIBUTES.to_h { |name| [name, public_send(name)] }
58
90
  }.compact
59
91
  end
60
-
61
- private
62
-
63
- # Other languages read these args, so only JSON types are valid.
64
- def validate_json!(value)
65
- case value
66
- when nil, true, false, String, Integer, Float
67
- nil
68
- when Array
69
- value.each { |item| validate_json!(item) }
70
- when Hash
71
- value.each do |key, item|
72
- raise ArgumentError, "job hash keys must be strings: #{key.inspect}" unless key.is_a?(String)
73
-
74
- validate_json!(item)
75
- end
76
- else
77
- raise ArgumentError, "job args must be JSON types: #{value.inspect}"
78
- end
79
- end
80
92
  end
81
93
  end
@@ -0,0 +1,123 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'time'
4
+
5
+ module Anway
6
+ # The input contract: the keys that an app uses to declare or push a job.
7
+ # This module is the only place that turns them into the fields of a job on
8
+ # the wire. anway_options, set, perform_*, Anway.push, and Anway::Job.new
9
+ # all use it. See "Input contract" in docs/dev/clients.md of the server.
10
+ #
11
+ # event jobtype (positional in Anway::Job.new)
12
+ # queue, retry, reserve_for, backtrace, at
13
+ # the field with the same name
14
+ # unique_for, unique_until, expires_in, expires_at, track, on_dead
15
+ # custom, with expires_at as RFC 3339, track true as 1, and
16
+ # on_dead { event:, queue: } as { "jobtype", "queue" }
17
+ # custom custom, for the keys of the app. The keys above win.
18
+ # topics one SUBSCRIBE for each topic (a declaration only)
19
+ module Options
20
+ # Keys with a wire field of the same name.
21
+ FIELDS = %i[queue retry reserve_for backtrace at].freeze
22
+
23
+ # Keys that go to custom.
24
+ CUSTOM = %i[unique_for unique_until expires_in expires_at track on_dead].freeze
25
+
26
+ # The keys of a push: Anway::Job.new, Anway.push, and set.
27
+ PUSH = [*FIELDS, *CUSTOM, :custom].freeze
28
+
29
+ # The keys of a declaration: anway_options. at is only for a push, and
30
+ # topics only for a declaration.
31
+ DECLARATION = [:event, *(PUSH - [:at]), :topics].freeze
32
+
33
+ ON_DEAD = %i[event queue].freeze
34
+
35
+ module_function
36
+
37
+ def check!(options, allowed)
38
+ unknown = options.keys - allowed
39
+
40
+ return if unknown.empty?
41
+
42
+ raise ArgumentError, "unknown options: #{unknown.join(', ')}"
43
+ end
44
+
45
+ # Merges option sets in order. A single value from a later set wins.
46
+ # topics add up in order, with no duplicates. custom hashes merge, and a
47
+ # later key wins.
48
+ def merge(*sets)
49
+ sets.each_with_object({}) do |set, merged|
50
+ set.each do |key, value|
51
+ merged[key] =
52
+ case key
53
+ when :topics then (merged[:topics] || []) | Array(value).map(&:to_s)
54
+ when :custom then (merged[:custom] || {}).merge(stringify(value))
55
+ else value
56
+ end
57
+ end
58
+ end
59
+ end
60
+
61
+ # Turns the keys of a push into wire fields, with string keys. A nil
62
+ # value sends no field.
63
+ def wire(options)
64
+ fields = FIELDS.to_h { |key| [key.to_s, field(key, options[key])] }
65
+
66
+ contract = CUSTOM.to_h { |key| [key.to_s, custom_field(key, options[key])] }.compact
67
+ custom = stringify(options[:custom]).merge(contract)
68
+
69
+ fields['custom'] = custom unless custom.empty?
70
+
71
+ fields.compact
72
+ end
73
+
74
+ # A time as RFC 3339, in UTC. A string goes as it is.
75
+ def time(value)
76
+ return value if value.nil? || value.is_a?(String)
77
+
78
+ value.to_time.utc.iso8601(9)
79
+ end
80
+
81
+ def field(key, value)
82
+ case key
83
+ when :queue then value&.to_s
84
+ when :at then time(value)
85
+ else value
86
+ end
87
+ end
88
+
89
+ def custom_field(key, value)
90
+ case key
91
+ when :unique_until then value&.to_s
92
+ when :expires_at then time(value)
93
+ when :track then track(value)
94
+ when :on_dead then on_dead(value)
95
+ else value
96
+ end
97
+ end
98
+
99
+ def track(value)
100
+ case value
101
+ when true then 1
102
+ when false then nil
103
+ else value
104
+ end
105
+ end
106
+
107
+ def on_dead(value)
108
+ return nil if value.nil?
109
+
110
+ hook = value.to_h.transform_keys(&:to_sym)
111
+
112
+ check!(hook, ON_DEAD)
113
+
114
+ raise ArgumentError, 'on_dead needs an event' if hook[:event].to_s.empty?
115
+
116
+ { 'jobtype' => hook[:event].to_s, 'queue' => hook[:queue]&.to_s }.compact
117
+ end
118
+
119
+ def stringify(hash)
120
+ (hash || {}).transform_keys(&:to_s)
121
+ end
122
+ end
123
+ end
data/lib/anway/runner.rb CHANGED
@@ -20,10 +20,13 @@ module Anway
20
20
  # hostname uses the machine name. The server can change the thread count
21
21
  # in a BEAT reply, up to limit, such as the database pool size. autoscale,
22
22
  # as { max: n } or { min: n, max: n }, starts the worker with autoscale on.
23
+ # subscriptions is a list of Worker::Subscription. The default is the
24
+ # subscriptions of all registered job classes, read at run.
23
25
  def initialize(queues: ['default'], concurrency: 10, timeout: 25, cancel_grace: 5, labels: [],
24
- hostname: nil, tag: nil, autoscale: nil, limit: nil,
26
+ hostname: nil, tag: nil, autoscale: nil, limit: nil, subscriptions: nil,
25
27
  beat_interval: BEAT_INTERVAL, url: nil, logger: Anway.config.logger)
26
28
  @queues = Queues.new(queues)
29
+ @subscriptions = subscriptions
27
30
  @concurrency = concurrency
28
31
  @limit = limit
29
32
  @timeout = timeout
@@ -69,10 +72,12 @@ module Anway
69
72
  end
70
73
 
71
74
  # The first beat reports the threads, so the server can scale the worker
72
- # at once.
75
+ # at once. The subscriptions go to the server before the first fetch.
73
76
  def run
74
77
  @client.heartbeat(nil, concurrency: @concurrency)
75
78
 
79
+ subscribe_all
80
+
76
81
  @lock.synchronize { @processors = Array.new(@concurrency) { start_processor } }
77
82
 
78
83
  beat_thread = start_beat
@@ -94,6 +99,26 @@ module Anway
94
99
  @events_writer.write_nonblock(letter, exception: false)
95
100
  end
96
101
 
102
+ # SUBSCRIBE is idempotent, so each start sends all subscriptions. A
103
+ # subscription queue that the worker does not fetch gets copies that wait.
104
+ def subscribe_all
105
+ (@subscriptions || Worker.subscriptions).each do |subscription|
106
+ @client.subscribe(
107
+ subscription.topic,
108
+ queue: subscription.queue,
109
+ event: subscription.event,
110
+ retry: subscription.retry,
111
+ reserve_for: subscription.reserve_for
112
+ )
113
+
114
+ @logger.info("anway subscribed topic=#{subscription.topic} queue=#{subscription.queue} event=#{subscription.event}")
115
+
116
+ next if @queues.names.include?(subscription.queue)
117
+
118
+ @logger.warn("anway does not fetch queue #{subscription.queue}, so the events of topic #{subscription.topic} wait there. Add the queue to queues.")
119
+ end
120
+ end
121
+
97
122
  def wait_for_stop
98
123
  loop do
99
124
  @events_reader.wait_readable
@@ -255,7 +280,7 @@ module Anway
255
280
  end
256
281
 
257
282
  def notify_error(error, job)
258
- @logger.warn("job failed jid=#{job.jid} jobtype=#{job.type} error=#{error.class}: #{error.message}")
283
+ @logger.warn("job failed jid=#{job.jid} event=#{job.type} error=#{error.class}: #{error.message}")
259
284
 
260
285
  Anway.config.error_handlers.each { |handler| handler.call(error, job) }
261
286
  rescue StandardError => e
@@ -302,7 +327,7 @@ module Anway
302
327
 
303
328
  return unless claim(job.jid)
304
329
 
305
- @logger.warn("job did not stop jid=#{job.jid} jobtype=#{job.type}")
330
+ @logger.warn("job did not stop jid=#{job.jid} event=#{job.type}")
306
331
 
307
332
  entry[:thread].kill
308
333
 
data/lib/anway/testing.rb CHANGED
@@ -5,15 +5,17 @@ require 'anway'
5
5
  module Anway
6
6
  # Test modes for apps. No server is necessary.
7
7
  #
8
- # Anway::Testing.fake! keeps pushed jobs in a list
9
- # Anway::Testing.inline! runs each job at push
8
+ # Anway::Testing.fake! keeps pushed jobs and published events in lists
9
+ # Anway::Testing.inline! runs each job at push, and each event in the
10
+ # subscribed classes of the app at publish
10
11
  # Anway::Testing.disable! uses the real client
11
12
  module Testing
12
13
  @mode = nil
13
14
  @jobs = []
15
+ @events = []
14
16
 
15
17
  class << self
16
- attr_reader :jobs, :mode
18
+ attr_reader :jobs, :events, :mode
17
19
 
18
20
  def fake!
19
21
  @mode = :fake
@@ -29,6 +31,7 @@ module Anway
29
31
 
30
32
  def clear
31
33
  @jobs.clear
34
+ @events.clear
32
35
  end
33
36
 
34
37
  def enqueue(job)
@@ -39,10 +42,39 @@ module Anway
39
42
  job.jid
40
43
  end
41
44
 
45
+ # Keeps the event as the PUBLISH payload, with string keys. jobs is the
46
+ # number of subscriptions in the job classes of the app. There is no
47
+ # duplicate check.
48
+ def publish(topic, args = [], id: nil, unique_for: nil, custom: nil)
49
+ event = { 'topic' => topic, 'args' => args, 'id' => id, 'unique_for' => unique_for, 'custom' => custom }
50
+ copy = JSON.parse(JSON.generate(event.compact))
51
+
52
+ event_id = id || "evt-#{SecureRandom.hex(12)}"
53
+ subscriptions = Worker.subscriptions.select { |subscription| subscription.topic == topic.to_s }
54
+
55
+ @events << copy
56
+
57
+ subscriptions.each { |subscription| Executor.call(event_job(subscription, copy, event_id)) } if @mode == :inline
58
+
59
+ Client::Published.new(event: event_id, jobs: subscriptions.size, duplicate: false)
60
+ end
61
+
42
62
  # Runs and removes all fake jobs. Jobs that they push also run.
43
63
  def drain
44
64
  Executor.call(@jobs.shift) until @jobs.empty?
45
65
  end
66
+
67
+ private
68
+
69
+ # The copy that the server makes for one subscription.
70
+ def event_job(subscription, event, event_id)
71
+ custom = (event['custom'] || {}).merge('topic' => subscription.topic, 'event' => event_id)
72
+
73
+ Job.new(
74
+ subscription.event, event['args'],
75
+ queue: subscription.queue, retry: subscription.retry, reserve_for: subscription.reserve_for, custom: custom
76
+ )
77
+ end
46
78
  end
47
79
  end
48
80
  end
data/lib/anway/version.rb CHANGED
@@ -1,8 +1,8 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Anway
4
- VERSION = '0.2.0'
4
+ VERSION = '0.4.0'
5
5
 
6
6
  # The anway server that the platform gems carry, and that CI tests against.
7
- SERVER_VERSION = '0.2.2'
7
+ SERVER_VERSION = '0.3.1'
8
8
  end
data/lib/anway/worker.rb CHANGED
@@ -6,15 +6,28 @@ module Anway
6
6
  # class WelcomeJob
7
7
  # include Anway::Worker
8
8
  #
9
- # job_options queue: 'mailers', retry: 5
9
+ # anway_options event: 'email.welcome', retry: 5
10
+ # anway_options topics: %w[user.created], queue: 'mailers'
10
11
  #
11
12
  # def perform(user_id); end
12
13
  # end
13
14
  #
14
15
  # WelcomeJob.perform_async(42)
16
+ # WelcomeJob.set(queue: 'low', unique_for: 60).perform_async(42)
17
+ #
18
+ # The keys are the input contract (Anway::Options). The event is the job
19
+ # type on the wire, and the default is the class name. Each topic makes one
20
+ # subscription, which the worker sends when it starts.
15
21
  module Worker
16
22
  DEFAULT_BACKTRACE = 30
17
23
 
24
+ # One topic, queue, and event. retry and reserve_for are the options of
25
+ # each copy.
26
+ Subscription = Data.define(:topic, :queue, :event, :retry, :reserve_for)
27
+
28
+ # A subclass does not inherit these keys.
29
+ OWN_KEYS = %i[event topics].freeze
30
+
18
31
  @registry = {}
19
32
  @lock = Mutex.new
20
33
 
@@ -25,10 +38,21 @@ module Anway
25
38
  register(base) if base.name
26
39
  end
27
40
 
28
- def register(klass, old_type: nil)
41
+ # Each event has one class. A class with the same name replaces the old
42
+ # one, as after a code reload. Another class with the same event raises
43
+ # ArgumentError.
44
+ def register(klass, old_event: nil)
45
+ event = klass.anway_options[:event]
46
+
29
47
  @lock.synchronize do
30
- @registry.delete(old_type) if old_type
31
- @registry[klass.job_type] = klass
48
+ current = @registry[event]
49
+
50
+ if current && !current.equal?(klass) && current.name != klass.name
51
+ raise ArgumentError, "event #{event.inspect} already has the class #{current.name}, so #{klass.name} cannot use it"
52
+ end
53
+
54
+ @registry.delete(old_event) if old_event && @registry[old_event].equal?(klass)
55
+ @registry[event] = klass
32
56
  end
33
57
  end
34
58
 
@@ -36,13 +60,19 @@ module Anway
36
60
  @lock.synchronize { @registry.values }
37
61
  end
38
62
 
39
- # Only registered classes run. The job type comes from the network, so it
63
+ # The subscriptions of all registered classes. A worker sends them with
64
+ # SUBSCRIBE when it starts.
65
+ def subscriptions
66
+ classes.flat_map(&:subscriptions).uniq
67
+ end
68
+
69
+ # Only registered classes run. The event comes from the network, so it
40
70
  # never becomes a constant lookup. The lookup by the class name below
41
71
  # uses a registered name, and returns the newest class after a reload.
42
- def find(type)
43
- klass = @lock.synchronize { @registry[type] }
72
+ def find(event)
73
+ klass = @lock.synchronize { @registry[event] }
44
74
 
45
- raise UnknownJob, "no handler for job type #{type.inspect}" unless klass
75
+ raise UnknownJob, "no handler for event #{event.inspect}" unless klass
46
76
 
47
77
  klass.name ? Object.const_get(klass.name) : klass
48
78
  end
@@ -66,21 +96,46 @@ module Anway
66
96
  Worker.register(subclass) if subclass.name
67
97
  end
68
98
 
69
- def job_type(name = nil)
70
- return @job_type || self.name unless name
99
+ # With keys, adds one option set to the class. The keys are
100
+ # Anway::Options::DECLARATION, and an unknown key raises ArgumentError.
101
+ #
102
+ # Without keys, returns the options of the class: the options of the
103
+ # parent class without event and topics, then each set in call order.
104
+ # event and topics are always in the result.
105
+ def anway_options(**options)
106
+ return declared_options if options.empty?
71
107
 
72
- old_type = job_type
73
- @job_type = name
108
+ Options.check!(options, Options::DECLARATION)
74
109
 
75
- Worker.register(self, old_type: old_type)
76
- end
110
+ # Translates the set now, so that a bad value, such as an on_dead
111
+ # without an event, fails when the class loads.
112
+ Options.wire(options.except(*OWN_KEYS))
77
113
 
78
- def job_options(options = nil)
79
- inherited_options = superclass.respond_to?(:job_options) ? superclass.job_options : {}
114
+ options = options.merge(event: event_name(options[:event])) if options.key?(:event)
115
+ old_event = declared_options[:event]
80
116
 
81
- @job_options = (@job_options || {}).merge(options) if options
117
+ (@anway_option_sets ||= []) << options.freeze
82
118
 
83
- inherited_options.merge(@job_options || {})
119
+ register_event(old_event) if options.key?(:event)
120
+
121
+ declared_options
122
+ end
123
+
124
+ # One subscription for each topic, with the event, queue, retry, and
125
+ # reserve_for of the class. Without a queue, the copies go to default.
126
+ def subscriptions
127
+ options = declared_options
128
+ queue = (options[:queue] || 'default').to_s
129
+
130
+ options[:topics].map do |topic|
131
+ Subscription.new(
132
+ topic: topic,
133
+ queue: queue,
134
+ event: options[:event],
135
+ retry: options[:retry],
136
+ reserve_for: options[:reserve_for]
137
+ )
138
+ end
84
139
  end
85
140
 
86
141
  def perform_async(*args)
@@ -95,13 +150,48 @@ module Anway
95
150
  enqueue_with(args, { at: Time.now + seconds.to_f })
96
151
  end
97
152
 
98
- # Changes the options for one push: WelcomeJob.set(queue: 'low').perform_async(1)
153
+ # Changes the options for one push, with the push keys of
154
+ # Anway::Options::PUSH: WelcomeJob.set(queue: 'low').perform_async(1)
99
155
  def set(**options)
156
+ Options.check!(options, Options::PUSH)
157
+
100
158
  Setter.new(self, options)
101
159
  end
102
160
 
161
+ # The options of the class, then the options of the push, merge with
162
+ # the same rules as two anway_options calls.
103
163
  def enqueue_with(args, options)
104
- Anway.enqueue(Job.new(job_type, args, backtrace: DEFAULT_BACKTRACE, **job_options, **options))
164
+ declared = declared_options
165
+ push = Options.merge({ backtrace: DEFAULT_BACKTRACE }, declared.except(*OWN_KEYS), options)
166
+
167
+ Anway.enqueue(Job.new(declared[:event], args, **push))
168
+ end
169
+
170
+ private
171
+
172
+ def declared_options
173
+ parent = superclass.respond_to?(:anway_options) ? superclass.anway_options.except(*OWN_KEYS) : {}
174
+
175
+ Options.merge({ event: name, topics: [] }, parent, *@anway_option_sets).freeze
176
+ end
177
+
178
+ # A set with an event that another class has does not stay.
179
+ def register_event(old_event)
180
+ return unless name
181
+
182
+ Worker.register(self, old_event: old_event)
183
+ rescue ArgumentError
184
+ @anway_option_sets.pop
185
+
186
+ raise
187
+ end
188
+
189
+ def event_name(value)
190
+ event = value.to_s
191
+
192
+ raise ArgumentError, 'event must not be empty' if event.empty?
193
+
194
+ event
105
195
  end
106
196
  end
107
197
 
data/lib/anway.rb CHANGED
@@ -3,6 +3,7 @@
3
3
  require_relative 'anway/version'
4
4
  require_relative 'anway/errors'
5
5
  require_relative 'anway/configuration'
6
+ require_relative 'anway/options'
6
7
  require_relative 'anway/job'
7
8
  require_relative 'anway/connection'
8
9
  require_relative 'anway/pool'
@@ -39,9 +40,10 @@ module Anway
39
40
  end
40
41
  end
41
42
 
42
- # Sends a job with no local class, for a worker in any language.
43
- def push(type, args = [], **options)
44
- enqueue(Job.new(type, args, **options))
43
+ # Sends a job with no local class, for a worker in any language. The
44
+ # options are the push keys of the input contract.
45
+ def push(event, args = [], **options)
46
+ enqueue(Job.new(event, args, **options))
45
47
  end
46
48
 
47
49
  # Inside a database transaction, the push waits for the commit.
@@ -55,6 +57,23 @@ module Anway
55
57
  job.jid
56
58
  end
57
59
 
60
+ # Sends one event to each subscription of the topic. Returns a
61
+ # Client::Published. Inside a database transaction, the publish waits for
62
+ # the commit and returns nil.
63
+ def publish(topic, args = [], **options)
64
+ Job.validate_args!(args)
65
+
66
+ testing = const_defined?(:Testing) ? Testing : nil
67
+
68
+ return testing.publish(topic, args, **options) if testing&.mode
69
+
70
+ published = nil
71
+
72
+ config.push_wrapper.call { published = client.publish(topic, args, **options) }
73
+
74
+ published
75
+ end
76
+
58
77
  def reset!
59
78
  @lock.synchronize do
60
79
  @client&.close
data/libexec/anway-server CHANGED
Binary file
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: anway
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.2.0
4
+ version: 0.4.0
5
5
  platform: x86_64-linux-gnu
6
6
  authors:
7
7
  - Thadeu
@@ -42,6 +42,7 @@ files:
42
42
  - lib/anway/errors.rb
43
43
  - lib/anway/executor.rb
44
44
  - lib/anway/job.rb
45
+ - lib/anway/options.rb
45
46
  - lib/anway/pool.rb
46
47
  - lib/anway/puma/plugin.rb
47
48
  - lib/anway/queues.rb