Record used SSH keys only once per day
Use Gitlab::ExclusiveLease to make sure that we enqueue Sidekiq job at most once per day for given key.
This commit is contained in:
parent
5a41d92b9d
commit
8c41d5f5e1
|
@ -4,6 +4,8 @@ class Key < ActiveRecord::Base
|
||||||
include AfterCommitQueue
|
include AfterCommitQueue
|
||||||
include Sortable
|
include Sortable
|
||||||
|
|
||||||
|
LAST_USED_AT_REFRESH_TIME = 1.day.to_i
|
||||||
|
|
||||||
belongs_to :user
|
belongs_to :user
|
||||||
|
|
||||||
before_validation :generate_fingerprint
|
before_validation :generate_fingerprint
|
||||||
|
@ -50,7 +52,10 @@ class Key < ActiveRecord::Base
|
||||||
end
|
end
|
||||||
|
|
||||||
def update_last_used_at
|
def update_last_used_at
|
||||||
UseKeyWorker.perform_async(self.id)
|
lease = Gitlab::ExclusiveLease.new("key_update_last_used_at:#{id}", timeout: LAST_USED_AT_REFRESH_TIME)
|
||||||
|
return unless lease.try_obtain
|
||||||
|
|
||||||
|
UseKeyWorker.perform_async(id)
|
||||||
end
|
end
|
||||||
|
|
||||||
def add_to_shell
|
def add_to_shell
|
||||||
|
|
|
@ -0,0 +1,4 @@
|
||||||
|
---
|
||||||
|
title: Record used SSH keys only once per day
|
||||||
|
merge_request: 8655
|
||||||
|
author:
|
|
@ -30,13 +30,32 @@ describe Key, models: true do
|
||||||
end
|
end
|
||||||
|
|
||||||
describe "#update_last_used_at" do
|
describe "#update_last_used_at" do
|
||||||
it "enqueues a UseKeyWorker job" do
|
let(:key) { create(:key) }
|
||||||
key = create(:key)
|
|
||||||
|
|
||||||
|
context 'when key was not updated during the last day' do
|
||||||
|
before do
|
||||||
|
allow_any_instance_of(Gitlab::ExclusiveLease).to receive(:try_obtain).
|
||||||
|
and_return('000000')
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'enqueues a UseKeyWorker job' do
|
||||||
expect(UseKeyWorker).to receive(:perform_async).with(key.id)
|
expect(UseKeyWorker).to receive(:perform_async).with(key.id)
|
||||||
key.update_last_used_at
|
key.update_last_used_at
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
context 'when key was updated during the last day' do
|
||||||
|
before do
|
||||||
|
allow_any_instance_of(Gitlab::ExclusiveLease).to receive(:try_obtain).
|
||||||
|
and_return(false)
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'does not enqueue a UseKeyWorker job' do
|
||||||
|
expect(UseKeyWorker).not_to receive(:perform_async)
|
||||||
|
key.update_last_used_at
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
context "validation of uniqueness (based on fingerprint uniqueness)" do
|
context "validation of uniqueness (based on fingerprint uniqueness)" do
|
||||||
|
|
Loading…
Reference in New Issue