delayed 4.1.0 → 4.2.1

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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 70e3822f06e3d5b6a663f08998abf783ae91137a96cf154dded1487548ab9544
4
- data.tar.gz: e166f6ba77ff5e268059dc32de8e72e619b56106e69a96b884c1c5e31e22542a
3
+ metadata.gz: 0011431bc15bd6f5140336013ba0bd0c2c8c138f71adccd1d93bc682d707e325
4
+ data.tar.gz: 3d8f73c040e570200bd6bddadd3b6a79190626bdb1f96dba8135752dfd0ed7cd
5
5
  SHA512:
6
- metadata.gz: 86379222dec057f27b106602cc91ce90800861f705e16fb53857590f6b730a6e523780be0eeec09c6a9dd8d9f9b1760b0c15793c73fcfac5173bf2ba17354f4b
7
- data.tar.gz: 4ce59e9dbec2d10339cf3979ff5c49a97adc337fba6119d69662e65ff2407f8fc1ab32cac09ab3ad83044e795384f2c36ae478fa5763a3578b87178cdb624123
6
+ metadata.gz: 9e66b2fe7abc29c13f76c9aeaeb6abca58eb64030413e7b1d6efd2f4bb824504ab05ce2cc12da8a5cfd3e7c0529ac749b3d092d2f1c31d3057272a153b0ee788
7
+ data.tar.gz: faece8e910179b948fef3d189865604a1f2084c2fed183468a6f183df7f5f7ab10687323e33b38088949b854fe45c8c729c2b06b936b54f18aca0f744a3c9dac
data/README.md CHANGED
@@ -632,6 +632,18 @@ upserting `RETURNING` clause and database-native timestamp arithmetic. You can c
632
632
  connection at runtime with `Delayed::Limit.supported?`. (Attempting to use the limiter on an
633
633
  unsupported database will raise `Delayed::Limit::UnsupportedDatabaseError`.)
634
634
 
635
+ Additionally, the limiter **must not be called inside an open database
636
+ transaction** (it raises `Delayed::Limit::TransactionOpenError`), because the
637
+ reserved row would stay locked until the transaction commits. If it must run
638
+ inside transactions, give `Delayed::Limit` a connection pool of its own (at the
639
+ cost of up to one extra connection per thread) in a Rails initializer:
640
+
641
+ ```ruby
642
+ Rails.application.config.to_prepare do
643
+ Delayed::Limit.establish_connection(ActiveRecord::Base.connection_db_config.configuration_hash)
644
+ end
645
+ ```
646
+
635
647
  #### Traffic Shaping vs Traffic Enforcement
636
648
 
637
649
  By default, the limiter will `sleep` up to 5 seconds (or a specified `wait_timeout`) before
@@ -38,6 +38,10 @@ module Delayed
38
38
  #
39
39
  # It is **not** recommended to register limits dynamically at runtime, because
40
40
  # registered limits are cached indefinitely in memory and are not thread-safe.
41
+ #
42
+ # The limiter must not be called inside an open database transaction (it
43
+ # raises `TransactionOpenError`), because the reserved row would stay locked
44
+ # until that transaction commits.
41
45
  class Limit < ActiveRecord::Base
42
46
  self.table_name = 'delayed_limits'
43
47
 
@@ -52,6 +56,12 @@ module Delayed
52
56
  # (see `.supported?`).
53
57
  class UnsupportedDatabaseError < StandardError; end
54
58
 
59
+ # Raised when `.within_limit` is called inside an open database
60
+ # transaction. The reservation query takes a row lock that would otherwise
61
+ # be held until the transaction commits, causing lock contention to pile up
62
+ # behind the caller's (potentially long-running) work.
63
+ class TransactionOpenError < StandardError; end
64
+
55
65
  class << self
56
66
  # Used only for limits registered in advance (via `.register!`):
57
67
  def limits
@@ -115,6 +125,11 @@ module Delayed
115
125
  # e.g. for a target of 100 req/min, the drain_interval would be 0.6 sec/req.
116
126
  drain_interval = config.fetch(:per).seconds / config.fetch(:max).to_d
117
127
 
128
+ if transaction_open?
129
+ raise TransactionOpenError,
130
+ 'Delayed::Limit.within_limit cannot be called inside a database transaction '
131
+ end
132
+
118
133
  # Attempt to reserve capacity via an uncached database query:
119
134
  limit = connection.uncached do
120
135
  find_by_sql(reserve_sql(purpose, drain_interval, wait_timeout.seconds)).first
@@ -144,6 +159,14 @@ module Delayed
144
159
 
145
160
  private
146
161
 
162
+ # Checks `joinable?` rather than the connection's `transaction_open?` so
163
+ # that the per-example transaction opened by Rails' transactional tests
164
+ # (which is non-joinable) does not trip the guard, while any transaction
165
+ # opened by application code (joinable by default) does.
166
+ def transaction_open?
167
+ connection.current_transaction.joinable?
168
+ end
169
+
147
170
  # We reserve capacity by pushing a 'drained_at' timestamp forward by the
148
171
  # drain_interval, returning how long the caller must wait to avoid filling
149
172
  # the bucket beyond its capacity. (The WHERE clause significantly reduces
@@ -44,6 +44,9 @@ module Delayed
44
44
  Float::INFINITY
45
45
  end
46
46
 
47
+ WRAPPER_LOCK = Mutex.new
48
+ private_constant :WRAPPER_LOCK
49
+
47
50
  class_methods do
48
51
  def with_limit(
49
52
  purpose = name.underscore.to_sym,
@@ -62,7 +65,7 @@ module Delayed
62
65
  retry_on(Delayed::Limit::LimitExceededError, attempts: retry_attempts, wait: retry_wait)
63
66
  end
64
67
 
65
- prepend(Module.new do
68
+ defer_limit_wrapper(Module.new do
66
69
  Array(on).each do |method_name|
67
70
  define_method(method_name) do |*args, **kwargs, &block|
68
71
  Delayed::Limit.within_limit(purpose, wait_timeout: wait_timeout) do
@@ -73,8 +76,40 @@ module Delayed
73
76
  end)
74
77
  end
75
78
 
79
+ def new(...)
80
+ prepend_limit_wrappers!
81
+ super
82
+ end
83
+
84
+ def allocate
85
+ prepend_limit_wrappers!
86
+ super
87
+ end
88
+
76
89
  private
77
90
 
91
+ # Deferred so that `method_added` hooks (e.g. Sorbet sigs) don't find the wrapper.
92
+ def defer_limit_wrapper(wrapper)
93
+ WRAPPER_LOCK.synchronize { (@pending_limit_wrappers ||= []) << wrapper }
94
+ end
95
+
96
+ def prepend_limit_wrappers!
97
+ klass = self
98
+ while klass.respond_to?(:with_limit)
99
+ klass.send(:prepend_own_limit_wrappers!)
100
+ klass = klass.superclass
101
+ end
102
+ end
103
+
104
+ def prepend_own_limit_wrappers!
105
+ return unless @pending_limit_wrappers
106
+
107
+ WRAPPER_LOCK.synchronize do
108
+ @pending_limit_wrappers&.each { |wrapper| prepend(wrapper) }
109
+ @pending_limit_wrappers = nil
110
+ end
111
+ end
112
+
78
113
  def polynomial_backoff(min_wait, attempt, jitter)
79
114
  [min_wait, (attempt**4)].max * (1 + rand(-jitter..jitter))
80
115
  end
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Delayed
4
- VERSION = '4.1.0'
4
+ VERSION = '4.2.1'
5
5
  end
@@ -557,7 +557,7 @@ describe Delayed::Job do
557
557
 
558
558
  context 'during DST change' do
559
559
  before do
560
- Time.zone = 'US/Eastern'
560
+ Time.zone = 'America/New_York'
561
561
  end
562
562
 
563
563
  let(:dst_start) { Time.zone.parse('2024-11-03 01:00:00 EDT') }
@@ -604,7 +604,7 @@ describe Delayed::Job do
604
604
 
605
605
  context 'during DST change' do
606
606
  before do
607
- Time.zone = 'US/Eastern'
607
+ Time.zone = 'America/New_York'
608
608
  end
609
609
 
610
610
  let(:dst_start) { Time.zone.parse('2024-11-03 01:00:00 EDT') }
@@ -3,6 +3,8 @@
3
3
  require 'helper'
4
4
 
5
5
  RSpec::Matchers.define_negated_matcher :not_change, :change
6
+ RSpec::Matchers.define_negated_matcher :not_yield_control, :yield_control
7
+ RSpec::Matchers.define_negated_matcher :not_emit_notification, :emit_notification
6
8
 
7
9
  RSpec.describe Delayed::Limit do
8
10
  before do
@@ -128,6 +130,105 @@ RSpec.describe Delayed::Limit do
128
130
  end
129
131
  end
130
132
 
133
+ context 'when called inside a database transaction' do
134
+ it 'raises TransactionOpenError without reserving capacity or yielding' do
135
+ expect { |b| described_class.transaction { described_class.within_limit(purpose, **limit, &b) } }
136
+ .to raise_error(described_class::TransactionOpenError, /inside a database transaction/)
137
+ .and not_change { described_class.count }
138
+ .and not_yield_control
139
+ end
140
+
141
+ it 'raises before the transaction is materialized (no SQL is sent)' do
142
+ expect { described_class.transaction { described_class.within_limit(purpose, **limit) { nil } } }
143
+ .to raise_error(described_class::TransactionOpenError)
144
+ .and not_emit_notification('sql.active_record')
145
+ end
146
+ end
147
+
148
+ context 'when the only open transaction is non-joinable' do
149
+ it 'does not raise, and reserves capacity as usual' do
150
+ expect { |b| described_class.transaction(joinable: false) { described_class.within_limit(purpose, **limit, &b) } }
151
+ .to yield_control.once
152
+
153
+ expect(described_class.count).to eq(1)
154
+ end
155
+
156
+ it 'still raises when application code opens a nested transaction' do
157
+ expect { |b| described_class.transaction(joinable: false) { described_class.transaction { described_class.within_limit(purpose, **limit, &b) } } }
158
+ .to raise_error(described_class::TransactionOpenError)
159
+ .and not_yield_control
160
+ end
161
+ end
162
+
163
+ context "under Rails' transactional test harness" do
164
+ # Opens the per-example transaction the same way ActiveRecord::TestFixtures does
165
+ # (via the connection pool on Rails 7.2+, and directly on the connection before that).
166
+ around do |example|
167
+ pool = described_class.connection_pool
168
+ if pool.respond_to?(:pin_connection!)
169
+ pool.pin_connection!(true)
170
+ begin
171
+ example.run
172
+ ensure
173
+ pool.unpin_connection!
174
+ end
175
+ else
176
+ connection = described_class.connection
177
+ connection.begin_transaction(joinable: false, _lazy: false)
178
+ begin
179
+ example.run
180
+ ensure
181
+ connection.rollback_transaction
182
+ end
183
+ end
184
+ end
185
+
186
+ it 'does not raise, and reserves capacity as usual' do
187
+ expect(described_class.connection.transaction_open?).to be(true)
188
+
189
+ expect { |b| described_class.within_limit(purpose, **limit, &b) }
190
+ .to yield_control.once
191
+
192
+ expect(described_class.count).to eq(1)
193
+ end
194
+
195
+ it 'still raises when the code under test opens a transaction' do
196
+ expect { |b| described_class.transaction { described_class.within_limit(purpose, **limit, &b) } }
197
+ .to raise_error(described_class::TransactionOpenError)
198
+ .and not_yield_control
199
+ end
200
+ end
201
+
202
+ context 'when Delayed::Limit has its own connection pool' do
203
+ around do |example|
204
+ config = if ActiveRecord::Base.respond_to?(:connection_db_config)
205
+ ActiveRecord::Base.connection_db_config.configuration_hash
206
+ else
207
+ ActiveRecord::Base.connection_config
208
+ end
209
+ described_class.establish_connection(config)
210
+ example.run
211
+ ensure
212
+ described_class.remove_connection
213
+ end
214
+
215
+ it 'uses a separate pool from the application' do
216
+ expect(described_class.connection_pool).not_to equal(ActiveRecord::Base.connection_pool)
217
+ end
218
+
219
+ it 'does not treat a transaction on the application pool as an open transaction' do
220
+ expect { |b| ActiveRecord::Base.transaction { described_class.within_limit(purpose, **limit, &b) } }
221
+ .to yield_control.once
222
+ .and change { described_class.count }.by(1)
223
+ end
224
+
225
+ it 'still raises for a transaction on its own pool' do
226
+ expect { |b| described_class.transaction { described_class.within_limit(purpose, **limit, &b) } }
227
+ .to raise_error(described_class::TransactionOpenError)
228
+ .and not_yield_control
229
+ end
230
+ end
231
+
131
232
  context 'with a limit registered in advance via .register!' do
132
233
  before { allow(described_class).to receive(:limits).and_return(purpose => limit) }
133
234
 
@@ -0,0 +1,20 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'helper'
4
+ require 'open3'
5
+
6
+ RSpec.describe Delayed::Limitable do
7
+ describe 'Sorbet runtime compatibility' do
8
+ it 'does not load sorbet-runtime in the test process' do
9
+ expect(defined?(T::Sig)).to be_nil
10
+ end
11
+
12
+ it 'supports `sig`s on methods defined after with_limit' do
13
+ output, status = Open3.capture2e(
14
+ RbConfig.ruby, '-rbundler/setup', 'spec/support/sorbet_runtime/limitable_jobs.rb',
15
+ chdir: File.expand_path('../..', __dir__)
16
+ )
17
+ expect(status).to be_success, output
18
+ end
19
+ end
20
+ end
@@ -126,6 +126,52 @@ RSpec.describe Delayed::Limitable do
126
126
  end
127
127
  end
128
128
 
129
+ context 'when the methods are defined after with_limit' do
130
+ let(:job_class) do
131
+ p = purpose
132
+ Class.new(ActiveJob::Base) do
133
+ def self.method_added(name)
134
+ super
135
+ (@owners_when_added ||= {})[name] = instance_method(name).owner
136
+ end
137
+
138
+ with_limit p, max: 4, per: 1.second, on: %i(perform deliver!)
139
+
140
+ def perform(id:)
141
+ deliver!(id: id)
142
+ end
143
+
144
+ def deliver!(id:)
145
+ id * 10
146
+ end
147
+ end
148
+ end
149
+
150
+ it 'does not shadow the methods while they are being defined' do
151
+ owners = job_class.instance_variable_get(:@owners_when_added)
152
+ expect(owners).to eq(perform: job_class, deliver!: job_class)
153
+ end
154
+
155
+ it 'wraps each method (with kwargs) once the job is instantiated' do
156
+ expect(job_class.perform_now(id: 1)).to eq(10)
157
+ expect(job_class.perform_now(id: 2)).to eq(20)
158
+ expect(Delayed::Limit).to have_received(:within_limit)
159
+ .with(purpose, wait_timeout: 5.seconds).exactly(4).times
160
+ end
161
+
162
+ it 'wraps the methods of an allocated (e.g. deserialized) job' do
163
+ expect(job_class.allocate.deliver!(id: 1)).to eq(10)
164
+ expect(Delayed::Limit).to have_received(:within_limit).once
165
+ end
166
+
167
+ it 'wraps the methods of a subclass instantiated before its parent' do
168
+ subclass = Class.new(job_class)
169
+ expect(subclass.new.deliver!(id: 1)).to eq(10)
170
+ expect(job_class.new.deliver!(id: 2)).to eq(20)
171
+ expect(Delayed::Limit).to have_received(:within_limit).twice
172
+ end
173
+ end
174
+
129
175
  context 'when the purpose was registered in advance and no config is given' do
130
176
  before { Delayed::Limit.register!(purpose, max: 4, per: 1.second) }
131
177
 
@@ -232,6 +278,29 @@ RSpec.describe Delayed::Limitable do
232
278
  allow(Delayed::Limit).to receive(:within_limit).and_raise(Delayed::Limit::LimitExceededError)
233
279
  expect { klass.new.do_work }.to raise_error(Delayed::Limit::LimitExceededError)
234
280
  end
281
+
282
+ it 'does not shadow methods defined after with_limit' do
283
+ p = purpose
284
+ owners = {}
285
+ plain_class = Class.new do
286
+ include Delayed::Limitable
287
+
288
+ define_singleton_method(:method_added) do |name|
289
+ super(name)
290
+ owners[name] = instance_method(name).owner
291
+ end
292
+
293
+ with_limit p, max: 4, per: 1.second, on: :do_work
294
+
295
+ def do_work
296
+ :result
297
+ end
298
+ end
299
+
300
+ expect(owners).to eq(do_work: plain_class)
301
+ expect(plain_class.new.do_work).to eq(:result)
302
+ expect(Delayed::Limit).to have_received(:within_limit).once
303
+ end
235
304
  end
236
305
  end
237
306
 
@@ -25,7 +25,7 @@ RSpec.describe Delayed::Monitor do
25
25
 
26
26
  around do |example|
27
27
  if app_local_db_time
28
- Time.zone = 'US/Central'
28
+ Time.zone = 'America/Chicago'
29
29
  self.default_timezone = :local
30
30
  end
31
31
 
@@ -0,0 +1,90 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'sorbet-runtime'
4
+ require 'active_job'
5
+ require 'delayed'
6
+
7
+ ActiveJob::Base.logger = Logger.new(nil)
8
+
9
+ LIMITED = [] # rubocop:disable Style/MutableConstant
10
+
11
+ Delayed::Limit.singleton_class.prepend(Module.new do
12
+ def within_limit(purpose, **)
13
+ LIMITED << purpose
14
+ yield
15
+ end
16
+ end)
17
+
18
+ class ApplicationJob < ActiveJob::Base; end
19
+
20
+ class KwargsJob < ApplicationJob
21
+ extend T::Sig
22
+
23
+ with_limit :kwargs_job
24
+
25
+ sig { params(id: Integer).returns(Integer) }
26
+ def perform(id:)
27
+ id
28
+ end
29
+ end
30
+
31
+ class PositionalJob < ApplicationJob
32
+ extend T::Sig
33
+
34
+ with_limit :positional_job
35
+
36
+ sig { params(id: Integer).returns(Integer) }
37
+ def perform(id)
38
+ id
39
+ end
40
+ end
41
+
42
+ class OnMethodJob < ApplicationJob
43
+ extend T::Sig
44
+
45
+ with_limit :on_method_job, on: :deliver!
46
+
47
+ sig { params(id: Integer).returns(Integer) }
48
+ def perform(id:)
49
+ deliver!(id: id)
50
+ end
51
+
52
+ sig { params(id: Integer).returns(Integer) }
53
+ def deliver!(id:)
54
+ id * 10
55
+ end
56
+ end
57
+
58
+ class PlainLimitable
59
+ extend T::Sig
60
+ include Delayed::Limitable
61
+
62
+ with_limit :plain_limitable, on: :do_work
63
+
64
+ sig { params(id: Integer).returns(Integer) }
65
+ def do_work(id:)
66
+ id
67
+ end
68
+ end
69
+
70
+ def check(description, expected_result, expected_limited)
71
+ LIMITED.clear
72
+ result = yield
73
+ return if result == expected_result && LIMITED == expected_limited
74
+
75
+ abort "#{description}: expected #{[expected_result, expected_limited]}, got #{[result, LIMITED]}"
76
+ end
77
+
78
+ 2.times do
79
+ check('KwargsJob.perform_now', 1, %i(kwargs_job)) { KwargsJob.perform_now(id: 1) }
80
+ check('PositionalJob.perform_now', 2, %i(positional_job)) { PositionalJob.perform_now(2) }
81
+ check('OnMethodJob.perform_now', 30, %i(on_method_job)) { OnMethodJob.perform_now(id: 3) }
82
+ check('PlainLimitable#do_work', 4, %i(plain_limitable)) { PlainLimitable.new.do_work(id: 4) }
83
+ end
84
+
85
+ begin
86
+ KwargsJob.perform_now(id: 'one')
87
+ abort 'KwargsJob.perform_now: expected a TypeError from its sig'
88
+ rescue TypeError
89
+ nil
90
+ end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: delayed
3
3
  version: !ruby/object:Gem::Version
4
- version: 4.1.0
4
+ version: 4.2.1
5
5
  platform: ruby
6
6
  authors:
7
7
  - Nathan Griffith
@@ -16,9 +16,10 @@ authors:
16
16
  - Matt Griffin
17
17
  - Steve Richert
18
18
  - Tobias Lütke
19
+ autorequire:
19
20
  bindir: bin
20
21
  cert_chain: []
21
- date: 1980-01-02 00:00:00.000000000 Z
22
+ date: 2026-11-23 00:00:00.000000000 Z
22
23
  dependencies:
23
24
  - !ruby/object:Gem::Dependency
24
25
  name: activerecord
@@ -129,6 +130,7 @@ files:
129
130
  - spec/delayed/helpers/migration_spec.rb
130
131
  - spec/delayed/job_spec.rb
131
132
  - spec/delayed/limit_spec.rb
133
+ - spec/delayed/limitable_sorbet_spec.rb
132
134
  - spec/delayed/limitable_spec.rb
133
135
  - spec/delayed/monitor_spec.rb
134
136
  - spec/delayed/plugins/instrumentation_spec.rb
@@ -143,6 +145,7 @@ files:
143
145
  - spec/performable_method_spec.rb
144
146
  - spec/psych_ext_spec.rb
145
147
  - spec/sample_jobs.rb
148
+ - spec/support/sorbet_runtime/limitable_jobs.rb
146
149
  - spec/worker_spec.rb
147
150
  - spec/yaml_ext_spec.rb
148
151
  homepage: http://github.com/betterment/delayed
@@ -153,6 +156,7 @@ metadata:
153
156
  bug_tracker_uri: https://github.com/betterment/delayed/issues
154
157
  source_code_uri: https://github.com/betterment/delayed
155
158
  rubygems_mfa_required: 'true'
159
+ post_install_message:
156
160
  rdoc_options: []
157
161
  require_paths:
158
162
  - lib
@@ -167,7 +171,8 @@ required_rubygems_version: !ruby/object:Gem::Requirement
167
171
  - !ruby/object:Gem::Version
168
172
  version: '0'
169
173
  requirements: []
170
- rubygems_version: 4.0.16
174
+ rubygems_version: 3.5.22
175
+ signing_key:
171
176
  specification_version: 4
172
177
  summary: a multi-threaded, SQL-driven ActiveJob backend used at Betterment to process
173
178
  millions of background jobs per day
@@ -183,6 +188,7 @@ test_files:
183
188
  - spec/delayed/helpers/migration_spec.rb
184
189
  - spec/delayed/job_spec.rb
185
190
  - spec/delayed/limit_spec.rb
191
+ - spec/delayed/limitable_sorbet_spec.rb
186
192
  - spec/delayed/limitable_spec.rb
187
193
  - spec/delayed/monitor_spec.rb
188
194
  - spec/delayed/plugins/instrumentation_spec.rb
@@ -197,5 +203,6 @@ test_files:
197
203
  - spec/performable_method_spec.rb
198
204
  - spec/psych_ext_spec.rb
199
205
  - spec/sample_jobs.rb
206
+ - spec/support/sorbet_runtime/limitable_jobs.rb
200
207
  - spec/worker_spec.rb
201
208
  - spec/yaml_ext_spec.rb