The personal finance app for everyone (by everyone)
Ruby
Set explicit HTTP timeouts on six market-data clients (#5308)
jaysbeekay93d3f2355012
diff --git a/app/models/provider/alpha_vantage.rb b/app/models/provider/alpha_vantage.rbindex 033c9cfbfa..ab2cc2a10b 100644--- a/app/models/provider/alpha_vantage.rb+++ b/app/models/provider/alpha_vantage.rb@@ -219,6 +219,9 @@ class Provider::AlphaVantage < 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.request(:retry, {max: 3,interval: 1.0,diff --git a/app/models/provider/eodhd.rb b/app/models/provider/eodhd.rbindex c66426a78e..da8d36329e 100644--- a/app/models/provider/eodhd.rb+++ b/app/models/provider/eodhd.rb@@ -16,6 +16,11 @@ class Provider::Eodhd < Provider# EODHD bills each fundamentals request as 10 API calls against the daily allowanceFUNDAMENTALS_REQUEST_COST = 10+ # A fundamentals response is large and slow to start, so it gets a 60 s read+ # limit rather than the client's 20 s: each retry after a timeout bills+ # another ten calls.+ FUNDAMENTALS_READ_TIMEOUT = 60+# The free tier provides ~1 year of EOD data; paid plans go back 30+ years.# Raising EODHD_MAX_REQUESTS_PER_DAY above the free cap signals a paid key.def max_history_days@@ -196,6 +201,7 @@ class Provider::Eodhd < Provider@last_counted_on = nilresponse = client.get("#{base_url}/api/fundamentals/#{CGI.escape(ticker)}") do |req|+ req.options.timeout = FUNDAMENTALS_READ_TIMEOUTreq.params["api_token"] = api_keyreq.params["fmt"] = "json"end@@ -301,6 +307,9 @@ class Provider::Eodhd < 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.request(:retry, {max: 3,interval: 1.0,diff --git a/app/models/provider/mansa.rb b/app/models/provider/mansa.rbindex 9cb4b95411..ba6ea23b23 100644--- a/app/models/provider/mansa.rb+++ b/app/models/provider/mansa.rb@@ -250,6 +250,9 @@ class Provider::Mansa < 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.request(:retry, {max: 3,interval: 1.0,diff --git a/app/models/provider/mfapi.rb b/app/models/provider/mfapi.rbindex 0e597891f7..6dd136943f 100644--- a/app/models/provider/mfapi.rb+++ b/app/models/provider/mfapi.rb@@ -142,6 +142,9 @@ class Provider::Mfapi < 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.request(:retry, {max: 3,interval: 1.0,diff --git a/app/models/provider/tiingo.rb b/app/models/provider/tiingo.rbindex cb40cd1c34..0b153f2af7 100644--- a/app/models/provider/tiingo.rb+++ b/app/models/provider/tiingo.rb@@ -217,6 +217,9 @@ class Provider::Tiingo < 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.request(:retry, {max: 3,interval: 1.0,diff --git a/app/models/provider/twelve_data.rb b/app/models/provider/twelve_data.rbindex e96fd1ff90..097bc72e6e 100644--- a/app/models/provider/twelve_data.rb+++ b/app/models/provider/twelve_data.rb@@ -11,6 +11,11 @@ class Provider::TwelveData < Provider# Minimum delay between requests to avoid rate limiting (in seconds)MIN_REQUEST_INTERVAL = 1.0+ # time_series answers can hold years of daily rows and are slow to start, so+ # they get a 60 s read limit rather than the client's 20 s.+ # A retry after a timeout is not counted against the per-minute credits.+ HISTORY_READ_TIMEOUT = 60+# Pattern to detect plan upgrade errors in API responsesPLAN_UPGRADE_PATTERN = /available starting with (\w+)/i@@ -84,6 +89,7 @@ class Provider::TwelveData < Provider# Try to fetch the currency pair via the time_series API (consumes 1 credit) - this might not return anything as the API does not provide time series data for all possible currency pairsthrottle_requestresponse = client.get("#{base_url}/time_series") do |req|+ req.options.timeout = HISTORY_READ_TIMEOUTreq.params["symbol"] = "#{from}/#{to}"req.params["start_date"] = start_date.to_sreq.params["end_date"] = end_date.to_s@@ -99,6 +105,7 @@ class Provider::TwelveData < ProviderRails.logger.info("#{self.class.name}: Currency pair #{from}/#{to} not available, fetching via time_series/cross API")throttle_request(credits: 5)response = client.get("#{base_url}/time_series/cross") do |req|+ req.options.timeout = HISTORY_READ_TIMEOUTreq.params["base"] = fromreq.params["quote"] = toreq.params["start_date"] = start_date.to_s@@ -214,6 +221,7 @@ class Provider::TwelveData < Providerwith_provider_response dothrottle_requestresponse = client.get("#{base_url}/time_series") do |req|+ req.options.timeout = HISTORY_READ_TIMEOUTreq.params["symbol"] = symbolreq.params["mic_code"] = exchange_operating_micreq.params["start_date"] = start_date.to_s@@ -269,6 +277,9 @@ class Provider::TwelveData < 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.request(:retry, {max: 3,interval: 1.0,diff --git a/test/models/provider/alpha_vantage_test.rb b/test/models/provider/alpha_vantage_test.rbindex 55697e626a..1eb15f4ca7 100644--- a/test/models/provider/alpha_vantage_test.rb+++ b/test/models/provider/alpha_vantage_test.rb@@ -1,6 +1,8 @@require "test_helper"class Provider::AlphaVantageTest < ActiveSupport::TestCase+ include ProviderTestHelper+OVERVIEW_URL = "https://www.alphavantage.co/query".freezesetup do@@ -63,4 +65,45 @@ class Provider::AlphaVantageTest < ActiveSupport::TestCaseassert_requested :get, OVERVIEW_URL, query: hash_including("function" => "OVERVIEW"), times: 1assert_equal 26, store.read("alpha_vantage:daily:#{Date.current}")end++ test "client sets explicit open and read timeouts" do+ provider = Provider::AlphaVantage.new("test_api_key")+ options = provider.send(:client).options++ assert_equal 5, options.open_timeout+ assert_equal 20, options.timeout+ end++ test "a timed-out request returns a failed response with the provider's Error" do+ provider = Provider::AlphaVantage.new("test_api_key")+ provider.stubs(:throttle_request)+ Faraday::Retry::Middleware.any_instance.stubs(:sleep)+ search = stub_request(:get, "https://www.alphavantage.co/query")+ .with(query: hash_including("function" => "SYMBOL_SEARCH")).to_timeout+ errors = capture_transformed_errors(provider)++ response = provider.search_securities("TEST")++ assert_not response.success?+ assert_instance_of Provider::AlphaVantage::Error, response.error+ assert_requested search, times: 4+ assert_kind_of Faraday::ConnectionFailed, errors.last+ assert_kind_of Net::OpenTimeout, errors.last.wrapped_exception+ end++ test "a read timeout is retried and returns a failed response with the provider's Error" do+ provider = Provider::AlphaVantage.new("test_api_key")+ provider.stubs(:throttle_request)+ Faraday::Retry::Middleware.any_instance.stubs(:sleep)+ search = stub_request(:get, "https://www.alphavantage.co/query")+ .with(query: hash_including("function" => "SYMBOL_SEARCH")).to_raise(Net::ReadTimeout)+ errors = capture_transformed_errors(provider)++ response = provider.search_securities("TEST")++ assert_not response.success?+ assert_instance_of Provider::AlphaVantage::Error, response.error+ assert_requested search, times: 4+ assert_kind_of Faraday::TimeoutError, errors.last+ endenddiff --git a/test/models/provider/eodhd_test.rb b/test/models/provider/eodhd_test.rbindex b4646a15e6..135a71eff7 100644--- a/test/models/provider/eodhd_test.rb+++ b/test/models/provider/eodhd_test.rb@@ -1,6 +1,8 @@require "test_helper"class Provider::EodhdTest < ActiveSupport::TestCase+ include ProviderTestHelper+FUNDAMENTALS_URL = "https://eodhd.com/api/fundamentals/AAPL.US".freezesetup do@@ -588,6 +590,60 @@ class Provider::EodhdTest < ActiveSupport::TestCasestore&.delete(provider&.send(:daily_cache_key))end+ test "client sets explicit open and read timeouts" do+ options = @provider.send(:client).options++ assert_equal 5, options.open_timeout+ assert_equal 20, options.timeout+ end++ test "a timed-out request returns a failed response with the provider's Error" do+ @provider.stubs(:enforce_daily_limit!)+ @provider.stubs(:throttle_request)+ Faraday::Retry::Middleware.any_instance.stubs(:sleep)+ search = stub_request(:get, %r{\Ahttps://eodhd\.com/api/search/TEST}).to_timeout+ errors = capture_transformed_errors(@provider)++ response = @provider.search_securities("TEST")++ assert_not response.success?+ assert_instance_of Provider::Eodhd::Error, response.error+ assert_requested search, times: 4+ assert_kind_of Faraday::ConnectionFailed, errors.last+ assert_kind_of Net::OpenTimeout, errors.last.wrapped_exception+ end++ test "a read timeout is retried and returns a failed response with the provider's Error" do+ @provider.stubs(:enforce_daily_limit!)+ @provider.stubs(:throttle_request)+ Faraday::Retry::Middleware.any_instance.stubs(:sleep)+ search = stub_request(:get, %r{\Ahttps://eodhd\.com/api/search/TEST}).to_raise(Net::ReadTimeout)+ errors = capture_transformed_errors(@provider)++ response = @provider.search_securities("TEST")++ assert_not response.success?+ assert_instance_of Provider::Eodhd::Error, response.error+ assert_requested search, times: 4+ assert_kind_of Faraday::TimeoutError, errors.last+ end++ test "a fundamentals request gets a longer read timeout than the client default" do+ stub_quota_hook(@provider)+ stub_request(:get, FUNDAMENTALS_URL)+ .with(query: hash_including("fmt" => "json"))+ .to_return(status: 200, body: { "General" => { "Name" => "Apple Inc" } }.to_json)+ stub_request(:get, %r{\Ahttps://eodhd\.com/api/search/AAPL}).to_return(status: 200, body: [].to_json)+ timeouts = capture_request_timeouts(@provider)++ with_fresh_cache do+ assert @provider.fetch_security_info(symbol: "AAPL", exchange_operating_mic: "XNYS").success?+ end+ assert @provider.search_securities("AAPL").success?++ assert_equal [ 60, 20 ], timeouts+ end+private# The real client routes every HTTP attempt through count_request_attempt!;# these tests stub the client, so the hook is stubbed off the request pathdiff --git a/test/models/provider/mansa_test.rb b/test/models/provider/mansa_test.rbindex c3e65c8f4c..92be82ff13 100644--- a/test/models/provider/mansa_test.rb+++ b/test/models/provider/mansa_test.rb@@ -1,6 +1,8 @@require "test_helper"class Provider::MansaTest < ActiveSupport::TestCase+ include ProviderTestHelper+STOCK_URL = %r{\Ahttps://mansaapi\.com/api/v1/markets/exchanges/[^/]+/stocks/MTNN}.freezesetup do@@ -400,6 +402,40 @@ class Provider::MansaTest < ActiveSupport::TestCaseassert_equal 101, store.read("mansa:daily:#{Date.current}")end+ test "client sets explicit open and read timeouts" do+ options = @provider.send(:client).options++ assert_equal 5, options.open_timeout+ assert_equal 20, options.timeout+ end++ test "a timed-out request returns a failed response with the provider's Error" do+ Faraday::Retry::Middleware.any_instance.stubs(:sleep)+ search = stub_request(:get, %r{\Ahttps://mansaapi\.com/api/v1/markets/search}).to_timeout+ errors = capture_transformed_errors(@provider)++ response = @provider.search_securities("TEST")++ assert_not response.success?+ assert_instance_of Provider::Mansa::Error, response.error+ assert_requested search, times: 4+ assert_kind_of Faraday::ConnectionFailed, errors.last+ assert_kind_of Net::OpenTimeout, errors.last.wrapped_exception+ end++ test "a read timeout is retried and returns a failed response with the provider's Error" do+ Faraday::Retry::Middleware.any_instance.stubs(:sleep)+ search = stub_request(:get, %r{\Ahttps://mansaapi\.com/api/v1/markets/search}).to_raise(Net::ReadTimeout)+ errors = capture_transformed_errors(@provider)++ response = @provider.search_securities("TEST")++ assert_not response.success?+ assert_instance_of Provider::Mansa::Error, response.error+ assert_requested search, times: 4+ assert_kind_of Faraday::TimeoutError, errors.last+ end+privatedef stub_search_response(*listings)mock_response = mockdiff --git a/test/models/provider/mfapi_test.rb b/test/models/provider/mfapi_test.rbnew file mode 100644index 0000000000..d7797cfe79--- /dev/null+++ b/test/models/provider/mfapi_test.rb@@ -0,0 +1,44 @@+require "test_helper"++class Provider::MfapiTest < ActiveSupport::TestCase+ include ProviderTestHelper++ test "client sets explicit open and read timeouts" do+ provider = Provider::Mfapi.new+ options = provider.send(:client).options++ assert_equal 5, options.open_timeout+ assert_equal 20, options.timeout+ end++ test "a timed-out request returns a failed response with the provider's Error" do+ provider = Provider::Mfapi.new+ provider.stubs(:throttle_request)+ Faraday::Retry::Middleware.any_instance.stubs(:sleep)+ search = stub_request(:get, %r{\Ahttps://api\.mfapi\.in/mf/search}).to_timeout+ errors = capture_transformed_errors(provider)++ response = provider.search_securities("TEST")++ assert_not response.success?+ assert_instance_of Provider::Mfapi::Error, response.error+ assert_requested search, times: 4+ assert_kind_of Faraday::ConnectionFailed, errors.last+ assert_kind_of Net::OpenTimeout, errors.last.wrapped_exception+ end++ test "a read timeout is retried and returns a failed response with the provider's Error" do+ provider = Provider::Mfapi.new+ provider.stubs(:throttle_request)+ Faraday::Retry::Middleware.any_instance.stubs(:sleep)+ search = stub_request(:get, %r{\Ahttps://api\.mfapi\.in/mf/search}).to_raise(Net::ReadTimeout)+ errors = capture_transformed_errors(provider)++ response = provider.search_securities("TEST")++ assert_not response.success?+ assert_instance_of Provider::Mfapi::Error, response.error+ assert_requested search, times: 4+ assert_kind_of Faraday::TimeoutError, errors.last+ end+enddiff --git a/test/models/provider/tiingo_test.rb b/test/models/provider/tiingo_test.rbindex 719ccb1b99..01ff760107 100644--- a/test/models/provider/tiingo_test.rb+++ b/test/models/provider/tiingo_test.rb@@ -1,6 +1,8 @@require "test_helper"class Provider::TiingoTest < ActiveSupport::TestCase+ include ProviderTestHelper+setup do@provider = Provider::Tiingo.new("test_api_key")@provider.stubs(:throttle_request)@@ -284,4 +286,38 @@ class Provider::TiingoTest < ActiveSupport::TestCasestore&.delete("tiingo:symbol_count:#{month}")%w[AAPL MSFT].each { |symbol| store&.delete("tiingo:symbol:#{month}:#{symbol}") }end++ test "client sets explicit open and read timeouts" do+ options = @provider.send(:client).options++ assert_equal 5, options.open_timeout+ assert_equal 20, options.timeout+ end++ test "a timed-out request returns a failed response with the provider's Error" do+ Faraday::Retry::Middleware.any_instance.stubs(:sleep)+ search = stub_request(:get, %r{\Ahttps://api\.tiingo\.com/tiingo/utilities/search}).to_timeout+ errors = capture_transformed_errors(@provider)++ response = @provider.search_securities("TEST")++ assert_not response.success?+ assert_instance_of Provider::Tiingo::Error, response.error+ assert_requested search, times: 4+ assert_kind_of Faraday::ConnectionFailed, errors.last+ assert_kind_of Net::OpenTimeout, errors.last.wrapped_exception+ end++ test "a read timeout is retried and returns a failed response with the provider's Error" do+ Faraday::Retry::Middleware.any_instance.stubs(:sleep)+ search = stub_request(:get, %r{\Ahttps://api\.tiingo\.com/tiingo/utilities/search}).to_raise(Net::ReadTimeout)+ errors = capture_transformed_errors(@provider)++ response = @provider.search_securities("TEST")++ assert_not response.success?+ assert_instance_of Provider::Tiingo::Error, response.error+ assert_requested search, times: 4+ assert_kind_of Faraday::TimeoutError, errors.last+ endenddiff --git a/test/models/provider/twelve_data_test.rb b/test/models/provider/twelve_data_test.rbindex 198e78b7cc..5d3d36eb09 100644--- a/test/models/provider/twelve_data_test.rb+++ b/test/models/provider/twelve_data_test.rb@@ -1,6 +1,8 @@require "test_helper"class Provider::TwelveDataTest < ActiveSupport::TestCase+ include ProviderTestHelper+setup do@provider = Provider::TwelveData.new("test_api_key")end@@ -339,4 +341,61 @@ class Provider::TwelveDataTest < ActiveSupport::TestCasestore.delete(minute_key)endend++ test "client sets explicit open and read timeouts" do+ options = @provider.send(:client).options++ assert_equal 5, options.open_timeout+ assert_equal 20, options.timeout+ end++ test "a timed-out request returns a failed response with the provider's Error" do+ @provider.stubs(:throttle_request)+ Faraday::Retry::Middleware.any_instance.stubs(:sleep)+ search = stub_request(:get, %r{\Ahttps://api\.twelvedata\.com/symbol_search}).to_timeout+ errors = capture_transformed_errors(@provider)++ response = @provider.search_securities("TEST")++ assert_not response.success?+ assert_instance_of Provider::TwelveData::Error, response.error+ assert_requested search, times: 4+ assert_kind_of Faraday::ConnectionFailed, errors.last+ assert_kind_of Net::OpenTimeout, errors.last.wrapped_exception+ end++ test "a read timeout is retried and returns a failed response with the provider's Error" do+ @provider.stubs(:throttle_request)+ Faraday::Retry::Middleware.any_instance.stubs(:sleep)+ search = stub_request(:get, %r{\Ahttps://api\.twelvedata\.com/symbol_search}).to_raise(Net::ReadTimeout)+ errors = capture_transformed_errors(@provider)++ response = @provider.search_securities("TEST")++ assert_not response.success?+ assert_instance_of Provider::TwelveData::Error, response.error+ assert_requested search, times: 4+ assert_kind_of Faraday::TimeoutError, errors.last+ end++ test "time_series history requests get a longer read timeout than the client default" do+ @provider.stubs(:throttle_request)+ values = { "values" => [ { "datetime" => "2026-01-02", "close" => "1.5" } ], "meta" => { "currency" => "USD" } }.to_json+ stub_request(:get, %r{\Ahttps://api\.twelvedata\.com/time_series\?}).to_return(status: 200, body: values)+ # A pair time_series can't serve falls through to time_series/cross+ stub_request(:get, %r{\Ahttps://api\.twelvedata\.com/time_series\?})+ .with(query: hash_including("symbol" => "USD/ZZZ")).to_return(status: 200, body: {}.to_json)+ stub_request(:get, %r{\Ahttps://api\.twelvedata\.com/time_series/cross}).to_return(status: 200, body: values)+ stub_request(:get, %r{\Ahttps://api\.twelvedata\.com/symbol_search}).to_return(status: 200, body: { "data" => [] }.to_json)+ timeouts = capture_request_timeouts(@provider)++ @provider.fetch_security_prices(symbol: "AAPL", exchange_operating_mic: "XNAS", start_date: Date.new(2026, 1, 1), end_date: Date.new(2026, 1, 2))+ @provider.fetch_exchange_rates(from: "USD", to: "EUR", start_date: Date.new(2026, 1, 1), end_date: Date.new(2026, 1, 2))+ @provider.fetch_exchange_rates(from: "USD", to: "ZZZ", start_date: Date.new(2026, 1, 1), end_date: Date.new(2026, 1, 2))+ @provider.search_securities("AAPL")++ assert_requested :get, %r{\Ahttps://api\.twelvedata\.com/time_series/cross}, times: 1+ # prices, the EUR pair, the ZZZ pair and its cross fallback, then search+ assert_equal [ 60, 60, 60, 60, 20 ], timeouts+ endenddiff --git a/test/support/provider_test_helper.rb b/test/support/provider_test_helper.rbindex 3e3ddcead2..9e85927857 100644--- a/test/support/provider_test_helper.rb+++ b/test/support/provider_test_helper.rb@@ -14,4 +14,28 @@ module ProviderTestHelpererror: error)end++ # The errors a provider hands its default_error_transformer, so a test can+ # check which failure produced a failed response, not only that one did.+ def capture_transformed_errors(provider)+ seen = []+ provider.singleton_class.prepend(Module.new do+ define_method(:default_error_transformer) do |error|+ seen << error+ super(error)+ end+ end)+ seen+ end++ # The read timeout each request a provider sends carries, in order, so a test+ # can check a per-request override, not only the client's default.+ def capture_request_timeouts(provider)+ seen = []+ recorder = Class.new(Faraday::Middleware) do+ define_method(:on_request) { |env| seen << env.request.timeout }+ end+ provider.send(:client).builder.insert(0, recorder)+ seen+ endend