fix: prevent deadlocks by detecting existing transactions

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

View file

@ -763,7 +763,7 @@ defmodule Mv.Membership.Member do
end
# Regenerates cycles with new type/amount
# CycleGenerator uses its own transaction with advisory lock
# CycleGenerator detects if already in transaction and uses advisory lock accordingly
defp regenerate_cycles(member_id) do
case Mv.MembershipFees.CycleGenerator.generate_cycles_for_member(member_id) do
{:ok, _cycles} -> :ok

View file

@ -188,6 +188,26 @@ defmodule Mv.MembershipFees.CycleGenerator do
# Convert UUID to integer for advisory lock (use hash)
lock_key = :erlang.phash2(member_id)
# 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) ->
# Notifications will be sent after the outer transaction commits
# Return in same format as non-transaction case for consistency
{:ok, result}
{:ok, result} ->
{:ok, result}
{: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
@ -220,6 +240,7 @@ defmodule Mv.MembershipFees.CycleGenerator do
{:error, reason}
end
end
end
defp do_generate_cycles(member, today) do
# Reload member with relationships to ensure fresh data