anway 0.1.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 334855b00a1b57308782f76328e3d72d2339169713022fe5cc5421961a4acfc9
4
- data.tar.gz: d63ddc5085f28acc3d00174f77632f3f2a95a6c827b4d901629496ccfc0251a0
3
+ metadata.gz: 4d25840660dc0bce4fc2e5ead99ff4fe76499b803fd088ee20fc81c34acdf705
4
+ data.tar.gz: ed64d40cd02daca157f38c31c1d1b694523e29eaf39eabd472c3fa35730dc11a
5
5
  SHA512:
6
- metadata.gz: 56e3d4d168da46531849c13c713e85483d624336fd30f42eace765adbbce119c8c97e09072375e5373410750e5cded72a315eda6d6b917bb137ab57a887aa09a
7
- data.tar.gz: a97fb1df5b38f972d9165fbc9eee86045abec79b5ec543684cb008dbee60f1ec0c222e7a39d7ea99ffdf3b72c80687f1747f79c5f9ebf70d76c9b0be04486bf2
6
+ metadata.gz: dbd8670d2579adc51f702ae65d768bf554c66d1cb28b4e9c2265521c604060071a90c74f90170a387bce24bc3e34fba1eff8c0a88a43ea68efb553b768d2459c
7
+ data.tar.gz: f01d5117e68fc4d3527bd17ae421dbcebd61b42a35121be8e8c22473c294fa0f0f99e82accdc336e5b62a9f69d6bbe85c99884a5d21b3586bae133e83cfb317d
data/README.md CHANGED
@@ -1,12 +1,96 @@
1
+ <p>
2
+ <a href="https://github.com/thadeu/anway">
3
+ <picture>
4
+ <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/thadeu/anway/main/brand/png/lockup-on-dark.png">
5
+ <img src="https://raw.githubusercontent.com/thadeu/anway/main/brand/png/lockup-on-light.png" alt="Anway" width="320">
6
+ </picture>
7
+ </a>
8
+ </p>
9
+
1
10
  # anway-ruby
2
11
 
3
12
  Ruby and Rails client and worker for [Anway](https://github.com/thadeu/anway). Ruby 3.4 or later. Rails 8.1 for the Rails integration.
4
13
 
14
+ ## Install in Rails
15
+
16
+ ```bash
17
+ bundle add anway
18
+ bin/rails generate anway:install
19
+ bin/dev
20
+ ```
21
+
22
+ That is all: no Redis and no migrations. The gem for each platform carries the Anway server, and `bin/dev` starts it with Puma. Add `--active-job` to the installer to use Anway as the Active Job adapter. Without it, Active Job stays as it is, and `include Anway::Worker` works in any class.
23
+
24
+ The installer writes `config/anway.yml` and `bin/anway`, adds `plugin :anway` to `config/puma.rb`, and adds the console mount to `config/routes.rb` as a comment.
25
+
26
+ `anway-demo/shop` is a full example app.
27
+
28
+ ## Server: embedded or apart
29
+
30
+ Without a `url`, the app runs the Anway server itself: the server is **embedded**. With `url` in `config/anway.yml`, or with `ANWAY_URL`, the app uses a server that runs apart, and it runs only workers. Use cases:
31
+
32
+ 1. A Rails app is the server, and runs its own workers and workers from other apps and languages.
33
+ 2. A Rails app runs only workers, and the server runs apart.
34
+
35
+ ```yaml
36
+ # config/anway.yml
37
+ queues: [default]
38
+ concurrency: 10
39
+
40
+ development:
41
+ server:
42
+ web: 127.0.0.1:7420 # optional: the HTTP API for the web console
43
+ web_token: dev
44
+
45
+ production:
46
+ url: <%= ENV["ANWAY_URL"] %>
47
+ ```
48
+
49
+ | `server` key | Default | Purpose |
50
+ |---|---|---|
51
+ | `mode` | `embedded`, or `external` with a url | Set it only to override the url rule. `ANWAY_SERVER` also sets it. |
52
+ | `bind` | `127.0.0.1:7419` | Address of the embedded server. Use `0.0.0.0:7419` and a `password` for workers on other hosts. |
53
+ | `data` | `storage/anway` | Data folder of the embedded server |
54
+ | `password` | None | Server password |
55
+ | `web`, `web_token` | Off | HTTP API address and token, for the web console |
56
+
57
+ Run one server for each deployment. On more than one host, run `bin/anway server` once, or the `ghcr.io/thadeu/anway` image, and set `ANWAY_URL` on every host. Two embedded servers have two separate sets of queues.
58
+
59
+ `ANWAY_SERVER_PATH` names another server binary. The gem for the `ruby` platform has no server, so it needs `ANWAY_SERVER_PATH` or a url.
60
+
61
+ The server address comes from the settings, then from `ANWAY_URL`, for example `tcp://:password@localhost:7419`. Use `tcp+tls://` for TLS. `Anway.config.url` in an initializer overrides both.
62
+
63
+ ## Console
64
+
5
65
  ```ruby
6
- gem 'anway'
66
+ # config/routes.rb
67
+ authenticate :user, ->(user) { user.admin? } do
68
+ mount Anway::Web => "/anway"
69
+ end
70
+ ```
71
+
72
+ ```yaml
73
+ # config/anway.yml
74
+ console:
75
+ path: /path/to/anway-webui
7
76
  ```
8
77
 
9
- The server address comes from `ANWAY_URL`, for example `tcp://:password@localhost:7419`. Use `tcp+tls://` for TLS.
78
+ `console.path`, or `ANWAY_CONSOLE_PATH`, names the console binary. `bin/anway`, and so the Puma plugin, then starts the console next to the server, on `127.0.0.1:7421`. With an embedded server, it also opens the server API on `127.0.0.1:7420`, with a random token that only these two processes know.
79
+
80
+ `Anway::Web` proxies the mount path to the console:
81
+
82
+ - It keeps the session cookie and `Authorization` in the app.
83
+ - It sends the mount path in `X-Forwarded-Prefix`, so the console links and redirects stay under it.
84
+ - The console accepts form posts only from its own pages, so a form on another site cannot change jobs with an admin's session.
85
+
86
+ | `console` key | Default | Purpose |
87
+ |---|---|---|
88
+ | `path` | None | Console binary. Without it, no console starts. |
89
+ | `bind` | `127.0.0.1:7421` | Console address, and where `Anway::Web` finds it |
90
+ | `api` | The API of the embedded server | Server API that the console reads, for a server that runs apart |
91
+ | `token` | The server `web_token` | Token for that API |
92
+
93
+ `bin/anway console` runs only the console. Mount `Anway::Web` only in a route that checks the user: the console can kill and delete jobs.
10
94
 
11
95
  ## Worker
12
96
 
@@ -38,6 +122,41 @@ To send a job that a worker in any language runs:
38
122
  Anway.push('image.resize', [42], queue: 'media')
39
123
  ```
40
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
+
41
160
  ## Rails
42
161
 
43
162
  ```ruby
@@ -54,18 +173,37 @@ Tasks in `recurring.yml` and jobs that wait in Solid Queue do not move automatic
54
173
  ## Process
55
174
 
56
175
  ```bash
57
- bundle exec anway -q critical,mailers,default -c 10
176
+ bundle exec anway # the embedded server when there is no url, and workers
177
+ bundle exec anway server # only the server
178
+ bundle exec anway console # only the console
179
+ bundle exec anway worker -q mailers # only workers
180
+ bundle exec anway -C config/anway.yml -q critical,mailers,default -c 10
181
+ ```
182
+
183
+ ### Puma
184
+
185
+ `plugin :anway` in `config/puma.rb` runs `bin/anway` next to Puma, and stops it with Puma. `ANWAY_IN_PUMA` turns it on or off, as `SOLID_QUEUE_IN_PUMA` does. Without it, the plugin runs only in development. If `bin/anway` stops by itself, Puma stops too, so a broken worker is not hidden.
186
+
187
+ The worker process sets `ANWAY_WORKER=1` before it loads the app.
188
+
189
+ With Solid Cable 4.1, a code reload in one job thread can deadlock with a broadcast from another job thread. To avoid it, turn off reloading in the worker process in development, and run `bin/rails restart` after a change to a job:
190
+
191
+ ```ruby
192
+ # config/environments/development.rb
193
+ config.enable_reloading = ENV["ANWAY_WORKER"].blank?
58
194
  ```
59
195
 
60
196
  | Flag | Default | Purpose |
61
197
  |---|---|---|
62
- | `-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` |
63
199
  | `-c`, `--concurrency` | `10` | Job threads |
64
200
  | `-t`, `--timeout` | `25` | Seconds for jobs to finish at a stop |
65
201
  | `-r`, `--require` | `config/environment.rb` | File that loads the jobs. Required outside Rails. |
66
202
  | `-C`, `--config` | `config/anway.yml` | YAML config file |
67
203
  | `-e`, `--environment` | `RAILS_ENV`, `APP_ENV` | Environment section of the YAML file |
68
204
  | `-l`, `--label` | None | Worker label |
205
+ | `-g`, `--tag` | The app folder | Name of the app in the console |
206
+ | `-a`, `--autoscale` | Off | Turn on autoscale, up to this many threads |
69
207
  | `-v`, `--verbose` | Off | Debug logs |
70
208
  | `-V`, `--version` | | Print the version |
71
209
 
@@ -83,6 +221,27 @@ production:
83
221
 
84
222
  Flags have priority over the environment section, and the environment section has priority over top-level keys. A list without weights uses strict order.
85
223
 
224
+ The console shows each worker process as `hostname:pid`, with its tag, queues, threads, and start time, as Sidekiq does. The hostname is the machine name, and the tag is the app folder (`shop` for `~/code/shop`). To change them:
225
+
226
+ ```yaml
227
+ hostname: worker.1 # or ANWAY_HOSTNAME, for example from the container or dyno name
228
+ tag: shop # or ANWAY_TAG, or --tag
229
+ ```
230
+
231
+ `ANWAY_HOSTNAME` and `ANWAY_TAG` have priority over the file.
232
+
233
+ ### Threads and autoscale
234
+
235
+ The console and the server API can change the threads of a running worker. With autoscale, the server adds threads while jobs wait and removes them when the load drops:
236
+
237
+ ```yaml
238
+ concurrency: 10 # the start count, and the autoscale min
239
+ autoscale:
240
+ max: 40
241
+ ```
242
+
243
+ The worker never runs more threads than its ActiveRecord pool, so make the pool of the worker process as large as `max`. [docs/threads-and-autoscale.md](docs/threads-and-autoscale.md) explains the setup, the console, the API, and problems.
244
+
86
245
  | Signal | Effect |
87
246
  |---|---|
88
247
  | `TERM`, `INT` | Stop |
@@ -105,9 +264,14 @@ WelcomeJob.perform_async('a@b.com')
105
264
  Anway::Testing.jobs.size
106
265
  Anway::Testing.drain
107
266
 
267
+ Anway.publish('chat.message', [{ 'body' => 'hi' }])
268
+ Anway::Testing.events.last['topic']
269
+
108
270
  Anway::Testing.inline!
109
271
  ```
110
272
 
273
+ In inline mode, `Anway.publish` runs one copy in each job class of the app that subscribes to the topic.
274
+
111
275
  ## Client
112
276
 
113
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.
@@ -48,8 +48,10 @@ module ActiveJob
48
48
 
49
49
  # Each push has a new id. A retry_on attempt keeps its job_id while the
50
50
  # first attempt is still reserved, and the server rejects a repeated id.
51
+ # custom.wrapped names the job class, so that the console shows it, as
52
+ # Sidekiq does.
51
53
  def push(job, options)
52
- options = options.merge(queue: job.queue_name, backtrace: BACKTRACE)
54
+ options = options.merge(queue: job.queue_name, backtrace: BACKTRACE, custom: { 'wrapped' => job.class.name })
53
55
 
54
56
  # retry_on owns the attempts, so its final error goes to the dead set.
55
57
  options[:retry] = DEAD_SET if job.class.anway_retry_on
data/lib/anway/cli.rb CHANGED
@@ -1,8 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require 'erb'
4
3
  require 'optparse'
5
- require 'yaml'
6
4
 
7
5
  # The Railtie registers only when Rails loads before the gem.
8
6
  begin
@@ -14,13 +12,17 @@ end
14
12
  require 'anway'
15
13
 
16
14
  module Anway
17
- # bundle exec anway -q critical,mailers:2,default -c 10
15
+ # bundle exec anway the embedded server when config/anway.yml has no url, the
16
+ # console when it sets console.path, and workers
17
+ # bundle exec anway server only the server
18
+ # bundle exec anway console only the console
19
+ # bundle exec anway worker -q mail only workers
18
20
  class CLI
19
21
  EXIT_OK = 0
20
22
  EXIT_BOOT = 1
21
23
  EXIT_USAGE = 2
22
24
  DEFAULTS = { concurrency: 10, timeout: 25, labels: [] }.freeze
23
- DEFAULT_CONFIG = 'config/anway.yml'
25
+ COMMANDS = %w[server console worker].freeze
24
26
  RAILS_ENTRY = 'config/environment.rb'
25
27
 
26
28
  def initialize(argv)
@@ -34,7 +36,16 @@ module Anway
34
36
  return EXIT_OK if parse == :done
35
37
 
36
38
  boot
37
- start
39
+
40
+ return Server.new(@settings).exec if @command == 'server'
41
+ return Console.new(@settings).exec if @command == 'console'
42
+
43
+ # The app can tell that it runs in a worker process, for example to turn
44
+ # off code reloading.
45
+ ENV['ANWAY_WORKER'] = '1'
46
+
47
+ load_app
48
+ run_workers
38
49
  EXIT_OK
39
50
  rescue OptionParser::ParseError, ArgumentError => e
40
51
  warn("anway: #{e.message}")
@@ -51,6 +62,8 @@ module Anway
51
62
  def parse
52
63
  parser.parse!(@argv)
53
64
 
65
+ @command = @argv.shift if COMMANDS.include?(@argv.first)
66
+
54
67
  raise ArgumentError, "unexpected argument: #{@argv.first}" unless @argv.empty?
55
68
 
56
69
  @flags[:done] ? :done : nil
@@ -58,7 +71,7 @@ module Anway
58
71
 
59
72
  def parser
60
73
  OptionParser.new do |options|
61
- options.banner = 'Usage: anway [options]'
74
+ options.banner = 'Usage: anway [server|console|worker] [options]'
62
75
 
63
76
  options.on('-q', '--queues LIST', 'Queues in order, as name or name:weight') do |list|
64
77
  @flags[:queues] = list.split(',').map { |entry| entry.split(':') }
@@ -70,6 +83,8 @@ module Anway
70
83
  options.on('-C', '--config PATH', 'YAML config file') { |path| @flags[:config] = path }
71
84
  options.on('-e', '--environment NAME', 'Environment name') { |name| @flags[:environment] = name }
72
85
  options.on('-l', '--label NAME', 'Worker label') { |name| (@flags[:labels] ||= []) << name }
86
+ options.on('-g', '--tag NAME', 'Name of the app in the console') { |name| @flags[:tag] = name }
87
+ options.on('-a', '--autoscale MAX', Integer, 'Turn on autoscale, up to MAX threads') { |n| @flags[:autoscale] = { max: n } }
73
88
  options.on('-v', '--verbose', 'Debug logs') { @flags[:verbose] = true }
74
89
 
75
90
  options.on('-V', '--version', 'Print the version') do
@@ -92,29 +107,27 @@ module Anway
92
107
  ENV['RAILS_ENV'] ||= environment
93
108
  ENV['APP_ENV'] ||= environment
94
109
 
95
- @options = DEFAULTS.merge(file_options(environment)).merge(@flags)
96
-
97
- load_app
110
+ @settings = Settings.load(path: @flags[:config], environment: environment)
111
+ @options = DEFAULTS.merge(@settings.worker_options).merge(@flags)
98
112
 
99
113
  Anway.config.logger.level = Logger::DEBUG if @options[:verbose]
100
-
101
- check_database_pool
102
114
  end
103
115
 
104
- def file_options(environment)
105
- path = @flags[:config] || DEFAULT_CONFIG
116
+ # The app loads first, so that a usage error never leaves a server running.
117
+ # The console stops first, and the server last, so jobs can still report.
118
+ def run_workers
119
+ server = Server.new(@settings) if @command.nil? && @settings.embedded?
120
+ console = Console.new(@settings) if @command.nil? && @settings.console?
106
121
 
107
- unless File.exist?(path)
108
- raise ArgumentError, "config file not found: #{path}" if @flags[:config]
122
+ begin
123
+ server&.start
124
+ console&.start
109
125
 
110
- return {}
126
+ start
127
+ ensure
128
+ console&.stop
129
+ server&.stop
111
130
  end
112
-
113
- content = YAML.safe_load(ERB.new(File.read(path)).result, aliases: true) || {}
114
- section = content.fetch(environment, {})
115
- common = content.reject { |_key, value| value.is_a?(Hash) }
116
-
117
- common.merge(section).transform_keys(&:to_sym)
118
131
  end
119
132
 
120
133
  def load_app
@@ -126,30 +139,59 @@ module Anway
126
139
  require File.expand_path(path)
127
140
 
128
141
  Rails.application.eager_load! if defined?(Rails) && Rails.application
142
+
143
+ check_database_pool
144
+ end
145
+
146
+ # Each job thread can hold a database connection, so the pool size is the
147
+ # most threads that the worker runs. Rails connects at the first query, but
148
+ # the pool exists after boot.
149
+ def database_pool
150
+ return nil unless defined?(ActiveRecord::Base)
151
+
152
+ ActiveRecord::Base.connection_pool.size
153
+ rescue StandardError
154
+ nil
129
155
  end
130
156
 
131
157
  def check_database_pool
132
- return unless defined?(ActiveRecord::Base) && ActiveRecord::Base.connected?
158
+ size = database_pool
133
159
 
134
- size = ActiveRecord::Base.connection_pool.size
160
+ return unless size
135
161
 
136
- return if size >= @options[:concurrency]
162
+ logger = Anway.config.logger
163
+ max = @options.dig(:autoscale, :max)
137
164
 
138
- Anway.config.logger.warn("database pool #{size} is smaller than concurrency #{@options[:concurrency]}")
165
+ logger.warn("database pool #{size} is smaller than concurrency #{@options[:concurrency]}") if size < @options[:concurrency]
166
+ logger.warn("autoscale max #{max} is above the database pool #{size}, so the worker runs at most #{size} threads. Raise pool in config/database.yml.") if max && max > size
139
167
  end
140
168
 
141
169
  def start
142
170
  runner = Runner.new(
171
+ url: Anway.config.url || @settings.client_url,
143
172
  queues: queues,
144
173
  concurrency: @options[:concurrency],
145
174
  timeout: @options[:timeout],
146
- labels: @options[:labels]
175
+ labels: @options[:labels],
176
+ hostname: @options[:hostname],
177
+ tag: @options[:tag] || default_tag,
178
+ autoscale: @options[:autoscale],
179
+ limit: database_pool
147
180
  )
148
181
 
149
182
  trap_signals(runner)
150
183
  runner.run
151
184
  end
152
185
 
186
+ # The app folder, as Sidekiq does. A Capistrano release folder has a
187
+ # number as its name, so the folder above it names the app.
188
+ def default_tag
189
+ root = defined?(Rails) && Rails.respond_to?(:root) && Rails.root ? Rails.root.to_s : Dir.pwd
190
+ name = File.basename(root)
191
+
192
+ name.match?(/\A\d+\z/) ? File.basename(File.dirname(File.dirname(root))) : name
193
+ end
194
+
153
195
  def trap_signals(runner)
154
196
  %w[TERM INT].each { |name| Signal.trap(name) { runner.stop } }
155
197
 
@@ -157,11 +199,14 @@ module Anway
157
199
  Signal.trap('TTIN') { runner.dump }
158
200
  end
159
201
 
160
- # 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.
161
205
  def queues
162
206
  return @options[:queues] if @options[:queues]
163
207
 
164
208
  names = Worker.classes.map { |klass| klass.job_options[:queue]&.to_s }
209
+ names.concat(Worker.subscriptions.map(&:queue))
165
210
  names.concat(active_job_queues)
166
211
 
167
212
  [*names.compact, 'default'].uniq
data/lib/anway/client.rb CHANGED
@@ -12,14 +12,22 @@ module Anway
12
12
 
13
13
  Endpoint = Data.define(:host, :port, :password, :tls)
14
14
 
15
+ # The BEAT reply: the state (nil, "quiet", or "terminate"), and the thread
16
+ # count that the server wants, or nil.
17
+ Heartbeat = Data.define(:state, :concurrency)
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
+
15
23
  # A blank URL uses ANWAY_URL, then the local default.
16
- def initialize(url = nil, pool_size: 8, timeout: 10, tls: nil, wid: nil, labels: [])
24
+ def initialize(url = nil, pool_size: 8, timeout: 10, tls: nil, wid: nil, labels: [], identity: {})
17
25
  @endpoint = parse_url(url || ENV.fetch('ANWAY_URL', nil) || DEFAULT_URL)
18
26
  @timeout = timeout
19
27
  @wid = wid
20
28
 
21
29
  @pool = Pool.new(pool_size) do
22
- Connection.new(@endpoint, timeout: timeout, tls: tls, wid: wid, labels: labels)
30
+ Connection.new(@endpoint, timeout: timeout, tls: tls, wid: wid, labels: labels, identity: identity)
23
31
  end
24
32
  end
25
33
 
@@ -55,9 +63,25 @@ module Anway
55
63
 
56
64
  # Returns nil, "quiet", or "terminate".
57
65
  def beat(current_state = nil)
58
- reply = call('BEAT', { wid: @wid, current_state: current_state }.compact)
66
+ heartbeat(current_state).state
67
+ end
68
+
69
+ # Sends BEAT with the thread count of the worker, so the server can ask for
70
+ # another count. Returns a Heartbeat.
71
+ def heartbeat(current_state = nil, concurrency: nil)
72
+ reply = call('BEAT', { wid: @wid, current_state: current_state, concurrency: concurrency }.compact)
73
+
74
+ return Heartbeat.new(state: nil, concurrency: nil) if reply == 'OK'
75
+
76
+ data = JSON.parse(reply)
59
77
 
60
- reply == 'OK' ? nil : JSON.parse(reply)['state']
78
+ Heartbeat.new(state: data['state'], concurrency: data['concurrency'])
79
+ end
80
+
81
+ # Lets the client hold size connections at once, for a worker that adds
82
+ # threads.
83
+ def grow_pool(size)
84
+ @pool.grow(size)
61
85
  end
62
86
 
63
87
  def info
@@ -90,6 +114,35 @@ module Anway
90
114
  true
91
115
  end
92
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
+
93
146
  def batch_new(success: nil, complete: nil, parent_bid: nil, description: nil)
94
147
  definition = {
95
148
  success: success&.to_h, complete: complete&.to_h, parent_bid: parent_bid, description: description
@@ -4,11 +4,12 @@ require 'logger'
4
4
 
5
5
  module Anway
6
6
  class Configuration
7
- attr_accessor :url, :pool_size, :timeout, :tls, :logger, :push_wrapper, :reloader
7
+ attr_accessor :url, :console_url, :pool_size, :timeout, :tls, :logger, :push_wrapper, :reloader
8
8
  attr_reader :middleware, :error_handlers
9
9
 
10
10
  def initialize
11
11
  @url = nil
12
+ @console_url = nil
12
13
  @pool_size = 8
13
14
  @timeout = 10
14
15
  @tls = nil
@@ -12,12 +12,14 @@ module Anway
12
12
  PROTOCOL_VERSION = 2
13
13
  READ_SIZE = 16_384
14
14
 
15
- def initialize(endpoint, timeout:, tls: nil, wid: nil, labels: [])
15
+ # identity holds more HELLO fields of a worker, such as tag, queues, and
16
+ # concurrency. Its hostname replaces the machine name.
17
+ def initialize(endpoint, timeout:, tls: nil, wid: nil, labels: [], identity: {})
16
18
  @timeout = timeout
17
19
  @buffer = String.new(encoding: Encoding::BINARY)
18
20
  @io = open_socket(endpoint, tls)
19
21
 
20
- handshake(endpoint, wid, labels)
22
+ handshake(endpoint, wid, labels, identity)
21
23
  rescue StandardError
22
24
  close
23
25
 
@@ -82,7 +84,7 @@ module Anway
82
84
  end
83
85
  end
84
86
 
85
- def handshake(endpoint, wid, labels)
87
+ def handshake(endpoint, wid, labels, identity)
86
88
  deadline = monotonic + @timeout
87
89
  greeting = JSON.parse(read_reply(deadline).delete_prefix('HI '))
88
90
 
@@ -95,7 +97,7 @@ module Anway
95
97
  end
96
98
 
97
99
  if wid
98
- hello.merge!(wid: wid, hostname: Socket.gethostname, pid: Process.pid, labels: labels)
100
+ hello.merge!(wid: wid, hostname: Socket.gethostname, pid: Process.pid, labels: labels, **identity.compact)
99
101
  end
100
102
 
101
103
  command('HELLO', hello)
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Anway
4
+ # Console runs the web console binary, which reads the HTTP API of the
5
+ # server. `mount Anway::Web` serves it inside the app. console.path in
6
+ # config/anway.yml, or ANWAY_CONSOLE_PATH, names the binary.
7
+ class Console < Daemon
8
+ private
9
+
10
+ def name
11
+ 'console'
12
+ end
13
+
14
+ def address
15
+ @settings.console_bind
16
+ end
17
+
18
+ def env
19
+ @settings.console_env
20
+ end
21
+
22
+ def executable
23
+ path = @settings.console_path
24
+
25
+ raise Error, 'the console has no binary. Set console.path in config/anway.yml, or ANWAY_CONSOLE_PATH.' unless path
26
+ raise Error, "the console binary is not executable: #{path}" unless File.executable?(path)
27
+
28
+ path
29
+ end
30
+
31
+ def announce
32
+ @logger.info("anway: console on #{@settings.console_url}. Mount Anway::Web in config/routes.rb to open it in the app.")
33
+ end
34
+ end
35
+ end