diff --git a/README.md b/README.md index 2106260..17f15fd 100644 --- a/README.md +++ b/README.md @@ -30,7 +30,7 @@ MIT License - [Using Postgres schemas](guides/Getting%20Started.md#using-postgres-schemas) - [Event data and metadata data type](guides/Getting%20Started.md#event-data-and-metadata-data-type) - [Using the `jsonb` data type](guides/Getting%20Started.md#using-the-jsonb-data-type) - - [Using with PgBouncer](guides/Getting%20Started.md#using-with-pg-bouncer) + - [Using with PgBouncer](guides/Getting%20Started.md#using-with-pgbouncer) - [Using the EventStore](guides/Usage.md) - [Writing to a stream](guides/Usage.md#writing-to-a-stream) - [Using correlation and causation identifiers](guides/Usage.md#using-correlation-and-causation-identifiers) diff --git a/guides/Cluster.md b/guides/Cluster.md index 26b66cd..ee8b399 100644 --- a/guides/Cluster.md +++ b/guides/Cluster.md @@ -27,7 +27,7 @@ PostgreSQL only releases the locks of a session once it notices the client is go ### Keepalives when PgBouncer is in front of the lock connection -When `session_mode_url` points at PgBouncer in session mode, as suggested in [Using with PgBouncer](Getting Started.md#using-with-pgbouncer), the server's keepalives no longer protect you. The client of the lock session, as PostgreSQL sees it, is PgBouncer, which is still running after a node's host dies, so the server finds nothing wrong and the session keeps its advisory locks. They are released only when PgBouncer notices that its own client is gone and resets the server connection. By default PgBouncer leaves that to the operating system's keepalive settings, which on Linux default to 7,200 seconds before the first probe and then 9 probes 75 seconds apart. That is roughly 2 hours and 11 minutes before PgBouncer can notice, and the lock is released only after it does, so the actual wait depends on PgBouncer and the network as well. Until then no other node can take over the subscriptions. +When `session_mode_url` points at PgBouncer in session mode, as suggested in [Using with PgBouncer](https://hexdocs.pm/eventstore/getting-started.html#using-with-pgbouncer), the server's keepalives no longer protect you. The client of the lock session, as PostgreSQL sees it, is PgBouncer, which is still running after a node's host dies, so the server finds nothing wrong and the session keeps its advisory locks. They are released only when PgBouncer notices that its own client is gone and resets the server connection with its `server_reset_query`. By default PgBouncer leaves that to the operating system's keepalive settings, which on Linux default to 7,200 seconds before the first probe and then 9 probes 75 seconds apart. That is roughly 2 hours and 11 minutes before PgBouncer can notice, and the lock is released only after it does, so the actual wait depends on PgBouncer and the network as well. Until then no other node can take over the subscriptions. Configure the keepalives on PgBouncer as well, in the `[pgbouncer]` section of `pgbouncer.ini`, with the same values as the server advice above: @@ -41,7 +41,9 @@ tcp_keepcnt = 3 `tcp_keepalive` is on by default and uses the operating system's values; `tcp_keepidle`, `tcp_keepintvl` and `tcp_keepcnt` are unset by default and override them, so set them together. In a test that cut a node off from PgBouncer, these values released the lock after about 27 seconds, the same as a connection straight to PostgreSQL, while with the defaults it was still held after 120 seconds. Keep the server's own keepalives as well, since they cover PgBouncer's host dying. -Do not use PgBouncer's `client_idle_timeout` for this. The lock connection is idle between queries by design, so the timeout would close healthy lock sessions and make subscriptions lose their locks. +Keep PgBouncer's `server_reset_query` at its default, `DISCARD ALL`, which releases the session's advisory locks. With an empty reset query, or one that leaves advisory locks in place, PgBouncer drops the dead client but keeps the server connection, and the dead node's locks with it. No node connecting straight to PostgreSQL can take them, while the next client PgBouncer hands that server connection to inherits them without having claimed them. + +Do not rely on PgBouncer's `client_idle_timeout` for this. In a test on PgBouncer 1.24.1 in session mode, `client_idle_timeout = 10` did not close a cut-off node's lock session after 10 seconds; the lock was released only when the keepalives noticed, 25 seconds after the cut, so the setting does not speed up the hand-off. The test cut a node off, so it does not show whether the setting disconnects a healthy client that is idle. Keepalives set on the node's side, such as `socket_options: [keepalive: true]` in `session_mode_pool`, do not help here. Those probes are sent by the node's host, which is the machine that died, so nothing is left to send them. diff --git a/guides/Getting Started.md b/guides/Getting Started.md index c07629e..d053521 100644 --- a/guides/Getting Started.md +++ b/guides/Getting Started.md @@ -86,7 +86,7 @@ EventStore is [available in Hex](https://hex.pm/packages/eventstore) and can be Subscription options: - - `:subscription_retry_interval` - interval between subscription connection retry attempts (default: 60,000ms). + - `:subscription_retry_interval` - interval between a subscription's attempts to take its lock, and between its attempts to read again after a catch-up read fails (default: 60,000ms). A failed read is logged as a warning, and a catch-up request or a notification of new events makes the subscription read again without waiting out the interval. - `:subscription_hibernate_after` - subscriptions will automatically hibernate to save memory after a period of inactivity (default: 15,000ms). 4. Add your event store module to the `event_stores` list for your app in mix config: diff --git a/lib/event_store/subscriptions/subscription.ex b/lib/event_store/subscriptions/subscription.ex index 0c5d50f..73dad4b 100644 --- a/lib/event_store/subscriptions/subscription.ex +++ b/lib/event_store/subscriptions/subscription.ex @@ -236,12 +236,12 @@ defmodule EventStore.Subscriptions.Subscription do end @impl GenServer - def handle_info(:retry_catch_up, %Subscription{} = state) do + def handle_info({:timeout, ref, :retry_catch_up}, %Subscription{} = state) do %Subscription{subscription: subscription} = state state = subscription - |> SubscriptionFsm.retry_catch_up() + |> SubscriptionFsm.retry_catch_up(ref) |> apply_subscription_to_state(state) {:noreply, state} diff --git a/lib/event_store/subscriptions/subscription_fsm.ex b/lib/event_store/subscriptions/subscription_fsm.ex index b967bb5..19e4d0f 100644 --- a/lib/event_store/subscriptions/subscription_fsm.ex +++ b/lib/event_store/subscriptions/subscription_fsm.ex @@ -140,13 +140,28 @@ defmodule EventStore.Subscriptions.SubscriptionFsm do %__MODULE__{fsm | state: :request_catch_up, data: data} end + # A catch-up request is a reason to try again now rather than wait out a failed read's retry. + def catch_up( + %__MODULE__{state: :catching_up, data: %SubscriptionState{retry_timer_ref: ref} = data} = + fsm + ) + when is_reference(ref) do + catch_up_from_stream(fsm, cancel_retry(data)) + end + def catch_up(%__MODULE__{data: %SubscriptionState{}} = fsm), do: fsm - def retry_catch_up(%__MODULE__{state: :catching_up, data: %SubscriptionState{} = data} = fsm) do - catch_up_from_stream(fsm, data) + # A retry already in the mailbox when an early read armed the next one must not start a second retry. + def retry_catch_up( + %__MODULE__{state: :catching_up, data: %SubscriptionState{retry_timer_ref: ref} = data} = + fsm, + ref + ) + when is_reference(ref) do + catch_up_from_stream(fsm, %SubscriptionState{data | retry_timer_ref: nil}) end - def retry_catch_up(%__MODULE__{} = fsm), do: fsm + def retry_catch_up(%__MODULE__{} = fsm, _ref), do: fsm def ack( %__MODULE__{state: :request_catch_up, data: %SubscriptionState{} = data} = fsm, @@ -160,6 +175,21 @@ defmodule EventStore.Subscriptions.SubscriptionFsm do end end + # A failed read already has a retry pending, so an ack must not start another one. + def ack( + %__MODULE__{state: :catching_up, data: %SubscriptionState{retry_timer_ref: ref} = data} = + fsm, + ack, + subscriber + ) + when is_reference(ref) do + with {:ok, data} <- ack_events(data, ack, subscriber) do + %__MODULE__{fsm | state: :catching_up, data: data} + else + reply -> {reply, fsm} + end + end + def ack( %__MODULE__{state: :catching_up, data: %SubscriptionState{} = data} = fsm, ack, @@ -305,6 +335,18 @@ defmodule EventStore.Subscriptions.SubscriptionFsm do end end + # New events are a reason to try again now rather than wait out a failed read's retry. + def notify_events( + %__MODULE__{state: :catching_up, data: %SubscriptionState{retry_timer_ref: ref} = data} = + fsm, + events + ) + when is_reference(ref) do + data = data |> track_last_received(events) |> cancel_retry() + + catch_up_from_stream(fsm, data) + end + # Ignore notify events unless subscribed def notify_events(%__MODULE__{data: %SubscriptionState{} = data} = fsm, events) do %__MODULE__{fsm | data: track_last_received(data, events)} @@ -335,6 +377,8 @@ defmodule EventStore.Subscriptions.SubscriptionFsm do %SubscriptionState{data | lock_ref: nil, fencing_token: nil} |> SubscriptionState.reset_event_tracking() |> purge_in_flight_events() + # A retry left over from before the lock was lost would hold back acks after reconnecting. + |> cancel_retry() %__MODULE__{fsm | state: :disconnected, data: data} end @@ -504,12 +548,14 @@ defmodule EventStore.Subscriptions.SubscriptionFsm do # Allow subscriptions to streams which don't yet exist, but might be created later %__MODULE__{fsm | state: :subscribed, data: data} - {:error, _error} -> - # A failed read says nothing about the stream, so wait out the retry interval and read again - %SubscriptionState{retry_interval: retry_interval} = data - Process.send_after(self(), :retry_catch_up, retry_interval) + {:error, error} -> + Logger.warning( + describe(data) <> + " failed to catch up, retrying in #{data.retry_interval}ms due to: " <> inspect(error) + ) - %__MODULE__{fsm | state: :catching_up, data: data} + # A failed read says nothing about the stream, so wait out the retry interval and read again + %__MODULE__{fsm | state: :catching_up, data: schedule_retry(data)} end end @@ -517,6 +563,22 @@ defmodule EventStore.Subscriptions.SubscriptionFsm do %__MODULE__{fsm | state: :catching_up, data: data} end + defp schedule_retry(%SubscriptionState{} = data) do + %SubscriptionState{retry_interval: retry_interval} = data = cancel_retry(data) + + retry_timer_ref = :erlang.start_timer(retry_interval, self(), :retry_catch_up) + + %SubscriptionState{data | retry_timer_ref: retry_timer_ref} + end + + defp cancel_retry(%SubscriptionState{retry_timer_ref: nil} = data), do: data + + defp cancel_retry(%SubscriptionState{retry_timer_ref: retry_timer_ref} = data) do + Process.cancel_timer(retry_timer_ref) + + %SubscriptionState{data | retry_timer_ref: nil} + end + defp read_stream_forward(%SubscriptionState{} = data) do %SubscriptionState{ conn: conn, diff --git a/lib/event_store/subscriptions/subscription_state.ex b/lib/event_store/subscriptions/subscription_state.ex index 8df1eb7..2142a63 100644 --- a/lib/event_store/subscriptions/subscription_state.ex +++ b/lib/event_store/subscriptions/subscription_state.ex @@ -33,6 +33,7 @@ defmodule EventStore.Subscriptions.SubscriptionState do checkpoint_after: 0, checkpoint_threshold: 1, checkpoint_timer_ref: nil, + retry_timer_ref: nil, checkpoints_pending: 0, checkpoint_unwritten: false, subscribers: %{}, diff --git a/test/storage/subscription_lock_refused_test.exs b/test/storage/subscription_lock_refused_test.exs new file mode 100644 index 0000000..75cd416 --- /dev/null +++ b/test/storage/subscription_lock_refused_test.exs @@ -0,0 +1,82 @@ +defmodule EventStore.Storage.SubscriptionLockRefusedTest do + use EventStore.StorageCase + + alias EventStore.Storage.Lock + + @database "eventstore_test_xact_lock_denied" + @role "eventstore_xact_lock_denied" + + setup %{conn: conn, postgrex_config: postgrex_config} do + drop = fn -> + # DROP DATABASE ... WITH (FORCE) needs PostgreSQL 13, so end the sessions first. + Postgrex.query!( + conn, + "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = $1", + [@database] + ) + + # Sessions end asynchronously and the drop waits only five seconds for them. + await_no_sessions(conn, 100) + + Postgrex.query!(conn, ~s|DROP DATABASE IF EXISTS "#{@database}"|, []) + Postgrex.query!(conn, ~s|DROP ROLE IF EXISTS "#{@role}"|, []) + end + + drop.() + on_exit(fn -> drop.() end) + + Postgrex.query!(conn, ~s|CREATE ROLE "#{@role}" LOGIN PASSWORD 'secret'|, []) + Postgrex.query!(conn, ~s|CREATE DATABASE "#{@database}" TEMPLATE template0|, []) + + {:ok, admin} = Postgrex.start_link(Keyword.put(postgrex_config, :database, @database)) + + Postgrex.query!( + admin, + "CREATE TABLE public.subscriptions (subscription_id bigint PRIMARY KEY, " <> + "lock_generation bigint NOT NULL DEFAULT 0, last_seen bigint)", + [] + ) + + Postgrex.query!(admin, "INSERT INTO public.subscriptions (subscription_id) VALUES (1)", []) + Postgrex.query!(admin, ~s|GRANT SELECT, UPDATE ON public.subscriptions TO "#{@role}"|, []) + + Postgrex.query!( + admin, + "REVOKE EXECUTE ON FUNCTION pg_catalog.pg_try_advisory_xact_lock(integer, integer) FROM PUBLIC", + [] + ) + + GenServer.stop(admin) + + role_config = + Keyword.merge(postgrex_config, database: @database, username: @role, password: "secret") + + [role_conn: start_supervised!({Postgrex, role_config}, id: :role_conn)] + end + + test "a claim returns the error when only the advisory lock statement is refused", context do + assert {:error, %Postgrex.Error{postgres: %{code: :insufficient_privilege} = postgres}} = + Lock.claim_subscription_lock(context.role_conn, 1, schema: "public") + + assert postgres.message =~ "pg_try_advisory_xact_lock" + end + + defp await_no_sessions(conn, attempts) do + %Postgrex.Result{rows: [[sessions]]} = + Postgrex.query!(conn, "SELECT count(*) FROM pg_stat_activity WHERE datname = $1", [ + @database + ]) + + cond do + sessions == 0 -> + :ok + + attempts > 0 -> + Process.sleep(100) + await_no_sessions(conn, attempts - 1) + + true -> + flunk("#{sessions} sessions on #{@database} did not end") + end + end +end diff --git a/test/subscriptions/subscription_fsm_test.exs b/test/subscriptions/subscription_fsm_test.exs index e707757..fd7e25c 100644 --- a/test/subscriptions/subscription_fsm_test.exs +++ b/test/subscriptions/subscription_fsm_test.exs @@ -1,6 +1,8 @@ defmodule EventStore.Subscriptions.SubscriptionFsmTest do use EventStore.StorageCase + import ExUnit.CaptureLog + alias EventStore.{EventFactory, Storage, UUID} alias EventStore.Storage.Lock alias EventStore.Subscriptions.{Subscription, SubscriptionFsm, SubscriptionState} @@ -535,13 +537,22 @@ defmodule EventStore.Subscriptions.SubscriptionFsmTest do assert %SubscriptionFsm{state: :catching_up} = SubscriptionFsm.catch_up(fsm) end + test "logs why the read failed", context do + fsm = fsm(context, state: :request_catch_up, schema: "no_such_schema") + + log = capture_log([level: :warning], fn -> SubscriptionFsm.catch_up(fsm) end) + + assert log =~ "failed to catch up" + assert log =~ "no_such_schema" + end + test "asks to read again after the retry interval", context do fsm = fsm(context, state: :request_catch_up, schema: "no_such_schema", retry_interval: 20) SubscriptionFsm.catch_up(fsm) - assert_receive :retry_catch_up, 1_000 + assert_receive {:timeout, _ref, :retry_catch_up}, 1_000 end test "reads again and delivers events once storage recovers", context do @@ -550,11 +561,11 @@ defmodule EventStore.Subscriptions.SubscriptionFsmTest do fsm = SubscriptionFsm.connect_subscriber(fsm, self(), buffer_size: 10) - %SubscriptionFsm{data: data} = failed = SubscriptionFsm.catch_up(fsm) + %SubscriptionFsm{data: %SubscriptionState{} = data} = failed = SubscriptionFsm.catch_up(fsm) :ok = TestEventStore.append_to_stream(context.stream_uuid, 0, EventFactory.create_events(3)) - assert_receive :retry_catch_up, 1_000 + assert_receive {:timeout, ref, :retry_catch_up}, 1_000 refute_received {:events, _events} recovered = %SubscriptionFsm{ @@ -563,17 +574,165 @@ defmodule EventStore.Subscriptions.SubscriptionFsmTest do } assert %SubscriptionFsm{state: :request_catch_up, data: data} = - SubscriptionFsm.retry_catch_up(recovered) + SubscriptionFsm.retry_catch_up(recovered, ref) assert data.last_sent == 3 assert_received {:events, [%{event_number: 1}, %{event_number: 2}, %{event_number: 3}]} end - test "ignores a retry for a subscription that is no longer waiting on one", context do - fsm = fsm(context, state: :subscribed) + test "retries a read that fails because the pool has no connection to give", context do + %{conn: conn} = context + fsm = fsm(context, state: :request_catch_up, retry_interval: 20, query_timeout: 100) + test_pid = self() + + holder = + Task.async(fn -> + Postgrex.transaction(conn, fn _held -> + send(test_pid, :connection_held) + receive do: (:release -> :ok) + end) + end) + + assert_receive :connection_held, 5_000 + + assert %SubscriptionFsm{state: :catching_up} = SubscriptionFsm.catch_up(fsm) + assert_receive {:timeout, _ref, :retry_catch_up}, 1_000 + + send(holder.pid, :release) + assert {:ok, :ok} = Task.await(holder) + end + + test "waits the retry interval before reading again", context do + fsm = + fsm(context, state: :request_catch_up, schema: "no_such_schema", retry_interval: 5_000) + + assert %SubscriptionFsm{state: :catching_up} = SubscriptionFsm.catch_up(fsm) + refute_receive {:timeout, _ref, :retry_catch_up}, 300 + end + + test "reads again on a catch-up request instead of waiting out the retry", context do + failed = failed_read(context) + + :ok = TestEventStore.append_to_stream(context.stream_uuid, 0, EventFactory.create_events(2)) + + assert %SubscriptionFsm{state: :request_catch_up} = + failed |> recover_schema(context) |> SubscriptionFsm.catch_up() + + assert_received {:events, [%{event_number: 1}, %{event_number: 2}]} + end + + test "reads again on a notification of new events instead of waiting out the retry", + context do + failed = failed_read(context) + + :ok = TestEventStore.append_to_stream(context.stream_uuid, 0, EventFactory.create_events(2)) + {:ok, events} = TestEventStore.read_stream_forward(context.stream_uuid) + + assert %SubscriptionFsm{state: :request_catch_up} = + failed |> recover_schema(context) |> SubscriptionFsm.notify_events(events) + + assert_received {:events, [%{event_number: 1}, %{event_number: 2}]} + end + + test "leaves no retry pending once an early read succeeds", context do + failed = failed_read(context, retry_interval: 200) + + failed |> recover_schema(context) |> SubscriptionFsm.catch_up() + + refute_receive {:timeout, _ref, :retry_catch_up}, 400 + end + + test "ignores a retry that was already due when an early read armed the next one", context do + failed = failed_read(context, retry_interval: 200) + + assert_receive {:timeout, stale, :retry_catch_up}, 1_000 + + rearmed = SubscriptionFsm.catch_up(failed) + + assert %SubscriptionFsm{state: :catching_up} = + SubscriptionFsm.retry_catch_up(rearmed, stale) - assert ^fsm = SubscriptionFsm.retry_catch_up(fsm) + assert_receive {:timeout, _ref, :retry_catch_up}, 1_000 + refute_receive {:timeout, _ref, :retry_catch_up}, 400 end + + test "drops the pending retry when the subscription loses its lock", context do + lock_ref = make_ref() + + %SubscriptionFsm{data: %SubscriptionState{} = data} = + failed = failed_read(context, retry_interval: 200) + + failed = %SubscriptionFsm{failed | data: %SubscriptionState{data | lock_ref: lock_ref}} + + assert %SubscriptionFsm{state: :disconnected, data: data} = + SubscriptionFsm.disconnect(failed, lock_ref) + + assert data.retry_timer_ref == nil + refute_receive {:timeout, _ref, :retry_catch_up}, 400 + end + + test "waits on in-flight events without a pending retry", context do + fsm = in_flight_fsm(context, 1, state: :catching_up) + + assert ^fsm = SubscriptionFsm.catch_up(fsm) + end + + test "keeps a single retry pending when in-flight events are acked one by one", context do + :ok = + TestEventStore.append_to_stream(context.stream_uuid, 0, EventFactory.create_events(10)) + + %SubscriptionFsm{data: %SubscriptionState{} = data} = + context + |> fsm(state: :request_catch_up, retry_interval: 200, checkpoint_threshold: 100) + |> SubscriptionFsm.connect_subscriber(self(), buffer_size: 10) + |> SubscriptionFsm.catch_up() + + assert_received {:events, events} + assert length(events) == 10 + + failed = + SubscriptionFsm.catch_up(%SubscriptionFsm{ + state: :request_catch_up, + data: %SubscriptionState{data | schema: "no_such_schema"} + }) + + acked = + Enum.reduce(events, failed, fn %{event_number: event_number}, fsm -> + SubscriptionFsm.ack(fsm, event_number, self()) + end) + + assert %SubscriptionFsm{state: :catching_up} = acked + assert_receive {:timeout, _ref, :retry_catch_up}, 1_000 + refute_receive {:timeout, _ref, :retry_catch_up}, 400 + end + + for state <- [:subscribed, :max_capacity] do + test "ignores a retry for a #{state} subscription even with events to read", context do + fsm = + context + |> fsm(state: unquote(state)) + |> SubscriptionFsm.connect_subscriber(self(), buffer_size: 10) + + :ok = + TestEventStore.append_to_stream(context.stream_uuid, 0, EventFactory.create_events(3)) + + assert ^fsm = SubscriptionFsm.retry_catch_up(fsm, make_ref()) + refute_received {:events, _events} + end + end + end + + defp failed_read(context, overrides \\ []) do + context + |> fsm( + [state: :request_catch_up, schema: "no_such_schema", checkpoint_threshold: 100] ++ overrides + ) + |> SubscriptionFsm.connect_subscriber(self(), buffer_size: 10) + |> SubscriptionFsm.catch_up() + end + + defp recover_schema(%SubscriptionFsm{data: %SubscriptionState{} = data} = fsm, context) do + %SubscriptionFsm{fsm | data: %SubscriptionState{data | schema: context.schema}} end defp in_flight_fsm(context, count, overrides) do @@ -646,7 +805,7 @@ defmodule EventStore.Subscriptions.SubscriptionFsmTest do checkpoint_after: Keyword.get(overrides, :checkpoint_after, 0), checkpoint_threshold: Keyword.get(overrides, :checkpoint_threshold, 1), retry_interval: Keyword.get(overrides, :retry_interval, 60_000), - query_timeout: 15_000, + query_timeout: Keyword.get(overrides, :query_timeout, 15_000), event_store: TestEventStore, serializer: context.serializer, correlation_id_type: context.correlation_id_type,