The personal finance app for everyone (by everyone)
Ruby
fix(lunchflow): keep balances current during rate limits (#3129)
Alessandro Pogliaghid18d853c8e3c
diff --git a/app/models/lunchflow_item/importer.rb b/app/models/lunchflow_item/importer.rbindex 516b1ca2a2..f3b4a91006 100644--- a/app/models/lunchflow_item/importer.rb+++ b/app/models/lunchflow_item/importer.rb@@ -23,7 +23,8 @@ class LunchflowItem::Importeraccounts_failed: 0,accounts_pruned: 0,transactions_imported: 0,- transactions_failed: 0+ transactions_failed: 0,+ balances_failed: 0}end@@ -94,11 +95,11 @@ class LunchflowItem::ImporterRails.logger.info "LunchflowItem::Importer - Updated #{accounts_updated} accounts, created #{accounts_created} new (#{accounts_failed} failed), pruned #{accounts_pruned}"- # Step 3: Fetch transactions only for linked accounts with active statustransactions_imported = 0transactions_failed = 0+ balances_failed = 0- lunchflow_item.lunchflow_accounts.joins(:account).merge(Account.visible).each do |lunchflow_account|+ lunchflow_item.lunchflow_accounts.joins(:account).includes(:account_provider).merge(Account.visible).each do |lunchflow_account|beginresult = fetch_and_store_transactions(lunchflow_account)if result[:success]@@ -111,18 +112,21 @@ class LunchflowItem::ImporterRails.logger.error "LunchflowItem::Importer - Failed to fetch/store transactions for account #{lunchflow_account.account_id}: #{e.message}"# Continue with other accounts even if one failsend++ balances_failed += 1 unless fetch_and_update_balance(lunchflow_account)end- Rails.logger.info "LunchflowItem::Importer - Completed import for item #{lunchflow_item.id}: #{accounts_updated} accounts updated, #{accounts_created} new accounts discovered, #{transactions_imported} transactions"+ Rails.logger.info "LunchflowItem::Importer - Completed import for item #{lunchflow_item.id}: #{accounts_updated} accounts updated, #{accounts_created} new accounts discovered, #{transactions_imported} transactions, #{balances_failed} balance failures"{- success: accounts_failed == 0 && transactions_failed == 0,+ success: accounts_failed == 0 && transactions_failed == 0 && balances_failed == 0,accounts_updated: accounts_updated,accounts_created: accounts_created,accounts_failed: accounts_failed,accounts_pruned: accounts_pruned,transactions_imported: transactions_imported,- transactions_failed: transactions_failed+ transactions_failed: transactions_failed,+ balances_failed: balances_failed}end@@ -350,26 +354,6 @@ class LunchflowItem::ImporterRails.logger.info "LunchflowItem::Importer - No transactions to store for account #{lunchflow_account.account_id}"end- # Fetch and update balance- begin- fetch_and_update_balance(lunchflow_account)- rescue => e- # Log but don't fail transaction import if balance fetch fails.- # current_balance stays nil, so the processor will skip the balance- # update for this account — capture the failure, because the sync- # still reports success and this is otherwise invisible to support.- DebugLogEntry.capture(- category: "provider_sync",- level: "warn",- message: "Balance fetch failed for account #{lunchflow_account.account_id}; keeping previous balance",- source: self.class.name,- provider_key: "lunchflow",- family: lunchflow_item.family,- metadata: { account_id: lunchflow_account.account_id, error_class: e.class.name, error: e.message }- )- Rails.logger.warn "LunchflowItem::Importer - Failed to update balance for account #{lunchflow_account.account_id}: #{e.message}"- end-# Fetch holdings for investment/crypto accountsbeginfetch_and_store_holdings(lunchflow_account)@@ -393,46 +377,51 @@ class LunchflowItem::Importerenddef fetch_and_update_balance(lunchflow_account)- begin- balance_data = lunchflow_provider.get_account_balance(lunchflow_account.account_id)+ balance_data = lunchflow_provider.get_account_balance(lunchflow_account.account_id)- # Validate response structure- unless balance_data.is_a?(Hash)- Rails.logger.error "LunchflowItem::Importer - Invalid balance_data format for account #{lunchflow_account.account_id}"- return- end+ return balance_failure(lunchflow_account, "Invalid balance response format") unless balance_data.is_a?(Hash)- if balance_data[:balance].present?- balance_info = balance_data[:balance]+ balance_info = balance_data[:balance]+ return balance_failure(lunchflow_account, "No balance data returned") if balance_info.blank?+ return balance_failure(lunchflow_account, "Invalid balance data format") unless balance_info.is_a?(Hash)+ return balance_failure(lunchflow_account, "No amount in balance data") if balance_info[:amount].blank?- # Validate balance info structure- unless balance_info.is_a?(Hash)- Rails.logger.error "LunchflowItem::Importer - Invalid balance info format for account #{lunchflow_account.account_id}"- return- end+ amount = BigDecimal(balance_info[:amount].to_s, exception: false)+ return balance_failure(lunchflow_account, "Invalid balance amount") unless amount&.finite?- # Only update if we have a valid amount- if balance_info[:amount].present?- lunchflow_account.update!(- current_balance: balance_info[:amount],- currency: balance_info[:currency].presence || lunchflow_account.currency- )- else- Rails.logger.warn "LunchflowItem::Importer - No amount in balance data for account #{lunchflow_account.account_id}"- end- else- Rails.logger.warn "LunchflowItem::Importer - No balance data returned for account #{lunchflow_account.account_id}"- end- rescue Provider::Lunchflow::LunchflowError => e- Rails.logger.error "LunchflowItem::Importer - Lunchflow API error fetching balance for account #{lunchflow_account.id}: #{e.message}"- # Don't fail if balance fetch fails- rescue ActiveRecord::RecordInvalid => e- Rails.logger.error "LunchflowItem::Importer - Failed to save balance for account #{lunchflow_account.id}: #{e.message}"- # Don't fail if balance save fails- rescue => e- Rails.logger.error "LunchflowItem::Importer - Unexpected error updating balance for account #{lunchflow_account.id}: #{e.class} - #{e.message}"- # Don't fail if balance update fails+ lunchflow_account.update!(+ current_balance: amount,+ currency: balance_info[:currency].presence || lunchflow_account.currency+ )+ true+ rescue => e+ balance_failure(lunchflow_account, "Balance fetch failed", error: e)+ end++ def balance_failure(lunchflow_account, reason, error: nil)+ message = "#{reason} for account #{lunchflow_account.account_id}; keeping previous Sure account balance"+ metadata = { account_id: lunchflow_account.account_id }+ if error+ metadata[:error_class] = error.class.name+ metadata[:error] = error.message+ metadata[:error_type] = error.error_type if error.respond_to?(:error_type)end++ DebugLogEntry.capture(+ category: "provider_sync",+ level: "warn",+ message: message,+ source: self.class.name,+ provider_key: "lunchflow",+ family: lunchflow_item.family,+ account_provider: lunchflow_account.account_provider,+ metadata: metadata+ )+ Rails.logger.warn "LunchflowItem::Importer - #{message}#{": #{error.message}" if error}"+ false+ rescue => e+ Rails.logger.error "LunchflowItem::Importer - Failed to capture balance diagnostic: #{e.class} - #{e.message}"+ falseenddef fetch_and_store_holdings(lunchflow_account)diff --git a/app/models/provider/lunchflow.rb b/app/models/provider/lunchflow.rbindex f849bc5fd5..1c4d2a973c 100644--- a/app/models/provider/lunchflow.rb+++ b/app/models/provider/lunchflow.rb@@ -5,6 +5,13 @@ class Provider::Lunchflowheaders "User-Agent" => "Sure Finance Lunch Flow Client"default_options.merge!({ timeout: 120 }.merge(httparty_ssl_options))+ MAX_RETRIES = 2+ MAX_RATE_LIMIT_RETRIES = 1+ INITIAL_RETRY_DELAY = 2+ MAX_RETRY_DELAY = 60+ DEFAULT_RATE_LIMIT_DELAY = 60+ NETWORK_ERRORS = Provider::HttpTransport::TRANSPORT_ERRORS+attr_reader :api_key, :base_urldef initialize(api_key, base_url: "https://lunchflow.app/api/v1")@@ -15,18 +22,7 @@ class Provider::Lunchflow# Get all accounts# Returns: { accounts: [...], total: N }def get_accounts- response = self.class.get(- "#{@base_url}/accounts",- headers: auth_headers- )-- handle_response(response)- rescue SocketError, Net::OpenTimeout, Net::ReadTimeout => e- Rails.logger.error "Lunch Flow API: GET /accounts failed: #{e.class}: #{e.message}"- raise LunchflowError.new("Exception during GET request: #{e.message}", :request_failed)- rescue => e- Rails.logger.error "Lunch Flow API: Unexpected error during GET /accounts: #{e.class}: #{e.message}"- raise LunchflowError.new("Exception during GET request: #{e.message}", :request_failed)+ get("/accounts")end# Get transactions for a specific account@@ -50,18 +46,7 @@ class Provider::Lunchflowpath = "/accounts/#{ERB::Util.url_encode(account_id.to_s)}/transactions"path += "?#{URI.encode_www_form(query_params)}" unless query_params.empty?- response = self.class.get(- "#{@base_url}#{path}",- headers: auth_headers- )-- handle_response(response)- rescue SocketError, Net::OpenTimeout, Net::ReadTimeout => e- Rails.logger.error "Lunch Flow API: GET #{path} failed: #{e.class}: #{e.message}"- raise LunchflowError.new("Exception during GET request: #{e.message}", :request_failed)- rescue => e- Rails.logger.error "Lunch Flow API: Unexpected error during GET #{path}: #{e.class}: #{e.message}"- raise LunchflowError.new("Exception during GET request: #{e.message}", :request_failed)+ get(path)end# Get balance for a specific account@@ -69,18 +54,7 @@ class Provider::Lunchflowdef get_account_balance(account_id)path = "/accounts/#{ERB::Util.url_encode(account_id.to_s)}/balance"- response = self.class.get(- "#{@base_url}#{path}",- headers: auth_headers- )-- handle_response(response)- rescue SocketError, Net::OpenTimeout, Net::ReadTimeout => e- Rails.logger.error "Lunch Flow API: GET #{path} failed: #{e.class}: #{e.message}"- raise LunchflowError.new("Exception during GET request: #{e.message}", :request_failed)- rescue => e- Rails.logger.error "Lunch Flow API: Unexpected error during GET #{path}: #{e.class}: #{e.message}"- raise LunchflowError.new("Exception during GET request: #{e.message}", :request_failed)+ get(path)end# Get holdings for a specific account (investment accounts only)@@ -89,27 +63,28 @@ class Provider::Lunchflowdef get_account_holdings(account_id)path = "/accounts/#{ERB::Util.url_encode(account_id.to_s)}/holdings"- response = self.class.get(- "#{@base_url}#{path}",- headers: auth_headers- )-- # Handle 501 specially - indicates holdings not supported for this account- if response.code == 501- return { holdings_not_supported: true }- end-- handle_response(response)- rescue SocketError, Net::OpenTimeout, Net::ReadTimeout => e- Rails.logger.error "Lunch Flow API: GET #{path} failed: #{e.class}: #{e.message}"- raise LunchflowError.new("Exception during GET request: #{e.message}", :request_failed)- rescue => e- Rails.logger.error "Lunch Flow API: Unexpected error during GET #{path}: #{e.class}: #{e.message}"- raise LunchflowError.new("Exception during GET request: #{e.message}", :request_failed)+ get(path, holdings_not_supported: true)endprivate+ def get(path, holdings_not_supported: false)+ operation_name = "GET #{path}"++ with_retries(operation_name) do+ response = self.class.get(+ "#{base_url}#{path}",+ headers: auth_headers+ )++ if holdings_not_supported && response.code == 501+ { holdings_not_supported: true }+ else+ handle_response(response)+ end+ end+ end+def auth_headers{"x-api-key" => api_key,@@ -123,28 +98,155 @@ class Provider::Lunchflowwhen 200JSON.parse(response.body, symbolize_names: true)when 400- Rails.logger.error "Lunch Flow API: Bad request - #{response.body}"- raise LunchflowError.new("Bad request to Lunch Flow API: #{response.body}", :bad_request)+ raise LunchflowError.new("Bad request to Lunch Flow API: #{response.body}", :bad_request, status: response.code)when 401- raise LunchflowError.new("Invalid API key", :unauthorized)+ raise LunchflowError.new("Invalid API key", :unauthorized, status: response.code)when 403- raise LunchflowError.new("Access forbidden - check your API key permissions", :access_forbidden)+ raise LunchflowError.new("Access forbidden - check your API key permissions", :access_forbidden, status: response.code)when 404- raise LunchflowError.new("Resource not found", :not_found)+ raise LunchflowError.new("Resource not found", :not_found, status: response.code)when 429- raise LunchflowError.new("Rate limit exceeded. Please try again later.", :rate_limited)+ raise rate_limit_error(response)else- Rails.logger.error "Lunch Flow API: Unexpected response - Code: #{response.code}, Body: #{response.body}"- raise LunchflowError.new("Failed to fetch data: #{response.code} #{response.message} - #{response.body}", :fetch_failed)+ raise rate_limit_error(response) if rate_limited_response?(response)++ error_type = response.code.in?(500..599) ? :server_error : :fetch_failed+ raise LunchflowError.new(+ "Failed to fetch data: #{response.code} #{response.message} - #{response.body}",+ error_type,+ status: response.code+ )endend+ def with_retries(operation_name, max_retries: MAX_RETRIES)+ retries = 0++ begin+ yield+ rescue => original_error+ error = normalize_request_error(original_error, operation_name)+ unless retryable_error?(error, original_error)+ capture_terminal_error(operation_name, error, original_error)+ raise error+ end++ retry_limit = error.error_type == :rate_limited ? MAX_RATE_LIMIT_RETRIES : max_retries+ if retries >= retry_limit+ capture_terminal_error(operation_name, error, original_error, retries:, retry_limit:)+ raise error+ end++ retries += 1+ delay = retry_delay(error, retries)+ DebugLogEntry.capture(+ category: "provider_sync",+ level: "warn",+ message: "Lunch Flow API request will be retried",+ source: self.class.name,+ provider_key: "lunchflow",+ metadata: {+ operation: operation_name,+ error_type: error.error_type,+ error_class: original_error.class.name,+ retry_attempt: retries,+ retry_limit: retry_limit,+ retry_delay: delay+ }+ )+ Rails.logger.warn(+ "Lunch Flow API: #{operation_name} failed (retry #{retries}/#{retry_limit}): " \+ "#{error.error_type}. Retrying in #{delay}s..."+ )+ sleep(delay) if delay.positive?+ retry+ end+ end++ def normalize_request_error(error, operation_name)+ return error if error.is_a?(LunchflowError)++ if NETWORK_ERRORS.any? { |error_class| error.is_a?(error_class) }+ return LunchflowError.new("#{operation_name} failed: #{error.message}", :request_failed)+ end++ LunchflowError.new("Exception during #{operation_name}: #{error.message}", :request_failed)+ end++ def capture_terminal_error(operation_name, error, original_error, retries: nil, retry_limit: nil)+ DebugLogEntry.capture(+ category: "provider_sync",+ level: "error",+ message: "Lunch Flow API request failed",+ source: self.class.name,+ provider_key: "lunchflow",+ metadata: {+ operation: operation_name,+ status: error.status,+ error_type: error.error_type,+ error_class: original_error.class.name,+ retry_attempts: retries,+ retry_limit: retry_limit+ }+ )+ end++ def retryable_error?(error, original_error)+ error.error_type.in?([ :rate_limited, :server_error ]) ||+ NETWORK_ERRORS.any? { |error_class| original_error.is_a?(error_class) }+ end++ def retry_delay(error, retry_count)+ return error.retry_after || DEFAULT_RATE_LIMIT_DELAY if error.error_type == :rate_limited++ base_delay = INITIAL_RETRY_DELAY * (2 ** (retry_count - 1))+ jitter = base_delay * rand * 0.25+ [ base_delay + jitter, MAX_RETRY_DELAY ].min+ end++ def rate_limited_response?(response)+ body = parsed_response_body(response)+ body["error"].to_s.match?(/rate.?limit/i) ||+ body["message"].to_s.match?(/(?:429|rate.?limit)/i) ||+ response.body.to_s.match?(/(?:GCRateLimited|429[^\n]*rate limit|rate limit exceeded)/i)+ end++ def rate_limit_error(response)+ body = parsed_response_body(response)+ message = body["message"].presence || "Rate limit exceeded. Please try again later."+ LunchflowError.new(+ message,+ :rate_limited,+ retry_after: retry_after_seconds(response, message),+ status: response.code+ )+ end++ def parsed_response_body(response)+ parsed_body = JSON.parse(response.body.to_s)+ parsed_body.is_a?(Hash) ? parsed_body : {}+ rescue JSON::ParserError+ {}+ end++ def retry_after_seconds(response, message)+ headers = response.headers if response.respond_to?(:headers)+ header = headers["retry-after"] if headers+ header_seconds = Float(header, exception: false)+ return [ header_seconds, MAX_RETRY_DELAY ].min if header_seconds&.positive?++ match = message.to_s.match(/try again in\s+(\d+(?:\.\d+)?)\s*seconds?/i)+ match ? [ match[1].to_f, MAX_RETRY_DELAY ].min : nil+ end+class LunchflowError < StandardError- attr_reader :error_type+ attr_reader :error_type, :retry_after, :status- def initialize(message, error_type = :unknown)+ def initialize(message, error_type = :unknown, retry_after: nil, status: nil)super(message)@error_type = error_type+ @retry_after = retry_after+ @status = statusendendenddiff --git a/test/models/lunchflow_item/importer_balance_test.rb b/test/models/lunchflow_item/importer_balance_test.rbnew file mode 100644index 0000000000..e62b4ff654--- /dev/null+++ b/test/models/lunchflow_item/importer_balance_test.rb@@ -0,0 +1,78 @@+require "test_helper"++class LunchflowItem::ImporterBalanceTest < ActiveSupport::TestCase+ setup do+ @family = families(:dylan_family)+ @item = LunchflowItem.create!(+ family: @family,+ name: "Balance isolation test",+ api_key: "test_key_123",+ status: :good+ )+ @lunchflow_account = @item.lunchflow_accounts.create!(+ account_id: "acct-balance",+ name: "Linked checking",+ currency: "EUR"+ )+ @account = @family.accounts.create!(+ name: "Linked checking",+ balance: 10,+ currency: "EUR",+ accountable: Depository.new(subtype: "checking")+ )+ AccountProvider.create!(account: @account, provider: @lunchflow_account)++ @provider = mock("lunchflow_provider")+ @provider.stubs(:get_accounts).returns(+ accounts: [+ {+ id: @lunchflow_account.account_id,+ name: "Linked checking",+ currency: "EUR",+ status: "ACTIVE"+ }+ ]+ )+ @importer = LunchflowItem::Importer.new(@item, lunchflow_provider: @provider)+ end++ test "refreshes balance when transaction fetch is rate limited" do+ error = Provider::Lunchflow::LunchflowError.new("Bank data is temporarily unavailable", :rate_limited)+ @provider.expects(:get_account_transactions).raises(error)+ @provider.expects(:get_account_balance).with(@lunchflow_account.account_id).returns(+ balance: { amount: "123.45", currency: "EUR" }+ )++ result = @importer.import++ assert_equal 1, result[:transactions_failed]+ assert_equal 0, result[:balances_failed]+ assert_not result[:success]+ assert_equal BigDecimal("123.45"), @lunchflow_account.reload.current_balance+ end++ test "reports balance failure without suppressing a successful transaction fetch" do+ @provider.expects(:get_account_transactions).returns(transactions: [])+ @provider.expects(:get_account_balance)+ .with(@lunchflow_account.account_id)+ .raises(Provider::Lunchflow::LunchflowError.new("temporarily unavailable", :server_error))++ result = @importer.import++ assert_equal 0, result[:transactions_failed]+ assert_equal 1, result[:balances_failed]+ assert_not result[:success]+ assert_equal BigDecimal("10"), @account.reload.balance+ end++ test "rejects invalid and non-finite balance amounts" do+ @lunchflow_account.update!(current_balance: BigDecimal("10"))++ [ "invalid", "NaN", "Infinity" ].each do |amount|+ @provider.expects(:get_account_balance).returns(balance: { amount: amount, currency: "EUR" })++ assert_not @importer.send(:fetch_and_update_balance, @lunchflow_account)+ assert_equal BigDecimal("10"), @lunchflow_account.reload.current_balance+ end+ end+enddiff --git a/test/models/provider/lunchflow_test.rb b/test/models/provider/lunchflow_test.rbnew file mode 100644index 0000000000..a1edb76a88--- /dev/null+++ b/test/models/provider/lunchflow_test.rb@@ -0,0 +1,153 @@+require "test_helper"++class Provider::LunchflowTest < ActiveSupport::TestCase+ setup do+ @provider = Provider::Lunchflow.new("test_key", base_url: "https://www.lunchflow.app/api/v1")+ end++ test "retries a wrapped GoCardless rate limit and preserves its type" do+ rate_limited = response(+ 503,+ {+ error: "GCRateLimited",+ message: "Bank data is temporarily unavailable. This usually resolves within a minute."+ }.to_json,+ "Service Unavailable"+ )+ success = response(200, { transactions: [] }.to_json, "OK")++ Provider::Lunchflow.expects(:get).times(2).returns(rate_limited, success)+ @provider.expects(:sleep).with(Provider::Lunchflow::DEFAULT_RATE_LIMIT_DELAY).once++ result = assert_difference -> { DebugLogEntry.with_provider_key("lunchflow").count }, 1 do+ @provider.get_account_transactions("acct-1")+ end++ assert_equal({ transactions: [] }, result)+ entry = DebugLogEntry.with_provider_key("lunchflow").recent.first+ assert_equal "rate_limited", entry.metadata["error_type"]+ assert_equal 1, entry.metadata["retry_attempt"]+ assert_equal Provider::Lunchflow::DEFAULT_RATE_LIMIT_DELAY, entry.metadata["retry_delay"]+ end++ test "uses the retry delay from a wrapped upstream 429 message" do+ rate_limited = response(+ 500,+ {+ error: "ProviderError",+ message: "API request failed (429 - Rate limit exceeded). Please try again in 7 seconds."+ }.to_json,+ "Internal Server Error"+ )+ success = response(200, { balance: { amount: "10.00", currency: "EUR" } }.to_json, "OK")++ Provider::Lunchflow.expects(:get).times(2).returns(rate_limited, success)+ @provider.expects(:sleep).with(7.0).once++ assert_equal "10.00", @provider.get_account_balance("acct-1").dig(:balance, :amount)+ end++ test "uses a bounded Retry-After header for a direct 429" do+ rate_limited = response(+ 429,+ { error: "RateLimited" }.to_json,+ "Too Many Requests",+ headers: { "retry-after" => "120" }+ )+ success = response(200, { transactions: [] }.to_json, "OK")++ Provider::Lunchflow.expects(:get).times(2).returns(rate_limited, success)+ @provider.expects(:sleep).with(Provider::Lunchflow::MAX_RETRY_DELAY).once++ assert_equal({ transactions: [] }, @provider.get_account_transactions("acct-1"))+ end++ test "retries transient server errors with exponential backoff" do+ unavailable = response(502, { error: "BadGateway" }.to_json, "Bad Gateway")+ success = response(200, { accounts: [] }.to_json, "OK")++ Provider::Lunchflow.expects(:get).times(2).returns(unavailable, success)+ @provider.stubs(:rand).returns(0)+ @provider.expects(:sleep).with(Provider::Lunchflow::INITIAL_RETRY_DELAY).once++ assert_equal({ accounts: [] }, @provider.get_accounts)+ end++ test "retries server errors with non-object JSON bodies" do+ unavailable = response(502, [].to_json, "Bad Gateway")+ success = response(200, { accounts: [] }.to_json, "OK")++ Provider::Lunchflow.expects(:get).times(2).returns(unavailable, success)+ @provider.stubs(:rand).returns(0)+ @provider.expects(:sleep).with(Provider::Lunchflow::INITIAL_RETRY_DELAY).once++ assert_equal({ accounts: [] }, @provider.get_accounts)+ end++ test "retries transient network errors" do+ success = response(200, { accounts: [] }.to_json, "OK")++ Provider::Lunchflow.expects(:get)+ .times(2)+ .raises(Net::ReadTimeout.new("timed out"))+ .then+ .returns(success)+ @provider.stubs(:rand).returns(0)+ @provider.expects(:sleep).with(Provider::Lunchflow::INITIAL_RETRY_DELAY).once++ assert_equal({ accounts: [] }, @provider.get_accounts)+ end++ test "raises the typed rate limit error after retries are exhausted" do+ rate_limited = response(+ 503,+ { error: "GCRateLimited", message: "Bank data is temporarily unavailable." }.to_json,+ "Service Unavailable"+ )++ Provider::Lunchflow.expects(:get).times(Provider::Lunchflow::MAX_RATE_LIMIT_RETRIES + 1).returns(rate_limited)+ @provider.stubs(:sleep)++ error = nil+ assert_difference -> { DebugLogEntry.with_provider_key("lunchflow").count }, 2 do+ error = assert_raises(Provider::Lunchflow::LunchflowError) do+ @provider.get_accounts+ end+ end++ assert_equal :rate_limited, error.error_type+ entry = DebugLogEntry.with_provider_key("lunchflow").recent.first+ assert_equal "Lunch Flow API request failed", entry.message+ assert_equal "GET /accounts", entry.metadata["operation"]+ assert_equal 503, entry.metadata["status"]+ assert_equal "rate_limited", entry.metadata["error_type"]+ assert_equal Provider::Lunchflow::MAX_RATE_LIMIT_RETRIES, entry.metadata["retry_attempts"]+ end++ test "does not retry authentication failures" do+ unauthorized = response(401, { error: "Unauthorized" }.to_json, "Unauthorized")++ Provider::Lunchflow.expects(:get).once.returns(unauthorized)+ @provider.expects(:sleep).never++ error = nil+ assert_difference -> { DebugLogEntry.with_provider_key("lunchflow").count }, 1 do+ error = assert_raises(Provider::Lunchflow::LunchflowError) do+ @provider.get_accounts+ end+ end++ assert_equal :unauthorized, error.error_type+ entry = DebugLogEntry.with_provider_key("lunchflow").recent.first+ assert_equal "GET /accounts", entry.metadata["operation"]+ assert_equal 401, entry.metadata["status"]+ assert_equal "unauthorized", entry.metadata["error_type"]+ assert_not_includes entry.metadata.to_json, unauthorized.body+ end++ private++ def response(code, body, message, headers: {})+ OpenStruct.new(code: code, body: body, message: message, headers: headers)+ end+end