Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Share the Yahoo Finance request budget across processes (#4925)

Mollyc0701daab6e4
diff --git a/app/models/provider/yahoo_finance.rb b/app/models/provider/yahoo_finance.rb
index 0bcd1c8eb8..84a00289d9 100644
--- a/app/models/provider/yahoo_finance.rb
+++ b/app/models/provider/yahoo_finance.rb
@@ -40,6 +40,22 @@ class Provider::YahooFinance < Provider
# Minimum delay between requests to avoid rate limiting (in seconds)
MIN_REQUEST_INTERVAL = 0.5
+ REQUEST_SLOT_CACHE_KEY = "yahoo_finance_request_slot"
+ # Longest a request queues for a shared request slot (in seconds)
+ MAX_REQUEST_WAIT = 30
+
+ # Runs a hook immediately before every HTTP attempt, including retries, so
+ # each one claims a shared request slot.
+ class BeforeEachAttempt < Faraday::Middleware
+ def initialize(app, hook)
+ super(app)
+ @hook = hook
+ end
+
+ def on_request(_env)
+ @hook.call
+ end
+ end
# Pool of modern browser user-agents to rotate through
# Based on https://github.com/ranaroussi/yfinance/pull/2277
@@ -980,6 +996,8 @@ class Provider::YahooFinance < Provider
exceptions: [ Faraday::ConnectionFailed, Faraday::TimeoutError ]
})
+ # After the retry middleware, so it runs for each attempt.
+ faraday.use BeforeEachAttempt, -> { wait_for_request_slot }
faraday.request :json
faraday.response :raise_error
@@ -1013,6 +1031,49 @@ class Provider::YahooFinance < Provider
ENV.fetch("YAHOO_FINANCE_MIN_REQUEST_INTERVAL", MIN_REQUEST_INTERVAL).to_f
end
+ def max_request_wait
+ ENV.fetch("YAHOO_FINANCE_MAX_REQUEST_WAIT", MAX_REQUEST_WAIT).to_f
+ end
+
+ # Every HTTP attempt, retries included, claims one min_request_interval-wide
+ # time slot in the shared cache (Redis in production), so provider
+ # instances, Sidekiq workers and web processes share one request budget
+ # instead of each pacing itself. A request queues for at most
+ # max_request_wait seconds. When every slot in that window is taken, the
+ # request does not claim one: it waits out the window and then goes, so
+ # callers beyond the window can burst together. That bounds latency at the
+ # cost of a strict budget. A cache that refuses the claim (Redis down)
+ # leaves the request unpaced after that single attempt.
+ def wait_for_request_slot
+ interval = min_request_interval
+ return unless interval.positive?
+
+ now = Time.current.to_f
+ current = (now / interval).floor
+ horizon = current + [ (max_request_wait / interval).ceil, 1 ].max
+ next_slot_key = "#{REQUEST_SLOT_CACHE_KEY}:next"
+ first = [ current, Rails.cache.read(next_slot_key).to_i ].max
+ slot = nil
+
+ (first...horizon).each do |candidate|
+ key = "#{REQUEST_SLOT_CACHE_KEY}:#{candidate}"
+ if Rails.cache.write(key, true, unless_exist: true, expires_in: (candidate * interval - now + interval + 1).seconds)
+ slot = candidate
+ break
+ end
+ return unless Rails.cache.exist?(key)
+ end
+
+ if slot
+ Rails.cache.write(next_slot_key, slot + 1, expires_in: (max_request_wait + interval + 1).seconds)
+ else
+ slot = horizon
+ end
+
+ wait = slot * interval - now
+ sleep(wait) if wait.positive?
+ end
+
def throttle_request
@last_request_time ||= Time.at(0)
elapsed = Time.current - @last_request_time
@@ -1124,6 +1185,7 @@ class Provider::YahooFinance < Provider
# Client for authentication requests (no error raising - fc.yahoo.com returns 404 but sets cookie)
def auth_client
@auth_client ||= Faraday.new(ssl: self.class.faraday_ssl_options) do |faraday|
+ faraday.use BeforeEachAttempt, -> { wait_for_request_slot }
faraday.headers["User-Agent"] = random_user_agent
faraday.headers["Accept"] = "*/*"
faraday.headers["Accept-Language"] = "en-US,en;q=0.9"
@@ -1144,6 +1206,7 @@ class Provider::YahooFinance < Provider
exceptions: [ Faraday::ConnectionFailed, Faraday::TimeoutError ]
})
+ faraday.use BeforeEachAttempt, -> { wait_for_request_slot }
faraday.request :json
faraday.response :raise_error
diff --git a/test/models/provider/yahoo_finance_test.rb b/test/models/provider/yahoo_finance_test.rb
index 04de7ab288..c6d2a3088b 100644
--- a/test/models/provider/yahoo_finance_test.rb
+++ b/test/models/provider/yahoo_finance_test.rb
@@ -998,6 +998,69 @@ class Provider::YahooFinanceTest < ActiveSupport::TestCase
assert second_elapsed >= (min_interval - 0.05), "Second request should wait at least #{min_interval - 0.05}s"
end
+ test "wait_for_request_slot shares the request budget across provider instances" do
+ other = Provider::YahooFinance.new
+ [ @provider, other ].each { |provider| provider.stubs(:min_request_interval).returns(0.5) }
+
+ travel_to Time.zone.at(1_800_000_000) do
+ @provider.expects(:sleep).never
+ @provider.send(:wait_for_request_slot)
+
+ other.expects(:sleep).with { |seconds| (seconds - 0.5).abs < 0.001 }
+ other.send(:wait_for_request_slot)
+ end
+ end
+
+ test "wait_for_request_slot queues behind a full horizon instead of bypassing the budget" do
+ @provider.stubs(:min_request_interval).returns(0.5)
+ @provider.stubs(:max_request_wait).returns(1.0)
+ @provider.expects(:sleep).with { |seconds| (seconds - 0.5).abs < 0.001 }.once
+ @provider.expects(:sleep).with { |seconds| (seconds - 1.0).abs < 0.001 }.once
+
+ travel_to Time.zone.at(1_800_000_000) do
+ 3.times { @provider.send(:wait_for_request_slot) }
+ end
+ end
+
+ test "wait_for_request_slot tries the cache once and does not wait when it refuses claims" do
+ refusing_cache = ActiveSupport::Cache::MemoryStore.new
+ refusing_cache.expects(:write).once.returns(false)
+ Rails.stubs(:cache).returns(refusing_cache)
+ @provider.stubs(:min_request_interval).returns(0.5)
+
+ travel_to Time.zone.at(1_800_000_000) do
+ @provider.expects(:sleep).never
+ @provider.send(:wait_for_request_slot)
+ end
+ end
+
+ test "every Yahoo client claims a request slot after its retry middleware" do
+ [ @provider.send(:client), @provider.send(:authenticated_client, "cookie") ].each do |connection|
+ handlers = connection.builder.handlers.map(&:klass)
+
+ assert_operator handlers.index(Provider::YahooFinance::BeforeEachAttempt), :>, handlers.index(Faraday::Retry::Middleware)
+ end
+ assert_includes @provider.send(:auth_client).builder.handlers.map(&:klass), Provider::YahooFinance::BeforeEachAttempt
+ end
+
+ test "BeforeEachAttempt runs again for each retried attempt" do
+ claims = 0
+ attempts = 0
+ connection = Faraday.new do |faraday|
+ faraday.request :retry, max: 2, interval: 0, retry_statuses: [ 429 ]
+ faraday.use Provider::YahooFinance::BeforeEachAttempt, -> { claims += 1 }
+ faraday.adapter :test do |stub|
+ stub.get("/quote") do
+ attempts += 1
+ attempts == 1 ? [ 429, {}, "" ] : [ 200, {}, "ok" ]
+ end
+ end
+ end
+
+ assert_equal 200, connection.get("/quote").status
+ assert_equal 2, claims
+ end
+
# ================================
# Configuration Tests
# ================================