systemprompt_database/lifecycle/installation/
lock_conflict.rs1use 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}