Skip to main content

es_entity/
error.rs

1//! Types for working with errors produced by es-entity.
2
3use thiserror::Error;
4
5/// Error type for entity hydration failures (reconstructing entities from events).
6#[derive(Error, Debug)]
7pub enum EntityHydrationError {
8    #[error("EntityHydrationError - UninitializedFieldError: {0}")]
9    UninitializedFieldError(#[from] derive_builder::UninitializedFieldError),
10    #[error("EntityHydrationError - Deserialization: {0}")]
11    EventDeserialization(#[from] serde_json::Error),
12}
13
14#[derive(Error, Debug)]
15#[error("CursorDestructureError: couldn't turn {0} into {1}")]
16pub struct CursorDestructureError(&'static str, &'static str);
17
18impl From<(&'static str, &'static str)> for CursorDestructureError {
19    fn from((name, variant): (&'static str, &'static str)) -> Self {
20        Self(name, variant)
21    }
22}
23
24#[doc(hidden)]
25/// Extracts the conflicting value from a PostgreSQL constraint violation detail message.
26///
27/// PostgreSQL formats unique violation details as:
28/// `Key (column)=(value) already exists.`
29///
30/// Returns `None` if the detail is missing or doesn't match the expected format.
31///
32/// **Security note:** the extracted value is attacker-influenced input that
33/// was rejected by a unique constraint and may be PII (e.g. an email
34/// address). Returning it to untrusted API clients enables user
35/// enumeration; logging it may place PII in log pipelines.
36pub fn parse_constraint_detail_value(detail: Option<&str>) -> Option<String> {
37    let detail = detail?;
38    let start = detail.find("=(")? + 2;
39    let end = detail.rfind(") already")?;
40    if start <= end {
41        Some(detail[start..end].to_string())
42    } else {
43        None
44    }
45}
46
47#[doc(hidden)]
48/// Extracts the conflicting value from a database error's constraint violation.
49///
50/// Downcasts to [`sqlx::postgres::PgDatabaseError`], reads its `detail()`,
51/// and parses the conflicting value.
52///
53/// **Security note:** see [`parse_constraint_detail_value`] — the returned
54/// value may be PII and must not be exposed to untrusted clients.
55pub fn extract_constraint_value(db_err: &dyn sqlx::error::DatabaseError) -> Option<String> {
56    let pg_err = db_err.try_downcast_ref::<sqlx::postgres::PgDatabaseError>()?;
57    parse_constraint_detail_value(pg_err.detail())
58}
59
60#[doc(hidden)]
61/// Wrapper used by generated code to format not-found values.
62/// Prefers `Display` over `Debug` via inherent-vs-trait method resolution.
63pub struct NotFoundValue<'a, T: ?Sized>(pub &'a T);
64
65impl<T: std::fmt::Display + ?Sized> NotFoundValue<'_, T> {
66    pub fn to_not_found_value(&self) -> String {
67        self.0.to_string()
68    }
69}
70
71#[doc(hidden)]
72pub trait ToNotFoundValueFallback {
73    fn to_not_found_value(&self) -> String;
74}
75
76impl<T: std::fmt::Debug + ?Sized> ToNotFoundValueFallback for NotFoundValue<'_, T> {
77    fn to_not_found_value(&self) -> String {
78        format!("{:?}", self.0)
79    }
80}
81
82#[cfg(test)]
83mod tests {
84    use super::*;
85
86    #[test]
87    fn parse_simple_uuid_value() {
88        let detail = Some("Key (id)=(550e8400-e29b-41d4-a716-446655440000) already exists.");
89        assert_eq!(
90            parse_constraint_detail_value(detail),
91            Some("550e8400-e29b-41d4-a716-446655440000".to_string())
92        );
93    }
94
95    #[test]
96    fn parse_string_value() {
97        let detail = Some("Key (email)=(user@example.com) already exists.");
98        assert_eq!(
99            parse_constraint_detail_value(detail),
100            Some("user@example.com".to_string())
101        );
102    }
103
104    #[test]
105    fn parse_composite_key_value() {
106        let detail = Some("Key (tenant_id, email)=(abc, user@example.com) already exists.");
107        assert_eq!(
108            parse_constraint_detail_value(detail),
109            Some("abc, user@example.com".to_string())
110        );
111    }
112
113    #[test]
114    fn parse_none_detail() {
115        assert_eq!(parse_constraint_detail_value(None), None);
116    }
117
118    #[test]
119    fn parse_unexpected_format() {
120        let detail = Some("something unexpected");
121        assert_eq!(parse_constraint_detail_value(detail), None);
122    }
123
124    #[test]
125    fn parse_value_containing_parentheses() {
126        let detail = Some("Key (name)=(foo (bar)) already exists.");
127        assert_eq!(
128            parse_constraint_detail_value(detail),
129            Some("foo (bar)".to_string())
130        );
131    }
132
133    #[test]
134    fn parse_empty_value() {
135        let detail = Some("Key (col)=() already exists.");
136        assert_eq!(parse_constraint_detail_value(detail), Some("".to_string()));
137    }
138
139    #[test]
140    fn not_found_value_uses_display_when_available() {
141        #[allow(unused_imports)]
142        use crate::ToNotFoundValueFallback;
143
144        // String implements Display - should get clean output
145        let val = "hello";
146        assert_eq!(NotFoundValue(val).to_not_found_value(), "hello");
147
148        // i32 implements Display
149        let num = 42;
150        assert_eq!(NotFoundValue(&num).to_not_found_value(), "42");
151    }
152
153    #[test]
154    fn not_found_value_falls_back_to_debug() {
155        use crate::ToNotFoundValueFallback;
156
157        // A type with Debug but no Display
158        #[derive(Debug)]
159        #[allow(dead_code)]
160        struct OnlyDebug(i32);
161
162        let val = OnlyDebug(7);
163        assert_eq!(NotFoundValue(&val).to_not_found_value(), "OnlyDebug(7)");
164    }
165}