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

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

19 changes: 8 additions & 11 deletions crates/database/src/repositories/audit/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -164,10 +164,10 @@ impl From<CheckpointRow> 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
Expand All @@ -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),
)
)
Expand Down
22 changes: 7 additions & 15 deletions crates/database/src/repositories/events/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
///
Expand All @@ -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,
Expand All @@ -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),
)
Expand Down
28 changes: 26 additions & 2 deletions crates/database/src/repositories/mod.rs
Original file line number Diff line number Diff line change
@@ -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};
Expand Down Expand Up @@ -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
Expand Down
6 changes: 4 additions & 2 deletions docs/architecture/database-crate.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading