Skip to main content

drevo_core/
error.rs

1//! The error type of `drevo-core`.
2//!
3//! [`crate::error::CoreError`] is returned by the graph engine, its indexes and
4//! the dump format. It names the graph-level failures (`NodeNotFound`,
5//! `EdgeNotFound`, `DuplicateTitle`, `InvalidWeight`) plus the I/O and JSON
6//! boundaries (`Io`, `Json`).
7//!
8//! Failures from layers built on top — vector indexes, transaction state in a
9//! server — have no structured home here; they travel in the opaque
10//! [`crate::error::CoreError::Backend`] variant, carrying the lower layer's
11//! rendered message.
12//!
13//! # Relationship to drevo's `DrevoError`
14//!
15//! drevo's own error type, `DrevoError`, also covers vector indexes, codecs
16//! and server-side transaction state. The two convert in both directions: the
17//! shared variants map one-to-one, and anything without a counterpart becomes
18//! [`crate::error::CoreError::Backend`] going down or `DrevoError::Io` coming
19//! back up.
20
21use thiserror::Error;
22
23/// Errors from the graph engine, its indexes and the dump format.
24///
25/// See the [module docs](self) for how it relates to drevo's `DrevoError`.
26#[derive(Debug, Error)]
27pub enum CoreError {
28    /// The requested node was not found.
29    #[error("node not found: {0}")]
30    NodeNotFound(u64),
31
32    /// The requested edge was not found.
33    #[error("edge not found: {0}")]
34    EdgeNotFound(u64),
35
36    /// A node with the given title already exists (title uniqueness).
37    #[error("duplicate title: {0}")]
38    DuplicateTitle(String),
39
40    /// An edge weight failed validation: it is not a finite `f32`
41    /// (NaN, +Inf, or -Inf are rejected at edge create / update). `Edge`
42    /// derives `PartialEq`, which `f32::NAN != f32::NAN` would break.
43    #[error("invalid edge weight: {0} — weight must be a finite f32")]
44    InvalidWeight(f32),
45
46    /// An I/O error occurred (e.g. reading or writing a dump file).
47    #[error("io error: {0}")]
48    Io(#[from] std::io::Error),
49
50    /// A JSON (de)serialization error occurred while encoding a property value
51    /// or a dump record.
52    #[error("json error: {0}")]
53    Json(#[from] serde_json::Error),
54
55    /// The durable store is already open by another handle or process.
56    ///
57    /// [`NativeGraph::open_durable`](crate::native::NativeGraph::open_durable)
58    /// takes an exclusive advisory lock on the store's lock sidecar; a second
59    /// open of the same path fails with this rather than letting two writers
60    /// interleave WAL appends and corrupt the log. Maps to drevo's
61    /// `DrevoError::Locked`. The advisory lock is released when the
62    /// owning process dies, so a crash never leaves a stale lock behind.
63    #[error("database locked")]
64    Locked,
65
66    /// A failure from a layer built on top — a vector-index error, a
67    /// transaction-state error — that has no structured variant here. Carries
68    /// the lower layer's
69    /// rendered message so nothing is lost on the wire, even though the
70    /// structured variant is not preserved.
71    #[error("backend error: {0}")]
72    Backend(String),
73
74    /// Two-phase commit: a transaction is prepared and every other
75    /// write is refused until it is resolved (the prepared fence). Retryable;
76    /// carries the pending global transaction ids.
77    #[error("writes are paused while prepared transaction(s) {} await resolution; retry", .0.join(", "))]
78    PreparedTransactionPending(Vec<String>),
79}
80
81/// Convenience alias for fallible core operations.
82pub type Result<T> = std::result::Result<T, CoreError>;
83
84#[cfg(test)]
85mod tests {
86    use super::*;
87
88    #[test]
89    fn display_matches_the_drevo_error_wording() {
90        // The rendered strings are asserted here so the two crates' error
91        // messages stay identical across the seam (the HTTP/Bolt layers surface
92        // them verbatim).
93        assert_eq!(CoreError::NodeNotFound(7).to_string(), "node not found: 7");
94        assert_eq!(CoreError::EdgeNotFound(9).to_string(), "edge not found: 9");
95        assert_eq!(
96            CoreError::DuplicateTitle("Dup".into()).to_string(),
97            "duplicate title: Dup"
98        );
99        assert_eq!(
100            CoreError::InvalidWeight(f32::NAN).to_string(),
101            "invalid edge weight: NaN — weight must be a finite f32"
102        );
103        assert_eq!(
104            CoreError::Backend("scan failed".into()).to_string(),
105            "backend error: scan failed"
106        );
107        assert_eq!(CoreError::Locked.to_string(), "database locked");
108    }
109
110    #[test]
111    fn prepared_transaction_pending_names_the_gids() {
112        assert_eq!(
113            CoreError::PreparedTransactionPending(vec!["a".into(), "b".into()]).to_string(),
114            "writes are paused while prepared transaction(s) a, b await resolution; retry"
115        );
116    }
117
118    #[test]
119    fn io_and_json_lift_through_the_question_mark_operator() {
120        fn io() -> Result<()> {
121            Err(std::io::Error::other("boom"))?;
122            Ok(())
123        }
124        fn json() -> Result<()> {
125            let _: serde_json::Value = serde_json::from_str("{ not json")?;
126            Ok(())
127        }
128        assert!(matches!(io(), Err(CoreError::Io(_))));
129        assert!(matches!(json(), Err(CoreError::Json(_))));
130    }
131}