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
14 changes: 13 additions & 1 deletion guides/Upgrades.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,18 @@
# Upgrading an EventStore

The [CHANGELOG](https://github.com/commanded/eventstore/blob/master/CHANGELOG.md) is used to indicate when a schema migration is required for a given version of the EventStore.
Versions that need a schema migration are listed below. The [CHANGELOG](https://github.com/TrogonStack/commanded_eventstore/blob/main/CHANGELOG.md) of this fork and the [upstream CHANGELOG](https://github.com/commanded/eventstore/blob/master/CHANGELOG.md) for versions before the fork describe what changed in each release.

## Upgrading to 1.5.0

1.5.0 adds a `lock_generation` column to the `subscriptions` table, which fences the progress writes of a node that lost a subscription's lock. Run `mix event_store.migrate` (or `EventStore.Tasks.Migrate.exec/2` from a release) before starting any node on 1.5.0. EventStore does not migrate on start: a 1.5.0 node on an unmigrated database starts, but none of its persistent subscriptions ever subscribe, and it logs an error naming the migration until the schema is migrated.

Subscription locks are now taken with an `UPDATE` on the `subscriptions` table over the session mode connection. When `session_mode_pool` (or `session_mode_url`) connects as a different role from the main pool, grant that role `SELECT` and `UPDATE` on `subscriptions` in the event store's schema:

```sql
GRANT SELECT, UPDATE ON "public".subscriptions TO session_mode_role;
```

Without these grants, persistent subscriptions never subscribe and the node logs an error naming the missing privileges.

## Migrate before rolling nodes

Expand Down
65 changes: 62 additions & 3 deletions lib/event_store/advisory_locks.ex
Original file line number Diff line number Diff line change
Expand Up @@ -18,23 +18,66 @@ defmodule EventStore.AdvisoryLocks do
defstruct [
:conn,
:connection,
:event_store,
:lost_connection,
:monitor,
:query_timeout,
:ref,
:schema,
:verify_timer,
locks: %{},
released: []
released: [],
reported_claim_problems: MapSet.new()
]

def new(opts) do
conn = Keyword.fetch!(opts, :conn)
event_store = Keyword.fetch!(opts, :event_store)
monitor = Keyword.fetch!(opts, :monitor)
query_timeout = Keyword.fetch!(opts, :query_timeout)
schema = Keyword.fetch!(opts, :schema)

%State{conn: conn, monitor: monitor, query_timeout: query_timeout, schema: schema}
%State{
conn: conn,
event_store: event_store,
monitor: monitor,
query_timeout: query_timeout,
schema: schema
}
end
end

defmodule ClaimProblem do
@moduledoc false

# A claim that fails on the schema or on the lock role's grants keeps failing
# on every retry until an operator acts, so it is reported to them.

@type t :: :schema_outdated | :missing_grants

@spec from_error(Postgrex.Error.t()) :: {:ok, t()} | :error
def from_error(%Postgrex.Error{postgres: %{code: :undefined_column}}),
do: {:ok, :schema_outdated}

def from_error(%Postgrex.Error{postgres: %{code: :insufficient_privilege}}),
do: {:ok, :missing_grants}

def from_error(%Postgrex.Error{}), do: :error

@spec message(t(), event_store :: atom(), schema :: String.t(), Postgrex.Error.t()) ::
String.t()
def message(:schema_outdated, event_store, _schema, error) do
"EventStore #{inspect(event_store)} cannot start persistent subscriptions because " <>
"its database schema predates v1.5.0. Run `mix event_store.migrate` (or " <>
"`EventStore.Tasks.Migrate.exec/2`); subscriptions keep retrying until then. " <>
"Reason: " <> Exception.message(error)
end

def message(:missing_grants, event_store, schema, error) do
"EventStore #{inspect(event_store)} cannot start persistent subscriptions because " <>
"the role of its session mode connection lacks privileges on " <>
~s("#{schema}".subscriptions. Grant it SELECT and UPDATE on that table; ) <>
"subscriptions keep retrying until then. Reason: " <> Exception.message(error)
end
end

Expand Down Expand Up @@ -104,7 +147,7 @@ defmodule EventStore.AdvisoryLocks do
end

alias DBConnection.ConnectionError
alias EventStore.AdvisoryLocks.{Connection, Lease, Lock, State}
alias EventStore.AdvisoryLocks.{ClaimProblem, Connection, Lease, Lock, State}
alias EventStore.Storage
alias EventStore.Storage.Session

Expand Down Expand Up @@ -236,6 +279,9 @@ defmodule EventStore.AdvisoryLocks do
{:reply, {:ok, Lease.new(ref, lease)},
%State{state | locks: Map.put(locks, owner_ref, lock)}}

{_held, {:error, %Postgrex.Error{} = error} = reply} ->
{:reply, reply, report_claim_problem(error, state)}

{_held, reply} ->
{:reply, reply, state}
end
Expand Down Expand Up @@ -270,6 +316,19 @@ defmodule EventStore.AdvisoryLocks do
end)
end

defp report_claim_problem(%Postgrex.Error{} = error, %State{} = state) do
%State{event_store: event_store, schema: schema, reported_claim_problems: reported} = state

with {:ok, problem} <- ClaimProblem.from_error(error),
false <- MapSet.member?(reported, problem) do
Logger.error(ClaimProblem.message(problem, event_store, schema, error))

%State{state | reported_claim_problems: MapSet.put(reported, problem)}
else
_reported_or_transient -> state
end
end

defp held_lock(%State{locks: locks}, key, owner) do
Enum.find(locks, fn
{_owner_ref, %Lock{key: ^key, owner: ^owner}} -> true
Expand Down
1 change: 1 addition & 0 deletions lib/event_store/supervisor.ex
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ defmodule EventStore.Supervisor do
),
{AdvisoryLocks,
conn: advisory_locks_postgrex_conn,
event_store: name,
monitor: advisory_locks_postgrex_monitor,
query_timeout: query_timeout,
schema: schema,
Expand Down
4 changes: 4 additions & 0 deletions test/advisory_locks_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -732,6 +732,7 @@ defmodule EventStore.AdvisoryLocksTest do
start_supervised!(
{AdvisoryLocks,
conn: conn_name,
event_store: TestEventStore,
monitor: monitor_name,
query_timeout: Keyword.fetch!(config, :timeout),
schema: "public",
Expand Down Expand Up @@ -770,6 +771,7 @@ defmodule EventStore.AdvisoryLocksTest do
start_supervised!(
{AdvisoryLocks,
conn: conn_name,
event_store: TestEventStore,
monitor: monitor_name,
query_timeout: Keyword.fetch!(config, :timeout),
schema: "public",
Expand Down Expand Up @@ -823,6 +825,7 @@ defmodule EventStore.AdvisoryLocksTest do
start_supervised(
{AdvisoryLocks,
conn: conn_name,
event_store: TestEventStore,
monitor: monitor_name,
query_timeout: Keyword.fetch!(config, :timeout),
schema: "public",
Expand Down Expand Up @@ -860,6 +863,7 @@ defmodule EventStore.AdvisoryLocksTest do
start_supervised!(
{AdvisoryLocks,
conn: conn_name,
event_store: TestEventStore,
monitor: monitor_name,
query_timeout: 100,
schema: schema,
Expand Down
79 changes: 78 additions & 1 deletion test/subscriptions/subscription_unmigrated_schema_test.exs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
defmodule EventStore.Subscriptions.SubscriptionUnmigratedSchemaTest do
use EventStore.StorageCase

alias EventStore.{EventFactory, UUID, Wait}
import ExUnit.CaptureLog

alias EventStore.{AdvisoryLocks, EventFactory, UUID, Wait}
alias EventStore.Subscriptions.Subscription

@advisory_locks TestEventStore.EventStore.AdvisoryLocks
Expand Down Expand Up @@ -39,6 +41,81 @@ defmodule EventStore.Subscriptions.SubscriptionUnmigratedSchemaTest do
Wait.until(fn -> assert :subscribed == subscription_state(subscription) end)
end

test "a database without the lock generation tells the operator to migrate, once",
%{conn: conn} do
on_exit(fn -> add_lock_generation(conn) end)

Postgrex.query!(conn, "ALTER TABLE subscriptions DROP COLUMN lock_generation", [])

log =
capture_log(fn ->
{:ok, _subscription} =
TestEventStore.subscribe_to_all_streams(UUID.uuid4(), self(), buffer_size: 10)

claim_repeatedly(@advisory_locks, :undefined_column)

refute_receive {:subscribed, _subscription}
end)

assert [_reported] = Regex.scan(~r/\[error\].*TestEventStore/, log)
assert log =~ "v1.5.0"
assert log =~ "mix event_store.migrate"
end

test "a session pool role that cannot update subscriptions is named as the cause, once",
%{conn: conn, schema: schema} do
role = "es_lock_role_" <> String.replace(UUID.uuid4(), "-", "")
password = UUID.uuid4()

on_exit(fn -> drop_role(conn, schema, role) end)

Postgrex.query!(conn, ~s(CREATE ROLE "#{role}" LOGIN PASSWORD '#{password}'), [])
Postgrex.query!(conn, ~s(GRANT USAGE ON SCHEMA "#{schema}" TO "#{role}"), [])
Postgrex.query!(conn, ~s(GRANT SELECT ON "#{schema}".subscriptions TO "#{role}"), [])

start_supervised!(
{TestEventStore,
name: :limited_lock_role_store,
schema: schema,
session_mode_pool: [username: role, password: password]},
id: :limited_lock_role_store
)

log =
capture_log(fn ->
{:ok, _subscription} =
TestEventStore.subscribe_to_all_streams(UUID.uuid4(), self(),
name: :limited_lock_role_store,
buffer_size: 10
)

claim_repeatedly(
Module.concat([:limited_lock_role_store, AdvisoryLocks]),
:insufficient_privilege
)

refute_receive {:subscribed, _subscription}
end)

assert [_reported] = Regex.scan(~r/\[error\].*limited_lock_role_store/, log)
assert log =~ "UPDATE"
assert log =~ ~s("#{schema}".subscriptions)
end

# Every claim fails the same way, so each one is a chance to report it again.
defp claim_repeatedly(advisory_locks, code) do
for _attempt <- 1..3 do
assert {:error, %Postgrex.Error{postgres: %{code: ^code}}} =
AdvisoryLocks.try_subscription_lock(advisory_locks, 1, 5_000)
end
end

defp drop_role(conn, schema, role) do
Postgrex.query!(conn, ~s(REVOKE ALL ON ALL TABLES IN SCHEMA "#{schema}" FROM "#{role}"), [])
Postgrex.query!(conn, ~s(REVOKE ALL ON SCHEMA "#{schema}" FROM "#{role}"), [])
Postgrex.query!(conn, ~s(DROP ROLE IF EXISTS "#{role}"), [])
end

defp add_lock_generation(conn) do
Postgrex.query!(
conn,
Expand Down
Loading