anway 0.1.1 → 0.2.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: 798844ea8d9235a50604afe6c8502acb34ff9f30ad5d4daef4bee44624c81e02
4
+ data.tar.gz: d50079d4fc02dbe4aa40e877448dce3a101c3da129c9e19643de715a5896cf78
5
5
  SHA512:
6
- metadata.gz: 56e3d4d168da46531849c13c713e85483d624336fd30f42eace765adbbce119c8c97e09072375e5373410750e5cded72a315eda6d6b917bb137ab57a887aa09a
7
- data.tar.gz: a97fb1df5b38f972d9165fbc9eee86045abec79b5ec543684cb008dbee60f1ec0c222e7a39d7ea99ffdf3b72c80687f1747f79c5f9ebf70d76c9b0be04486bf2
6
+ metadata.gz: 97a7bcc366a45ae77773ed4b6bf1c3575b9c6830f4bd01c9b849a7261a5f008f8d146117dcf60b9ccb1eb90f555ff4f7e3c2201344b32442e3b899cf48abbe04
7
+ data.tar.gz: 1e537ac271526c10637b1be120164708e49d23c9606faa3a013f0922a104f40751ab87fafade1c05ea94688e97749e8c58ad87a3896cf037e1ccdcd6e6a4de29
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
 
@@ -54,7 +138,24 @@ Tasks in `recurring.yml` and jobs that wait in Solid Queue do not move automatic
54
138
  ## Process
55
139
 
56
140
  ```bash
57
- bundle exec anway -q critical,mailers,default -c 10
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?
58
159
  ```
59
160
 
60
161
  | Flag | Default | Purpose |
@@ -66,6 +167,8 @@ bundle exec anway -q critical,mailers,default -c 10
66
167
  | `-C`, `--config` | `config/anway.yml` | YAML config file |
67
168
  | `-e`, `--environment` | `RAILS_ENV`, `APP_ENV` | Environment section of the YAML file |
68
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 |
69
172
  | `-v`, `--verbose` | Off | Debug logs |
70
173
  | `-V`, `--version` | | Print the version |
71
174
 
@@ -83,6 +186,27 @@ production:
83
186
 
84
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.
85
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
+
86
210
  | Signal | Effect |
87
211
  |---|---|
88
212
  | `TERM`, `INT` | Stop |
@@ -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
 
data/lib/anway/client.rb CHANGED
@@ -12,14 +12,18 @@ 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
+
15
19
  # 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: [])
20
+ def initialize(url = nil, pool_size: 8, timeout: 10, tls: nil, wid: nil, labels: [], identity: {})
17
21
  @endpoint = parse_url(url || ENV.fetch('ANWAY_URL', nil) || DEFAULT_URL)
18
22
  @timeout = timeout
19
23
  @wid = wid
20
24
 
21
25
  @pool = Pool.new(pool_size) do
22
- Connection.new(@endpoint, timeout: timeout, tls: tls, wid: wid, labels: labels)
26
+ Connection.new(@endpoint, timeout: timeout, tls: tls, wid: wid, labels: labels, identity: identity)
23
27
  end
24
28
  end
25
29
 
@@ -55,9 +59,25 @@ module Anway
55
59
 
56
60
  # Returns nil, "quiet", or "terminate".
57
61
  def beat(current_state = nil)
58
- reply = call('BEAT', { wid: @wid, current_state: current_state }.compact)
62
+ heartbeat(current_state).state
63
+ end
64
+
65
+ # Sends BEAT with the thread count of the worker, so the server can ask for
66
+ # another count. Returns a Heartbeat.
67
+ def heartbeat(current_state = nil, concurrency: nil)
68
+ reply = call('BEAT', { wid: @wid, current_state: current_state, concurrency: concurrency }.compact)
69
+
70
+ return Heartbeat.new(state: nil, concurrency: nil) if reply == 'OK'
71
+
72
+ data = JSON.parse(reply)
73
+
74
+ Heartbeat.new(state: data['state'], concurrency: data['concurrency'])
75
+ end
59
76
 
60
- reply == 'OK' ? nil : JSON.parse(reply)['state']
77
+ # Lets the client hold size connections at once, for a worker that adds
78
+ # threads.
79
+ def grow_pool(size)
80
+ @pool.grow(size)
61
81
  end
62
82
 
63
83
  def info
@@ -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
@@ -0,0 +1,115 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'socket'
4
+
5
+ module Anway
6
+ # Daemon runs a binary as a child process: the server or the console. A
7
+ # subclass names the binary, its address, and its environment.
8
+ class Daemon
9
+ START_TIMEOUT = 15
10
+ STOP_TIMEOUT = 40
11
+ LOCAL_HOSTS = ['', '0.0.0.0', '::', '[::]'].freeze
12
+
13
+ attr_reader :pid
14
+
15
+ def self.local_host(host)
16
+ LOCAL_HOSTS.include?(host) ? '127.0.0.1' : host
17
+ end
18
+
19
+ def initialize(settings, logger: Anway.config.logger)
20
+ @settings = settings
21
+ @logger = logger
22
+ end
23
+
24
+ # Starts the binary and waits for its port. When a process already
25
+ # listens on the address, it uses that one and returns false. With a
26
+ # random web token, that process has another token, so the start fails.
27
+ def start
28
+ if listening?
29
+ raise Error, "a #{name} already listens on #{address} with another web token. Stop it, or set server.web_token in config/anway.yml." if @settings.random_web_token?
30
+
31
+ @logger.info("anway: a #{name} already listens on #{address}, so this process uses it")
32
+
33
+ return false
34
+ end
35
+
36
+ prepare
37
+
38
+ @pid = Process.spawn(env, executable)
39
+
40
+ wait_for_port
41
+ announce
42
+
43
+ true
44
+ end
45
+
46
+ # Runs the binary in this process. It does not return.
47
+ def exec
48
+ prepare
49
+ announce
50
+
51
+ Process.exec(env, executable)
52
+ end
53
+
54
+ # Asks the process to stop, and kills it after STOP_TIMEOUT.
55
+ def stop
56
+ return unless @pid
57
+
58
+ Process.kill('TERM', @pid)
59
+
60
+ return if wait(STOP_TIMEOUT)
61
+
62
+ Process.kill('KILL', @pid)
63
+ wait(5)
64
+ rescue Errno::ESRCH, Errno::ECHILD
65
+ nil
66
+ ensure
67
+ @pid = nil
68
+ end
69
+
70
+ private
71
+
72
+ def prepare; end
73
+
74
+ def wait_for_port
75
+ deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + START_TIMEOUT
76
+
77
+ until listening?
78
+ raise Error, "the anway #{name} stopped at start with #{$? || 'an error'}" if exited?
79
+ raise Error, "the anway #{name} did not open #{address} in #{START_TIMEOUT} seconds" if Process.clock_gettime(Process::CLOCK_MONOTONIC) > deadline
80
+
81
+ sleep 0.05
82
+ end
83
+ end
84
+
85
+ def listening?
86
+ host, _, port = address.rpartition(':')
87
+
88
+ Socket.tcp(self.class.local_host(host), port.to_i, connect_timeout: 0.2).close
89
+
90
+ true
91
+ rescue SystemCallError, SocketError
92
+ false
93
+ end
94
+
95
+ def exited?
96
+ Process.wait(@pid, Process::WNOHANG) == @pid
97
+ rescue Errno::ECHILD
98
+ true
99
+ end
100
+
101
+ def wait(seconds)
102
+ deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + seconds
103
+
104
+ while Process.clock_gettime(Process::CLOCK_MONOTONIC) < deadline
105
+ return true if Process.wait(@pid, Process::WNOHANG)
106
+
107
+ sleep 0.05
108
+ end
109
+
110
+ false
111
+ rescue Errno::ECHILD
112
+ true
113
+ end
114
+ end
115
+ end
data/lib/anway/pool.rb CHANGED
@@ -36,6 +36,18 @@ module Anway
36
36
  end
37
37
  end
38
38
 
39
+ # Adds free slots up to size. A pool does not shrink: a free connection
40
+ # stays open until close.
41
+ def grow(size)
42
+ @lock.synchronize do
43
+ return if @closed || size <= @size
44
+
45
+ @slots.max = size
46
+ (size - @size).times { @slots.push(Slot.new(nil)) }
47
+ @size = size
48
+ end
49
+ end
50
+
39
51
  def close
40
52
  @lock.synchronize do
41
53
  return if @closed
@@ -0,0 +1,34 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Anway
4
+ module Puma
5
+ # Plugin holds the logic of `plugin :anway`, so that it can be tested
6
+ # without Puma. lib/puma/plugin/anway.rb connects it to Puma.
7
+ module Plugin
8
+ ON = %w[1 true yes on].freeze
9
+ OFF = %w[0 false no off].freeze
10
+
11
+ # ANWAY_IN_PUMA turns the plugin on or off. Without it, the plugin runs
12
+ # only in development, as SOLID_QUEUE_IN_PUMA does for Solid Queue.
13
+ def self.enabled?(env = ENV)
14
+ value = env['ANWAY_IN_PUMA'].to_s.strip.downcase
15
+
16
+ return Settings.environment(env) == 'development' if value.empty?
17
+ return true if ON.include?(value)
18
+ return false if OFF.include?(value)
19
+
20
+ raise ArgumentError, "ANWAY_IN_PUMA must be true or false, not #{env['ANWAY_IN_PUMA']}"
21
+ end
22
+
23
+ # The app binstub loads Bundler and the app. Without it, the gem command
24
+ # runs with Bundler.
25
+ def self.command(root = Dir.pwd)
26
+ binstub = File.join(root, 'bin/anway')
27
+
28
+ return [Gem.ruby, binstub] if File.exist?(binstub)
29
+
30
+ [Gem.ruby, '-rbundler/setup', File.expand_path('../../../exe/anway', __dir__)]
31
+ end
32
+ end
33
+ end
34
+ end