Add lease to CheckGcpProjectBillingWorker

This commit is contained in:
Matija Čupić 2017-12-16 04:21:13 +01:00
parent 78f85f3fd3
commit 99043d244c
No known key found for this signature in database
GPG key ID: 4BAF84FFACD2E5DE
2 changed files with 38 additions and 9 deletions

View file

@ -1,16 +1,27 @@
class CheckGcpProjectBillingWorker
include ApplicationWorker
LEASE_TIMEOUT = 1.minute.to_i
def self.redis_shared_state_key_for(token)
"gitlab:gcp:#{token}:billing_enabled"
end
def perform(token)
return unless token
return unless try_obtain_lease_for(token)
billing_enabled = CheckGcpProjectBillingService.new.execute(token)
Gitlab::Redis::SharedState.with do |redis|
redis.set(self.class.redis_shared_state_key_for(token), billing_enabled)
end
end
private
def try_obtain_lease_for(token)
Gitlab::ExclusiveLease
.new("check_gcp_project_billing_worker:#{token}", timeout: LEASE_TIMEOUT)
.try_obtain
end
end

View file

@ -5,20 +5,38 @@ describe CheckGcpProjectBillingWorker do
let(:token) { 'bogustoken' }
subject { described_class.new.perform(token) }
it 'calls the service' do
expect(CheckGcpProjectBillingService).to receive_message_chain(:new, :execute)
context 'when there is no lease' do
before do
allow_any_instance_of(CheckGcpProjectBillingWorker).to receive(:try_obtain_lease_for).and_return('randomuuid')
end
subject
it 'calls the service' do
expect(CheckGcpProjectBillingService).to receive_message_chain(:new, :execute)
subject
end
it 'stores billing status in redis' do
redis_double = double
expect(CheckGcpProjectBillingService).to receive_message_chain(:new, :execute).and_return(true)
expect(Gitlab::Redis::SharedState).to receive(:with).and_yield(redis_double)
expect(redis_double).to receive(:set).with(CheckGcpProjectBillingWorker.redis_shared_state_key_for(token), anything)
subject
end
end
it 'stores billing status in redis' do
redis_double = double
context 'when there is a lease' do
before do
allow_any_instance_of(CheckGcpProjectBillingWorker).to receive(:try_obtain_lease_for).and_return(false)
end
expect(CheckGcpProjectBillingService).to receive_message_chain(:new, :execute).and_return(true)
expect(Gitlab::Redis::SharedState).to receive(:with).and_yield(redis_double)
expect(redis_double).to receive(:set).with(CheckGcpProjectBillingWorker.redis_shared_state_key_for(token), anything)
it 'does not call the service' do
expect(CheckGcpProjectBillingService).not_to receive(:new)
subject
subject
end
end
end
end