1use std::fmt;
8
9use serde_json::{Map, Value, json};
10
11#[derive(Clone, Debug, PartialEq)]
13pub struct SurfaceError {
14 pub code: String,
16 pub message: String,
17 pub data: Option<Value>,
19 pub retriable: bool,
20}
21
22impl SurfaceError {
23 #[must_use]
24 pub fn new(code: &str, message: impl Into<String>) -> Self {
25 Self {
26 code: code.to_owned(),
27 message: message.into(),
28 data: None,
29 retriable: false,
30 }
31 }
32
33 #[must_use]
34 pub fn with_data(code: &str, message: impl Into<String>, data: Value) -> Self {
35 Self {
36 code: code.to_owned(),
37 message: message.into(),
38 data: Some(data),
39 retriable: false,
40 }
41 }
42
43 #[must_use]
47 pub fn filter_invalid(message: impl Into<String>, hint: &str) -> Self {
48 let message = message.into();
49 Self::with_data(
50 "filter_invalid",
51 message.clone(),
52 json!({ "reason": message, "hint": hint }),
53 )
54 }
55
56 #[must_use]
58 pub fn cursor_invalid(surface: &str) -> Self {
59 Self::with_data(
60 "filter_invalid",
61 "invalid cursor",
62 json!({
63 "reason": format!("cursor was not issued by {surface}"),
64 "hint": "resume only with a `cursor` returned by a truncated page of the same tool",
65 }),
66 )
67 }
68
69 #[must_use]
72 pub fn cursor_invalid_reason(reason: &str) -> Self {
73 Self::with_data(
74 "filter_invalid",
75 format!("invalid cursor: {reason}"),
76 json!({
77 "reason": reason,
78 "hint": "resume only with a `cursor` returned by a truncated page of the same tool",
79 }),
80 )
81 }
82
83 #[must_use]
85 pub fn other(message: impl Into<String>) -> Self {
86 Self::new("repo_not_found", message)
87 }
88
89 #[must_use]
91 pub fn to_json(&self) -> Value {
92 let mut m = Map::new();
93 m.insert("error".to_owned(), Value::String(self.code.clone()));
94 m.insert("message".to_owned(), Value::String(self.message.clone()));
95 if let Some(d) = &self.data {
96 m.insert("data".to_owned(), d.clone());
97 }
98 m.insert("retriable".to_owned(), Value::Bool(self.retriable));
99 Value::Object(m)
100 }
101}
102
103impl fmt::Display for SurfaceError {
104 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
105 write!(f, "{}: {}", self.code, self.message)
106 }
107}
108
109impl std::error::Error for SurfaceError {}
110
111impl From<omgbase_store::Error> for SurfaceError {
112 fn from(e: omgbase_store::Error) -> Self {
113 match e {
114 omgbase_store::Error::Mutation(m) => Self::from(m),
115 omgbase_store::Error::Search(s) => Self::new(s.code(), s.to_string()),
116 other => Self::other(other.to_string()),
117 }
118 }
119}
120
121impl From<omgbase_store::MutationError> for SurfaceError {
122 fn from(m: omgbase_store::MutationError) -> Self {
123 let retriable = m
124 .data
125 .get("retriable")
126 .and_then(Value::as_bool)
127 .unwrap_or(false);
128 Self {
129 code: m.code.as_str().to_owned(),
130 message: m.message,
131 data: Some(Value::Object(m.data)),
132 retriable,
133 }
134 }
135}
136
137impl From<omgbase_sync::Error> for SurfaceError {
138 fn from(e: omgbase_sync::Error) -> Self {
139 match e {
140 omgbase_sync::Error::Store(s) => Self::from(s),
141 omgbase_sync::Error::RepoNotFound {
142 message,
143 candidates,
144 } => Self::with_data(
145 "repo_not_found",
146 message,
147 json!({ "candidates": candidates }),
148 ),
149 other => Self::other(other.to_string()),
150 }
151 }
152}
153
154impl From<rusqlite::Error> for SurfaceError {
155 fn from(e: rusqlite::Error) -> Self {
156 Self::other(format!("sqlite: {e}"))
157 }
158}
159
160impl From<oqx::OqxError> for SurfaceError {
161 fn from(e: oqx::OqxError) -> Self {
163 Self::filter_invalid(e.message, "OQX")
164 }
165}
166
167pub type Result<T> = std::result::Result<T, SurfaceError>;
169
170#[cfg(test)]
171mod tests {
172 use super::*;
173
174 #[test]
175 fn envelope_shape() {
176 let e = SurfaceError::filter_invalid("bad", "OQX");
177 let j = e.to_json();
178 assert_eq!(j["error"], "filter_invalid");
179 assert_eq!(j["message"], "bad");
180 assert_eq!(j["data"]["reason"], "bad");
181 assert_eq!(j["data"]["hint"], "OQX");
182 assert_eq!(j["retriable"], false);
183 let plain = SurfaceError::other("boom").to_json();
184 assert!(plain.get("data").is_none());
185 assert_eq!(plain["error"], "repo_not_found");
186 }
187
188 #[test]
189 fn mutation_errors_keep_code_and_data() {
190 let m = omgbase_store::MutationError::with_data(
191 omgbase_store::mutate_kernel::ErrorCode::StaleExpectation,
192 "stale",
193 json!({ "block": "b_1", "retriable": true }),
194 );
195 let e = SurfaceError::from(omgbase_store::Error::from(m));
196 assert_eq!(e.code, "stale_expectation");
197 assert!(e.retriable);
198 assert_eq!(e.data.unwrap()["block"], "b_1");
199 }
200}