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,146 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "sidekiq"
4
+ require "robin/compat/cron_line"
5
+
6
+ module Sidekiq
7
+ # sidekiq-cron's interface, on Robin: cron jobs kept in Redis, created at
8
+ # runtime or loaded from config/schedule.yml.
9
+ #
10
+ # Sidekiq::Cron::Job.create(name: "Hard worker", cron: "*/5 * * * *", class: "HardWorker")
11
+ #
12
+ # The jobs are stored as sidekiq-cron stores them, so the ones it made
13
+ # keep running, and the two can run side by side while you switch.
14
+ # Robin's leader enqueues them, claiming each tick in Redis the way
15
+ # sidekiq-cron does, so a tick is enqueued once by either.
16
+ #
17
+ # A schedule is a cron line (five fields, or six with seconds first),
18
+ # with an optional time zone at its end ("0 22 * * 1-5 America/Chicago";
19
+ # without one, Rails' Time.zone, else the system's). Natural-language
20
+ # schedules ("every day at five") need the fugit gem.
21
+ module Cron
22
+ class << self
23
+ def configuration = @configuration ||= Configuration.new
24
+
25
+ def configure
26
+ yield configuration if block_given?
27
+ end
28
+
29
+ def reset! = @configuration = Configuration.new
30
+
31
+ # What a server does as it starts (unless disabled): loads the
32
+ # schedule file, and polls for due jobs until it quiets or stops.
33
+ def boot(config)
34
+ return unless configuration.enabled
35
+
36
+ Job.migrate_old_jobs_if_needed!
37
+ loader = ScheduleLoader.new
38
+ if loader.has_schedule_file?
39
+ loader.load_schedule.each do |name, errors|
40
+ config.logger.warn { "Cron Jobs - #{name} in the schedule file is invalid: #{errors.join(", ")}" }
41
+ end
42
+ end
43
+ interval = Integer(configuration.cron_poll_interval)
44
+ return unless interval.positive?
45
+
46
+ @poller = Poller.new(config, interval: interval).start
47
+ config.on(:quiet) { halt }
48
+ config.on(:shutdown) { halt }
49
+ end
50
+
51
+ # Stops polling, as a server quiets or stops.
52
+ def halt
53
+ @poller&.terminate
54
+ @poller = nil
55
+ end
56
+
57
+ # A schedule as a Robin::Cron: a cron line, with an optional time
58
+ # zone at its end, or (with fugit) natural language, read as
59
+ # natural_cron_parsing_mode says: the first of several schedules
60
+ # (:single) or an error (:strict).
61
+ def parse(schedule)
62
+ Robin::Compat::CronLine.parse(schedule)
63
+ rescue Robin::Cron::ParseError => e
64
+ parser = Robin::Compat::CronLine.fugit
65
+ raise e.exception("#{e} (natural-language schedules need the fugit gem)") unless parser
66
+
67
+ natural = parser.parse_nat(schedule, multi: (configuration.natural_cron_parsing_mode == :strict) && :fail)
68
+ raise unless natural
69
+
70
+ parse(natural.to_cron_s) # a cron line, which fugit made
71
+ end
72
+ end
73
+
74
+ # Sidekiq::Cron.configure's settings, with sidekiq-cron's defaults.
75
+ # cron_poll_process_count is taken but unused: only Robin's leader
76
+ # polls.
77
+ class Configuration
78
+ attr_accessor :enabled, :cron_poll_interval, :cron_schedule_file, :cron_history_size,
79
+ :default_namespace, :available_namespaces, :reschedule_grace_period
80
+ attr_reader :natural_cron_parsing_mode, :cron_poll_process_count
81
+
82
+ def initialize
83
+ @enabled = true
84
+ @cron_poll_interval = 30
85
+ @cron_schedule_file = "config/schedule.yml"
86
+ @cron_history_size = 10
87
+ @default_namespace = "default"
88
+ @available_namespaces = [@default_namespace]
89
+ @natural_cron_parsing_mode = :single
90
+ @reschedule_grace_period = 60
91
+ end
92
+
93
+ def natural_cron_parsing_mode=(mode)
94
+ raise ArgumentError, "Unknown natural cron parsing mode: #{mode.inspect}" unless %i[single strict].include?(mode)
95
+
96
+ @natural_cron_parsing_mode = mode
97
+ end
98
+
99
+ def cron_poll_process_count=(count)
100
+ raise ArgumentError, "invalid cron process count: #{count.inspect}" unless count.instance_of?(Integer) && count.positive?
101
+
102
+ @cron_poll_process_count = count
103
+ end
104
+ end
105
+
106
+ # The namespaces cron jobs are grouped in.
107
+ class Namespace
108
+ class << self
109
+ # available_namespaces (or, with :auto, those found in Redis), and
110
+ # the default one.
111
+ def all
112
+ names = case (available = Cron.configuration.available_namespaces)
113
+ when nil then []
114
+ when Array then available
115
+ when :auto then Cron.redis { |c| c.call("KEYS", "#{Cron.prefix}cron_jobs:*") }.map { |key| key.split(":").last }
116
+ else raise ArgumentError, "Unexpected value provided for `available_namespaces`: #{available.inspect}"
117
+ end
118
+ names | [Cron.configuration.default_namespace]
119
+ end
120
+
121
+ def all_with_count = all.map { |name| {count: count(name), name: name} }
122
+
123
+ def count(name = nil) = Job.count(name)
124
+
125
+ # Whether available_namespaces lists them (rather than :auto).
126
+ def available_namespaces_provided?
127
+ available = Cron.configuration.available_namespaces
128
+ !available.nil? && !available.equal?(:auto)
129
+ end
130
+ end
131
+ end
132
+
133
+ class << self
134
+ # The Redis cron jobs live in: Robin's (Sidekiq's).
135
+ def redis(&) = Robin.redis(&)
136
+
137
+ # Prefixed to sidekiq-cron's keys: the prefix of Sidekiq's own keys
138
+ # (none, by default).
139
+ def prefix = Robin.config.key_prefix
140
+ end
141
+ end
142
+ end
143
+
144
+ require "sidekiq/cron/job"
145
+ require "sidekiq/cron/schedule_loader"
146
+ require "sidekiq/cron/poller"
@@ -0,0 +1,62 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "delegate"
4
+ require "time"
5
+ require "sidekiq"
6
+
7
+ module Sidekiq
8
+ # Deploy marks, as Robin::Deploy's: the dashboard's metrics charts draw a
9
+ # line at each.
10
+ #
11
+ # require "sidekiq/deploy"
12
+ # Sidekiq::Deploy.mark!("v42")
13
+ # Sidekiq::Deploy.mark! # labelled with the latest git commit
14
+ #
15
+ # A label marked in the last hour isn't marked again, so every process
16
+ # may mark the same deploy (at boot, say).
17
+ class Deploy
18
+ # Robin keeps marks as long as its hourly metrics
19
+ # (Config#metrics_retention_days, 90 days by default) instead.
20
+ MARK_TTL = 90 * 24 * 60 * 60
21
+
22
+ # The label of a mark made without one: the latest commit's short hash
23
+ # and subject.
24
+ LABEL_MAKER = -> { `git log -1 --format="%h %s"`.strip }
25
+
26
+ def self.mark!(label = nil) = new.mark!(label: label)
27
+
28
+ # Marks go through +pool+ (anything whose #with yields a connection,
29
+ # such as Sidekiq.redis_pool), or Robin's own.
30
+ def initialize(pool = nil)
31
+ @config = pool ? Through.new(Robin.config, pool) : Robin.config
32
+ end
33
+
34
+ # Marks a deploy at +at+. Returns false when +label+ was already marked
35
+ # in the last hour, true otherwise.
36
+ def mark!(at: Time.now, label: nil)
37
+ Robin::Deploy.mark!(label || LABEL_MAKER.call, at: at, config: @config)
38
+ end
39
+
40
+ # The marks made on +date+ (a Date or Time, in UTC): the time of each,
41
+ # to the minute in ISO 8601, and its label. The first of a minute's
42
+ # marks is kept.
43
+ def fetch(date = Time.now.utc)
44
+ day = Time.utc(date.year, date.month, date.day)
45
+ marks = Robin::Deploy.list(from: day, to: day + Rational(86_399_999, 1000), config: @config)
46
+ marks.each_with_object({}) do |mark, found|
47
+ found[Time.at(mark.fetch("at") / 60_000 * 60).utc.iso8601] ||= mark.fetch("label").to_s
48
+ end
49
+ end
50
+
51
+ # Robin's configuration, with Redis reached through another pool.
52
+ class Through < SimpleDelegator
53
+ def initialize(config, pool)
54
+ super(config)
55
+ @pool = pool
56
+ end
57
+
58
+ def redis(&) = @pool.with(&)
59
+ end
60
+ private_constant :Through
61
+ end
62
+ end
@@ -0,0 +1,55 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Sidekiq
4
+ module Job
5
+ # Raised when an iterable job is interrupted.
6
+ class Interrupted < ::RuntimeError; end
7
+
8
+ # Sidekiq's iterable jobs: build_enumerator, each_iteration and the
9
+ # on_* hooks, run by Robin::IterableJob.
10
+ #
11
+ # class ImportJob
12
+ # include Sidekiq::IterableJob
13
+ #
14
+ # def build_enumerator(import_id, cursor:)
15
+ # active_record_records_enumerator(Import.find(import_id).rows, cursor: cursor)
16
+ # end
17
+ #
18
+ # def each_iteration(row, import_id)
19
+ # end
20
+ # end
21
+ module Iterable
22
+ def self.included(base)
23
+ base.include(Robin::IterableJob)
24
+ base.include(InstanceMethods)
25
+ base.extend(ClassMethods)
26
+ end
27
+
28
+ # The job's arguments.
29
+ def arguments = payload&.fetch("args")
30
+
31
+ # Stops the job at its next iteration (see Robin.cancel!).
32
+ def cancel! = Robin.cancel!(jid)
33
+
34
+ # Iterates ActiveRecord relations of +batch_size+ records, in
35
+ # primary-key order; the cursor is the last finished batch's last id.
36
+ def active_record_relations_enumerator(relation, cursor:, batch_size: 100)
37
+ Enumerator.new do |y|
38
+ active_record_batches_enumerator(relation, cursor: cursor, batch_size: batch_size).each do |records, last_id|
39
+ y.yield relation.where({relation.primary_key => records.map(&:id)}), last_id
40
+ end
41
+ end
42
+ end
43
+
44
+ # Iterates a CSV in batches of +batch_size+ rows; the cursor is the
45
+ # index of the last finished batch.
46
+ def csv_batches_enumerator(csv, cursor:, batch_size: 100)
47
+ Enumerator.new do |y|
48
+ csv.each_slice(batch_size).with_index { |rows, i| y.yield rows, i if cursor.nil? || i > cursor }
49
+ end
50
+ end
51
+ end
52
+ end
53
+
54
+ IterableJob = Job::Iterable
55
+ end
@@ -0,0 +1,207 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Sidekiq
4
+ # Include in a class to make it a job, as with Sidekiq. It's a Robin job
5
+ # (Robin::Job) underneath, so Robin's own options work too.
6
+ #
7
+ # class HardJob
8
+ # include Sidekiq::Job
9
+ # sidekiq_options queue: "critical", retry: 5
10
+ # sidekiq_retry_in { |count, exception, job| 10 * (count + 1) }
11
+ #
12
+ # def perform(name, count)
13
+ # end
14
+ # end
15
+ module Job
16
+ @default_options = {"retry" => true, "queue" => "default"}.freeze
17
+
18
+ # Sidekiq's retry backoff, as Robin's config.retry_backoff takes it.
19
+ RETRY_BACKOFF = lambda do |failures, _exception, _job, custom|
20
+ count = failures - 1
21
+ (custom || ((count**4) + 15)) + rand(10 * (count + 1))
22
+ end
23
+
24
+ class << self
25
+ # Options every job class starts from (Sidekiq.default_job_options).
26
+ attr_reader :default_options
27
+
28
+ def default_options=(options)
29
+ @default_options = options.to_h { |k, v| [k.to_s, v] }.freeze
30
+ end
31
+
32
+ def included(base)
33
+ base.include(Robin::Job)
34
+ base.include(InstanceMethods)
35
+ base.extend(ClassMethods)
36
+ end
37
+
38
+ # What a sidekiq_retry_in block's answer means: a positive number of
39
+ # seconds (Strings too), :discard or :kill; anything else is the
40
+ # default backoff (nil).
41
+ def retry_delay(answer)
42
+ return answer if answer == :discard || answer == :kill
43
+
44
+ seconds = answer.to_i if answer.respond_to?(:to_i)
45
+ seconds if seconds&.positive?
46
+ end
47
+
48
+ # Sidekiq stringifies option keys, and the keys of Hash values.
49
+ def stringify(options)
50
+ options.map { |k, v| [k.to_s, (Hash === v) ? v.transform_keys(&:to_s) : v] }.to_h
51
+ end
52
+ end
53
+
54
+ # Methods a job instance has that take precedence over Robin::Job's
55
+ # (sidekiq/batch adds +batch+ and +valid_within_batch?+).
56
+ module InstanceMethods; end
57
+
58
+ module ClassMethods
59
+ def sidekiq_options(opts = nil)
60
+ opts = Job.stringify(opts.to_h) # Sidekiq takes nil as no options
61
+ # A pool (a shard's Redis) stays with the class rather than the job.
62
+ @sidekiq_pool = opts.delete("pool") if opts.key?("pool")
63
+ # Sidekiq encrypts the last argument only.
64
+ opts["encrypt"] = "last" if opts["encrypt"]
65
+ robin_options(opts)
66
+ get_sidekiq_options
67
+ end
68
+
69
+ def get_sidekiq_options
70
+ pool = sidekiq_pool
71
+ pool ? robin_options.merge({"pool" => pool}) : robin_options
72
+ end
73
+
74
+ # A class without options of its own (or inherited) has
75
+ # Sidekiq.default_job_options rather than Robin's defaults.
76
+ def robin_options(opts = nil)
77
+ options = super
78
+ options.equal?(Robin::Job::DEFAULT_OPTIONS) ? Job.default_options : options
79
+ end
80
+
81
+ def sidekiq_pool = @sidekiq_pool || (superclass.sidekiq_pool if superclass.respond_to?(:sidekiq_pool))
82
+
83
+ # The block gets (retry count, exception, job): the count is 0 the
84
+ # first time the job fails.
85
+ def sidekiq_retry_in(&block)
86
+ @sidekiq_retry_in_block = block
87
+ robin_retry_in { |failures, exception, job| Job.retry_delay(block.call(failures - 1, exception, job)) }
88
+ end
89
+
90
+ def sidekiq_retry_in_block
91
+ @sidekiq_retry_in_block || (superclass.sidekiq_retry_in_block if superclass.respond_to?(:sidekiq_retry_in_block))
92
+ end
93
+
94
+ # The block gets (job, exception); returning :discard skips the dead
95
+ # set.
96
+ def sidekiq_retries_exhausted(&) = robin_retries_exhausted(&)
97
+
98
+ def sidekiq_retries_exhausted_block = robin_retries_exhausted_block
99
+
100
+ def queue_as(queue) = sidekiq_options({"queue" => queue})
101
+
102
+ def set(options) = Setter.new(self, options)
103
+
104
+ # perform_async, perform_in and perform_at are Robin::Job's (pushing
105
+ # through client_push below).
106
+
107
+ def perform_inline(*) = Setter.new(self, {}).perform_inline(*)
108
+ alias_method :perform_sync, :perform_inline
109
+
110
+ def perform_bulk(args, **) = Setter.new(self, {}).perform_bulk(args, **)
111
+
112
+ def delay(*) = raise(ArgumentError, "Do not call .delay on a Sidekiq::Job class, call .perform_async")
113
+
114
+ def delay_for(*) = raise(ArgumentError, "Do not call .delay_for on a Sidekiq::Job class, call .perform_in")
115
+
116
+ def delay_until(*) = raise(ArgumentError, "Do not call .delay_until on a Sidekiq::Job class, call .perform_at")
117
+
118
+ def client_push(item)
119
+ item = item.transform_keys(&:to_s)
120
+ pool = item.delete("pool") || sidekiq_pool
121
+ client = Client.new(pool: pool)
122
+ client.push(item)
123
+ end
124
+
125
+ def build_client = Client.new(pool: sidekiq_pool)
126
+
127
+ # A job's uniqueness: the digest covers its class, queue and what
128
+ # sidekiq_unique_context returns (the class may define it, given the
129
+ # job), else its arguments.
130
+ def robin_unique_args(args)
131
+ return args unless respond_to?(:sidekiq_unique_context)
132
+
133
+ sidekiq_unique_context({"class" => name, "queue" => get_sidekiq_options["queue"], "args" => args})
134
+ end
135
+ end
136
+
137
+ # Per-push options: HardJob.set(queue: "low", wait: 30).perform_async(1)
138
+ class Setter
139
+ def initialize(klass, options)
140
+ @klass = klass
141
+ @options = {}
142
+ set(options)
143
+ end
144
+
145
+ # +wait+ is resolved now (so a reused setter keeps its time);
146
+ # +sync: true+ runs the job inline.
147
+ def set(options)
148
+ options = Job.stringify(options)
149
+ if (wait = options.delete("wait"))
150
+ options["at"] = Robin::Client.timestamp_ms(wait)
151
+ end
152
+ if (wait_until = options.delete("wait_until"))
153
+ options["at"] = wait_until
154
+ end
155
+ @options.merge!(options)
156
+ self
157
+ end
158
+
159
+ def perform_async(*args)
160
+ return perform_inline(*args) if @options["sync"]
161
+
162
+ @klass.client_push(@options.merge({"class" => @klass, "args" => args}))
163
+ end
164
+
165
+ def perform_in(interval, *args)
166
+ @klass.client_push(@options.merge({"class" => @klass, "args" => args, "at" => interval}))
167
+ end
168
+ alias_method :perform_at, :perform_in
169
+
170
+ # Runs the job now, in this thread, through the client and server
171
+ # middleware and a JSON round trip, as Sidekiq does. Returns true, or
172
+ # nil when a middleware stopped it. The arguments aren't checked for
173
+ # JSON-native types, as in Sidekiq 8.0 (8.1 checks them): the round
174
+ # trip turns a Symbol into a String, say.
175
+ def perform_inline(*args)
176
+ client = Robin::Client.new
177
+ # normalize leaves out "sync".
178
+ item = client.normalize(@options.except("pool").merge({"class" => @klass, "args" => []}))
179
+ item["args"] = args
180
+ config = Robin.config
181
+ pushed = config.client_middleware.invoke(item.fetch("class"), item, item.fetch("queue"), config.redis_pool) { item }
182
+ return unless pushed
183
+
184
+ job = Robin.load_json(Robin.dump_json(item))
185
+ instance = Object.const_get(job.fetch("class")).new
186
+ instance.jid = job.fetch("jid")
187
+ instance.payload = job
188
+ ran = config.server_middleware.invoke(instance, job, job.fetch("queue")) do
189
+ instance.perform(*job.fetch("args"))
190
+ true
191
+ end
192
+ true if ran
193
+ end
194
+ alias_method :perform_sync, :perform_inline
195
+
196
+ # +options+ as Client#push_bulk takes them (batch_size, at,
197
+ # spread_interval), over the setter's.
198
+ def perform_bulk(args, **options)
199
+ Client.new(pool: @options["pool"] || @klass.sidekiq_pool)
200
+ .push_bulk(@options.except("pool").merge(options, {"class" => @klass, "args" => args}))
201
+ end
202
+ end
203
+ end
204
+
205
+ # Sidekiq's older name for Sidekiq::Job.
206
+ Worker = Job
207
+ end
@@ -0,0 +1,23 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Sidekiq
4
+ # The exceptions apps rescue or raise around retries.
5
+ class JobRetry
6
+ # Raised (by Sidekiq) once a failure has been recorded for retry.
7
+ class Handled < ::RuntimeError; end
8
+
9
+ # Raise to stop a job without retrying it, as Robin::Discard does.
10
+ Skip = Robin::Discard
11
+
12
+ # With "retry" true, a job retries at most config.max_retries times,
13
+ # even with retry_for: it stops at whichever limit comes first. That's
14
+ # Sidekiq 8.0's rule. Sidekiq 8.1, like Robin, lets retry_for alone set
15
+ # the limit, which differs only when the window outlasts the retries.
16
+ module CountLimit
17
+ def max_retries(payload)
18
+ (payload["retry"] == true) ? config.max_retries : super
19
+ end
20
+ end
21
+ Robin::Retrier.prepend(CountLimit)
22
+ end
23
+ end
@@ -0,0 +1,144 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "sidekiq"
4
+ require "sidekiq/batch"
5
+
6
+ module Sidekiq
7
+ # Sidekiq Enterprise's rate limiters, as Robin::Limiter's:
8
+ #
9
+ # STRIPE = Sidekiq::Limiter.concurrent("stripe", 10, wait_timeout: 0, lock_timeout: 30)
10
+ # STRIPE.within_limit { charge! }
11
+ #
12
+ # Inside a job, an OverLimit reschedules the job instead of failing it,
13
+ # after Sidekiq's backoff (about 5 minutes more each time) unless
14
+ # Limiter.configure or the limiter gives another.
15
+ module Limiter
16
+ OverLimit = Robin::Limiter::OverLimit
17
+
18
+ # Sidekiq's default backoff: 5 minutes for each time the job hit a
19
+ # limit, plus up to 5 minutes of jitter.
20
+ DEFAULT_BACKOFF = ->(_limiter, job, _exception) { (300 * job.fetch("overrated")) + rand(1..300) }
21
+
22
+ # Stands in for the limiter when an error listed in
23
+ # Limiter.configure's +errors+ is treated as hitting a limit.
24
+ ErrorLimit = Struct.new(:name, :type, :reschedule, :backoff)
25
+
26
+ # What Limiter.configure yields.
27
+ class Configuration
28
+ # Errors that count as hitting a rate limit (e.g. an API's "429").
29
+ attr_reader :errors
30
+
31
+ # The backoff for limiters without one of their own: a callable
32
+ # (limiter, job, exception) returning seconds, where job["overrated"]
33
+ # counts the times the job hit a limit.
34
+ attr_accessor :backoff
35
+
36
+ # The pool the limiters keep their state in (nil: Robin's own).
37
+ attr_reader :pool
38
+
39
+ def initialize
40
+ @errors = []
41
+ @backoff = DEFAULT_BACKOFF
42
+ end
43
+
44
+ # Keeps the limiters' state in another Redis (Sidekiq's redis
45
+ # options).
46
+ def redis=(options)
47
+ config = Robin::Config.new
48
+ Config.new(config).redis = options
49
+ @pool = config.redis_pool
50
+ end
51
+ end
52
+
53
+ class << self
54
+ def configure
55
+ yield configuration
56
+ install_errors_middleware unless configuration.errors.empty?
57
+ end
58
+
59
+ def configuration = @configuration ||= Configuration.new
60
+
61
+ def concurrent(name, count, **) = wrap(Robin::Limiter.concurrent(name, count, **options(**)))
62
+
63
+ def bucket(name, count, interval, **) = wrap(Robin::Limiter.bucket(name, count, interval, **options(**)))
64
+
65
+ def window(name, count, interval, **) = wrap(Robin::Limiter.window(name, count, interval, **options(**)))
66
+
67
+ def leaky(name, count, interval, **) = wrap(Robin::Limiter.leaky(name, count, interval, **options(**)))
68
+
69
+ def points(name, points, interval, **) = Points.new(Robin::Limiter.points(name, points, interval, **options(**)))
70
+
71
+ def unlimited(name = "unlimited") = Robin::Limiter.unlimited(name)
72
+
73
+ # A Sidekiq backoff (limiter, job, exception) as Robin takes it:
74
+ # (count, error, job), the count being job["overrated"].
75
+ def backoff(callable = nil)
76
+ lambda do |count, error, job|
77
+ (callable || configuration.backoff).call(error.limiter, job.merge({"overrated" => count}), error)
78
+ end
79
+ end
80
+
81
+ # Runs the block with the limiters' calls going to the configured
82
+ # Redis, if any (else where Robin::Limiter.via says, or Robin's).
83
+ def with_redis(&)
84
+ pool = configuration.pool
85
+ pool ? Robin::Limiter.via(pool, &) : yield
86
+ end
87
+
88
+ private
89
+
90
+ # Sidekiq's limiter options as Robin's: policy :ignore is :skip,
91
+ # backoffs take (limiter, job, exception), and +ttl+ (how long an
92
+ # unused limiter's data stays) is Robin's own, fixed one.
93
+ def options(policy: :raise, backoff: nil, ttl: nil, **options)
94
+ policy = policy.to_sym
95
+ options.merge(policy: (policy == :ignore) ? :skip : policy, backoff: backoff(backoff))
96
+ end
97
+
98
+ def wrap(limiter) = Handle.new(limiter)
99
+
100
+ # Inside Robin's batch tracking, so a batch doesn't count the error
101
+ # as its job failing when the job is rescheduled instead.
102
+ def install_errors_middleware
103
+ Robin.config.server_middleware { |chain| chain.insert_after(Batch::Server, ErrorsMiddleware) }
104
+ end
105
+ end
106
+
107
+ # Turns the errors listed in Limiter.configure's +errors+ into
108
+ # OverLimit, so the job is rescheduled rather than failed.
109
+ class ErrorsMiddleware
110
+ include Robin::Middleware::Stateless
111
+
112
+ def call(_job, _payload, _queue)
113
+ yield
114
+ rescue *Limiter.configuration.errors => e
115
+ raise OverLimit.new(ErrorLimit.new(e.class.name, "error", nil, Limiter.backoff))
116
+ end
117
+ end
118
+
119
+ # A limiter whose calls go to the Redis Limiter.configure set.
120
+ class Handle < SimpleDelegator
121
+ %i[within_limit used to_h reset_state over_limit!].each do |name|
122
+ define_method(name) { |*args, **opts, &block| Limiter.with_redis { super(*args, **opts, &block) } }
123
+ end
124
+ end
125
+
126
+ # A points limiter whose block reports what it actually used:
127
+ #
128
+ # OPENAI.within_limit(estimate: 1_000) { |handle| handle.points_used(response.tokens) }
129
+ class Points < Handle
130
+ def within_limit(estimate: 1)
131
+ super(points: estimate) { yield Usage.new(self, estimate) }
132
+ end
133
+
134
+ %i[adjust refund].each do |name|
135
+ define_method(name) { |points| Limiter.with_redis { super(points) } }
136
+ end
137
+
138
+ # Settles the difference between the estimate and what was used.
139
+ Usage = Struct.new(:limiter, :estimate) do
140
+ def points_used(points) = limiter.adjust(points - estimate)
141
+ end
142
+ end
143
+ end
144
+ end
@@ -0,0 +1,25 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Sidekiq
4
+ # Sidekiq's job logging context: Context.with(key: value) { ... } adds
5
+ # to every line logged inside the block; Context.add, to the rest of the
6
+ # running job's.
7
+ module Context
8
+ def self.with(hash, &) = Robin::Context.with(hash, &)
9
+
10
+ def self.current = Robin::Context.current
11
+
12
+ def self.add(key, value)
13
+ current[key] = value
14
+ end
15
+ end
16
+
17
+ # Log formatters under Sidekiq's names.
18
+ module Logger
19
+ module Formatters
20
+ Pretty = Robin::JobLogger::Formatter
21
+ JSON = Robin::JobLogger::JSONFormatter
22
+ WithoutTimestamp = Robin::JobLogger::Formatter
23
+ end
24
+ end
25
+ end
@@ -0,0 +1,27 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "delegate"
4
+
5
+ module Sidekiq
6
+ module Middleware
7
+ # A Robin middleware chain with the methods Sidekiq's chains add.
8
+ class Chain < SimpleDelegator
9
+ # Robin's chain is replaced on every change, so its methods return
10
+ # it; these return this wrapper instead, for chaining calls.
11
+ %i[add prepend insert_before insert_after remove clear].each do |name|
12
+ define_method(name) do |*args|
13
+ __getobj__.public_send(name, *args)
14
+ self
15
+ end
16
+ end
17
+
18
+ def include?(klass) = exists?(klass)
19
+
20
+ # The middleware instances, built (or reused, for stateless ones) as
21
+ # a job would get them.
22
+ def retrieve = map(&:build)
23
+
24
+ def copy_for(_capsule) = self
25
+ end
26
+ end
27
+ end