The personal finance app for everyone (by everyone)
Ruby
Rebuild balances when a rate they lacked is stored (#5129)
jaysbeekay627fbfa39abd
diff --git a/app/jobs/exchange_rate_balance_refresh_job.rb b/app/jobs/exchange_rate_balance_refresh_job.rbnew file mode 100644index 0000000000..a4a343d31d--- /dev/null+++ b/app/jobs/exchange_rate_balance_refresh_job.rb@@ -0,0 +1,11 @@+# Syncs the accounts whose balances converted at exchange rates a write just+# stored or changed (ExchangeRate::BalanceRefresh). A job rather than inline,+# because the write can sit inside a sync's open transaction or a request.+class ExchangeRateBalanceRefreshJob < ApplicationJob+ queue_as :low_priority++ # `rates` is [{ "from" =>, "to" =>, "date" => }] as the writers enqueue it.+ def perform(rates)+ ExchangeRate::BalanceRefresh.schedule(rates.map { |rate| rate.to_h.symbolize_keys })+ end+enddiff --git a/app/models/exchange_rate/balance_refresh.rb b/app/models/exchange_rate/balance_refresh.rbnew file mode 100644index 0000000000..8427c6a00e--- /dev/null+++ b/app/models/exchange_rate/balance_refresh.rb@@ -0,0 +1,148 @@+# Rebuilds the balances a stored or changed exchange rate would have fed.+#+# Balance::SyncCache converts each foreign-currency entry into its account's+# currency when the balances are materialized, at the rate stored then: the+# latest usable one up to NEAREST_RATE_LOOKBACK_DAYS before the date. With+# none, the entry is dropped. Holding::PortfolioCache converts a security's+# price the same way and falls back to 1:1. Nothing rebuilt those balances+# when the rate arrived or was corrected later, so a balance stayed wrong until+# something else happened to sync the account.+#+# Given the rates a write newly stored, this syncs every account with an entry,+# a holding or a trade priced in that currency that had no usable rate before+# them: every usable rate in its lookback is one of the new ones, or was stored+# after them by another write, whose own refresh counts these as already+# there. A rate following yesterday's, which the conversion already had,+# changes nothing here. Synced from the earliest such date. Run from+# ExchangeRateBalanceRefreshJob, never inside the write, which can sit in a+# sync's open transaction.+class ExchangeRate::BalanceRefresh+ # `rates` is [{ from:, to:, date:, stored_at: }], the rows a write newly+ # stored and the time it stored them (their created_at).+ def self.schedule(rates)+ new(rates).schedule+ end++ # Queues the refresh for rates a write just stored. Best-effort: the rates+ # are stored either way, so a queue that cannot take the job is recorded for+ # support rather than raised into the write's caller -- or, inside a+ # transaction, into whoever commits it: the job is queued once every open+ # transaction has committed (as ApplicationJob would defer it), within the+ # rescue.+ def self.enqueue(rates, source:, provider: nil)+ ActiveRecord.after_all_transactions_commit do+ attempted_job = nil+ ExchangeRateBalanceRefreshJob.perform_later(rates) { |job| attempted_job = job }++ # perform_later returns false rather than raising when the adapter raises+ # ActiveJob::EnqueueError or a callback aborts the enqueue, so the job's+ # own state is what says the refresh never reached the queue.+ if attempted_job && !attempted_job.successfully_enqueued?+ raise attempted_job.enqueue_error || ActiveJob::EnqueueError.new("ExchangeRateBalanceRefreshJob was not enqueued")+ end+ rescue StandardError => e+ Rails.logger.error("Could not queue the balance refresh for #{rates.size} exchange rate(s): #{e.message}")+ Sentry.capture_exception(e)+ DebugLogEntry.capture(+ category: "exchange_rates",+ level: "error",+ message: "Could not queue the balance refresh for newly stored exchange rates: #{e.class} - #{e.message}",+ source: source,+ provider: provider,+ metadata: { rates: rates.map { |rate| rate.slice(:from, :to, :date) } }+ )+ end+ end++ def initialize(rates)+ @rates = Array(rates)+ end++ def schedule+ dates = earliest_dates+ return if dates.empty?++ Account.visible.where(id: dates.keys).find_each do |account|+ refresh(account, dates.fetch(account.id))+ end+ end++ private+ attr_reader :rates++ # A running sync cannot widen its window (Sync#expand_window_if_needed+ # only widens a pending one), so it is asked for a full resync once it+ # finishes, as Sync#queue_full_resync does -- checked under its lock, so a+ # sync that finished meanwhile is not flagged after it read the flag.+ # Otherwise the account syncs from the date, merged into any sync still+ # pending.+ def refresh(account, date)+ running = account.syncs.visible.where(status: "syncing").first+ flagged = running&.with_lock do+ running.syncing? && running.update!(full_resync_requested: true)+ end++ account.sync_later(window_start_date: date) unless flagged+ end++ # { account_id => earliest affected date } across every changed pair.+ def earliest_dates+ rates.group_by { |rate| [ rate[:from], rate[:to] ] }.each_with_object({}) do |((from, to), rows), earliest|+ stored_at = rows.map { |rate| rate.fetch(:stored_at) }.min+ affected_accounts(from, to, rows.map { |rate| rate[:date].to_date }.uniq, stored_at).each do |account_id, date|+ earliest[account_id] = [ earliest[account_id], date ].compact.min+ end+ end+ end++ # What a balance converted from `from` into an account kept in `to`: an+ # entry already applied (a day of headroom past today, since a sync reads+ # today in the family's zone), a holding whose security is priced in+ # `from`, or a trade priced in `from` with shares in it, which+ # Holding::PortfolioCache prices the security from even at amount 0 (a+ # transfer or split) -- at a date whose lookback holds a new rate and no+ # other usable one stored before it, so the conversion found none before.+ # A rate another write stored later is not one the balance had. A+ # valuation counts even at amount 0: it sets the balance, and a sync drops+ # it without a rate like any other entry.+ def affected_accounts(from, to, dates, stored_at)+ sql = <<~SQL+ SELECT converted.account_id, MIN(converted.date)+ FROM (+ SELECT entries.account_id, entries.date FROM entries+ WHERE entries.currency = :from AND (entries.amount <> 0 OR entries.entryable_type = 'Valuation')+ AND entries.date BETWEEN :first_date AND LEAST(:last_date, CAST(:today AS date))+ UNION ALL+ SELECT holdings.account_id, holdings.date FROM holdings+ WHERE holdings.amount <> 0+ AND holdings.date BETWEEN :first_date AND :last_date+ AND (holdings.currency = :from OR EXISTS (+ SELECT 1 FROM security_prices sp WHERE sp.security_id = holdings.security_id AND sp.currency = :from))+ UNION ALL+ SELECT entries.account_id, entries.date FROM entries+ JOIN trades ON entries.entryable_type = 'Trade' AND trades.id = entries.entryable_id+ WHERE trades.currency = :from AND trades.qty <> 0+ AND entries.date BETWEEN :first_date AND LEAST(:last_date, CAST(:today AS date))+ ) converted+ JOIN accounts ON accounts.id = converted.account_id AND accounts.currency = :to+ WHERE EXISTS (SELECT 1 FROM exchange_rates r+ WHERE r.from_currency = :from AND r.to_currency = :to AND r.rate > 0+ AND r.date BETWEEN converted.date - :lookback AND converted.date+ AND r.date IN (:dates))+ AND NOT EXISTS (SELECT 1 FROM exchange_rates r+ WHERE r.from_currency = :from AND r.to_currency = :to AND r.rate > 0+ AND r.date BETWEEN converted.date - :lookback AND converted.date+ AND r.date NOT IN (:dates) AND r.created_at < :stored_at)+ GROUP BY converted.account_id+ SQL++ binds = {+ from: from, to: to, dates: dates, stored_at: stored_at, today: Date.current + 1.day,+ lookback: ExchangeRate::Provided::NEAREST_RATE_LOOKBACK_DAYS,+ first_date: dates.min, last_date: dates.max + ExchangeRate::Provided::NEAREST_RATE_LOOKBACK_DAYS+ }++ ActiveRecord::Base.connection.select_rows(ActiveRecord::Base.sanitize_sql_array([ sql, binds ]))+ .map { |account_id, date| [ account_id, date.to_date ] }+ end+enddiff --git a/app/models/exchange_rate/importer.rb b/app/models/exchange_rate/importer.rbindex 8cba9afe0f..52894c1376 100644--- a/app/models/exchange_rate/importer.rb+++ b/app/models/exchange_rate/importer.rb@@ -112,6 +112,9 @@ class ExchangeRate::Importerprovider_name: current_provider_name)end+ ensure+ # Rows already written stay written, so on every way out.+ refresh_balancesendprivate@@ -123,18 +126,41 @@ class ExchangeRate::Importertotal_upsert_count = 0rows.each_slice(batch_size) do |batch|- upserted_ids = ExchangeRate.upsert_all(+ # xmax is 0 only on a row the upsert inserted rather than updated.+ upserted = ExchangeRate.upsert_all(batch,unique_by: %i[from_currency to_currency date],- returning: [ "id" ]+ returning: Arel.sql("from_currency, to_currency, date, created_at, (xmax = 0) AS inserted"))- total_upsert_count += upserted_ids.count+ upserted.each do |row|+ next unless ActiveModel::Type::Boolean.new.cast(row["inserted"])++ inserted_rates << {+ from: row["from_currency"], to: row["to_currency"], date: row["date"].to_date,+ stored_at: ExchangeRate.type_for_attribute(:created_at).deserialize(row["created_at"])+ }+ end++ total_upsert_count += upserted.countendtotal_upsert_countend+ def inserted_rates+ @inserted_rates ||= []+ end++ # A rate stored where there was none is one a balance had to do without+ # (ExchangeRate::BalanceRefresh). An updated row was already usable: the+ # table refuses a rate that is not positive.+ def refresh_balances+ return if inserted_rates.empty?++ ExchangeRate::BalanceRefresh.enqueue(inserted_rates, source: "ExchangeRate::Importer", provider: current_provider_name)+ end+def start_rate_valueif fill_start_date == start_dateprovider_rate_value = latest_valid_provider_rate(before_or_on: start_date)diff --git a/app/models/exchange_rate/provided.rb b/app/models/exchange_rate/provided.rbindex 124ca518f2..cd745e6cc5 100644--- a/app/models/exchange_rate/provided.rb+++ b/app/models/exchange_rate/provided.rb@@ -121,6 +121,14 @@ module ExchangeRate::ProvidedRails.logger.warn("Could not replace unusable exchange rate #{rate.from}/#{rate.to} on #{rate.date}: #{e.message}")endend++ # Reached only when no usable rate was stored for the date, so this one+ # is a rate a balance may have had to do without+ # (ExchangeRate::BalanceRefresh).+ ExchangeRate::BalanceRefresh.enqueue(+ [ { from: stored.from_currency, to: stored.to_currency, date: stored.date, stored_at: stored.created_at } ],+ source: "ExchangeRate.find_or_fetch_rate", provider: provider+ )rateenddiff --git a/test/models/exchange_rate/balance_refresh_test.rb b/test/models/exchange_rate/balance_refresh_test.rbnew file mode 100644index 0000000000..b593215764--- /dev/null+++ b/test/models/exchange_rate/balance_refresh_test.rb@@ -0,0 +1,253 @@+require "test_helper"++class ExchangeRate::BalanceRefreshTest < ActiveSupport::TestCase+ include ActiveJob::TestHelper++ setup do+ ExchangeRate.delete_all+ @family = families(:empty)+ @account = usd_account+ @date = 10.days.ago.to_date+ end++ # The bug end to end: a sync drops an entry it has no rate for, the rate+ # arrives later, and the balance has to come back with the entry in it.+ test "a rate stored after a sync dropped an entry rebuilds the balance with it" do+ eur_deposit(account: @account, date: @date, amount: 100)+ Balance::Materializer.new(@account, strategy: :forward).materialize_balances+ before = closing_balance(@account)++ ExchangeRate.create!(from_currency: "EUR", to_currency: "USD", date: @date, rate: 1.1)+ perform_enqueued_jobs do+ ExchangeRate::BalanceRefresh.schedule([ { from: "EUR", to: "USD", date: @date, stored_at: Time.current } ])+ end++ assert_equal before + 110, closing_balance(@account), "the 100 EUR deposit is now in the balance at 1.1"+ end++ test "an account whose entry converts at a changed rate is synced from that entry's date" do+ eur_deposit(account: @account, date: @date + 2.days, amount: 100)+ eur_deposit(account: @account, date: @date + 1.day, amount: 50)+ ExchangeRate.create!(from_currency: "EUR", to_currency: "USD", date: @date, rate: 1.1)++ ExchangeRate::BalanceRefresh.schedule([ { from: "EUR", to: "USD", date: @date, stored_at: Time.current } ])++ assert_equal [ @date + 1.day ], @account.syncs.pluck(:window_start_date)+ end++ # Only entries that had no usable rate before the write: an entry with an+ # older rate in its lookback (the daily case, a rate following yesterday's)+ # was converted, and a new rate there changes nothing.+ test "accounts whose entries do not convert at a changed rate are left alone" do+ later_rate = usd_account+ eur_deposit(account: later_rate, date: @date + 2.days, amount: 100)+ ExchangeRate.create!(from_currency: "EUR", to_currency: "USD", date: @date + 1.day, rate: 1.2)++ out_of_reach = usd_account+ eur_deposit(account: out_of_reach, date: @date + ExchangeRate::Provided::NEAREST_RATE_LOOKBACK_DAYS + 1, amount: 100)++ other_pair = usd_account+ other_pair.entries.create!(name: "GBP", date: @date, amount: -100, currency: "GBP", entryable: Transaction.new)++ same_currency = @family.accounts.create!(name: "EUR", balance: 0, currency: "EUR", accountable: Depository.new)+ eur_deposit(account: same_currency, date: @date, amount: 100)++ ExchangeRate.create!(from_currency: "EUR", to_currency: "USD", date: @date, rate: 1.1)+ eur_deposit(account: @account, date: @date, amount: 100)++ ExchangeRate::BalanceRefresh.schedule([ { from: "EUR", to: "USD", date: @date, stored_at: Time.current } ])++ assert_equal 1, @account.syncs.count, "precondition: the account that did use the rate is synced"+ [ later_rate, out_of_reach, other_pair, same_currency ].each do |account|+ assert_equal 0, account.syncs.count, "#{account.name} converts no differently"+ end+ end++ # Two writes stored apart, each queuing its own refresh before either runs:+ # the rate the other write stored was not there when this one's balance+ # went without, so it cannot stand in for one that was.+ test "rates stored by separate writes do not cancel each other's refresh" do+ eur_deposit(account: @account, date: @date + 1.day, amount: 100)+ Balance::Materializer.new(@account, strategy: :forward).materialize_balances+ before = closing_balance(@account)++ first = ExchangeRate.create!(from_currency: "EUR", to_currency: "USD", date: @date, rate: 1.1)+ travel 1.second+ second = ExchangeRate.create!(from_currency: "EUR", to_currency: "USD", date: @date + 1.day, rate: 1.1)++ ExchangeRate::BalanceRefresh.schedule([ { from: "EUR", to: "USD", date: first.date, stored_at: first.created_at } ])+ ExchangeRate::BalanceRefresh.schedule([ { from: "EUR", to: "USD", date: second.date, stored_at: second.created_at } ])+ perform_enqueued_jobs++ assert_equal [ @date + 1.day ], @account.syncs.pluck(:window_start_date), "one refresh syncs the entry's account from its date"+ assert_equal before + 110, closing_balance(@account), "the 100 EUR deposit is now in the balance at 1.1"+ end++ # Several pairs at once: the account syncs from the earliest date any of+ # them affects.+ test "an account affected through several pairs is synced from the earliest date" do+ eur_deposit(account: @account, date: @date + 2.days, amount: 100)+ @account.entries.create!(name: "GBP", date: @date, amount: -50, currency: "GBP", entryable: Transaction.new)+ ExchangeRate.create!(from_currency: "EUR", to_currency: "USD", date: @date + 2.days, rate: 1.1)+ ExchangeRate.create!(from_currency: "GBP", to_currency: "USD", date: @date, rate: 1.3)++ ExchangeRate::BalanceRefresh.schedule([+ { from: "EUR", to: "USD", date: @date + 2.days, stored_at: Time.current },+ { from: "GBP", to: "USD", date: @date, stored_at: Time.current }+ ])++ assert_equal [ @date ], @account.syncs.pluck(:window_start_date)+ end++ # A security priced in another currency is converted into the account's+ # when its holdings are built, at 1:1 when there is no rate, and the holding+ # is stored in the account's currency -- so it is found by its price.+ test "an account holding a security priced in the changed currency is synced" do+ security = Security.create!(ticker: "EURX#{SecureRandom.hex(3)}", name: "EUR fund")+ Security::Price.create!(security: security, date: @date, price: 100, currency: "EUR")+ @account.holdings.create!(security: security, date: @date, qty: 1, price: 100, amount: 100, currency: "USD")+ ExchangeRate.create!(from_currency: "EUR", to_currency: "USD", date: @date, rate: 1.1)++ ExchangeRate::BalanceRefresh.schedule([ { from: "EUR", to: "USD", date: @date, stored_at: Time.current } ])++ assert_equal [ @date ], @account.syncs.pluck(:window_start_date)+ end++ # A trade that moves shares without cash (a transfer or split, imported at+ # amount 0) still prices its security in the trade's currency for the+ # holdings built from it, at 1:1 without a rate -- with no provider price+ # and the holding kept in the account's currency, only the trade shows it.+ test "an account with a zero-amount trade priced in the changed currency is synced" do+ security = Security.create!(ticker: "EURT#{SecureRandom.hex(3)}", name: "EUR transfer")+ trade_date = @date + 2.days+ eur_share_transfer(account: @account, security: security, date: trade_date, qty: 10)+ @account.holdings.create!(security: security, date: trade_date, qty: 10, price: 50, amount: 500, currency: "USD")+ ExchangeRate.create!(from_currency: "EUR", to_currency: "USD", date: @date, rate: 1.1)++ ExchangeRate::BalanceRefresh.schedule([ { from: "EUR", to: "USD", date: @date, stored_at: Time.current } ])++ assert_equal [ trade_date ], @account.syncs.pluck(:window_start_date)+ end++ # A trade with no shares (interest, a dividend) prices nothing: the holdings+ # skip it, so a rate for its currency changes nothing it fed.+ test "a zero-quantity trade in the changed currency does not sync its account" do+ security = Security.create!(ticker: "EURI#{SecureRandom.hex(3)}", name: "EUR income")+ eur_share_transfer(account: @account, security: security, date: @date, qty: 0)+ ExchangeRate.create!(from_currency: "EUR", to_currency: "USD", date: @date, rate: 1.1)++ assert_no_difference "Sync.count" do+ ExchangeRate::BalanceRefresh.schedule([ { from: "EUR", to: "USD", date: @date, stored_at: Time.current } ])+ end+ end++ # A valuation sets the balance whatever its amount, so a zero one (an+ # account reset to nothing) needs a rate like any other and is dropped+ # without one.+ test "a rate stored after a sync dropped a zero valuation rebuilds the balance with it" do+ @account.entries.create!(name: "USD deposit", date: @date - 1.day, amount: -500, currency: "USD", entryable: Transaction.new)+ @account.entries.create!(name: "EUR reset", date: @date, amount: 0, currency: "EUR",+ entryable: Valuation.new(kind: "reconciliation"))+ Balance::Materializer.new(@account, strategy: :forward).materialize_balances+ assert_equal 500, closing_balance(@account), "precondition: the sync dropped the valuation it had no rate for"++ ExchangeRate.create!(from_currency: "EUR", to_currency: "USD", date: @date, rate: 1.1)+ perform_enqueued_jobs do+ ExchangeRate::BalanceRefresh.schedule([ { from: "EUR", to: "USD", date: @date, stored_at: Time.current } ])+ end++ assert_equal [ @date ], @account.syncs.pluck(:window_start_date)+ assert_equal 0, closing_balance(@account), "the zero EUR valuation now resets the balance"+ end++ # Any other entry at amount 0 adds nothing to the balance, converted or not.+ test "a zero-amount transaction in the changed currency does not sync its account" do+ @account.entries.create!(name: "EUR zero", date: @date, amount: 0, currency: "EUR", entryable: Transaction.new)+ with_amount = usd_account+ eur_deposit(account: with_amount, date: @date, amount: 100)+ ExchangeRate.create!(from_currency: "EUR", to_currency: "USD", date: @date, rate: 1.1)++ ExchangeRate::BalanceRefresh.schedule([ { from: "EUR", to: "USD", date: @date, stored_at: Time.current } ])++ assert_equal 1, with_amount.syncs.count, "precondition: the refresh syncs an account with an amount in the changed currency"+ assert_equal 0, @account.syncs.count+ end++ # A running sync cannot widen its window, so it is asked for a full resync+ # when it finishes rather than having the request dropped.+ test "an account already syncing is resynced in full after it finishes" do+ eur_deposit(account: @account, date: @date, amount: 100)+ ExchangeRate.create!(from_currency: "EUR", to_currency: "USD", date: @date, rate: 1.1)+ running = @account.syncs.create!(status: "syncing")+ Account.any_instance.expects(:sync_later).never++ assert_no_difference "Sync.count" do+ ExchangeRate::BalanceRefresh.schedule([ { from: "EUR", to: "USD", date: @date, stored_at: Time.current } ])+ end+ assert running.reload.full_resync_requested+ end++ # What the balance never converted cannot be what is wrong with it: an+ # entry scheduled after today, or an account on its way out.+ # Read, then locked: a sync that finished in between already read its flag,+ # so the account is synced afresh instead of flagging a finished sync.+ test "a sync that stopped syncing before it was flagged leaves the account synced afresh" do+ eur_deposit(account: @account, date: @date, amount: 100)+ ExchangeRate.create!(from_currency: "EUR", to_currency: "USD", date: @date, rate: 1.1)+ running = @account.syncs.create!(status: "syncing")+ Sync.any_instance.stubs(:syncing?).returns(false)+ Account.any_instance.expects(:sync_later).with(window_start_date: @date).once++ ExchangeRate::BalanceRefresh.schedule([ { from: "EUR", to: "USD", date: @date, stored_at: Time.current } ])++ assert_not running.reload.full_resync_requested+ end++ test "scheduled entries and accounts pending deletion are left alone" do+ today = Date.current+ eur_deposit(account: @account, date: today + 2.days, amount: 100)+ leaving = usd_account+ eur_deposit(account: leaving, date: today, amount: 100)+ leaving.update_columns(status: "pending_deletion")+ ExchangeRate.create!(from_currency: "EUR", to_currency: "USD", date: today, rate: 1.1)++ assert_no_difference "Sync.count" do+ ExchangeRate::BalanceRefresh.schedule([ { from: "EUR", to: "USD", date: today, stored_at: Time.current } ])+ end+ end++ test "the job refreshes the rates it is given" do+ eur_deposit(account: @account, date: @date, amount: 100)+ ExchangeRate.create!(from_currency: "EUR", to_currency: "USD", date: @date, rate: 1.1)++ ExchangeRateBalanceRefreshJob.perform_now([ { from: "EUR", to: "USD", date: @date, stored_at: Time.current } ])++ assert_equal [ @date ], @account.syncs.pluck(:window_start_date)+ end++ test "no changed rates schedule nothing" do+ eur_deposit(account: @account, date: @date, amount: 100)++ assert_no_difference "Sync.count" do+ ExchangeRate::BalanceRefresh.schedule([])+ end+ end++ private+ def usd_account+ @family.accounts.create!(name: "USD #{SecureRandom.hex(3)}", balance: 0, currency: "USD", accountable: Depository.new)+ end++ def eur_deposit(account:, date:, amount:)+ account.entries.create!(name: "EUR deposit", date: date, amount: -amount, currency: "EUR", entryable: Transaction.new)+ end++ def eur_share_transfer(account:, security:, date:, qty:)+ account.entries.create!(name: "EUR transfer", date: date, amount: 0, currency: "EUR",+ entryable: Trade.new(security: security, qty: qty, price: 50, currency: "EUR"))+ end++ def closing_balance(account)+ account.balances.where(currency: account.currency).order(date: :desc).pick(:end_balance) || 0+ end+enddiff --git a/test/models/exchange_rate/importer_test.rb b/test/models/exchange_rate/importer_test.rbindex 2f2840fc6b..2ac393024a 100644--- a/test/models/exchange_rate/importer_test.rb+++ b/test/models/exchange_rate/importer_test.rb@@ -86,6 +86,67 @@ class ExchangeRate::ImporterTest < ActiveSupport::TestCaseassert_equal [ 1.2, 1.25, 1.3, 1.3 ], forward_rates.map(&:rate)end+ # A rate stored where there was none is one a balance may have had to do+ # without, so it is passed to the balance refresh. A row that already+ # existed was usable, whether the import leaves it or corrects it, so it is+ # not.+ test "passes only the rates it newly stored to the balance refresh" do+ ExchangeRate.delete_all+ yesterday = 1.day.ago.to_date+ ExchangeRate.create!(from_currency: "USD", to_currency: "EUR", date: yesterday, rate: 1.3)+ ExchangeRate.create!(from_currency: "EUR", to_currency: "USD", date: yesterday, rate: (BigDecimal("1") / BigDecimal("1.3")).round(12))++ @provider.expects(:fetch_exchange_rates)+ .with(from: "USD", to: "EUR", start_date: get_provider_fetch_start_date(yesterday), end_date: Date.current)+ .returns(provider_success_response([+ OpenStruct.new(from: "USD", to: "EUR", date: yesterday, rate: 1.35),+ OpenStruct.new(from: "USD", to: "EUR", date: Date.current, rate: 1.4)+ ]))++ refreshed = nil+ ExchangeRateBalanceRefreshJob.expects(:perform_later).with { |rates| refreshed = rates }.once++ ExchangeRate::Importer.new(+ exchange_rate_provider: @provider,+ from: "USD",+ to: "EUR",+ start_date: yesterday,+ end_date: Date.current,+ clear_cache: true+ ).import_provider_rates++ assert_equal [ [ "EUR", "USD", Date.current ], [ "USD", "EUR", Date.current ] ],+ refreshed.map { |rate| [ rate[:from], rate[:to], rate[:date] ] }.sort+ assert_equal BigDecimal("1.35"), ExchangeRate.find_by(from_currency: "USD", to_currency: "EUR", date: yesterday).rate,+ "precondition: the existing row was corrected, not left alone"+ refreshed.each do |rate|+ stored = ExchangeRate.find_by!(from_currency: rate[:from], to_currency: rate[:to], date: rate[:date])+ assert_equal stored.created_at, rate[:stored_at], "each rate carries the time it was stored"+ end+ end++ # The rates are stored either way; a queue that cannot take the refresh is+ # recorded for support rather than failing the import.+ test "a refresh that cannot be queued is logged and the import completes" do+ ExchangeRate.delete_all+ @provider.expects(:fetch_exchange_rates)+ .returns(provider_success_response([ OpenStruct.new(from: "USD", to: "EUR", date: Date.current, rate: 1.4) ]))+ ExchangeRateBalanceRefreshJob.expects(:perform_later).raises(StandardError, "queue unavailable")++ assert_difference -> { DebugLogEntry.where(category: "exchange_rates").count }, 1 do+ ExchangeRate::Importer.new(+ exchange_rate_provider: @provider,+ from: "USD",+ to: "EUR",+ start_date: Date.current,+ end_date: Date.current,+ clear_cache: true+ ).import_provider_rates+ end++ assert ExchangeRate.exists?(from_currency: "USD", to_currency: "EUR", date: Date.current)+ end+test "no provider calls when all rates exist" doExchangeRate.delete_alldiff --git a/test/models/exchange_rate_test.rb b/test/models/exchange_rate_test.rbindex 5837111f32..b42361247d 100644--- a/test/models/exchange_rate_test.rb+++ b/test/models/exchange_rate_test.rb@@ -161,6 +161,81 @@ class ExchangeRateTest < ActiveSupport::TestCaseassert ExchangeRatePair.find_by!(from_currency: "KZT", to_currency: "RUB").quoted_directly?end+ # A rate stored here can be one a balance had to do without, so it is+ # passed to the balance refresh. One already stored is not.+ test "a rate fetched and stored is passed to the balance refresh" do+ ExchangeRate.delete_all+ @provider.expects(:fetch_exchange_rate).returns(provider_success_response(+ OpenStruct.new(from: "USD", to: "EUR", date: Date.current, rate: 1.2)+ ))+ refreshed = nil+ ExchangeRateBalanceRefreshJob.expects(:perform_later).with { |rates| refreshed = rates }.once++ ExchangeRate.find_or_fetch_rate(from: "USD", to: "EUR", date: Date.current, cache: true)+ stored = ExchangeRate.find_by!(from_currency: "USD", to_currency: "EUR", date: Date.current)+ assert_equal [ { from: "USD", to: "EUR", date: Date.current, stored_at: stored.created_at } ], refreshed++ ExchangeRateBalanceRefreshJob.expects(:perform_later).never+ ExchangeRate.find_or_fetch_rate(from: "USD", to: "EUR", date: Date.current, cache: true)+ end++ # The rate is stored before the refresh is queued, so a queue that cannot+ # take the job must not cost the caller the rate it fetched; support sees+ # the balance it left unrepaired in the debug log.+ test "a refresh that cannot be queued still returns the fetched rate" do+ ExchangeRate.delete_all+ @provider.expects(:fetch_exchange_rate).returns(provider_success_response(+ OpenStruct.new(from: "USD", to: "EUR", date: Date.current, rate: 1.2)+ ))+ ExchangeRateBalanceRefreshJob.expects(:perform_later).raises(StandardError, "queue unavailable")++ rate = nil+ assert_difference -> { DebugLogEntry.where(category: "exchange_rates").count }, 1 do+ rate = ExchangeRate.find_or_fetch_rate(from: "USD", to: "EUR", date: Date.current, cache: true)+ end++ assert_equal 1.2, rate.rate+ assert ExchangeRate.exists?(from_currency: "USD", to_currency: "EUR", date: Date.current)+ end++ # Inside a transaction the job is queued when it commits (ApplicationJob+ # enqueue_after_transaction_commit), after the write has returned; a queue+ # that cannot take it then must not fail whoever committed.+ test "a refresh that cannot be queued when a transaction commits does not fail the commit" do+ ExchangeRate.delete_all+ @provider.expects(:fetch_exchange_rate).returns(provider_success_response(+ OpenStruct.new(from: "USD", to: "EUR", date: Date.current, rate: 1.2)+ ))+ ExchangeRateBalanceRefreshJob.queue_adapter.stubs(:enqueue).raises(StandardError, "queue unavailable")++ rate = nil+ assert_difference -> { DebugLogEntry.where(category: "exchange_rates").count }, 1 do+ ExchangeRate.transaction do+ rate = ExchangeRate.find_or_fetch_rate(from: "USD", to: "EUR", date: Date.current, cache: true)+ end+ end++ assert_equal 1.2, rate.rate+ end++ # perform_later turns an adapter's ActiveJob::EnqueueError into a false+ # return rather than raising it, so the dropped refresh is logged all the+ # same.+ test "a refresh the queue adapter rejects is logged" do+ ExchangeRate.delete_all+ @provider.expects(:fetch_exchange_rate).returns(provider_success_response(+ OpenStruct.new(from: "USD", to: "EUR", date: Date.current, rate: 1.2)+ ))+ ExchangeRateBalanceRefreshJob.queue_adapter.stubs(:enqueue).raises(ActiveJob::EnqueueError, "queue unavailable")++ rate = nil+ assert_difference -> { DebugLogEntry.where(category: "exchange_rates").count }, 1 do+ rate = ExchangeRate.find_or_fetch_rate(from: "USD", to: "EUR", date: Date.current, cache: true)+ end++ assert_equal 1.2, rate.rate+ end+test "returns nil on provider error" doprovider_response = provider_error_response(StandardError.new("Test error"))