diff --git a/guides/Cluster.md b/guides/Cluster.md index 41cee88e..b72e28de 100644 --- a/guides/Cluster.md +++ b/guides/Cluster.md @@ -16,6 +16,15 @@ Subscribers must therefore be idempotent, as they are for any at-least-once deli When the lock connection stalls, each attempt a subscription makes to take its lock waits for up to the event store's `timeout` (15 seconds by default), and the subscription makes another attempt every `:subscription_retry_interval` for as long as the connection stays stalled. A subscriber that calls `ack/2` on that subscription during an attempt can exit with a `:timeout` after the default 5 second call timeout, and that exposure comes back on every retry, so acks can keep timing out for far longer than a single `timeout`. The subscription's position is unaffected: a subscription waiting for its lock ignores those acks anyway, and it resumes from the last committed checkpoint once it holds the lock again. Subscribers that ack from a process that must not crash should catch that exit. +### How long a node takes to learn its lock session ended + +Subscriptions hold their locks on a dedicated connection. When the database stops answering on that connection, how soon the node stops its subscriptions depends on what that connection was doing: + +- While a lock query is running, the node learns of the loss once the query reaches its `:timeout` (15,000ms by default), plus up to two seconds spent trying to cancel it. With `timeout: :infinity` the query never gives up and `ping_timeout` does not apply to it, so the node is not told until the socket itself errors, and until then its subscriptions keep running on a session that has ended. Keep `:timeout` finite on any node that runs subscriptions. +- While the connection is idle, the node learns of the loss when the connection next pings the database: within one to two times `idle_interval` (1,000ms by default), plus however long the ping waits for a reply. That wait is `ping_timeout`, which defaults to `:timeout`. With `timeout: :infinity` the ping waits forever, so set `ping_timeout` in `session_mode_pool` to bound it, for example `session_mode_pool: [ping_timeout: 15_000]`. + +PostgreSQL only releases the locks of a session once it notices the client is gone, which can take longer still unless `tcp_keepalives_idle` or `client_connection_check_interval` is configured on the server. Until then no other node can take the lock, so a slow release delays the hand-off but never lets two nodes record progress at the same time. + ## Automatic cluster formation You can use [libcluster](https://github.com/bitwalker/libcluster) to automatically form clusters of Erlang nodes, with either static or dynamic node membership. diff --git a/lib/event_store/advisory_locks.ex b/lib/event_store/advisory_locks.ex index 1d7228e7..b6196266 100644 --- a/lib/event_store/advisory_locks.ex +++ b/lib/event_store/advisory_locks.ex @@ -239,6 +239,7 @@ defmodule EventStore.AdvisoryLocks do end def handle_cast({:release, ref}, %State{} = state) do + state = handle_pending_session_loss(state) %State{locks: locks} = state state = @@ -260,6 +261,8 @@ defmodule EventStore.AdvisoryLocks do _from, %State{} = state ) do + state = handle_pending_session_loss(state) + case {held_lock(state, subscription_id, owner), claim_subscription_lock(subscription_id, timeout, state)} do {nil, {:ok, %Storage.Lock.Lease{session: session} = lease}} -> @@ -288,6 +291,8 @@ defmodule EventStore.AdvisoryLocks do end def handle_call({:try_advisory_lock, key, owner, timeout}, _from, %State{} = state) do + state = handle_pending_session_loss(state) + case held_lock(state, key, owner) do {_owner_ref, %Lock{} = lock} -> {:reply, {:ok, Lock.ref(lock)}, state} @@ -399,6 +404,7 @@ defmodule EventStore.AdvisoryLocks do # Release lock when the lock owner process terminates. def handle_info({:DOWN, ref, :process, _pid, _reason}, %State{} = state) do + state = handle_pending_session_loss(state) %State{locks: locks} = state state = @@ -421,6 +427,19 @@ defmodule EventStore.AdvisoryLocks do {:stop, reason, state} end + # A query held up by a connection that stopped answering leaves the notice of + # its lost session queued behind the requests that arrived meanwhile, so it is + # handled before them instead of after each one has waited on the pool. + defp handle_pending_session_loss(%State{connection: %Connection{pid: conn_pid}} = state) do + receive do + {__MODULE__, :session_lost, ^conn_pid} -> disconnected(conn_pid, :session_ended, state) + after + 0 -> state + end + end + + defp handle_pending_session_loss(%State{} = state), do: state + defp connected(conn_pid, %State{connection: connection} = state) do Connection.demonitor(connection) diff --git a/lib/event_store/advisory_locks/protocol.ex b/lib/event_store/advisory_locks/protocol.ex index 58d2da5c..b34bb5b2 100644 --- a/lib/event_store/advisory_locks/protocol.ex +++ b/lib/event_store/advisory_locks/protocol.ex @@ -4,11 +4,13 @@ defmodule EventStore.AdvisoryLocks.Protocol do # Postgrex closes a connection by sending a cancel request first, and both its # connect and its wait for the reply use the :timeout option, so this can take # that long when the database stops answering. - # The lock owners cannot wait that long to hear the session is gone. + # The lock owners cannot wait that long to hear the session is gone, and the + # lock server cannot handle that notice until the socket is closed. @behaviour DBConnection @session_listener {__MODULE__, :session_listener} + @cancel_timeout 1_000 def start_link(opts) do opts = Postgrex.Utils.default_opts(opts) @@ -24,12 +26,18 @@ defmodule EventStore.AdvisoryLocks.Protocol do end @impl DBConnection - def disconnect(error, state) do + def disconnect(error, %Postgrex.Protocol{timeout: timeout} = state) do notify_session_lost(error) - Postgrex.Protocol.disconnect(error, state) + Postgrex.Protocol.disconnect(error, %Postgrex.Protocol{ + state + | timeout: cancel_timeout(timeout) + }) end + defp cancel_timeout(:infinity), do: @cancel_timeout + defp cancel_timeout(timeout), do: min(timeout, @cancel_timeout) + defp notify_session_lost(_error) do case Process.get(@session_listener) do nil -> :ok @@ -37,6 +45,11 @@ defmodule EventStore.AdvisoryLocks.Protocol do end end + # A retry runs on the next connection before the lock server has handled the + # loss of this session, so the lock owners would hear of it only afterwards. + defp without_retry({:disconnect_and_retry, error, state}), do: {:disconnect, error, state} + defp without_retry(result), do: result + @impl DBConnection defdelegate checkout(state), to: Postgrex.Protocol @@ -44,7 +57,8 @@ defmodule EventStore.AdvisoryLocks.Protocol do defdelegate ping(state), to: Postgrex.Protocol @impl DBConnection - defdelegate handle_begin(opts, state), to: Postgrex.Protocol + def handle_begin(opts, state), + do: without_retry(Postgrex.Protocol.handle_begin(opts, state)) @impl DBConnection defdelegate handle_commit(opts, state), to: Postgrex.Protocol @@ -56,13 +70,16 @@ defmodule EventStore.AdvisoryLocks.Protocol do defdelegate handle_status(opts, state), to: Postgrex.Protocol @impl DBConnection - defdelegate handle_prepare(query, opts, state), to: Postgrex.Protocol + def handle_prepare(query, opts, state), + do: without_retry(Postgrex.Protocol.handle_prepare(query, opts, state)) @impl DBConnection - defdelegate handle_execute(query, params, opts, state), to: Postgrex.Protocol + def handle_execute(query, params, opts, state), + do: without_retry(Postgrex.Protocol.handle_execute(query, params, opts, state)) @impl DBConnection - defdelegate handle_close(query, opts, state), to: Postgrex.Protocol + def handle_close(query, opts, state), + do: without_retry(Postgrex.Protocol.handle_close(query, opts, state)) @impl DBConnection defdelegate handle_declare(query, params, opts, state), to: Postgrex.Protocol diff --git a/test/advisory_locks_test.exs b/test/advisory_locks_test.exs index 3c93bc85..732c8457 100644 --- a/test/advisory_locks_test.exs +++ b/test/advisory_locks_test.exs @@ -490,29 +490,9 @@ defmodule EventStore.AdvisoryLocksTest do test "should send `lock_released` message when the database stops answering new connections", %{conn: conn, schema: schema} do - name = :proxied_lock_store - locks = Module.concat([name, AdvisoryLocks]) + {locks, proxy} = start_proxied_lock_store(:proxied_lock_store, schema, idle_interval: 100) lock_pool = Module.concat([locks, Postgrex]) - config = Config.parsed(TestEventStore, :eventstore) - - proxy = - start_supervised!( - {EventStore.TcpProxy, - {Keyword.fetch!(config, :hostname), Keyword.fetch!(config, :port)}} - ) - - start_supervised!( - {TestEventStore, - name: name, - schema: schema, - session_mode_pool: [ - port: EventStore.TcpProxy.port(proxy), - timeout: 60_000, - idle_interval: 100 - ]} - ) - try do {:ok, lock} = AdvisoryLocks.try_advisory_lock(locks, 1) @@ -983,6 +963,86 @@ defmodule EventStore.AdvisoryLocksTest do end end + describe "lock connection stops answering while a lock query waits on it" do + @tag capture_log: true + test "should send `lock_released` message without waiting for the connection to finish closing", + %{schema: schema} do + {locks, proxy} = + start_proxied_lock_store(:stalled_lock_store, schema, idle_interval: 60_000) + + try do + {:ok, lock} = AdvisoryLocks.try_advisory_lock(locks, 1) + + :ok = EventStore.TcpProxy.freeze(proxy) + + spawn(fn -> AdvisoryLocks.try_advisory_lock(locks, 2, 500) end) + + assert_receive {AdvisoryLocks, :lock_released, ^lock, _reason}, 5_000 + after + stop_supervised!(EventStore.TcpProxy) + end + end + + @tag capture_log: true + test "should send `lock_released` message before answering the calls queued behind the query", + %{schema: schema} do + {locks, proxy} = start_proxied_lock_store(:queued_lock_store, schema, idle_interval: 60_000) + server = Process.whereis(locks) + test_process = self() + + try do + {:ok, lock} = AdvisoryLocks.try_advisory_lock(locks, 1) + + :ok = EventStore.TcpProxy.freeze(proxy) + + spawn(fn -> AdvisoryLocks.try_advisory_lock(locks, 2, 2_000) end) + + Wait.until(fn -> assert {:timeout, _} = catch_exit(:sys.get_state(server, 10)) end) + + spawn(fn -> + send(test_process, {:queued_reply, AdvisoryLocks.try_advisory_lock(locks, 3, 20_000)}) + end) + + Wait.until(fn -> + {:messages, messages} = Process.info(server, :messages) + + assert Enum.any?( + messages, + &match?({:"$gen_call", _from, {:try_advisory_lock, 3, _, _}}, &1) + ) + end) + + assert_receive {AdvisoryLocks, :lock_released, ^lock, _reason}, 10_000 + refute_received {:queued_reply, _reply} + after + stop_supervised!(EventStore.TcpProxy) + end + end + end + + # An event store whose lock connection goes through a proxy that can stop answering. + defp start_proxied_lock_store(name, schema, session_mode_pool_opts) do + config = Config.parsed(TestEventStore, :eventstore) + + proxy = + start_supervised!( + {EventStore.TcpProxy, {Keyword.fetch!(config, :hostname), Keyword.fetch!(config, :port)}} + ) + + start_supervised!( + {TestEventStore, + name: name, + schema: schema, + session_mode_pool: + Keyword.merge( + [port: EventStore.TcpProxy.port(proxy), timeout: 60_000], + session_mode_pool_opts + )} + ) + + {Module.concat([name, AdvisoryLocks]), proxy} + end + # A lock server whose queries give up on a busy connection almost at once. defp start_impatient_lock_server(name, schema) do alias EventStore.Storage.Session