anway 0.2.0-x86_64-linux-gnu

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
data/lib/anway/pool.rb ADDED
@@ -0,0 +1,97 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Anway
4
+ # Connections open at first use. A forked process starts with an empty pool
5
+ # and does not touch the sockets of its parent.
6
+ class Pool
7
+ # A wrapper, because a pop timeout also returns nil.
8
+ Slot = Data.define(:connection)
9
+
10
+ def initialize(size, &opener)
11
+ @size = size
12
+ @opener = opener
13
+ @lock = Mutex.new
14
+ @closed = false
15
+
16
+ reset
17
+ end
18
+
19
+ def with(timeout:)
20
+ connection = checkout(timeout)
21
+ healthy = false
22
+
23
+ begin
24
+ connection ||= @opener.call
25
+
26
+ result = yield connection
27
+ healthy = true
28
+
29
+ result
30
+ rescue ServerError, NotUnique
31
+ healthy = true
32
+
33
+ raise
34
+ ensure
35
+ checkin(connection, healthy)
36
+ end
37
+ end
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
+
51
+ def close
52
+ @lock.synchronize do
53
+ return if @closed
54
+
55
+ @closed = true
56
+ end
57
+
58
+ @slots.close
59
+
60
+ @size.times do
61
+ @slots.pop(timeout: 1)&.connection&.close
62
+ end
63
+ end
64
+
65
+ private
66
+
67
+ def reset
68
+ @pid = Process.pid
69
+ @slots = Thread::SizedQueue.new(@size)
70
+
71
+ @size.times { @slots.push(Slot.new(nil)) }
72
+ end
73
+
74
+ def checkout(timeout)
75
+ raise Closed if @closed
76
+
77
+ @lock.synchronize { reset unless @pid == Process.pid }
78
+
79
+ entry = @slots.pop(timeout: timeout)
80
+
81
+ raise Closed if entry.nil? && @slots.closed?
82
+ raise ConnectionError, 'no free connection' if entry.nil?
83
+
84
+ entry.connection
85
+ end
86
+
87
+ def checkin(connection, healthy)
88
+ connection&.close unless healthy
89
+
90
+ return connection&.close if @slots.closed?
91
+
92
+ @slots.push(Slot.new(healthy ? connection : nil))
93
+ rescue ClosedQueueError
94
+ connection&.close
95
+ end
96
+ end
97
+ end
@@ -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
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Anway
4
+ # Entries are names, or [name, weight] pairs. Without weights, the order is
5
+ # strict. With weights, each fetch uses a new random order.
6
+ class Queues
7
+ attr_reader :names
8
+
9
+ def initialize(entries)
10
+ pairs = entries.map { |entry| Array(entry) }
11
+
12
+ @names = pairs.map { |name, _| name.to_s }.uniq
13
+ @weighted = pairs.any? { |pair| pair.size > 1 }
14
+ @pool = pairs.flat_map { |name, weight| [name.to_s] * Integer(weight || 1) }
15
+ end
16
+
17
+ def order
18
+ @weighted ? @pool.shuffle.uniq : @names
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,32 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Anway
4
+ class Railtie < Rails::Railtie
5
+ # Rails looks up the adapter in active_job.set_configs.
6
+ initializer 'anway.active_job', before: 'active_job.set_configs' do
7
+ require 'active_job/queue_adapters/anway_adapter' if defined?(ActiveJob)
8
+ end
9
+
10
+ initializer 'anway.transactions' do
11
+ ActiveSupport.on_load(:active_record) do
12
+ Anway.config.push_wrapper = ->(&block) { ActiveRecord.after_all_transactions_commit(&block) }
13
+ end
14
+ end
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.
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
26
+ Anway.config.logger = Rails.logger if Rails.logger
27
+ Anway.config.reloader = ->(&block) { app.reloader.wrap(&block) }
28
+
29
+ Anway.config.on_error { |error, _job| Rails.error.report(error, handled: true, source: 'anway') }
30
+ end
31
+ end
32
+ end
@@ -0,0 +1,324 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'securerandom'
4
+
5
+ module Anway
6
+ # Runs jobs until stop, or until the server sends terminate.
7
+ #
8
+ # After quiet, the runner stops fetching and stays alive. At a stop, running
9
+ # jobs get `timeout` seconds to finish. Then Anway::Shutdown is raised in them,
10
+ # and they get `cancel_grace` seconds to return. Jobs that still run then fail.
11
+ class Runner
12
+ BEAT_INTERVAL = 15
13
+ ERROR_PAUSE = 1
14
+ EMPTY_FETCH_MINIMUM = 0.2
15
+ BACKTRACE_LINES = 30
16
+
17
+ attr_reader :wid
18
+
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
+ def initialize(queues: ['default'], concurrency: 10, timeout: 25, cancel_grace: 5, labels: [],
24
+ hostname: nil, tag: nil, autoscale: nil, limit: nil,
25
+ beat_interval: BEAT_INTERVAL, url: nil, logger: Anway.config.logger)
26
+ @queues = Queues.new(queues)
27
+ @concurrency = concurrency
28
+ @limit = limit
29
+ @timeout = timeout
30
+ @cancel_grace = cancel_grace
31
+ @beat_interval = beat_interval
32
+ @logger = logger
33
+ @wid = SecureRandom.hex(12)
34
+ @fetching = Thread::Queue.new
35
+ @stopped_beat = Thread::Queue.new
36
+ @events_reader, @events_writer = IO.pipe
37
+ @running = {}
38
+ @lock = Mutex.new
39
+ @processors = []
40
+ @retiring = 0
41
+
42
+ @client = Client.new(
43
+ url || Anway.config.url,
44
+ pool_size: concurrency + 1,
45
+ timeout: Anway.config.timeout,
46
+ tls: Anway.config.tls,
47
+ wid: @wid,
48
+ labels: ['ruby', *labels],
49
+ identity: {
50
+ hostname: hostname, tag: tag, queues: @queues.names, concurrency: concurrency,
51
+ autoscale: autoscale, max_concurrency: limit
52
+ }
53
+ )
54
+ end
55
+
56
+ # Safe in a signal handler.
57
+ def stop
58
+ signal('s')
59
+ end
60
+
61
+ # Safe in a signal handler.
62
+ def quiet
63
+ signal('q')
64
+ end
65
+
66
+ # Safe in a signal handler.
67
+ def dump
68
+ signal('d')
69
+ end
70
+
71
+ # The first beat reports the threads, so the server can scale the worker
72
+ # at once.
73
+ def run
74
+ @client.heartbeat(nil, concurrency: @concurrency)
75
+
76
+ @lock.synchronize { @processors = Array.new(@concurrency) { start_processor } }
77
+
78
+ beat_thread = start_beat
79
+
80
+ @logger.info("anway started queues=#{@queues.names.join(',')} concurrency=#{@concurrency}")
81
+
82
+ wait_for_stop
83
+ shutdown
84
+
85
+ @stopped_beat.close
86
+ beat_thread.join
87
+ ensure
88
+ @client.close
89
+ end
90
+
91
+ private
92
+
93
+ def signal(letter)
94
+ @events_writer.write_nonblock(letter, exception: false)
95
+ end
96
+
97
+ def wait_for_stop
98
+ loop do
99
+ @events_reader.wait_readable
100
+
101
+ case @events_reader.read_nonblock(1)
102
+ when 's' then return
103
+ when 'q' then stop_fetching
104
+ when 'd' then dump_threads
105
+ end
106
+ end
107
+ end
108
+
109
+ def dump_threads
110
+ Thread.list.each { |thread| @logger.info("#{thread.inspect}\n#{thread.backtrace&.first(10)&.join("\n")}") }
111
+ end
112
+
113
+ def stop_fetching
114
+ @fetching.close
115
+ end
116
+
117
+ def fetching?
118
+ !@fetching.closed?
119
+ end
120
+
121
+ def pause(seconds)
122
+ @fetching.pop(timeout: seconds)
123
+ end
124
+
125
+ def start_beat
126
+ Thread.new do
127
+ state = nil
128
+
129
+ until @stopped_beat.closed?
130
+ @stopped_beat.pop(timeout: @beat_interval)
131
+
132
+ break if @stopped_beat.closed?
133
+
134
+ state = beat(state)
135
+ end
136
+ end
137
+ end
138
+
139
+ def beat(state)
140
+ reply = @client.heartbeat(state, concurrency: @concurrency)
141
+
142
+ # A new count goes to the server at once, not at the next beat, so the
143
+ # console shows the threads that run, and the next autoscale step starts
144
+ # from them.
145
+ @client.heartbeat(state, concurrency: @concurrency) if reply.concurrency && resize(reply.concurrency)
146
+
147
+ case reply.state
148
+ when 'quiet'
149
+ quiet
150
+
151
+ 'quiet'
152
+ when 'terminate'
153
+ stop
154
+
155
+ state
156
+ else
157
+ state
158
+ end
159
+ rescue Error => e
160
+ @logger.warn("beat failed: #{e.message}")
161
+
162
+ state
163
+ end
164
+
165
+ # Starts threads, or asks threads to stop after their job. A stop that is
166
+ # still pending is canceled first, so the count is right at once. Returns
167
+ # true when the count changed.
168
+ def resize(size)
169
+ return unless size.is_a?(Integer) && size.positive? && fetching?
170
+
171
+ size = [size, @limit].min if @limit
172
+
173
+ @lock.synchronize do
174
+ change = size - @concurrency
175
+
176
+ return if change.zero?
177
+
178
+ if change.positive?
179
+ kept = [@retiring, change].min
180
+
181
+ @retiring -= kept
182
+ @client.grow_pool(size + 1)
183
+ @processors.select!(&:alive?)
184
+ (change - kept).times { @processors << start_processor }
185
+ else
186
+ @retiring -= change
187
+ end
188
+
189
+ @concurrency = size
190
+ end
191
+
192
+ @logger.info("anway threads=#{size}")
193
+
194
+ true
195
+ end
196
+
197
+ def retire?
198
+ @lock.synchronize do
199
+ return false unless @retiring.positive?
200
+
201
+ @retiring -= 1
202
+
203
+ true
204
+ end
205
+ end
206
+
207
+ # Shutdown stays pending outside perform, so it cannot break a report.
208
+ def start_processor
209
+ Thread.new do
210
+ Thread.handle_interrupt(Shutdown => :never) { process_loop }
211
+ end
212
+ end
213
+
214
+ # A fetch in progress is not canceled, because its reply can hold a job.
215
+ def process_loop
216
+ while fetching? && !retire?
217
+ started = monotonic
218
+ job = fetch_next
219
+
220
+ if job
221
+ process(job)
222
+ elsif monotonic - started < EMPTY_FETCH_MINIMUM
223
+ pause(EMPTY_FETCH_MINIMUM)
224
+ end
225
+ end
226
+ end
227
+
228
+ def fetch_next
229
+ @client.fetch(*@queues.order)
230
+ rescue Error => e
231
+ @logger.warn("fetch failed: #{e.message}")
232
+ pause(ERROR_PAUSE)
233
+
234
+ nil
235
+ end
236
+
237
+ def process(job)
238
+ @lock.synchronize { @running[job.jid] = { job: job, thread: Thread.current } }
239
+
240
+ error = perform(job)
241
+
242
+ return unless claim(job.jid)
243
+
244
+ report(job, error)
245
+ end
246
+
247
+ def perform(job)
248
+ Thread.handle_interrupt(Shutdown => :immediate) { Executor.call(job) }
249
+
250
+ nil
251
+ rescue Exception => e # rubocop:disable Lint/RescueException
252
+ notify_error(e, job) unless e.is_a?(Shutdown)
253
+
254
+ e
255
+ end
256
+
257
+ def notify_error(error, job)
258
+ @logger.warn("job failed jid=#{job.jid} jobtype=#{job.type} error=#{error.class}: #{error.message}")
259
+
260
+ Anway.config.error_handlers.each { |handler| handler.call(error, job) }
261
+ rescue StandardError => e
262
+ @logger.error("error handler failed: #{e.message}")
263
+ end
264
+
265
+ def claim(jid)
266
+ @lock.synchronize { !@running.delete(jid).nil? }
267
+ end
268
+
269
+ def report(job, error)
270
+ if error
271
+ @client.fail(
272
+ job.jid,
273
+ errtype: error.class.name,
274
+ message: error.message,
275
+ backtrace: error.backtrace&.first(BACKTRACE_LINES) || []
276
+ )
277
+ else
278
+ @client.ack(job.jid)
279
+ end
280
+ rescue Error => e
281
+ @logger.warn("job report failed, the reservation will expire jid=#{job.jid}: #{e.message}")
282
+ end
283
+
284
+ def shutdown
285
+ stop_fetching if fetching?
286
+
287
+ return if join_processors(@timeout)
288
+
289
+ running.each { |entry| entry[:thread].raise(Shutdown, 'the worker is stopping') }
290
+
291
+ return if join_processors(@cancel_grace)
292
+
293
+ running.each { |entry| abandon(entry) }
294
+ end
295
+
296
+ def running
297
+ @lock.synchronize { @running.values }
298
+ end
299
+
300
+ def abandon(entry)
301
+ job = entry[:job]
302
+
303
+ return unless claim(job.jid)
304
+
305
+ @logger.warn("job did not stop jid=#{job.jid} jobtype=#{job.type}")
306
+
307
+ entry[:thread].kill
308
+
309
+ report(job, Shutdown.new('the worker stopped before the job finished'))
310
+ end
311
+
312
+ def join_processors(limit)
313
+ deadline = monotonic + limit
314
+
315
+ threads = @lock.synchronize { @processors.dup }
316
+
317
+ threads.all? { |thread| thread.join([deadline - monotonic, 0].max) }
318
+ end
319
+
320
+ def monotonic
321
+ Process.clock_gettime(Process::CLOCK_MONOTONIC)
322
+ end
323
+ end
324
+ end
@@ -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