Skip to main content

systemprompt_database/lifecycle/installation/
lock_conflict.rs

1//! Which schema-phase failures are a transient lock conflict with live
2//! traffic, so the phase is rolled back and retried rather than failing the
3//! install.
4//!
5//! The decision reads the Postgres SQLSTATE wherever the error chain carries
6//! one: `55P03` `lock_not_available` (the phase's `lock_timeout`), `40P01`
7//! `deadlock_detected` (re-creating a trigger while writers hold row locks on
8//! the tables it touches) and `40001` `serialization_failure`. Any other
9//! SQLSTATE is not retried, whatever its message says. Only a chain that
10//! carries no SQLSTATE at all falls back to the server's message text.
11//!
12//! Copyright (c) systemprompt.io — Business Source License 1.1.
13//! See <https://systemprompt.io> for licensing details.
14
15use std::error::Error;
16
17use systemprompt_traits::RepositoryError;
18
19pub const RETRYABLE_SQLSTATES: [&str; 3] = ["55P03", "40P01", "40001"];
20
21const RETRYABLE_MESSAGES: [&str; 3] = [
22    "lock timeout",
23    "deadlock detected",
24    "could not serialize access",
25];
26
27#[must_use]
28pub fn is_retryable_sqlstate(code: &str) -> bool {
29    RETRYABLE_SQLSTATES.contains(&code)
30}
31
32#[must_use]
33pub fn is_retryable_lock_conflict(error: &(dyn Error + 'static)) -> bool {
34    sqlstate_in_chain(error).map_or_else(
35        || message_in_chain(error),
36        |code| is_retryable_sqlstate(&code),
37    )
38}
39
40fn sqlstate_in_chain(error: &(dyn Error + 'static)) -> Option<String> {
41    let mut source: Option<&(dyn Error + 'static)> = Some(error);
42    while let Some(current) = source {
43        if let Some(RepositoryError::Database {
44            sqlstate: Some(code),
45            ..
46        }) = current.downcast_ref::<RepositoryError>()
47        {
48            return Some(code.clone());
49        }
50        if let Some(code) = current
51            .downcast_ref::<sqlx::Error>()
52            .and_then(sqlx::Error::as_database_error)
53            .and_then(sqlx::error::DatabaseError::code)
54        {
55            return Some(code.into_owned());
56        }
57        source = current.source();
58    }
59    None
60}
61
62fn message_in_chain(error: &(dyn Error + 'static)) -> bool {
63    let mut source: Option<&(dyn Error + 'static)> = Some(error);
64    while let Some(current) = source {
65        let text = current.to_string();
66        if RETRYABLE_MESSAGES
67            .iter()
68            .any(|needle| text.contains(needle))
69        {
70            return true;
71        }
72        source = current.source();
73    }
74    false
75}