Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
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 README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
6 changes: 4 additions & 2 deletions guides/Cluster.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand All @@ -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.

Expand Down
2 changes: 1 addition & 1 deletion guides/Getting Started.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
4 changes: 2 additions & 2 deletions lib/event_store/subscriptions/subscription.ex
Original file line number Diff line number Diff line change
Expand Up @@ -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}
Expand Down
78 changes: 70 additions & 8 deletions lib/event_store/subscriptions/subscription_fsm.ex
Original file line number Diff line number Diff line change
Expand Up @@ -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})
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
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,
Expand All @@ -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,
Expand Down Expand Up @@ -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)}
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -504,19 +548,37 @@ 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

defp catch_up_from_stream(%__MODULE__{} = fsm, %SubscriptionState{} = data) 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)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

%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,
Expand Down
1 change: 1 addition & 0 deletions lib/event_store/subscriptions/subscription_state.ex
Original file line number Diff line number Diff line change
Expand Up @@ -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: %{},
Expand Down
82 changes: 82 additions & 0 deletions test/storage/subscription_lock_refused_test.exs
Original file line number Diff line number Diff line change
@@ -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",
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
[@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
Loading
Loading