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.
@@ -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/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/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
data/lib/anway/railtie.rb CHANGED
@@ -13,7 +13,16 @@ module Anway
13
13
  end
14
14
  end
15
15
 
16
+ # Pushes from the web go to the same server as the workers: the embedded
17
+ # one, or the url in config/anway.yml or ANWAY_URL. A url that the app
18
+ # sets in an initializer wins.
16
19
  config.after_initialize do |app|
20
+ path = app.root.join(Settings::DEFAULT_PATH)
21
+
22
+ settings = Settings.load(path: (path.to_s if path.exist?), environment: Rails.env)
23
+
24
+ Anway.config.url ||= settings.client_url
25
+ Anway.config.console_url ||= settings.console_url
17
26
  Anway.config.logger = Rails.logger if Rails.logger
18
27
  Anway.config.reloader = ->(&block) { app.reloader.wrap(&block) }
19
28
 
data/lib/anway/runner.rb CHANGED
@@ -16,10 +16,19 @@ module Anway
16
16
 
17
17
  attr_reader :wid
18
18
 
19
- def initialize(queues: ['default'], concurrency: 10, timeout: 25, cancel_grace: 5,
20
- labels: [], beat_interval: BEAT_INTERVAL, url: nil, logger: Anway.config.logger)
19
+ # The console shows the worker as hostname:pid with its tag. A nil
20
+ # hostname uses the machine name. The server can change the thread count
21
+ # in a BEAT reply, up to limit, such as the database pool size. autoscale,
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.
25
+ def initialize(queues: ['default'], concurrency: 10, timeout: 25, cancel_grace: 5, labels: [],
26
+ hostname: nil, tag: nil, autoscale: nil, limit: nil, subscriptions: nil,
27
+ beat_interval: BEAT_INTERVAL, url: nil, logger: Anway.config.logger)
21
28
  @queues = Queues.new(queues)
29
+ @subscriptions = subscriptions
22
30
  @concurrency = concurrency
31
+ @limit = limit
23
32
  @timeout = timeout
24
33
  @cancel_grace = cancel_grace
25
34
  @beat_interval = beat_interval
@@ -30,6 +39,8 @@ module Anway
30
39
  @events_reader, @events_writer = IO.pipe
31
40
  @running = {}
32
41
  @lock = Mutex.new
42
+ @processors = []
43
+ @retiring = 0
33
44
 
34
45
  @client = Client.new(
35
46
  url || Anway.config.url,
@@ -37,7 +48,11 @@ module Anway
37
48
  timeout: Anway.config.timeout,
38
49
  tls: Anway.config.tls,
39
50
  wid: @wid,
40
- labels: ['ruby', *labels]
51
+ labels: ['ruby', *labels],
52
+ identity: {
53
+ hostname: hostname, tag: tag, queues: @queues.names, concurrency: concurrency,
54
+ autoscale: autoscale, max_concurrency: limit
55
+ }
41
56
  )
42
57
  end
43
58
 
@@ -56,10 +71,14 @@ module Anway
56
71
  signal('d')
57
72
  end
58
73
 
74
+ # The first beat reports the threads, so the server can scale the worker
75
+ # at once. The subscriptions go to the server before the first fetch.
59
76
  def run
60
- @client.beat
77
+ @client.heartbeat(nil, concurrency: @concurrency)
61
78
 
62
- @processors = Array.new(@concurrency) { start_processor }
79
+ subscribe_all
80
+
81
+ @lock.synchronize { @processors = Array.new(@concurrency) { start_processor } }
63
82
 
64
83
  beat_thread = start_beat
65
84
 
@@ -80,6 +99,26 @@ module Anway
80
99
  @events_writer.write_nonblock(letter, exception: false)
81
100
  end
82
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
+
83
122
  def wait_for_stop
84
123
  loop do
85
124
  @events_reader.wait_readable
@@ -123,7 +162,14 @@ module Anway
123
162
  end
124
163
 
125
164
  def beat(state)
126
- case @client.beat(state)
165
+ reply = @client.heartbeat(state, concurrency: @concurrency)
166
+
167
+ # A new count goes to the server at once, not at the next beat, so the
168
+ # console shows the threads that run, and the next autoscale step starts
169
+ # from them.
170
+ @client.heartbeat(state, concurrency: @concurrency) if reply.concurrency && resize(reply.concurrency)
171
+
172
+ case reply.state
127
173
  when 'quiet'
128
174
  quiet
129
175
 
@@ -141,6 +187,48 @@ module Anway
141
187
  state
142
188
  end
143
189
 
190
+ # Starts threads, or asks threads to stop after their job. A stop that is
191
+ # still pending is canceled first, so the count is right at once. Returns
192
+ # true when the count changed.
193
+ def resize(size)
194
+ return unless size.is_a?(Integer) && size.positive? && fetching?
195
+
196
+ size = [size, @limit].min if @limit
197
+
198
+ @lock.synchronize do
199
+ change = size - @concurrency
200
+
201
+ return if change.zero?
202
+
203
+ if change.positive?
204
+ kept = [@retiring, change].min
205
+
206
+ @retiring -= kept
207
+ @client.grow_pool(size + 1)
208
+ @processors.select!(&:alive?)
209
+ (change - kept).times { @processors << start_processor }
210
+ else
211
+ @retiring -= change
212
+ end
213
+
214
+ @concurrency = size
215
+ end
216
+
217
+ @logger.info("anway threads=#{size}")
218
+
219
+ true
220
+ end
221
+
222
+ def retire?
223
+ @lock.synchronize do
224
+ return false unless @retiring.positive?
225
+
226
+ @retiring -= 1
227
+
228
+ true
229
+ end
230
+ end
231
+
144
232
  # Shutdown stays pending outside perform, so it cannot break a report.
145
233
  def start_processor
146
234
  Thread.new do
@@ -150,7 +238,7 @@ module Anway
150
238
 
151
239
  # A fetch in progress is not canceled, because its reply can hold a job.
152
240
  def process_loop
153
- while fetching?
241
+ while fetching? && !retire?
154
242
  started = monotonic
155
243
  job = fetch_next
156
244
 
@@ -249,7 +337,9 @@ module Anway
249
337
  def join_processors(limit)
250
338
  deadline = monotonic + limit
251
339
 
252
- @processors.all? { |thread| thread.join([deadline - monotonic, 0].max) }
340
+ threads = @lock.synchronize { @processors.dup }
341
+
342
+ threads.all? { |thread| thread.join([deadline - monotonic, 0].max) }
253
343
  end
254
344
 
255
345
  def monotonic
@@ -0,0 +1,48 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'fileutils'
4
+
5
+ module Anway
6
+ # Server runs the anway server binary that the platform gem carries.
7
+ # ANWAY_SERVER_PATH names another binary.
8
+ class Server < Daemon
9
+ BUNDLED = File.expand_path('../../libexec/anway-server', __dir__)
10
+
11
+ def self.executable(env = ENV)
12
+ override = env['ANWAY_SERVER_PATH'].to_s.strip
13
+
14
+ return override unless override.empty?
15
+ return BUNDLED if File.executable?(BUNDLED)
16
+
17
+ raise Error, "this install of anway has no server for #{Gem::Platform.local}. " \
18
+ 'Set ANWAY_SERVER_PATH to an anway server binary, or set url to use a server that runs apart.'
19
+ end
20
+
21
+ private
22
+
23
+ def name
24
+ 'server'
25
+ end
26
+
27
+ def address
28
+ @settings.bind
29
+ end
30
+
31
+ def env
32
+ @settings.server_env
33
+ end
34
+
35
+ def executable
36
+ self.class.executable
37
+ end
38
+
39
+ def prepare
40
+ FileUtils.mkdir_p(@settings.data)
41
+ end
42
+
43
+ def announce
44
+ @logger.info("anway: embedded server on #{@settings.bind}, data in #{@settings.data}. " \
45
+ 'On more than one host, run one server and set ANWAY_URL.')
46
+ end
47
+ end
48
+ end
@@ -0,0 +1,229 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'erb'
4
+ require 'securerandom'
5
+ require 'yaml'
6
+
7
+ module Anway
8
+ # Settings reads config/anway.yml. The keys at the top apply to every
9
+ # environment, and the section of the current environment overrides them.
10
+ #
11
+ # queues: [critical, default]
12
+ # concurrency: 10
13
+ #
14
+ # production:
15
+ # url: <%= ENV["ANWAY_URL"] %>
16
+ #
17
+ # The server is embedded, so the app runs it, unless a url is set in the
18
+ # file or in ANWAY_URL. `server: { mode: }` or ANWAY_SERVER can still choose.
19
+ class Settings
20
+ DEFAULT_PATH = 'config/anway.yml'
21
+ DEFAULT_BIND = '127.0.0.1:7419'
22
+ DEFAULT_DATA = 'storage/anway'
23
+ DEFAULT_WEB = '127.0.0.1:7420'
24
+ DEFAULT_CONSOLE = '127.0.0.1:7421'
25
+ MODES = %w[embedded external].freeze
26
+ KEYS = %w[queues concurrency timeout labels hostname tag autoscale require url server console].freeze
27
+ SERVER_KEYS = %w[mode bind data password web web_token].freeze
28
+ CONSOLE_KEYS = %w[path bind api token].freeze
29
+
30
+ def self.environment(env = ENV)
31
+ env['RAILS_ENV'] || env['APP_ENV'] || env['RACK_ENV'] || 'development'
32
+ end
33
+
34
+ # A missing file is fine, unless the caller named it.
35
+ def self.load(path: nil, environment: nil, env: ENV)
36
+ file = path || DEFAULT_PATH
37
+
38
+ raise ArgumentError, "config file not found: #{file}" if path && !File.exist?(file)
39
+
40
+ content = File.exist?(file) ? YAML.safe_load(ERB.new(File.read(file)).result, aliases: true) : {}
41
+
42
+ new(content || {}, environment: environment || self.environment(env), env: env)
43
+ end
44
+
45
+ def initialize(content, environment:, env: ENV)
46
+ section = content[environment].is_a?(Hash) ? content[environment] : {}
47
+
48
+ @values = content.slice(*KEYS).merge(section.slice(*KEYS))
49
+ @server = section_of(content, 'server', SERVER_KEYS).merge(section_of(section, 'server', SERVER_KEYS))
50
+ @console = section_of(content, 'console', CONSOLE_KEYS).merge(section_of(section, 'console', CONSOLE_KEYS))
51
+ @env = env
52
+
53
+ check!
54
+ end
55
+
56
+ # Options for the worker, as the CLI names them.
57
+ # ANWAY_HOSTNAME and ANWAY_TAG come before the file.
58
+ def worker_options
59
+ options = @values.slice('queues', 'concurrency', 'timeout', 'labels', 'hostname', 'tag', 'require').transform_keys(&:to_sym)
60
+
61
+ options[:hostname] = present(@env['ANWAY_HOSTNAME']) || present(options[:hostname])
62
+ options[:tag] = present(@env['ANWAY_TAG']) || present(options[:tag])
63
+ options[:autoscale] = autoscale
64
+
65
+ options.compact
66
+ end
67
+
68
+ # autoscale: { max: n } or { min: n, max: n }, or nil when it is off.
69
+ def autoscale
70
+ value = @values['autoscale']
71
+
72
+ return nil unless value.is_a?(Hash)
73
+
74
+ value.slice('min', 'max').transform_keys(&:to_sym)
75
+ end
76
+
77
+ # The url of a server that runs apart: from the file, then from ANWAY_URL.
78
+ def url
79
+ present(@values['url']) || present(@env['ANWAY_URL'])
80
+ end
81
+
82
+ def mode
83
+ present(@env['ANWAY_SERVER']) || present(@server['mode']) || (url ? 'external' : 'embedded')
84
+ end
85
+
86
+ def embedded?
87
+ mode == 'embedded'
88
+ end
89
+
90
+ def bind
91
+ present(@server['bind']) || DEFAULT_BIND
92
+ end
93
+
94
+ def data
95
+ present(@server['data']) || DEFAULT_DATA
96
+ end
97
+
98
+ def password
99
+ present(@server['password'])
100
+ end
101
+
102
+ # The url that clients in this app use: the external server, or the
103
+ # embedded one on its local address.
104
+ def client_url
105
+ return url unless embedded?
106
+
107
+ host, port = split_bind
108
+ auth = password ? ":#{password}@" : ''
109
+
110
+ "tcp://#{auth}#{Daemon.local_host(host)}:#{port}"
111
+ end
112
+
113
+ # The address of the HTTP API that the web console reads. It is off
114
+ # unless it is set, or the console runs next to an embedded server.
115
+ def web
116
+ present(@server['web']) || (console? && embedded? ? DEFAULT_WEB : nil)
117
+ end
118
+
119
+ # Without a token in the file, the server and the console that this
120
+ # process starts share a random one.
121
+ def web_token
122
+ present(@server['web_token']) || (web ? (@random_token ||= SecureRandom.hex(16)) : nil)
123
+ end
124
+
125
+ # A random token changes at each start, so a server or console from an
126
+ # earlier start does not accept it.
127
+ def random_web_token?
128
+ !web.nil? && present(@server['web_token']).nil?
129
+ end
130
+
131
+ # The web console binary: ANWAY_CONSOLE_PATH, then console.path.
132
+ def console_path
133
+ path = present(@env['ANWAY_CONSOLE_PATH']) || present(@console['path'])
134
+
135
+ path && File.expand_path(path)
136
+ end
137
+
138
+ def console?
139
+ !console_path.nil?
140
+ end
141
+
142
+ def console_bind
143
+ present(@console['bind']) || DEFAULT_CONSOLE
144
+ end
145
+
146
+ # The address where `mount Anway::Web` finds the console.
147
+ def console_url
148
+ host, port = split(console_bind)
149
+
150
+ "http://#{Daemon.local_host(host)}:#{port}"
151
+ end
152
+
153
+ # The HTTP API that the console reads: console.api, or the API of the
154
+ # embedded server.
155
+ def console_api
156
+ return present(@console['api']) if present(@console['api'])
157
+ return nil unless web
158
+
159
+ host, port = split(web)
160
+
161
+ "http://#{Daemon.local_host(host)}:#{port}"
162
+ end
163
+
164
+ def console_env
165
+ host, port = split(console_bind)
166
+
167
+ { 'HOST' => host, 'PORT' => port, 'ANWAY_API_URL' => console_api, 'WEB_TOKEN' => present(@console['token']) || web_token.to_s }
168
+ end
169
+
170
+ # The environment of the server binary.
171
+ def server_env
172
+ env = { 'BIND_ADDR' => bind, 'DATA_DIR' => File.expand_path(data) }
173
+
174
+ env['SERVER_PASSWORD'] = password if password
175
+ env['WEB_ADDR'] = web if web
176
+ env['WEB_TOKEN'] = web_token if web_token
177
+
178
+ env
179
+ end
180
+
181
+ private
182
+
183
+ def section_of(hash, name, keys)
184
+ value = hash[name]
185
+
186
+ return {} if value.nil?
187
+
188
+ raise ArgumentError, "#{name} must be a hash of #{keys.join(', ')}" unless value.is_a?(Hash)
189
+
190
+ value.slice(*keys)
191
+ end
192
+
193
+ def check!
194
+ check_autoscale!
195
+ raise ArgumentError, "server mode must be embedded or external, not #{mode}" unless MODES.include?(mode)
196
+ raise ArgumentError, 'an external server needs url or ANWAY_URL' if mode == 'external' && url.nil?
197
+ raise ArgumentError, "server bind must be host:port, not #{bind}" unless split_bind.last.to_s.match?(/\A\d+\z/)
198
+ raise ArgumentError, "console bind must be host:port, not #{console_bind}" unless split(console_bind).last.to_s.match?(/\A\d+\z/)
199
+ raise ArgumentError, 'the console needs a server API: set server.web, or console.api' if console? && console_api.nil?
200
+ end
201
+
202
+ def check_autoscale!
203
+ value = @values['autoscale']
204
+
205
+ return if value.nil?
206
+
207
+ message = 'autoscale must be a hash with max, and min if you want, as positive numbers'
208
+
209
+ raise ArgumentError, message unless value.is_a?(Hash) && value['max'].is_a?(Integer) && value['max'].positive?
210
+ raise ArgumentError, message unless value['min'].nil? || (value['min'].is_a?(Integer) && value['min'].between?(1, value['max']))
211
+ end
212
+
213
+ def split_bind
214
+ split(bind)
215
+ end
216
+
217
+ def split(address)
218
+ host, _, port = address.rpartition(':')
219
+
220
+ [host, port]
221
+ end
222
+
223
+ def present(value)
224
+ text = value.to_s.strip
225
+
226
+ text.empty? ? nil : text
227
+ end
228
+ end
229
+ end