diff --git a/libs/@local/graph/postgres-store/src/store/postgres/knowledge/entity/outbox.rs b/libs/@local/graph/postgres-store/src/store/postgres/knowledge/entity/outbox.rs index 21635b32bda..702db81b34b 100644 --- a/libs/@local/graph/postgres-store/src/store/postgres/knowledge/entity/outbox.rs +++ b/libs/@local/graph/postgres-store/src/store/postgres/knowledge/entity/outbox.rs @@ -5,7 +5,7 @@ use core::{error::Error, num::NonZero}; use bytes::{BufMut as _, BytesMut}; use error_stack::{Report, ResultExt as _}; use futures::{Stream, StreamExt as _, TryFutureExt as _}; -use hash_graph_store::error::QueryError; +use hash_graph_store::error::{QueryError, UpdateError}; use hash_graph_temporal_versioning::{DecisionTime, Timestamp, TransactionTime}; use postgres_types::{FromSql, IsNull, ToSql, Type, to_sql_checked}; use tokio_postgres::{GenericClient as _, Row}; @@ -205,6 +205,108 @@ where .map_err(|error| Report::new(error).change_context(QueryError)) }) } + + /// Returns the cursor of the last event `relay` has published, or [`None`] if it has stored + /// none. + /// + /// # Errors + /// + /// - if the cursor could not be read + #[tracing::instrument(level = "debug", skip(self))] + pub async fn entity_outbox_cursor( + &self, + relay: &str, + ) -> Result, Report> { + let row = self + .as_client() + .query_opt( + "SELECT transaction_id, ordinal FROM entity_outbox_cursor WHERE relay = $1", + &[&relay], + ) + .instrument(tracing::info_span!( + "SELECT entity outbox cursor", + otel.kind = "client", + db.system = "postgresql", + peer.service = "Postgres", + )) + .await + .change_context(QueryError)?; + + row.map(|row| { + Ok(EntityOutboxCursor { + transaction_id: row.try_get(0)?, + ordinal: row.try_get(1)?, + }) + }) + .transpose() + .map_err(|error: tokio_postgres::Error| Report::new(error).change_context(QueryError)) + } + + /// Stores `cursor` as the cursor of the last event `relay` has published. + /// + /// # Errors + /// + /// - if the cursor could not be stored + #[tracing::instrument(level = "debug", skip(self))] + pub async fn store_entity_outbox_cursor( + &self, + relay: &str, + cursor: EntityOutboxCursor, + ) -> Result<(), Report> { + self.as_client() + .execute( + " + INSERT INTO entity_outbox_cursor (relay, transaction_id, ordinal) + VALUES ($1, $2, $3) + ON CONFLICT (relay) DO UPDATE + SET transaction_id = excluded.transaction_id, + ordinal = excluded.ordinal;", + &[&relay, &cursor.transaction_id, &cursor.ordinal], + ) + .instrument(tracing::info_span!( + "UPSERT entity outbox cursor", + otel.kind = "client", + db.system = "postgresql", + peer.service = "Postgres", + )) + .await + .change_context(UpdateError)?; + + Ok(()) + } + + /// Tries to become the only connection that publishes the outbox as `relay`. + /// + /// Returns `false` if another connection holds that role. The role is a session-level advisory + /// lock: the database releases it when the connection of this store closes, also when the + /// process holding it dies. + /// + /// # Errors + /// + /// - if the lock could not be requested + #[tracing::instrument(level = "debug", skip(self))] + pub async fn try_lock_entity_outbox_relay( + &self, + relay: &str, + ) -> Result> { + self.as_client() + .query_one( + "SELECT pg_try_advisory_lock( + 'entity_outbox_cursor'::regclass::oid::integer, + hashtext($1) + )", + &[&relay], + ) + .instrument(tracing::info_span!( + "LOCK entity outbox relay", + otel.kind = "client", + db.system = "postgresql", + peer.service = "Postgres", + )) + .await + .and_then(|row| row.try_get(0)) + .change_context(QueryError) + } } impl PostgresStore diff --git a/libs/@local/graph/postgres-store/tests/outbox/main.rs b/libs/@local/graph/postgres-store/tests/outbox/main.rs index c8028dcdb29..472a14b5523 100644 --- a/libs/@local/graph/postgres-store/tests/outbox/main.rs +++ b/libs/@local/graph/postgres-store/tests/outbox/main.rs @@ -293,3 +293,56 @@ async fn limit_splits_a_transaction() { }) .await; } + +#[tokio::test] +async fn cursor_is_absent_until_stored_and_then_replaced() { + let mut database = DatabaseTestWrapper::new().await; + let transaction = database + .connection + .transaction() + .await + .expect("could not begin the transaction"); + let relay = Uuid::now_v7().to_string(); + let read = async || { + transaction + .entity_outbox_cursor(&relay) + .await + .expect("could not read the cursor") + }; + let first = EntityOutboxCursor { + transaction_id: TransactionId::new(7), + ordinal: 3, + }; + let second = EntityOutboxCursor { + transaction_id: TransactionId::new(8), + ordinal: 0, + }; + + assert_eq!(read().await, None); + for cursor in [first, second] { + transaction + .store_entity_outbox_cursor(&relay, cursor) + .await + .expect("could not store the cursor"); + assert_eq!(read().await, Some(cursor)); + } +} + +#[tokio::test] +async fn relay_lock_is_held_by_one_connection_per_relay() { + let holder = DatabaseTestWrapper::new().await; + let contender = DatabaseTestWrapper::new().await; + let relay = Uuid::now_v7().to_string(); + let other_relay = Uuid::now_v7().to_string(); + let try_lock = async |database: &DatabaseTestWrapper, relay: &str| { + database + .connection + .try_lock_entity_outbox_relay(relay) + .await + .expect("could not request the relay lock") + }; + + assert!(try_lock(&holder, &relay).await); + assert!(!try_lock(&contender, &relay).await); + assert!(try_lock(&contender, &other_relay).await); +}