diff --git a/app/services/alma_services.rb b/app/services/alma_services.rb index b283b664..254fcd25 100644 --- a/app/services/alma_services.rb +++ b/app/services/alma_services.rb @@ -167,7 +167,25 @@ def record(id) record_id = BerkeleyLibrary::Alma::RecordId.parse(id) return unless record_id - record_id.get_marc_record + fetch_record(record_id, id) + end + + private + + def fetch_record(record_id, id) + attempts = 0 + + begin + attempts += 1 + record_id.get_marc_record + rescue Errno::ECONNRESET => e + raise if attempts >= 3 + + Rails.logger.warn("Retry Alma fetch #{attempts + 1}/3 for #{id}: #{e.message}") + + sleep(1) + retry + end end end end diff --git a/spec/models/host_bib_spec.rb b/spec/models/host_bib_spec.rb index 84d2bf38..729752c3 100644 --- a/spec/models/host_bib_spec.rb +++ b/spec/models/host_bib_spec.rb @@ -26,12 +26,46 @@ def marc_stub record end - context 'AlmaServices::Marc has' do - it 'alma marc' do + context 'AlmaServices::Marc' do + it 'has alma marc' do class_double(BerkeleyLibrary::Alma::RecordId, parse: record_id).as_stubbed_const expect(record_id).to receive(:get_marc_record).and_return('marc_stub') expect(AlmaServices::Marc.record(mms_id)).to eq('marc_stub') end + + it 'retries when the connection is reset' do + class_double(BerkeleyLibrary::Alma::RecordId, parse: record_id).as_stubbed_const + allow(AlmaServices::Marc).to receive(:sleep) + + attempts = 0 + + allow(record_id).to receive(:get_marc_record) do + attempts += 1 + raise Errno::ECONNRESET if attempts == 1 + + 'marc_stub' + end + + expect(AlmaServices::Marc.record(mms_id)).to eq('marc_stub') + expect(record_id).to have_received(:get_marc_record).twice + end + + it 'raises after exhuasting retries' do + class_double(BerkeleyLibrary::Alma::RecordId, parse: record_id).as_stubbed_const + allow(AlmaServices::Marc).to receive(:sleep) + + allow(record_id) + .to receive(:get_marc_record) + .and_raise(Errno::ECONNRESET) + + expect do + AlmaServices::Marc.record(mms_id) + end.to raise_error(Errno::ECONNRESET) + + expect(record_id) + .to have_received(:get_marc_record) + .exactly(3).times + end end RSpec.shared_examples 'host_bib has alma marc' do |marc_status|