The personal finance app for everyone (by everyone)
Ruby
Fall back to Frankfurter when the exchange rate provider has no API key (#4962)
arnaurodondev842dbf84de00
diff --git a/app/models/balance/sync_cache.rb b/app/models/balance/sync_cache.rbindex c3c98664b0..189870a2d8 100644--- a/app/models/balance/sync_cache.rb+++ b/app/models/balance/sync_cache.rb@@ -161,11 +161,11 @@ class Balance::SyncCache)end- # Which FX backend was configured when the rate came up missing, so support can filter- # these entries by provider. Read from the setting rather than `ExchangeRate.provider`,- # which raises on an unrecognized configuration — diagnostics must never fail the sync.+ # Which FX backend was in use when the rate came up missing, so support can filter+ # these entries by provider. `ExchangeRate.provider_name` raises on an unrecognized+ # configuration — diagnostics must never fail the sync.def exchange_rate_provider_key- ENV["EXCHANGE_RATE_PROVIDER"].presence || Setting.exchange_rate_provider+ ExchangeRate.provider_namerescue StandardErrornilenddiff --git a/app/models/exchange_rate/importer.rb b/app/models/exchange_rate/importer.rbindex 04fa84761e..2a7667a23c 100644--- a/app/models/exchange_rate/importer.rb+++ b/app/models/exchange_rate/importer.rb@@ -4,8 +4,9 @@ class ExchangeRate::ImporterPROVISIONAL_LOOKBACK_DAYS = 5- def initialize(exchange_rate_provider:, from:, to:, start_date:, end_date:, clear_cache: false)+ def initialize(exchange_rate_provider:, from:, to:, start_date:, end_date:, clear_cache: false, provider_name: ExchangeRate.provider_name)@exchange_rate_provider = exchange_rate_provider+ @current_provider_name = provider_name@from = from@to = to@start_date = start_date@@ -109,13 +110,7 @@ class ExchangeRate::Importerendprivate- attr_reader :exchange_rate_provider, :from, :to, :start_date, :end_date, :clear_cache-- # Resolves the provider name the same way as ExchangeRate::Provided.provider:- # ENV takes precedence over the DB Setting to stay consistent in env-configured deployments.- def current_provider_name- @current_provider_name ||= (ENV["EXCHANGE_RATE_PROVIDER"].presence || Setting.exchange_rate_provider).to_s- end+ attr_reader :exchange_rate_provider, :from, :to, :start_date, :end_date, :clear_cache, :current_provider_namedef upsert_rows(rows)batch_size = 200diff --git a/app/models/exchange_rate/provided.rb b/app/models/exchange_rate/provided.rbindex f90ad1b98b..4ce9f5b83a 100644--- a/app/models/exchange_rate/provided.rb+++ b/app/models/exchange_rate/provided.rb@@ -2,12 +2,29 @@ module ExchangeRate::Providedextend ActiveSupport::Concernclass_methods do- def provider- provider = ENV["EXCHANGE_RATE_PROVIDER"].presence || Setting.exchange_rate_provider- registry = Provider::Registry.for_concept(:exchange_rates)- registry.get_provider(provider.to_sym)+ def provider(name = provider_name)+ Provider::Registry.for_concept(:exchange_rates).get_provider(name.to_sym)end+ # Name of the backend `provider` uses. The default, Twelve Data, needs an API key;+ # without one, use keyless Frankfurter rather than no provider, which would import+ # no rates at all. Pair metadata and sync diagnostics key on this name, so+ # adding or removing the key is detected like any other provider change.+ def provider_name+ configured = configured_provider_name+ Provider::Registry.for_concept(:exchange_rates).get_provider(configured.to_sym) ? configured : "frankfurter"+ end++ def configured_provider_name+ (ENV["EXCHANGE_RATE_PROVIDER"].presence || Setting.exchange_rate_provider).to_s+ end++ def fallback_provider?+ provider_name != configured_provider_name+ end++ FALLBACK_DOWN_KEY = "exchange_rate:fallback_frankfurter_down"+# Maximum number of days to look back for a cached rate before calling the provider.NEAREST_RATE_LOOKBACK_DAYS = 5@@ -38,10 +55,18 @@ module ExchangeRate::Provided.firstreturn nearest if nearest.present?- return nil unless provider.present? # No provider configured (some self-hosted apps)+ fx_provider = provider+ return nil unless fx_provider.present? # No provider configured (some self-hosted apps)- response = provider.fetch_exchange_rate(from: from, to: to, date: date)+ # Keyless fallback on a signed-in request (e.g. reports): one short try, then skip Frankfurter for a+ # minute after a timeout or connection error (no HTTP response), so loops can't each wait. A lookup that+ # got a response (an HTTP error, an invalid rate) skips nothing else. Jobs keep retries.+ fail_fast = Current.session.present? && fallback_provider?+ return nil if fail_fast && Rails.cache.read(FALLBACK_DOWN_KEY)+ fx_provider = Provider::Frankfurter.new(timeout: 3, max_retries: 0) if fail_fast+ response = fx_provider.fetch_exchange_rate(from: from, to: to, date: date)+ Rails.cache.write(FALLBACK_DOWN_KEY, true, expires_in: 1.minute) if fail_fast && !response.success? && response.error.failure_code == :unreachablereturn nil unless response.success? # Provider errorrate = response.data@@ -198,7 +223,9 @@ module ExchangeRate::Provided# @return [Integer] The number of exchange rates synceddef import_provider_rates(from:, to:, start_date:, end_date:, clear_cache: false)- unless provider.present?+ name = provider_name+ exchange_rate_provider = provider(name)+ unless exchange_rate_provider.present?Rails.logger.warn("No provider configured for ExchangeRate.import_provider_rates")return 0end@@ -222,7 +249,8 @@ module ExchangeRate::ProvidedbeginExchangeRate::Importer.new(- exchange_rate_provider: provider,+ exchange_rate_provider: exchange_rate_provider,+ provider_name: name,from: from,to: to,start_date: start_date,diff --git a/app/models/exchange_rate_pair.rb b/app/models/exchange_rate_pair.rbindex 2da5f72be8..857602d728 100644--- a/app/models/exchange_rate_pair.rb+++ b/app/models/exchange_rate_pair.rb@@ -3,7 +3,7 @@ class ExchangeRatePair < ApplicationRecorddef self.for_pair(from:, to:, provider_name: nil)pair = find_or_create_by!(from_currency: from, to_currency: to)- current_provider = provider_name || resolve_provider_name+ current_provider = provider_name || ExchangeRate.provider_nameif pair.provider_name != current_provider && pair.first_provider_rate_on.present?ExchangeRatePair@@ -18,16 +18,10 @@ class ExchangeRatePair < ApplicationRecordfind_by!(from_currency: from, to_currency: to)end- # Resolves the runtime provider name the same way as ExchangeRate::Provided.provider:- # ENV takes precedence over the DB Setting.- def self.resolve_provider_name- (ENV["EXCHANGE_RATE_PROVIDER"].presence || Setting.exchange_rate_provider).to_s- end-def self.record_first_provider_rate_on(from:, to:, date:, provider_name: nil)return if date.blank?- current_provider = provider_name || resolve_provider_name+ current_provider = provider_name || ExchangeRate.provider_namepair = for_pair(from: from, to: to, provider_name: current_provider)ExchangeRatePairdiff --git a/app/models/provider/frankfurter.rb b/app/models/provider/frankfurter.rbindex aca0e7511f..294583b0b7 100644--- a/app/models/provider/frankfurter.rb+++ b/app/models/provider/frankfurter.rb@@ -21,8 +21,11 @@ class Provider::Frankfurter < Provider# No published rate limit, but a light throttle is cheap insurance.MIN_REQUEST_INTERVAL = 0.15- def initialize- # No API key required, public endpoint only.+ # No API key required. The defaults suit background syncs; a request-thread+ # caller can pass a tighter timeout and no retries.+ def initialize(timeout: 20, max_retries: 3)+ @timeout = timeout+ @max_retries = max_retriesenddef healthy?@@ -106,11 +109,11 @@ class Provider::Frankfurter < Providerdef client@client ||= Faraday.new(url: base_url, ssl: self.class.faraday_ssl_options) do |faraday|- faraday.options.open_timeout = 5- faraday.options.timeout = 20+ faraday.options.open_timeout = [ 5, @timeout ].min+ faraday.options.timeout = @timeoutfaraday.request(:retry, {- max: 3,+ max: @max_retries,interval: 0.5,interval_randomness: 0.5,backoff_factor: 2,@@ -123,6 +126,14 @@ class Provider::Frankfurter < Providerendend+ # A request that got no HTTP response at all (timeout, refused connection) is tagged+ # :unreachable, so a caller can tell Frankfurter being down from a bad answer for one pair.+ def default_error_transformer(error)+ return super unless error.is_a?(Faraday::Error) && error.response.nil?++ Error.new(error.message, failure_code: :unreachable)+ end+def generate_same_currency_rates(from, to, start_date, end_date)(start_date..end_date).map do |date|Rate.new(date: date, from: from, to: to, rate: 1.0)diff --git a/test/models/balance/sync_cache_test.rb b/test/models/balance/sync_cache_test.rbindex d0c5741647..896ef56ceb 100644--- a/test/models/balance/sync_cache_test.rb+++ b/test/models/balance/sync_cache_test.rb@@ -228,11 +228,30 @@ class Balance::SyncCacheTest < ActiveSupport::TestCaseassert_equal "Balance::SyncCache", log.sourceassert_equal "warn", log.levelassert_equal @account, log.account- assert_equal Setting.exchange_rate_provider, log.provider_key+ assert_equal ExchangeRate.provider_name, log.provider_keyassert_equal 2, log.metadata["unconvertible_entry_count"]assert_equal [ "EUR->USD", "GBP->USD" ], log.metadata["missing_rate_pairs"].sortend+ test "labels missing-rate debug entries with Frankfurter when Twelve Data has no key" do+ @account.entries.create!(+ date: Date.current,+ name: "EUR Transaction",+ amount: 100,+ currency: "EUR",+ entryable: Transaction.new(extra: {})+ )+ Setting.stubs(:exchange_rate_provider).returns("twelve_data")+ Setting.stubs(:twelve_data_api_key).returns(nil)+ ExchangeRate.stubs(:find_or_fetch_rate).returns(nil)++ with_env_overrides("EXCHANGE_RATE_PROVIDER" => nil, "TWELVE_DATA_API_KEY" => nil) do+ Balance::SyncCache.new(@account).send(:converted_entries)+ end++ assert_equal "frankfurter", DebugLogEntry.order(:created_at).last.provider_key+ end+test "records no debug log entry when every entry converts" do@account.entries.create!(date: Date.current,diff --git a/test/models/exchange_rate/importer_test.rb b/test/models/exchange_rate/importer_test.rbindex e227b9b478..b9614f9242 100644--- a/test/models/exchange_rate/importer_test.rb+++ b/test/models/exchange_rate/importer_test.rb@@ -363,7 +363,7 @@ class ExchangeRate::ImporterTest < ActiveSupport::TestCaseExchangeRatePair.create!(from_currency: "USD", to_currency: "EUR",first_provider_rate_on: 3.days.ago.to_date,- provider_name: Setting.exchange_rate_provider.to_s+ provider_name: ExchangeRate.provider_name)# Provider now returns an earlier date with clear_cache@@ -388,6 +388,63 @@ class ExchangeRate::ImporterTest < ActiveSupport::TestCaseassert_equal 10.days.ago.to_date, pair.first_provider_rate_onend+ test "first_provider_rate_on is reset when Frankfurter replaces a keyless Twelve Data" do+ ExchangeRate.delete_all+ ExchangeRatePair.delete_all+ Setting.stubs(:exchange_rate_provider).returns("twelve_data")+ Setting.stubs(:twelve_data_api_key).returns(nil)++ ExchangeRatePair.create!(+ from_currency: "USD", to_currency: "EUR",+ first_provider_rate_on: 10.days.ago.to_date,+ provider_name: "twelve_data"+ )++ provider_response = provider_success_response([+ OpenStruct.new(from: "USD", to: "EUR", date: 3.days.ago.to_date, rate: 1.3),+ OpenStruct.new(from: "USD", to: "EUR", date: Date.current, rate: 1.5)+ ])++ @provider.expects(:fetch_exchange_rates).returns(provider_response)++ with_env_overrides("EXCHANGE_RATE_PROVIDER" => nil, "TWELVE_DATA_API_KEY" => nil) do+ ExchangeRate::Importer.new(+ exchange_rate_provider: @provider,+ from: "USD",+ to: "EUR",+ start_date: 30.days.ago.to_date,+ end_date: Date.current,+ clear_cache: true+ ).import_provider_rates+ end++ pair = ExchangeRatePair.find_by!(from_currency: "USD", to_currency: "EUR")+ assert_equal "frankfurter", pair.provider_name+ assert_equal 3.days.ago.to_date, pair.first_provider_rate_on+ end++ test "pair metadata keeps the name of the provider that fetched, even if settings change mid-import" do+ ExchangeRate.delete_all+ ExchangeRatePair.delete_all+ Setting.stubs(:exchange_rate_provider).returns("twelve_data")+ Setting.stubs(:twelve_data_api_key).returns(nil)++ provider_response = provider_success_response([+ OpenStruct.new(from: "USD", to: "EUR", date: 3.days.ago.to_date, rate: 1.3),+ OpenStruct.new(from: "USD", to: "EUR", date: Date.current, rate: 1.5)+ ])++ with_env_overrides("EXCHANGE_RATE_PROVIDER" => nil, "TWELVE_DATA_API_KEY" => nil) do+ # A Twelve Data key is saved while the keyless Frankfurter fallback is fetching.+ Provider::Frankfurter.any_instance.expects(:fetch_exchange_rates)+ .with { ENV["TWELVE_DATA_API_KEY"] = "new-key" }.returns(provider_response)++ ExchangeRate.import_provider_rates(from: "USD", to: "EUR", start_date: 30.days.ago.to_date, end_date: Date.current, clear_cache: true)+ end++ assert_equal "frankfurter", ExchangeRatePair.find_by!(from_currency: "USD", to_currency: "EUR").provider_name+ end+test "first_provider_rate_on is NOT moved forward when provider shrinks coverage" doExchangeRate.delete_allExchangeRatePair.delete_all@@ -395,7 +452,7 @@ class ExchangeRate::ImporterTest < ActiveSupport::TestCaseExchangeRatePair.create!(from_currency: "USD", to_currency: "EUR",first_provider_rate_on: 10.days.ago.to_date,- provider_name: Setting.exchange_rate_provider.to_s+ provider_name: ExchangeRate.provider_name)# Provider now only returns from 3 days ago (shrunk window)@@ -427,7 +484,7 @@ class ExchangeRate::ImporterTest < ActiveSupport::TestCaseExchangeRatePair.create!(from_currency: "USD", to_currency: "EUR",first_provider_rate_on: clamp_date,- provider_name: Setting.exchange_rate_provider.to_s+ provider_name: ExchangeRate.provider_name)# Seed DB with rates from clamp to yesterday@@ -465,7 +522,7 @@ class ExchangeRate::ImporterTest < ActiveSupport::TestCaseExchangeRatePair.create!(from_currency: "USD", to_currency: "EUR",first_provider_rate_on: clamp_date,- provider_name: Setting.exchange_rate_provider.to_s+ provider_name: ExchangeRate.provider_name)(clamp_date..Date.current).each_with_index do |date, idx|diff --git a/test/models/exchange_rate_pair_test.rb b/test/models/exchange_rate_pair_test.rbindex ffec338b5c..4279ec49e6 100644--- a/test/models/exchange_rate_pair_test.rb+++ b/test/models/exchange_rate_pair_test.rb@@ -40,6 +40,39 @@ class ExchangeRatePairTest < ActiveSupport::TestCaseendend+ test "for_pair resets clamp when the Twelve Data key is removed and Frankfurter takes over" do+ ExchangeRatePair.delete_all+ ExchangeRatePair.create!(+ from_currency: "USD", to_currency: "EUR",+ first_provider_rate_on: 1.year.ago.to_date, provider_name: "twelve_data"+ )+ Setting.stubs(:exchange_rate_provider).returns("twelve_data")+ Setting.stubs(:twelve_data_api_key).returns(nil)++ with_env_overrides("EXCHANGE_RATE_PROVIDER" => nil, "TWELVE_DATA_API_KEY" => nil) do+ refreshed = ExchangeRatePair.for_pair(from: "USD", to: "EUR")++ assert_nil refreshed.first_provider_rate_on+ assert_equal "frankfurter", refreshed.provider_name+ end+ end++ test "for_pair resets clamp when a Twelve Data key is added" do+ ExchangeRatePair.delete_all+ ExchangeRatePair.create!(+ from_currency: "USD", to_currency: "EUR",+ first_provider_rate_on: 1.year.ago.to_date, provider_name: "frankfurter"+ )+ Setting.stubs(:exchange_rate_provider).returns("twelve_data")++ with_env_overrides("EXCHANGE_RATE_PROVIDER" => nil, "TWELVE_DATA_API_KEY" => "test-key") do+ refreshed = ExchangeRatePair.for_pair(from: "USD", to: "EUR")++ assert_nil refreshed.first_provider_rate_on+ assert_equal "twelve_data", refreshed.provider_name+ end+ end+test "record_first_provider_rate_on sets date on NULL" doExchangeRatePair.delete_allExchangeRatePair.for_pair(from: "USD", to: "EUR")diff --git a/test/models/exchange_rate_test.rb b/test/models/exchange_rate_test.rbindex 279124dffd..988c44257d 100644--- a/test/models/exchange_rate_test.rb+++ b/test/models/exchange_rate_test.rb@@ -10,6 +10,82 @@ class ExchangeRateTest < ActiveSupport::TestCaseExchangeRate.stubs(:provider).returns(@provider)end+ test "falls back to Frankfurter when the configured provider has no API key" do+ ExchangeRate.unstub(:provider)+ Setting.stubs(:exchange_rate_provider).returns("twelve_data")+ Setting.stubs(:twelve_data_api_key).returns(nil)++ with_env_overrides("EXCHANGE_RATE_PROVIDER" => nil, "TWELVE_DATA_API_KEY" => nil) do+ assert_instance_of Provider::Frankfurter, ExchangeRate.provider+ assert_equal "frankfurter", ExchangeRate.provider_name+ end+ end++ test "uses the configured provider when it has an API key" do+ ExchangeRate.unstub(:provider)+ Setting.stubs(:exchange_rate_provider).returns("twelve_data")++ with_env_overrides("EXCHANGE_RATE_PROVIDER" => nil, "TWELVE_DATA_API_KEY" => "test-key") do+ assert_instance_of Provider::TwelveData, ExchangeRate.provider+ assert_equal "twelve_data", ExchangeRate.provider_name+ end+ end++ test "keyless fallback on a signed-in request tries Frankfurter once, then skips it for a minute" do+ keyless_fallback(signed_in: true) do+ stub_request(:get, %r{/rate/SEK/JPY}).to_timeout+ 10.times { assert_raises(Money::ConversionError) { Money.new(100, "SEK").exchange_to("JPY") } }+ 5.times { |i| assert_equal({}, ExchangeRate.rates_for(%w[SEK], to: "JPY", date: Date.current - (i * 10).days)) }+ assert_requested :get, %r{/rate/SEK/JPY}, times: 1++ travel 61.seconds+ assert_nil ExchangeRate.find_or_fetch_rate(from: "SEK", to: "JPY", date: Date.current)+ assert_requested :get, %r{/rate/SEK/JPY}, times: 2+ end+ end++ test "keyless fallback keeps checking other pairs after an unsupported one" do+ keyless_fallback(signed_in: true) do+ stub_request(:get, %r{/rate/XAG/JPY}).to_return(status: 404, body: { message: "not found" }.to_json)+ stub_request(:get, %r{/rate/SEK/JPY}).to_return(status: 200, body: { date: Date.current.to_s, base: "SEK", quote: "JPY", rate: 14.2 }.to_json)++ assert_nil ExchangeRate.find_or_fetch_rate(from: "XAG", to: "JPY", date: Date.current)+ assert_equal 14.2, ExchangeRate.find_or_fetch_rate(from: "SEK", to: "JPY", date: Date.current).rate+ end+ end++ test "keyless fallback keeps checking other pairs after an invalid rate for one" do+ keyless_fallback(signed_in: true) do+ stub_request(:get, %r{/rate/SEK/JPY}).to_return(status: 200, body: { date: Date.current.to_s, base: "SEK", quote: "JPY", rate: 0 }.to_json)+ stub_request(:get, %r{/rate/DKK/JPY}).to_return(status: 200, body: { date: Date.current.to_s, base: "DKK", quote: "JPY", rate: nil }.to_json)+ stub_request(:get, %r{/rate/NOK/JPY}).to_return(status: 200, body: { date: Date.current.to_s, base: "NOK", quote: "JPY", rate: 13.9 }.to_json)++ assert_nil ExchangeRate.find_or_fetch_rate(from: "SEK", to: "JPY", date: Date.current)+ assert_nil ExchangeRate.find_or_fetch_rate(from: "DKK", to: "JPY", date: Date.current)+ assert_equal 13.9, ExchangeRate.find_or_fetch_rate(from: "NOK", to: "JPY", date: Date.current).rate+ end+ end++ test "keyless fallback skips Frankfurter for a minute after a refused connection" do+ keyless_fallback(signed_in: true) do+ stub_request(:get, %r{/rate/SEK/JPY}).to_raise(Faraday::ConnectionFailed.new("connection refused"))+ stub_request(:get, %r{/rate/NOK/JPY}).to_return(status: 200, body: { date: Date.current.to_s, base: "NOK", quote: "JPY", rate: 13.9 }.to_json)++ assert_nil ExchangeRate.find_or_fetch_rate(from: "SEK", to: "JPY", date: Date.current)+ assert_nil ExchangeRate.find_or_fetch_rate(from: "NOK", to: "JPY", date: Date.current)+ assert_not_requested :get, %r{/rate/NOK/JPY}+ end+ end++ test "keyless fallback outside a request, as in a sync job, keeps the retries" do+ keyless_fallback(signed_in: false) do+ stub_request(:get, %r{/rate/SEK/JPY}).to_timeout+ .then.to_return(status: 200, body: { date: Date.current.to_s, base: "SEK", quote: "JPY", rate: 14.2 }.to_json)++ assert_equal 14.2, ExchangeRate.find_or_fetch_rate(from: "SEK", to: "JPY", date: Date.current).rate+ end+ end+test "finds rate in DB" doexisting_rate = exchange_rates(:one)@@ -304,6 +380,16 @@ class ExchangeRateTest < ActiveSupport::TestCaseendprivate+ def keyless_fallback(signed_in:, &block)+ ExchangeRate.unstub(:provider)+ ExchangeRate.where(from_currency: %w[SEK XAG NOK DKK], to_currency: "JPY").delete_all+ Setting.stubs(:exchange_rate_provider).returns("twelve_data")+ Setting.stubs(:twelve_data_api_key).returns(nil)+ Rails.stubs(:cache).returns(ActiveSupport::Cache::MemoryStore.new)+ Current.session = sessions(:one) if signed_in+ with_env_overrides("EXCHANGE_RATE_PROVIDER" => nil, "TWELVE_DATA_API_KEY" => nil, &block)+ end+# With sequential scans priced out, the planner uses an index whenever one# can answer the query; without one it still falls back to a sequential scan.def assert_index_lookup(relation, index_name)