happenstance_core/error.rs
1//! Error types for the contract layer.
2//!
3//! Two distinct families live here:
4//!
5//! * **Validation errors** ([`InvalidTag`], [`InvalidEventType`],
6//! [`InvalidQuery`]) are returned by constructors that enforce the
7//! specification's invariants. They are programmer errors, not runtime
8//! conditions.
9//! * **[`AppendError`]** is the outcome of an append. It separates
10//! [`ConditionViolated`] and a transient [`Busy`](AppendError::Busy) refusal
11//! from adapter-specific failures; its documentation says why that is in the
12//! type system rather than in a string.
13
14use crate::SequencePosition;
15
16/// A [`Tag`](crate::Tag) failed validation.
17#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
18#[non_exhaustive]
19pub enum InvalidTag {
20 /// The tag, or one half of a `key:value` pair, was empty.
21 #[error("a tag must not be empty")]
22 Empty,
23 /// The tag exceeded [`MAX_TAG_LEN`](crate::MAX_TAG_LEN) bytes.
24 #[error("a tag must be at most {max} bytes, got {len}", max = crate::MAX_TAG_LEN)]
25 TooLong {
26 /// The rejected length, in bytes.
27 len: usize,
28 },
29 /// The tag contained a control character (Unicode `Cc`).
30 #[error("a tag must not contain control characters")]
31 ControlCharacter,
32 /// The tag contained one of the nine explicit bidirectional formatting
33 /// controls: U+202A–U+202E or U+2066–U+2069.
34 ///
35 /// Separate from [`ControlCharacter`](Self::ControlCharacter) because the
36 /// two refusals have different remedies. A control character in an
37 /// identifier is almost always an encoding bug; a bidirectional override is
38 /// almost always an attack — a tag that renders as one thing in every
39 /// console and matches another in every query.
40 #[error("a tag must not contain bidirectional formatting controls")]
41 BidirectionalControl,
42 /// The key half of a `key:value` pair itself contained a colon, which would
43 /// make [`Tag::key`](crate::Tag::key) ambiguous.
44 #[error("the key of a `key:value` tag must not contain a colon")]
45 ColonInKey,
46}
47
48/// An [`EventType`](crate::EventType) failed validation.
49#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
50#[non_exhaustive]
51pub enum InvalidEventType {
52 /// The event type was empty. The specification requires every event to
53 /// carry a type.
54 #[error("an event type must not be empty")]
55 Empty,
56 /// The event type exceeded [`MAX_EVENT_TYPE_LEN`](crate::MAX_EVENT_TYPE_LEN)
57 /// bytes.
58 #[error("an event type must be at most {max} bytes, got {len}", max = crate::MAX_EVENT_TYPE_LEN)]
59 TooLong {
60 /// The rejected length, in bytes.
61 len: usize,
62 },
63 /// The event type contained a control character (Unicode `Cc`).
64 #[error("an event type must not contain control characters")]
65 ControlCharacter,
66 /// The event type contained one of the nine explicit bidirectional
67 /// formatting controls: U+202A–U+202E or U+2066–U+2069.
68 ///
69 /// Separate from [`ControlCharacter`](Self::ControlCharacter) for the reason
70 /// [`InvalidTag::BidirectionalControl`] gives.
71 #[error("an event type must not contain bidirectional formatting controls")]
72 BidirectionalControl,
73}
74
75impl From<core::convert::Infallible> for InvalidEventType {
76 /// Lets [`Event::new`](crate::Event::new) accept both `&str`, which
77 /// converts fallibly, and an already-built [`EventType`](crate::EventType),
78 /// whose conversion cannot fail.
79 ///
80 /// The match has no arms because [`Infallible`](core::convert::Infallible)
81 /// has no values, and the compiler accepts an empty match on an uninhabited
82 /// type as exhaustive. That is what lets an infallible conversion satisfy a
83 /// fallible bound.
84 fn from(never: core::convert::Infallible) -> Self {
85 match never {}
86 }
87}
88
89/// A [`Query`](crate::Query) or [`QueryItem`](crate::QueryItem) failed
90/// validation.
91#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
92#[non_exhaustive]
93pub enum InvalidQuery {
94 /// A query was built from zero items. The specification requires a query to
95 /// hold at least one item or to be the match-all query; use
96 /// [`Query::all`](crate::Query::all) for the latter.
97 #[error("a query must contain at least one item; use `Query::all()` to match everything")]
98 NoItems,
99 /// A query item constrained neither types nor tags, and would therefore
100 /// match every event — which is [`Query::all`](crate::Query::all)'s job.
101 #[error("a query item must constrain at least one of types or tags")]
102 UnconstrainedItem,
103 /// One of the item's event types was itself invalid.
104 #[error(transparent)]
105 EventType(#[from] InvalidEventType),
106 /// One of the item's tags was itself invalid.
107 ///
108 /// This is what lets a command handler in a library crate build tags, items
109 /// and a query, propagate all three with `?`, and still have one error type
110 /// — without a bespoke enum and without reaching for `anyhow`, which the
111 /// house style forbids in library code. The conversion direction is
112 /// unambiguous: a query can contain tags, and a tag cannot contain a query.
113 #[error(transparent)]
114 Tag(#[from] InvalidTag),
115}
116
117impl From<core::convert::Infallible> for InvalidQuery {
118 /// Lets [`QueryItem::new`](crate::QueryItem::new) accept both `&str` (which
119 /// converts fallibly) and an already-built
120 /// [`EventType`](crate::EventType) (which cannot fail).
121 fn from(never: core::convert::Infallible) -> Self {
122 match never {}
123 }
124}
125
126/// The specification-defined outcome of an append that was rejected because the
127/// store already held an event matching the
128/// [`AppendCondition`](crate::AppendCondition).
129///
130/// This is the DCB concurrency signal. Callers respond by rebuilding their
131/// decision model from the current state and retrying — it is an expected,
132/// routine outcome under contention, not a fault.
133#[derive(Debug, Clone, PartialEq, Eq)]
134#[non_exhaustive]
135pub struct ConditionViolated {
136 /// The position of a conflicting event, when the adapter can identify one
137 /// cheaply.
138 ///
139 /// **A hint, not a promise, and a caller must be written for `None`.** An
140 /// adapter that detects the conflict without learning which event caused it
141 /// reports `None`, and that is not a deficient adapter: a store reached over
142 /// one-shot HTTP has no interactive transaction, so the only shape it can
143 /// express is a conditional `INSERT … SELECT … WHERE NOT EXISTS`, which
144 /// yields a boolean and no row. A retry loop that branches on this field
145 /// being `Some` works against an in-process store and stops working against
146 /// a remote one.
147 pub conflicting_position: Option<SequencePosition>,
148}
149
150impl ConditionViolated {
151 /// A violation with no identified conflicting event.
152 #[must_use]
153 pub const fn unspecified() -> Self {
154 Self {
155 conflicting_position: None,
156 }
157 }
158
159 /// A violation naming the event that caused it.
160 #[must_use]
161 pub const fn at(position: SequencePosition) -> Self {
162 Self {
163 conflicting_position: Some(position),
164 }
165 }
166}
167
168impl core::fmt::Display for ConditionViolated {
169 /// Renders the conflicting position when the adapter supplied one.
170 ///
171 /// Hand-written rather than a `thiserror` attribute because the message has
172 /// two shapes, and the field the store already populates was previously
173 /// carried and never shown — an operator reading a log got "the store
174 /// already contains a matching event" and no way to find which.
175 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
176 f.write_str("append condition violated: the store already contains a matching event")?;
177 if let Some(position) = self.conflicting_position {
178 write!(f, " at position {position}")?;
179 }
180 f.write_str("; rebuild the decision model and retry")
181 }
182}
183
184impl core::error::Error for ConditionViolated {}
185
186/// Why an append failed.
187///
188/// The DCB concurrency signal is lifted out of the adapter's error type and
189/// into this enum on purpose. Every store fails differently — disk full, socket
190/// closed, a lost acknowledgement — but every store fails *identically* when an
191/// append condition is violated, and callers must be able to distinguish
192/// "retry the decision" from "this went wrong" without pattern-matching on
193/// strings or knowing which adapter they were handed.
194///
195/// A **busy** refusal is lifted out for the same reason, into
196/// [`Busy`](Self::Busy). `SQLITE_BUSY` after a busy timeout and a PostgreSQL
197/// serialisation failure after an adapter's own retry budget are different
198/// driver errors with one meaning — *nothing was written, and the same decision
199/// may be taken again* — and a generic caller that could only ask
200/// [`is_condition_violated`](Self::is_condition_violated) could not see that
201/// meaning behind [`Store`](Self::Store).
202///
203/// # Examples
204///
205/// ```
206/// # use happenstance_core::{AppendError, ConditionViolated};
207/// # fn handle<E: core::fmt::Debug>(result: Result<(), AppendError<E>>) {
208/// match result {
209/// Ok(()) => {}
210/// // Expected under contention: rebuild the decision model and retry.
211/// Err(AppendError::ConditionViolated(_)) => { /* re-decide */ }
212/// // Transient, and nothing was written: deciding again is safe.
213/// Err(AppendError::Busy(_)) => { /* re-decide, within your own bound */ }
214/// // Everything else is a genuine failure.
215/// Err(other) => panic!("append failed: {other:?}"),
216/// }
217/// # }
218/// ```
219///
220/// Note the catch-all arm: this enum is `#[non_exhaustive]`, so matching every
221/// named variant is not enough and a wildcard is required.
222#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
223#[non_exhaustive]
224pub enum AppendError<E> {
225 /// The store already contained an event matching the append condition.
226 #[error(transparent)]
227 ConditionViolated(#[from] ConditionViolated),
228
229 /// The caller passed an empty batch.
230 ///
231 /// The specification defines a batch as a non-empty collection of events,
232 /// so there is no position an adapter could honestly return. This is a
233 /// caller bug, not a store failure.
234 #[error("an append must contain at least one event")]
235 NoEvents,
236
237 /// The batch exceeded a capacity the store documents.
238 ///
239 /// Distinct from [`Store`](Self::Store) on purpose, and the distinction is
240 /// the whole reason the variant exists: a caller that cannot tell "this will
241 /// never fit here, park it and tell a human" from "the disk is full, retry"
242 /// has to guess, and a sync runner that guesses wrong drops an event
243 /// permanently.
244 ///
245 /// A store MUST report a capacity refusal through this variant rather than
246 /// through [`Store`](Self::Store), and MUST NOT truncate instead.
247 #[error("append exceeds the store's {limit} limit: {len}")]
248 ExceedsStoreLimit {
249 /// Which limit was exceeded.
250 limit: crate::limits::StoreLimit,
251 /// The value that exceeded it — a byte count, a tag count or an event
252 /// count, according to `limit`.
253 len: usize,
254 },
255
256 /// The store refused the append for a transient reason, before the batch
257 /// took any effect.
258 ///
259 /// **Nothing was written, and re-running the decision is safe.** That
260 /// sentence is the variant's whole contract, and an adapter reporting it
261 /// promises all three parts of it:
262 ///
263 /// * **Before any effect.** No event of the batch is in the store, and none
264 /// will appear later. A position the store allocated and then abandoned
265 /// may leave a gap, which the specification already permits.
266 /// * **Transient.** The same call can succeed once whatever held the store
267 /// has let go: a lock not acquired within the adapter's own bound, or a
268 /// serialisation failure its own retry budget did not absorb. A refusal
269 /// that no retry can cure is [`Store`](Self::Store).
270 /// * **Safe to re-run.** Read again, decide again, and append under the new
271 /// read's condition, which is the loop a
272 /// [`ConditionViolated`](Self::ConditionViolated) already asks for.
273 /// Because nothing landed, re-submitting the same batch under the same
274 /// condition is safe too: the condition still guards it.
275 ///
276 /// **An ambiguous outcome MUST stay [`Store`](Self::Store).** A commit whose
277 /// acknowledgement was lost, a connection that dropped after `COMMIT` was
278 /// sent, a timeout whose effect is unknown: each may have written, so none
279 /// may be reported here, however transient its cause looks. `Busy` is a
280 /// claim about what the store holds, not about why the driver failed. A
281 /// caller who re-runs an unconditional append on the strength of it would
282 /// otherwise append twice. A store that cannot tell is not busy.
283 ///
284 /// It is **not** the concurrency signal:
285 /// [`is_condition_violated`](AppendError::is_condition_violated) answers
286 /// `false`, because no condition was evaluated. Nor is it a capacity
287 /// refusal, which is [`ExceedsStoreLimit`](Self::ExceedsStoreLimit) and will
288 /// never fit. A store is never obliged to produce it: one that serialises
289 /// its writers in-process, as `MemoryEventStore` does, has nothing to be
290 /// busy with.
291 ///
292 /// The payload is the adapter's own error, carried for diagnostics exactly
293 /// as [`Store`](Self::Store) carries it and reachable through
294 /// [`source`](core::error::Error::source). Branch on the variant, never on
295 /// the payload.
296 #[error("the store was busy and refused the append before writing anything")]
297 Busy(#[source] E),
298
299 /// The adapter failed for its own reasons.
300 ///
301 /// Including every outcome it cannot vouch for: an append reported here may
302 /// or may not have landed. [`Busy`](Self::Busy) is the refusal known to have
303 /// written nothing.
304 #[error(transparent)]
305 Store(E),
306}
307
308impl<E> AppendError<E> {
309 /// Whether this is the DCB concurrency signal rather than a store failure.
310 pub const fn is_condition_violated(&self) -> bool {
311 matches!(self, Self::ConditionViolated(_))
312 }
313
314 /// Whether the store refused transiently, before writing anything.
315 ///
316 /// `true` only for [`Busy`](Self::Busy). A caller that retries on this
317 /// re-runs a decision that is known not to have landed. It is not the
318 /// question [`is_condition_violated`](Self::is_condition_violated) asks, and
319 /// a loop that wants both asks both.
320 ///
321 /// ```
322 /// # use happenstance_core::AppendError;
323 /// let busy: AppendError<std::io::Error> =
324 /// AppendError::Busy(std::io::Error::other("database is locked"));
325 /// assert!(busy.is_busy());
326 /// assert!(!busy.is_condition_violated());
327 ///
328 /// // A store failure is neither, whatever its message says.
329 /// let broken: AppendError<std::io::Error> =
330 /// AppendError::Store(std::io::Error::other("database is locked"));
331 /// assert!(!broken.is_busy());
332 /// ```
333 pub const fn is_busy(&self) -> bool {
334 matches!(self, Self::Busy(_))
335 }
336
337 /// Maps the adapter-specific error wherever one is carried, in
338 /// [`Store`](Self::Store) and in [`Busy`](Self::Busy), leaving every other
339 /// variant untouched.
340 ///
341 /// Useful when a higher layer wraps an adapter's error in its own type. The
342 /// variant survives the mapping: a busy refusal stays busy, because the
343 /// classification is the store's claim about what it holds, and a wrapper
344 /// has no standing to change it.
345 ///
346 /// ```
347 /// # use happenstance_core::AppendError;
348 /// let busy: AppendError<&str> = AppendError::Busy("database is locked");
349 /// let wrapped: AppendError<String> = busy.map_store(str::to_owned);
350 /// assert!(wrapped.is_busy());
351 /// ```
352 pub fn map_store<F, T>(self, f: F) -> AppendError<T>
353 where
354 F: FnOnce(E) -> T,
355 {
356 match self {
357 Self::ConditionViolated(violation) => AppendError::ConditionViolated(violation),
358 Self::NoEvents => AppendError::NoEvents,
359 Self::ExceedsStoreLimit { limit, len } => AppendError::ExceedsStoreLimit { limit, len },
360 Self::Busy(err) => AppendError::Busy(f(err)),
361 Self::Store(err) => AppendError::Store(f(err)),
362 }
363 }
364}
365
366#[cfg(test)]
367mod tests {
368 use alloc::borrow::ToOwned;
369 use alloc::string::ToString;
370
371 use super::AppendError;
372
373 /// A payload a test can name, with the message a driver would give it.
374 #[derive(Debug, PartialEq, Eq, thiserror::Error)]
375 #[error("database is locked")]
376 struct Locked;
377
378 /// `map_store` keeps a busy refusal busy.
379 ///
380 /// The wrong implementation this rejects is the one-arm shortcut, which
381 /// maps `Busy` into `Store`. It compiles and keeps the payload, and it
382 /// silently turns a refusal that wrote nothing into one a caller must treat
383 /// as possibly written.
384 #[test]
385 fn map_store_keeps_the_busy_classification() {
386 let mapped = AppendError::Busy(Locked).map_store(|locked| locked.to_string());
387 assert_eq!(mapped, AppendError::Busy("database is locked".to_owned()));
388
389 let mapped = AppendError::Store(Locked).map_store(|locked| locked.to_string());
390 assert_eq!(mapped, AppendError::Store("database is locked".to_owned()));
391 }
392
393 /// A busy refusal says so, and keeps the adapter's error as its source.
394 ///
395 /// `Store` is `transparent` and renders the adapter's message alone. `Busy`
396 /// cannot be, or an operator's log line would read the same for a refusal
397 /// that wrote nothing and a failure that may have written.
398 #[test]
399 fn busy_names_itself_and_carries_the_adapter_error_as_its_source() {
400 let busy = AppendError::Busy(Locked);
401 assert!(busy.to_string().contains("busy"), "got: {busy}");
402 let source = core::error::Error::source(&busy).map(ToString::to_string);
403 assert_eq!(source.as_deref(), Some("database is locked"));
404
405 let broken = AppendError::Store(Locked);
406 assert!(!broken.to_string().contains("busy"), "got: {broken}");
407 }
408}