The personal finance app for everyone (by everyone)
Ruby
fix(providers): restore deletion flag when DestroyJob enqueue fails (#3562)
jaysbeekaybbccde10aa97
diff --git a/app/models/akahu_item.rb b/app/models/akahu_item.rbindex 5c550420db..897437336d 100644--- a/app/models/akahu_item.rb+++ b/app/models/akahu_item.rb@@ -1,5 +1,5 @@class AkahuItem < ApplicationRecord- include Syncable, Provided, Unlinking, Encryptable+ include Syncable, Provided, Unlinking, Encryptable, DestroyableLaterenum :status, { good: "good", requires_update: "requires_update" }, default: :good@@ -23,11 +23,6 @@ class AkahuItem < ApplicationRecordscope :ordered, -> { order(created_at: :desc) }scope :needs_update, -> { where(status: :requires_update) }- def destroy_later- update!(scheduled_for_deletion: true)- DestroyJob.perform_later(self)- end-def import_latest_akahu_dataprovider = akahu_providerunless providerdiff --git a/app/models/binance_item.rb b/app/models/binance_item.rbindex 7843dfd2e1..abb0528456 100644--- a/app/models/binance_item.rb+++ b/app/models/binance_item.rb@@ -1,7 +1,7 @@# frozen_string_literal: trueclass BinanceItem < ApplicationRecord- include Syncable, Provided, Unlinking, Encryptable+ include Syncable, Provided, Unlinking, Encryptable, DestroyableLaterenum :status, { good: "good", requires_update: "requires_update" }, default: :good@@ -27,11 +27,6 @@ class BinanceItem < ApplicationRecordscope :ordered, -> { order(created_at: :desc) }scope :needs_update, -> { where(status: :requires_update) }- def destroy_later- update!(scheduled_for_deletion: true)- DestroyJob.perform_later(self)- end-def import_latest_binance_dataprovider = binance_providerunless providerdiff --git a/app/models/brex_item.rb b/app/models/brex_item.rbindex 865797e65f..ab71d52fab 100644--- a/app/models/brex_item.rb+++ b/app/models/brex_item.rb@@ -1,5 +1,5 @@class BrexItem < ApplicationRecord- include Syncable, Provided, Unlinking, Encryptable+ include Syncable, Provided, Unlinking, Encryptable, DestroyableLaterBLANK_TOKEN_SENTINELS = [ "", " ", " ", " ", "\t", "\n", "\r" ].freeze@@ -40,11 +40,6 @@ class BrexItem < ApplicationRecordcredentialed_items.first if credentialed_items.one?end- def destroy_later- update!(scheduled_for_deletion: true)- DestroyJob.perform_later(self)- end-def import_latest_brex_data(sync_start_date: nil)provider = brex_providerunless providerdiff --git a/app/models/coinbase_item.rb b/app/models/coinbase_item.rbindex 0adf2fe118..45996e1cd2 100644--- a/app/models/coinbase_item.rb+++ b/app/models/coinbase_item.rb@@ -1,5 +1,5 @@class CoinbaseItem < ApplicationRecord- include Syncable, Provided, Unlinking+ include Syncable, Provided, Unlinking, DestroyableLaterinclude Encryptableenum :status, { good: "good", requires_update: "requires_update" }, default: :good@@ -26,11 +26,6 @@ class CoinbaseItem < ApplicationRecordscope :ordered, -> { order(created_at: :desc) }scope :needs_update, -> { where(status: :requires_update) }- def destroy_later- update!(scheduled_for_deletion: true)- DestroyJob.perform_later(self)- end-def import_latest_coinbase_dataprovider = coinbase_providerunless providerdiff --git a/app/models/coinspot_item.rb b/app/models/coinspot_item.rbindex 8b9bbca3fd..c27d09fa01 100644--- a/app/models/coinspot_item.rb+++ b/app/models/coinspot_item.rb@@ -1,7 +1,7 @@# frozen_string_literal: trueclass CoinspotItem < ApplicationRecord- include Syncable, Provided, Unlinking, Encryptable+ include Syncable, Provided, Unlinking, Encryptable, DestroyableLaterenum :status, { good: "good", requires_update: "requires_update" }, default: :good@@ -29,25 +29,6 @@ class CoinspotItem < ApplicationRecordbefore_validation :strip_credentials- # Marks the connection for asynchronous deletion rather than destroying it- # inline, so a large item with many accounts doesn't block the request.- # `active` excludes a flagged row, so if the enqueue never lands the- # connection disappears from the UI with no job coming to delete it and no- # way for the user to retry. DestroyJob's own rescue only covers failures- # once the job is *running*, which is the other side of this window.- # perform_later can both raise (Redis down) and return false (a rejecting- # enqueue callback), so both are restored.- def destroy_later- update!(scheduled_for_deletion: true)-- enqueued = DestroyJob.perform_later(self)- update!(scheduled_for_deletion: false) if enqueued == false- enqueued- rescue StandardError- update!(scheduled_for_deletion: false)- raise- end-# Fetches and imports this connection's latest balances and transaction# history from CoinSpot. Raises if credentials aren't configured or the# import itself fails -- callers (the syncer) are responsible for turningdiff --git a/app/models/coinstats_item.rb b/app/models/coinstats_item.rbindex 6a1bf82917..f22c420708 100644--- a/app/models/coinstats_item.rb+++ b/app/models/coinstats_item.rb@@ -1,7 +1,7 @@# Represents a CoinStats API connection for a family.# Stores credentials and manages associated wallet and exchange portfolio accounts.class CoinstatsItem < ApplicationRecord- include Syncable, Provided, Unlinking+ include Syncable, Provided, Unlinking, DestroyableLaterenum :status, { good: "good", requires_update: "requires_update" }, default: :good@@ -33,12 +33,6 @@ class CoinstatsItem < ApplicationRecordscope :ordered, -> { order(created_at: :desc) }scope :needs_update, -> { where(status: :requires_update) }- # Schedules this item for async deletion.- def destroy_later- update!(scheduled_for_deletion: true)- DestroyJob.perform_later(self)- end-# Fetches latest wallet data from CoinStats API and updates local records.# @raise [StandardError] if provider is not configured or import failsdef import_latest_coinstats_datadiff --git a/app/models/concerns/destroyable_later.rb b/app/models/concerns/destroyable_later.rbnew file mode 100644index 0000000000..2bc17d9c1d--- /dev/null+++ b/app/models/concerns/destroyable_later.rb@@ -0,0 +1,68 @@+# Asynchronous deletion for provider connections (the `*_item` models).+#+# `destroy_later` flags the row and enqueues DestroyJob. A flagged row drops out+# of `active` and `syncable`, so if the enqueue never lands the connection is+# left stuck: never synced again, shown as "Deletion in progress" indefinitely,+# with no job coming to delete it. DestroyJob's own rescue only covers a failure+# once the job is running; the enqueue side is handled here.+#+# perform_later can raise (the Sidekiq adapter re-raises RedisClient errors when+# Redis is unreachable) or return false (an enqueue callback aborting, or an+# adapter raising ActiveJob::EnqueueError). Both restore the flag.+#+# Both writes use update_column, skipping validations (item models declare no+# save callbacks for it to skip). Setting the flag must not fail on a validation+# unrelated to deletion: BrexItem checks base_url against an allowlist on every+# save, so a row that predates an allowlist change would otherwise be+# undeletable. Restoring it must not fail on one that depends on the flag --+# QuestradeItem skips its refresh_token presence check while+# scheduled_for_deletion is set -- and mask the enqueue error with its own.+#+# Don't call this inside a transaction: ApplicationJob defers enqueues until+# commit, so perform_later would return before the push is attempted and a+# failure would surface after this method has already returned.+module DestroyableLater+ extend ActiveSupport::Concern++ def destroy_later+ claimed = claim_scheduled_for_deletion++ enqueued = begin+ DestroyJob.perform_later(self)+ rescue StandardError+ restore_scheduled_for_deletion if claimed+ raise+ end++ # perform_later returns the job or false. Match false exactly: a bare mock of+ # perform_later returns nil, and treating that as a failure would clear the+ # flag in every test that only expects the enqueue.+ restore_scheduled_for_deletion if claimed && enqueued == false+ enqueued+ end++ private+ # Sets the flag under a row lock and reports whether this call set it.+ #+ # An item that is already flagged is still re-enqueued: that is how a+ # connection stuck by an earlier lost enqueue gets deleted. But a failure+ # here must not clear a flag an earlier request set, whose DestroyJob may+ # already be queued.+ #+ # The lock can't be held across the enqueue (see above), so one overlap+ # remains: this call claims, a concurrent call enqueues successfully, then+ # this call's enqueue fails and clears the flag. The queued DestroyJob still+ # destroys the item; the connection just reappears until it runs.+ def claim_scheduled_for_deletion+ with_lock do+ next false if scheduled_for_deletion?++ update_column(:scheduled_for_deletion, true)+ true+ end+ end++ def restore_scheduled_for_deletion+ update_column(:scheduled_for_deletion, false)+ end+enddiff --git a/app/models/enable_banking_item.rb b/app/models/enable_banking_item.rbindex 87af6ec78b..8916946fec 100644--- a/app/models/enable_banking_item.rb+++ b/app/models/enable_banking_item.rb@@ -1,5 +1,5 @@class EnableBankingItem < ApplicationRecord- include Syncable, Provided, Unlinking, Encryptable+ include Syncable, Provided, Unlinking, Encryptable, DestroyableLaterenum :status, { good: "good", requires_update: "requires_update" }, default: :good@@ -27,11 +27,6 @@ class EnableBankingItem < ApplicationRecordscope :ordered, -> { order(created_at: :desc) }scope :needs_update, -> { where(status: :requires_update) }- def destroy_later- update!(scheduled_for_deletion: true)- DestroyJob.perform_later(self)- end-def credentials_configured?application_id.present? && client_certificate.present? && country_code.present?enddiff --git a/app/models/ibkr_item.rb b/app/models/ibkr_item.rbindex 923debb1e1..c309485e1e 100644--- a/app/models/ibkr_item.rb+++ b/app/models/ibkr_item.rb@@ -1,5 +1,5 @@class IbkrItem < ApplicationRecord- include Syncable, Provided, Unlinking, Encryptable+ include Syncable, Provided, Unlinking, Encryptable, DestroyableLaterenum :status, { good: "good", requires_update: "requires_update" }, default: :good@@ -23,11 +23,6 @@ class IbkrItem < ApplicationRecordscope :ordered, -> { order(created_at: :desc) }scope :needs_update, -> { where(status: :requires_update) }- def destroy_later- update!(scheduled_for_deletion: true)- DestroyJob.perform_later(self)- end-def credentials_configured?query_id.present? && token.present?enddiff --git a/app/models/indexa_capital_item.rb b/app/models/indexa_capital_item.rbindex 53bd562a80..698c7d251e 100644--- a/app/models/indexa_capital_item.rb+++ b/app/models/indexa_capital_item.rb@@ -1,7 +1,7 @@# frozen_string_literal: trueclass IndexaCapitalItem < ApplicationRecord- include Syncable, Provided, Unlinking+ include Syncable, Provided, Unlinking, DestroyableLaterenum :status, { good: "good", requires_update: "requires_update" }, default: :good@@ -38,11 +38,6 @@ class IndexaCapitalItem < ApplicationRecordIndexaCapitalItem::Syncer.new(self)end- def destroy_later- update!(scheduled_for_deletion: true)- DestroyJob.perform_later(self)- end-# Override syncing? to include background activities fetchdef syncing?super || indexa_capital_accounts.where(activities_fetch_pending: true).exists?diff --git a/app/models/kraken_item.rb b/app/models/kraken_item.rbindex 2c47d5f8ba..9616ad26dc 100644--- a/app/models/kraken_item.rb+++ b/app/models/kraken_item.rb@@ -1,7 +1,7 @@# frozen_string_literal: trueclass KrakenItem < ApplicationRecord- include Syncable, Provided, Unlinking, Encryptable+ include Syncable, Provided, Unlinking, Encryptable, DestroyableLaterenum :status, { good: "good", requires_update: "requires_update" }, default: :good@@ -29,11 +29,6 @@ class KrakenItem < ApplicationRecordbefore_validation :strip_credentials- def destroy_later- update!(scheduled_for_deletion: true)- DestroyJob.perform_later(self)- end-def import_latest_kraken_dataprovider = kraken_providerraise StandardError, "Kraken credentials not configured" unless providerdiff --git a/app/models/lunchflow_item.rb b/app/models/lunchflow_item.rbindex 40a56e182a..f34eeb4635 100644--- a/app/models/lunchflow_item.rb+++ b/app/models/lunchflow_item.rb@@ -1,5 +1,5 @@class LunchflowItem < ApplicationRecord- include Syncable, Provided, Unlinking, Encryptable+ include Syncable, Provided, Unlinking, Encryptable, DestroyableLaterDEFAULT_BASE_URL = "https://lunchflow.app/api/v1".freeze@@ -26,11 +26,6 @@ class LunchflowItem < ApplicationRecordscope :ordered, -> { order(created_at: :desc) }scope :needs_update, -> { where(status: :requires_update) }- def destroy_later- update!(scheduled_for_deletion: true)- DestroyJob.perform_later(self)- end-def import_latest_lunchflow_dataprovider = lunchflow_providerunless providerdiff --git a/app/models/mercury_item.rb b/app/models/mercury_item.rbindex 5869156fb9..ed3b5ba306 100644--- a/app/models/mercury_item.rb+++ b/app/models/mercury_item.rb@@ -1,5 +1,5 @@class MercuryItem < ApplicationRecord- include Syncable, Provided, Unlinking+ include Syncable, Provided, Unlinking, DestroyableLaterenum :status, { good: "good", requires_update: "requires_update" }, default: :good@@ -31,11 +31,6 @@ class MercuryItem < ApplicationRecordscope :ordered, -> { order(created_at: :desc) }scope :needs_update, -> { where(status: :requires_update) }- def destroy_later- update!(scheduled_for_deletion: true)- DestroyJob.perform_later(self)- end-# TODO: Implement data import from provider API# This method should fetch the latest data from the provider and import it.# May need provider-specific validation (e.g., session validity checks).diff --git a/app/models/monobank_item.rb b/app/models/monobank_item.rbindex 0cf3ac0e64..08b1aaa9a5 100644--- a/app/models/monobank_item.rb+++ b/app/models/monobank_item.rb@@ -1,5 +1,5 @@class MonobankItem < ApplicationRecord- include Syncable, Provided, Unlinking, Encryptable+ include Syncable, Provided, Unlinking, Encryptable, DestroyableLaterenum :status, { good: "good", requires_update: "requires_update" }, default: :good@@ -27,12 +27,6 @@ class MonobankItem < ApplicationRecordscope :ordered, -> { order(created_at: :desc) }scope :needs_update, -> { where(status: :requires_update) }- # Mark the item for deletion and enqueue the background destroy job.- def destroy_later- update!(scheduled_for_deletion: true)- DestroyJob.perform_later(self)- end-# Run the importer to fetch the latest accounts/transactions from Monobank.def import_latest_monobank_dataprovider = monobank_providerdiff --git a/app/models/onchain_wallet_item.rb b/app/models/onchain_wallet_item.rbindex fbe391fcae..8951915f0e 100644--- a/app/models/onchain_wallet_item.rb+++ b/app/models/onchain_wallet_item.rb@@ -4,7 +4,7 @@# the family tracks; the addresses and the assets held at them live on# onchain_wallet_accounts.class OnchainWalletItem < ApplicationRecord- include Syncable, Provided, Encryptable+ include Syncable, Provided, Encryptable, DestroyableLaterenum :status, { good: "good", requires_update: "requires_update" }, default: :good@@ -26,11 +26,6 @@ class OnchainWalletItem < ApplicationRecordbefore_validation :strip_credentials- def destroy_later- update!(scheduled_for_deletion: true)- DestroyJob.perform_later(self)- end-# Self-custody needs no credentials: every chain is readable keyless. The# optional Etherscan key only raises Ethereum's rate limit.def credentials_configured?diff --git a/app/models/plaid_item.rb b/app/models/plaid_item.rbindex b95f3a32b9..14191302c1 100644--- a/app/models/plaid_item.rb+++ b/app/models/plaid_item.rb@@ -1,5 +1,5 @@class PlaidItem < ApplicationRecord- include Syncable, Provided, Encryptable+ include Syncable, Provided, Encryptable, DestroyableLaterenum :plaid_region, { us: "us", eu: "eu" }enum :status, { good: "good", requires_update: "requires_update" }, default: :good@@ -78,11 +78,6 @@ class PlaidItem < ApplicationRecordPlaidFollowUpSyncJob.set(wait: PlaidFollowUpSyncJob::RETRY_DELAY).perform_later(self, active_sync_id: active_sync.id)end- def destroy_later- update!(scheduled_for_deletion: true)- DestroyJob.perform_later(self)- end-def request_transactions_refresh_laterreturn unless supports_product?("transactions")return unless shared_transactions_refresh_cache?diff --git a/app/models/questrade_item.rb b/app/models/questrade_item.rbindex 12a4191891..8570079b96 100644--- a/app/models/questrade_item.rb+++ b/app/models/questrade_item.rb@@ -1,7 +1,7 @@# frozen_string_literal: trueclass QuestradeItem < ApplicationRecord- include Syncable, Provided, Unlinking, Encryptable+ include Syncable, Provided, Unlinking, Encryptable, DestroyableLaterenum :status, { good: "good", requires_update: "requires_update" }, default: :good@@ -31,11 +31,6 @@ class QuestradeItem < ApplicationRecordQuestradeItem::Syncer.new(self)end- def destroy_later- update!(scheduled_for_deletion: true)- DestroyJob.perform_later(self)- end-# Override syncing? to include background activities fetchdef syncing?super || questrade_accounts.where(activities_fetch_pending: true).exists?diff --git a/app/models/redbark_item.rb b/app/models/redbark_item.rbindex 01a4b53b9b..a219bc86f8 100644--- a/app/models/redbark_item.rb+++ b/app/models/redbark_item.rb@@ -1,7 +1,7 @@# frozen_string_literal: trueclass RedbarkItem < ApplicationRecord- include Syncable, Provided, Unlinking, Encryptable+ include Syncable, Provided, Unlinking, Encryptable, DestroyableLaterenum :status, { good: "good", requires_update: "requires_update" }, default: :good@@ -31,13 +31,6 @@ class RedbarkItem < ApplicationRecordRedbarkItem::Syncer.new(self)end- # Deliberately not transactional - the job must enqueue after the flag commits- def destroy_later- update!(scheduled_for_deletion: true)- DestroyJob.perform_later(self)- end--# Import data from provider APIdef import_latest_redbark_data(sync: nil)provider = redbark_providerdiff --git a/app/models/simplefin_item.rb b/app/models/simplefin_item.rbindex 37f3b628cb..fb29092ae3 100644--- a/app/models/simplefin_item.rb+++ b/app/models/simplefin_item.rb@@ -1,5 +1,5 @@class SimplefinItem < ApplicationRecord- include Syncable, Provided, Encryptable+ include Syncable, Provided, Encryptable, DestroyableLaterinclude SimplefinItem::Unlinkingenum :status, { good: "good", requires_update: "requires_update" }, default: :good@@ -45,11 +45,6 @@ class SimplefinItem < ApplicationRecord.uniqend- def destroy_later- update!(scheduled_for_deletion: true)- DestroyJob.perform_later(self)- end-def import_latest_simplefin_data(sync: nil)SimplefinItem::Importer.new(self, simplefin_provider: simplefin_provider, sync: sync).importenddiff --git a/app/models/snaptrade_item.rb b/app/models/snaptrade_item.rbindex 7b1094f1a0..2d5539834a 100644--- a/app/models/snaptrade_item.rb+++ b/app/models/snaptrade_item.rb@@ -1,5 +1,5 @@class SnaptradeItem < ApplicationRecord- include Syncable, Provided, Unlinking+ include Syncable, Provided, Unlinking, DestroyableLaterenum :status, { good: "good", requires_update: "requires_update" }, default: :good@@ -40,11 +40,6 @@ class SnaptradeItem < ApplicationRecordscope :ordered, -> { order(created_at: :desc) }scope :needs_update, -> { where(status: :requires_update) }- def destroy_later- update!(scheduled_for_deletion: true)- DestroyJob.perform_later(self)- end-def import_latest_snaptrade_data(sync: nil)provider = snaptrade_providerunless providerdiff --git a/app/models/sophtron_item.rb b/app/models/sophtron_item.rbindex aa61946813..12bd33c763 100644--- a/app/models/sophtron_item.rb+++ b/app/models/sophtron_item.rb@@ -12,7 +12,7 @@# @attr [Boolean] scheduled_for_deletion Whether the item is scheduled for deletion# @attr [DateTime] last_synced_at When the last successful sync occurredclass SophtronItem < ApplicationRecord- include Syncable, Provided, Unlinking+ include Syncable, Provided, Unlinking, DestroyableLaterINITIAL_LOAD_LOOKBACK_DAYS = 120MAX_TRANSACTION_HISTORY_YEARS = 3@@ -54,11 +54,6 @@ class SophtronItem < ApplicationRecordscope :ordered, -> { order(created_at: :desc) }scope :needs_update, -> { where(status: :requires_update) }- def destroy_later- update!(scheduled_for_deletion: true)- DestroyJob.perform_later(self)- end-# Imports the latest account and transaction data from Sophtron.## This method fetches all accounts and transactions from the Sophtron APIdiff --git a/app/models/trade_republic_item.rb b/app/models/trade_republic_item.rbindex 1b3f0f9e86..4f8e3e6184 100644--- a/app/models/trade_republic_item.rb+++ b/app/models/trade_republic_item.rb@@ -1,5 +1,5 @@class TradeRepublicItem < ApplicationRecord- include Syncable, Provided, Unlinking, Encryptable+ include Syncable, Provided, Unlinking, Encryptable, DestroyableLater# The PIN is accepted only for the authentication request. It is never# persisted; session restoration uses the encrypted session blob instead.@@ -26,11 +26,6 @@ class TradeRepublicItem < ApplicationRecordscope :ordered, -> { order(created_at: :desc) }scope :needs_update, -> { where(status: :requires_update) }- def destroy_later- update!(scheduled_for_deletion: true)- DestroyJob.perform_later(self)- end-# Reloading represents a new persisted state; never carry an authentication# PIN across that boundary in the in-memory model instance.def reload(*)diff --git a/app/models/trading212_item.rb b/app/models/trading212_item.rbindex 4a4c9fa228..8f16139137 100644--- a/app/models/trading212_item.rb+++ b/app/models/trading212_item.rb@@ -1,5 +1,5 @@class Trading212Item < ApplicationRecord- include Syncable, Provided, Unlinking, Encryptable+ include Syncable, Provided, Unlinking, Encryptable, DestroyableLaterenum :status, { good: "good", requires_update: "requires_update" }, default: :goodenum :environment, { live: "live", demo: "demo" }, default: :live@@ -22,11 +22,6 @@ class Trading212Item < ApplicationRecordscope :ordered, -> { order(created_at: :desc) }scope :needs_update, -> { where(status: :requires_update) }- def destroy_later- update!(scheduled_for_deletion: true)- DestroyJob.perform_later(self)- end-def credentials_configured?api_key.present? && api_secret.present?enddiff --git a/app/models/up_item.rb b/app/models/up_item.rbindex 27c4e6ce9d..79ff50cf91 100644--- a/app/models/up_item.rb+++ b/app/models/up_item.rb@@ -1,5 +1,5 @@class UpItem < ApplicationRecord- include Syncable, Provided, Unlinking, Encryptable+ include Syncable, Provided, Unlinking, Encryptable, DestroyableLaterenum :status, { good: "good", requires_update: "requires_update" }, default: :good@@ -22,12 +22,6 @@ class UpItem < ApplicationRecordscope :ordered, -> { order(created_at: :desc) }scope :needs_update, -> { where(status: :requires_update) }- # Mark the item for deletion and enqueue the background destroy job.- def destroy_later- update!(scheduled_for_deletion: true)- DestroyJob.perform_later(self)- end-# Run the importer to fetch the latest accounts/transactions from Up.def import_latest_up_dataprovider = up_providerdiff --git a/app/models/wise_item.rb b/app/models/wise_item.rbindex d66af3e084..73c9eab5d0 100644--- a/app/models/wise_item.rb+++ b/app/models/wise_item.rb@@ -1,7 +1,7 @@# frozen_string_literal: trueclass WiseItem < ApplicationRecord- include Syncable, Provided, Unlinking, Encryptable+ include Syncable, Provided, Unlinking, Encryptable, DestroyableLaterSCA_PRIVATE_KEY_ATTRIBUTE = "sca_private_key"@@ -42,11 +42,6 @@ class WiseItem < ApplicationRecordscope :ordered, -> { order(created_at: :desc) }scope :needs_update, -> { where(status: :requires_update) }- def destroy_later- update!(scheduled_for_deletion: true)- DestroyJob.perform_later(self)- end-def import_latest_wise_data(sync_start_date: nil)provider = wise_providerunless provider@@ -214,11 +209,10 @@ class WiseItem < ApplicationRecord# Scoped to writes of the key itself. An install that generated a key# before this validation existed still has that value in the column, so- # validating on every save would reject every later write to the record:- # renaming the connection, and worse, WiseItemsController#destroy, which- # unlinks the accounts BEFORE destroy_later's update! and would leave the- # provider half unlinked and still active. Refusing a NEW key is the point;- # refusing to let go of an old one is not.+ # validating on every save would reject every later write to the record,+ # such as renaming the connection. (DestroyableLater sets the deletion flag+ # with update_column, so deleting it no longer depends on this.) Refusing a+ # NEW key is the point; refusing to let go of an old one is not.def sca_private_key_requires_encryptionreturn unless will_save_change_to_sca_private_key?return if sca_private_key.blank? || sca_encryption_available?diff --git a/lib/generators/provider/family/templates/item_model.rb.tt b/lib/generators/provider/family/templates/item_model.rb.ttindex 015814ed7e..dcc3b4d8cf 100644--- a/lib/generators/provider/family/templates/item_model.rb.tt+++ b/lib/generators/provider/family/templates/item_model.rb.tt@@ -1,7 +1,7 @@# frozen_string_literal: trueclass <%= class_name %>Item < ApplicationRecord- include Syncable, Provided, Unlinking+ include Syncable, Provided, Unlinking, DestroyableLaterenum :status, { good: "good", requires_update: "requires_update" }, default: :good@@ -44,11 +44,6 @@ class <%= class_name %>Item < ApplicationRecord<%= class_name %>Item::Syncer.new(self)end- def destroy_later- update!(scheduled_for_deletion: true)- DestroyJob.perform_later(self)- end-<% if investment_provider? -%># Override syncing? to include background activities fetchdef syncing?diff --git a/lib/generators/provider/global/templates/global_item_model.rb.tt b/lib/generators/provider/global/templates/global_item_model.rb.ttindex acd3009218..917372305f 100644--- a/lib/generators/provider/global/templates/global_item_model.rb.tt+++ b/lib/generators/provider/global/templates/global_item_model.rb.tt@@ -1,5 +1,5 @@class <%= class_name %>Item < ApplicationRecord- include Syncable, Provided+ include Syncable, Provided, DestroyableLaterenum :status, { good: "good", requires_update: "requires_update" }, default: :good@@ -15,11 +15,6 @@ class <%= class_name %>Item < ApplicationRecordscope :ordered, -> { order(created_at: :desc) }scope :needs_update, -> { where(status: :requires_update) }- def destroy_later- update!(scheduled_for_deletion: true)- DestroyJob.perform_later(self)- end-# NOTE: This is a GLOBAL provider# Credentials are configured globally in /settings/providers (self-hosted mode)# or via environment variablesdiff --git a/test/models/concerns/destroyable_later_test.rb b/test/models/concerns/destroyable_later_test.rbnew file mode 100644index 0000000000..054e149c0b--- /dev/null+++ b/test/models/concerns/destroyable_later_test.rb@@ -0,0 +1,118 @@+require "test_helper"++class DestroyableLaterTest < ActiveSupport::TestCase+ include ActiveJob::TestHelper++ setup do+ @item = plaid_items(:one)+ end++ test "flags the item and enqueues its destruction" do+ assert_enqueued_with(job: DestroyJob, args: [ @item ]) do+ assert @item.destroy_later+ end++ assert @item.reload.scheduled_for_deletion?+ assert_not_includes PlaidItem.syncable, @item+ end++ # The adapter is stubbed rather than perform_later, so ActiveJob's own+ # enqueue path decides what destroy_later sees. This is what an unreachable+ # Redis looks like through the Sidekiq adapter: the push raises straight out.+ test "restores the flag and re-raises when the enqueue raises" do+ DestroyJob.queue_adapter.stubs(:enqueue).raises(RedisClient::CannotConnectError, "Connection refused")++ assert_raises(RedisClient::CannotConnectError) { @item.destroy_later }++ assert_not @item.reload.scheduled_for_deletion?+ assert_includes PlaidItem.syncable, @item+ end++ # An adapter raising ActiveJob::EnqueueError (or an enqueue callback aborting)+ # makes perform_later return false instead of raising.+ test "restores the flag when the enqueue is rejected" do+ DestroyJob.queue_adapter.stubs(:enqueue).raises(ActiveJob::EnqueueError, "rejected")++ assert_equal false, @item.destroy_later++ assert_not @item.reload.scheduled_for_deletion?+ end++ # The Delete menu stays visible on a flagged item, so a second request is how+ # a connection stuck by an earlier lost enqueue gets deleted.+ test "re-enqueues destruction for an item that is already flagged" do+ @item.update_column(:scheduled_for_deletion, true)++ assert_enqueued_with(job: DestroyJob, args: [ @item ]) do+ assert @item.destroy_later+ end++ assert @item.reload.scheduled_for_deletion?+ end++ # A retry that fails must not clear the flag an earlier request set: that+ # request's DestroyJob is still queued, and clearing the flag would put the+ # item back into active/syncable until the job runs.+ test "a failed retry keeps the flag set by an earlier successful request" do+ @item.destroy_later+ assert_enqueued_jobs 1, only: DestroyJob++ DestroyJob.queue_adapter.stubs(:enqueue).raises(RedisClient::CannotConnectError, "Connection refused")+ assert_raises(RedisClient::CannotConnectError) { @item.destroy_later }++ assert @item.reload.scheduled_for_deletion?+ end++ test "a rejected retry keeps the flag set by an earlier successful request" do+ @item.destroy_later++ DestroyJob.queue_adapter.stubs(:enqueue).raises(ActiveJob::EnqueueError, "rejected")+ assert_equal false, @item.destroy_later++ assert @item.reload.scheduled_for_deletion?+ end++ # A validation unrelated to deletion must not make a connection undeletable.+ # BrexItem validates base_url against an allowlist on every save, so a row+ # written before the allowlist changed would fail update!.+ test "flags an item that fails an unrelated validation" do+ item = BrexItem.create!(family: families(:dylan_family), name: "Legacy Brex", token: "tok")+ item.update_column(:base_url, "https://legacy-proxy.example.com")+ assert_not item.valid?++ assert_enqueued_with(job: DestroyJob, args: [ item ]) do+ assert item.destroy_later+ end++ assert item.reload.scheduled_for_deletion?+ end++ # QuestradeItem only requires a refresh token while not scheduled for+ # deletion, so a restore that re-ran validations would raise RecordInvalid+ # here, masking the enqueue error and leaving the flag set.+ test "restores the flag without re-running validations that depend on it" do+ item = questrade_items(:one)+ item.update_column(:refresh_token, nil)+ DestroyJob.queue_adapter.stubs(:enqueue).raises(RedisClient::CannotConnectError, "Connection refused")++ assert_raises(RedisClient::CannotConnectError) { item.destroy_later }++ assert_not item.reload.scheduled_for_deletion?+ end++ # Every table with the flag gets its destroy_later from here, so a new provider+ # (or a local override) can't reintroduce the unguarded version.+ test "every model with a scheduled_for_deletion column uses the concern" do+ connection = ActiveRecord::Base.connection+ models = connection.tables+ .select { |table| connection.column_exists?(table, :scheduled_for_deletion) }+ .map { |table| table.classify.constantize }++ assert_operator models.size, :>=, 24++ models.each do |model|+ assert_equal DestroyableLater, model.instance_method(:destroy_later).owner,+ "#{model.name}#destroy_later must come from DestroyableLater"+ end+ end+end