fix: prevent deadlocks by detecting existing transactions

This commit is contained in:
Moritz 2025-12-15 12:32:05 +01:00
parent 83cf6d7503
commit 5b66d49fcd
Signed by: moritz
GPG key ID: 1020A035E5DD0824
2 changed files with 46 additions and 25 deletions

View file

@ -188,36 +188,57 @@ defmodule Mv.MembershipFees.CycleGenerator do
# Convert UUID to integer for advisory lock (use hash)
lock_key = :erlang.phash2(member_id)
result =
Repo.transaction(fn ->
# Acquire advisory lock for this transaction
Ecto.Adapters.SQL.query!(Repo, "SELECT pg_advisory_xact_lock($1)", [lock_key])
# Check if we're already in a transaction (e.g., called from Ash action)
if Repo.in_transaction?() do
# Already in transaction: use advisory lock directly without starting new transaction
# This prevents nested transactions which can cause deadlocks
Ecto.Adapters.SQL.query!(Repo, "SELECT pg_advisory_xact_lock($1)", [lock_key])
case fun.() do
{:ok, result, notifications} when is_list(notifications) ->
# Return result and notifications separately
{result, notifications}
case fun.() do
{:ok, result, notifications} when is_list(notifications) ->
# Notifications will be sent after the outer transaction commits
# Return in same format as non-transaction case for consistency
{:ok, result}
{:ok, result} ->
# Handle case where no notifications were returned (backward compatibility)
{result, []}
{:ok, result} ->
{:ok, result}
{:error, reason} ->
Repo.rollback(reason)
end
end)
{:error, reason} ->
{:error, reason}
end
else
# Not in transaction: start new transaction with advisory lock
result =
Repo.transaction(fn ->
# Acquire advisory lock for this transaction
Ecto.Adapters.SQL.query!(Repo, "SELECT pg_advisory_xact_lock($1)", [lock_key])
# Extract result and notifications, send notifications after transaction
case result do
{:ok, {cycles, notifications}} ->
if Enum.any?(notifications) do
Ash.Notifier.notify(notifications)
end
case fun.() do
{:ok, result, notifications} when is_list(notifications) ->
# Return result and notifications separately
{result, notifications}
{:ok, cycles}
{:ok, result} ->
# Handle case where no notifications were returned (backward compatibility)
{result, []}
{:error, reason} ->
{:error, reason}
{:error, reason} ->
Repo.rollback(reason)
end
end)
# Extract result and notifications, send notifications after transaction
case result do
{:ok, {cycles, notifications}} ->
if Enum.any?(notifications) do
Ash.Notifier.notify(notifications)
end
{:ok, cycles}
{:error, reason} ->
{:error, reason}
end
end
end