264 lines
9.5 KiB
Rust
264 lines
9.5 KiB
Rust
//! The named-lock mechanism's Postgres arm (`pg-engine-locks`) — the
|
|
//! substrate's lock-op semantics re-derived over the schema task's
|
|
//! locks table (the POC's lock probe pinned acquire/release/renew with
|
|
//! TTL and expiry re-acquisition directly):
|
|
//!
|
|
//! - `try_lock(name, owner, ttl)` — shared-namespace + non-empty
|
|
//! owner validation, the **duration guard (ADR-023 §2)** on `ttl <=
|
|
//! 0` at the entry (opaque `Err(Database)`, detail in the source
|
|
//! chain — an exclusion mechanism must not silently hand back a
|
|
//! lease the caller believes it holds), the closed-store check,
|
|
//! then the acquire op on a pool connection: opportunistic-
|
|
//! expiry-delete + insert-or-reacquire + read-back. `Ok(None)` =
|
|
//! held elsewhere (no-work is a value); `Ok(Some(..))` = the boxed
|
|
//! [`Lock`] handle.
|
|
//! - `Lock::renew(ttl)` — the same duration guard; the new **full**
|
|
//! TTL window from now (not additive); `false` = lost it (expired
|
|
//! and re-acquired elsewhere — exclusion lapses silently at TTL
|
|
//! expiry, no revocation event, ADR-008 §7).
|
|
//! - `Lock::release(self: Box<Self>)` — consuming (the RAII shape,
|
|
//! ADR-019 §1); deletes only the owner's row (`false` = already
|
|
//! expired/re-acquired — a no-op, not an error). No handle-local
|
|
//! "held" flag caching: the row-scoped delete is the truth-teller.
|
|
//!
|
|
//! No `lock_tx` exists — deliberate (core-contract.md's named-locks
|
|
//! section): acquisition is a separate auto-commit op; the TTL
|
|
//! discipline governs. There is no general expiry sweeper either:
|
|
//! expired rows hang until the next acquire's opportunistic delete
|
|
//! deletes them (the inherited substrate posture, documented) — the
|
|
//! `locks_expiry_idx` index keeps that delete cheap.
|
|
|
|
use std::sync::Arc;
|
|
use std::sync::atomic::{AtomicBool, Ordering};
|
|
|
|
use deadpool_postgres::Pool;
|
|
|
|
use alkstore::{BoxedFuture, Lock, Result, validate_local_name, validate_shared_name};
|
|
|
|
use crate::resolution::{now_unix, saturating_stamp_expr};
|
|
use crate::schema::{QualifiedTable, tables};
|
|
use crate::seam::{database_error, pg_error, pool_error};
|
|
|
|
/// The duration guard's message (ADR-023 §2's engine detail — rides
|
|
/// the source chain, `Database`'s Display is opaque).
|
|
fn duration_error(ttl: i64) -> alkstore::Error {
|
|
database_error(format!(
|
|
"ttl must be a positive duration (seconds), got {ttl}"
|
|
))
|
|
}
|
|
|
|
/// Qualified table reference for this engine-owned schema.
|
|
fn table(schema: &str, name: &str) -> String {
|
|
QualifiedTable { schema, name }.to_string()
|
|
}
|
|
|
|
/// The acquire op (see the module docs): the opportunistic
|
|
/// expired-row delete for this name, then the insert-or-reacquire
|
|
/// (the PK on `name` prevents dual acquisition — `ON CONFLICT DO
|
|
/// NOTHING` keeps the incumbent row exactly as-is, so a same-owner
|
|
/// re-acquire keeps the original row with its TTL *not* refreshed,
|
|
/// the substrate's `INSERT OR IGNORE` shape), then the read-back —
|
|
/// the holder column decides, not the insert's row count (the D-4
|
|
/// swallow's lesson: never trust a write result for ownership).
|
|
///
|
|
/// One statement sequence on one pool connection in autocommit mode
|
|
/// (each statement commits as it lands; the acquire is **not** a
|
|
/// single transaction): the correctness guarantee is the PK
|
|
/// constraint, not statement atomicity — a concurrent grant of the
|
|
/// same name either lands first (the read-back then shows the foreign
|
|
/// owner) or reads as foreign.
|
|
pub(crate) async fn lock_acquire(
|
|
client: &tokio_postgres::Client,
|
|
schema: &str,
|
|
name: &str,
|
|
owner: &str,
|
|
ttl: i64,
|
|
) -> Result<bool> {
|
|
let now = now_unix();
|
|
client
|
|
.execute(
|
|
&format!(
|
|
"DELETE FROM {locks} WHERE name = $1 AND expires_at <= $2",
|
|
locks = table(schema, tables::LOCKS)
|
|
),
|
|
&[&name, &now],
|
|
)
|
|
.await
|
|
.map_err(pg_error)?;
|
|
client
|
|
.execute(
|
|
&format!(
|
|
"INSERT INTO {locks} (name, owner, expires_at)
|
|
VALUES ($1, $2, {expires_at})
|
|
ON CONFLICT (name) DO NOTHING",
|
|
locks = table(schema, tables::LOCKS),
|
|
expires_at = saturating_stamp_expr("($3::bigint)::numeric + ($4::bigint)::numeric"),
|
|
),
|
|
&[&name, &owner, &now, &ttl],
|
|
)
|
|
.await
|
|
.map_err(pg_error)?;
|
|
let holder: Option<String> = client
|
|
.query_opt(
|
|
&format!(
|
|
"SELECT owner FROM {locks} WHERE name = $1",
|
|
locks = table(schema, tables::LOCKS)
|
|
),
|
|
&[&name],
|
|
)
|
|
.await
|
|
.map_err(pg_error)?
|
|
.map(|row| row.get(0));
|
|
Ok(holder.as_deref() == Some(owner))
|
|
}
|
|
|
|
/// The acquire path (see the module docs): validation, duration
|
|
/// guard, closed-store check, then the acquire op on a pool
|
|
/// connection. `Ok(None)` is the held-by-someone-else arm.
|
|
pub(crate) fn try_lock(
|
|
pool: Pool,
|
|
schema: String,
|
|
closed: Arc<AtomicBool>,
|
|
name: String,
|
|
owner: String,
|
|
ttl: i64,
|
|
) -> BoxedFuture<'static, Result<Option<Box<dyn Lock>>>> {
|
|
if let Err(e) = validate_shared_name(&name) {
|
|
return Box::pin(async move { Err(e) });
|
|
}
|
|
if let Err(e) = validate_local_name(&owner) {
|
|
return Box::pin(async move { Err(e) });
|
|
}
|
|
if ttl <= 0 {
|
|
return Box::pin(async move { Err(duration_error(ttl)) });
|
|
}
|
|
if closed.load(Ordering::Acquire) {
|
|
return Box::pin(async { Err(database_error("the store is closed")) });
|
|
}
|
|
Box::pin(async move {
|
|
let client = pool.get().await.map_err(pool_error)?;
|
|
let granted = lock_acquire(&client, &schema, &name, &owner, ttl).await?;
|
|
Ok(granted.then(|| {
|
|
Box::new(PgLockHandle {
|
|
name,
|
|
owner,
|
|
pool,
|
|
schema,
|
|
closed,
|
|
}) as Box<dyn Lock>
|
|
}))
|
|
})
|
|
}
|
|
|
|
/// The held named-lock handle (see the module docs). [`Lock::release`]
|
|
/// consumes it; `renew` is the repeatable `&self` case.
|
|
pub struct PgLockHandle {
|
|
name: String,
|
|
owner: String,
|
|
pool: Pool,
|
|
schema: String,
|
|
closed: Arc<AtomicBool>,
|
|
}
|
|
|
|
impl std::fmt::Debug for PgLockHandle {
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
f.debug_struct("PgLockHandle")
|
|
.field("name", &self.name)
|
|
.finish_non_exhaustive()
|
|
}
|
|
}
|
|
|
|
impl PgLockHandle {
|
|
/// The engine-internal constructor (the SQLite twin's
|
|
/// `SqliteLockHandle::new_internal` shape): the scheduler's
|
|
/// leadership lease on the reserved name — `try_lock`'s entry
|
|
/// validation would reject the reserved name, so the engine's own
|
|
/// holder builds the handle directly after its own acquire.
|
|
pub(crate) fn new_internal(
|
|
name: String,
|
|
owner: String,
|
|
pool: Pool,
|
|
schema: String,
|
|
closed: Arc<AtomicBool>,
|
|
) -> Self {
|
|
Self {
|
|
name,
|
|
owner,
|
|
pool,
|
|
schema,
|
|
closed,
|
|
}
|
|
}
|
|
}
|
|
|
|
impl Lock for PgLockHandle {
|
|
fn name(&self) -> &str {
|
|
&self.name
|
|
}
|
|
|
|
fn renew<'a>(&'a self, ttl: i64) -> BoxedFuture<'a, Result<bool>> {
|
|
if ttl <= 0 {
|
|
return Box::pin(async move { Err(duration_error(ttl)) });
|
|
}
|
|
if self.closed.load(Ordering::Acquire) {
|
|
return Box::pin(async { Err(database_error("the store is closed")) });
|
|
}
|
|
let name = self.name.clone();
|
|
let owner = self.owner.clone();
|
|
let pool = self.pool.clone();
|
|
let schema = self.schema.clone();
|
|
Box::pin(async move {
|
|
let now = now_unix();
|
|
let client = pool.get().await.map_err(pool_error)?;
|
|
// The owner-scoped update: 0 rows = expired-and-gone or
|
|
// re-acquired by another owner — `false`, the lost-it arm.
|
|
let n = client
|
|
.execute(
|
|
&format!(
|
|
"UPDATE {locks} SET expires_at = {expires_at}
|
|
WHERE name = $1 AND owner = $2",
|
|
locks = table(&schema, tables::LOCKS),
|
|
expires_at =
|
|
saturating_stamp_expr("($3::bigint)::numeric + ($4::bigint)::numeric"),
|
|
),
|
|
&[&name, &owner, &now, &ttl],
|
|
)
|
|
.await
|
|
.map_err(pg_error)?;
|
|
Ok(n > 0)
|
|
})
|
|
}
|
|
|
|
fn release(self: Box<Self>) -> BoxedFuture<'static, Result<bool>> {
|
|
let PgLockHandle {
|
|
name,
|
|
owner,
|
|
pool,
|
|
schema,
|
|
closed,
|
|
} = *self;
|
|
Box::pin(async move {
|
|
if closed.load(Ordering::Acquire) {
|
|
return Err(database_error("the store is closed"));
|
|
}
|
|
let client = pool.get().await.map_err(pool_error)?;
|
|
// The owner-scoped delete — row-scoped truth-teller: `true`
|
|
// = the row was there and is gone by this owner's hand
|
|
// (including the stale row past its TTL, which no sweeper
|
|
// has touched); `false` = row-less or foreign (the
|
|
// no-op arm).
|
|
let n = client
|
|
.execute(
|
|
&format!(
|
|
"DELETE FROM {locks} WHERE name = $1 AND owner = $2",
|
|
locks = table(&schema, tables::LOCKS)
|
|
),
|
|
&[&name, &owner],
|
|
)
|
|
.await
|
|
.map_err(pg_error)?;
|
|
Ok(n > 0)
|
|
})
|
|
}
|
|
}
|