diff --git a/guides/Upgrades.md b/guides/Upgrades.md index bc0675ce..1894e2b5 100644 --- a/guides/Upgrades.md +++ b/guides/Upgrades.md @@ -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 diff --git a/lib/event_store/advisory_locks.ex b/lib/event_store/advisory_locks.ex index 68b74809..76b1350b 100644 --- a/lib/event_store/advisory_locks.ex +++ b/lib/event_store/advisory_locks.ex @@ -18,6 +18,7 @@ defmodule EventStore.AdvisoryLocks do defstruct [ :conn, :connection, + :event_store, :lost_connection, :monitor, :query_timeout, @@ -25,16 +26,58 @@ defmodule EventStore.AdvisoryLocks do :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 @@ -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 @@ -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 @@ -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 diff --git a/lib/event_store/supervisor.ex b/lib/event_store/supervisor.ex index 69d47325..aa6aed25 100644 --- a/lib/event_store/supervisor.ex +++ b/lib/event_store/supervisor.ex @@ -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, diff --git a/test/advisory_locks_test.exs b/test/advisory_locks_test.exs index d18166c5..a68707df 100644 --- a/test/advisory_locks_test.exs +++ b/test/advisory_locks_test.exs @@ -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", @@ -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", @@ -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", @@ -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, diff --git a/test/subscriptions/subscription_unmigrated_schema_test.exs b/test/subscriptions/subscription_unmigrated_schema_test.exs index c66a85cc..fbe6cd96 100644 --- a/test/subscriptions/subscription_unmigrated_schema_test.exs +++ b/test/subscriptions/subscription_unmigrated_schema_test.exs @@ -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 @@ -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,