Skip to main content

systemprompt_database/lifecycle/installation/extension/
lock.rs

1//! Session-pinned Postgres advisory lock serialising concurrent bootstraps.
2//!
3//! Acquisition polls `pg_try_advisory_lock` with a deadline and logs progress,
4//! so a wedged holder surfaces as a typed [`BootstrapLockTimeout`] rather than
5//! an unbounded silent wait.
6//!
7//! While a server boot waits here the early-bind listener is already serving:
8//! `/livez` answers `200` and `/readyz` answers `503 starting`, so a liveness
9//! probe keeps the replica alive and no traffic is admitted. When the wait
10//! runs out the boot fails with that typed error and the process exits for
11//! the orchestrator to restart; a startup probe with a budget shorter than
12//! [`BootstrapLockGuard::DEFAULT_WAIT`] restarts it sooner instead.
13//!
14//! Copyright (c) systemprompt.io — Business Source License 1.1.
15//! See <https://systemprompt.io> for licensing details.
16
17use sqlx::Postgres;
18use sqlx::pool::PoolConnection;
19use systemprompt_extension::LoaderError;
20use systemprompt_identifiers::ExtensionId;
21use tokio::time::{Duration, Instant};
22use tracing::{debug, info, warn};
23
24use crate::services::DatabaseProvider;
25
26pub const BOOTSTRAP_ADVISORY_LOCK_KEY: i64 = 0x73_70_72_6F_6D_70_74_01;
27
28const POLL_INTERVAL: Duration = Duration::from_millis(250);
29const PROGRESS_INTERVAL: Duration = Duration::from_secs(30);
30
31/// Session-pinned advisory lock serialising concurrent bootstraps.
32///
33/// Only the acquiring Postgres session can release its advisory lock, so the
34/// guard pins that connection. Dropping the guard without `release` closes
35/// the session instead of returning it to the pool, so the lock never
36/// outlives a cancelled or panicking holder.
37pub struct BootstrapLockGuard {
38    conn: Option<PoolConnection<Postgres>>,
39}
40
41impl std::fmt::Debug for BootstrapLockGuard {
42    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
43        f.debug_struct("BootstrapLockGuard")
44            .field("key", &BOOTSTRAP_ADVISORY_LOCK_KEY)
45            .field("held", &self.conn.is_some())
46            .finish()
47    }
48}
49
50/// The bootstrap lock was still held by another session when the wait ran out.
51#[derive(Debug, Clone, Copy, thiserror::Error)]
52#[error("bootstrap advisory lock still held by another session after {waited:?}")]
53pub struct BootstrapLockTimeout {
54    pub waited: Duration,
55}
56
57impl BootstrapLockGuard {
58    pub const DEFAULT_WAIT: Duration = Duration::from_mins(15);
59
60    pub async fn acquire(db: &dyn DatabaseProvider) -> Result<Self, LoaderError> {
61        Self::acquire_within(db, Self::DEFAULT_WAIT).await
62    }
63
64    pub async fn acquire_within(
65        db: &dyn DatabaseProvider,
66        wait: Duration,
67    ) -> Result<Self, LoaderError> {
68        let mut conn = db.get_postgres_pool().acquire().await.map_err(|e| {
69            LoaderError::SchemaInstallationStepFailed {
70                extension: ExtensionId::new("database"),
71                context: "Failed to acquire bootstrap lock connection".to_owned(),
72                source: Box::new(e),
73            }
74        })?;
75
76        let started = Instant::now();
77        let deadline = started + wait;
78        let mut next_progress = started + PROGRESS_INTERVAL;
79        loop {
80            let acquired = sqlx::query_scalar!(
81                r#"SELECT pg_try_advisory_lock($1) AS "acquired!""#,
82                BOOTSTRAP_ADVISORY_LOCK_KEY
83            )
84            .fetch_one(conn.as_mut())
85            .await
86            .map_err(|e| LoaderError::SchemaInstallationStepFailed {
87                extension: ExtensionId::new("database"),
88                context: "Failed to acquire bootstrap advisory lock".to_owned(),
89                source: Box::new(e),
90            })?;
91            if acquired {
92                break;
93            }
94            let now = Instant::now();
95            if now >= deadline {
96                return Err(LoaderError::SchemaInstallationStepFailed {
97                    extension: ExtensionId::new("database"),
98                    context: "Timed out waiting for the bootstrap advisory lock".to_owned(),
99                    source: Box::new(BootstrapLockTimeout { waited: wait }),
100                });
101            }
102            if now >= next_progress {
103                info!(
104                    key = BOOTSTRAP_ADVISORY_LOCK_KEY,
105                    waited_secs = now.duration_since(started).as_secs(),
106                    "Waiting for another session to release the bootstrap advisory lock"
107                );
108                next_progress = now + PROGRESS_INTERVAL;
109            }
110            tokio::time::sleep(POLL_INTERVAL.min(deadline - now)).await;
111        }
112
113        debug!(
114            key = BOOTSTRAP_ADVISORY_LOCK_KEY,
115            "Acquired bootstrap advisory lock"
116        );
117
118        Ok(Self { conn: Some(conn) })
119    }
120
121    pub async fn release(mut self) {
122        let Some(mut conn) = self.conn.take() else {
123            return;
124        };
125        match sqlx::query_scalar!("SELECT pg_advisory_unlock($1)", BOOTSTRAP_ADVISORY_LOCK_KEY)
126            .fetch_one(conn.as_mut())
127            .await
128        {
129            Ok(Some(true)) => drop(conn),
130            Ok(released) => {
131                warn!(
132                    key = BOOTSTRAP_ADVISORY_LOCK_KEY,
133                    ?released,
134                    "Bootstrap advisory lock was not held by this session at release"
135                );
136                drop(conn);
137            },
138            Err(e) => {
139                warn!(
140                    error = %e,
141                    "Failed to release bootstrap advisory lock; closing its session instead of pooling it"
142                );
143                let session = conn.detach();
144                drop(session);
145            },
146        }
147    }
148}
149
150impl Drop for BootstrapLockGuard {
151    fn drop(&mut self) {
152        // Why: a connection returned to the pool keeps its session, and with it
153        // the advisory lock; detaching closes the session so a cancelled or
154        // panicking install cannot leave every other replica blocked.
155        if let Some(conn) = self.conn.take() {
156            warn!(
157                key = BOOTSTRAP_ADVISORY_LOCK_KEY,
158                "BootstrapLockGuard dropped without explicit release; closing its session"
159            );
160            let session = conn.detach();
161            drop(session);
162        }
163    }
164}