anway 0.3.0-aarch64-linux-gnu → 0.5.0-aarch64-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: cd8fffae9cc66a49cf6e3c70c4728c7981f5f3c55c95debe65925ac4219ee904
4
- data.tar.gz: 60a1ecb325d1e77b099ade2b90aaca1a23b6313e0553463c2c8606d52dce870f
3
+ metadata.gz: a2becf6866b6061f3147f57b6297de5286103a77082c9e1d13ce9c6dc4c73cfb
4
+ data.tar.gz: 590370fce81f67766fa12e499213af7020825b89c30aa7c15a2702ad62bb7444
5
5
  SHA512:
6
- metadata.gz: 332bf304ee9a86cd4d0ed19af50c4afcded83cfa8faee7b65ab75dd7030727108e2829b935ac8fdc58c3aeb99bb36bdb8b6abcea3fcfb188f6223348b71f302d
7
- data.tar.gz: 262dae241d8e14c067ca4efc340c749eb951439140d2625092b66f09b99476a994207851125bad0dd711cf67c29ec3967278a3246d09c772a1e06f916dc33f15
6
+ metadata.gz: c8e15c3a326397d7dd68c699c3919047cf1530b6454d8673ceb97ae14bbcca67446694b255a503630a435d1a01b806cbba563c6a37aa26f5c11186b1e637388b
7
+ data.tar.gz: ba8ddb723267e1df464e8138f4bfab53960e53b81860ee0e77fae9608d3443a1743eadffbe2e444af0a6569b6f802669c870b0d178bbbbde4478e14de393463d
data/README.md CHANGED
@@ -98,30 +98,86 @@ 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
+ ## Bulk push
159
+
160
+ A bulk push sends many jobs with one `PUSHB` command, and the server puts them in with one write. Use it to push a large list of jobs fast. Bulk push needs server v0.3.2 or later.
161
+
162
+ ```ruby
163
+ WelcomeJob.perform_bulk([[1], [2], [3]])
164
+ # => {}
165
+
166
+ WelcomeJob.set(queue: 'low', at: Time.now + 300).perform_bulk(users.map { |user| [user.id] })
167
+
168
+ Anway.push_bulk([Anway::Job.new('image.resize', [1]), Anway::Job.new('image.resize', [2])])
169
+ ```
170
+
171
+ - Each item of `perform_bulk` is the args of one job. The jobs get the options of the class and of `set`, as `perform_async` does.
172
+ - The result is a hash with the reason for each job that the server refused, by jid. When all jobs are in, it is `{}`.
173
+ - A refused job, such as a duplicate jid or a job that a unique lock blocks, does not stop the other jobs.
174
+ - One `PUSHB` takes at most 1,000 jobs. `perform_bulk` and `Anway.push_bulk` split a longer list into several `PUSHB` commands, and merge the failures.
175
+ - The gem builds all jobs before the first send. An item that is not valid raises `ArgumentError`, and no job goes to the server.
176
+ - In a database transaction, the push waits for the commit, and the result is `nil`. A rollback cancels the push.
177
+ - A list of more than 1,000 jobs uses more than one `PUSHB`. If a connection error occurs after the first `PUSHB`, the jobs of the earlier commands stay in, and the gem does not send them again.
178
+
179
+ `client.push_bulk(jobs)` sends one `PUSHB`. It takes at most 1,000 jobs, and more raise `ArgumentError` before the send.
180
+
125
181
  ## Topics
126
182
 
127
183
  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.
@@ -130,7 +186,7 @@ A topic sends one event to many queues. Each subscription of the topic gets one
130
186
  class BroadcastMessage
131
187
  include Anway::Worker
132
188
 
133
- subscribe 'chat.message', queue: 'realtime'
189
+ anway_options topics: %w[chat.message], queue: 'realtime'
134
190
 
135
191
  def perform(message)
136
192
  # ...
@@ -141,7 +197,7 @@ Anway.publish('chat.message', [{ 'room' => 'general', 'body' => 'hi' }], id: 'ms
141
197
  # => #<data Anway::Client::Published event="msg-42", jobs=3, duplicate=false>
142
198
  ```
143
199
 
144
- - `subscribe` uses the `job_type` of the class. `queue`, `retry`, and `reserve_for` have the `job_options` of the class as defaults.
200
+ - 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
201
  - 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
202
  - 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
203
  - The server adds `topic` and `event` to `custom` of each copy. Use `job.custom['event']` to make the handler idempotent.
@@ -151,8 +207,8 @@ The client has the same commands:
151
207
 
152
208
  ```ruby
153
209
  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')
210
+ client.subscribe('chat.message', queue: 'realtime', event: 'BroadcastMessage', retry: 3, reserve_for: 60)
211
+ client.unsubscribe('chat.message', queue: 'realtime', event: 'BroadcastMessage')
156
212
  ```
157
213
 
158
214
  [docs/topics.md](docs/topics.md) explains the chat example with three apps, the options, the tests, and problems.
@@ -167,6 +223,7 @@ config.active_job.queue_adapter = :anway
167
223
  - In a database transaction, a push waits for the commit, and a rollback cancels it. This also applies to `perform_async`.
168
224
  - A job with `retry_on` keeps ActiveJob attempts, and its final error goes to the dead set.
169
225
  - A job with no `retry_on` uses server retries.
226
+ - `ActiveJob.perform_all_later(jobs)` sends one `PUSHB` for each 1,000 jobs, for jobs of all classes and queues. A job with `set(wait:)` or `set(wait_until:)` keeps its time. Each job gets `successfully_enqueued`, and a job that the server refused gets an `ActiveJob::EnqueueError` in `enqueue_error`.
170
227
 
171
228
  Tasks in `recurring.yml` and jobs that wait in Solid Queue do not move automatically. Move recurring tasks to the server cron, and drain the old queue first.
172
229
 
@@ -260,7 +317,7 @@ Keep the database pool at the concurrency value or more. A job queue with no wor
260
317
  require 'anway/testing'
261
318
 
262
319
  Anway::Testing.fake!
263
- WelcomeJob.perform_async('a@b.com')
320
+ WelcomeJob.perform_async(1)
264
321
  Anway::Testing.jobs.size
265
322
  Anway::Testing.drain
266
323
 
@@ -272,13 +329,16 @@ Anway::Testing.inline!
272
329
 
273
330
  In inline mode, `Anway.publish` runs one copy in each job class of the app that subscribes to the topic.
274
331
 
332
+ `perform_bulk` and `Anway.push_bulk` work as single pushes do: fake mode adds each job to `Anway::Testing.jobs`, and inline mode runs each job. The result is `{}`.
333
+
275
334
  ## Client
276
335
 
277
336
  `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.
278
337
 
279
338
  ```ruby
280
339
  client = Anway::Client.new('tcp://localhost:7419')
281
- client.push(Anway::Job.new('email.send', ['a@b.com']))
340
+ client.push(Anway::Job.new('email.welcome', [1]))
341
+ client.push_bulk([Anway::Job.new('email.welcome', [2]), Anway::Job.new('email.welcome', [3])])
282
342
  ```
283
343
 
284
344
  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)
@@ -44,23 +46,56 @@ module ActiveJob
44
46
  push(job, { at: Time.at(timestamp) })
45
47
  end
46
48
 
49
+ # ActiveJob.perform_all_later calls this. Jobs of all classes and queues
50
+ # go together, with one PUSHB for each 1,000 jobs, and a scheduled job
51
+ # gets its at. Sets successfully_enqueued on each job, and enqueue_error
52
+ # on a refused job. Returns the number of jobs in. Inside a database
53
+ # transaction, the push waits for the commit, and each job counts as in,
54
+ # as perform_later does.
55
+ def enqueue_all(jobs)
56
+ pushed = jobs.map { |job| [job, build(job, scheduled(job))] }
57
+ failures = Anway.push_bulk(pushed.map(&:last)) || {}
58
+
59
+ pushed.each do |job, wire|
60
+ reason = failures[wire.jid]
61
+
62
+ job.provider_job_id = wire.jid
63
+ job.successfully_enqueued = reason.nil?
64
+ job.enqueue_error = reason && ActiveJob::EnqueueError.new(reason)
65
+ end
66
+
67
+ jobs.count(&:successfully_enqueued?)
68
+ end
69
+
47
70
  private
48
71
 
72
+ def scheduled(job)
73
+ job.scheduled_at ? { at: Time.at(job.scheduled_at.to_f) } : {}
74
+ end
75
+
49
76
  # Each push has a new id. A retry_on attempt keeps its job_id while the
50
77
  # first attempt is still reserved, and the server rejects a repeated id.
51
78
  # custom.wrapped names the job class, so that the console shows it, as
52
- # Sidekiq does.
79
+ # Sidekiq does. The options are the push keys of the input contract.
53
80
  def push(job, options)
81
+ pushed = build(job, options)
82
+
83
+ job.provider_job_id = pushed.jid
84
+
85
+ Anway.enqueue(pushed)
86
+ end
87
+
88
+ def build(job, options)
54
89
  options = options.merge(queue: job.queue_name, backtrace: BACKTRACE, custom: { 'wrapped' => job.class.name })
55
90
 
56
91
  # retry_on owns the attempts, so its final error goes to the dead set.
57
92
  options[:retry] = DEAD_SET if job.class.anway_retry_on
58
93
 
59
- pushed = Anway::Job.new('ActiveJob', [job.serialize.as_json], **options)
60
-
61
- job.provider_job_id = pushed.jid
62
-
63
- Anway.enqueue(pushed)
94
+ Anway::Job.new(
95
+ Anway::ActiveJobWrapper::EVENT,
96
+ [job.serialize.as_json],
97
+ **options
98
+ )
64
99
  end
65
100
  end
66
101
  end
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
@@ -10,6 +10,9 @@ module Anway
10
10
  DEFAULT_PORT = 7419
11
11
  FETCH_WAIT = 2
12
12
 
13
+ # The most jobs that one PUSHB takes.
14
+ MAX_BULK = 1000
15
+
13
16
  Endpoint = Data.define(:host, :port, :password, :tls)
14
17
 
15
18
  # The BEAT reply: the state (nil, "quiet", or "terminate"), and the thread
@@ -42,6 +45,20 @@ module Anway
42
45
  job.jid
43
46
  end
44
47
 
48
+ # Sends up to MAX_BULK jobs with one PUSHB. A refused job, such as a
49
+ # duplicate jid or a unique lock, does not stop the others. Returns the
50
+ # reason for each refused job by jid, or {} when all jobs are in. More
51
+ # than MAX_BULK jobs raise ArgumentError before the send.
52
+ def push_bulk(jobs)
53
+ jobs = jobs.to_a
54
+
55
+ raise ArgumentError, "a bulk push has at most #{MAX_BULK} jobs, not #{jobs.size}" if jobs.size > MAX_BULK
56
+
57
+ return {} if jobs.empty?
58
+
59
+ JSON.parse(call('PUSHB', jobs.map(&:to_h)))
60
+ end
61
+
45
62
  # Returns the next job, or nil when no job arrives in about 2 seconds.
46
63
  def fetch(*queues)
47
64
  reply = call('FETCH', queues.join(' '), wait: FETCH_WAIT)
@@ -106,8 +123,8 @@ module Anway
106
123
 
107
124
  # The command is "kill", "discard", "requeue", or "clear".
108
125
  # 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
126
+ def mutate(command, target, event: nil, jids: nil, regexp: nil)
127
+ filter = { jobtype: event, jids: jids, regexp: regexp }.compact
111
128
 
112
129
  call('MUTATE', { cmd: command, target: target, filter: filter })
113
130
 
@@ -126,19 +143,20 @@ module Anway
126
143
  Published.new(event: data['event'], jobs: data['jobs'], duplicate: data['duplicate'] == true)
127
144
  end
128
145
 
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)
146
+ # Each event of the topic makes one job in queue, with event as its job
147
+ # type. A second call with the same topic, queue, and event sets new retry
148
+ # and reserve_for.
149
+ def subscribe(topic, queue:, event:, retry: nil, reserve_for: nil)
132
150
  options = { retry: binding.local_variable_get(:retry), reserve_for: reserve_for }
133
151
 
134
- call('SUBSCRIBE', { topic: topic, queue: queue, jobtype: jobtype, **options }.compact)
152
+ call('SUBSCRIBE', { topic: topic, queue: queue, jobtype: event, **options }.compact)
135
153
 
136
154
  true
137
155
  end
138
156
 
139
157
  # A missing subscription is not an error.
140
- def unsubscribe(topic, queue:, jobtype:)
141
- call('UNSUBSCRIBE', { topic: topic, queue: queue, jobtype: jobtype })
158
+ def unsubscribe(topic, queue:, event:)
159
+ call('UNSUBSCRIBE', { topic: topic, queue: queue, jobtype: event })
142
160
 
143
161
  true
144
162
  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
@@ -42,6 +42,14 @@ module Anway
42
42
  job.jid
43
43
  end
44
44
 
45
+ # Keeps or runs each job as a single push does. No job is refused, so
46
+ # the result is {}.
47
+ def push_bulk(jobs)
48
+ jobs.each { |job| enqueue(job) }
49
+
50
+ {}
51
+ end
52
+
45
53
  # Keeps the event as the PUBLISH payload, with string keys. jobs is the
46
54
  # number of subscriptions in the job classes of the app. There is no
47
55
  # duplicate check.
@@ -70,7 +78,10 @@ module Anway
70
78
  def event_job(subscription, event, event_id)
71
79
  custom = (event['custom'] || {}).merge('topic' => subscription.topic, 'event' => event_id)
72
80
 
73
- Job.new(subscription.jobtype, event['args'], queue: subscription.queue, custom: custom)
81
+ Job.new(
82
+ subscription.event, event['args'],
83
+ queue: subscription.queue, retry: subscription.retry, reserve_for: subscription.reserve_for, custom: custom
84
+ )
74
85
  end
75
86
  end
76
87
  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.3.0'
4
+ VERSION = '0.5.0'
5
5
 
6
6
  # The anway server that the platform gems carry, and that CI tests against.
7
- SERVER_VERSION = '0.3.1'
7
+ SERVER_VERSION = '0.3.2'
8
8
  end
data/lib/anway/worker.rb CHANGED
@@ -6,29 +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
+ # WelcomeJob.perform_bulk([[1], [2], [3]])
15
18
  #
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
19
+ # The keys are the input contract (Anway::Options). The event is the job
20
+ # type on the wire, and the default is the class name. Each topic makes one
21
+ # subscription, which the worker sends when it starts.
25
22
  module Worker
26
23
  DEFAULT_BACKTRACE = 30
27
- SUBSCRIBE_OPTIONS = %i[retry reserve_for].freeze
28
24
 
29
- # One topic, queue, and job type. retry and reserve_for are the options of
25
+ # One topic, queue, and event. retry and reserve_for are the options of
30
26
  # each copy.
31
- Subscription = Data.define(:topic, :queue, :jobtype, :retry, :reserve_for)
27
+ Subscription = Data.define(:topic, :queue, :event, :retry, :reserve_for)
28
+
29
+ # A subclass does not inherit these keys.
30
+ OWN_KEYS = %i[event topics].freeze
32
31
 
33
32
  @registry = {}
34
33
  @lock = Mutex.new
@@ -40,10 +39,21 @@ module Anway
40
39
  register(base) if base.name
41
40
  end
42
41
 
43
- def register(klass, old_type: nil)
42
+ # Each event has one class. A class with the same name replaces the old
43
+ # one, as after a code reload. Another class with the same event raises
44
+ # ArgumentError.
45
+ def register(klass, old_event: nil)
46
+ event = klass.anway_options[:event]
47
+
44
48
  @lock.synchronize do
45
- @registry.delete(old_type) if old_type
46
- @registry[klass.job_type] = klass
49
+ current = @registry[event]
50
+
51
+ if current && !current.equal?(klass) && current.name != klass.name
52
+ raise ArgumentError, "event #{event.inspect} already has the class #{current.name}, so #{klass.name} cannot use it"
53
+ end
54
+
55
+ @registry.delete(old_event) if old_event && @registry[old_event].equal?(klass)
56
+ @registry[event] = klass
47
57
  end
48
58
  end
49
59
 
@@ -57,13 +67,13 @@ module Anway
57
67
  classes.flat_map(&:subscriptions).uniq
58
68
  end
59
69
 
60
- # Only registered classes run. The job type comes from the network, so it
70
+ # Only registered classes run. The event comes from the network, so it
61
71
  # never becomes a constant lookup. The lookup by the class name below
62
72
  # uses a registered name, and returns the newest class after a reload.
63
- def find(type)
64
- klass = @lock.synchronize { @registry[type] }
73
+ def find(event)
74
+ klass = @lock.synchronize { @registry[event] }
65
75
 
66
- raise UnknownJob, "no handler for job type #{type.inspect}" unless klass
76
+ raise UnknownJob, "no handler for event #{event.inspect}" unless klass
67
77
 
68
78
  klass.name ? Object.const_get(klass.name) : klass
69
79
  end
@@ -87,48 +97,44 @@ module Anway
87
97
  Worker.register(subclass) if subclass.name
88
98
  end
89
99
 
90
- def job_type(name = nil)
91
- return @job_type || self.name unless name
100
+ # With keys, adds one option set to the class. The keys are
101
+ # Anway::Options::DECLARATION, and an unknown key raises ArgumentError.
102
+ #
103
+ # Without keys, returns the options of the class: the options of the
104
+ # parent class without event and topics, then each set in call order.
105
+ # event and topics are always in the result.
106
+ def anway_options(**options)
107
+ return declared_options if options.empty?
92
108
 
93
- old_type = job_type
94
- @job_type = name
109
+ Options.check!(options, Options::DECLARATION)
95
110
 
96
- Worker.register(self, old_type: old_type)
97
- end
111
+ # Translates the set now, so that a bad value, such as an on_dead
112
+ # without an event, fails when the class loads.
113
+ Options.wire(options.except(*OWN_KEYS))
98
114
 
99
- def job_options(options = nil)
100
- inherited_options = superclass.respond_to?(:job_options) ? superclass.job_options : {}
115
+ options = options.merge(event: event_name(options[:event])) if options.key?(:event)
116
+ old_event = declared_options[:event]
101
117
 
102
- @job_options = (@job_options || {}).merge(options) if options
118
+ (@anway_option_sets ||= []) << options.freeze
103
119
 
104
- inherited_options.merge(@job_options || {})
105
- end
120
+ register_event(old_event) if options.key?(:event)
106
121
 
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
113
-
114
- raise ArgumentError, "unknown subscribe options: #{unknown.join(', ')}" if unknown.any?
115
-
116
- entry = { topic: topic.to_s, queue: queue&.to_s, **options }
117
-
118
- @subscriptions ||= []
119
- @subscriptions << entry unless @subscriptions.include?(entry)
122
+ declared_options
120
123
  end
121
124
 
125
+ # One subscription for each topic, with the event, queue, retry, and
126
+ # reserve_for of the class. Without a queue, the copies go to default.
122
127
  def subscriptions
123
- defaults = job_options
128
+ options = declared_options
129
+ queue = (options[:queue] || 'default').to_s
124
130
 
125
- (@subscriptions || []).map do |entry|
131
+ options[:topics].map do |topic|
126
132
  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])
133
+ topic: topic,
134
+ queue: queue,
135
+ event: options[:event],
136
+ retry: options[:retry],
137
+ reserve_for: options[:reserve_for]
132
138
  )
133
139
  end
134
140
  end
@@ -145,13 +151,79 @@ module Anway
145
151
  enqueue_with(args, { at: Time.now + seconds.to_f })
146
152
  end
147
153
 
148
- # Changes the options for one push: WelcomeJob.set(queue: 'low').perform_async(1)
154
+ # Changes the options for one push, with the push keys of
155
+ # Anway::Options::PUSH: WelcomeJob.set(queue: 'low').perform_async(1)
149
156
  def set(**options)
157
+ Options.check!(options, Options::PUSH)
158
+
150
159
  Setter.new(self, options)
151
160
  end
152
161
 
162
+ # Pushes one job for each item, and each item is the args of one job:
163
+ # WelcomeJob.perform_bulk([[1], [2], [3]]). All jobs are built before
164
+ # the first send, so a bad item sends no job. Each Client::MAX_BULK jobs
165
+ # go in one PUSHB. Returns the reason for each refused job by jid, or {}
166
+ # when all jobs are in. Inside a database transaction, the push waits
167
+ # for the commit and returns nil.
168
+ def perform_bulk(args_list)
169
+ bulk_with(args_list, {})
170
+ end
171
+
153
172
  def enqueue_with(args, options)
154
- Anway.enqueue(Job.new(job_type, args, backtrace: DEFAULT_BACKTRACE, **job_options, **options))
173
+ event, push = push_options(options)
174
+
175
+ Anway.enqueue(Job.new(event, args, **push))
176
+ end
177
+
178
+ def bulk_with(args_list, options)
179
+ raise ArgumentError, "perform_bulk needs an array of args: #{args_list.inspect}" unless args_list.is_a?(Array)
180
+
181
+ event, push = push_options(options)
182
+
183
+ jobs = args_list.map do |args|
184
+ Job.validate_args!(args)
185
+
186
+ Job.new(event, args, **push)
187
+ end
188
+
189
+ Anway.push_bulk(jobs)
190
+ end
191
+
192
+ private
193
+
194
+ # The event, and the push keys: the options of the class, then the
195
+ # options of the push, merge with the same rules as two anway_options
196
+ # calls.
197
+ def push_options(options)
198
+ declared = declared_options
199
+ push = Options.merge({ backtrace: DEFAULT_BACKTRACE }, declared.except(*OWN_KEYS), options)
200
+
201
+ [declared[:event], push]
202
+ end
203
+
204
+ def declared_options
205
+ parent = superclass.respond_to?(:anway_options) ? superclass.anway_options.except(*OWN_KEYS) : {}
206
+
207
+ Options.merge({ event: name, topics: [] }, parent, *@anway_option_sets).freeze
208
+ end
209
+
210
+ # A set with an event that another class has does not stay.
211
+ def register_event(old_event)
212
+ return unless name
213
+
214
+ Worker.register(self, old_event: old_event)
215
+ rescue ArgumentError
216
+ @anway_option_sets.pop
217
+
218
+ raise
219
+ end
220
+
221
+ def event_name(value)
222
+ event = value.to_s
223
+
224
+ raise ArgumentError, 'event must not be empty' if event.empty?
225
+
226
+ event
155
227
  end
156
228
  end
157
229
 
@@ -172,6 +244,10 @@ module Anway
172
244
  def perform_in(seconds, *args)
173
245
  @klass.enqueue_with(args, @options.merge(at: Time.now + seconds.to_f))
174
246
  end
247
+
248
+ def perform_bulk(args_list)
249
+ @klass.bulk_with(args_list, @options)
250
+ end
175
251
  end
176
252
  end
177
253
  end
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,25 @@ module Anway
55
57
  job.jid
56
58
  end
57
59
 
60
+ # Sends the jobs with one PUSHB for each Client::MAX_BULK jobs. Returns
61
+ # the reason for each refused job by jid, from all the sends, or {} when
62
+ # all jobs are in. Inside a database transaction, the push waits for the
63
+ # commit and returns nil.
64
+ def push_bulk(jobs)
65
+ jobs = jobs.to_a
66
+ testing = const_defined?(:Testing) ? Testing : nil
67
+
68
+ return testing.push_bulk(jobs) if testing&.mode
69
+
70
+ failures = nil
71
+
72
+ config.push_wrapper.call do
73
+ failures = jobs.each_slice(Client::MAX_BULK).reduce({}) { |merged, slice| merged.merge(client.push_bulk(slice)) }
74
+ end
75
+
76
+ failures
77
+ end
78
+
58
79
  # Sends one event to each subscription of the topic. Returns a
59
80
  # Client::Published. Inside a database transaction, the publish waits for
60
81
  # the commit and returns nil.
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.3.0
4
+ version: 0.5.0
5
5
  platform: aarch64-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