From b50125e0ab645b57599035b7b395ffe3374ff29c Mon Sep 17 00:00:00 2001 From: carolyncole <1599081+carolyncole@users.noreply.github.com> Date: Wed, 18 Dec 2024 14:39:10 -0500 Subject: [PATCH] Cache the mediaflux good status for 5 minutes on the health.json page (#1150) --- app/models/mediaflux_status.rb | 18 +++++++++--------- spec/models/mediaflux_status_spec.rb | 18 ++++++++++++++++++ 2 files changed, 27 insertions(+), 9 deletions(-) diff --git a/app/models/mediaflux_status.rb b/app/models/mediaflux_status.rb index afd86d97f..3398fadb0 100644 --- a/app/models/mediaflux_status.rb +++ b/app/models/mediaflux_status.rb @@ -4,15 +4,15 @@ def check! # Notice that we check Mediaflux status using our TigerData account # (rather than the "logged in" user since there is not always a logged # in user for the health check) - domain = Rails.configuration.mediaflux["api_domain"] - user = Rails.configuration.mediaflux["api_user"] - password = Rails.configuration.mediaflux["api_password"] - logon_request = Mediaflux::LogonRequest.new(domain:, user:, password:) - session_token = logon_request.session_token - if logon_request.error? - raise logon_request.response_error[:message] - else - Mediaflux::LogoutRequest.new(session_token:) + Rails.cache.fetch("mediaflux_health_session", expires_in: 5.minutes) do + logon_request = Mediaflux::LogonRequest.new + session_token = logon_request.session_token + if logon_request.error? + raise logon_request.response_error[:message] + else + Mediaflux::LogoutRequest.new(session_token:) + end + session_token end end end diff --git a/spec/models/mediaflux_status_spec.rb b/spec/models/mediaflux_status_spec.rb index d0d78d15c..60be7d4aa 100644 --- a/spec/models/mediaflux_status_spec.rb +++ b/spec/models/mediaflux_status_spec.rb @@ -2,10 +2,23 @@ require "rails_helper" RSpec.describe MediafluxStatus, connect_to_mediaflux: true, type: :model do + let(:memory_store) { ActiveSupport::Cache.lookup_store(:memory_store) } + + before do + allow(Mediaflux::LogonRequest).to receive(:new).and_call_original + allow(Rails).to receive(:cache).and_return(memory_store) + Rails.cache.clear + end + context "when Mediaflux is up and running" do it "reports status OK" do status = described_class.new expect { status.check! }.not_to raise_error + + # Does not make a second call immediately + expect { status.check! }.not_to raise_error + + expect(Mediaflux::LogonRequest).to have_received(:new).once end end @@ -20,6 +33,11 @@ it "reports that the status is not OK" do status = described_class.new expect { status.check! }.to raise_error(StandardError) + + # Does make a second call immediately on error + expect { status.check! }.to raise_error(StandardError) + + expect(Mediaflux::LogonRequest).to have_received(:new).twice end end end