Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion lib/event_store/sql/statements.ex
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ defmodule EventStore.Sql.Statements do
{:try_advisory_session_lock, [:schema]},
{:advisory_unlock, [:schema]},
{:bound_lock_wait, []},
{:claim_subscription_lock, [:schema]},
{:bump_lock_generation, [:schema]},
{:subscription_ack, [:schema]},
{:insert_snapshot, [:schema]},
{:delete_snapshot, [:schema]},
Expand Down
4 changes: 4 additions & 0 deletions lib/event_store/sql/statements/bump_lock_generation.sql.eex
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
UPDATE "<%= schema %>".subscriptions
SET lock_generation = lock_generation + 1
WHERE subscription_id = $1
RETURNING lock_generation, last_seen;
16 changes: 0 additions & 16 deletions lib/event_store/sql/statements/claim_subscription_lock.sql.eex

This file was deleted.

56 changes: 26 additions & 30 deletions lib/event_store/storage/lock.ex
Original file line number Diff line number Diff line change
Expand Up @@ -55,41 +55,22 @@ defmodule EventStore.Storage.Lock do

@doc """
Takes the advisory lock of a subscription and bumps its `lock_generation` in
the same statement, returning the lease that fences the subscription's
the same transaction, returning the lease that fences the subscription's
progress writes to this lock owner.
"""
def claim_subscription_lock(conn, subscription_id, opts) do
{schema, opts} = Keyword.pop(opts, :schema)

query = Statements.claim_subscription_lock(schema)

reply =
with_bounded_lock_wait(conn, opts, fn conn ->
Postgrex.query(conn, query, [subscription_id], opts)
end)

case reply do
{:ok, %Postgrex.Result{rows: [[false, _backend_pid, _session_id, _generation, _last_seen]]}} ->
{:error, :lock_already_taken}

{:ok, %Postgrex.Result{rows: [[true, _backend_pid, _session_id, nil, nil]]}} ->
with :ok <- unlock(conn, subscription_id, [schema: schema] ++ opts) do
{:error, :subscription_not_found}
end

{:ok, %Postgrex.Result{rows: [[true, backend_pid, session_id, generation, last_seen]]}} ->
token = FencingToken.new(subscription_id, generation)

{:ok, Lease.new(token, last_seen, Session.new(backend_pid, session_id))}

{:error, %Postgrex.Error{} = error} ->
_ = unlock(conn, subscription_id, [schema: schema] ++ opts)

{:error, error}

{:error, %DBConnection.ConnectionError{}} = reply ->
reply
end
# Every wait happens before the advisory lock is tried, so a failed claim
# never has to give back a lock that may be a hold its owner already had.
with_bounded_lock_wait(conn, opts, fn conn ->
with {:ok, %FencingToken{} = token, last_seen} <-
bump_lock_generation(conn, subscription_id, schema, opts),
{:ok, %Session{} = session} <-
try_acquire_exclusive_session_lock(conn, subscription_id, [schema: schema] ++ opts) do
{:ok, Lease.new(token, last_seen, session)}
end
end)
end

def unlock(conn, key, opts) do
Expand All @@ -104,6 +85,21 @@ defmodule EventStore.Storage.Lock do
end
end

defp bump_lock_generation(conn, subscription_id, schema, opts) do
query = Statements.bump_lock_generation(schema)

case Postgrex.query(conn, query, [subscription_id], opts) do
{:ok, %Postgrex.Result{rows: [[generation, last_seen]]}} ->
{:ok, FencingToken.new(subscription_id, generation), last_seen}

{:ok, %Postgrex.Result{rows: []}} ->
{:error, :subscription_not_found}

{:error, _error} = reply ->
reply
end
end

# A query that outlives its timeout drops the connection along with every lock
# the session holds, so waiting on a lock held on the subscriptions table gives
# up well before that.
Expand Down
67 changes: 64 additions & 3 deletions test/advisory_locks_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,7 @@ defmodule EventStore.AdvisoryLocksTest do
@monitor TestEventStore.EventStore.AdvisoryLocks.Postgrex.EventStore.MonitoredServer

setup do
postgrex_config = Config.parsed(TestEventStore, :eventstore) |> Config.default_postgrex_opts()

conn = start_supervised!({Postgrex, postgrex_config})
conn = start_supervised!({Postgrex, postgrex_config()})

[conn: conn]
end
Expand Down Expand Up @@ -168,6 +166,65 @@ defmodule EventStore.AdvisoryLocksTest do
Storage.Lock.try_acquire_exclusive_lock(conn, held_id, schema: schema)
end

test "should keep the lock held when a repeated claim cannot wait for a table lock",
context do
%{conn: conn, schema: schema} = context
%{subscription_id: subscription_id} = create_subscription(context)

{:ok, %AdvisoryLocks.Lease{}} = AdvisoryLocks.try_subscription_lock(@locks, subscription_id)

table_lock = lock_subscriptions_table(context)

try do
assert {:error, %Postgrex.Error{postgres: %{code: :lock_not_available}}} =
AdvisoryLocks.try_subscription_lock(@locks, subscription_id, 1_000)
after
release_table_lock(table_lock)
end

assert {:error, :lock_already_taken} =
Storage.Lock.try_acquire_exclusive_lock(conn, subscription_id, schema: schema)
end

test "should keep the lock held when a repeated claim is cancelled while it waits", context do
%{conn: conn, schema: schema} = context
%{subscription_id: subscription_id} = create_subscription(context)

{:ok, %AdvisoryLocks.Lease{}} = AdvisoryLocks.try_subscription_lock(@locks, subscription_id)

lock_backend_pid = backend_pid(@conn)

canceller = start_supervised!({Postgrex, postgrex_config()}, id: :canceller)

table_lock = lock_subscriptions_table(context)

try do
cancel =
Task.async(fn ->
Wait.until(fn ->
assert %Postgrex.Result{rows: [["Lock"]]} =
Postgrex.query!(
canceller,
"SELECT wait_event_type FROM pg_stat_activity WHERE pid = $1",
[lock_backend_pid]
)
end)

Postgrex.query!(canceller, "SELECT pg_cancel_backend($1)", [lock_backend_pid])
end)

assert {:error, %Postgrex.Error{postgres: %{code: :query_canceled}}} =
AdvisoryLocks.try_subscription_lock(@locks, subscription_id, 10_000)

assert %Postgrex.Result{rows: [[true]]} = Task.await(cancel)
after
release_table_lock(table_lock)
end

assert {:error, :lock_already_taken} =
Storage.Lock.try_acquire_exclusive_lock(conn, subscription_id, schema: schema)
end

test "should fail to acquire the lock of a subscription that does not exist" do
assert {:error, :subscription_not_found} =
AdvisoryLocks.try_subscription_lock(@locks, 999_999)
Expand Down Expand Up @@ -966,6 +1023,10 @@ defmodule EventStore.AdvisoryLocksTest do
holder
end

defp postgrex_config do
Config.parsed(TestEventStore, :eventstore) |> Config.default_postgrex_opts()
end

defp lock_subscriptions_table(%{conn: conn, schema: schema}) do
reply_to = self()

Expand Down
2 changes: 1 addition & 1 deletion test/storage/subscription_lock_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ defmodule EventStore.Storage.SubscriptionLockTest do
ProcessHelper.shutdown(other)
end

test "a claim that fails after taking the advisory lock leaves the subscription claimable",
test "a claim that cannot lock the subscription row leaves the subscription claimable",
context do
%{postgrex_config: postgrex_config, conn: conn, schema: schema} = context
%{subscription_id: subscription_id} = create_subscription(context)
Expand Down
Loading