The personal finance app for everyone (by everyone)
Ruby
EODHD: count a fundamentals call as 10 requests against the daily limit (#5050)
arnaurodondev8fbc8f58410e
diff --git a/app/models/provider/eodhd.rb b/app/models/provider/eodhd.rbindex 1268378805..0f32345265 100644--- a/app/models/provider/eodhd.rb+++ b/app/models/provider/eodhd.rb@@ -13,6 +13,9 @@ class Provider::Eodhd < Provider# Maximum API calls per day (EODHD free/basic plans are very restrictive)MAX_REQUESTS_PER_DAY = 20+ # EODHD bills each fundamentals request as 10 API calls against the daily allowance+ FUNDAMENTALS_REQUEST_COST = 10+# 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@@ -175,7 +178,7 @@ class Provider::Eodhd < Providerfailed_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)- enforce_daily_limit!+ counted_on = enforce_daily_limit!(cost: FUNDAMENTALS_REQUEST_COST)throttle_requestbegin@@ -186,8 +189,19 @@ class Provider::Eodhd < Providerparsed = JSON.parse(response.body)check_api_error!(parsed)- rescue Faraday::ForbiddenError, Faraday::ResourceNotFound, Error+ rescue Faraday::ForbiddenError, Faraday::ResourceNotFound, Error => eRails.cache.write(failed_key, true, expires_in: 7.days)+ # EODHD documents that a lookup for an unknown ticker (404) is billed at its+ # full price, but not whether a request the plan does not include (403, e.g.+ # fundamentals on the free plan) is. Count it as one request rather than ten:+ # 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)+ 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 == 402raiseend@@ -320,12 +334,29 @@ class Provider::Eodhd < Provider# Enforces the daily rate limit. Raises RateLimitError if the limit is exhausted.# Uses atomic increment-then-check to avoid TOCTOU races between concurrent workers.- def enforce_daily_limit!- new_count = Rails.cache.increment(daily_cache_key, 1, expires_in: 24.hours).to_i+ # `cost` is how many API calls EODHD bills for the request. A refused request is+ # taken back off the count, so a refused fundamentals call leaves the rest for prices.+ # Between the increment and the refund a concurrent request sees the higher count and+ # may be refused although it would fit; that costs it one retry on the next sync.+ # Returns the counter key, so a later refund goes to the same day even after midnight.+ def enforce_daily_limit!(cost: 1)+ key = daily_cache_key+ new_count = Rails.cache.increment(key, cost, expires_in: 24.hours).to_iif new_count > max_requests_per_day+ refund_daily_requests(cost, key: key)raise RateLimitError, "EODHD daily rate limit of #{max_requests_per_day} requests exhausted"end++ key+ end++ # Takes requests back off the count they were added to. If the counter vanished in+ # the meantime (evicted, or the cache cleared), the decrement recreates it below zero;+ # put it back to zero so it does not hand out free requests.+ def refund_daily_requests(amount, key:)+ count = Rails.cache.decrement(key, amount, expires_in: 24.hours).to_i+ Rails.cache.increment(key, -count, expires_in: 24.hours) if count.negative?end# throttle_request and min_request_interval provided by RateLimitablediff --git a/test/models/provider/eodhd_test.rb b/test/models/provider/eodhd_test.rbindex 876c263bad..56f0abbf64 100644--- a/test/models/provider/eodhd_test.rb+++ b/test/models/provider/eodhd_test.rb@@ -227,6 +227,7 @@ class Provider::EodhdTest < ActiveSupport::TestCaseresult = @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 tenassert_equal 1, Rails.cache.read("eodhd:daily:#{Date.current}")end@@ -239,7 +240,154 @@ class Provider::EodhdTest < ActiveSupport::TestCasemock_client.expects(:get).times(3).raises(Faraday::ServerError.new("502")).then.raises(Faraday::TimeoutError.new("timeout")).then.returns(ok)- 2.times { assert_not @provider.fetch_security_info(symbol: "AAPL", exchange_operating_mic: "XNYS").success? }+ # 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?+ 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)+assert @provider.fetch_security_info(symbol: "AAPL", exchange_operating_mic: "XNYS").success?+ assert_equal 10, Rails.cache.read("eodhd:daily:#{Date.current}")+ 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_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+ 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?+ 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?+ 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"))++ assert_not @provider.fetch_security_info(symbol: "NOPE", exchange_operating_mic: "XNYS").success?+ assert_equal 10, Rails.cache.read("eodhd:daily:#{Date.current}")+ 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)++ assert_not @provider.fetch_security_info(symbol: "AAPL", exchange_operating_mic: "XNYS").success?+ assert_equal 10, Rails.cache.read("eodhd:daily:#{Date.current}")+ 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)+ end+ @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?+ 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 }))++ 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? }+ 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"+ 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?++ assert_equal 1, Rails.cache.read("eodhd:daily:2026-08-21")+ assert_equal 5, Rails.cache.read("eodhd:daily:2026-08-22")endend