diff --git a/crates/database/.sqlx/query-af7512781fa362a02208733d4ab0a8e500542ab72bb0de645339ce19ec983271.json b/crates/database/.sqlx/query-be1810aec08903cffacb404daeb5b9b833c5edc65fd2d531a661f8dc07e7dde8.json similarity index 92% rename from crates/database/.sqlx/query-af7512781fa362a02208733d4ab0a8e500542ab72bb0de645339ce19ec983271.json rename to crates/database/.sqlx/query-be1810aec08903cffacb404daeb5b9b833c5edc65fd2d531a661f8dc07e7dde8.json index f7ca3d636..f29a06cc5 100644 --- a/crates/database/.sqlx/query-af7512781fa362a02208733d4ab0a8e500542ab72bb0de645339ce19ec983271.json +++ b/crates/database/.sqlx/query-be1810aec08903cffacb404daeb5b9b833c5edc65fd2d531a661f8dc07e7dde8.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT\n e.id AS \"id: EventId\", e.txid::text::bigint AS \"txid!\", e.sequence,\n e.occurred_at, e.kind, e.version, e.payload, e.actor AS \"actor: Json\",\n e.subject_user_id AS \"subject_user_id: UserId\",\n e.trace_id AS \"trace_id: TraceId\",\n p.event_id IS NOT NULL AS \"personal!\", p.client_ip AS \"client_ip?: IpAddr\",\n p.user_agent_family AS \"browser?: Browser\",\n p.platform AS \"platform?: Platform\",\n p.details AS \"details?\", p.reason AS \"reason?\"\n FROM domain_events e\n LEFT JOIN event_personal_data p ON p.event_id = e.id\n LEFT JOIN event_consumers c ON c.name = $1\n WHERE (e.txid, e.sequence) > (COALESCE(c.txid, '0'::xid8), COALESCE(c.sequence, 0))\n AND e.txid < pg_snapshot_xmin(pg_current_snapshot())\n ORDER BY e.txid, e.sequence\n LIMIT $2", + "query": "SELECT\n e.id AS \"id: EventId\", e.txid::text::bigint AS \"txid!\", e.sequence,\n e.occurred_at, e.kind, e.version, e.payload, e.actor AS \"actor: Json\",\n e.subject_user_id AS \"subject_user_id: UserId\",\n e.trace_id AS \"trace_id: TraceId\",\n p.event_id IS NOT NULL AS \"personal!\", p.client_ip AS \"client_ip?: IpAddr\",\n p.user_agent_family AS \"browser?: Browser\",\n p.platform AS \"platform?: Platform\",\n p.details AS \"details?\", p.reason AS \"reason?\"\n FROM domain_events e\n LEFT JOIN event_personal_data p ON p.event_id = e.id\n LEFT JOIN event_consumers c ON c.name = $1\n WHERE (e.txid, e.sequence) > (COALESCE(c.txid, '0'::xid8), COALESCE(c.sequence, 0)) AND e.txid < pg_snapshot_xmin(pg_current_snapshot()) ORDER BY e.txid, e.sequence LIMIT $2", "describe": { "columns": [ { @@ -109,5 +109,5 @@ true ] }, - "hash": "af7512781fa362a02208733d4ab0a8e500542ab72bb0de645339ce19ec983271" + "hash": "be1810aec08903cffacb404daeb5b9b833c5edc65fd2d531a661f8dc07e7dde8" } diff --git a/crates/database/.sqlx/query-5675f85c69bf600c5de917f979039329a33026a83b0327511b4d6622a4598c0b.json b/crates/database/.sqlx/query-fa66a4fb55d05dc901397703382fd3835f1dca45eb8a5fd8910db60e09736432.json similarity index 81% rename from crates/database/.sqlx/query-5675f85c69bf600c5de917f979039329a33026a83b0327511b4d6622a4598c0b.json rename to crates/database/.sqlx/query-fa66a4fb55d05dc901397703382fd3835f1dca45eb8a5fd8910db60e09736432.json index f100739f5..d6c9ea2a0 100644 --- a/crates/database/.sqlx/query-5675f85c69bf600c5de917f979039329a33026a83b0327511b4d6622a4598c0b.json +++ b/crates/database/.sqlx/query-fa66a4fb55d05dc901397703382fd3835f1dca45eb8a5fd8910db60e09736432.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT\n id, kind, version, occurred_at, actor, subject_user_id AS subject,\n client_id AS client, session_id AS session, trace_id, payload\n FROM domain_events\n WHERE chain_position IS NULL\n AND txid < pg_snapshot_xmin(pg_current_snapshot())\n ORDER BY txid, sequence\n LIMIT $1\n FOR UPDATE", + "query": "SELECT\n id, kind, version, occurred_at, actor, subject_user_id AS subject,\n client_id AS client, session_id AS session, trace_id, payload\n FROM domain_events e\n WHERE chain_position IS NULL AND e.txid < pg_snapshot_xmin(pg_current_snapshot()) ORDER BY e.txid, e.sequence LIMIT $1 FOR UPDATE", "describe": { "columns": [ { @@ -72,5 +72,5 @@ false ] }, - "hash": "5675f85c69bf600c5de917f979039329a33026a83b0327511b4d6622a4598c0b" + "hash": "fa66a4fb55d05dc901397703382fd3835f1dca45eb8a5fd8910db60e09736432" } diff --git a/crates/database/src/repositories/audit/mod.rs b/crates/database/src/repositories/audit/mod.rs index 86396a245..588289328 100644 --- a/crates/database/src/repositories/audit/mod.rs +++ b/crates/database/src/repositories/audit/mod.rs @@ -164,10 +164,10 @@ impl From for Checkpoint { impl AuditRepository<'_> { /// Returns up to `limit` unsealed events in the order to seal them: the safe - /// consumer order of [`EventRepository::read_after`](crate::EventRepository::read_after), - /// `(txid, sequence)`, and only events of transactions older than every running - /// one. No event can later appear before one returned here, so positions never - /// need to be reassigned. The rows stay locked until the transaction ends, so + /// consumer order of `in_safe_order!`, which + /// [`EventRepository::read_after`](crate::EventRepository::read_after) shares. No + /// event can later appear before one returned here, so positions never need to be + /// reassigned. The rows stay locked until the transaction ends, so /// none changes between being hashed and being sealed. /// /// # Errors @@ -177,17 +177,14 @@ impl AuditRepository<'_> { run!( self, fetch_all, - sqlx::query_as!( + in_safe_order!( EventContent, r#"SELECT id, kind, version, occurred_at, actor, subject_user_id AS subject, client_id AS client, session_id AS session, trace_id, payload - FROM domain_events - WHERE chain_position IS NULL - AND txid < pg_snapshot_xmin(pg_current_snapshot()) - ORDER BY txid, sequence - LIMIT $1 - FOR UPDATE"#, + FROM domain_events e + WHERE chain_position IS NULL"#, + "LIMIT $1 FOR UPDATE", i64::from(limit), ) ) diff --git a/crates/database/src/repositories/events/mod.rs b/crates/database/src/repositories/events/mod.rs index d3ede80ab..1e21f0097 100644 --- a/crates/database/src/repositories/events/mod.rs +++ b/crates/database/src/repositories/events/mod.rs @@ -498,16 +498,10 @@ impl EventRepository<'_> { Ok(id) } - /// Returns up to `limit` events after `consumer`'s acknowledged cursor, in a - /// safe order, for consumers such as alerts (#83). The audit sealer reads in the - /// same order through [`AuditRepository::unsealed`](crate::AuditRepository::unsealed). - /// - /// Sequence order alone is not safe: a transaction can take sequence 10 and - /// commit after another took 11, so a reader that saw 11 would skip 10. Events - /// are read in `(txid, sequence)` order instead, and only from transactions - /// older than every transaction still running. Those have all finished, so no - /// event can later appear before the cursor. The cost is that a long-running - /// transaction holds back every consumer until it ends. + /// Returns up to `limit` events after `consumer`'s acknowledged cursor, in the + /// safe consumer order of `in_safe_order!`, for consumers such as alerts (#83). + /// No event can later appear before the cursor. The audit sealer reads in the same + /// order through [`AuditRepository::unsealed`](crate::AuditRepository::unsealed). /// /// # Errors /// @@ -520,7 +514,7 @@ impl EventRepository<'_> { run!( self, fetch_all, - sqlx::query_as!( + in_safe_order!( EventRow, r#"SELECT e.id AS "id: EventId", e.txid::text::bigint AS "txid!", e.sequence, @@ -534,10 +528,8 @@ impl EventRepository<'_> { FROM domain_events e LEFT JOIN event_personal_data p ON p.event_id = e.id LEFT JOIN event_consumers c ON c.name = $1 - WHERE (e.txid, e.sequence) > (COALESCE(c.txid, '0'::xid8), COALESCE(c.sequence, 0)) - AND e.txid < pg_snapshot_xmin(pg_current_snapshot()) - ORDER BY e.txid, e.sequence - LIMIT $2"#, + WHERE (e.txid, e.sequence) > (COALESCE(c.txid, '0'::xid8), COALESCE(c.sequence, 0))"#, + "LIMIT $2", consumer, i64::from(limit), ) diff --git a/crates/database/src/repositories/mod.rs b/crates/database/src/repositories/mod.rs index 136995498..73882384d 100644 --- a/crates/database/src/repositories/mod.rs +++ b/crates/database/src/repositories/mod.rs @@ -1,8 +1,8 @@ //! Domain repository handles backed by a private pool or transaction connection. //! //! This module holds only what every repository shares: the executor, the -//! declaration macro, the `run!` query macro and the column types that checked -//! queries decode into. Each submodule owns one repository together with the +//! declaration macro, the `run!` query macro, the `in_safe_order!` event order and +//! the column types that checked queries decode into. Each submodule owns one repository together with the //! records it accepts and returns. use crate::{Database, DatabaseTransaction, ExclusiveConnection}; @@ -153,6 +153,30 @@ macro_rules! run { }}; } +/// A checked `sqlx::query_as!` over `domain_events e` in the safe consumer order, +/// the one rule every cursor-style reader of the stream follows: `$query` selects and +/// filters, the macro adds the rule, and `$tail` follows it (`LIMIT`, row locks), e.g. +/// `in_safe_order!(Row, "SELECT e.id FROM domain_events e WHERE true", "LIMIT $1", 10)`. +/// +/// Sequence order alone is not safe: a transaction can take sequence 10 and commit +/// after another took 11, so a reader that saw 11 would skip 10. Events are read in +/// `(txid, sequence)` order instead, and only from transactions older than every +/// transaction still running. Those have all finished, so no event can later appear +/// before one already read. The cost is that a long-running transaction holds back +/// every reader until it ends. +macro_rules! in_safe_order { + ($record:ty, $query:literal, $tail:literal $(, $arg:expr)* $(,)?) => { + sqlx::query_as!( + $record, + $query + + " AND e.txid < pg_snapshot_xmin(pg_current_snapshot())" + + " ORDER BY e.txid, e.sequence " + + $tail + $(, $arg)* + ) + }; +} + impl RepositoryExecutor<'_> { /// A client span for one query, recording its parameterized `sql` as /// `db.query.text`, never its bind values. A query outside any trace, such as an diff --git a/docs/architecture/database-crate.md b/docs/architecture/database-crate.md index 4e87b0838..e6d808299 100644 --- a/docs/architecture/database-crate.md +++ b/docs/architecture/database-crate.md @@ -320,8 +320,10 @@ consumer's effects. A sequence number alone is not a safe cursor: a transaction take sequence 10 and commit after another one took 11, and a reader that saw 11 would skip 10. Consumers therefore read in `(txid, sequence)` order, and only events of transactions older than every running one (`txid < pg_snapshot_xmin(...)`), which -have all finished. A long-running transaction holds back every consumer until it -ends, so keep transactions short. `history_for_user` lists an account's events, +have all finished. The rule is written once, in the `in_safe_order!` query macro of +`repositories/mod.rs`, which `read_after` and the audit sealer's `audit().unsealed` +both build on. A long-running transaction holds back every consumer until it ends, +so keep transactions short. `history_for_user` lists an account's events, newest first. ### Sessions