anway 0.3.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: ad9bb829ab955e887e887d3bcfda9df84584fc6ddc4e67125514c8da5cf48be6
4
- data.tar.gz: 7bd89b2606e90c9aa21ace2b3f9e927e9ab85f02588dc762f9484763846ad84a
3
+ metadata.gz: 2dc92ff0ab7b743fa243aa78cdd186860e1a564be584d110a73ea0a8708293d4
4
+ data.tar.gz: 0ecd6eac6ffdfb8f445e6a3ceed7fe550f128f9bb7e0eca488625e6713827340
5
5
  SHA512:
6
- metadata.gz: dd123d9ae6acbc45a3c983aeab2744e32dee60d7aa982a4757050bdfb24611baaa20c7a6ea165056af40ee95db987bdfe81fbdbd4ea7420418346e7e70b3c60f
7
- data.tar.gz: b867be47fe00496979d3732bf4da16b4e303f8fc5547f7ec4128b18c057e3128607c9207d917ce37a52f23d1f7baaaec83efab993edb7637455a4404e9182798
6
+ metadata.gz: 06b4dd95b906fcaa6cc5625213ac95356621f9cd5a2ae99d8e2d201aea3fadf0b70d8091036de21e4d446f2dadbf167ada2573906a3ceac675c9563ffc850daa
7
+ data.tar.gz: b68fa05cec43691113b31df2b398fa67c36cf3bec0f5c4641815379bca6737804a5667f14985b350cb54ec990ba8d512c0ae0e8a607dc118499d472f21e49e2d
data/README.md CHANGED
@@ -98,28 +98,61 @@ 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
 
125
158
  ## Topics
@@ -130,7 +163,7 @@ A topic sends one event to many queues. Each subscription of the topic gets one
130
163
  class BroadcastMessage
131
164
  include Anway::Worker
132
165
 
133
- subscribe 'chat.message', queue: 'realtime'
166
+ anway_options topics: %w[chat.message], queue: 'realtime'
134
167
 
135
168
  def perform(message)
136
169
  # ...
@@ -141,7 +174,7 @@ Anway.publish('chat.message', [{ 'room' => 'general', 'body' => 'hi' }], id: 'ms
141
174
  # => #<data Anway::Client::Published event="msg-42", jobs=3, duplicate=false>
142
175
  ```
143
176
 
144
- - `subscribe` uses the `job_type` of the class. `queue`, `retry`, and `reserve_for` have the `job_options` of the class as defaults.
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.
145
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.
146
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`.
147
180
  - The server adds `topic` and `event` to `custom` of each copy. Use `job.custom['event']` to make the handler idempotent.
@@ -151,8 +184,8 @@ The client has the same commands:
151
184
 
152
185
  ```ruby
153
186
  client.publish('chat.message', [{ 'body' => 'hi' }], id: 'msg-42', unique_for: 3600, custom: { 'source' => 'web' })
154
- client.subscribe('chat.message', queue: 'realtime', jobtype: 'BroadcastMessage', retry: 3, reserve_for: 60)
155
- client.unsubscribe('chat.message', queue: 'realtime', jobtype: 'BroadcastMessage')
187
+ client.subscribe('chat.message', queue: 'realtime', event: 'BroadcastMessage', retry: 3, reserve_for: 60)
188
+ client.unsubscribe('chat.message', queue: 'realtime', event: 'BroadcastMessage')
156
189
  ```
157
190
 
158
191
  [docs/topics.md](docs/topics.md) explains the chat example with three apps, the options, the tests, and problems.
@@ -260,7 +293,7 @@ Keep the database pool at the concurrency value or more. A job queue with no wor
260
293
  require 'anway/testing'
261
294
 
262
295
  Anway::Testing.fake!
263
- WelcomeJob.perform_async('a@b.com')
296
+ WelcomeJob.perform_async(1)
264
297
  Anway::Testing.jobs.size
265
298
  Anway::Testing.drain
266
299
 
@@ -278,7 +311,7 @@ In inline mode, `Anway.publish` runs one copy in each job class of the app that
278
311
 
279
312
  ```ruby
280
313
  client = Anway::Client.new('tcp://localhost:7419')
281
- client.push(Anway::Job.new('email.send', ['a@b.com']))
314
+ client.push(Anway::Job.new('email.welcome', [1]))
282
315
  ```
283
316
 
284
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
@@ -205,7 +205,7 @@ module Anway
205
205
  def queues
206
206
  return @options[:queues] if @options[:queues]
207
207
 
208
- names = Worker.classes.map { |klass| klass.job_options[:queue]&.to_s }
208
+ names = Worker.classes.map { |klass| klass.anway_options[:queue]&.to_s }
209
209
  names.concat(Worker.subscriptions.map(&:queue))
210
210
  names.concat(active_job_queues)
211
211
 
data/lib/anway/client.rb CHANGED
@@ -106,8 +106,8 @@ module Anway
106
106
 
107
107
  # The command is "kill", "discard", "requeue", or "clear".
108
108
  # The target is "retries", "scheduled", or "dead".
109
- def mutate(command, target, jobtype: nil, jids: nil, regexp: nil)
110
- 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
111
111
 
112
112
  call('MUTATE', { cmd: command, target: target, filter: filter })
113
113
 
@@ -126,19 +126,20 @@ module Anway
126
126
  Published.new(event: data['event'], jobs: data['jobs'], duplicate: data['duplicate'] == true)
127
127
  end
128
128
 
129
- # Each event of the topic makes one job of jobtype in queue. A second call
130
- # with the same topic, queue, and jobtype sets new retry and reserve_for.
131
- def subscribe(topic, queue:, jobtype:, retry: nil, reserve_for: nil)
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)
132
133
  options = { retry: binding.local_variable_get(:retry), reserve_for: reserve_for }
133
134
 
134
- call('SUBSCRIBE', { topic: topic, queue: queue, jobtype: jobtype, **options }.compact)
135
+ call('SUBSCRIBE', { topic: topic, queue: queue, jobtype: event, **options }.compact)
135
136
 
136
137
  true
137
138
  end
138
139
 
139
140
  # A missing subscription is not an error.
140
- def unsubscribe(topic, queue:, jobtype:)
141
- call('UNSUBSCRIBE', { topic: topic, queue: queue, jobtype: jobtype })
141
+ def unsubscribe(topic, queue:, event:)
142
+ call('UNSUBSCRIBE', { topic: topic, queue: queue, jobtype: event })
142
143
 
143
144
  true
144
145
  end
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
@@ -48,24 +49,30 @@ module Anway
48
49
  job
49
50
  end
50
51
 
51
- # Options: queue, retry, reserve_for, backtrace, at, custom, jid.
52
- def initialize(type, args = [], **options)
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)
53
56
  self.class.validate_json!(args)
54
57
 
55
- @jid = options[:jid] || SecureRandom.hex(12)
56
- @type = type
58
+ Options.check!(options, Options::PUSH)
59
+
60
+ fields = Options.wire(options)
61
+
62
+ @jid = jid || SecureRandom.hex(12)
63
+ @type = event
57
64
  @args = args
58
- @queue = options[:queue]&.to_s
59
- @retry = options[:retry]
60
- @reserve_for = options[:reserve_for]
61
- @backtrace = options[:backtrace]
62
- @custom = options[:custom]&.transform_keys(&:to_s)
63
65
 
64
- 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']
65
72
  end
66
73
 
67
74
  def run_at(time)
68
- @at = time.to_time.utc.iso8601(9)
75
+ @at = Options.time(time)
69
76
 
70
77
  self
71
78
  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
@@ -106,12 +106,12 @@ module Anway
106
106
  @client.subscribe(
107
107
  subscription.topic,
108
108
  queue: subscription.queue,
109
- jobtype: subscription.jobtype,
109
+ event: subscription.event,
110
110
  retry: subscription.retry,
111
111
  reserve_for: subscription.reserve_for
112
112
  )
113
113
 
114
- @logger.info("anway subscribed topic=#{subscription.topic} queue=#{subscription.queue} jobtype=#{subscription.jobtype}")
114
+ @logger.info("anway subscribed topic=#{subscription.topic} queue=#{subscription.queue} event=#{subscription.event}")
115
115
 
116
116
  next if @queues.names.include?(subscription.queue)
117
117
 
@@ -280,7 +280,7 @@ module Anway
280
280
  end
281
281
 
282
282
  def notify_error(error, job)
283
- @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}")
284
284
 
285
285
  Anway.config.error_handlers.each { |handler| handler.call(error, job) }
286
286
  rescue StandardError => e
@@ -327,7 +327,7 @@ module Anway
327
327
 
328
328
  return unless claim(job.jid)
329
329
 
330
- @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}")
331
331
 
332
332
  entry[:thread].kill
333
333
 
data/lib/anway/testing.rb CHANGED
@@ -70,7 +70,10 @@ module Anway
70
70
  def event_job(subscription, event, event_id)
71
71
  custom = (event['custom'] || {}).merge('topic' => subscription.topic, 'event' => event_id)
72
72
 
73
- Job.new(subscription.jobtype, event['args'], queue: subscription.queue, custom: custom)
73
+ Job.new(
74
+ subscription.event, event['args'],
75
+ queue: subscription.queue, retry: subscription.retry, reserve_for: subscription.reserve_for, custom: custom
76
+ )
74
77
  end
75
78
  end
76
79
  end
data/lib/anway/version.rb CHANGED
@@ -1,7 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Anway
4
- VERSION = '0.3.0'
4
+ VERSION = '0.4.0'
5
5
 
6
6
  # The anway server that the platform gems carry, and that CI tests against.
7
7
  SERVER_VERSION = '0.3.1'
data/lib/anway/worker.rb CHANGED
@@ -6,29 +6,27 @@ 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)
15
17
  #
16
- # A class can also run the events of a topic:
17
- #
18
- # class BroadcastMessage
19
- # include Anway::Worker
20
- #
21
- # subscribe 'chat.message', queue: 'realtime'
22
- #
23
- # def perform(message); end
24
- # end
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.
25
21
  module Worker
26
22
  DEFAULT_BACKTRACE = 30
27
- SUBSCRIBE_OPTIONS = %i[retry reserve_for].freeze
28
23
 
29
- # One topic, queue, and job type. retry and reserve_for are the options of
24
+ # One topic, queue, and event. retry and reserve_for are the options of
30
25
  # each copy.
31
- Subscription = Data.define(:topic, :queue, :jobtype, :retry, :reserve_for)
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
32
30
 
33
31
  @registry = {}
34
32
  @lock = Mutex.new
@@ -40,10 +38,21 @@ module Anway
40
38
  register(base) if base.name
41
39
  end
42
40
 
43
- 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
+
44
47
  @lock.synchronize do
45
- @registry.delete(old_type) if old_type
46
- @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
47
56
  end
48
57
  end
49
58
 
@@ -57,13 +66,13 @@ module Anway
57
66
  classes.flat_map(&:subscriptions).uniq
58
67
  end
59
68
 
60
- # Only registered classes run. The job type comes from the network, so it
69
+ # Only registered classes run. The event comes from the network, so it
61
70
  # never becomes a constant lookup. The lookup by the class name below
62
71
  # uses a registered name, and returns the newest class after a reload.
63
- def find(type)
64
- klass = @lock.synchronize { @registry[type] }
72
+ def find(event)
73
+ klass = @lock.synchronize { @registry[event] }
65
74
 
66
- raise UnknownJob, "no handler for job type #{type.inspect}" unless klass
75
+ raise UnknownJob, "no handler for event #{event.inspect}" unless klass
67
76
 
68
77
  klass.name ? Object.const_get(klass.name) : klass
69
78
  end
@@ -87,48 +96,44 @@ module Anway
87
96
  Worker.register(subclass) if subclass.name
88
97
  end
89
98
 
90
- def job_type(name = nil)
91
- 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?
92
107
 
93
- old_type = job_type
94
- @job_type = name
95
-
96
- Worker.register(self, old_type: old_type)
97
- end
108
+ Options.check!(options, Options::DECLARATION)
98
109
 
99
- def job_options(options = nil)
100
- inherited_options = superclass.respond_to?(:job_options) ? superclass.job_options : {}
101
-
102
- @job_options = (@job_options || {}).merge(options) if options
103
-
104
- inherited_options.merge(@job_options || {})
105
- 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))
106
113
 
107
- # Runs each event of the topic in this class. The job type is the job
108
- # type of the class. queue, retry, and reserve_for have the job_options
109
- # of the class as defaults, read when the worker starts. A subclass does
110
- # not get the subscriptions of its parent.
111
- def subscribe(topic, queue: nil, **options)
112
- unknown = options.keys - SUBSCRIBE_OPTIONS
114
+ options = options.merge(event: event_name(options[:event])) if options.key?(:event)
115
+ old_event = declared_options[:event]
113
116
 
114
- raise ArgumentError, "unknown subscribe options: #{unknown.join(', ')}" if unknown.any?
117
+ (@anway_option_sets ||= []) << options.freeze
115
118
 
116
- entry = { topic: topic.to_s, queue: queue&.to_s, **options }
119
+ register_event(old_event) if options.key?(:event)
117
120
 
118
- @subscriptions ||= []
119
- @subscriptions << entry unless @subscriptions.include?(entry)
121
+ declared_options
120
122
  end
121
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.
122
126
  def subscriptions
123
- defaults = job_options
127
+ options = declared_options
128
+ queue = (options[:queue] || 'default').to_s
124
129
 
125
- (@subscriptions || []).map do |entry|
130
+ options[:topics].map do |topic|
126
131
  Subscription.new(
127
- topic: entry[:topic],
128
- queue: entry[:queue] || defaults[:queue]&.to_s || 'default',
129
- jobtype: job_type,
130
- retry: entry.fetch(:retry, defaults[:retry]),
131
- reserve_for: entry.fetch(:reserve_for, defaults[:reserve_for])
132
+ topic: topic,
133
+ queue: queue,
134
+ event: options[:event],
135
+ retry: options[:retry],
136
+ reserve_for: options[:reserve_for]
132
137
  )
133
138
  end
134
139
  end
@@ -145,13 +150,48 @@ module Anway
145
150
  enqueue_with(args, { at: Time.now + seconds.to_f })
146
151
  end
147
152
 
148
- # 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)
149
155
  def set(**options)
156
+ Options.check!(options, Options::PUSH)
157
+
150
158
  Setter.new(self, options)
151
159
  end
152
160
 
161
+ # The options of the class, then the options of the push, merge with
162
+ # the same rules as two anway_options calls.
153
163
  def enqueue_with(args, options)
154
- 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
155
195
  end
156
196
  end
157
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.
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.3.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