anway 0.2.0-aarch64-linux-gnu → 0.3.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: 00d2ba25d93d56baff866c500d623aea16e25c0e5865ff7fd1bd1959fa187e01
4
- data.tar.gz: 154ad758cbbecb423e0287e45dd8f8c6f85fb785a1ce52db03977923154ba496
3
+ metadata.gz: cd8fffae9cc66a49cf6e3c70c4728c7981f5f3c55c95debe65925ac4219ee904
4
+ data.tar.gz: 60a1ecb325d1e77b099ade2b90aaca1a23b6313e0553463c2c8606d52dce870f
5
5
  SHA512:
6
- metadata.gz: a708a68ae3114953a184ef0ebd970dc09b19133465efe83bd2d031b4e07054b66427226a0673f868753879c6fa3abaae85d0183307f2ad550a10a50d677e2dc8
7
- data.tar.gz: 452cf04d71b31a31de2057100f55625e99d91a9ed56c0758e32f4f11b522227b5c3efbc81d44e08ffb6489c58565de8b6cf45b2c5f76ea36f213837ed86a6237
6
+ metadata.gz: 332bf304ee9a86cd4d0ed19af50c4afcded83cfa8faee7b65ab75dd7030727108e2829b935ac8fdc58c3aeb99bb36bdb8b6abcea3fcfb188f6223348b71f302d
7
+ data.tar.gz: 262dae241d8e14c067ca4efc340c749eb951439140d2625092b66f09b99476a994207851125bad0dd711cf67c29ec3967278a3246d09c772a1e06f916dc33f15
data/README.md CHANGED
@@ -122,6 +122,41 @@ To send a job that a worker in any language runs:
122
122
  Anway.push('image.resize', [42], queue: 'media')
123
123
  ```
124
124
 
125
+ ## Topics
126
+
127
+ 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.
128
+
129
+ ```ruby
130
+ class BroadcastMessage
131
+ include Anway::Worker
132
+
133
+ subscribe 'chat.message', queue: 'realtime'
134
+
135
+ def perform(message)
136
+ # ...
137
+ end
138
+ end
139
+
140
+ Anway.publish('chat.message', [{ 'room' => 'general', 'body' => 'hi' }], id: 'msg-42')
141
+ # => #<data Anway::Client::Published event="msg-42", jobs=3, duplicate=false>
142
+ ```
143
+
144
+ - `subscribe` uses the `job_type` of the class. `queue`, `retry`, and `reserve_for` have the `job_options` of the class as defaults.
145
+ - 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
+ - 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
+ - The server adds `topic` and `event` to `custom` of each copy. Use `job.custom['event']` to make the handler idempotent.
148
+ - An event with no subscription goes to the Dead set, and the reply has `jobs: 0`.
149
+
150
+ The client has the same commands:
151
+
152
+ ```ruby
153
+ 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')
156
+ ```
157
+
158
+ [docs/topics.md](docs/topics.md) explains the chat example with three apps, the options, the tests, and problems.
159
+
125
160
  ## Rails
126
161
 
127
162
  ```ruby
@@ -160,7 +195,7 @@ config.enable_reloading = ENV["ANWAY_WORKER"].blank?
160
195
 
161
196
  | Flag | Default | Purpose |
162
197
  |---|---|---|
163
- | `-q`, `--queues` | Queues of the job classes, and `default` | Queues in order, as `name` or `name:weight` |
198
+ | `-q`, `--queues` | Queues of the job classes and of their subscriptions, and `default` | Queues in order, as `name` or `name:weight` |
164
199
  | `-c`, `--concurrency` | `10` | Job threads |
165
200
  | `-t`, `--timeout` | `25` | Seconds for jobs to finish at a stop |
166
201
  | `-r`, `--require` | `config/environment.rb` | File that loads the jobs. Required outside Rails. |
@@ -229,9 +264,14 @@ WelcomeJob.perform_async('a@b.com')
229
264
  Anway::Testing.jobs.size
230
265
  Anway::Testing.drain
231
266
 
267
+ Anway.publish('chat.message', [{ 'body' => 'hi' }])
268
+ Anway::Testing.events.last['topic']
269
+
232
270
  Anway::Testing.inline!
233
271
  ```
234
272
 
273
+ In inline mode, `Anway.publish` runs one copy in each job class of the app that subscribes to the topic.
274
+
235
275
  ## Client
236
276
 
237
277
  `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.
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
208
  names = Worker.classes.map { |klass| klass.job_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)
@@ -110,6 +114,35 @@ module Anway
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 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)
132
+ options = { retry: binding.local_variable_get(:retry), reserve_for: reserve_for }
133
+
134
+ call('SUBSCRIBE', { topic: topic, queue: queue, jobtype: jobtype, **options }.compact)
135
+
136
+ true
137
+ end
138
+
139
+ # A missing subscription is not an error.
140
+ def unsubscribe(topic, queue:, jobtype:)
141
+ call('UNSUBSCRIBE', { topic: topic, queue: queue, jobtype: jobtype })
142
+
143
+ true
144
+ end
145
+
113
146
  def batch_new(success: nil, complete: nil, parent_bid: nil, description: nil)
114
147
  definition = {
115
148
  success: success&.to_h, complete: complete&.to_h, parent_bid: parent_bid, description: description
data/lib/anway/job.rb CHANGED
@@ -10,6 +10,31 @@ module Anway
10
10
 
11
11
  attr_accessor :jid, :type, :args, :custom, *ATTRIBUTES.map(&:to_sym)
12
12
 
13
+ # Other languages read job args, so only JSON types with string hash keys
14
+ # are valid. Topic events use the same rule.
15
+ def self.validate_args!(args)
16
+ raise ArgumentError, "job args must be an array: #{args.inspect}" unless args.is_a?(Array)
17
+
18
+ validate_json!(args)
19
+ end
20
+
21
+ def self.validate_json!(value)
22
+ case value
23
+ when nil, true, false, String, Integer, Float
24
+ nil
25
+ when Array
26
+ value.each { |item| validate_json!(item) }
27
+ when Hash
28
+ value.each do |key, item|
29
+ raise ArgumentError, "job hash keys must be strings: #{key.inspect}" unless key.is_a?(String)
30
+
31
+ validate_json!(item)
32
+ end
33
+ else
34
+ raise ArgumentError, "job args must be JSON types: #{value.inspect}"
35
+ end
36
+ end
37
+
13
38
  def self.from_hash(hash)
14
39
  job = allocate
15
40
 
@@ -25,7 +50,7 @@ module Anway
25
50
 
26
51
  # Options: queue, retry, reserve_for, backtrace, at, custom, jid.
27
52
  def initialize(type, args = [], **options)
28
- validate_json!(args)
53
+ self.class.validate_json!(args)
29
54
 
30
55
  @jid = options[:jid] || SecureRandom.hex(12)
31
56
  @type = type
@@ -57,25 +82,5 @@ module Anway
57
82
  **ATTRIBUTES.to_h { |name| [name, public_send(name)] }
58
83
  }.compact
59
84
  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
85
  end
81
86
  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
+ jobtype: subscription.jobtype,
110
+ retry: subscription.retry,
111
+ reserve_for: subscription.reserve_for
112
+ )
113
+
114
+ @logger.info("anway subscribed topic=#{subscription.topic} queue=#{subscription.queue} jobtype=#{subscription.jobtype}")
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
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,36 @@ 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(subscription.jobtype, event['args'], queue: subscription.queue, custom: custom)
74
+ end
46
75
  end
47
76
  end
48
77
  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.3.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
@@ -12,8 +12,23 @@ module Anway
12
12
  # end
13
13
  #
14
14
  # WelcomeJob.perform_async(42)
15
+ #
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
15
25
  module Worker
16
26
  DEFAULT_BACKTRACE = 30
27
+ SUBSCRIBE_OPTIONS = %i[retry reserve_for].freeze
28
+
29
+ # One topic, queue, and job type. retry and reserve_for are the options of
30
+ # each copy.
31
+ Subscription = Data.define(:topic, :queue, :jobtype, :retry, :reserve_for)
17
32
 
18
33
  @registry = {}
19
34
  @lock = Mutex.new
@@ -36,6 +51,12 @@ module Anway
36
51
  @lock.synchronize { @registry.values }
37
52
  end
38
53
 
54
+ # The subscriptions of all registered classes. A worker sends them with
55
+ # SUBSCRIBE when it starts.
56
+ def subscriptions
57
+ classes.flat_map(&:subscriptions).uniq
58
+ end
59
+
39
60
  # Only registered classes run. The job type comes from the network, so it
40
61
  # never becomes a constant lookup. The lookup by the class name below
41
62
  # uses a registered name, and returns the newest class after a reload.
@@ -83,6 +104,35 @@ module Anway
83
104
  inherited_options.merge(@job_options || {})
84
105
  end
85
106
 
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)
120
+ end
121
+
122
+ def subscriptions
123
+ defaults = job_options
124
+
125
+ (@subscriptions || []).map do |entry|
126
+ 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
+ )
133
+ end
134
+ end
135
+
86
136
  def perform_async(*args)
87
137
  enqueue_with(args, {})
88
138
  end
data/lib/anway.rb CHANGED
@@ -55,6 +55,23 @@ module Anway
55
55
  job.jid
56
56
  end
57
57
 
58
+ # Sends one event to each subscription of the topic. Returns a
59
+ # Client::Published. Inside a database transaction, the publish waits for
60
+ # the commit and returns nil.
61
+ def publish(topic, args = [], **options)
62
+ Job.validate_args!(args)
63
+
64
+ testing = const_defined?(:Testing) ? Testing : nil
65
+
66
+ return testing.publish(topic, args, **options) if testing&.mode
67
+
68
+ published = nil
69
+
70
+ config.push_wrapper.call { published = client.publish(topic, args, **options) }
71
+
72
+ published
73
+ end
74
+
58
75
  def reset!
59
76
  @lock.synchronize do
60
77
  @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.3.0
5
5
  platform: aarch64-linux-gnu
6
6
  authors:
7
7
  - Thadeu