From 3fffc4a0b90f4b966ae3ea9841582a2115425382 Mon Sep 17 00:00:00 2001 From: Keito Kira Date: Tue, 12 Dec 2023 17:55:47 +0900 Subject: [PATCH] Fix negative delay. Issue: https://github.com/aws/aws-sdk-rails/issues/106 --- .../queue_adapters/amazon_sqs_adapter.rb | 2 + .../queue_adapters/amazon_sqs_adapter_test.rb | 66 ++++++++++++------- 2 files changed, 45 insertions(+), 23 deletions(-) diff --git a/lib/active_job/queue_adapters/amazon_sqs_adapter.rb b/lib/active_job/queue_adapters/amazon_sqs_adapter.rb index 28a9b3a2..9998d18b 100644 --- a/lib/active_job/queue_adapters/amazon_sqs_adapter.rb +++ b/lib/active_job/queue_adapters/amazon_sqs_adapter.rb @@ -11,6 +11,8 @@ def enqueue(job) def enqueue_at(job, timestamp) delay = (timestamp - Time.now.to_f).floor + + delay = 0 if delay.negative? raise ArgumentError, 'Unable to queue a job with a delay great than 15 minutes' if delay > 15.minutes _enqueue(job, nil, delay_seconds: delay) diff --git a/test/active_job/queue_adapters/amazon_sqs_adapter_test.rb b/test/active_job/queue_adapters/amazon_sqs_adapter_test.rb index 459c818e..f0caf2d8 100644 --- a/test/active_job/queue_adapters/amazon_sqs_adapter_test.rb +++ b/test/active_job/queue_adapters/amazon_sqs_adapter_test.rb @@ -144,30 +144,50 @@ module QueueAdapters end end - it 'enqueues delayed jobs' do - t1 = Time.now - allow(Time).to receive(:now).and_return t1 - - expect(client).to receive(:send_message).with( - { - queue_url: 'https://queue-url', - delay_seconds: 60, - message_body: instance_of(String), - message_attributes: instance_of(Hash) - } - ) - - TestJob.set(wait: 1.minute).perform_later('test') - sleep(0.2) - end + describe 'with queue delay' do + it 'enqueues jobs with proper delay' do + t1 = Time.now + allow(Time).to receive(:now).and_return t1 + + expect(client).to receive(:send_message).with( + { + queue_url: 'https://queue-url', + delay_seconds: 60, + message_body: instance_of(String), + message_attributes: instance_of(Hash) + } + ) + + TestJob.set(wait: 1.minute).perform_later('test') + sleep(0.2) + end - it 'raises an error when job delay is great than SQS support' do - t1 = Time.now - allow(Time).to receive(:now).and_return t1 - expect do - TestJob.set(wait: 1.day).perform_later('test') - end.to raise_error ArgumentError - end + it 'enqueues jobs with zero or negative delay' do + t1 = Time.now + allow(Time).to receive(:now).and_return t1 + + expect(client).to receive(:send_message).with( + { + queue_url: 'https://queue-url', + delay_seconds: 0, + message_body: instance_of(String), + message_attributes: instance_of(Hash) + } + ).twice + + TestJob.set(wait: 0).perform_later('test') + TestJob.set(wait: -1).perform_later('test') + sleep(0.2) + end + + it 'raises an error when job delay is great than SQS support' do + t1 = Time.now + allow(Time).to receive(:now).and_return t1 + expect do + TestJob.set(wait: 1.day).perform_later('test') + end.to raise_error ArgumentError + end + end end end end