anway 0.2.0-x86_64-darwin
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 +7 -0
- data/LICENSE +22 -0
- data/README.md +270 -0
- data/exe/anway +6 -0
- data/lib/active_job/queue_adapters/anway_adapter.rb +67 -0
- data/lib/anway/cli.rb +218 -0
- data/lib/anway/client.rb +171 -0
- data/lib/anway/configuration.rb +33 -0
- data/lib/anway/connection.rb +197 -0
- data/lib/anway/console.rb +35 -0
- data/lib/anway/daemon.rb +115 -0
- data/lib/anway/errors.rb +34 -0
- data/lib/anway/executor.rb +29 -0
- data/lib/anway/job.rb +81 -0
- data/lib/anway/pool.rb +97 -0
- data/lib/anway/puma/plugin.rb +34 -0
- data/lib/anway/queues.rb +21 -0
- data/lib/anway/railtie.rb +32 -0
- data/lib/anway/runner.rb +324 -0
- data/lib/anway/server.rb +48 -0
- data/lib/anway/settings.rb +229 -0
- data/lib/anway/testing.rb +48 -0
- data/lib/anway/version.rb +8 -0
- data/lib/anway/web.rb +104 -0
- data/lib/anway/worker.rb +127 -0
- data/lib/anway.rb +65 -0
- data/lib/generators/anway/install/install_generator.rb +74 -0
- data/lib/generators/anway/install/templates/anway +12 -0
- data/lib/generators/anway/install/templates/anway.yml +32 -0
- data/lib/puma/plugin/anway.rb +69 -0
- data/libexec/anway-server +0 -0
- metadata +82 -0
checksums.yaml
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
---
|
|
2
|
+
SHA256:
|
|
3
|
+
metadata.gz: e23edd86245de5eb2c1009863286ef768406e7822e10d2556c0205345e0bd74c
|
|
4
|
+
data.tar.gz: b62b1b150d752f41deaf2e53d6b8eae6b6b6f6c9d0d14391a525e94fabe70898
|
|
5
|
+
SHA512:
|
|
6
|
+
metadata.gz: b5548bec6387a34fdfb4bb33c7488572e40542d3cfd7a42a4a39e31428c7fd7b6276c2ea77d7231d4e2a00037275a361a67ffa2ec2c5d2ca424fe76ace8f2614
|
|
7
|
+
data.tar.gz: 64b2930309ad21453862d79f48b91435aa535ad404be9e64c4e9407750865c97c67af4f5fadf19290aadab39cde23d16fa88a6cbc5e7a33699fc0d1e548077a0
|
data/LICENSE
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Thadeu
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
22
|
+
|
data/README.md
ADDED
|
@@ -0,0 +1,270 @@
|
|
|
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
|
+
|
|
10
|
+
# anway-ruby
|
|
11
|
+
|
|
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.
|
|
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
|
+
|
|
65
|
+
```ruby
|
|
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
|
|
76
|
+
```
|
|
77
|
+
|
|
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.
|
|
94
|
+
|
|
95
|
+
## Worker
|
|
96
|
+
|
|
97
|
+
```ruby
|
|
98
|
+
class WelcomeJob
|
|
99
|
+
include Anway::Worker
|
|
100
|
+
|
|
101
|
+
job_type 'email.send'
|
|
102
|
+
job_options queue: 'mailers', retry: 5
|
|
103
|
+
|
|
104
|
+
def perform(address)
|
|
105
|
+
# ...
|
|
106
|
+
end
|
|
107
|
+
end
|
|
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')
|
|
112
|
+
```
|
|
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 }`.
|
|
116
|
+
- Args must be JSON types with string hash keys. Symbols, times, and objects raise `ArgumentError`.
|
|
117
|
+
- Delivery is at least once, so jobs must be idempotent.
|
|
118
|
+
|
|
119
|
+
To send a job that a worker in any language runs:
|
|
120
|
+
|
|
121
|
+
```ruby
|
|
122
|
+
Anway.push('image.resize', [42], queue: 'media')
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
## Rails
|
|
126
|
+
|
|
127
|
+
```ruby
|
|
128
|
+
config.active_job.queue_adapter = :anway
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
- Existing ActiveJob classes work. Each one runs in the Rails reloader.
|
|
132
|
+
- In a database transaction, a push waits for the commit, and a rollback cancels it. This also applies to `perform_async`.
|
|
133
|
+
- A job with `retry_on` keeps ActiveJob attempts, and its final error goes to the dead set.
|
|
134
|
+
- A job with no `retry_on` uses server retries.
|
|
135
|
+
|
|
136
|
+
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.
|
|
137
|
+
|
|
138
|
+
## Process
|
|
139
|
+
|
|
140
|
+
```bash
|
|
141
|
+
bundle exec anway # the embedded server when there is no url, and workers
|
|
142
|
+
bundle exec anway server # only the server
|
|
143
|
+
bundle exec anway console # only the console
|
|
144
|
+
bundle exec anway worker -q mailers # only workers
|
|
145
|
+
bundle exec anway -C config/anway.yml -q critical,mailers,default -c 10
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
### Puma
|
|
149
|
+
|
|
150
|
+
`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.
|
|
151
|
+
|
|
152
|
+
The worker process sets `ANWAY_WORKER=1` before it loads the app.
|
|
153
|
+
|
|
154
|
+
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:
|
|
155
|
+
|
|
156
|
+
```ruby
|
|
157
|
+
# config/environments/development.rb
|
|
158
|
+
config.enable_reloading = ENV["ANWAY_WORKER"].blank?
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
| Flag | Default | Purpose |
|
|
162
|
+
|---|---|---|
|
|
163
|
+
| `-q`, `--queues` | Queues of the job classes, and `default` | Queues in order, as `name` or `name:weight` |
|
|
164
|
+
| `-c`, `--concurrency` | `10` | Job threads |
|
|
165
|
+
| `-t`, `--timeout` | `25` | Seconds for jobs to finish at a stop |
|
|
166
|
+
| `-r`, `--require` | `config/environment.rb` | File that loads the jobs. Required outside Rails. |
|
|
167
|
+
| `-C`, `--config` | `config/anway.yml` | YAML config file |
|
|
168
|
+
| `-e`, `--environment` | `RAILS_ENV`, `APP_ENV` | Environment section of the YAML file |
|
|
169
|
+
| `-l`, `--label` | None | Worker label |
|
|
170
|
+
| `-g`, `--tag` | The app folder | Name of the app in the console |
|
|
171
|
+
| `-a`, `--autoscale` | Off | Turn on autoscale, up to this many threads |
|
|
172
|
+
| `-v`, `--verbose` | Off | Debug logs |
|
|
173
|
+
| `-V`, `--version` | | Print the version |
|
|
174
|
+
|
|
175
|
+
```yaml
|
|
176
|
+
concurrency: <%= ENV.fetch('WORKER_THREADS', 10) %>
|
|
177
|
+
timeout: 25
|
|
178
|
+
queues:
|
|
179
|
+
- [critical, 4]
|
|
180
|
+
- [mailers, 2]
|
|
181
|
+
- [default, 1]
|
|
182
|
+
|
|
183
|
+
production:
|
|
184
|
+
concurrency: 20
|
|
185
|
+
```
|
|
186
|
+
|
|
187
|
+
Flags have priority over the environment section, and the environment section has priority over top-level keys. A list without weights uses strict order.
|
|
188
|
+
|
|
189
|
+
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:
|
|
190
|
+
|
|
191
|
+
```yaml
|
|
192
|
+
hostname: worker.1 # or ANWAY_HOSTNAME, for example from the container or dyno name
|
|
193
|
+
tag: shop # or ANWAY_TAG, or --tag
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
`ANWAY_HOSTNAME` and `ANWAY_TAG` have priority over the file.
|
|
197
|
+
|
|
198
|
+
### Threads and autoscale
|
|
199
|
+
|
|
200
|
+
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:
|
|
201
|
+
|
|
202
|
+
```yaml
|
|
203
|
+
concurrency: 10 # the start count, and the autoscale min
|
|
204
|
+
autoscale:
|
|
205
|
+
max: 40
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
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.
|
|
209
|
+
|
|
210
|
+
| Signal | Effect |
|
|
211
|
+
|---|---|
|
|
212
|
+
| `TERM`, `INT` | Stop |
|
|
213
|
+
| `TSTP` | Quiet: stop fetching and stay alive |
|
|
214
|
+
| `TTIN` | Write thread data to the log |
|
|
215
|
+
|
|
216
|
+
Exit codes: `0` for a normal stop, `1` for a boot failure, `2` for a usage error.
|
|
217
|
+
|
|
218
|
+
At a stop, jobs get `--timeout` seconds to finish. Then `Anway::Shutdown` is raised in them, and they get 5 seconds to return. The process then fails jobs that still run and stops. Set the container stop timeout above 30 seconds.
|
|
219
|
+
|
|
220
|
+
Keep the database pool at the concurrency value or more. A job queue with no worker has no error, and its jobs wait.
|
|
221
|
+
|
|
222
|
+
## Tests in your app
|
|
223
|
+
|
|
224
|
+
```ruby
|
|
225
|
+
require 'anway/testing'
|
|
226
|
+
|
|
227
|
+
Anway::Testing.fake!
|
|
228
|
+
WelcomeJob.perform_async('a@b.com')
|
|
229
|
+
Anway::Testing.jobs.size
|
|
230
|
+
Anway::Testing.drain
|
|
231
|
+
|
|
232
|
+
Anway::Testing.inline!
|
|
233
|
+
```
|
|
234
|
+
|
|
235
|
+
## Client
|
|
236
|
+
|
|
237
|
+
`Anway::Client` has the operations of [anway-go](https://github.com/thadeu/anway-go), in snake_case. It is safe for threads and for forks.
|
|
238
|
+
|
|
239
|
+
```ruby
|
|
240
|
+
client = Anway::Client.new('tcp://localhost:7419')
|
|
241
|
+
client.push(Anway::Job.new('email.send', ['a@b.com']))
|
|
242
|
+
```
|
|
243
|
+
|
|
244
|
+
The error kinds are `Anway::NotUnique`, `Anway::Closed`, `Anway::ServerError`, and `Anway::ConnectionError`. A failed call does not resend.
|
|
245
|
+
|
|
246
|
+
## Configuration
|
|
247
|
+
|
|
248
|
+
```ruby
|
|
249
|
+
Anway.configure do |config|
|
|
250
|
+
config.pool_size = 8
|
|
251
|
+
config.timeout = 10
|
|
252
|
+
config.tls = { ca_file: 'ca.pem' }
|
|
253
|
+
config.use MyMiddleware.new
|
|
254
|
+
config.on_error { |error, job| report(error, job) }
|
|
255
|
+
end
|
|
256
|
+
```
|
|
257
|
+
|
|
258
|
+
Middleware has `call(job)` and yields. The first one added is the outermost.
|
|
259
|
+
|
|
260
|
+
## Tests
|
|
261
|
+
|
|
262
|
+
```bash
|
|
263
|
+
SERVER_BIN=/path/to/anway bundle exec rspec
|
|
264
|
+
```
|
|
265
|
+
|
|
266
|
+
The specs map to the [conformance scenarios](https://github.com/thadeu/anway/blob/main/conformance/scenarios.md).
|
|
267
|
+
|
|
268
|
+
## License
|
|
269
|
+
|
|
270
|
+
MIT
|
data/exe/anway
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require 'active_job'
|
|
4
|
+
require 'anway'
|
|
5
|
+
|
|
6
|
+
module Anway
|
|
7
|
+
# Runs serialized ActiveJob payloads.
|
|
8
|
+
class ActiveJobWrapper
|
|
9
|
+
include Anway::Worker
|
|
10
|
+
|
|
11
|
+
job_type 'ActiveJob'
|
|
12
|
+
|
|
13
|
+
def perform(data)
|
|
14
|
+
ActiveJob::Base.execute(data)
|
|
15
|
+
end
|
|
16
|
+
end
|
|
17
|
+
|
|
18
|
+
# Records the use of retry_on, because rescue_handlers also holds rescue_from.
|
|
19
|
+
module ActiveJobRetries
|
|
20
|
+
def retry_on(...)
|
|
21
|
+
self.anway_retry_on = true
|
|
22
|
+
|
|
23
|
+
super
|
|
24
|
+
end
|
|
25
|
+
end
|
|
26
|
+
end
|
|
27
|
+
|
|
28
|
+
ActiveSupport.on_load(:active_job) do
|
|
29
|
+
class_attribute :anway_retry_on, default: false
|
|
30
|
+
singleton_class.prepend(Anway::ActiveJobRetries)
|
|
31
|
+
end
|
|
32
|
+
|
|
33
|
+
module ActiveJob
|
|
34
|
+
module QueueAdapters
|
|
35
|
+
class AnwayAdapter < AbstractAdapter
|
|
36
|
+
BACKTRACE = 30
|
|
37
|
+
DEAD_SET = -1
|
|
38
|
+
|
|
39
|
+
def enqueue(job)
|
|
40
|
+
push(job, {})
|
|
41
|
+
end
|
|
42
|
+
|
|
43
|
+
def enqueue_at(job, timestamp)
|
|
44
|
+
push(job, { at: Time.at(timestamp) })
|
|
45
|
+
end
|
|
46
|
+
|
|
47
|
+
private
|
|
48
|
+
|
|
49
|
+
# Each push has a new id. A retry_on attempt keeps its job_id while the
|
|
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.
|
|
53
|
+
def push(job, options)
|
|
54
|
+
options = options.merge(queue: job.queue_name, backtrace: BACKTRACE, custom: { 'wrapped' => job.class.name })
|
|
55
|
+
|
|
56
|
+
# retry_on owns the attempts, so its final error goes to the dead set.
|
|
57
|
+
options[:retry] = DEAD_SET if job.class.anway_retry_on
|
|
58
|
+
|
|
59
|
+
pushed = Anway::Job.new('ActiveJob', [job.serialize.as_json], **options)
|
|
60
|
+
|
|
61
|
+
job.provider_job_id = pushed.jid
|
|
62
|
+
|
|
63
|
+
Anway.enqueue(pushed)
|
|
64
|
+
end
|
|
65
|
+
end
|
|
66
|
+
end
|
|
67
|
+
end
|
data/lib/anway/cli.rb
ADDED
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require 'optparse'
|
|
4
|
+
|
|
5
|
+
# The Railtie registers only when Rails loads before the gem.
|
|
6
|
+
begin
|
|
7
|
+
require 'rails'
|
|
8
|
+
rescue LoadError
|
|
9
|
+
nil
|
|
10
|
+
end
|
|
11
|
+
|
|
12
|
+
require 'anway'
|
|
13
|
+
|
|
14
|
+
module Anway
|
|
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
|
|
20
|
+
class CLI
|
|
21
|
+
EXIT_OK = 0
|
|
22
|
+
EXIT_BOOT = 1
|
|
23
|
+
EXIT_USAGE = 2
|
|
24
|
+
DEFAULTS = { concurrency: 10, timeout: 25, labels: [] }.freeze
|
|
25
|
+
COMMANDS = %w[server console worker].freeze
|
|
26
|
+
RAILS_ENTRY = 'config/environment.rb'
|
|
27
|
+
|
|
28
|
+
def initialize(argv)
|
|
29
|
+
$stdout.sync = true
|
|
30
|
+
|
|
31
|
+
@argv = argv.dup
|
|
32
|
+
@flags = {}
|
|
33
|
+
end
|
|
34
|
+
|
|
35
|
+
def run
|
|
36
|
+
return EXIT_OK if parse == :done
|
|
37
|
+
|
|
38
|
+
boot
|
|
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
|
|
49
|
+
EXIT_OK
|
|
50
|
+
rescue OptionParser::ParseError, ArgumentError => e
|
|
51
|
+
warn("anway: #{e.message}")
|
|
52
|
+
|
|
53
|
+
EXIT_USAGE
|
|
54
|
+
rescue Error, ScriptError, StandardError => e
|
|
55
|
+
warn("anway: #{e.class}: #{e.message}")
|
|
56
|
+
|
|
57
|
+
EXIT_BOOT
|
|
58
|
+
end
|
|
59
|
+
|
|
60
|
+
private
|
|
61
|
+
|
|
62
|
+
def parse
|
|
63
|
+
parser.parse!(@argv)
|
|
64
|
+
|
|
65
|
+
@command = @argv.shift if COMMANDS.include?(@argv.first)
|
|
66
|
+
|
|
67
|
+
raise ArgumentError, "unexpected argument: #{@argv.first}" unless @argv.empty?
|
|
68
|
+
|
|
69
|
+
@flags[:done] ? :done : nil
|
|
70
|
+
end
|
|
71
|
+
|
|
72
|
+
def parser
|
|
73
|
+
OptionParser.new do |options|
|
|
74
|
+
options.banner = 'Usage: anway [server|console|worker] [options]'
|
|
75
|
+
|
|
76
|
+
options.on('-q', '--queues LIST', 'Queues in order, as name or name:weight') do |list|
|
|
77
|
+
@flags[:queues] = list.split(',').map { |entry| entry.split(':') }
|
|
78
|
+
end
|
|
79
|
+
|
|
80
|
+
options.on('-c', '--concurrency N', Integer, 'Number of job threads') { |n| @flags[:concurrency] = n }
|
|
81
|
+
options.on('-t', '--timeout N', Float, 'Seconds for jobs to finish at stop') { |n| @flags[:timeout] = n }
|
|
82
|
+
options.on('-r', '--require PATH', 'File that loads the jobs') { |path| @flags[:require] = path }
|
|
83
|
+
options.on('-C', '--config PATH', 'YAML config file') { |path| @flags[:config] = path }
|
|
84
|
+
options.on('-e', '--environment NAME', 'Environment name') { |name| @flags[:environment] = name }
|
|
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 } }
|
|
88
|
+
options.on('-v', '--verbose', 'Debug logs') { @flags[:verbose] = true }
|
|
89
|
+
|
|
90
|
+
options.on('-V', '--version', 'Print the version') do
|
|
91
|
+
puts "anway #{VERSION}"
|
|
92
|
+
|
|
93
|
+
@flags[:done] = true
|
|
94
|
+
end
|
|
95
|
+
|
|
96
|
+
options.on('-h', '--help', 'Print this help') do
|
|
97
|
+
puts options
|
|
98
|
+
|
|
99
|
+
@flags[:done] = true
|
|
100
|
+
end
|
|
101
|
+
end
|
|
102
|
+
end
|
|
103
|
+
|
|
104
|
+
def boot
|
|
105
|
+
environment = @flags[:environment] || ENV['RAILS_ENV'] || ENV['APP_ENV'] || 'development'
|
|
106
|
+
|
|
107
|
+
ENV['RAILS_ENV'] ||= environment
|
|
108
|
+
ENV['APP_ENV'] ||= environment
|
|
109
|
+
|
|
110
|
+
@settings = Settings.load(path: @flags[:config], environment: environment)
|
|
111
|
+
@options = DEFAULTS.merge(@settings.worker_options).merge(@flags)
|
|
112
|
+
|
|
113
|
+
Anway.config.logger.level = Logger::DEBUG if @options[:verbose]
|
|
114
|
+
end
|
|
115
|
+
|
|
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?
|
|
121
|
+
|
|
122
|
+
begin
|
|
123
|
+
server&.start
|
|
124
|
+
console&.start
|
|
125
|
+
|
|
126
|
+
start
|
|
127
|
+
ensure
|
|
128
|
+
console&.stop
|
|
129
|
+
server&.stop
|
|
130
|
+
end
|
|
131
|
+
end
|
|
132
|
+
|
|
133
|
+
def load_app
|
|
134
|
+
path = @options[:require]
|
|
135
|
+
path ||= RAILS_ENTRY if File.exist?(RAILS_ENTRY)
|
|
136
|
+
|
|
137
|
+
raise ArgumentError, 'use -r to load the jobs outside Rails' unless path
|
|
138
|
+
|
|
139
|
+
require File.expand_path(path)
|
|
140
|
+
|
|
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
|
|
155
|
+
end
|
|
156
|
+
|
|
157
|
+
def check_database_pool
|
|
158
|
+
size = database_pool
|
|
159
|
+
|
|
160
|
+
return unless size
|
|
161
|
+
|
|
162
|
+
logger = Anway.config.logger
|
|
163
|
+
max = @options.dig(:autoscale, :max)
|
|
164
|
+
|
|
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
|
|
167
|
+
end
|
|
168
|
+
|
|
169
|
+
def start
|
|
170
|
+
runner = Runner.new(
|
|
171
|
+
url: Anway.config.url || @settings.client_url,
|
|
172
|
+
queues: queues,
|
|
173
|
+
concurrency: @options[:concurrency],
|
|
174
|
+
timeout: @options[:timeout],
|
|
175
|
+
labels: @options[:labels],
|
|
176
|
+
hostname: @options[:hostname],
|
|
177
|
+
tag: @options[:tag] || default_tag,
|
|
178
|
+
autoscale: @options[:autoscale],
|
|
179
|
+
limit: database_pool
|
|
180
|
+
)
|
|
181
|
+
|
|
182
|
+
trap_signals(runner)
|
|
183
|
+
runner.run
|
|
184
|
+
end
|
|
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
|
+
|
|
195
|
+
def trap_signals(runner)
|
|
196
|
+
%w[TERM INT].each { |name| Signal.trap(name) { runner.stop } }
|
|
197
|
+
|
|
198
|
+
Signal.trap('TSTP') { runner.quiet }
|
|
199
|
+
Signal.trap('TTIN') { runner.dump }
|
|
200
|
+
end
|
|
201
|
+
|
|
202
|
+
# Without a list, the worker uses the queues of its job classes.
|
|
203
|
+
def queues
|
|
204
|
+
return @options[:queues] if @options[:queues]
|
|
205
|
+
|
|
206
|
+
names = Worker.classes.map { |klass| klass.job_options[:queue]&.to_s }
|
|
207
|
+
names.concat(active_job_queues)
|
|
208
|
+
|
|
209
|
+
[*names.compact, 'default'].uniq
|
|
210
|
+
end
|
|
211
|
+
|
|
212
|
+
def active_job_queues
|
|
213
|
+
return [] unless defined?(ActiveJob::Base)
|
|
214
|
+
|
|
215
|
+
ActiveJob::Base.descendants.map(&:queue_name).grep(String)
|
|
216
|
+
end
|
|
217
|
+
end
|
|
218
|
+
end
|