diff options
author | Adam Niedzielski <adamsunday@gmail.com> | 2017-01-20 13:42:46 +0300 |
---|---|---|
committer | Adam Niedzielski <adamsunday@gmail.com> | 2017-01-20 13:42:46 +0300 |
commit | 8c41d5f5e13c321aa38d7636e608dc84371cfd5d (patch) | |
tree | 6a68d0a5657015a8ce1a173d8ce9c294b2e40459 | |
parent | 5a41d92b9d73cbc41b649239e40a15955094f77e (diff) |
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.
-rw-r--r-- | app/models/key.rb | 7 | ||||
-rw-r--r-- | changelogs/unreleased/record-used-ssh-keys-once-per-day.yml | 4 | ||||
-rw-r--r-- | spec/models/key_spec.rb | 27 |
3 files changed, 33 insertions, 5 deletions
diff --git a/app/models/key.rb b/app/models/key.rb index 8be29c697f1..9c74ca84753 100644 --- a/app/models/key.rb +++ b/app/models/key.rb @@ -4,6 +4,8 @@ class Key < ActiveRecord::Base include AfterCommitQueue include Sortable + LAST_USED_AT_REFRESH_TIME = 1.day.to_i + belongs_to :user before_validation :generate_fingerprint @@ -50,7 +52,10 @@ class Key < ActiveRecord::Base end 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 def add_to_shell diff --git a/changelogs/unreleased/record-used-ssh-keys-once-per-day.yml b/changelogs/unreleased/record-used-ssh-keys-once-per-day.yml new file mode 100644 index 00000000000..9af9e3833c6 --- /dev/null +++ b/changelogs/unreleased/record-used-ssh-keys-once-per-day.yml @@ -0,0 +1,4 @@ +--- +title: Record used SSH keys only once per day +merge_request: 8655 +author: diff --git a/spec/models/key_spec.rb b/spec/models/key_spec.rb index 5eaddd822be..7c40cfd8253 100644 --- a/spec/models/key_spec.rb +++ b/spec/models/key_spec.rb @@ -30,11 +30,30 @@ describe Key, models: true do end describe "#update_last_used_at" do - it "enqueues a UseKeyWorker job" do - key = create(:key) + let(: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) + key.update_last_used_at + 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 - expect(UseKeyWorker).to receive(:perform_async).with(key.id) - key.update_last_used_at + it 'does not enqueue a UseKeyWorker job' do + expect(UseKeyWorker).not_to receive(:perform_async) + key.update_last_used_at + end end end end |