robin-compat 0.1.2

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.
Files changed (59) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +28 -0
  3. data/COPYING +674 -0
  4. data/LICENSE +165 -0
  5. data/README.md +258 -0
  6. data/exe/sidekiq +5 -0
  7. data/exe/sidekiqswarm +6 -0
  8. data/lib/robin/compat/cron_line.rb +46 -0
  9. data/lib/robin/compat/version.rb +8 -0
  10. data/lib/robin-compat.rb +3 -0
  11. data/lib/sidekiq/active_job.rb +87 -0
  12. data/lib/sidekiq/api.rb +352 -0
  13. data/lib/sidekiq/batch.rb +175 -0
  14. data/lib/sidekiq/capsule.rb +38 -0
  15. data/lib/sidekiq/cli.rb +70 -0
  16. data/lib/sidekiq/client.rb +84 -0
  17. data/lib/sidekiq/config.rb +190 -0
  18. data/lib/sidekiq/cron/job.rb +555 -0
  19. data/lib/sidekiq/cron/poller.rb +47 -0
  20. data/lib/sidekiq/cron/schedule_loader.rb +41 -0
  21. data/lib/sidekiq/cron/web.rb +7 -0
  22. data/lib/sidekiq/cron.rb +146 -0
  23. data/lib/sidekiq/deploy.rb +62 -0
  24. data/lib/sidekiq/iterable_job.rb +55 -0
  25. data/lib/sidekiq/job.rb +207 -0
  26. data/lib/sidekiq/job_retry.rb +23 -0
  27. data/lib/sidekiq/limiter.rb +144 -0
  28. data/lib/sidekiq/logger.rb +25 -0
  29. data/lib/sidekiq/middleware/chain.rb +27 -0
  30. data/lib/sidekiq/middleware/current_attributes.rb +19 -0
  31. data/lib/sidekiq/middleware/modules.rb +15 -0
  32. data/lib/sidekiq/middleware/server/statsd.rb +3 -0
  33. data/lib/sidekiq/periodic.rb +94 -0
  34. data/lib/sidekiq/pro/metrics.rb +134 -0
  35. data/lib/sidekiq/pro/web.rb +5 -0
  36. data/lib/sidekiq/rails.rb +18 -0
  37. data/lib/sidekiq/redis_connection.rb +166 -0
  38. data/lib/sidekiq/scheduler.rb +4 -0
  39. data/lib/sidekiq/testing/inline.rb +5 -0
  40. data/lib/sidekiq/testing.rb +188 -0
  41. data/lib/sidekiq/web.rb +112 -0
  42. data/lib/sidekiq-cron.rb +4 -0
  43. data/lib/sidekiq-ent/periodic/testing.rb +4 -0
  44. data/lib/sidekiq-ent/web.rb +5 -0
  45. data/lib/sidekiq-ent.rb +90 -0
  46. data/lib/sidekiq-pro.rb +16 -0
  47. data/lib/sidekiq-scheduler/config.rb +65 -0
  48. data/lib/sidekiq-scheduler/manager.rb +34 -0
  49. data/lib/sidekiq-scheduler/poller.rb +46 -0
  50. data/lib/sidekiq-scheduler/redis_manager.rb +108 -0
  51. data/lib/sidekiq-scheduler/schedule.rb +65 -0
  52. data/lib/sidekiq-scheduler/scheduled_job.rb +80 -0
  53. data/lib/sidekiq-scheduler/scheduler.rb +218 -0
  54. data/lib/sidekiq-scheduler/utils.rb +120 -0
  55. data/lib/sidekiq-scheduler/version.rb +6 -0
  56. data/lib/sidekiq-scheduler/web.rb +7 -0
  57. data/lib/sidekiq-scheduler.rb +48 -0
  58. data/lib/sidekiq.rb +222 -0
  59. metadata +121 -0
@@ -0,0 +1,19 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "sidekiq"
4
+ require "robin/rails/current_attributes"
5
+
6
+ module Sidekiq
7
+ # Carries ActiveSupport::CurrentAttributes into jobs:
8
+ #
9
+ # Sidekiq::CurrentAttributes.persist("Current")
10
+ # Sidekiq::CurrentAttributes.persist(["Current", "Tenant::Current"])
11
+ #
12
+ # They're kept in the job as Sidekiq keeps them ("cattr", "cattr_1"...),
13
+ # so jobs pushed by either run with them.
14
+ module CurrentAttributes
15
+ def self.persist(klass_or_array, config = Sidekiq.default_configuration)
16
+ Robin::Rails::CurrentAttributes.install(config, klass_or_array)
17
+ end
18
+ end
19
+ end
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Sidekiq
4
+ # Helpers for middleware classes: +config+, +logger+, +redis+ and
5
+ # +redis_pool+ (the configuration is set when the middleware is built).
6
+ module ServerMiddleware
7
+ include Robin::Middleware::ConfigAware
8
+
9
+ def redis(&) = Sidekiq.redis(&)
10
+
11
+ def redis_pool = Sidekiq.redis_pool
12
+ end
13
+
14
+ ClientMiddleware = ServerMiddleware
15
+ end
@@ -0,0 +1,3 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "sidekiq/pro/metrics"
@@ -0,0 +1,94 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "sidekiq"
4
+
5
+ module Sidekiq
6
+ # Sidekiq Enterprise's periodic jobs, as Robin::Periodic's:
7
+ #
8
+ # Sidekiq.configure_server do |config|
9
+ # config.periodic do |mgr|
10
+ # mgr.tz = ActiveSupport::TimeZone.new("Pacific Time (US & Canada)")
11
+ # mgr.register("0 * * * *", "HourlyReport", retry: 2, "args" => ["summary"])
12
+ # end
13
+ # end
14
+ module Periodic
15
+ # What config.periodic yields.
16
+ class Manager
17
+ def initialize(registry)
18
+ @registry = registry
19
+ end
20
+
21
+ # The zone of the jobs registered after it's set (an
22
+ # ActiveSupport::TimeZone, TZInfo zone or name); nil is the system's.
23
+ attr_accessor :tz
24
+
25
+ # Options are the job's ("retry", "queue"...), with String or Symbol
26
+ # keys, plus "args" (static), "tz" (this job's zone) and Robin's
27
+ # "description".
28
+ def register(cron, klass, options = {})
29
+ options = options.transform_keys(&:to_sym)
30
+ zone = options.delete(:tz) || tz
31
+ @registry.register(cron, klass, **options, tz: Periodic.zone_name(zone))
32
+ end
33
+ end
34
+
35
+ # Each periodic job, as Sidekiq Enterprise's LoopSet lists them.
36
+ class LoopSet
37
+ include Enumerable
38
+
39
+ # A periodic job: its id, cron schedule, class name, zone, job
40
+ # options, next run (a Time) and history ([jid, Time] pairs, newest
41
+ # first).
42
+ Loop = Struct.new(:lid, :schedule, :klass, :tz, :options, :next_run, :history)
43
+
44
+ # How many runs a Loop's history shows.
45
+ HISTORY = 25
46
+
47
+ def each
48
+ return to_enum unless block_given?
49
+
50
+ Robin::Periodic.list(history: HISTORY).each do |entry|
51
+ history = entry.fetch("history").map { |run| [run.fetch("jid"), Periodic.time(run.fetch("at"))] }
52
+ yield Loop.new(entry.fetch("id"), entry.fetch("cron"), entry.fetch("class"), entry.fetch("tz"),
53
+ entry.fetch("options").merge({"queue" => entry.fetch("queue"), "args" => entry.fetch("args")}),
54
+ entry.fetch("next_at")&.then { |ms| Periodic.time(ms) }, history)
55
+ end
56
+ end
57
+
58
+ def size = count
59
+ end
60
+
61
+ # Checks a periodic configuration in a test (raising
62
+ # Robin::Periodic::Invalid with every problem found):
63
+ #
64
+ # Sidekiq::Periodic::ConfigTester.new.verify { |mgr| mgr.register(...) }
65
+ class ConfigTester
66
+ def verify(&block)
67
+ Robin::Periodic.verify! { |registry| block.call(Manager.new(registry)) }
68
+ true
69
+ end
70
+ end
71
+
72
+ class << self
73
+ # A zone's IANA name (nil for none: the system's zone).
74
+ def zone_name(zone)
75
+ return zone.tzinfo.name if zone.respond_to?(:tzinfo)
76
+ return zone.identifier if zone.respond_to?(:identifier)
77
+
78
+ zone&.to_s
79
+ end
80
+
81
+ def time(ms) = Time.at(Rational(ms, 1000))
82
+ end
83
+ end
84
+
85
+ # Sidekiq Enterprise's cron parser.
86
+ class CronParser
87
+ def initialize(expression, tz: nil)
88
+ @cron = Robin::Cron.new(expression, tz: Periodic.zone_name(tz))
89
+ end
90
+
91
+ # The next run after +after+ (a Time).
92
+ def next(after = Time.now) = @cron.next_time(after)
93
+ end
94
+ end
@@ -0,0 +1,134 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "socket"
4
+ require "sidekiq"
5
+
6
+ module Sidekiq
7
+ module Pro
8
+ # Sidekiq Pro's StatsD metrics, sent through the app's dogstatsd
9
+ # client with Sidekiq Pro's names (prefixed "sidekiq.", except for apps
10
+ # written for Sidekiq 7: see Metrics.name):
11
+ #
12
+ # config.dogstatsd = -> { Datadog::Statsd.new("localhost", 8125) }
13
+ # config.server_middleware { |chain| chain.add Sidekiq::Middleware::Server::Statsd }
14
+ #
15
+ # config[:use_datadog_extensions] = false leaves out the *_dist
16
+ # (Datadog distribution) metrics.
17
+ module Metrics
18
+ # Robin's event names and the names Sidekiq Pro sends them under.
19
+ NAMES = {
20
+ "jobs.recovered" => "jobs.recovered.fetch", "batch.duration" => "batches.duration",
21
+ "batch.duration_dist" => "batches.duration_dist"
22
+ }.freeze
23
+
24
+ @lock = Mutex.new
25
+
26
+ class << self
27
+ # The dogstatsd client (made by the factory on first use).
28
+ # mutant:disable -- the lock only matters to threads racing to
29
+ # make the client, which a test can't stage deterministically.
30
+ def client = @lock.synchronize { @client ||= @factory&.call }
31
+
32
+ def install(config, factory)
33
+ @factory = factory
34
+ @client = nil
35
+ config.statsd = Events.new
36
+ end
37
+
38
+ def distributions? = Sidekiq.default_configuration.fetch(:use_datadog_extensions, true)
39
+
40
+ # A metric's full name: prefixed "sidekiq." as from Pro 8.0 (Pro 7
41
+ # leaves it to the client's namespace).
42
+ def name(metric) = Sidekiq.compatible_before?("8.0") ? metric : "sidekiq.#{metric}"
43
+
44
+ # Sends a metric with the client, if there is one. Like Robin's
45
+ # own StatsD client, network trouble never raises into the code it
46
+ # measures.
47
+ def emit(method, *args, **options)
48
+ client&.public_send(method, *args, **options)
49
+ nil
50
+ rescue IOError, SystemCallError, SocketError
51
+ nil
52
+ end
53
+ end
54
+
55
+ # Robin's StatsD events (batches, recovered and poison pill jobs...)
56
+ # forwarded to the dogstatsd client under Sidekiq Pro's names. Job
57
+ # counts and timings come from Middleware::Server::Statsd instead.
58
+ class Events
59
+ def dogstatsd? = true
60
+
61
+ def distributions? = Metrics.distributions?
62
+
63
+ def increment(name, value = 1, tags: {}) = Metrics.emit(:increment, metric(name), by: value, tags: tags(tags))
64
+
65
+ def gauge(name, value, tags: {}) = Metrics.emit(:gauge, metric(name), value, tags: tags(tags))
66
+
67
+ def timing(name, ms, tags: {}) = Metrics.emit(:timing, metric(name), ms, tags: tags(tags))
68
+
69
+ def distribution(name, value, tags: {})
70
+ return if name == "jobs.perform_dist" # sent by the middleware, with Sidekiq's tags
71
+
72
+ Metrics.emit(:distribution, metric(name), value, tags: tags(tags))
73
+ end
74
+
75
+ def job_metrics(_jobs)
76
+ end
77
+
78
+ def queue_metrics(_queues)
79
+ end
80
+
81
+ def close
82
+ end
83
+
84
+ private
85
+
86
+ def metric(name) = Metrics.name(NAMES.fetch(name, name))
87
+
88
+ def tags(tags) = tags.flat_map { |key, value| Array(value).map { |v| "#{key}:#{v}" } }
89
+ end
90
+ end
91
+ end
92
+
93
+ module Middleware
94
+ module Server
95
+ # Counts and times jobs: sidekiq.jobs.count, .success, .failure,
96
+ # .perform (ms) and .perform_dist, tagged worker:<class> and
97
+ # queue:<queue> (Statsd.options may supply other options).
98
+ class Statsd
99
+ include Robin::Middleware::Stateless
100
+
101
+ class << self
102
+ # A callable (class name, job, queue) returning the options sent
103
+ # with each metric (tags:, sample_rate:...).
104
+ attr_accessor :options
105
+ end
106
+
107
+ def call(_job, payload, queue)
108
+ started = monotonic
109
+ ok = false
110
+ result = yield
111
+ ok = true
112
+ result
113
+ ensure
114
+ report(payload, queue, ok, (monotonic - started) * 1000)
115
+ end
116
+
117
+ private
118
+
119
+ def monotonic = ::Process.clock_gettime(::Process::CLOCK_MONOTONIC)
120
+
121
+ def report(payload, queue, ok, ms)
122
+ klass = Robin.display_class(payload)
123
+ options = self.class.options&.call(klass, payload, queue) || {tags: ["worker:#{klass}", "queue:#{queue}"]}
124
+ Pro::Metrics.emit(:increment, Pro::Metrics.name("jobs.count"), **options)
125
+ Pro::Metrics.emit(:increment, Pro::Metrics.name(ok ? "jobs.success" : "jobs.failure"), **options)
126
+ Pro::Metrics.emit(:timing, Pro::Metrics.name("jobs.perform"), ms, **options)
127
+ Pro::Metrics.emit(:distribution, Pro::Metrics.name("jobs.perform_dist"), ms, **options) if Pro::Metrics.distributions?
128
+ rescue => e # from Statsd.options; the job's outcome stands
129
+ Robin.config.handle_exception(e, {context: "statsd options", job: payload})
130
+ end
131
+ end
132
+ end
133
+ end
134
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Robin's dashboard already shows batches, rate limiters and periodic
4
+ # jobs.
5
+ require "sidekiq/web"
@@ -0,0 +1,18 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Robin's Rails integration does the rest of the Rails wiring; loaded now,
4
+ # so its Railtie joins the app's boot even if robin was loaded first.
5
+ require "robin/rails"
6
+
7
+ module Sidekiq
8
+ # Sets up Active Job's :sidekiq adapter name and sidekiq_options on
9
+ # Active Job classes.
10
+ class Rails < ::Rails::Railtie
11
+ # Before Active Job looks up the configured adapter. Loaded right away
12
+ # (without loading ActiveJob::Base), so a server can run jobs naming
13
+ # Sidekiq's wrapper classes before anything loads Active Job.
14
+ initializer "sidekiq.active_job", before: "active_job.set_configs" do
15
+ require "sidekiq/active_job" if defined?(::ActiveJob::Railtie)
16
+ end
17
+ end
18
+ end
@@ -0,0 +1,166 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Sidekiq
4
+ # What Sidekiq.redis yields: a Robin connection that speaks the
5
+ # redis-client interface apps use with Sidekiq.
6
+ #
7
+ # Sidekiq.redis do |conn|
8
+ # conn.set("lock", "1", nx: true, ex: 60) # keyword arguments become flags
9
+ # conn.call("HGETALL", "h") # => {"field" => "value"}
10
+ # conn.pipelined { |p| p.incr("a"); p.incr("b") }
11
+ # end
12
+ #
13
+ # Replies come back in the shapes RESP3 gives them, as redis-client
14
+ # returns them: hashes for HGETALL and CONFIG GET, [member, score]
15
+ # pairs for sorted-set ranges WITHSCORES, Floats for scores.
16
+ module RedisConnection
17
+ # Turns call arguments into a command: keyword arguments become flags
18
+ # (+true+ adds just the name, +false+/+nil+ leave it out, anything else
19
+ # adds the name and the value), Arrays are flattened, Hashes splatted.
20
+ def self.command(args, kwargs)
21
+ command = args.flat_map { |arg| arg.is_a?(Hash) ? arg.to_a.flatten : arg }
22
+ kwargs.each do |name, value|
23
+ next unless value
24
+
25
+ command << name.to_s.upcase
26
+ command << value unless value.equal?(true)
27
+ end
28
+ command
29
+ end
30
+
31
+ # The RESP3-shaped reply to +command+ (see the module docs).
32
+ def self.shape(command, reply)
33
+ name, subcommand = command
34
+ case name.to_s.upcase
35
+ when "HGETALL" then reply.each_slice(2).to_h
36
+ when "CONFIG" then subcommand.to_s.casecmp?("GET") ? reply.each_slice(2).to_h : reply
37
+ when "ZSCORE", "ZINCRBY", "INCRBYFLOAT", "HINCRBYFLOAT"
38
+ reply && Float(reply)
39
+ when "ZMSCORE"
40
+ reply.map { |score| score && Float(score) }
41
+ when "ZPOPMIN", "ZPOPMAX"
42
+ pairs(reply)
43
+ when "ZRANGE", "ZRANGEBYSCORE", "ZREVRANGE", "ZREVRANGEBYSCORE", "ZRANDMEMBER", "ZUNION", "ZINTER", "ZDIFF"
44
+ (command.any? { |arg| arg.to_s.casecmp?("WITHSCORES") }) ? pairs(reply) : reply
45
+ else reply
46
+ end
47
+ end
48
+
49
+ def self.pairs(reply) = reply.each_slice(2).map { |member, score| [member, Float(score)] }
50
+
51
+ # Commands collected for a pipeline or transaction.
52
+ class Collector
53
+ attr_reader :commands
54
+
55
+ def initialize
56
+ @commands = []
57
+ end
58
+
59
+ def call(*args, **kwargs)
60
+ @commands << RedisConnection.command(args, kwargs)
61
+ nil
62
+ end
63
+
64
+ def method_missing(name, *args, **kwargs) = call(name.to_s, *args, **kwargs)
65
+
66
+ def respond_to_missing?(*) = true
67
+ end
68
+
69
+ class Connection
70
+ def initialize(conn)
71
+ @conn = conn
72
+ end
73
+
74
+ # The Robin::Redis::Connection underneath.
75
+ attr_reader :conn
76
+
77
+ def call(*args, **kwargs)
78
+ command = RedisConnection.command(args, kwargs)
79
+ RedisConnection.shape(command, @conn.call(*command))
80
+ end
81
+
82
+ def blocking_call(timeout, *args, **kwargs)
83
+ command = RedisConnection.command(args, kwargs)
84
+ RedisConnection.shape(command, @conn.blocking_call(timeout || 0, *command))
85
+ end
86
+
87
+ def pipelined
88
+ collector = Collector.new
89
+ yield collector
90
+ replies = @conn.pipelined { |p| collector.commands.each { |command| p.call(*command) } }
91
+ collector.commands.zip(replies).map { |command, reply| RedisConnection.shape(command, reply) }
92
+ end
93
+
94
+ def multi
95
+ collector = Collector.new
96
+ yield collector
97
+ replies = @conn.multi { |tx| collector.commands.each { |command| tx.call(*command) } }
98
+ collector.commands.zip(replies).map { |command, reply| RedisConnection.shape(command, reply) }
99
+ end
100
+
101
+ # Iterates with SCAN (or SSCAN, HSCAN, ZSCAN on +key+), yielding each
102
+ # element (HSCAN and ZSCAN: each [field, value] or [member, score]).
103
+ def scan(*args, **kwargs, &) = cursor_scan("SCAN", nil, args, kwargs, &)
104
+
105
+ def sscan(key, *args, **kwargs, &) = cursor_scan("SSCAN", key, args, kwargs, &)
106
+
107
+ def hscan(key, *args, **kwargs, &) = cursor_scan("HSCAN", key, args, kwargs, &)
108
+
109
+ def zscan(key, *args, **kwargs, &) = cursor_scan("ZSCAN", key, args, kwargs, &)
110
+
111
+ # INFO as a Hash (section headers and blank lines left out).
112
+ def info(*sections)
113
+ call("INFO", sections).each_line.with_object({}) do |line, info|
114
+ key, value = line.chomp.split(":", 2)
115
+ info[key] = value if value
116
+ end
117
+ end
118
+
119
+ def exists?(*keys) = call("EXISTS", keys).positive?
120
+
121
+ def evalsha(sha, keys = [], argv = []) = call("EVALSHA", sha, keys.size, keys, argv)
122
+
123
+ def close = @conn.close
124
+
125
+ def connected? = true
126
+
127
+ def method_missing(name, *args, **kwargs) = call(name.to_s, *args, **kwargs)
128
+
129
+ def respond_to_missing?(*) = true
130
+
131
+ private
132
+
133
+ def cursor_scan(command, key, args, kwargs, &block)
134
+ return to_enum(:cursor_scan, command, key, args, kwargs) unless block
135
+
136
+ pairs = %w[HSCAN ZSCAN].include?(command)
137
+ cursor = "0"
138
+ loop do
139
+ cursor, items = call(command, *key, cursor, args, **kwargs)
140
+ items = items.each_slice(2).map { |a, b| [a, (command == "ZSCAN") ? Float(b) : b] } if pairs
141
+ items.each(&block)
142
+ break if cursor == "0"
143
+ end
144
+ end
145
+ end
146
+
147
+ # What Sidekiq.redis_pool returns: Robin's pool, yielding Connections.
148
+ class Pool
149
+ def initialize(pool)
150
+ @pool = pool
151
+ end
152
+
153
+ # The Robin::Redis::Pool underneath.
154
+ attr_reader :pool
155
+
156
+ def with
157
+ @pool.with { |conn| yield Connection.new(conn) }
158
+ end
159
+ alias_method :then, :with
160
+
161
+ def size = @pool.size
162
+
163
+ def shutdown(&) = @pool.shutdown
164
+ end
165
+ end
166
+ end
@@ -0,0 +1,4 @@
1
+ # frozen_string_literal: true
2
+
3
+ # sidekiq-scheduler's interface, on Robin (see SidekiqScheduler).
4
+ require "sidekiq-scheduler"
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "sidekiq/testing"
4
+
5
+ Sidekiq::Testing.inline!
@@ -0,0 +1,188 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "sidekiq"
4
+
5
+ module Sidekiq
6
+ # Sidekiq's testing modes. Requiring "sidekiq/testing" switches to fake
7
+ # mode: pushed jobs are kept in memory (Sidekiq::Queues) instead of
8
+ # going to Redis.
9
+ #
10
+ # HardJob.perform_async(1)
11
+ # assert_equal 1, HardJob.jobs.size
12
+ # HardJob.drain
13
+ #
14
+ # Sidekiq::Testing.inline! { HardJob.perform_async(2) } # runs it now
15
+ #
16
+ # Jobs run in tests go through Sidekiq::Testing.server_middleware, which
17
+ # is empty unless a test adds to it, not the configured server chain.
18
+ class Testing
19
+ # Sidekiq 7.2+ raises it for a nested test mode, which robin-compat
20
+ # allows (see .switch). Kept for apps that rescue it.
21
+ class TestModeAlreadySetError < RuntimeError; end
22
+
23
+ MODE_KEY = :sidekiq_test_mode
24
+
25
+ class << self
26
+ attr_accessor :global_mode
27
+
28
+ def fake!(&) = switch(:fake, &)
29
+
30
+ def inline!(&) = switch(:inline, &)
31
+
32
+ def disable!(&) = switch(:disable, &)
33
+
34
+ def mode = Thread.current[MODE_KEY] || global_mode
35
+
36
+ def enabled? = !disabled?
37
+
38
+ def disabled? = mode == :disable
39
+
40
+ def fake? = mode == :fake
41
+
42
+ def inline? = mode == :inline
43
+
44
+ # Sidekiq's internal names, which some test helpers call.
45
+ alias_method :__test_mode, :mode
46
+
47
+ # The middleware jobs run through in tests (empty by default).
48
+ def server_middleware
49
+ @server_chain ||= Middleware::Chain.new(Robin::Middleware::Chain.new(Robin.config))
50
+ yield @server_chain if block_given?
51
+ @server_chain
52
+ end
53
+
54
+ # Called by the client in place of a Redis push: returns the
55
+ # payloads it took, or nil to let them go to Redis.
56
+ def intercept(payloads)
57
+ if fake?
58
+ now = Robin.now_ms
59
+ payloads.each do |job|
60
+ job = Robin.load_json(Robin.dump_json(job))
61
+ # As in Sidekiq, only a job due later keeps its "at"; the rest
62
+ # count as pushed now.
63
+ unless job.key?("at") && job.fetch("at") > Robin.epoch_seconds(now)
64
+ job.delete("at")
65
+ job["enqueued_at"] = Robin.config.job_timestamp(now)
66
+ end
67
+ Queues.push(job.fetch("queue"), job.fetch("class"), job)
68
+ end
69
+ elsif inline?
70
+ payloads.each do |job|
71
+ job = Robin.load_json(Robin.dump_json(job))
72
+ job_class(job.fetch("class")).process_job(job)
73
+ end
74
+ end
75
+ end
76
+
77
+ def __set_test_mode(mode, &) = switch(mode, &)
78
+
79
+ # The job class named +name+.
80
+ # mutant:disable -- `const_get` on Testing instead of Object differs
81
+ # only for constants nested in Testing, none of which are job classes.
82
+ def job_class(name) = Object.const_get(name)
83
+
84
+ private
85
+
86
+ # A block's mode lasts for the block, on its thread. Blocks may nest,
87
+ # as in Sidekiq 7.0 and 7.1 (from 7.2, Sidekiq raises
88
+ # TestModeAlreadySetError instead).
89
+ def switch(mode)
90
+ return self.global_mode = mode unless block_given?
91
+
92
+ previous = Thread.current[MODE_KEY]
93
+ Thread.current[MODE_KEY] = mode
94
+ begin
95
+ yield
96
+ ensure
97
+ Thread.current[MODE_KEY] = previous
98
+ end
99
+ end
100
+ end
101
+ end
102
+
103
+ class EmptyQueueError < RuntimeError; end
104
+
105
+ # The jobs pushed in fake mode, by queue and by class. The arrays are
106
+ # live: tests may change them.
107
+ module Queues
108
+ class << self
109
+ def [](queue) = jobs_by_queue[queue.to_s]
110
+
111
+ def push(queue, klass, job)
112
+ self[queue] << job
113
+ jobs_by_class[klass] << job
114
+ end
115
+
116
+ def jobs_by_queue = @jobs_by_queue ||= Hash.new { |h, k| h[k] = [] }
117
+
118
+ def jobs_by_class = @jobs_by_class ||= Hash.new { |h, k| h[k] = [] }
119
+ alias_method :jobs_by_worker, :jobs_by_class
120
+
121
+ def delete_for(jid, queue, klass)
122
+ self[queue].delete_if { |job| job["jid"] == jid }
123
+ jobs_by_class[klass].delete_if { |job| job["jid"] == jid }
124
+ end
125
+
126
+ def clear_for(queue, klass)
127
+ self[queue].clear
128
+ jobs_by_class[klass].clear
129
+ end
130
+
131
+ def clear_all
132
+ jobs_by_queue.clear
133
+ jobs_by_class.clear
134
+ end
135
+ end
136
+ end
137
+
138
+ module Job
139
+ # Fake-mode helpers on job classes.
140
+ module TestingMethods
141
+ def queue = get_sidekiq_options.fetch("queue")
142
+
143
+ def jobs = Queues.jobs_by_class[to_s]
144
+
145
+ def clear = Queues.clear_for(queue, to_s)
146
+
147
+ # Runs the jobs of this class (including any they push), in the
148
+ # order they were pushed.
149
+ def drain
150
+ while (job = jobs.first)
151
+ Queues.delete_for(job["jid"], job["queue"], to_s)
152
+ process_job(job)
153
+ end
154
+ end
155
+
156
+ def perform_one
157
+ job = jobs.first or raise(EmptyQueueError, "perform_one called with empty job queue")
158
+ Queues.delete_for(job["jid"], job["queue"], to_s)
159
+ process_job(job)
160
+ end
161
+
162
+ def process_job(job)
163
+ instance = new
164
+ instance.jid = job["jid"]
165
+ instance.payload = job
166
+ Testing.server_middleware.invoke(instance, job, job["queue"]) { execute_job(instance, job["args"]) }
167
+ end
168
+
169
+ def execute_job(job, args) = job.perform(*args)
170
+ end
171
+ ClassMethods.include(TestingMethods)
172
+
173
+ class << self
174
+ def jobs = Queues.jobs_by_queue.values.flatten
175
+
176
+ def clear_all = Queues.clear_all
177
+
178
+ def drain_all
179
+ while jobs.any?
180
+ jobs.map { |job| job.fetch("class") }.uniq.each { |name| Testing.job_class(name).drain }
181
+ end
182
+ end
183
+ end
184
+ end
185
+
186
+ Testing.global_mode = :fake
187
+ Robin::Client.interceptor = ->(payloads) { Testing.intercept(payloads) }
188
+ end