1use std::{collections::BTreeSet, convert::Infallible};
2
3use ankurah_proto::{CollectionId, DecodeError, EntityId, EventId};
4use thiserror::Error;
5
6use crate::{connector::SendError, policy::AccessDenied};
7
8#[derive(Error, Debug)]
9pub enum RetrievalError {
10 #[error("access denied")]
11 AccessDenied(AccessDenied),
12 #[error("Parse error: {0}")]
13 ParseError(ankql::error::ParseError),
14 #[error("Entity not found: {0:?}")]
15 EntityNotFound(EntityId),
16 #[error("Event not found: {0:?}")]
17 EventNotFound(EventId),
18 #[error("Storage error: {0}")]
19 StorageError(Box<dyn std::error::Error + Send + Sync + 'static>),
20 #[error("Collection not found: {0}")]
21 CollectionNotFound(CollectionId),
22 #[error("Update failed: {0}")]
23 FailedUpdate(Box<dyn std::error::Error + Send + Sync + 'static>),
24 #[error("Deserialization error: {0}")]
25 DeserializationError(bincode::Error),
26 #[error("No durable peers available for fetch operation")]
27 NoDurablePeers,
28 #[error("Other error: {0}")]
29 Other(String),
30 #[error("bucket name must only contain valid characters")]
31 InvalidBucketName,
32 #[error("ankql filter: {0}")]
33 AnkqlFilter(crate::selection::filter::Error),
34 #[error("Future join: {0}")]
35 FutureJoin(tokio::task::JoinError),
36 #[error("{0}")]
37 Anyhow(anyhow::Error),
38 #[error("Decode error: {0}")]
39 DecodeError(DecodeError),
40 #[error("State error: {0}")]
41 StateError(StateError),
42 #[error("Mutation error: {0}")]
43 MutationError(Box<MutationError>),
44 #[error("Property error: {0}")]
45 PropertyError(Box<crate::property::PropertyError>),
46 #[error("Request error: {0}")]
47 RequestError(RequestError),
48 #[error("Apply error: {0}")]
49 ApplyError(ApplyError),
50}
51
52impl From<RequestError> for RetrievalError {
53 fn from(err: RequestError) -> Self { RetrievalError::RequestError(err) }
54}
55
56impl From<crate::property::PropertyError> for RetrievalError {
57 fn from(err: crate::property::PropertyError) -> Self { RetrievalError::PropertyError(Box::new(err)) }
58}
59
60impl From<tokio::task::JoinError> for RetrievalError {
61 fn from(err: tokio::task::JoinError) -> Self { RetrievalError::FutureJoin(err) }
62}
63
64impl From<MutationError> for RetrievalError {
65 fn from(err: MutationError) -> Self { RetrievalError::MutationError(Box::new(err)) }
66}
67
68impl RetrievalError {
69 pub fn storage(err: impl std::error::Error + Send + Sync + 'static) -> Self { RetrievalError::StorageError(Box::new(err)) }
70}
71
72impl From<bincode::Error> for RetrievalError {
73 fn from(e: bincode::Error) -> Self { RetrievalError::DeserializationError(e) }
74}
75
76impl From<crate::selection::filter::Error> for RetrievalError {
77 fn from(err: crate::selection::filter::Error) -> Self { RetrievalError::AnkqlFilter(err) }
78}
79
80impl From<anyhow::Error> for RetrievalError {
81 fn from(err: anyhow::Error) -> Self { RetrievalError::Anyhow(err) }
82}
83
84impl From<Infallible> for RetrievalError {
85 fn from(_: Infallible) -> Self { unreachable!("Infallible can never be constructed") }
86}
87
88#[derive(Error, Debug)]
89pub enum RequestError {
90 #[error("Peer not connected")]
91 PeerNotConnected,
92 #[error("Connection lost")]
93 ConnectionLost,
94 #[error("Server error: {0}")]
95 ServerError(String),
96 #[error("Send error: {0}")]
97 SendError(SendError),
98 #[error("Internal channel closed")]
99 InternalChannelClosed,
100 #[error("Unexpected response: {0:?}")]
101 UnexpectedResponse(ankurah_proto::NodeResponseBody),
102 #[error("Access denied: {0}")]
103 AccessDenied(AccessDenied),
104}
105
106impl From<AccessDenied> for RequestError {
107 fn from(err: AccessDenied) -> Self { RequestError::AccessDenied(err) }
108}
109
110impl From<SendError> for RequestError {
111 fn from(err: SendError) -> Self { RequestError::SendError(err) }
112}
113
114#[derive(Error, Debug)]
115pub enum SubscriptionError {
116 #[error("predicate not found")]
117 PredicateNotFound,
118 #[error("already subscribed to predicate")]
119 PredicateAlreadySubscribed,
120 #[error("subscription not found")]
121 SubscriptionNotFound,
122}
123
124impl From<DecodeError> for RetrievalError {
125 fn from(err: DecodeError) -> Self { RetrievalError::DecodeError(err) }
126}
127
128#[derive(Error, Debug)]
129pub enum MutationError {
130 #[error("access denied")]
131 AccessDenied(AccessDenied),
132 #[error("already exists")]
133 AlreadyExists,
134 #[error("retrieval error: {0}")]
135 RetrievalError(RetrievalError),
136 #[error("state error: {0}")]
137 StateError(StateError),
138 #[error("failed update: {0}")]
139 UpdateFailed(Box<dyn std::error::Error + Send + Sync + 'static>),
140 #[error("failed step: {0}: {1}")]
141 FailedStep(&'static str, String),
142 #[error("failed to set property: {0}: {1}")]
143 FailedToSetProperty(&'static str, String),
144 #[error("general error: {0}")]
145 General(Box<dyn std::error::Error + Send + Sync + 'static>),
146 #[error("no durable peers available")]
147 NoDurablePeers,
148 #[error("decode error: {0}")]
149 DecodeError(DecodeError),
150 #[error("lineage error: {0}")]
151 LineageError(LineageError),
152 #[error("peer rejected transaction")]
153 PeerRejected,
154 #[error("invalid event")]
155 InvalidEvent,
156 #[error("invalid update")]
157 InvalidUpdate(&'static str),
158 #[error("property error: {0}")]
159 PropertyError(crate::property::PropertyError),
160 #[error("future join: {0}")]
161 FutureJoin(tokio::task::JoinError),
162 #[error("anyhow error: {0}")]
163 Anyhow(anyhow::Error),
164 #[error("TOCTOU attempts exhausted")]
165 TOCTOUAttemptsExhausted,
166}
167
168impl From<tokio::task::JoinError> for MutationError {
169 fn from(err: tokio::task::JoinError) -> Self { MutationError::FutureJoin(err) }
170}
171
172impl From<anyhow::Error> for MutationError {
173 fn from(err: anyhow::Error) -> Self { MutationError::Anyhow(err) }
174}
175
176#[derive(Debug)]
177pub enum LineageError {
178 Incomparable,
179 PartiallyDescends { meet: Vec<EventId> },
180 BudgetExceeded { original_budget: usize, subject_frontier: BTreeSet<EventId>, other_frontier: BTreeSet<EventId> },
181}
182
183impl std::fmt::Display for LineageError {
184 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
185 match self {
186 LineageError::Incomparable => write!(f, "incomparable"),
187 LineageError::PartiallyDescends { meet } => {
188 write!(f, "partially descends: [")?;
189 let meets: Vec<_> = meet.iter().map(|id| id.to_base64_short()).collect();
190 write!(f, "{}]", meets.join(", "))
191 }
192 LineageError::BudgetExceeded { original_budget, subject_frontier, other_frontier } => {
193 let subject: Vec<_> = subject_frontier.iter().map(|id| id.to_base64_short()).collect();
194 let other: Vec<_> = other_frontier.iter().map(|id| id.to_base64_short()).collect();
195 write!(f, "budget exceeded ({}): subject[{}] other[{}]", original_budget, subject.join(", "), other.join(", "))
196 }
197 }
198 }
199}
200
201impl std::error::Error for LineageError {}
202
203impl From<LineageError> for MutationError {
204 fn from(err: LineageError) -> Self { MutationError::LineageError(err) }
205}
206
207impl From<DecodeError> for MutationError {
208 fn from(err: DecodeError) -> Self { MutationError::DecodeError(err) }
209}
210
211#[cfg(feature = "wasm")]
212impl From<MutationError> for wasm_bindgen::JsValue {
213 fn from(err: MutationError) -> Self { err.to_string().into() }
214}
215#[cfg(feature = "wasm")]
216impl From<RetrievalError> for wasm_bindgen::JsValue {
217 fn from(err: RetrievalError) -> Self { err.to_string().into() }
218}
219
220impl From<AccessDenied> for MutationError {
221 fn from(err: AccessDenied) -> Self { MutationError::AccessDenied(err) }
222}
223
224impl From<bincode::Error> for MutationError {
225 fn from(e: bincode::Error) -> Self { MutationError::StateError(StateError::SerializationError(e)) }
226}
227
228impl From<RetrievalError> for MutationError {
229 fn from(err: RetrievalError) -> Self {
230 match err {
231 RetrievalError::AccessDenied(a) => MutationError::AccessDenied(a),
232 _ => MutationError::RetrievalError(err),
233 }
234 }
235}
236impl From<AccessDenied> for RetrievalError {
237 fn from(err: AccessDenied) -> Self { RetrievalError::AccessDenied(err) }
238}
239
240impl From<SubscriptionError> for RetrievalError {
241 fn from(err: SubscriptionError) -> Self { RetrievalError::Anyhow(anyhow::anyhow!("Subscription error: {:?}", err)) }
242}
243
244#[derive(Error, Debug)]
245pub enum StateError {
246 #[error("serialization error: {0}")]
247 SerializationError(Box<dyn std::error::Error + Send + Sync + 'static>),
248 #[error("DDL error: {0}")]
249 DDLError(Box<dyn std::error::Error + Send + Sync + 'static>),
250 #[error("DMLError: {0}")]
251 DMLError(Box<dyn std::error::Error + Send + Sync + 'static>),
252}
253
254impl From<bincode::Error> for StateError {
255 fn from(e: bincode::Error) -> Self { StateError::SerializationError(Box::new(e)) }
256}
257
258impl From<StateError> for MutationError {
259 fn from(err: StateError) -> Self { MutationError::StateError(err) }
260}
261
262impl From<crate::property::PropertyError> for MutationError {
263 fn from(err: crate::property::PropertyError) -> Self { MutationError::PropertyError(err) }
264}
265
266impl From<StateError> for RetrievalError {
267 fn from(err: StateError) -> Self { RetrievalError::StateError(err) }
268}
269
270#[derive(Error, Debug)]
271pub enum ValidationError {
272 #[error("Deserialization error: {0}")]
273 Deserialization(Box<dyn std::error::Error + Send + Sync + 'static>),
274 #[error("Validation failed: {0}")]
275 ValidationFailed(String),
276 #[error("Serialization error: {0}")]
277 Serialization(String),
278 #[error("Rejected: {0}")]
279 Rejected(&'static str),
280}
281
282#[derive(Debug)]
284pub enum ApplyError {
285 Items(Vec<ApplyErrorItem>),
286 CollectionNotFound(CollectionId),
287 RetrievalError(Box<RetrievalError>),
288 MutationError(Box<MutationError>),
289}
290
291impl std::fmt::Display for ApplyError {
292 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
293 match self {
294 ApplyError::Items(errors) => {
295 write!(f, "Failed to apply {} delta(s)", errors.len())?;
296 for (i, err) in errors.iter().enumerate() {
297 write!(f, "\n [{}] {}", i + 1, err)?;
298 }
299 Ok(())
300 }
301 ApplyError::CollectionNotFound(id) => write!(f, "Collection not found: {}", id),
302 ApplyError::RetrievalError(e) => write!(f, "Retrieval error: {}", e),
303 ApplyError::MutationError(e) => write!(f, "Mutation error: {}", e),
304 }
305 }
306}
307
308impl std::error::Error for ApplyError {
309 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
310 match self {
311 ApplyError::RetrievalError(e) => Some(e),
312 ApplyError::MutationError(e) => Some(e),
313 _ => None,
314 }
315 }
316}
317
318#[derive(Debug)]
320pub struct ApplyErrorItem {
321 pub entity_id: EntityId,
322 pub collection: CollectionId,
323 pub cause: MutationError,
324}
325
326impl std::fmt::Display for ApplyErrorItem {
327 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
328 write!(f, "Failed to apply delta for entity {} in collection {}: {}", self.entity_id.to_base64_short(), self.collection, self.cause)
329 }
330}
331
332impl From<RetrievalError> for ApplyError {
333 fn from(err: RetrievalError) -> Self { ApplyError::RetrievalError(Box::new(err)) }
334}
335
336impl From<MutationError> for ApplyError {
337 fn from(err: MutationError) -> Self { ApplyError::MutationError(Box::new(err)) }
338}
339
340impl From<ApplyError> for RetrievalError {
341 fn from(err: ApplyError) -> Self { RetrievalError::ApplyError(err) }
342}