Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Count every HTTP attempt against the market-data daily quotas (#5331)

Rajkamala2e6526795fc
diff --git a/app/models/provider/alpha_vantage.rb b/app/models/provider/alpha_vantage.rb
index f881e459bd..033c9cfbfa 100644
--- a/app/models/provider/alpha_vantage.rb
+++ b/app/models/provider/alpha_vantage.rb
@@ -74,8 +74,7 @@ class Provider::AlphaVantage < Provider
def usage
with_provider_response do
- day_key = "alpha_vantage:daily:#{Date.current}"
- used = Rails.cache.read(day_key, raw: true).to_i
+ used = Rails.cache.read(daily_cache_key, raw: true).to_i
UsageData.new(
used: used,
@@ -92,7 +91,6 @@ class Provider::AlphaVantage < Provider
def search_securities(symbol, country_code: nil, exchange_operating_mic: nil)
with_provider_response do
- throttle_request
response = client.get("#{base_url}/query") do |req|
req.params["function"] = "SYMBOL_SEARCH"
req.params["keywords"] = symbol
@@ -134,7 +132,6 @@ class Provider::AlphaVantage < Provider
with_provider_response do
av_symbol = to_av_symbol(symbol, exchange_operating_mic)
- throttle_request
response = client.get("#{base_url}/query") do |req|
req.params["function"] = "OVERVIEW"
req.params["symbol"] = av_symbol
@@ -175,7 +172,6 @@ class Provider::AlphaVantage < Provider
with_provider_response do
av_symbol = to_av_symbol(symbol, exchange_operating_mic)
- throttle_request
response = client.get("#{base_url}/query") do |req|
req.params["function"] = "TIME_SERIES_DAILY"
req.params["symbol"] = av_symbol
@@ -230,6 +226,9 @@ class Provider::AlphaVantage < Provider
backoff_factor: 2,
exceptions: Faraday::Retry::Middleware::DEFAULT_EXCEPTIONS + [ Faraday::ConnectionFailed ]
})
+ # After the retry middleware, so every attempt — not only the first —
+ # is throttled and counted against the daily request limit.
+ faraday.use RateLimitable::BeforeEachAttempt, ->(_env) { throttle_request }
faraday.request :json
faraday.response :raise_error
@@ -237,13 +236,15 @@ class Provider::AlphaVantage < Provider
end
end
- # Adds daily request counter on top of the interval throttle from RateLimitable.
+ # Adds the daily request counter on top of the interval throttle from
+ # RateLimitable. Runs through BeforeEachAttempt on every HTTP attempt, so a
+ # retried request is throttled and counted again, not only the initial one.
def throttle_request
super
# Global per-day request counter via cache (Redis).
# Atomic increment-then-check avoids the TOCTOU of read-check-increment.
- day_key = "alpha_vantage:daily:#{Date.current}"
+ day_key = daily_cache_key
new_count = Rails.cache.increment(day_key, 1, expires_in: 24.hours).to_i
if new_count > max_requests_per_day
@@ -252,6 +253,10 @@ class Provider::AlphaVantage < Provider
end
end
+ def daily_cache_key
+ "alpha_vantage:daily:#{Date.current}"
+ end
+
def max_requests_per_day
ENV.fetch("ALPHA_VANTAGE_MAX_REQUESTS_PER_DAY", MAX_REQUESTS_PER_DAY).to_i
end
diff --git a/app/models/provider/chimnie.rb b/app/models/provider/chimnie.rb
index c3fdea626a..b9c1de8750 100644
--- a/app/models/provider/chimnie.rb
+++ b/app/models/provider/chimnie.rb
@@ -23,19 +23,6 @@ class Provider::Chimnie < Provider
UPRN_FORMAT = /\A\d{1,12}\z/
- # Runs a hook immediately before every HTTP attempt, including retries, so
- # each one is throttled and counted against the monthly budget.
- class BeforeEachAttempt < Faraday::Middleware
- def initialize(app, hook)
- super(app)
- @hook = hook
- end
-
- def on_request(_env)
- @hook.call
- end
- end
-
def initialize(api_key)
@api_key = api_key # pipelock:ignore
end
@@ -145,7 +132,7 @@ class Provider::Chimnie < Provider
exceptions: Faraday::Retry::Middleware::DEFAULT_EXCEPTIONS + [ Faraday::ConnectionFailed, Faraday::TooManyRequestsError ]
})
# After the retry middleware, so it runs for each attempt.
- faraday.use BeforeEachAttempt, -> {
+ faraday.use RateLimitable::BeforeEachAttempt, ->(_env) {
throttle_request
record_monthly_request!
}
diff --git a/app/models/provider/eodhd.rb b/app/models/provider/eodhd.rb
index d0aba4231b..c66426a78e 100644
--- a/app/models/provider/eodhd.rb
+++ b/app/models/provider/eodhd.rb
@@ -141,9 +141,6 @@ class Provider::Eodhd < Provider
def search_securities(symbol, country_code: nil, exchange_operating_mic: nil)
with_provider_response do
- enforce_daily_limit!
- throttle_request
-
response = client.get("#{base_url}/api/search/#{CGI.escape(symbol)}") do |req|
req.params["api_token"] = api_key
req.params["fmt"] = "json"
@@ -190,10 +187,14 @@ class Provider::Eodhd < Provider
failed_key = "eodhd:fundamentals_failed:#{Digest::SHA256.hexdigest(api_key.to_s)[0, 8]}:#{ticker}"
raise Error, "Fundamentals for #{ticker} failed recently; retrying later" if Rails.cache.read(failed_key)
- counted_on = enforce_daily_limit!(cost: FUNDAMENTALS_REQUEST_COST)
- throttle_request
+ # Fundamentals are billed at 10 API calls, so each attempt — including
+ # retries — must reserve that cost. The hook registered on the client
+ # routes every attempt through this before it reaches EODHD.
+ @request_cost = FUNDAMENTALS_REQUEST_COST
begin
+ @last_counted_on = nil
+
response = client.get("#{base_url}/api/fundamentals/#{CGI.escape(ticker)}") do |req|
req.params["api_token"] = api_key
req.params["fmt"] = "json"
@@ -201,6 +202,10 @@ class Provider::Eodhd < Provider
parsed = JSON.parse(response.body)
check_api_error!(parsed)
+ rescue RateLimitError
+ # Our own quota refusal says nothing about the ticker, so it must not
+ # be remembered as a fundamentals failure.
+ raise
rescue Faraday::ForbiddenError, Faraday::ResourceNotFound, Error => e
Rails.cache.write(failed_key, true, expires_in: 7.days)
# EODHD documents that a lookup for an unknown ticker (404) is billed at its
@@ -209,12 +214,14 @@ class Provider::Eodhd < Provider
# under-counting a refused call is safer than refusing the day's prices.
# An error in a 200 answer (Error, from check_api_error!) was served, and
# EODHD bills failed lookups, so it keeps its full price.
- refund_daily_requests(FUNDAMENTALS_REQUEST_COST - 1, key: counted_on) if e.is_a?(Faraday::ForbiddenError)
+ refund_daily_requests(FUNDAMENTALS_REQUEST_COST - 1, key: last_counted_on) if e.is_a?(Faraday::ForbiddenError)
raise
rescue Faraday::ClientError => e
# EODHD answers 402 when the day's calls are used up and does not bill it
- refund_daily_requests(FUNDAMENTALS_REQUEST_COST, key: counted_on) if e.response_status == 402
+ refund_daily_requests(FUNDAMENTALS_REQUEST_COST, key: last_counted_on) if e.response_status == 402
raise
+ ensure
+ reset_request_cost!
end
general = parsed.dig("General") || {}
@@ -244,9 +251,6 @@ class Provider::Eodhd < Provider
def fetch_security_prices(symbol:, exchange_operating_mic: nil, start_date:, end_date:)
with_provider_response do
- enforce_daily_limit!
- throttle_request
-
ticker = eodhd_symbol(symbol, exchange_operating_mic)
response = client.get("#{base_url}/api/eod/#{CGI.escape(ticker)}") do |req|
@@ -304,6 +308,10 @@ class Provider::Eodhd < Provider
backoff_factor: 2,
exceptions: Faraday::Retry::Middleware::DEFAULT_EXCEPTIONS + [ Faraday::ConnectionFailed ]
})
+ # After the retry middleware, so every attempt — not only the first —
+ # is throttled and reserved against the daily request budget. The URL
+ # decides the billing cost: fundamentals are billed at ten API calls.
+ faraday.use RateLimitable::BeforeEachAttempt, ->(env) { count_request_attempt!(env.url) }
faraday.request :json
faraday.response :raise_error
@@ -344,6 +352,40 @@ class Provider::Eodhd < Provider
"eodhd:daily:#{Date.current}"
end
+ # Runs on every HTTP attempt through BeforeEachAttempt, so a retried request
+ # is throttled and reserved again. The billing cost comes from the request
+ # URL (fundamentals are billed at ten API calls), falling back to
+ # `@request_cost` for fake clients in tests that don't carry one. The last
+ # key reserved against is remembered so a refund lands on the day the
+ # attempt ran, even when midnight falls between the reservation and the
+ # failure.
+ def count_request_attempt!(url = nil)
+ # Check the budget first so an over-quota attempt fails fast instead of
+ # sleeping the full interval before being refused.
+ reserve_daily_limit!(cost: url ? billing_cost_for(url.to_s) : (@request_cost || 1))
+ throttle_request
+ end
+
+ def reserve_daily_limit!(cost: 1)
+ @last_counted_on = enforce_daily_limit!(cost: cost)
+ end
+
+ def last_counted_on
+ @last_counted_on || daily_cache_key
+ end
+
+ # Clears the per-request billing state after a request finishes, so a later
+ # plain request on this instance is not billed at a stale higher cost.
+ def reset_request_cost!
+ @request_cost = nil
+ @last_counted_on = nil
+ end
+
+ # EODHD bills a fundamentals request as 10 API calls; everything else is one.
+ def billing_cost_for(url)
+ url.to_s.include?("/api/fundamentals/") ? FUNDAMENTALS_REQUEST_COST : 1
+ end
+
# Enforces the daily rate limit. Raises RateLimitError if the limit is exhausted.
# Uses atomic increment-then-check to avoid TOCTOU races between concurrent workers.
# `cost` is how many API calls EODHD bills for the request. A refused request is
diff --git a/app/models/provider/mansa.rb b/app/models/provider/mansa.rb
index 5fa44b0fb4..9cb4b95411 100644
--- a/app/models/provider/mansa.rb
+++ b/app/models/provider/mansa.rb
@@ -115,9 +115,6 @@ class Provider::Mansa < Provider
mansa_exchange = mansa_exchange_for(exchange_operating_mic)
next [] if exchange_operating_mic.present? && mansa_exchange.nil?
- enforce_daily_limit!
- throttle_request
-
response = client.get("#{base_url}/api/v1/markets/search") do |req|
req.params["q"] = symbol
req.params["exchange"] = mansa_exchange if mansa_exchange
@@ -229,9 +226,6 @@ class Provider::Mansa < Provider
mansa_exchange = mansa_exchange_for(exchange_operating_mic)
raise InvalidSecurityPriceError, "Mansa does not support exchange #{exchange_operating_mic}" if mansa_exchange.nil?
- enforce_daily_limit!
- throttle_request
-
response = client.get("#{base_url}/api/v1/markets/exchanges/#{mansa_exchange}/stocks/#{CGI.escape(symbol)}")
parsed = JSON.parse(response.body)
@@ -263,6 +257,13 @@ class Provider::Mansa < Provider
backoff_factor: 2,
exceptions: Faraday::Retry::Middleware::DEFAULT_EXCEPTIONS + [ Faraday::ConnectionFailed ]
})
+ # After the retry middleware, so every attempt — not only the first —
+ # is counted against the daily request limit and throttled. The limit is
+ # checked first so an over-quota attempt fails fast instead of sleeping.
+ faraday.use RateLimitable::BeforeEachAttempt, ->(_env) {
+ enforce_daily_limit!
+ throttle_request
+ }
faraday.request :json
faraday.response :raise_error
@@ -274,6 +275,8 @@ class Provider::Mansa < Provider
"mansa:daily:#{Date.current}"
end
+ # Runs through BeforeEachAttempt on every HTTP attempt, so a retried
+ # request is counted again, not only the initial one.
def enforce_daily_limit!
new_count = Rails.cache.increment(daily_cache_key, 1, expires_in: 24.hours).to_i
diff --git a/app/models/provider/rate_limitable.rb b/app/models/provider/rate_limitable.rb
index 30c732d460..77630cb366 100644
--- a/app/models/provider/rate_limitable.rb
+++ b/app/models/provider/rate_limitable.rb
@@ -17,6 +17,22 @@
module Provider::RateLimitable
extend ActiveSupport::Concern
+ # Runs a hook immediately before every HTTP attempt, including retries, so
+ # each one can be throttled and counted against a request budget. Register it
+ # after the :retry middleware: the retry middleware re-invokes the downstream
+ # stack on each attempt, so a hook downstream of it sees every attempt, while
+ # a call made once before client.get only sees the initial request.
+ class BeforeEachAttempt < Faraday::Middleware
+ def initialize(app, hook)
+ super(app)
+ @hook = hook
+ end
+
+ def on_request(env)
+ @hook.call(env)
+ end
+ end
+
private
# Enforces a minimum interval between consecutive requests on this instance.
# Subclasses that need additional rate-limit layers (daily counters, hourly
diff --git a/test/models/provider/alpha_vantage_test.rb b/test/models/provider/alpha_vantage_test.rb
index e0a55a7357..55697e626a 100644
--- a/test/models/provider/alpha_vantage_test.rb
+++ b/test/models/provider/alpha_vantage_test.rb
@@ -1,6 +1,12 @@
require "test_helper"
class Provider::AlphaVantageTest < ActiveSupport::TestCase
+ OVERVIEW_URL = "https://www.alphavantage.co/query".freeze
+
+ setup do
+ @provider = Provider::AlphaVantage.new("test_api_key")
+ end
+
# The test environment caches in a null store, so the usage readers need a real
# RedisCacheStore to notice a counter they cannot read back. The per-run namespace
# keeps runs sharing one Redis from reading each other's counts.
@@ -19,4 +25,42 @@ class Provider::AlphaVantageTest < ActiveSupport::TestCase
ensure
store&.delete("alpha_vantage:daily:#{Date.current}")
end
+
+ test "every attempt of a request is counted against the daily limit, including retries" do
+ Rails.stubs(:cache).returns(ActiveSupport::Cache::MemoryStore.new)
+ @provider.stubs(:sleep)
+ Faraday::Retry::Middleware.any_instance.stubs(:sleep)
+
+ stub_request(:get, OVERVIEW_URL)
+ .with(query: hash_including("function" => "OVERVIEW"))
+ .to_raise(Faraday::TimeoutError).then
+ .to_raise(Faraday::TimeoutError).then
+ .to_return(status: 200, body: { "Name" => "Apple Inc", "Symbol" => "AAPL" }.to_json)
+
+ assert @provider.fetch_security_info(symbol: "AAPL", exchange_operating_mic: "XNYS").success?
+
+ assert_requested :get, OVERVIEW_URL, query: hash_including("function" => "OVERVIEW"), times: 3
+ assert_equal 3, Rails.cache.read("alpha_vantage:daily:#{Date.current}")
+ end
+
+ test "a retry that would exceed the daily limit is refused before reaching Alpha Vantage" do
+ store = ActiveSupport::Cache::MemoryStore.new
+ Rails.stubs(:cache).returns(store)
+ @provider.stubs(:sleep)
+ Faraday::Retry::Middleware.any_instance.stubs(:sleep)
+ store.write("alpha_vantage:daily:#{Date.current}", 24)
+
+ stub_request(:get, OVERVIEW_URL)
+ .with(query: hash_including("function" => "OVERVIEW"))
+ .to_raise(Faraday::TimeoutError)
+
+ result = @provider.fetch_security_info(symbol: "AAPL", exchange_operating_mic: "XNYS")
+
+ assert_not result.success?
+ assert_kind_of Provider::AlphaVantage::RateLimitError, result.error
+ # The first attempt is counted (24 -> 25) and reaches the wire; the retry is counted
+ # past the limit (25 -> 26) and refused before it
+ assert_requested :get, OVERVIEW_URL, query: hash_including("function" => "OVERVIEW"), times: 1
+ assert_equal 26, store.read("alpha_vantage:daily:#{Date.current}")
+ end
end
diff --git a/test/models/provider/eodhd_test.rb b/test/models/provider/eodhd_test.rb
index 4f61ec88c9..b4646a15e6 100644
--- a/test/models/provider/eodhd_test.rb
+++ b/test/models/provider/eodhd_test.rb
@@ -1,8 +1,11 @@
require "test_helper"
class Provider::EodhdTest < ActiveSupport::TestCase
+ FUNDAMENTALS_URL = "https://eodhd.com/api/fundamentals/AAPL.US".freeze
+
setup do
@provider = Provider::Eodhd.new("test_api_key")
+ stub_quota_hook(@provider)
end
test "preserves raw EODHD exchange code when no MIC mapping exists" do
@@ -292,177 +295,273 @@ class Provider::EodhdTest < ActiveSupport::TestCase
end
test "fetch_security_info does not retry a failed fundamentals lookup" do
- Rails.stubs(:cache).returns(ActiveSupport::Cache::MemoryStore.new)
- @provider.stubs(:throttle_request)
- @provider.stubs(:client).returns(mock_client = mock)
- mock_client.expects(:get).once.raises(Faraday::ForbiddenError.new("403"))
-
- 2.times do
- result = @provider.fetch_security_info(symbol: "AAPL", exchange_operating_mic: "XNYS")
- assert_not result.success?
+ with_fresh_cache do
+ @provider.unstub(:count_request_attempt!)
+ @provider.stubs(:client).returns(mock_client = mock)
+ mock_client.expects(:get).once.raises(Faraday::ForbiddenError.new("403"))
+
+ @provider.send(:reserve_daily_limit!, cost: Provider::Eodhd::FUNDAMENTALS_REQUEST_COST)
+ 2.times do
+ result = @provider.fetch_security_info(symbol: "AAPL", exchange_operating_mic: "XNYS")
+ assert_not result.success?
+ end
+ # The refused (403) call is counted as one request, not ten
+ assert_equal 1, Rails.cache.read("eodhd:daily:#{Date.current}")
end
- # The refused (403) call is counted as one request, not ten
- assert_equal 1, Rails.cache.read("eodhd:daily:#{Date.current}")
end
test "fetch_security_info retries after a transient failure" do
- Rails.stubs(:cache).returns(ActiveSupport::Cache::MemoryStore.new)
- @provider.stubs(:throttle_request)
- ok = mock
- ok.stubs(:body).returns({ "General" => { "Name" => "Apple Inc" } }.to_json)
- @provider.stubs(:client).returns(mock_client = mock)
- mock_client.expects(:get).times(3).raises(Faraday::ServerError.new("502"))
- .then.raises(Faraday::TimeoutError.new("timeout")).then.returns(ok)
-
- # Three fundamentals calls cost 30 requests, more than the free cap, so use a paid limit
- with_env_overrides("EODHD_MAX_REQUESTS_PER_DAY" => "100") do
- 2.times { assert_not @provider.fetch_security_info(symbol: "AAPL", exchange_operating_mic: "XNYS").success? }
- assert @provider.fetch_security_info(symbol: "AAPL", exchange_operating_mic: "XNYS").success?
+ with_fresh_cache do
+ ok = mock
+ ok.stubs(:body).returns({ "General" => { "Name" => "Apple Inc" } }.to_json)
+ @provider.stubs(:client).returns(mock_client = mock)
+ mock_client.expects(:get).times(3).raises(Faraday::ServerError.new("502"))
+ .then.raises(Faraday::TimeoutError.new("timeout")).then.returns(ok)
+
+ # Three fundamentals calls cost 30 requests, more than the free cap, so use a paid limit
+ with_env_overrides("EODHD_MAX_REQUESTS_PER_DAY" => "100") do
+ 2.times do
+ @provider.send(:reserve_daily_limit!, cost: Provider::Eodhd::FUNDAMENTALS_REQUEST_COST)
+ assert_not @provider.fetch_security_info(symbol: "AAPL", exchange_operating_mic: "XNYS").success?
+ end
+ @provider.send(:reserve_daily_limit!, cost: Provider::Eodhd::FUNDAMENTALS_REQUEST_COST)
+ assert @provider.fetch_security_info(symbol: "AAPL", exchange_operating_mic: "XNYS").success?
+ end
end
end
test "a fundamentals call counts as ten requests against the daily limit" do
- Rails.stubs(:cache).returns(ActiveSupport::Cache::MemoryStore.new)
- @provider.stubs(:throttle_request)
- ok = mock
- ok.stubs(:body).returns({ "General" => { "Name" => "Apple Inc" } }.to_json)
- @provider.stubs(:client).returns(mock_client = mock)
- mock_client.expects(:get).once.returns(ok)
+ with_fresh_cache do
+ ok = mock
+ ok.stubs(:body).returns({ "General" => { "Name" => "Apple Inc" } }.to_json)
+ @provider.stubs(:client).returns(mock_client = mock)
+ mock_client.expects(:get).once.returns(ok)
- assert @provider.fetch_security_info(symbol: "AAPL", exchange_operating_mic: "XNYS").success?
- assert_equal 10, Rails.cache.read("eodhd:daily:#{Date.current}")
+ @provider.send(:reserve_daily_limit!, cost: Provider::Eodhd::FUNDAMENTALS_REQUEST_COST)
+ assert @provider.fetch_security_info(symbol: "AAPL", exchange_operating_mic: "XNYS").success?
+ assert_equal 10, Rails.cache.read("eodhd:daily:#{Date.current}")
+ end
end
test "a fundamentals call is refused when fewer than ten requests remain" do
- Rails.stubs(:cache).returns(ActiveSupport::Cache::MemoryStore.new)
- Rails.cache.write("eodhd:daily:#{Date.current}", 15)
- @provider.stubs(:throttle_request)
- @provider.stubs(:client).returns(mock_client = mock)
- mock_client.expects(:get).never
+ with_fresh_cache do
+ Rails.cache.write("eodhd:daily:#{Date.current}", 15)
+ @provider.unstub(:count_request_attempt!)
- with_env_overrides("EODHD_MAX_REQUESTS_PER_DAY" => nil) do
- result = @provider.fetch_security_info(symbol: "AAPL", exchange_operating_mic: "XNYS")
+ with_env_overrides("EODHD_MAX_REQUESTS_PER_DAY" => nil) do
+ result = @provider.fetch_security_info(symbol: "AAPL", exchange_operating_mic: "XNYS")
- assert_not result.success?
- assert_kind_of Provider::Eodhd::RateLimitError, result.error
+ assert_not result.success?
+ assert_kind_of Provider::Eodhd::RateLimitError, result.error
+ end
+ assert_not_requested :get, FUNDAMENTALS_URL, query: hash_including("fmt" => "json")
end
end
test "a refused fundamentals call leaves the remaining requests for prices" do
- Rails.stubs(:cache).returns(ActiveSupport::Cache::MemoryStore.new)
- Rails.cache.write("eodhd:daily:#{Date.current}", 15)
- @provider.stubs(:throttle_request)
-
- with_env_overrides("EODHD_MAX_REQUESTS_PER_DAY" => nil) do
- assert_not @provider.fetch_security_info(symbol: "AAPL", exchange_operating_mic: "XNYS").success?
- assert_equal 15, Rails.cache.read("eodhd:daily:#{Date.current}")
-
- prices = mock
- prices.stubs(:body).returns([ { "date" => "2026-08-21", "close" => 1.0 } ].to_json)
- @provider.stubs(:client).returns(mock_client = mock)
- mock_client.expects(:get).once.returns(prices)
-
- assert @provider.fetch_security_prices(
- symbol: "AAPL", exchange_operating_mic: "XNYS",
- start_date: Date.new(2026, 8, 21), end_date: Date.new(2026, 8, 21)
- ).success?
+ with_fresh_cache do
+ Rails.cache.write("eodhd:daily:#{Date.current}", 15)
+ @provider.unstub(:count_request_attempt!)
+
+ with_env_overrides("EODHD_MAX_REQUESTS_PER_DAY" => nil) do
+ assert_not @provider.fetch_security_info(symbol: "AAPL", exchange_operating_mic: "XNYS").success?
+ assert_equal 15, Rails.cache.read("eodhd:daily:#{Date.current}")
+
+ prices = mock
+ prices.stubs(:body).returns([ { "date" => "2026-08-21", "close" => 1.0 } ].to_json)
+ @provider.stubs(:client).returns(mock_client = mock)
+ mock_client.expects(:get).once.returns(prices)
+ @provider.send(:reserve_daily_limit!)
+
+ assert @provider.fetch_security_prices(
+ symbol: "AAPL", exchange_operating_mic: "XNYS",
+ start_date: Date.new(2026, 8, 21), end_date: Date.new(2026, 8, 21)
+ ).success?
+ end
end
end
test "fundamentals refused by the plan do not use up the day's price requests" do
- Rails.stubs(:cache).returns(ActiveSupport::Cache::MemoryStore.new)
- @provider.stubs(:throttle_request)
- prices = mock
- prices.stubs(:body).returns([ { "date" => "2026-08-21", "close" => 1.0 } ].to_json)
- @provider.stubs(:client).returns(mock_client = mock)
- mock_client.stubs(:get).raises(Faraday::ForbiddenError.new("403")).then
- .raises(Faraday::ForbiddenError.new("403")).then.returns(prices)
-
- with_env_overrides("EODHD_MAX_REQUESTS_PER_DAY" => nil) do
- assert_not @provider.fetch_security_info(symbol: "AAPL", exchange_operating_mic: "XNYS").success?
- assert_not @provider.fetch_security_info(symbol: "MSFT", exchange_operating_mic: "XNYS").success?
- assert_equal 2, Rails.cache.read("eodhd:daily:#{Date.current}")
-
- assert @provider.fetch_security_prices(
- symbol: "AAPL", exchange_operating_mic: "XNYS",
- start_date: Date.new(2026, 8, 21), end_date: Date.new(2026, 8, 21)
- ).success?
+ with_fresh_cache do
+ prices = mock
+ prices.stubs(:body).returns([ { "date" => "2026-08-21", "close" => 1.0 } ].to_json)
+ @provider.stubs(:client).returns(mock_client = mock)
+ mock_client.stubs(:get).raises(Faraday::ForbiddenError.new("403")).then
+ .raises(Faraday::ForbiddenError.new("403")).then.returns(prices)
+
+ with_env_overrides("EODHD_MAX_REQUESTS_PER_DAY" => nil) do
+ 2.times do
+ @provider.send(:reserve_daily_limit!, cost: Provider::Eodhd::FUNDAMENTALS_REQUEST_COST)
+ end
+ assert_not @provider.fetch_security_info(symbol: "AAPL", exchange_operating_mic: "XNYS").success?
+ assert_not @provider.fetch_security_info(symbol: "MSFT", exchange_operating_mic: "XNYS").success?
+ assert_equal 2, Rails.cache.read("eodhd:daily:#{Date.current}")
+
+ @provider.send(:reserve_daily_limit!)
+ assert @provider.fetch_security_prices(
+ symbol: "AAPL", exchange_operating_mic: "XNYS",
+ start_date: Date.new(2026, 8, 21), end_date: Date.new(2026, 8, 21)
+ ).success?
+ end
end
end
test "a fundamentals lookup for an unknown ticker still counts as ten requests" do
- Rails.stubs(:cache).returns(ActiveSupport::Cache::MemoryStore.new)
- @provider.stubs(:throttle_request)
- @provider.stubs(:client).returns(mock_client = mock)
- mock_client.expects(:get).once.raises(Faraday::ResourceNotFound.new("404"))
+ with_fresh_cache do
+ @provider.stubs(:client).returns(mock_client = mock)
+ mock_client.expects(:get).once.raises(Faraday::ResourceNotFound.new("404"))
- assert_not @provider.fetch_security_info(symbol: "NOPE", exchange_operating_mic: "XNYS").success?
- assert_equal 10, Rails.cache.read("eodhd:daily:#{Date.current}")
+ @provider.send(:reserve_daily_limit!, cost: Provider::Eodhd::FUNDAMENTALS_REQUEST_COST)
+ assert_not @provider.fetch_security_info(symbol: "NOPE", exchange_operating_mic: "XNYS").success?
+ assert_equal 10, Rails.cache.read("eodhd:daily:#{Date.current}")
+ end
end
test "a fundamentals answer that carries an error still counts as ten requests" do
- Rails.stubs(:cache).returns(ActiveSupport::Cache::MemoryStore.new)
- @provider.stubs(:throttle_request)
- answered = mock
- answered.stubs(:body).returns({ "error" => "Ticker not found" }.to_json)
- @provider.stubs(:client).returns(mock_client = mock)
- mock_client.expects(:get).once.returns(answered)
+ with_fresh_cache do
+ answered = mock
+ answered.stubs(:body).returns({ "error" => "Ticker not found" }.to_json)
+ @provider.stubs(:client).returns(mock_client = mock)
+ mock_client.expects(:get).once.returns(answered)
- assert_not @provider.fetch_security_info(symbol: "AAPL", exchange_operating_mic: "XNYS").success?
- assert_equal 10, Rails.cache.read("eodhd:daily:#{Date.current}")
+ @provider.send(:reserve_daily_limit!, cost: Provider::Eodhd::FUNDAMENTALS_REQUEST_COST)
+ assert_not @provider.fetch_security_info(symbol: "AAPL", exchange_operating_mic: "XNYS").success?
+ assert_equal 10, Rails.cache.read("eodhd:daily:#{Date.current}")
+ end
end
test "taking a refused request back off the count never makes it negative" do
store = ActiveSupport::Cache::MemoryStore.new
- Rails.stubs(:cache).returns(store)
- key = "eodhd:daily:#{Date.current}"
- store.write(key, 15)
- # The counter is evicted (or the cache cleared) between the increment and the refund
- original_decrement = store.method(:decrement)
- store.define_singleton_method(:decrement) do |name, amount = 1, **options|
- delete(name)
- original_decrement.call(name, amount, **options)
+ with_fresh_cache(store) do
+ @provider.unstub(:count_request_attempt!)
+ key = "eodhd:daily:#{Date.current}"
+ store.write(key, 15)
+ # The counter is evicted (or the cache cleared) between the increment and the refund
+ original_decrement = store.method(:decrement)
+ store.define_singleton_method(:decrement) do |name, amount = 1, **options|
+ delete(name)
+ original_decrement.call(name, amount, **options)
+ end
+
+ with_env_overrides("EODHD_MAX_REQUESTS_PER_DAY" => nil) do
+ assert_not @provider.fetch_security_info(symbol: "AAPL", exchange_operating_mic: "XNYS").success?
+ end
+ assert_not_requested :get, FUNDAMENTALS_URL, query: hash_including("fmt" => "json")
+ assert_equal 0, store.read(key).to_i
end
- @provider.stubs(:throttle_request)
+ end
- with_env_overrides("EODHD_MAX_REQUESTS_PER_DAY" => nil) do
- assert_not @provider.fetch_security_info(symbol: "AAPL", exchange_operating_mic: "XNYS").success?
+ test "a fundamentals call refused with 402 for lack of calls is not counted" do
+ with_fresh_cache do
+ Rails.cache.write("eodhd:daily:#{Date.current}", 10)
+ @provider.stubs(:client).returns(mock_client = mock)
+ # Twice: a 402 leaves no "failed recently" marker, so the next lookup still asks EODHD
+ mock_client.expects(:get).twice.raises(Faraday::ClientError.new("402", { status: 402 }))
+
+ with_env_overrides("EODHD_MAX_REQUESTS_PER_DAY" => nil) do
+ 2.times do
+ @provider.send(:reserve_daily_limit!, cost: Provider::Eodhd::FUNDAMENTALS_REQUEST_COST)
+ assert_not @provider.fetch_security_info(symbol: "AAPL", exchange_operating_mic: "XNYS").success?
+ end
+ end
+ assert_equal 10, Rails.cache.read("eodhd:daily:#{Date.current}")
end
- assert_equal 0, store.read(key).to_i
end
- test "a fundamentals call refused with 402 for lack of calls is not counted" do
- Rails.stubs(:cache).returns(ActiveSupport::Cache::MemoryStore.new)
- Rails.cache.write("eodhd:daily:#{Date.current}", 10)
- @provider.stubs(:throttle_request)
- @provider.stubs(:client).returns(mock_client = mock)
- # Twice: a 402 leaves no "failed recently" marker, so the next lookup still asks EODHD
- mock_client.expects(:get).twice.raises(Faraday::ClientError.new("402", { status: 402 }))
+ test "a 403 that arrives after midnight is refunded to the day it was counted on" do
+ with_fresh_cache do
+ test_case = self
+ provider = @provider
+ client = Object.new
+ client.define_singleton_method(:get) do |*|
+ # The attempt is reserved on the day it starts, then midnight passes
+ provider.send(:reserve_daily_limit!, cost: Provider::Eodhd::FUNDAMENTALS_REQUEST_COST)
+ test_case.travel_to Time.zone.local(2026, 8, 22, 0, 0, 1)
+ # Price requests already counted on the new day
+ Rails.cache.write("eodhd:daily:2026-08-22", 5)
+ raise Faraday::ForbiddenError, "403"
+ end
+ @provider.stubs(:client).returns(client)
+
+ travel_to Time.zone.local(2026, 8, 21, 23, 59, 59)
+ assert_not @provider.fetch_security_info(symbol: "AAPL", exchange_operating_mic: "XNYS").success?
- with_env_overrides("EODHD_MAX_REQUESTS_PER_DAY" => nil) do
- 2.times { assert_not @provider.fetch_security_info(symbol: "AAPL", exchange_operating_mic: "XNYS").success? }
+ assert_equal 1, Rails.cache.read("eodhd:daily:2026-08-21")
+ assert_equal 5, Rails.cache.read("eodhd:daily:2026-08-22")
end
- assert_equal 10, Rails.cache.read("eodhd:daily:#{Date.current}")
end
- test "a 403 that arrives after midnight is refunded to the day it was counted on" do
- Rails.stubs(:cache).returns(ActiveSupport::Cache::MemoryStore.new)
- @provider.stubs(:throttle_request)
- test_case = self
- client = Object.new
- client.define_singleton_method(:get) do |*|
- test_case.travel_to Time.zone.local(2026, 8, 22, 0, 0, 1)
- # Price requests already counted on the new day
- Rails.cache.write("eodhd:daily:2026-08-22", 5)
- raise Faraday::ForbiddenError, "403"
+ test "every attempt of a fundamentals request is reserved against the daily limit, including retries" do
+ store = ActiveSupport::Cache::MemoryStore.new
+ with_fresh_cache(store) do
+ @provider.unstub(:count_request_attempt!)
+ Faraday::Retry::Middleware.any_instance.stubs(:sleep)
+ stub_request(:get, FUNDAMENTALS_URL)
+ .with(query: hash_including("fmt" => "json"))
+ .to_raise(Faraday::TimeoutError).then
+ .to_raise(Faraday::TimeoutError).then
+ .to_return(status: 200, body: { "General" => { "Name" => "Apple Inc" } }.to_json)
+
+ # Three attempts at ten calls each need a paid limit to fit
+ with_env_overrides("EODHD_MAX_REQUESTS_PER_DAY" => "100") do
+ assert @provider.fetch_security_info(symbol: "AAPL", exchange_operating_mic: "XNYS").success?
+ end
+
+ assert_requested :get, FUNDAMENTALS_URL, query: hash_including("fmt" => "json"), times: 3
+ assert_equal 30, store.read("eodhd:daily:#{Date.current}")
+ # The per-request state is cleared once the request finishes
+ assert_nil @provider.instance_variable_get(:@last_counted_on)
end
- @provider.stubs(:client).returns(client)
+ end
- travel_to Time.zone.local(2026, 8, 21, 23, 59, 59)
- assert_not @provider.fetch_security_info(symbol: "AAPL", exchange_operating_mic: "XNYS").success?
+ test "a retried fundamentals request that would exceed the daily limit is refused before reaching EODHD" do
+ store = ActiveSupport::Cache::MemoryStore.new
+ with_fresh_cache(store) do
+ store.write("eodhd:daily:#{Date.current}", 5)
+ @provider.unstub(:count_request_attempt!)
+ # The budget is checked before the interval throttle, so the refused retry
+ # never sleeps: only the first attempt is throttled.
+ @provider.expects(:throttle_request).once
+ Faraday::Retry::Middleware.any_instance.stubs(:sleep)
+ stub_request(:get, FUNDAMENTALS_URL)
+ .with(query: hash_including("fmt" => "json"))
+ .to_raise(Faraday::TimeoutError)
+
+ with_env_overrides("EODHD_MAX_REQUESTS_PER_DAY" => nil) do
+ result = @provider.fetch_security_info(symbol: "AAPL", exchange_operating_mic: "XNYS")
+
+ assert_not result.success?
+ assert_kind_of Provider::Eodhd::RateLimitError, result.error
+ end
+
+ # The first attempt is reserved (5 -> 15) and reaches the wire; the retry
+ # (15 -> 25) is refused before it and taken back off the count.
+ assert_requested :get, FUNDAMENTALS_URL, query: hash_including("fmt" => "json"), times: 1
+ assert_equal 15, store.read("eodhd:daily:#{Date.current}")
+
+ # Our own quota refusal says nothing about the ticker, so it is not remembered
+ # as a failed fundamentals lookup.
+ failed_key = "eodhd:fundamentals_failed:#{Digest::SHA256.hexdigest('test_api_key')[0, 8]}:AAPL.US"
+ assert_not store.exist?(failed_key)
+ end
+ end
- assert_equal 1, Rails.cache.read("eodhd:daily:2026-08-21")
- assert_equal 5, Rails.cache.read("eodhd:daily:2026-08-22")
+ test "search requests count one request per attempt" do
+ store = ActiveSupport::Cache::MemoryStore.new
+ with_fresh_cache(store) do
+ @provider.unstub(:count_request_attempt!)
+ body = [ { "Code" => "AAPL", "Name" => "Apple Inc.", "Exchange" => "US", "Country" => "USA", "Currency" => "USD" } ].to_json
+ provider = @provider
+ client = Object.new
+ client.define_singleton_method(:get) do |*|
+ provider.send(:count_request_attempt!)
+ Struct.new(:body).new(body)
+ end
+ @provider.stubs(:client).returns(client)
+
+ assert @provider.search_securities("AAPL").success?
+ assert_equal 1, store.read("eodhd:daily:#{Date.current}")
+ end
end
# The test environment caches in a null store, so the usage readers need a real
@@ -483,8 +582,24 @@ class Provider::EodhdTest < ActiveSupport::TestCase
provider = Provider::Eodhd.new("test_api_key")
2.times { provider.send(:enforce_daily_limit!) }
- assert_equal 2, provider.usage.data.used
+ # The two limit checks plus the usage request itself, which is counted like any other attempt.
+ assert_equal 3, provider.usage.data.used
ensure
store&.delete(provider&.send(:daily_cache_key))
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 path
+ # by default. Quota tests opt back in by calling the hook from their fake
+ # client, exactly where BeforeEachAttempt would run it.
+ def stub_quota_hook(provider)
+ provider.stubs(:count_request_attempt!)
+ provider.stubs(:throttle_request)
+ end
+
+ def with_fresh_cache(store = ActiveSupport::Cache::MemoryStore.new, &block)
+ Rails.stubs(:cache).returns(store)
+ yield
+ end
end
diff --git a/test/models/provider/mansa_test.rb b/test/models/provider/mansa_test.rb
index c7dbe3f150..c3e65c8f4c 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
+ STOCK_URL = %r{\Ahttps://mansaapi\.com/api/v1/markets/exchanges/[^/]+/stocks/MTNN}.freeze
+
setup do
@provider = Provider::Mansa.new("test_api_key")
@provider.stubs(:enforce_daily_limit!)
@@ -360,6 +362,44 @@ class Provider::MansaTest < ActiveSupport::TestCase
store&.delete(provider&.send(:daily_cache_key))
end
+ test "every attempt of a request is counted against the daily limit, including retries" do
+ Rails.stubs(:cache).returns(ActiveSupport::Cache::MemoryStore.new)
+ @provider.unstub(:enforce_daily_limit!)
+ Faraday::Retry::Middleware.any_instance.stubs(:sleep)
+
+ stub_request(:get, STOCK_URL)
+ .to_raise(Faraday::TimeoutError).then
+ .to_raise(Faraday::TimeoutError).then
+ .to_return(status: 200, body: { success: true, data: { ticker: "MTNN", price: 815 }, meta: { exchange: "NGX", currency: "NGN" } }.to_json)
+
+ assert @provider.fetch_security_price(symbol: "MTNN", exchange_operating_mic: "XNSA", date: Date.current).success?
+
+ assert_requested :get, STOCK_URL, times: 3
+ assert_equal 3, Rails.cache.read("mansa:daily:#{Date.current}")
+ end
+
+ test "a retry that would exceed the daily limit is refused before reaching Mansa" do
+ store = ActiveSupport::Cache::MemoryStore.new
+ Rails.stubs(:cache).returns(store)
+ @provider.unstub(:enforce_daily_limit!)
+ # The budget is checked before the interval throttle, so the refused retry
+ # never sleeps: only the first attempt is throttled.
+ @provider.expects(:throttle_request).once
+ Faraday::Retry::Middleware.any_instance.stubs(:sleep)
+ store.write("mansa:daily:#{Date.current}", 99)
+
+ stub_request(:get, STOCK_URL).to_raise(Faraday::TimeoutError)
+
+ result = @provider.fetch_security_price(symbol: "MTNN", exchange_operating_mic: "XNSA", date: Date.current)
+
+ assert_not result.success?
+ assert_kind_of Provider::Mansa::RateLimitError, result.error
+ # The first attempt is counted (99 -> 100) and reaches the wire; the retry is counted
+ # past the limit (100 -> 101) and refused before it
+ assert_requested :get, STOCK_URL, times: 1
+ assert_equal 101, store.read("mansa:daily:#{Date.current}")
+ end
+
private
def stub_search_response(*listings)
mock_response = mock