anway 0.5.2 → 0.6.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 +4 -4
- data/README.md +117 -2
- data/lib/anway/api.rb +73 -0
- data/lib/anway/cli.rb +41 -4
- data/lib/anway/client.rb +17 -0
- data/lib/anway/configuration.rb +2 -1
- data/lib/anway/cron.rb +46 -0
- data/lib/anway/daemon.rb +1 -1
- data/lib/anway/inspect.rb +93 -0
- data/lib/anway/inspect_command.rb +143 -0
- data/lib/anway/job_info.rb +47 -0
- data/lib/anway/options.rb +7 -5
- data/lib/anway/runner.rb +88 -6
- data/lib/anway/server.rb +7 -0
- data/lib/anway/settings.rb +57 -7
- data/lib/anway/testing.rb +24 -1
- data/lib/anway/version.rb +2 -2
- data/lib/anway/worker.rb +29 -5
- data/lib/anway.rb +77 -0
- data/lib/generators/anway/install/templates/anway.yml +9 -0
- metadata +6 -1
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require 'json'
|
|
4
|
+
|
|
5
|
+
module Anway
|
|
6
|
+
# InspectCommand prints `anway jobs` and `anway job <jid>`.
|
|
7
|
+
#
|
|
8
|
+
# anway jobs one line for each set
|
|
9
|
+
# anway jobs --set retries --type EmitInvoice
|
|
10
|
+
# anway job a1b2c3d4 [--full]
|
|
11
|
+
# --json prints the API answer, for scripts and agents
|
|
12
|
+
class InspectCommand
|
|
13
|
+
BACKTRACE = 3
|
|
14
|
+
|
|
15
|
+
def initialize(api, out: $stdout, now: Time.now)
|
|
16
|
+
@api = api
|
|
17
|
+
@out = out
|
|
18
|
+
@now = now
|
|
19
|
+
end
|
|
20
|
+
|
|
21
|
+
def summary(json: false)
|
|
22
|
+
summary = Inspect.summary(@api)
|
|
23
|
+
|
|
24
|
+
return print_json(summary.to_h) if json
|
|
25
|
+
|
|
26
|
+
summary.sets.each { |line| @out.puts(summary_line(line)) }
|
|
27
|
+
end
|
|
28
|
+
|
|
29
|
+
def list(set:, type: nil, queue: nil, limit: 20, json: false)
|
|
30
|
+
infos = Inspect::Jobs.new(@api, set: set, type: type, queue: queue).first(limit)
|
|
31
|
+
|
|
32
|
+
return print_json(infos.map(&:to_h)) if json
|
|
33
|
+
return @out.puts("no #{set} jobs#{" of #{type}" if type}") if infos.empty?
|
|
34
|
+
|
|
35
|
+
rows = infos.map { |info| [short(info.jid), info.name, info.queue, try(info), when_of(info), error_line(info)] }
|
|
36
|
+
|
|
37
|
+
table(%w[JID TYPE QUEUE TRY NEXT ERROR], rows)
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
# Returns false when the job is not found.
|
|
41
|
+
def show(jid, full: false, json: false)
|
|
42
|
+
reply = @api.job(jid)
|
|
43
|
+
|
|
44
|
+
unless reply
|
|
45
|
+
warn("anway: not found: it finished, or it never existed (#{jid})")
|
|
46
|
+
|
|
47
|
+
return false
|
|
48
|
+
end
|
|
49
|
+
|
|
50
|
+
return print_json(reply) || true if json
|
|
51
|
+
|
|
52
|
+
describe(JobInfo.from_api(reply['job'], set: reply['set']), full)
|
|
53
|
+
|
|
54
|
+
true
|
|
55
|
+
end
|
|
56
|
+
|
|
57
|
+
private
|
|
58
|
+
|
|
59
|
+
def summary_line(line)
|
|
60
|
+
parts = [line[:set].ljust(9), line[:count].to_s.rjust(4)]
|
|
61
|
+
|
|
62
|
+
parts << "oldest #{ago(line[:oldest])}" if line[:set] == 'waiting' && line[:oldest]
|
|
63
|
+
parts << top_line(line[:top], line[:set] == 'working' ? line[:worker] : nil) if line[:top]
|
|
64
|
+
parts << line[:error][:value] if line[:error]
|
|
65
|
+
|
|
66
|
+
parts.join(' ')
|
|
67
|
+
end
|
|
68
|
+
|
|
69
|
+
def top_line(top, worker)
|
|
70
|
+
text = top[:count] > 1 ? "#{top[:value]} ×#{top[:count]}" : top[:value]
|
|
71
|
+
|
|
72
|
+
worker ? "#{text} on #{worker[:value]}" : text
|
|
73
|
+
end
|
|
74
|
+
|
|
75
|
+
def describe(info, full)
|
|
76
|
+
label = info.wrapped ? "#{info.wrapped} (Active Job, wrapper #{info.type})" : info.type
|
|
77
|
+
|
|
78
|
+
@out.puts(label)
|
|
79
|
+
|
|
80
|
+
field('state', state_text(info))
|
|
81
|
+
field('queue', info.queue)
|
|
82
|
+
field('args', JSON.generate(info.args))
|
|
83
|
+
field('custom', JSON.generate(info.custom)) unless info.custom.empty?
|
|
84
|
+
field('enqueued', clock(info.enqueued_at)) if info.enqueued_at
|
|
85
|
+
field('started', "#{clock(info.started_at)} on #{info.worker}") if info.started_at
|
|
86
|
+
|
|
87
|
+
error(info.error, full) if info.error
|
|
88
|
+
end
|
|
89
|
+
|
|
90
|
+
def error(error, full)
|
|
91
|
+
field('error', "#{error[:class]}: #{error[:message]}")
|
|
92
|
+
|
|
93
|
+
lines = full ? error[:backtrace] : error[:backtrace].first(BACKTRACE)
|
|
94
|
+
|
|
95
|
+
lines.each { |line| @out.puts(" #{line}") }
|
|
96
|
+
|
|
97
|
+
rest = error[:backtrace].size - lines.size
|
|
98
|
+
|
|
99
|
+
@out.puts(" (#{rest} lines more, --full shows all)") if rest.positive?
|
|
100
|
+
end
|
|
101
|
+
|
|
102
|
+
def state_text(info)
|
|
103
|
+
return info.state unless %w[retries scheduled].include?(info.state) && info.next_at
|
|
104
|
+
|
|
105
|
+
"#{info.state} (#{"try #{info.retry_count}, " if info.retry_count.positive?}next run #{clock(info.next_at)})"
|
|
106
|
+
end
|
|
107
|
+
|
|
108
|
+
def field(name, value) = @out.puts("#{name.ljust(9)} #{value}")
|
|
109
|
+
|
|
110
|
+
def table(headers, rows)
|
|
111
|
+
widths = headers.each_index.map { |i| ([headers[i]] + rows.map { |row| row[i].to_s }).map(&:length).max }
|
|
112
|
+
|
|
113
|
+
[headers, *rows].each { |row| @out.puts(row.each_with_index.map { |cell, i| cell.to_s.ljust(widths[i]) }.join(' ').rstrip) }
|
|
114
|
+
end
|
|
115
|
+
|
|
116
|
+
def short(jid) = jid.to_s[0, 8]
|
|
117
|
+
|
|
118
|
+
def try(info) = info.retry_count.positive? ? info.retry_count.to_s : '-'
|
|
119
|
+
|
|
120
|
+
def when_of(info) = info.next_at ? "in #{seconds(info.next_at - @now)}" : '-'
|
|
121
|
+
|
|
122
|
+
def error_line(info) = info.error ? "#{info.error[:class]}: #{info.error[:message]}"[0, 60] : ''
|
|
123
|
+
|
|
124
|
+
def ago(time) = seconds(@now - time)
|
|
125
|
+
|
|
126
|
+
def seconds(value)
|
|
127
|
+
value = value.round
|
|
128
|
+
|
|
129
|
+
return "#{value}s" if value.abs < 120
|
|
130
|
+
return "#{value / 60}m" if value.abs < 7200
|
|
131
|
+
|
|
132
|
+
"#{value / 3600}h"
|
|
133
|
+
end
|
|
134
|
+
|
|
135
|
+
def clock(time) = time.localtime.strftime('%H:%M:%S')
|
|
136
|
+
|
|
137
|
+
def print_json(value)
|
|
138
|
+
@out.puts(JSON.pretty_generate(value))
|
|
139
|
+
|
|
140
|
+
nil
|
|
141
|
+
end
|
|
142
|
+
end
|
|
143
|
+
end
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require 'time'
|
|
4
|
+
|
|
5
|
+
module Anway
|
|
6
|
+
# JobInfo is a read-only view of one job on the server, from the HTTP API
|
|
7
|
+
# (Anway.job, Anway.jobs, `anway job`).
|
|
8
|
+
#
|
|
9
|
+
# state is waiting, working, retries, scheduled or dead. wrapped is the
|
|
10
|
+
# Active Job class when the job type is the Active Job wrapper. error has
|
|
11
|
+
# class, message and backtrace when the job failed.
|
|
12
|
+
JobInfo = Data.define(
|
|
13
|
+
:jid, :type, :wrapped, :queue, :state, :args, :custom, :retry_count, :retry_max,
|
|
14
|
+
:next_at, :enqueued_at, :started_at, :worker, :error
|
|
15
|
+
) do
|
|
16
|
+
def self.from_api(view, set: nil)
|
|
17
|
+
custom = view['custom'] || {}
|
|
18
|
+
failure = view['failure']
|
|
19
|
+
|
|
20
|
+
new(
|
|
21
|
+
jid: view['jid'],
|
|
22
|
+
type: view['jobtype'],
|
|
23
|
+
wrapped: custom['wrapped'],
|
|
24
|
+
queue: view['queue'],
|
|
25
|
+
state: set || state_of(view['state']),
|
|
26
|
+
args: view['args'] || [],
|
|
27
|
+
custom: custom,
|
|
28
|
+
retry_count: failure ? failure['retry_count'].to_i + 1 : 0,
|
|
29
|
+
retry_max: view['retry'],
|
|
30
|
+
next_at: time(failure&.dig('next_at')) || (%w[scheduled retries].include?(set) ? time(view['at']) : nil),
|
|
31
|
+
enqueued_at: time(view['enqueued_at']),
|
|
32
|
+
started_at: time(view['started_at']),
|
|
33
|
+
worker: view['worker'],
|
|
34
|
+
error: failure && { class: failure['errtype'], message: failure['message'], backtrace: failure['backtrace'] || [] }
|
|
35
|
+
)
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
def self.state_of(state) = (state == 'queues') ? 'waiting' : state
|
|
39
|
+
|
|
40
|
+
def self.time(value)
|
|
41
|
+
Time.parse(value.to_s) if value && !value.to_s.empty?
|
|
42
|
+
end
|
|
43
|
+
|
|
44
|
+
# The class to show: the Active Job class, else the job type.
|
|
45
|
+
def name = wrapped || type
|
|
46
|
+
end
|
|
47
|
+
end
|
data/lib/anway/options.rb
CHANGED
|
@@ -16,6 +16,8 @@ module Anway
|
|
|
16
16
|
# on_dead { event:, queue: } as { "jobtype", "queue" }
|
|
17
17
|
# custom custom, for the keys of the app. The keys above win.
|
|
18
18
|
# topics one SUBSCRIBE for each topic (a declaration only)
|
|
19
|
+
# cron one entry of the SCHEDULE of the worker for each cron
|
|
20
|
+
# schedule (a declaration only)
|
|
19
21
|
module Options
|
|
20
22
|
# Keys with a wire field of the same name.
|
|
21
23
|
FIELDS = %i[queue retry reserve_for backtrace at].freeze
|
|
@@ -27,8 +29,8 @@ module Anway
|
|
|
27
29
|
PUSH = [*FIELDS, *CUSTOM, :custom].freeze
|
|
28
30
|
|
|
29
31
|
# The keys of a declaration: anway_options. at is only for a push, and
|
|
30
|
-
# topics only for a declaration.
|
|
31
|
-
DECLARATION = [:event, *(PUSH - [:at]), :topics].freeze
|
|
32
|
+
# topics and cron only for a declaration.
|
|
33
|
+
DECLARATION = [:event, *(PUSH - [:at]), :topics, :cron].freeze
|
|
32
34
|
|
|
33
35
|
ON_DEAD = %i[event queue].freeze
|
|
34
36
|
|
|
@@ -43,14 +45,14 @@ module Anway
|
|
|
43
45
|
end
|
|
44
46
|
|
|
45
47
|
# Merges option sets in order. A single value from a later set wins.
|
|
46
|
-
# topics add up in order, with no duplicates. custom hashes
|
|
47
|
-
# later key wins.
|
|
48
|
+
# topics and cron add up in order, with no duplicates. custom hashes
|
|
49
|
+
# merge, and a later key wins.
|
|
48
50
|
def merge(*sets)
|
|
49
51
|
sets.each_with_object({}) do |set, merged|
|
|
50
52
|
set.each do |key, value|
|
|
51
53
|
merged[key] =
|
|
52
54
|
case key
|
|
53
|
-
when :topics then (merged[
|
|
55
|
+
when :topics, :cron then (merged[key] || []) | Array(value).map(&:to_s)
|
|
54
56
|
when :custom then (merged[:custom] || {}).merge(stringify(value))
|
|
55
57
|
else value
|
|
56
58
|
end
|
data/lib/anway/runner.rb
CHANGED
|
@@ -13,6 +13,7 @@ module Anway
|
|
|
13
13
|
ERROR_PAUSE = 1
|
|
14
14
|
EMPTY_FETCH_MINIMUM = 0.2
|
|
15
15
|
BACKTRACE_LINES = 30
|
|
16
|
+
DEFAULT_RETRY = 25
|
|
16
17
|
|
|
17
18
|
attr_reader :wid
|
|
18
19
|
|
|
@@ -22,11 +23,19 @@ module Anway
|
|
|
22
23
|
# as { max: n } or { min: n, max: n }, starts the worker with autoscale on.
|
|
23
24
|
# subscriptions is a list of Worker::Subscription. The default is the
|
|
24
25
|
# subscriptions of all registered job classes, read at run.
|
|
26
|
+
#
|
|
27
|
+
# cron is a list of cron entries (Anway::Cron). The default is the entries
|
|
28
|
+
# of all registered job classes, read at run. The runner sends them in one
|
|
29
|
+
# SCHEDULE with cron_tag, which is tag by default. With entries and no
|
|
30
|
+
# cron_tag, run raises ArgumentError: a default tag could join the entries
|
|
31
|
+
# of two apps on one server.
|
|
25
32
|
def initialize(queues: ['default'], concurrency: 10, timeout: 25, cancel_grace: 5, labels: [],
|
|
26
33
|
hostname: nil, tag: nil, autoscale: nil, limit: nil, subscriptions: nil,
|
|
27
|
-
beat_interval: BEAT_INTERVAL, url: nil, logger: Anway.config.logger)
|
|
34
|
+
cron: nil, cron_tag: tag, beat_interval: BEAT_INTERVAL, url: nil, logger: Anway.config.logger)
|
|
28
35
|
@queues = Queues.new(queues)
|
|
29
36
|
@subscriptions = subscriptions
|
|
37
|
+
@cron = cron
|
|
38
|
+
@cron_tag = cron_tag
|
|
30
39
|
@concurrency = concurrency
|
|
31
40
|
@limit = limit
|
|
32
41
|
@timeout = timeout
|
|
@@ -72,11 +81,15 @@ module Anway
|
|
|
72
81
|
end
|
|
73
82
|
|
|
74
83
|
# The first beat reports the threads, so the server can scale the worker
|
|
75
|
-
# at once. The subscriptions go to the server before
|
|
84
|
+
# at once. The subscriptions and the cron entries go to the server before
|
|
85
|
+
# the first fetch.
|
|
76
86
|
def run
|
|
87
|
+
cron = cron_entries
|
|
88
|
+
|
|
77
89
|
@client.heartbeat(nil, concurrency: @concurrency)
|
|
78
90
|
|
|
79
91
|
subscribe_all
|
|
92
|
+
schedule_all(cron)
|
|
80
93
|
|
|
81
94
|
@lock.synchronize { @processors = Array.new(@concurrency) { start_processor } }
|
|
82
95
|
|
|
@@ -119,6 +132,34 @@ module Anway
|
|
|
119
132
|
end
|
|
120
133
|
end
|
|
121
134
|
|
|
135
|
+
def cron_entries
|
|
136
|
+
entries = @cron || Worker.cron_entries
|
|
137
|
+
|
|
138
|
+
return entries if entries.empty? || @cron_tag
|
|
139
|
+
|
|
140
|
+
raise ArgumentError, 'anway has cron entries but no tag: set tag in config/anway.yml, ANWAY_TAG, or --tag. ' \
|
|
141
|
+
'The server keeps the cron entries of each tag.'
|
|
142
|
+
end
|
|
143
|
+
|
|
144
|
+
# SCHEDULE replaces the entries of the tag, so an entry that the app
|
|
145
|
+
# removed goes away. With no entries, the runner sends nothing, so it does
|
|
146
|
+
# not remove the entries that another process sent for the tag.
|
|
147
|
+
def schedule_all(entries)
|
|
148
|
+
return if entries.empty?
|
|
149
|
+
|
|
150
|
+
@client.schedule(@cron_tag, entries)
|
|
151
|
+
|
|
152
|
+
@logger.info("anway scheduled tag=#{@cron_tag} cron=#{entries.size}")
|
|
153
|
+
|
|
154
|
+
entries.each do |entry|
|
|
155
|
+
queue = entry.dig('job', 'queue') || 'default'
|
|
156
|
+
|
|
157
|
+
next if @queues.names.include?(queue)
|
|
158
|
+
|
|
159
|
+
@logger.warn("anway does not fetch queue #{queue}, so the cron jobs #{entry.dig('job', 'type')} wait there. Add the queue to queues.")
|
|
160
|
+
end
|
|
161
|
+
end
|
|
162
|
+
|
|
122
163
|
def wait_for_stop
|
|
123
164
|
loop do
|
|
124
165
|
@events_reader.wait_readable
|
|
@@ -270,18 +311,59 @@ module Anway
|
|
|
270
311
|
end
|
|
271
312
|
|
|
272
313
|
def perform(job)
|
|
273
|
-
|
|
314
|
+
started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
|
|
315
|
+
|
|
316
|
+
tagged(job) { Thread.handle_interrupt(Shutdown => :immediate) { Executor.call(job) } }
|
|
317
|
+
|
|
318
|
+
@logger.info("anway done #{job_label(job)} #{elapsed(started)}ms")
|
|
274
319
|
|
|
275
320
|
nil
|
|
276
321
|
rescue Exception => e # rubocop:disable Lint/RescueException
|
|
277
|
-
|
|
322
|
+
unless e.is_a?(Shutdown)
|
|
323
|
+
@logger.warn("anway failed #{job_label(job)} try=#{try_of(job)} #{e.class}: #{e.message} (#{after_failure(job)}) #{elapsed(started)}ms")
|
|
324
|
+
|
|
325
|
+
notify_error(e, job)
|
|
326
|
+
end
|
|
278
327
|
|
|
279
328
|
e
|
|
280
329
|
end
|
|
281
330
|
|
|
282
|
-
|
|
283
|
-
|
|
331
|
+
# While a job runs, every line of a tagged logger (Rails.logger, and with
|
|
332
|
+
# it Active Record) carries the job. Tags are per thread, so jobs on two
|
|
333
|
+
# threads keep their own. A logger without tags, or an error in it, never
|
|
334
|
+
# stops the job.
|
|
335
|
+
def tagged(job, &block)
|
|
336
|
+
logger = Anway.config.logger
|
|
337
|
+
|
|
338
|
+
return yield unless Anway.config.log_tags && logger.respond_to?(:tagged)
|
|
339
|
+
|
|
340
|
+
logger.tagged("anway #{job_label(job)} try=#{try_of(job)}", &block)
|
|
341
|
+
end
|
|
342
|
+
|
|
343
|
+
def job_label(job)
|
|
344
|
+
wrapped = job.custom.is_a?(Hash) ? job.custom['wrapped'] : nil
|
|
345
|
+
|
|
346
|
+
"#{wrapped || job.type} jid=#{job.jid}"
|
|
347
|
+
end
|
|
284
348
|
|
|
349
|
+
def try_of(job)
|
|
350
|
+
job.failure.is_a?(Hash) ? job.failure['retry_count'].to_i + 2 : 1
|
|
351
|
+
end
|
|
352
|
+
|
|
353
|
+
# What the server does with this failure (job-lifecycle.md): retry while
|
|
354
|
+
# retries are left, then dead; retry 0 discards, retry -1 goes to dead.
|
|
355
|
+
def after_failure(job)
|
|
356
|
+
retries = job.retry.nil? ? DEFAULT_RETRY : job.retry.to_i
|
|
357
|
+
|
|
358
|
+
return 'discarded' if retries.zero?
|
|
359
|
+
return 'dead' if retries.negative? || try_of(job) > retries
|
|
360
|
+
|
|
361
|
+
'retry'
|
|
362
|
+
end
|
|
363
|
+
|
|
364
|
+
def elapsed(started) = ((Process.clock_gettime(Process::CLOCK_MONOTONIC) - started) * 1000).round
|
|
365
|
+
|
|
366
|
+
def notify_error(error, job)
|
|
285
367
|
Anway.config.error_handlers.each { |handler| handler.call(error, job) }
|
|
286
368
|
rescue StandardError => e
|
|
287
369
|
@logger.error("error handler failed: #{e.message}")
|
data/lib/anway/server.rb
CHANGED
|
@@ -38,6 +38,13 @@ module Anway
|
|
|
38
38
|
|
|
39
39
|
def prepare
|
|
40
40
|
FileUtils.mkdir_p(@settings.data)
|
|
41
|
+
|
|
42
|
+
save_web_token if @settings.random_web_token?
|
|
43
|
+
end
|
|
44
|
+
|
|
45
|
+
def save_web_token
|
|
46
|
+
File.open(@settings.web_token_file, File::WRONLY | File::CREAT | File::TRUNC, 0o600) { |file| file.write(@settings.web_token) }
|
|
47
|
+
File.chmod(0o600, @settings.web_token_file)
|
|
41
48
|
end
|
|
42
49
|
|
|
43
50
|
def announce
|
data/lib/anway/settings.rb
CHANGED
|
@@ -14,6 +14,10 @@ module Anway
|
|
|
14
14
|
# production:
|
|
15
15
|
# url: <%= ENV["ANWAY_URL"] %>
|
|
16
16
|
#
|
|
17
|
+
# cron:
|
|
18
|
+
# - schedule: "0 0 * * *"
|
|
19
|
+
# job: { type: credits.refill, queue: default }
|
|
20
|
+
#
|
|
17
21
|
# The server is embedded, so the app runs it, unless a url is set in the
|
|
18
22
|
# file or in ANWAY_URL. `server: { mode: }` or ANWAY_SERVER can still choose.
|
|
19
23
|
class Settings
|
|
@@ -23,7 +27,7 @@ module Anway
|
|
|
23
27
|
DEFAULT_WEB = '127.0.0.1:7420'
|
|
24
28
|
DEFAULT_CONSOLE = '127.0.0.1:7421'
|
|
25
29
|
MODES = %w[embedded external].freeze
|
|
26
|
-
KEYS = %w[queues concurrency timeout labels hostname tag autoscale require url server console].freeze
|
|
30
|
+
KEYS = %w[queues concurrency timeout labels hostname tag autoscale require url server console log_tags cron].freeze
|
|
27
31
|
SERVER_KEYS = %w[mode bind data password web web_token].freeze
|
|
28
32
|
CONSOLE_KEYS = %w[path bind api token].freeze
|
|
29
33
|
|
|
@@ -65,6 +69,18 @@ module Anway
|
|
|
65
69
|
options.compact
|
|
66
70
|
end
|
|
67
71
|
|
|
72
|
+
# The cron entries of the file, in the format of Anway::Cron: a list in
|
|
73
|
+
# the format of the cron entries of the server conf.d. The section of the
|
|
74
|
+
# environment replaces the list at the top.
|
|
75
|
+
def cron
|
|
76
|
+
@cron ||= Cron.entries(@values['cron'] || [])
|
|
77
|
+
end
|
|
78
|
+
|
|
79
|
+
# log_tags: false turns off the job tags on log lines. On by default.
|
|
80
|
+
def log_tags?
|
|
81
|
+
@values['log_tags'] != false
|
|
82
|
+
end
|
|
83
|
+
|
|
68
84
|
# autoscale: { max: n } or { min: n, max: n }, or nil when it is off.
|
|
69
85
|
def autoscale
|
|
70
86
|
value = @values['autoscale']
|
|
@@ -110,16 +126,43 @@ module Anway
|
|
|
110
126
|
"tcp://#{auth}#{Daemon.local_host(host)}:#{port}"
|
|
111
127
|
end
|
|
112
128
|
|
|
113
|
-
# The address of the HTTP API that the web console
|
|
114
|
-
#
|
|
129
|
+
# The address of the HTTP API that the web console and `anway jobs` read.
|
|
130
|
+
# An embedded server opens it on the loopback; an external one only when
|
|
131
|
+
# it is set.
|
|
115
132
|
def web
|
|
116
|
-
present(@server['web']) || (
|
|
133
|
+
present(@server['web']) || (embedded? ? DEFAULT_WEB : nil)
|
|
117
134
|
end
|
|
118
135
|
|
|
119
|
-
# Without a token in the file, the server and the console
|
|
120
|
-
#
|
|
136
|
+
# Without a token in the file, the server and the console share a random
|
|
137
|
+
# one. A running embedded server saved its token in the data folder, so
|
|
138
|
+
# every process of the app (Puma, workers, `anway jobs`) uses the same.
|
|
121
139
|
def web_token
|
|
122
|
-
present(@server['web_token']) || (web ? (@random_token ||= SecureRandom.hex(16)) : nil)
|
|
140
|
+
present(@server['web_token']) || (web ? (@random_token ||= saved_web_token || SecureRandom.hex(16)) : nil)
|
|
141
|
+
end
|
|
142
|
+
|
|
143
|
+
# True when a random token was saved by a server of this data folder, so
|
|
144
|
+
# another process can use that server.
|
|
145
|
+
def saved_web_token?
|
|
146
|
+
!saved_web_token.nil?
|
|
147
|
+
end
|
|
148
|
+
|
|
149
|
+
# The file where an embedded server keeps its random web token, so that
|
|
150
|
+
# `anway jobs` in another process can read the API. Only this user can
|
|
151
|
+
# read it.
|
|
152
|
+
def web_token_file
|
|
153
|
+
File.join(File.expand_path(data), 'web_token')
|
|
154
|
+
end
|
|
155
|
+
|
|
156
|
+
# The HTTP API that `anway jobs` and Anway.jobs read: ANWAY_API_URL, then
|
|
157
|
+
# console.api, then the embedded server's API.
|
|
158
|
+
def api_url
|
|
159
|
+
present(@env['ANWAY_API_URL']) || console_api
|
|
160
|
+
end
|
|
161
|
+
|
|
162
|
+
# Its token: ANWAY_WEB_TOKEN, then console.token, then server.web_token,
|
|
163
|
+
# then the token file of a running embedded server.
|
|
164
|
+
def api_token
|
|
165
|
+
present(@env['ANWAY_WEB_TOKEN']) || present(@console['token']) || present(@server['web_token']) || saved_web_token
|
|
123
166
|
end
|
|
124
167
|
|
|
125
168
|
# A random token changes at each start, so a server or console from an
|
|
@@ -180,6 +223,12 @@ module Anway
|
|
|
180
223
|
|
|
181
224
|
private
|
|
182
225
|
|
|
226
|
+
def saved_web_token
|
|
227
|
+
present(File.read(web_token_file).strip)
|
|
228
|
+
rescue SystemCallError
|
|
229
|
+
nil
|
|
230
|
+
end
|
|
231
|
+
|
|
183
232
|
def section_of(hash, name, keys)
|
|
184
233
|
value = hash[name]
|
|
185
234
|
|
|
@@ -192,6 +241,7 @@ module Anway
|
|
|
192
241
|
|
|
193
242
|
def check!
|
|
194
243
|
check_autoscale!
|
|
244
|
+
cron
|
|
195
245
|
raise ArgumentError, "server mode must be embedded or external, not #{mode}" unless MODES.include?(mode)
|
|
196
246
|
raise ArgumentError, 'an external server needs url or ANWAY_URL' if mode == 'external' && url.nil?
|
|
197
247
|
raise ArgumentError, "server bind must be host:port, not #{bind}" unless split_bind.last.to_s.match?(/\A\d+\z/)
|
data/lib/anway/testing.rb
CHANGED
|
@@ -9,13 +9,18 @@ module Anway
|
|
|
9
9
|
# Anway::Testing.inline! runs each job at push, and each event in the
|
|
10
10
|
# subscribed classes of the app at publish
|
|
11
11
|
# Anway::Testing.disable! uses the real client
|
|
12
|
+
#
|
|
13
|
+
# In both test modes, Anway.schedule and Anway.unschedule change
|
|
14
|
+
# Testing.schedules, a hash of the cron entries of each tag. Anway.cron
|
|
15
|
+
# lists the cron entries that the worker of the app declares.
|
|
12
16
|
module Testing
|
|
13
17
|
@mode = nil
|
|
14
18
|
@jobs = []
|
|
15
19
|
@events = []
|
|
20
|
+
@schedules = {}
|
|
16
21
|
|
|
17
22
|
class << self
|
|
18
|
-
attr_reader :jobs, :events, :mode
|
|
23
|
+
attr_reader :jobs, :events, :schedules, :mode
|
|
19
24
|
|
|
20
25
|
def fake!
|
|
21
26
|
@mode = :fake
|
|
@@ -32,6 +37,24 @@ module Anway
|
|
|
32
37
|
def clear
|
|
33
38
|
@jobs.clear
|
|
34
39
|
@events.clear
|
|
40
|
+
@schedules.clear
|
|
41
|
+
end
|
|
42
|
+
|
|
43
|
+
# Keeps the entries of the tag, in the format of Anway::Cron, as the
|
|
44
|
+
# server does: they replace the entries of the tag, and no entries
|
|
45
|
+
# remove it. The server checks the schedules, and this does not.
|
|
46
|
+
def schedule(tag, entries)
|
|
47
|
+
entries = Cron.entries(entries.to_a)
|
|
48
|
+
|
|
49
|
+
entries.empty? ? @schedules.delete(tag.to_s) : @schedules[tag.to_s] = entries
|
|
50
|
+
|
|
51
|
+
true
|
|
52
|
+
end
|
|
53
|
+
|
|
54
|
+
def unschedule(tag)
|
|
55
|
+
@schedules.delete(tag.to_s)
|
|
56
|
+
|
|
57
|
+
true
|
|
35
58
|
end
|
|
36
59
|
|
|
37
60
|
def enqueue(job)
|
data/lib/anway/version.rb
CHANGED
data/lib/anway/worker.rb
CHANGED
|
@@ -8,6 +8,7 @@ module Anway
|
|
|
8
8
|
#
|
|
9
9
|
# anway_options event: 'email.welcome', retry: 5
|
|
10
10
|
# anway_options topics: %w[user.created], queue: 'mailers'
|
|
11
|
+
# anway_options cron: '0 9 * * *'
|
|
11
12
|
#
|
|
12
13
|
# def perform(user_id); end
|
|
13
14
|
# end
|
|
@@ -18,7 +19,8 @@ module Anway
|
|
|
18
19
|
#
|
|
19
20
|
# The keys are the input contract (Anway::Options). The event is the job
|
|
20
21
|
# type on the wire, and the default is the class name. Each topic makes one
|
|
21
|
-
# subscription,
|
|
22
|
+
# subscription, and each cron schedule one cron entry. The worker sends both
|
|
23
|
+
# when it starts.
|
|
22
24
|
module Worker
|
|
23
25
|
DEFAULT_BACKTRACE = 30
|
|
24
26
|
|
|
@@ -27,7 +29,7 @@ module Anway
|
|
|
27
29
|
Subscription = Data.define(:topic, :queue, :event, :retry, :reserve_for)
|
|
28
30
|
|
|
29
31
|
# A subclass does not inherit these keys.
|
|
30
|
-
OWN_KEYS = %i[event topics].freeze
|
|
32
|
+
OWN_KEYS = %i[event topics cron].freeze
|
|
31
33
|
|
|
32
34
|
@registry = {}
|
|
33
35
|
@lock = Mutex.new
|
|
@@ -67,6 +69,12 @@ module Anway
|
|
|
67
69
|
classes.flat_map(&:subscriptions).uniq
|
|
68
70
|
end
|
|
69
71
|
|
|
72
|
+
# The cron entries of all registered classes, in the format of
|
|
73
|
+
# Anway::Cron. A worker sends them with SCHEDULE when it starts.
|
|
74
|
+
def cron_entries
|
|
75
|
+
classes.flat_map(&:cron_entries).uniq
|
|
76
|
+
end
|
|
77
|
+
|
|
70
78
|
# Only registered classes run. The event comes from the network, so it
|
|
71
79
|
# never becomes a constant lookup. The lookup by the class name below
|
|
72
80
|
# uses a registered name, and returns the newest class after a reload.
|
|
@@ -101,8 +109,8 @@ module Anway
|
|
|
101
109
|
# Anway::Options::DECLARATION, and an unknown key raises ArgumentError.
|
|
102
110
|
#
|
|
103
111
|
# Without keys, returns the options of the class: the options of the
|
|
104
|
-
# parent class without event and
|
|
105
|
-
# event and
|
|
112
|
+
# parent class without event, topics, and cron, then each set in call
|
|
113
|
+
# order. event, topics, and cron are always in the result.
|
|
106
114
|
def anway_options(**options)
|
|
107
115
|
return declared_options if options.empty?
|
|
108
116
|
|
|
@@ -139,6 +147,22 @@ module Anway
|
|
|
139
147
|
end
|
|
140
148
|
end
|
|
141
149
|
|
|
150
|
+
# One cron entry for each cron schedule. Its job has the event, queue,
|
|
151
|
+
# retry, and reserve_for of the class. Without a queue, the job goes to
|
|
152
|
+
# default.
|
|
153
|
+
def cron_entries
|
|
154
|
+
options = declared_options
|
|
155
|
+
|
|
156
|
+
job = {
|
|
157
|
+
'type' => options[:event],
|
|
158
|
+
'queue' => (options[:queue] || 'default').to_s,
|
|
159
|
+
'retry' => options[:retry],
|
|
160
|
+
'reserve_for' => options[:reserve_for]
|
|
161
|
+
}.compact
|
|
162
|
+
|
|
163
|
+
options[:cron].map { |schedule| { 'schedule' => schedule, 'job' => job } }
|
|
164
|
+
end
|
|
165
|
+
|
|
142
166
|
def perform_async(*args)
|
|
143
167
|
enqueue_with(args, {})
|
|
144
168
|
end
|
|
@@ -204,7 +228,7 @@ module Anway
|
|
|
204
228
|
def declared_options
|
|
205
229
|
parent = superclass.respond_to?(:anway_options) ? superclass.anway_options.except(*OWN_KEYS) : {}
|
|
206
230
|
|
|
207
|
-
Options.merge({ event: name, topics: [] }, parent, *@anway_option_sets).freeze
|
|
231
|
+
Options.merge({ event: name, topics: [], cron: [] }, parent, *@anway_option_sets).freeze
|
|
208
232
|
end
|
|
209
233
|
|
|
210
234
|
# A set with an event that another class has does not stay.
|