Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Enable Banking: fetch transaction history right after authorisation (#5046)

arnaurodondev32ac1e921020
diff --git a/app/models/enable_banking_account/transactions/processor.rb b/app/models/enable_banking_account/transactions/processor.rb
index b9a9cfe126..e08a4d1c65 100644
--- a/app/models/enable_banking_account/transactions/processor.rb
+++ b/app/models/enable_banking_account/transactions/processor.rb
@@ -6,6 +6,12 @@ class EnableBankingAccount::Transactions::Processor
end
def process
+ # Once the account is linked, rows stored by an early fetch are kept even
+ # if it is unlinked later (see EnableBankingItem::Importer).
+ if enable_banking_account.early_fetched_at && enable_banking_account.current_account.present?
+ enable_banking_account.update_columns(early_fetched_at: nil)
+ end
+
unless enable_banking_account.raw_transactions_payload.present?
Rails.logger.info "EnableBankingAccount::Transactions::Processor - No transactions in raw_transactions_payload for enable_banking_account #{enable_banking_account.id}"
return { success: true, total: 0, imported: 0, failed: 0, errors: [] }
@@ -19,6 +25,14 @@ class EnableBankingAccount::Transactions::Processor
failed_count = 0
errors = []
+ # The first fetch can store more history than the user asked for (it runs with
+ # strategy=longest, possibly before the setup modal sets sync_start_date), so
+ # rows before sync_start_date are kept raw but not imported. Read from the
+ # database: the setup modal can set the date while a sync that loaded the
+ # item earlier is still running.
+ sync_start_date = EnableBankingItem.where(id: enable_banking_account.enable_banking_item_id).pick(:sync_start_date)
+ timezone = enable_banking_account.current_account&.family&.timezone
+
shared_adapter = if enable_banking_account.current_account.present?
Account::ProviderImportAdapter.new(enable_banking_account.current_account)
end
@@ -113,6 +127,11 @@ class EnableBankingAccount::Transactions::Processor
next
end
+ if sync_start_date && EnableBankingEntry::Processor.transaction_date(transaction_data, timezone) < sync_start_date
+ skipped_count += 1
+ next
+ end
+
result = EnableBankingEntry::Processor.new(
transaction_data,
enable_banking_account: enable_banking_account,
diff --git a/app/models/enable_banking_item.rb b/app/models/enable_banking_item.rb
index ff6d5b6386..05baa9837d 100644
--- a/app/models/enable_banking_item.rb
+++ b/app/models/enable_banking_item.rb
@@ -212,8 +212,24 @@ class EnableBankingItem < ApplicationRecord
status: :good
)
- # Import the accounts from the session
- import_accounts_from_session(result[:accounts] || [])
+ # A fresh SCA: the next sync also fetches the accounts that are not linked
+ # yet, while the bank still serves full history (see
+ # EnableBankingItem::Importer#fetch_unlinked_accounts_after_authorization).
+ # One transaction with the account import, so a sync never sees the
+ # request before the session's accounts exist, and no imported account is
+ # left without it. The request's time is read only under a row lock that
+ # conflicts with sync_later's (FOR UPDATE): a sync created before the lock
+ # is older than the request, and one created after it waits for this
+ # commit and reads the request (see
+ # EnableBankingItem::Syncer#perform_post_sync). FOR NO KEY UPDATE, the
+ # lock the UPDATE takes anyway, because each account insert's foreign key
+ # check holds KEY SHARE on this row: two authorizations could not both
+ # upgrade from that to FOR UPDATE.
+ transaction do
+ import_accounts_from_session(result[:accounts] || [])
+ lock!("FOR NO KEY UPDATE")
+ update!(full_history_fetch_requested_at: Time.current)
+ end
result
end
diff --git a/app/models/enable_banking_item/importer.rb b/app/models/enable_banking_item/importer.rb
index 23adc20543..178079f2b4 100644
--- a/app/models/enable_banking_item/importer.rb
+++ b/app/models/enable_banking_item/importer.rb
@@ -18,6 +18,16 @@ class EnableBankingItem::Importer
# incremental_sync_start_date).
STORED_ROW_LOOKBACK_LIMIT = Provider::EnableBanking::FALLBACK_TRANSACTIONS_DATE_FROM_DAYS.first.days
+ # A full-history request (set by complete_authorization) is acted on by syncs
+ # for this long, then dropped even if a fetch kept failing. Enable Banking
+ # says full history is typically only available for about an hour after
+ # authorization (Revolut: 5 minutes), so later retries would not get more.
+ FULL_HISTORY_REQUEST_WINDOW = 1.hour
+
+ # Raw transactions stored by an early fetch are deleted if the account is
+ # still not linked this long after that fetch.
+ UNLINKED_TRANSACTIONS_RETENTION = 7.days
+
# Prefer booked ledger balances for net worth/current_balance. Available balances
# can include an arranged overdraft facility for some ASPSPs (for example CGD PT),
# so they are only a last-resort fallback.
@@ -107,6 +117,11 @@ class EnableBankingItem::Importer
sync_uids_from_accounts_data(session_data[:accounts])
+ # Before the linked accounts, so the early fetch runs as soon after the
+ # authorization as possible. The syncer purges stale early rows first.
+ @early_fetch_truncated = 0
+ handle_full_history_request
+
# Update accounts from session
accounts_updated = 0
accounts_failed = 0
@@ -188,6 +203,10 @@ class EnableBankingItem::Importer
end
end
+ # An authorization that completed while this sync ran reuses it instead
+ # of starting another one, so its request is handled here.
+ handle_full_history_request if newer_full_history_request?
+
result = {
success: accounts_failed == 0 && transactions_failed == 0,
accounts_updated: accounts_updated,
@@ -195,13 +214,49 @@ class EnableBankingItem::Importer
transactions_imported: transactions_imported,
transactions_failed: transactions_failed,
balances_failed: balances_failed,
- transactions_truncated: transactions_truncated
+ transactions_truncated: transactions_truncated + @early_fetch_truncated
}
result[:error] = @sync_error || I18n.t("enable_banking_items.errors.unexpected") if !result[:success]
result
end
+ # Raw transactions stored by an early fetch are deleted if the account is
+ # still unlinked UNLINKED_TRANSACTIONS_RETENTION later (skipped in setup,
+ # or setup never finished). Processing a linked account clears
+ # early_fetched_at, so rows of an account that was linked and later
+ # unlinked are kept, and a relink stays incremental. The syncer runs it at
+ # the start of every sync, before the early fetch, so a payload fetched in
+ # that sync is never deleted.
+ def purge_stale_unlinked_transactions
+ # A linked account keeps its rows even if no sync has processed it yet.
+ # An account being deleted keeps the flag, so its rows are purged once it is unlinked.
+ enable_banking_item.enable_banking_accounts.joins(:account)
+ .where.not(accounts: { status: "pending_deletion" })
+ .where.not(early_fetched_at: nil).update_all(early_fetched_at: nil)
+ unlinked_accounts.where(enable_banking_accounts: { early_fetched_at: ...UNLINKED_TRANSACTIONS_RETENTION.ago })
+ .update_all(raw_transactions_payload: nil, early_fetched_at: nil)
+ rescue => e
+ Rails.logger.warn "EnableBankingItem::Importer - Failed to purge unlinked account transactions: #{e.message}"
+ # Raw rows stay past their retention until a later sync purges them; show
+ # that in /settings/debug. The sync carries on.
+ DebugLogEntry.capture(
+ category: "provider_sync_error",
+ level: "warn",
+ message: "Enable Banking purge of stale early-fetched transactions failed; unlinked accounts keep their raw transactions until a later sync succeeds",
+ source: self.class.name,
+ provider_key: "enable_banking",
+ # An id, resolved inside capture's own rescue: the database may be what failed.
+ family_id: enable_banking_item.family_id,
+ metadata: {
+ enable_banking_item_id: enable_banking_item.id,
+ retention_days: UNLINKED_TRANSACTIONS_RETENTION.in_days.to_i,
+ error_class: e.class.name,
+ error_message: e.message.to_s.truncate(500)
+ }
+ )
+ end
+
private
# @param session_level [Boolean] true only for the top-level GET /sessions call.
@@ -1019,10 +1074,10 @@ class EnableBankingItem::Importer
{ success: true, transactions_count: transactions_count, truncated: truncated }
rescue Provider::EnableBanking::EnableBankingError => e
Rails.logger.error "EnableBankingItem::Importer - Error fetching transactions for account #{enable_banking_account.uid}: #{e.message}"
- { success: false, transactions_count: 0, error: handle_sync_error(e) }
+ { success: false, transactions_count: 0, error: handle_sync_error(e), exception: e }
rescue => e
Rails.logger.error "EnableBankingItem::Importer - Unexpected error fetching transactions for account #{enable_banking_account.uid}: #{e.class} - #{e.message}"
- { success: false, transactions_count: 0, error: handle_sync_error(e) }
+ { success: false, transactions_count: 0, error: handle_sync_error(e), exception: e }
end
# Collapse rows the API returns more than once for the same movement.
@@ -1360,6 +1415,109 @@ class EnableBankingItem::Importer
enable_banking_account.raw_transactions_payload.nil?
end
+ def full_history_fetch?
+ @full_history_requested_at.present?
+ end
+
+ def handle_full_history_request
+ capture_full_history_request
+ return unless full_history_fetch?
+
+ fetch_unlinked_accounts_after_authorization
+ finish_full_history_request
+ end
+
+ def newer_full_history_request?
+ requested_at = EnableBankingItem.where(id: enable_banking_item.id).pick(:full_history_fetch_requested_at)
+ requested_at.present? && requested_at != @full_history_requested_at
+ end
+
+ # Read from the database rather than the in-memory item, which a sync may
+ # have loaded before the authorization committed. A request older than
+ # FULL_HISTORY_REQUEST_WINDOW is dropped.
+ def capture_full_history_request
+ @full_history_incomplete = false
+ requested_at = EnableBankingItem.where(id: enable_banking_item.id).pick(:full_history_fetch_requested_at)
+
+ if requested_at && requested_at < FULL_HISTORY_REQUEST_WINDOW.ago
+ Rails.logger.warn "EnableBankingItem::Importer - Dropping the full-history request from #{requested_at.iso8601} for item #{enable_banking_item.id}: older than #{FULL_HISTORY_REQUEST_WINDOW.inspect}"
+ clear_full_history_request(requested_at)
+ requested_at = nil
+ end
+
+ @full_history_requested_at = requested_at
+ end
+
+ # The request stays for the next sync unless every early fetch in this one
+ # succeeded. Clearing compares against the value read at the start of this
+ # sync, so an authorization that lands while it runs keeps its own request.
+ def finish_full_history_request
+ clear_full_history_request(@full_history_requested_at) unless @full_history_incomplete
+ end
+
+ def clear_full_history_request(requested_at)
+ EnableBankingItem.where(id: enable_banking_item.id, full_history_fetch_requested_at: requested_at)
+ .update_all(full_history_fetch_requested_at: nil)
+ end
+
+ def unlinked_accounts
+ enable_banking_item.enable_banking_accounts
+ .left_joins(:account_provider)
+ .where(account_providers: { id: nil })
+ end
+
+ # Right after an authorization, also fetch the accounts that are not linked
+ # yet and have never been fetched, so their first (longest) fetch happens
+ # inside the bank's full-history window (Revolut: 5 minutes after SCA)
+ # instead of after the setup modal is submitted. The rows stay raw until
+ # the account is linked. An account with stored rows is left alone: some
+ # banks issue new transaction identifiers in every session, so a second
+ # longest fetch could import its history twice. Failures are retried while
+ # the request is fresh, never fail the sync, and are captured as debug log
+ # entries. Accounts the user ignored are not fetched.
+ def fetch_unlinked_accounts_after_authorization
+ enable_banking_item.enable_banking_accounts.needs_setup.where(raw_transactions_payload: nil).each do |enable_banking_account|
+ # Makes the rows purgeable while the account stays unlinked (see
+ # purge_stale_unlinked_transactions). Set before the fetch, so stored
+ # rows are never left without it.
+ enable_banking_account.update_columns(early_fetched_at: Time.current)
+ result = fetch_and_store_transactions(enable_banking_account)
+ if result[:success]
+ @early_fetch_truncated += 1 if result[:truncated]
+ else
+ @full_history_incomplete = true
+ capture_early_fetch_failure(enable_banking_account, result[:exception])
+ end
+ rescue => e
+ @full_history_incomplete = true
+ Rails.logger.warn "EnableBankingItem::Importer - Early transaction fetch failed for unlinked account #{enable_banking_account.uid}: #{e.message}"
+ capture_early_fetch_failure(enable_banking_account, e)
+ end
+ end
+
+ # Only the provider's own error fields are stored. Other errors keep just
+ # their class, since their message can carry a response body.
+ def capture_early_fetch_failure(enable_banking_account, error)
+ metadata = {
+ enable_banking_item_id: enable_banking_item.id,
+ enable_banking_account_id: enable_banking_account.id,
+ uid: enable_banking_account.uid,
+ full_history_requested_at: @full_history_requested_at&.iso8601,
+ error_class: error&.class&.name
+ }
+ metadata[:provider_error] = sanitized_provider_error(error) if error.is_a?(Provider::EnableBanking::EnableBankingError)
+
+ DebugLogEntry.capture(
+ category: "provider_sync_error",
+ level: "warn",
+ message: "Enable Banking transaction fetch after authorization failed for an unlinked account; retried while the full-history request is open",
+ source: self.class.name,
+ provider_key: "enable_banking",
+ family: enable_banking_item.family,
+ metadata: metadata
+ )
+ end
+
def determine_sync_start_date(enable_banking_account)
if first_transactions_fetch?(enable_banking_account)
# The first fetch asks for strategy=longest. The user's start date, when
diff --git a/app/models/enable_banking_item/syncer.rb b/app/models/enable_banking_item/syncer.rb
index 26ecfb62d2..de963cde2a 100644
--- a/app/models/enable_banking_item/syncer.rb
+++ b/app/models/enable_banking_item/syncer.rb
@@ -8,6 +8,11 @@ class EnableBankingItem::Syncer
end
def perform_sync(sync)
+ # Local only and needs no session, so it also runs when the session has
+ # expired or the bank rejects it. Runs before the import's early fetch, so
+ # a payload fetched in this sync is never deleted.
+ EnableBankingItem::Importer.new(enable_banking_item, enable_banking_provider: nil).purge_stale_unlinked_transactions
+
# An expired/missing session is an expected state that needs user action, not a
# hard failure. Mark the connection requires_update and finish the sync
# gracefully so the UI surfaces the "Reconnect" CTA instead of a red sync error.
@@ -88,12 +93,42 @@ class EnableBankingItem::Syncer
raise
end
+ # An authorization that completes while a sync runs reuses that sync
+ # through sync_later. While a full-history request newer than the latest
+ # sync is open, run one more sync while the bank still serves full history.
+ # That covers a request that arrived after the sync's last read of it, and
+ # one the sync read but whose early fetch failed (one retry). Read from the
+ # database, since the callback writes it from another process.
+ #
+ # Post-sync runs inside the sync's finalization transaction, which holds the
+ # sync row lock. The check runs once that transaction has committed: then
+ # sync_later doesn't take the item row lock while the sync row is locked (a
+ # deadlock with a sync that holds the item lock and waits for the sync row),
+ # and a callback whose sync_later still reused this sync has committed its
+ # request before the read. A later callback finds no running sync and
+ # starts its own.
+ #
+ # The block runs outside Sync#perform_post_sync's rescue, so it handles its
+ # own errors: one that escaped would skip finalizing the parent sync.
def perform_post_sync
- # no-op
+ ActiveRecord.after_all_transactions_commit do
+ queue_sync_for_late_full_history_request
+ rescue => e
+ Rails.logger.error("Error queueing the follow-up sync for EnableBankingItem (#{enable_banking_item.id}): #{e.message}")
+ Sentry.capture_exception(e)
+ end
end
private
+ def queue_sync_for_late_full_history_request
+ requested_at = EnableBankingItem.where(id: enable_banking_item.id).pick(:full_history_fetch_requested_at)
+ return unless requested_at && requested_at > EnableBankingItem::Importer::FULL_HISTORY_REQUEST_WINDOW.ago
+
+ latest_sync = enable_banking_item.syncs.ordered.first
+ enable_banking_item.sync_later if latest_sync.nil? || requested_at > latest_sync.created_at
+ end
+
# A full-history fetch that stopped early keeps its rows and the sync
# completes, so the sync summary shows that older history may be missing.
def collect_truncated_history_warning(sync, count)
diff --git a/db/migrate/20261120100000_add_early_fetch_columns_to_enable_banking.rb b/db/migrate/20261120100000_add_early_fetch_columns_to_enable_banking.rb
new file mode 100644
index 0000000000..dba532a492
--- /dev/null
+++ b/db/migrate/20261120100000_add_early_fetch_columns_to_enable_banking.rb
@@ -0,0 +1,6 @@
+class AddEarlyFetchColumnsToEnableBanking < ActiveRecord::Migration[8.1]
+ def change
+ add_column :enable_banking_items, :full_history_fetch_requested_at, :datetime
+ add_column :enable_banking_accounts, :early_fetched_at, :datetime
+ end
+end
diff --git a/db/schema.rb b/db/schema.rb
index a2072288c3..a8e8ce6c9a 100644
--- a/db/schema.rb
+++ b/db/schema.rb
@@ -10,7 +10,7 @@
#
# It's strongly recommended that you check this file into your version control system.
-ActiveRecord::Schema[8.1].define(version: 2026_11_20_050000) do
+ActiveRecord::Schema[8.1].define(version: 2026_11_20_100000) do
# These are extensions that must be enabled in order to support this database
enable_extension "pg_catalog.plpgsql"
enable_extension "pgcrypto"
@@ -634,6 +634,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_20_050000) do
t.decimal "credit_limit", precision: 19, scale: 4
t.string "currency"
t.decimal "current_balance", precision: 19, scale: 4
+ t.datetime "early_fetched_at"
t.uuid "enable_banking_item_id", null: false
t.string "iban"
t.jsonb "identification_hashes", default: []
@@ -665,6 +666,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_20_050000) do
t.string "country_code"
t.datetime "created_at", null: false
t.uuid "family_id", null: false
+ t.datetime "full_history_fetch_requested_at"
t.string "institution_color"
t.string "institution_domain"
t.string "institution_id"
diff --git a/test/models/enable_banking_account/transactions/processor_test.rb b/test/models/enable_banking_account/transactions/processor_test.rb
index 207c4dff02..cf7cffbeb3 100644
--- a/test/models/enable_banking_account/transactions/processor_test.rb
+++ b/test/models/enable_banking_account/transactions/processor_test.rb
@@ -50,6 +50,19 @@ class EnableBankingAccount::Transactions::ProcessorTest < ActiveSupport::TestCas
}
end
+ test "stored rows before sync_start_date are kept raw but not imported" do
+ @enable_banking_item.update!(sync_start_date: 10.days.ago.to_date)
+ old_row = raw_identifierless_transaction(amount: "40.00").merge(transaction_id: "old", booking_date: 30.days.ago.to_date.to_s)
+ new_row = raw_identifierless_transaction(amount: "41.00").merge(transaction_id: "new")
+
+ @enable_banking_account.update!(raw_transactions_payload: [ old_row, new_row ])
+ result = EnableBankingAccount::Transactions::Processor.new(@enable_banking_account).process
+
+ assert_equal 1, result[:skipped]
+ assert_equal 1, @account.entries.where(source: "enable_banking").count
+ assert @account.entries.exists?(external_id: EnableBankingEntry::Processor.compute_external_id(new_row))
+ end
+
test "a movement identified later in the same batch does not import twice" do
identifierless = raw_identifierless_transaction
settled = identifierless.merge(entry_reference: "2026-02-02.1")
diff --git a/test/models/enable_banking_item/authorization_request_concurrency_test.rb b/test/models/enable_banking_item/authorization_request_concurrency_test.rb
new file mode 100644
index 0000000000..f56edb98be
--- /dev/null
+++ b/test/models/enable_banking_item/authorization_request_concurrency_test.rb
@@ -0,0 +1,274 @@
+require "test_helper"
+require "concurrent"
+
+# The post-sync follow-up check treats a full-history request older than the
+# latest sync as one that sync already saw. complete_authorization therefore
+# takes a lock on the item row that conflicts with sync_later's before it
+# reads the clock for the request: a sync created before that lock is older
+# than the request, and one created after it waits for the request to commit,
+# so its importer reads the request. The lock is FOR NO KEY UPDATE, taken
+# after the session's accounts are imported, so neither another authorization
+# nor a delete of the item deadlocks with it.
+#
+# Real threads on real connections, so this needs real commits.
+class EnableBankingItem::AuthorizationRequestConcurrencyTest < ActiveSupport::TestCase
+ self.use_transactional_tests = false
+
+ setup do
+ @item = EnableBankingItem.create!(
+ family: families(:dylan_family),
+ name: "Concurrency",
+ country_code: "DE",
+ application_id: "app",
+ client_certificate: "cert",
+ session_id: "sess",
+ session_expires_at: 1.day.from_now,
+ status: :good
+ )
+ end
+
+ teardown do
+ Sync.where(syncable: @item).delete_all
+ EnableBankingAccount.where(enable_banking_item_id: @item.id).delete_all
+ EnableBankingItem.where(id: @item.id).delete_all
+ end
+
+ test "a sync created while the authorization waits for the item lock is older than its request" do
+ authorizing = EnableBankingItem.find(@item.id)
+ provider = mock
+ provider.stubs(:create_session).returns(session_id: "new_sess", accounts: [])
+ authorizing.stubs(:enable_banking_provider).returns(provider)
+ session_saved = Concurrent::CountDownLatch.new(1)
+ authorization_pid = Concurrent::IVar.new
+ locked = Concurrent::CountDownLatch.new(1)
+ # Pause once the session is stored, before the transaction that writes
+ # the request.
+ authorizing.define_singleton_method(:update!) do |attributes|
+ super(attributes).tap do
+ next unless attributes.key?(:session_id)
+
+ session_saved.count_down
+ raise "the other connection never took the item lock" unless locked.wait(5)
+ end
+ end
+
+ authorization = Thread.new do
+ ActiveRecord::Base.connection_pool.with_connection do
+ authorization_pid.set(ActiveRecord::Base.connection.select_value("SELECT pg_backend_pid()"))
+ authorizing.complete_authorization(code: "code")
+ end
+ end
+ # Another request's sync_later: it takes the item lock at that point, and
+ # creates its sync only once the authorization is blocked on that lock.
+ other = Thread.new do
+ ActiveRecord::Base.connection_pool.with_connection do
+ raise "the authorization never stored the session" unless session_saved.wait(5)
+
+ Sync.transaction do
+ EnableBankingItem.find(@item.id).lock!
+ locked.count_down
+ wait_until_blocked(authorization_pid.value(5))
+ @item.syncs.create!(status: "syncing")
+ end
+ end
+ end
+ sync = other.value
+ authorization.value
+
+ # That sync's importer could have read the request before it committed.
+ # Once it finishes, the post-sync check must still queue a follow-up.
+ sync.update!(status: "completed", completed_at: Time.current)
+ assert_operator @item.reload.full_history_fetch_requested_at, :>, sync.created_at,
+ "the request predates a sync that may not have seen it"
+ assert_difference -> { @item.syncs.count }, 1 do
+ EnableBankingItem::Syncer.new(@item).perform_post_sync
+ end
+ end
+
+ test "two authorizations that import distinct accounts both complete" do
+ first = authorizing_with(uid: "acct_first")
+ second = authorizing_with(uid: "acct_second")
+ second_pid = Concurrent::IVar.new
+ second_done = Concurrent::CountDownLatch.new(1)
+ blocked = method(:blocked?)
+ wait_until = method(:wait_until)
+ first_imported = Concurrent::CountDownLatch.new(1)
+ # The first authorization pauses after inserting its account, until the
+ # second has either finished or is waiting on it. Each insert's foreign key
+ # check holds KEY SHARE on the item row, so a lock that conflicts with KEY
+ # SHARE (FOR UPDATE) would leave each waiting for the other.
+ first.define_singleton_method(:import_accounts_from_session) do |accounts|
+ super(accounts).tap do
+ first_imported.count_down
+ wait_until.call("the second authorization neither finished nor waited") do
+ second_done.count.zero? || blocked.call(second_pid.value(5))
+ end
+ end
+ end
+
+ one = Thread.new do
+ ActiveRecord::Base.connection_pool.with_connection do
+ first.complete_authorization(code: "code")
+ end
+ end
+ two = Thread.new do
+ ActiveRecord::Base.connection_pool.with_connection do
+ second_pid.set(ActiveRecord::Base.connection.select_value("SELECT pg_backend_pid()"))
+ raise "the first authorization never imported its account" unless first_imported.wait(5)
+
+ second.complete_authorization(code: "code")
+ ensure
+ second_done.count_down
+ end
+ end
+
+ assert_empty thread_errors(one, two)
+ assert_equal %w[acct_first acct_second],
+ EnableBankingAccount.where(enable_banking_item_id: @item.id).order(:uid).pluck(:uid)
+ assert_not_nil @item.reload.full_history_fetch_requested_at
+ end
+
+ test "a second authorization waits while the first holds the item lock" do
+ first = authorizing_with(uid: "acct_first")
+ second = authorizing_with(uid: "acct_second")
+ second_pid = Concurrent::IVar.new
+ wait_until_blocked = method(:wait_until_blocked)
+ first_locked = Concurrent::CountDownLatch.new(1)
+ first_requested_at = Concurrent::IVar.new
+ # The first authorization pauses with the item lock held, just before it
+ # writes the request.
+ first.define_singleton_method(:update!) do |attributes|
+ if attributes.key?(:full_history_fetch_requested_at)
+ first_requested_at.set(attributes[:full_history_fetch_requested_at])
+ first_locked.count_down
+ wait_until_blocked.call(second_pid.value(5))
+ end
+ super(attributes)
+ end
+
+ one = Thread.new do
+ ActiveRecord::Base.connection_pool.with_connection do
+ first.complete_authorization(code: "code")
+ end
+ end
+ two = Thread.new do
+ ActiveRecord::Base.connection_pool.with_connection do
+ second_pid.set(ActiveRecord::Base.connection.select_value("SELECT pg_backend_pid()"))
+ raise "the first authorization never took the item lock" unless first_locked.wait(5)
+
+ second.complete_authorization(code: "code")
+ end
+ end
+
+ assert_empty thread_errors(one, two)
+ assert_operator @item.reload.full_history_fetch_requested_at, :>, first_requested_at.value,
+ "the second request was not written after the first"
+ end
+
+ test "a sync_later waiting on the account import's KEY SHARE lock creates its sync after the request" do
+ authorizing = authorizing_with(uid: "acct_new")
+ other_pid = Concurrent::IVar.new
+ wait_until_blocked = method(:wait_until_blocked)
+ imported = Concurrent::CountDownLatch.new(1)
+ # The authorization pauses after inserting the account, until sync_later's
+ # FOR UPDATE waits on its KEY SHARE lock, then takes the item lock itself.
+ authorizing.define_singleton_method(:import_accounts_from_session) do |accounts|
+ super(accounts).tap do
+ imported.count_down
+ wait_until_blocked.call(other_pid.value(5))
+ end
+ end
+
+ authorization = Thread.new do
+ ActiveRecord::Base.connection_pool.with_connection do
+ authorizing.complete_authorization(code: "code")
+ end
+ end
+ other = Thread.new do
+ ActiveRecord::Base.connection_pool.with_connection do
+ other_pid.set(ActiveRecord::Base.connection.select_value("SELECT pg_backend_pid()"))
+ raise "the authorization never imported its account" unless imported.wait(5)
+
+ EnableBankingItem.find(@item.id).sync_later
+ end
+ end
+
+ assert_empty thread_errors(authorization, other)
+ sync = @item.syncs.ordered.first
+ assert_operator sync.created_at, :>, @item.reload.full_history_fetch_requested_at
+ end
+
+ test "deleting the item while it is re-authorized does not deadlock" do
+ EnableBankingAccount.create!(enable_banking_item: @item, uid: "acct_stored", name: "Stored", currency: "EUR")
+ authorizing = authorizing_with(uid: "acct_stored")
+ deleting = EnableBankingItem.find(@item.id)
+ authorization_pid = Concurrent::IVar.new
+ wait_until_blocked = method(:wait_until_blocked)
+ accounts_deleted = Concurrent::CountDownLatch.new(1)
+ # The delete removes the item's account rows first (dependent: :destroy),
+ # then pauses before deleting the item row until the authorization waits
+ # on it.
+ deleting.define_singleton_method(:destroy_row) do
+ accounts_deleted.count_down
+ wait_until_blocked.call(authorization_pid.value(5))
+ super()
+ end
+
+ deletion = Thread.new do
+ ActiveRecord::Base.connection_pool.with_connection do
+ deleting.destroy!
+ end
+ end
+ authorization = Thread.new do
+ Thread.current.report_on_exception = false
+ ActiveRecord::Base.connection_pool.with_connection do
+ authorization_pid.set(ActiveRecord::Base.connection.select_value("SELECT pg_backend_pid()"))
+ raise "the delete never removed the accounts" unless accounts_deleted.wait(5)
+
+ authorizing.complete_authorization(code: "code")
+ end
+ end
+
+ assert_empty thread_errors(deletion)
+ # The authorization then finds the item gone.
+ assert_empty thread_errors(authorization).grep(/Deadlocked/)
+ assert_not EnableBankingItem.exists?(@item.id), "the item was not deleted"
+ end
+
+ private
+
+ def authorizing_with(uid:)
+ item = EnableBankingItem.find(@item.id)
+ provider = mock
+ provider.stubs(:create_session).returns(
+ session_id: "new_sess", accounts: [ { uid: uid, name: "Account #{uid}", currency: "EUR" } ]
+ )
+ item.stubs(:enable_banking_provider).returns(provider)
+ item
+ end
+
+ def thread_errors(*threads)
+ threads.filter_map do |thread|
+ thread.value
+ nil
+ rescue => e
+ "#{e.class}: #{e.message}"
+ end
+ end
+
+ def blocked?(pid)
+ ActiveRecord::Base.connection.select_value("SELECT cardinality(pg_blocking_pids(#{Integer(pid)}))").to_i.positive?
+ end
+
+ def wait_until(message)
+ deadline = 5.seconds.from_now
+ until yield
+ raise message if Time.current > deadline
+ sleep 0.01
+ end
+ end
+
+ def wait_until_blocked(pid)
+ wait_until("the other connection never waited on a lock") { blocked?(pid) }
+ end
+end
diff --git a/test/models/enable_banking_item/importer_early_fetch_test.rb b/test/models/enable_banking_item/importer_early_fetch_test.rb
new file mode 100644
index 0000000000..368f94edd4
--- /dev/null
+++ b/test/models/enable_banking_item/importer_early_fetch_test.rb
@@ -0,0 +1,480 @@
+require "test_helper"
+
+class EnableBankingItem::ImporterEarlyFetchTest < ActiveSupport::TestCase
+ setup do
+ @family = families(:dylan_family)
+ @item = EnableBankingItem.create!(
+ family: @family, name: "Test EB", country_code: "FR", application_id: "app",
+ client_certificate: "cert", session_id: "sess", session_expires_at: 1.day.from_now
+ )
+ @eba = EnableBankingAccount.create!(
+ enable_banking_item: @item, name: "Compte", uid: "early_uid", account_id: "early-uuid", currency: "EUR"
+ )
+ @requests = []
+ Setting.stubs(:syncs_include_pending).returns(false)
+ @item.stubs(:upsert_enable_banking_snapshot!)
+ end
+
+ test "complete_authorization requests a full-history fetch" do
+ provider = mock()
+ provider.stubs(:create_session).returns(session_id: "new_sess", accounts: [])
+ @item.stubs(:enable_banking_provider).returns(provider)
+
+ freeze_time do
+ @item.complete_authorization(code: "code")
+
+ assert_equal Time.current, @item.reload.full_history_fetch_requested_at
+ end
+ end
+
+ test "complete_authorization writes the request only after the session's accounts exist" do
+ provider = mock()
+ provider.stubs(:create_session).returns(
+ session_id: "new_sess", accounts: [ { uid: "session_uid", account_id: { iban: "FR7630006000011234567890189" }, currency: "EUR" } ] # pipelock:ignore IBAN
+ )
+ @item.stubs(:enable_banking_provider).returns(provider)
+
+ @item.complete_authorization(code: "code")
+
+ account = @item.enable_banking_accounts.find_by!(uid: "session_uid")
+ assert_operator @item.reload.full_history_fetch_requested_at, :>=, account.created_at,
+ "a sync can see the request before the session's accounts are imported"
+ end
+
+ test "an account import that fails part-way leaves no account without the request" do
+ provider = mock()
+ provider.stubs(:create_session).returns(
+ session_id: "new_sess",
+ accounts: [ { uid: "ok_uid", currency: "EUR" }, { uid: "failing_uid", currency: "EUR" } ]
+ )
+ @item.stubs(:enable_banking_provider).returns(provider)
+ # The second account fails validation.
+ EnableBankingAccount.any_instance.stubs(:build_account_name).returns("Ok").then.returns(nil)
+
+ assert_raises(ActiveRecord::RecordInvalid) { @item.complete_authorization(code: "code") }
+
+ assert_nil @item.enable_banking_accounts.find_by(uid: "ok_uid"),
+ "an imported account was committed without a full-history request"
+ assert_nil @item.reload.full_history_fetch_requested_at
+ end
+
+ test "the sync after an authorization fetches unlinked accounts once with strategy=longest" do
+ request_full_history!
+
+ build_importer(transactions: [ tx("old", "2019-01-01"), tx("new", 2.days.ago.to_date.iso8601) ]).import
+
+ assert_equal 1, @requests.size
+ assert_equal "longest", @requests.first[:strategy]
+ assert_nil @requests.first[:date_from]
+ assert_equal 2, @eba.reload.raw_transactions_payload.size
+ assert_not_nil @eba.early_fetched_at
+ assert_nil @item.reload.full_history_fetch_requested_at
+
+ build_importer.import
+ assert_equal 1, @requests.size, "an unlinked account is fetched again on a routine sync"
+ end
+
+ test "an early longest fetch keeps two booked rows that share a transaction_id apart once linked" do
+ request_full_history!
+ old_row = tx("shared", "2020-03-02", amount: "12.00").merge(entry_reference: "ref_2020")
+ new_row = tx("shared", 3.days.ago.to_date.iso8601, amount: "30.00").merge(entry_reference: "ref_now")
+
+ sync_import(build_importer(transactions: [ old_row, new_row ]))
+ assert_equal "longest", @requests.first[:strategy]
+ assert_equal 2, @eba.reload.raw_transactions_payload.size
+
+ account = link!
+ EnableBankingAccount::Transactions::Processor.new(@eba).process
+
+ assert_equal 2, account.entries.count, "a row sharing a transaction_id overwrote the other"
+ assert_equal [ 12, 30 ], account.entries.order(:date).map { |entry| entry.amount.to_i }
+ assert_equal 2, account.entries.distinct.count(:external_id)
+ end
+
+ test "a routine sync does not fetch unlinked accounts" do
+ Sync.create!(syncable: @item, status: "completed", completed_at: 60.days.ago, created_at: 60.days.ago)
+
+ build_importer(transactions: [ tx("old", "2019-01-01") ]).import
+
+ assert_empty @requests
+ assert_nil @eba.reload.raw_transactions_payload
+ end
+
+ test "a failing unlinked account is retried only while the request is fresh, and never fails the sync" do
+ request_full_history!
+ calls = 0
+ provider = mock()
+ provider.stubs(:get_account_balances).returns(balances: [])
+ provider.stubs(:get_account_transactions).with { |_| calls += 1; true }
+ .raises(Provider::EnableBanking::EnableBankingError.new("forbidden", :forbidden))
+ importer = EnableBankingItem::Importer.new(@item, enable_banking_provider: provider)
+ importer.stubs(:fetch_session_data).returns(accounts: [])
+
+ results = Array.new(2) { importer.import }
+ assert_equal 2, calls
+ assert results.all? { |result| result[:success] }, "a failed early fetch fails the sync"
+ assert_not_nil @item.reload.full_history_fetch_requested_at
+
+ warnings = []
+ Rails.logger.stubs(:warn).with { |msg| warnings << msg.to_s; true }
+ travel EnableBankingItem::Importer::FULL_HISTORY_REQUEST_WINDOW + 1.minute do
+ importer.import
+ end
+ assert_equal 2, calls, "an expired request is still retried"
+ assert warnings.any? { |msg| msg.include?("Dropping the full-history request") }, "no log line for the dropped request"
+ assert_nil @item.reload.full_history_fetch_requested_at
+ end
+
+ test "an authorization completed mid-sync keeps its full-history request" do
+ request_full_history!(5.minutes.ago)
+ item = @item
+ requests = @requests
+ provider = Object.new
+ provider.define_singleton_method(:get_account_balances) { |**| { balances: [] } }
+ provider.define_singleton_method(:get_account_transactions) do |**p|
+ requests << p
+ raise Provider::EnableBanking::EnableBankingError.new("timeout", :timeout) if p[:account_id] == "new-uuid"
+
+ unless EnableBankingAccount.exists?(uid: "new_uid")
+ # The OAuth callback of a new authorization commits while this sync runs.
+ EnableBankingAccount.create!(enable_banking_item: item, name: "New", uid: "new_uid", account_id: "new-uuid", currency: "EUR")
+ EnableBankingItem.where(id: item.id).update_all(session_id: "new_sess", full_history_fetch_requested_at: Time.current)
+ end
+ { transactions: [] }
+ end
+ importer = EnableBankingItem::Importer.new(@item, enable_banking_provider: provider)
+ importer.stubs(:fetch_session_data).returns(accounts: [])
+ importer.import
+
+ assert_equal %w[early-uuid new-uuid], @requests.map { |p| p[:account_id] }
+ assert_not_nil EnableBankingItem.find(item.id).full_history_fetch_requested_at,
+ "new authorization's request was consumed by the old sync"
+ end
+
+ test "an authorization completed after the early fetch is handled in the same sync" do
+ link!
+ @eba.update!(raw_transactions_payload: [ tx("stored", 3.days.ago.to_date.iso8601) ])
+ item = @item
+ requests = @requests
+ provider = Object.new
+ provider.define_singleton_method(:get_account_balances) { |**| { balances: [] } }
+ provider.define_singleton_method(:get_account_transactions) do |**p|
+ requests << p
+ if p[:account_id] == "early-uuid" && !EnableBankingAccount.exists?(uid: "new_uid")
+ # The OAuth callback commits while the linked account is fetched; its
+ # sync_later reuses this sync.
+ EnableBankingAccount.create!(enable_banking_item: item, name: "New", uid: "new_uid", account_id: "new-uuid", currency: "EUR")
+ EnableBankingItem.where(id: item.id).update_all(full_history_fetch_requested_at: Time.current)
+ end
+ { transactions: [] }
+ end
+ importer = EnableBankingItem::Importer.new(@item, enable_banking_provider: provider)
+ importer.stubs(:fetch_session_data).returns(accounts: [])
+ importer.import
+
+ new_account_request = @requests.find { |p| p[:account_id] == "new-uuid" }
+ assert new_account_request, "the new authorization's account waited for the next sync"
+ assert_equal "longest", new_account_request[:strategy]
+ assert_nil @item.reload.full_history_fetch_requested_at
+ end
+
+ test "a truncated early fetch is counted as truncated" do
+ request_full_history!
+ provider = Object.new
+ provider.define_singleton_method(:get_account_balances) { |**| { balances: [] } }
+ provider.define_singleton_method(:get_account_transactions) do |**|
+ { transactions: [ { transaction_id: "a", booking_date: "2020-01-01", status: "BOOK",
+ transaction_amount: { amount: "1.00", currency: "EUR" }, credit_debit_indicator: "DBIT" } ],
+ continuation_key: "same" }
+ end
+ importer = EnableBankingItem::Importer.new(@item, enable_banking_provider: provider)
+ importer.stubs(:fetch_session_data).returns(accounts: [])
+
+ result = importer.import
+
+ assert_equal 1, result[:transactions_truncated]
+ assert_equal 1, @eba.reload.raw_transactions_payload.size
+ end
+
+ test "a failed early fetch stores only sanitized error fields in the debug log" do
+ request_full_history!
+ errors = [
+ Provider::EnableBanking::EnableBankingError.new("BODY-MARKER raw response", :validation_error,
+ response_data: { message: "Invalid account" }),
+ StandardError.new("OTHER-MARKER raw response")
+ ]
+ provider = Object.new
+ provider.define_singleton_method(:get_account_balances) { |**| { balances: [] } }
+ provider.define_singleton_method(:get_account_transactions) { |**| raise errors.shift }
+ importer = EnableBankingItem::Importer.new(@item, enable_banking_provider: provider)
+ importer.stubs(:fetch_session_data).returns(accounts: [])
+
+ 2.times { importer.import }
+
+ provider_entry, other_entry = DebugLogEntry.where(provider_key: "enable_banking").order(:created_at).last(2)
+ assert_not_includes provider_entry.metadata.to_json, "BODY-MARKER"
+ assert_equal "Invalid account", provider_entry.metadata.dig("provider_error", "message")
+ assert_not_includes other_entry.metadata.to_json, "OTHER-MARKER"
+ assert_equal "StandardError", other_entry.metadata["error_class"]
+ end
+
+ test "rows of an early fetch are never stored without early_fetched_at" do
+ request_full_history!
+ EnableBankingAccount.any_instance.stubs(:update_columns).raises(ActiveRecord::StatementInvalid.new("write failed"))
+
+ build_importer(transactions: [ tx("a", "2020-01-01") ]).import
+
+ assert_nil @eba.reload.raw_transactions_payload, "rows stored that the purge can never delete"
+ assert_not_nil @item.reload.full_history_fetch_requested_at
+ end
+
+ test "the early fetch runs before the linked accounts are fetched" do
+ linked = EnableBankingAccount.create!(
+ enable_banking_item: @item, name: "Linked", uid: "linked_uid", account_id: "linked-uuid", currency: "EUR",
+ raw_transactions_payload: [ tx("stored", 3.days.ago.to_date.iso8601) ]
+ )
+ link!(linked)
+ request_full_history!
+
+ build_importer.import
+
+ assert_equal %w[early-uuid linked-uuid], @requests.map { |p| p[:account_id] }
+ assert_equal "longest", @requests.first[:strategy]
+ end
+
+ test "a failed early fetch is captured as a debug log entry" do
+ request_full_history!
+ provider = mock()
+ provider.stubs(:get_account_balances).returns(balances: [])
+ provider.stubs(:get_account_transactions)
+ .raises(Provider::EnableBanking::EnableBankingError.new("forbidden", :forbidden))
+ importer = EnableBankingItem::Importer.new(@item, enable_banking_provider: provider)
+ importer.stubs(:fetch_session_data).returns(accounts: [])
+
+ assert_difference -> { DebugLogEntry.where(provider_key: "enable_banking", category: "provider_sync_error").count }, 1 do
+ importer.import
+ end
+
+ entry = DebugLogEntry.last
+ assert_equal @family, entry.family
+ assert_equal "early_uid", entry.metadata["uid"]
+ assert_equal "forbidden", entry.metadata.dig("provider_error", "error_type")
+ end
+
+ test "a failing purge is captured in provider diagnostics and does not raise" do
+ @eba.update_columns(raw_transactions_payload: [ tx("a", "2020-01-01") ], early_fetched_at: 10.days.ago)
+ ActiveRecord::Relation.any_instance.stubs(:update_all).raises(ActiveRecord::StatementInvalid, "lock timeout")
+
+ assert_difference -> { DebugLogEntry.where(provider_key: "enable_banking", category: "provider_sync_error").count }, 1 do
+ assert_nothing_raised { build_importer.purge_stale_unlinked_transactions }
+ end
+
+ entry = DebugLogEntry.where(provider_key: "enable_banking").order(:created_at).last
+ assert_equal @family, entry.family
+ assert_equal "EnableBankingItem::Importer", entry.source
+ assert_equal @item.id, entry.metadata["enable_banking_item_id"]
+ assert_equal "ActiveRecord::StatementInvalid", entry.metadata["error_class"]
+ assert_not_nil @eba.reload.raw_transactions_payload
+ end
+
+ test "a re-authorization does not refetch accounts that already have rows" do
+ Sync.create!(syncable: @item, status: "completed", completed_at: 1.day.ago, created_at: 1.day.ago)
+ link!
+ @eba.update!(raw_transactions_payload: [ tx("stored", 3.days.ago.to_date.iso8601) ])
+ # Unlinked by the user, rows kept.
+ unlinked = EnableBankingAccount.create!(
+ enable_banking_item: @item, name: "Unlinked", uid: "unlinked_uid", account_id: "unlinked-uuid", currency: "EUR",
+ raw_transactions_payload: [ tx("kept", 30.days.ago.to_date.iso8601) ]
+ )
+ request_full_history!
+
+ build_importer(transactions: [ tx("old", "2019-01-01"), tx("stored", 3.days.ago.to_date.iso8601) ]).import
+
+ assert_equal 1, @requests.size, "an account with stored rows was fetched again"
+ assert_nil @requests.first[:strategy], "a linked account got a longest fetch after a re-authorization"
+ assert_equal %w[stored], @eba.reload.raw_transactions_payload.map { |row| row["transaction_id"] }
+ assert_equal %w[kept], unlinked.reload.raw_transactions_payload.map { |row| row["transaction_id"] }
+ assert_nil @item.reload.full_history_fetch_requested_at
+ end
+
+ test "a re-authorization does not fetch an account the user ignored" do
+ @eba.ignore!
+ request_full_history!
+
+ build_importer(transactions: [ tx("old", "2019-01-01") ]).import
+
+ assert_empty @requests, "an ignored account was fetched"
+ assert_nil @eba.reload.raw_transactions_payload
+ assert_nil @eba.early_fetched_at
+ assert_nil @item.reload.full_history_fetch_requested_at
+ end
+
+ test "a failed linked fetch does not keep the request" do
+ link!
+ @eba.update!(raw_transactions_payload: [ tx("a", 3.days.ago.to_date.iso8601) ])
+ request_full_history!
+ provider = mock()
+ provider.stubs(:get_account_balances).returns(balances: [])
+ provider.stubs(:get_account_transactions)
+ .raises(Provider::EnableBanking::EnableBankingError.new("Request timeout", :timeout))
+ importer = EnableBankingItem::Importer.new(@item, enable_banking_provider: provider)
+ importer.stubs(:fetch_session_data).returns(accounts: [])
+
+ importer.import
+
+ assert_nil @item.reload.full_history_fetch_requested_at
+ end
+
+ test "a request set after the in-memory item was loaded is still honoured" do
+ EnableBankingItem.where(id: @item.id).update_all(full_history_fetch_requested_at: Time.current)
+
+ build_importer.import
+
+ assert_equal "longest", @requests.first[:strategy]
+ end
+
+ test "the purge does not delete a payload fetched in the same sync" do
+ # Early-fetched after an earlier authorization and never linked.
+ @eba.update_columns(raw_transactions_payload: [ tx("a", "2020-01-01") ], early_fetched_at: 10.days.ago)
+ request_full_history!
+
+ sync_import(build_importer(transactions: [ tx("a", "2020-01-01") ]))
+
+ assert_equal "longest", @requests.first[:strategy]
+ assert_not_nil @eba.reload.raw_transactions_payload, "payload fetched seconds ago was purged"
+ assert_in_delta Time.current, @eba.early_fetched_at, 1.minute
+ end
+
+ test "early-fetched rows of an account that stays unlinked are deleted after the retention period" do
+ @eba.update_columns(raw_transactions_payload: [ tx("a", 9.days.ago.to_date.iso8601) ], early_fetched_at: 8.days.ago)
+ recent = EnableBankingAccount.create!(
+ enable_banking_item: @item, name: "Recent", uid: "recent_uid", account_id: "recent-uuid", currency: "EUR",
+ raw_transactions_payload: [ tx("b", 2.days.ago.to_date.iso8601) ], early_fetched_at: 2.days.ago
+ )
+ linked = EnableBankingAccount.create!(
+ enable_banking_item: @item, name: "Linked", uid: "linked_uid", account_id: "linked-uuid", currency: "EUR",
+ raw_transactions_payload: [ tx("c", 20.days.ago.to_date.iso8601) ], early_fetched_at: 30.days.ago
+ )
+ link!(linked)
+ # Unlinked by the user, so its rows were not stored by an early fetch.
+ unlinked = EnableBankingAccount.create!(
+ enable_banking_item: @item, name: "Unlinked", uid: "unlinked_uid", account_id: "unlinked-uuid", currency: "EUR",
+ raw_transactions_payload: [ tx("d", 20.days.ago.to_date.iso8601) ]
+ )
+ unlinked.update_columns(updated_at: 30.days.ago)
+
+ sync_import(build_importer)
+
+ assert_nil @eba.reload.raw_transactions_payload
+ assert_nil @eba.early_fetched_at
+ assert_equal 1, recent.reload.raw_transactions_payload.size
+ assert_equal 1, linked.reload.raw_transactions_payload.size
+ assert_equal 1, unlinked.reload.raw_transactions_payload.size
+ end
+
+ test "an early-fetched account that was linked keeps its rows after it is unlinked" do
+ @eba.update_columns(raw_transactions_payload: [ tx("a", 20.days.ago.to_date.iso8601) ], early_fetched_at: 1.day.ago)
+ account = link!
+ EnableBankingAccount::Transactions::Processor.new(@eba).process
+ assert_equal 1, account.entries.count
+ assert_nil @eba.reload.early_fetched_at
+
+ AccountProvider.where(provider: @eba).destroy_all
+ travel EnableBankingItem::Importer::UNLINKED_TRANSACTIONS_RETENTION + 1.day do
+ sync_import(build_importer)
+ end
+
+ assert_equal 1, @eba.reload.raw_transactions_payload.size, "rows of a once-linked account were purged"
+
+ # Relinking is incremental, as before.
+ AccountProvider.create!(account: account, provider: @eba.reload)
+ sync_import(build_importer)
+ assert_nil @requests.last[:strategy]
+ end
+
+ test "rows before a sync_start_date set mid-sync are not imported" do
+ account = link!
+ @eba.update!(raw_transactions_payload: [ tx("old", 2.years.ago.to_date.iso8601), tx("new", 5.days.ago.to_date.iso8601) ])
+ stale_item = EnableBankingItem.find(@item.id)
+ stale_item.enable_banking_accounts.to_a # loaded at sync start
+ EnableBankingItem.find(@item.id).update!(sync_start_date: 30.days.ago.to_date) # setup modal submitted
+
+ stale_item.process_accounts
+
+ assert_equal 1, account.entries.count, "rows before the chosen start date were imported"
+ end
+
+
+ test "an account linked but not yet processed keeps its early rows when unlinked" do
+ @item.update!(session_expires_at: 30.days.from_now)
+ request_full_history!
+ sync_import(build_importer(transactions: [ tx("old", "2019-01-01"), tx("new", 2.days.ago.to_date.iso8601) ]))
+ assert_not_nil @eba.reload.early_fetched_at
+
+ account = link!
+ # Syncs after the link fail before process_accounts (another account's
+ # fetch fails), but the import itself still runs.
+ travel 3.days do
+ sync_import(build_importer)
+ end
+
+ travel 8.days do
+ AccountProvider.where(provider: @eba).destroy_all # user unlinks to retry
+ sync_import(build_importer)
+ end
+
+ assert_equal 2, @eba.reload.raw_transactions_payload.to_a.size,
+ "full history of an account the user linked was purged after an unlink"
+ assert account.persisted?
+ end
+
+
+ test "an account linked then deleted before any processing is still purged" do
+ @item.update!(session_expires_at: 30.days.from_now)
+ request_full_history!
+ sync_import(build_importer(transactions: [ tx("old", "2019-01-01") ]))
+ account = link!
+ account.update_columns(status: "pending_deletion")
+ travel 1.hour do
+ sync_import(build_importer)
+ end
+ account.destroy!
+ travel 8.days do
+ sync_import(build_importer)
+ end
+ assert_nil @eba.reload.raw_transactions_payload, "rows of a deleted, never-processed account were kept"
+ end
+
+ private
+ # What the syncer does: purge stale early rows, then import.
+ def sync_import(importer)
+ importer.purge_stale_unlinked_transactions
+ importer.import
+ end
+
+ def build_importer(transactions: [])
+ requests = @requests
+ provider = mock()
+ provider.stubs(:get_account_balances).returns(balances: [])
+ provider.stubs(:get_account_transactions).with { |params| requests << params; true }.returns(transactions: transactions)
+ importer = EnableBankingItem::Importer.new(@item, enable_banking_provider: provider)
+ importer.stubs(:fetch_session_data).returns(accounts: [])
+ importer
+ end
+
+ def request_full_history!(at = Time.current)
+ @item.update!(full_history_fetch_requested_at: at)
+ end
+
+ def link!(enable_banking_account = @eba)
+ account = Account.create!(family: @family, name: "Linked", balance: 0, currency: "EUR", accountable: Depository.create!)
+ AccountProvider.create!(account: account, provider: enable_banking_account)
+ enable_banking_account.reload
+ account
+ end
+
+ def tx(id, date, amount: "10.00")
+ { transaction_id: id, entry_reference: "ref_#{id}", booking_date: date,
+ transaction_amount: { amount: amount, currency: "EUR" }, credit_debit_indicator: "DBIT", status: "BOOK" }
+ end
+end
diff --git a/test/models/enable_banking_item/syncer_test.rb b/test/models/enable_banking_item/syncer_test.rb
index 54328b161c..196b4f64cb 100644
--- a/test/models/enable_banking_item/syncer_test.rb
+++ b/test/models/enable_banking_item/syncer_test.rb
@@ -29,6 +29,123 @@ class EnableBankingItem::SyncerTest < ActiveSupport::TestCase
"Expired session should be a graceful reconnect state, not a red sync error"
end
+ test "an expired session still purges stale early-fetched rows" do
+ eba = EnableBankingAccount.create!(
+ enable_banking_item: @item, name: "Skipped", uid: "skipped_uid", account_id: "skipped-uuid", currency: "EUR"
+ )
+ eba.update_columns(raw_transactions_payload: [ { transaction_id: "a", booking_date: "2020-01-01" } ],
+ early_fetched_at: (EnableBankingItem::Importer::UNLINKED_TRANSACTIONS_RETENTION + 1.day).ago)
+
+ @syncer.perform_sync(Sync.create!(syncable: @item))
+
+ assert_nil eba.reload.raw_transactions_payload, "early rows outlived the retention while the session was expired"
+ end
+
+ test "a sync whose session the bank rejects still purges stale early-fetched rows" do
+ @item.update!(session_expires_at: 1.day.from_now)
+ eba = EnableBankingAccount.create!(
+ enable_banking_item: @item, name: "Skipped", uid: "skipped_uid", account_id: "skipped-uuid", currency: "EUR"
+ )
+ eba.update_columns(raw_transactions_payload: [ { transaction_id: "a", booking_date: "2020-01-01" } ],
+ early_fetched_at: (EnableBankingItem::Importer::UNLINKED_TRANSACTIONS_RETENTION + 1.day).ago)
+ # A session revoked at the bank: valid locally, but GET /sessions fails.
+ @item.stubs(:import_latest_enable_banking_data).returns(success: false, error: "Session invalid")
+
+ assert_raises(StandardError) { @syncer.perform_sync(Sync.create!(syncable: @item)) }
+
+ assert_nil eba.reload.raw_transactions_payload, "early rows outlived the retention while the bank rejected the session"
+ end
+
+ test "post-sync queues one more sync for a request that arrived after the last sync" do
+ Sync.create!(syncable: @item, status: "completed", completed_at: 1.minute.ago, created_at: 3.minutes.ago)
+ # Written by the callback in another process; the syncer's item is not reloaded.
+ EnableBankingItem.where(id: @item.id).update_all(full_history_fetch_requested_at: 2.minutes.ago)
+
+ assert_difference -> { @item.syncs.count }, 1 do
+ @syncer.perform_post_sync
+ end
+ end
+
+ test "post-sync queues the follow-up sync only after the finalization transaction commits" do
+ sync = Sync.create!(syncable: @item, status: "syncing", created_at: 3.minutes.ago)
+ EnableBankingItem.where(id: @item.id).update_all(full_history_fetch_requested_at: 2.minutes.ago)
+ # Transactions this code could still join when sync_later runs. The test's
+ # own transaction can't be joined, so none means the finalization committed.
+ open_transactions = []
+ @item.define_singleton_method(:sync_later) do |*args, **kwargs|
+ open_transactions << ActiveRecord.all_open_transactions.size
+ super(*args, **kwargs)
+ end
+
+ Sync.transaction do
+ sync.lock!
+ sync.update!(status: "completed", completed_at: Time.current)
+ @syncer.perform_post_sync
+ assert_equal 1, @item.syncs.count, "sync_later ran while the sync row lock was held"
+ end
+
+ assert_equal 2, @item.syncs.count
+ assert_equal [ 0 ], open_transactions, "sync_later ran before the finalization transaction committed"
+
+ # A request newer than every sync, so only the rollback can stop sync_later.
+ @item.syncs.update_all(created_at: 1.minute.ago)
+ EnableBankingItem.where(id: @item.id).update_all(full_history_fetch_requested_at: Time.current)
+ open_transactions.clear
+
+ Sync.transaction do
+ @syncer.perform_post_sync
+ raise ActiveRecord::Rollback
+ end
+ assert_empty open_transactions, "sync_later ran although the finalization transaction rolled back"
+
+ # The same request outside a transaction does queue, so the check above can fail.
+ @syncer.perform_post_sync
+ assert_equal [ 0 ], open_transactions
+ end
+
+ test "post-sync sees a request committed after it was called but before finalization commits" do
+ sync = Sync.create!(syncable: @item, status: "syncing", created_at: 3.minutes.ago)
+
+ Sync.transaction do
+ sync.lock!
+ sync.update!(status: "completed", completed_at: Time.current)
+ @syncer.perform_post_sync
+ # The callback commits its request now; its sync_later reused this sync.
+ EnableBankingItem.where(id: @item.id).update_all(full_history_fetch_requested_at: Time.current)
+ end
+
+ assert_equal 2, @item.syncs.count, "the late request waited for a later sync"
+ end
+
+ test "an error queueing the follow-up sync is reported and the parent sync still finalizes" do
+ family_sync = Sync.create!(syncable: @item.family, status: "syncing")
+ item_sync = Sync.create!(syncable: @item, parent: family_sync, status: "syncing", created_at: 3.minutes.ago)
+ EnableBankingItem.where(id: @item.id).update_all(full_history_fetch_requested_at: 2.minutes.ago)
+ error = StandardError.new("redis down")
+ EnableBankingItem.any_instance.stubs(:sync_later).raises(error)
+ Sentry.expects(:capture_exception).with(error)
+
+ assert_nothing_raised { item_sync.finalize_if_all_children_finalized }
+
+ assert_equal "completed", item_sync.reload.status
+ assert_equal "completed", family_sync.reload.status
+ end
+
+ test "post-sync does not queue a sync for a request the last sync already saw, or a stale one" do
+ @item.update_columns(full_history_fetch_requested_at: 4.minutes.ago)
+ Sync.create!(syncable: @item, status: "completed", completed_at: 1.minute.ago, created_at: 3.minutes.ago)
+
+ assert_no_difference -> { @item.syncs.count } do
+ @syncer.perform_post_sync
+ end
+
+ @item.update_columns(full_history_fetch_requested_at: (EnableBankingItem::Importer::FULL_HISTORY_REQUEST_WINDOW + 1.minute).ago)
+ @item.syncs.update_all(created_at: 2.hours.ago)
+ assert_no_difference -> { @item.syncs.count } do
+ @syncer.perform_post_sync
+ end
+ end
+
test "ignored accounts do not leave the connection waiting for setup" do
@item.update!(session_expires_at: 1.day.from_now)
@item.enable_banking_accounts.create!(name: "Theirs", uid: "hash_theirs", currency: "EUR").ignore!