1# frozen_string_literal: true 2 3require 'spec_helper' 4 5RSpec.describe Gitlab::Database::Reindexing::Coordinator do 6 include Database::DatabaseHelpers 7 include ExclusiveLeaseHelpers 8 9 describe '.perform' do 10 subject { described_class.new(index, notifier).perform } 11 12 let(:index) { create(:postgres_index) } 13 let(:notifier) { instance_double(Gitlab::Database::Reindexing::GrafanaNotifier, notify_start: nil, notify_end: nil) } 14 let(:reindexer) { instance_double(Gitlab::Database::Reindexing::ReindexConcurrently, perform: nil) } 15 let(:action) { create(:reindex_action, index: index) } 16 17 let!(:lease) { stub_exclusive_lease(lease_key, uuid, timeout: lease_timeout) } 18 let(:lease_key) { "gitlab/database/reindexing/coordinator/#{Gitlab::Database::PRIMARY_DATABASE_NAME}" } 19 let(:lease_timeout) { 1.day } 20 let(:uuid) { 'uuid' } 21 22 around do |example| 23 model = Gitlab::Database.database_base_models[Gitlab::Database::PRIMARY_DATABASE_NAME] 24 25 Gitlab::Database::SharedModel.using_connection(model.connection) do 26 example.run 27 end 28 end 29 30 before do 31 swapout_view_for_table(:postgres_indexes) 32 33 allow(Gitlab::Database::Reindexing::ReindexConcurrently).to receive(:new).with(index).and_return(reindexer) 34 allow(Gitlab::Database::Reindexing::ReindexAction).to receive(:create_for).with(index).and_return(action) 35 end 36 37 context 'locking' do 38 it 'acquires a lock while reindexing' do 39 expect(lease).to receive(:try_obtain).ordered.and_return(uuid) 40 41 expect(reindexer).to receive(:perform).ordered 42 43 expect(Gitlab::ExclusiveLease).to receive(:cancel).ordered.with(lease_key, uuid) 44 45 subject 46 end 47 48 it 'does not perform reindexing actions if lease is not granted' do 49 expect(lease).to receive(:try_obtain).ordered.and_return(false) 50 expect(Gitlab::Database::Reindexing::ReindexConcurrently).not_to receive(:new) 51 52 subject 53 end 54 end 55 56 context 'notifications' do 57 it 'sends #notify_start before reindexing' do 58 expect(notifier).to receive(:notify_start).with(action).ordered 59 expect(reindexer).to receive(:perform).ordered 60 61 subject 62 end 63 64 it 'sends #notify_end after reindexing and updating the action is done' do 65 expect(action).to receive(:finish).ordered 66 expect(notifier).to receive(:notify_end).with(action).ordered 67 68 subject 69 end 70 end 71 72 context 'action tracking' do 73 it 'calls #finish on the action' do 74 expect(reindexer).to receive(:perform).ordered 75 expect(action).to receive(:finish).ordered 76 77 subject 78 end 79 80 it 'upon error, it still calls finish and raises the error' do 81 expect(reindexer).to receive(:perform).ordered.and_raise('something went wrong') 82 expect(action).to receive(:finish).ordered 83 84 expect { subject }.to raise_error(/something went wrong/) 85 86 expect(action).to be_failed 87 end 88 end 89 end 90end 91