The personal finance app for everyone (by everyone)
Ruby
Restore account status when DestroyJob enqueue fails (#4172)
jaysbeekay414f2501cc72
diff --git a/app/controllers/accounts_controller.rb b/app/controllers/accounts_controller.rbindex a126954652..ca3af101c5 100644--- a/app/controllers/accounts_controller.rb+++ b/app/controllers/accounts_controller.rb@@ -246,8 +246,11 @@ class AccountsController < ApplicationControllerredirect_to account_path(@account), alert: t("accounts.destroy.cannot_delete_linked")elsebegin- @account.destroy_later- redirect_to accounts_path, notice: t("accounts.destroy.success", type: @account.accountable_type)+ if @account.destroy_later == false+ redirect_to accounts_path, alert: t("accounts.destroy.failed")+ else+ redirect_to accounts_path, notice: t("accounts.destroy.success", type: @account.accountable_type)+ endrescue => eRails.logger.error "Failed to schedule account #{@account.id} for deletion: #{e.message}"redirect_to accounts_path, alert: t("accounts.destroy.failed")diff --git a/app/controllers/coinbase_items_controller.rb b/app/controllers/coinbase_items_controller.rbindex b07c3078ac..8326b26529 100644--- a/app/controllers/coinbase_items_controller.rb+++ b/app/controllers/coinbase_items_controller.rb@@ -121,6 +121,7 @@ class CoinbaseItemsController < ApplicationControllerend# Relink behavior: detach any existing link and point provider link at the chosen account+ orphaned_account = nilAccount.transaction docoinbase_account.lock!@@ -136,7 +137,7 @@ class CoinbaseItemsController < ApplicationControllerbeginprevious_account.reloadif previous_account.account_providers.none?- previous_account.destroy_later if previous_account.may_mark_for_deletion?+ orphaned_account = previous_account if previous_account.may_mark_for_deletion?endrescue => eRails.logger.warn("Failed orphan cleanup for account ##{previous_account&.id}: #{e.class} - #{e.message}")@@ -144,6 +145,16 @@ class CoinbaseItemsController < ApplicationControllerendend+ # Queue the orphan for deletion only after the relink commits. destroy_later+ # pushes DestroyJob only once every open transaction commits, so called in+ # the block above, an enqueue error would leave it from the commit, past+ # the rescue inside it.+ begin+ orphaned_account&.destroy_later+ rescue => e+ Rails.logger.warn("Failed orphan cleanup for account ##{orphaned_account.id}: #{e.class} - #{e.message}")+ end+if turbo_frame_request?coinbase_account.reloaditem = coinbase_account.coinbase_itemdiff --git a/app/controllers/enable_banking_items_controller.rb b/app/controllers/enable_banking_items_controller.rbindex 939c62fa34..3ccea35087 100644--- a/app/controllers/enable_banking_items_controller.rb+++ b/app/controllers/enable_banking_items_controller.rb@@ -441,6 +441,7 @@ class EnableBankingItemsController < ApplicationControllerend# Relink behavior: detach any legacy link and point provider link at the chosen account+ orphaned_account = nilAccount.transaction doenable_banking_account.lock!@@ -459,13 +460,23 @@ class EnableBankingItemsController < ApplicationController# Disabled accounts still appear (greyed-out) in the manual list after a full refresh.# Use the app's standard deletion path (async) so the duplicate disappears and the# "pending_deletion" state remains truthful in the UI.- previous_account.destroy_later if previous_account.may_mark_for_deletion?+ orphaned_account = previous_account if previous_account.may_mark_for_deletion?rescue => eRails.logger.warn("Failed to cleanup orphaned account #{previous_account.id}: #{e.class} - #{e.message}")endendend+ # Queue the orphan for deletion only after the relink commits. destroy_later+ # pushes DestroyJob only once every open transaction commits, so called in+ # the block above, an enqueue error would leave it from the commit, past+ # the rescue inside it.+ begin+ orphaned_account&.destroy_later+ rescue => e+ Rails.logger.warn("Failed to cleanup orphaned account #{orphaned_account.id}: #{e.class} - #{e.message}")+ end+if turbo_frame_request?# Reload the item to ensure associations are freshenable_banking_account.reloaddiff --git a/app/controllers/simplefin_items_controller.rb b/app/controllers/simplefin_items_controller.rbindex ed32dfe844..f2a8a79e03 100644--- a/app/controllers/simplefin_items_controller.rb+++ b/app/controllers/simplefin_items_controller.rb@@ -404,6 +404,7 @@ class SimplefinItemsController < ApplicationControllerend# Relink behavior: detach any legacy link and point provider link at the chosen account+ orphaned_account = nilAccount.transaction dosimplefin_account.lock!@@ -443,7 +444,7 @@ class SimplefinItemsController < ApplicationController# consolidation we want the duplicate to disappear from the UI.# Use the app's standard deletion path (async) so the "pending_deletion" state# remains truthful in the UI.- previous_account.destroy_later if previous_account.may_mark_for_deletion?+ orphaned_account = previous_account if previous_account.may_mark_for_deletion?elseRails.logger.info("Skipped disabling account ##{previous_account.id} after relink because it still has active provider links")end@@ -453,6 +454,16 @@ class SimplefinItemsController < ApplicationControllerendend+ # Queue the orphan for deletion only after the relink commits. destroy_later+ # pushes DestroyJob only once every open transaction commits, so called in+ # the block above, an enqueue error would leave it from the commit, past+ # the rescue inside it.+ begin+ orphaned_account&.destroy_later+ rescue => e+ Rails.logger.warn("Failed disabling-orphan check for account ##{orphaned_account.id}: #{e.class} - #{e.message}")+ end+if turbo_frame_request?# Reload the item to ensure associations are freshsimplefin_account.reloaddiff --git a/app/models/account.rb b/app/models/account.rbindex e1422cb400..9c0c40698a 100644--- a/app/models/account.rb+++ b/app/models/account.rb@@ -635,11 +635,37 @@ class Account < ApplicationRecordendend+ # Marks the account pending_deletion and enqueues DestroyJob. If the enqueue+ # fails, the account goes back to the status it had, so it is not left hidden+ # from every list with no job coming to delete it. Mirrors DestroyableLater,+ # except that the claim is made under a row lock (see below).+ #+ # ApplicationJob defers enqueues until commit, so perform_later inside a+ # transaction returns before the push is tried. The enqueue therefore runs+ # once every open transaction has committed: immediately when there is none,+ # so the caller sees the outcome, and after the outer commit for a caller that+ # holds one (the relink cleanup), when the push really happens. A rolled-back+ # outer transaction undoes the mark and never enqueues.+ #+ # The prior status is read and the mark made under a row lock, which reloads+ # the account first. A second request for the same account (a double submit)+ # waits for the first to commit, sees pending_deletion and raises+ # AASM::InvalidTransition before it captures a status or schedules an+ # enqueue, so a restore only ever undoes the mark its own call made. Callers+ # pass a freshly loaded record: lock! refuses one with unsaved changes.+ #+ # Returns the job, or false when the enqueue was rejected. Inside an outer+ # transaction the enqueue has not run yet, so it returns nil.def destroy_later- transaction do- mark_for_deletion!- DestroyJob.perform_later(self)+ previous_status = with_lock do+ status.tap { mark_for_deletion! }end++ enqueued = nil+ ActiveRecord.after_all_transactions_commit do+ enqueued = enqueue_destroy_job(restoring: previous_status)+ end+ enqueuedend# Override destroy to handle error recovery for accounts@@ -793,6 +819,33 @@ class Account < ApplicationRecordprivate+ # perform_later raises (the Sidekiq adapter re-raises RedisClient errors) or+ # returns false (ActiveJob::EnqueueError). Either way the status goes back.+ def enqueue_destroy_job(restoring:)+ enqueued = begin+ DestroyJob.perform_later(self)+ rescue StandardError+ restore_status_after_failed_enqueue(restoring)+ raise+ end++ # Match false exactly, as DestroyableLater does: a bare mock of+ # perform_later returns nil, which is not a rejected enqueue.+ restore_status_after_failed_enqueue(restoring) if enqueued == false+ enqueued+ end++ # The row lock covers only the mark, and the push runs after commit, so+ # another request may have written a newer status by now (toggle_active+ # waiting on the lock, say). Undo the mark only while the row still holds+ # it. A direct write, because AASM has no event back to the prior status and+ # the restore must not fail on an unrelated validation and mask the error.+ def restore_status_after_failed_enqueue(restoring)+ restored = Account.where(id: id, status: "pending_deletion").update_all(status: restoring)+ self.status = restoring if restored == 1+ clear_attribute_changes([ :status ])+ end+def assign_default_ownerreturn if owner.present?diff --git a/test/controllers/accounts_controller_test.rb b/test/controllers/accounts_controller_test.rbindex c5449310f5..8b6fc804a5 100644--- a/test/controllers/accounts_controller_test.rb+++ b/test/controllers/accounts_controller_test.rb@@ -837,6 +837,46 @@ class AccountsControllerTest < ActionDispatch::IntegrationTestassert_equal "Depository account scheduled for deletion", flash[:notice]end+ test "destroy reports failure and keeps the account listed when the enqueue raises" do+ DestroyJob.queue_adapter.stubs(:enqueue).raises(RedisClient::CannotConnectError, "Connection refused")++ delete account_url(@account)++ assert_redirected_to accounts_path+ assert_equal I18n.t("accounts.destroy.failed"), flash[:alert]+ assert_equal "active", @account.reload.status++ get accounts_url+ assert_select "turbo-frame##{dom_id(@account)}"+ end++ test "destroy reports failure when the enqueue is rejected" do+ DestroyJob.queue_adapter.stubs(:enqueue).raises(ActiveJob::EnqueueError, "rejected")++ delete account_url(@account)++ assert_redirected_to accounts_path+ assert_equal I18n.t("accounts.destroy.failed"), flash[:alert]+ assert_nil flash[:notice]+ assert_equal "active", @account.reload.status+ end++ # The second request of a double submit finds the account already pending+ # deletion. It reports failure rather than erroring, enqueues nothing more,+ # and leaves the first request's mark in place.+ test "a second destroy of an account pending deletion reports failure" do+ delete account_url(@account)+ assert_equal "pending_deletion", @account.reload.status++ assert_no_enqueued_jobs(only: DestroyJob) do+ delete account_url(@account)+ end++ assert_redirected_to accounts_path+ assert_equal I18n.t("accounts.destroy.failed"), flash[:alert]+ assert_equal "pending_deletion", @account.reload.status+ end+test "syncing linked account triggers sync for all provider items" doplaid_account = plaid_accounts(:one)AccountProvider.create!(account: @account, provider: plaid_account)diff --git a/test/controllers/coinbase_items_controller_test.rb b/test/controllers/coinbase_items_controller_test.rbindex 721c70ed66..2ef13de731 100644--- a/test/controllers/coinbase_items_controller_test.rb+++ b/test/controllers/coinbase_items_controller_test.rb@@ -211,4 +211,41 @@ class CoinbaseItemsControllerTest < ActionDispatch::IntegrationTest}endend++ # The orphan cleanup's enqueue runs once the relink transaction commits. If it+ # ran inside that transaction, its error would escape the action's rescue+ # after the relink had committed, and the request would fail.+ test "link_existing_account still succeeds when the orphan's destroy enqueue fails" do+ orphan = Account.create!(+ family: @family,+ name: "Old Crypto",+ balance: 0,+ currency: "USD",+ accountable: Crypto.create!(subtype: "exchange")+ )+ target = Account.create!(+ family: @family,+ name: "Manual Crypto",+ balance: 0,+ currency: "USD",+ accountable: Crypto.create!(subtype: "exchange")+ )+ coinbase_account = @coinbase_item.coinbase_accounts.create!(+ name: "BTC Wallet",+ account_id: "btc_123",+ currency: "BTC",+ current_balance: 0.5+ )+ AccountProvider.create!(account: orphan, provider: coinbase_account)+ DestroyJob.queue_adapter.expects(:enqueue).once.raises(RedisClient::CannotConnectError, "Connection refused")++ post link_existing_account_coinbase_items_url, params: {+ account_id: target.id,+ coinbase_account_id: coinbase_account.id+ }++ assert_redirected_to accounts_path+ assert_equal target, coinbase_account.reload.current_account+ assert_equal "active", orphan.reload.status+ endenddiff --git a/test/controllers/enable_banking_items_controller_test.rb b/test/controllers/enable_banking_items_controller_test.rbindex d6d8d19740..929d100842 100644--- a/test/controllers/enable_banking_items_controller_test.rb+++ b/test/controllers/enable_banking_items_controller_test.rb@@ -307,6 +307,43 @@ class EnableBankingItemsControllerTest < ActionDispatch::IntegrationTestassert_redirected_to accounts_pathend+ # The orphan cleanup's enqueue runs once the relink transaction commits. If it+ # ran inside that transaction, its error would escape the action's rescue+ # after the relink had committed, and the request would fail.+ test "link_existing_account still succeeds when the orphan's destroy enqueue fails" do+ orphan = Account.create!(+ family: @family,+ name: "Old Checking",+ balance: 0,+ currency: "EUR",+ accountable: Depository.create!(subtype: "checking")+ )+ target = Account.create!(+ family: @family,+ name: "Manual Checking",+ balance: 0,+ currency: "EUR",+ accountable: Depository.create!(subtype: "checking")+ )+ eb_account = @item.enable_banking_accounts.create!(+ name: "Checking",+ uid: "eb_relink_1",+ currency: "EUR",+ current_balance: 0+ )+ AccountProvider.create!(account: orphan, provider: eb_account)+ DestroyJob.queue_adapter.expects(:enqueue).once.raises(RedisClient::CannotConnectError, "Connection refused")++ post link_existing_account_enable_banking_items_path, params: {+ account_id: target.id,+ enable_banking_account_id: eb_account.id+ }++ assert_response :see_other+ assert_equal target, AccountProvider.find_by!(provider: eb_account).account+ assert_equal "active", orphan.reload.status+ end+privatedef stub_authorization_startdiff --git a/test/controllers/simplefin_items_controller_test.rb b/test/controllers/simplefin_items_controller_test.rbindex 98464eb7b1..ec1606ea07 100644--- a/test/controllers/simplefin_items_controller_test.rb+++ b/test/controllers/simplefin_items_controller_test.rb@@ -146,6 +146,44 @@ class SimplefinItemsControllerTest < ActionDispatch::IntegrationTestassert_equal "pending_deletion", account_a.status, "expected orphaned duplicate to be hidden after relink"end+ # The orphan cleanup's enqueue runs once the relink transaction commits. If it+ # ran inside that transaction, its error would escape the action's rescue+ # after the relink had committed, and the request would fail.+ test "relink still succeeds when the orphan's destroy enqueue fails" do+ account_a = Account.create!(+ family: @family,+ name: "Duplicate A",+ balance: 0,+ currency: "USD",+ accountable: Depository.create!(subtype: "checking")+ )+ account_b = Account.create!(+ family: @family,+ name: "Target B",+ balance: 0,+ currency: "USD",+ accountable: Depository.create!(subtype: "savings")+ )+ sfa = @simplefin_item.simplefin_accounts.create!(+ name: "SF For Duplicate",+ account_id: "sf_dup_enqueue",+ account_type: "depository",+ currency: "USD",+ current_balance: 0+ )+ AccountProvider.create!(account: account_a, provider: sfa)+ DestroyJob.queue_adapter.expects(:enqueue).once.raises(RedisClient::CannotConnectError, "Connection refused")++ post link_existing_account_simplefin_items_path, params: {+ account_id: account_b.id,+ simplefin_account_id: sfa.id+ }++ assert_response :see_other+ assert_equal account_b, AccountProvider.find_by!(provider: sfa).account+ assert_equal "active", account_a.reload.status+ end+test "should get edit" do@simplefin_item.update!(status: :requires_update)get edit_simplefin_item_url(@simplefin_item)diff --git a/test/models/account/destroy_later_test.rb b/test/models/account/destroy_later_test.rbnew file mode 100644index 0000000000..b67f7390e5--- /dev/null+++ b/test/models/account/destroy_later_test.rb@@ -0,0 +1,152 @@+require "test_helper"++class Account::DestroyLaterTest < ActiveSupport::TestCase+ include ActiveJob::TestHelper++ setup do+ @account = accounts(:depository)+ end++ test "marks the account pending deletion and enqueues its destruction" do+ assert_enqueued_with(job: DestroyJob, args: [ @account ]) do+ assert @account.destroy_later+ end++ assert @account.reload.pending_deletion?+ 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 prior status and re-raises when the enqueue raises" do+ DestroyJob.queue_adapter.stubs(:enqueue).raises(RedisClient::CannotConnectError, "Connection refused")++ assert_raises(RedisClient::CannotConnectError) { @account.destroy_later }++ assert_equal "active", @account.reload.status+ assert_includes Account.visible, @account+ end++ # An adapter raising ActiveJob::EnqueueError makes perform_later return false+ # instead of raising.+ test "returns false and restores the prior status when the enqueue is rejected" do+ DestroyJob.queue_adapter.stubs(:enqueue).raises(ActiveJob::EnqueueError, "rejected")++ assert_equal false, @account.destroy_later++ assert_equal "active", @account.reload.status+ end++ test "restores a disabled account to disabled when the enqueue fails" do+ @account.update_column(:status, "disabled")+ DestroyJob.queue_adapter.stubs(:enqueue).raises(RedisClient::CannotConnectError, "Connection refused")++ assert_raises(RedisClient::CannotConnectError) { @account.destroy_later }++ assert_equal "disabled", @account.reload.status+ end++ test "restores a draft account to draft when the enqueue fails" do+ @account.update_column(:status, "draft")+ DestroyJob.queue_adapter.stubs(:enqueue).raises(ActiveJob::EnqueueError, "rejected")++ assert_equal false, @account.destroy_later++ assert_equal "draft", @account.reload.status+ end++ # A caller that wraps destroy_later in its own transaction, with its own+ # rescue, does not see the error there: the push only happens once that outer+ # transaction commits, so the error leaves from the commit. The relink cleanup+ # in the provider controllers calls destroy_later after its transaction for+ # this reason. Whoever calls it, the account must still be restored.+ test "an enqueue failure after an outer transaction commits restores the status" do+ DestroyJob.queue_adapter.stubs(:enqueue).raises(RedisClient::CannotConnectError, "Connection refused")+ rescued_inside = false++ assert_raises(RedisClient::CannotConnectError) do+ Account.transaction do+ @account.destroy_later+ rescue StandardError+ rescued_inside = true+ end+ end++ assert_not rescued_inside+ assert_equal "active", @account.reload.status+ end++ test "a rolled-back outer transaction leaves the status and the queue untouched" do+ assert_no_enqueued_jobs(only: DestroyJob) do+ Account.transaction do+ @account.destroy_later+ raise ActiveRecord::Rollback+ end+ end++ assert_equal "active", @account.reload.status+ end++ # The restore puts back only what this call changed. An account already+ # pending deletion was marked by an earlier request, so a second call must not+ # clear that mark.+ test "an account already pending deletion still raises and stays pending deletion" do+ @account.update_column(:status, "pending_deletion")+ DestroyJob.queue_adapter.stubs(:enqueue).raises(RedisClient::CannotConnectError, "Connection refused")++ assert_raises(AASM::InvalidTransition) { @account.destroy_later }++ assert_equal "pending_deletion", @account.reload.status+ end++ # A double submit loads the account twice before either request commits. The+ # second copy still holds the old status, so without a reload it would pass+ # the guard, and its failed enqueue would put back "active" while the first+ # request's DestroyJob is queued.+ test "a stale copy cannot put back a status another request already marked" do+ stale = Account.find(@account.id)+ assert @account.destroy_later+ DestroyJob.queue_adapter.stubs(:enqueue).raises(RedisClient::CannotConnectError, "Connection refused")++ assert_raises(AASM::InvalidTransition) { stale.destroy_later }++ assert_equal "pending_deletion", @account.reload.status+ end++ # The status to restore is read after the reload, so a stale copy puts back+ # what the row held when it was marked, not what the copy was loaded with.+ test "a stale copy restores the status the row held when it was marked" do+ stale = Account.find(@account.id)+ @account.disable!+ DestroyJob.queue_adapter.stubs(:enqueue).raises(RedisClient::CannotConnectError, "Connection refused")++ assert_raises(RedisClient::CannotConnectError) { stale.destroy_later }++ assert_equal "disabled", @account.reload.status+ end++ # The row lock covers only the mark; the push runs after commit. A request+ # blocked on that lock (toggle_active calling disable! on a copy loaded as+ # active) writes its status once the mark commits. A failed enqueue must not+ # then put back the status captured before the mark over that newer write.+ test "a failed enqueue does not overwrite a status another request set after the mark" do+ [+ [ RedisClient::CannotConnectError, ->(account) { assert_raises(RedisClient::CannotConnectError) { account.destroy_later } } ],+ [ ActiveJob::EnqueueError, ->(account) { assert_equal false, account.destroy_later } ]+ ].each_with_object({}) do |(error, call), statuses|+ @account.update_column(:status, "active")+ account = Account.find(@account.id)+ DestroyJob.queue_adapter.unstub(:enqueue)+ DestroyJob.queue_adapter.stubs(:enqueue).with do |*|+ Account.where(id: account.id).update_all(status: "disabled")+ true+ end.raises(error, "enqueue failed")++ call.call(account)++ statuses[error.name] = @account.reload.status+ end.then do |statuses|+ assert_equal({ "RedisClient::CannotConnectError" => "disabled", "ActiveJob::EnqueueError" => "disabled" }, statuses)+ end+ end+end