Skip to main content

systemprompt_database/lifecycle/
validation.rs

1//! Pre-flight validation helpers used by the boot path and tests.
2//!
3//! Copyright (c) systemprompt.io — Business Source License 1.1.
4//! See <https://systemprompt.io> for licensing details.
5
6use crate::error::{DatabaseResult, RepositoryError};
7use crate::services::{Database, DatabaseProvider};
8
9pub async fn validate_database_connection(db: &dyn DatabaseProvider) -> DatabaseResult<()> {
10    db.test_connection().await.map_err(|e| {
11        RepositoryError::Internal(format!("Failed to establish database connection: {e}"))
12    })
13}
14
15pub async fn validate_write_pool_is_primary(db: &Database) -> DatabaseResult<()> {
16    if !db.write().is_postgres() {
17        return Ok(());
18    }
19
20    let result = db
21        .write()
22        .query_raw(&"SELECT pg_is_in_recovery() as in_recovery")
23        .await?;
24
25    let in_recovery = result
26        .first()
27        .and_then(|row| row.get("in_recovery"))
28        .and_then(serde_json::Value::as_bool)
29        .ok_or_else(|| {
30            RepositoryError::Internal(
31                "Failed to determine whether the write pool is a primary".to_owned(),
32            )
33        })?;
34
35    if !in_recovery {
36        return Ok(());
37    }
38
39    Err(RepositoryError::invalid_state(if db.has_write_pool() {
40        "`database_write_url` points at a read-only standby. Writes, migrations and \
41         LISTEN/NOTIFY all require the primary — point it at the primary and restart"
42    } else {
43        "`database_url` points at a read-only standby and no `database_write_url` is set, so \
44         the write pool falls back to it. Set `database_write_url` (or `DATABASE_WRITE_URL` \
45         with the env secrets source) to the primary and restart"
46    }))
47}
48
49#[derive(Debug, Clone, Copy, PartialEq)]
50pub struct ReplicaStatus {
51    pub in_recovery: bool,
52    pub replay_lag_secs: Option<f64>,
53}
54
55pub async fn replica_status(db: &dyn DatabaseProvider) -> DatabaseResult<ReplicaStatus> {
56    let result = db
57        .query_raw(
58            &"SELECT pg_is_in_recovery() AS in_recovery, CASE WHEN pg_is_in_recovery() THEN \
59              EXTRACT(EPOCH FROM (now() - pg_last_xact_replay_timestamp()))::double precision \
60              ELSE NULL END AS lag_secs",
61        )
62        .await?;
63    let row = result.first().ok_or_else(|| {
64        RepositoryError::Internal("replica status probe returned no row".to_owned())
65    })?;
66    let in_recovery = row
67        .get("in_recovery")
68        .and_then(serde_json::Value::as_bool)
69        .ok_or_else(|| {
70            RepositoryError::Internal("replica status probe lacks in_recovery".to_owned())
71        })?;
72    let replay_lag_secs = row.get("lag_secs").and_then(serde_json::Value::as_f64);
73    Ok(ReplicaStatus {
74        in_recovery,
75        replay_lag_secs,
76    })
77}
78
79pub async fn validate_table_exists(
80    db: &dyn DatabaseProvider,
81    table_name: &str,
82) -> DatabaseResult<bool> {
83    let result = db
84        .query_raw_with(
85            &"SELECT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = \
86              'public' AND table_name = $1) as exists",
87            &[&table_name],
88        )
89        .await?;
90
91    result
92        .first()
93        .and_then(|row| row.get("exists"))
94        .and_then(serde_json::Value::as_bool)
95        .ok_or_else(|| {
96            RepositoryError::Internal(format!(
97                "Failed to check table existence for '{table_name}'"
98            ))
99        })
100}
101
102pub async fn validate_column_exists(
103    db: &dyn DatabaseProvider,
104    table_name: &str,
105    column_name: &str,
106) -> DatabaseResult<bool> {
107    let result = db
108        .query_raw_with(
109            &"SELECT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema = \
110              'public' AND table_name = $1 AND column_name = $2) as exists",
111            &[&table_name, &column_name],
112        )
113        .await?;
114
115    result
116        .first()
117        .and_then(|row| row.get("exists"))
118        .and_then(serde_json::Value::as_bool)
119        .ok_or_else(|| {
120            RepositoryError::Internal(format!(
121                "Failed to check column existence for '{table_name}.{column_name}'"
122            ))
123        })
124}