datumesh_store/error.rs
1//! The store's error type.
2
3use std::fmt;
4
5use datumesh_core::ErrorCode;
6
7/// What a [`Store`](crate::Store) method or a migration can fail with.
8#[non_exhaustive]
9#[derive(Debug)]
10pub enum Error {
11 /// The core rejected the input: not canonical, not a receipt, a receipt that does not
12 /// verify against the stored key document, not an instant or hash, a key document that
13 /// does not satisfy SPEC 9.2, ... The core's error carries its code
14 /// ([`Error::code`]), JSON path and detail.
15 Invalid(datumesh_core::Error),
16 /// An append-only history refused a time that is not later than its latest entry:
17 /// `put_version` (`what` = `"version"`, `key` = the cell id), `bind_name` (`"name"`,
18 /// the function name) or `put_namespace` (`"namespace"`, the host; equal is allowed
19 /// there).
20 NotLater {
21 /// `"version"`, `"name"` or `"namespace"`.
22 what: &'static str,
23 /// The cell id, function name or host.
24 key: String,
25 /// The time given.
26 given: String,
27 /// The latest time already recorded.
28 latest: String,
29 },
30 /// Something the write refers to is not in the store: the receipt of a version, the
31 /// descriptor of a name binding, or (since 0.4.1) the class or a method's descriptor of a
32 /// class binding.
33 NotFound {
34 /// `"receipt"`, `"descriptor"` or (since 0.4.1) `"class"`.
35 what: &'static str,
36 /// Its hash.
37 key: String,
38 },
39 /// The receipt named by `put_version` is for another cell, or has another `tx`.
40 Mismatch {
41 /// `"cell_id"` or `"tx"`.
42 what: &'static str,
43 /// The value given to `put_version`.
44 expected: String,
45 /// The receipt's value.
46 found: String,
47 },
48 /// A receipt with this hash is stored with other bytes: the same payload with another
49 /// valid signature by the same key (the receipt hash does not cover `sig`; it covers
50 /// `computed_by`, so a rotated key gives another hash). Only a randomised signer makes
51 /// two valid signatures; RFC 8032 Ed25519 is deterministic. The stored receipt is kept.
52 Conflict {
53 /// The receipt hash.
54 hash: String,
55 },
56 /// A new write under a suspended namespace (domain validation): a receipt signed by the
57 /// host, a version of such a receipt, or a name under the host, while the host's
58 /// namespace is suspended ([`Namespace::suspended_at`](crate::Namespace::suspended_at)).
59 /// Reads, and putting a receipt that is already stored, are not refused.
60 NamespaceSuspended {
61 /// The suspended host.
62 host: String,
63 /// When it was suspended.
64 suspended_at: String,
65 },
66 /// Class names and function names share one namespace of names, and `name` is currently
67 /// bound as the other kind: [`Store::bind_class`](crate::Store::bind_class) of a name
68 /// whose latest binding is a function (or of a class's method name whose latest binding is
69 /// a class), or [`Store::bind_name`](crate::Store::bind_name) of a name whose latest
70 /// binding is a class. Nothing is bound. Since 0.4.1.
71 NameTaken {
72 /// The name refused (for a method name, `<class name>/<method>`).
73 name: String,
74 /// What it is bound as now: `"function"` or `"class"`.
75 bound_as: &'static str,
76 },
77 /// The database refused or failed: the server's message and SQLSTATE (PostgreSQL) or
78 /// SQLite's message and result code, or the driver's description of a failure that is
79 /// not the database's (no connection, a URL that does not parse, a TLS handshake
80 /// refused, a certificate that did not verify).
81 Database(DatabaseError),
82 /// No connection became free within the pool's checkout timeout.
83 PoolTimeout,
84 /// A migration could not be applied or checked.
85 Migration(String),
86 /// The call needs a capability this store does not have: the vector calls
87 /// (`vector_find`, `put_embeddings`) where [`Store::vector_available`](crate::Store::vector_available)
88 /// is false (SQLite, or PostgreSQL without the `vector` extension). Since 0.5.0.
89 Unsupported(String),
90 /// A connection option is unusable: a root certificate bundle
91 /// ([`PoolOptions::tls_root_certificates_pem`](crate::PoolOptions::tls_root_certificates_pem))
92 /// with no certificate, or one that does not parse.
93 Config(String),
94}
95
96/// A database failure, [`Error::Database`]: what the database said (PostgreSQL: the
97/// server's message and SQLSTATE; SQLite: its message and result code), or the driver's
98/// description of a failure that is not the database's.
99///
100/// Its [`source`](std::error::Error::source) is the driver's error (type erased: the
101/// drivers' types are not part of this crate's API outside
102/// [`pg_unstable`](crate::pg_unstable)).
103#[derive(Debug)]
104pub struct DatabaseError {
105 message: String,
106 code: Option<String>,
107 source: Box<dyn std::error::Error + Send + Sync + 'static>,
108}
109
110impl DatabaseError {
111 pub(crate) fn new(e: postgres::Error) -> DatabaseError {
112 let (message, code) = match e.as_db_error() {
113 Some(d) => (d.message().to_string(), Some(d.code().code().to_string())),
114 None => (driver_text(&e), None),
115 };
116 DatabaseError { message, code, source: Box::new(e) }
117 }
118
119 /// A SQLite failure: SQLite's message and the name of its (extended) result code,
120 /// or, for a failure of the driver's own (a value of an unexpected type), its text.
121 #[cfg(feature = "sqlite")]
122 pub(crate) fn sqlite(e: rusqlite::Error) -> DatabaseError {
123 let (message, code) = match &e {
124 rusqlite::Error::SqliteFailure(f, msg) => {
125 (msg.clone().unwrap_or_else(|| f.to_string()), Some(crate::sqlite::result_code_name(f.extended_code)))
126 }
127 other => (other.to_string(), None),
128 };
129 DatabaseError { message, code, source: Box::new(e) }
130 }
131
132 /// A SQLite file that does not exist, for a call that must not create it
133 /// ([`SqliteStore::open_existing`](crate::SqliteStore::open_existing)).
134 #[cfg(feature = "sqlite")]
135 pub(crate) fn no_such_file(path: &std::path::Path) -> DatabaseError {
136 let message = format!("no such database file: {}", path.display());
137 let source = std::io::Error::new(std::io::ErrorKind::NotFound, message.clone());
138 DatabaseError { message, code: Some("SQLITE_CANTOPEN".into()), source: Box::new(source) }
139 }
140
141 /// The database's message (`relation "versions" does not exist`, `no such table:
142 /// versions`), or the driver's text and its causes when the database said nothing
143 /// (`error connecting to server: ...`, `error performing TLS handshake: invalid peer
144 /// certificate: ...`).
145 pub fn message(&self) -> &str {
146 &self.message
147 }
148
149 /// The code the database reported, if it was the database's error: PostgreSQL's
150 /// SQLSTATE (five characters, e.g. `42P01`), or (since 0.4.0) the name of SQLite's
151 /// extended result code (e.g. `SQLITE_ERROR`, `SQLITE_BUSY`,
152 /// `SQLITE_CONSTRAINT_TRIGGER`, `SQLITE_CANTOPEN`).
153 pub fn code(&self) -> Option<&str> {
154 self.code.as_deref()
155 }
156}
157
158/// The driver's error and its sources (`error performing TLS handshake: invalid peer
159/// certificate: UnknownIssuer`): the driver's own text often omits the cause.
160fn driver_text(e: &postgres::Error) -> String {
161 let mut text = e.to_string();
162 let mut source = std::error::Error::source(e);
163 while let Some(s) = source {
164 let s_text = s.to_string();
165 if !text.contains(&s_text) {
166 text.push_str(": ");
167 text.push_str(&s_text);
168 }
169 source = s.source();
170 }
171 text
172}
173
174impl fmt::Display for DatabaseError {
175 /// The message, then the SQLSTATE in parentheses when there is one.
176 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
177 match &self.code {
178 Some(c) => write!(f, "{} ({c})", self.message),
179 None => f.write_str(&self.message),
180 }
181 }
182}
183
184impl std::error::Error for DatabaseError {
185 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
186 Some(&*self.source)
187 }
188}
189
190impl Error {
191 /// The core's error code, for [`Error::Invalid`].
192 pub fn code(&self) -> Option<ErrorCode> {
193 match self {
194 Error::Invalid(e) => Some(e.code()),
195 _ => None,
196 }
197 }
198}
199
200impl fmt::Display for Error {
201 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
202 match self {
203 Error::Invalid(e) => write!(f, "invalid input: {e}"),
204 Error::NotLater { what, key, given, latest } => {
205 write!(f, "{what} {key}: {given} is not later than the latest, {latest}")
206 }
207 Error::NotFound { what, key } => write!(f, "no {what} {key} in the store"),
208 Error::Mismatch { what, expected, found } => {
209 write!(f, "the receipt's {what} is {found}, not {expected}")
210 }
211 Error::Conflict { hash } => {
212 write!(f, "receipt {hash} is stored with another valid signature; kept the stored one")
213 }
214 Error::NamespaceSuspended { host, suspended_at } => {
215 write!(f, "namespace {host} has been suspended since {suspended_at}: no new writes under it")
216 }
217 Error::NameTaken { name, bound_as } => {
218 write!(f, "name {name} is bound as a {bound_as}: class and function names are one namespace")
219 }
220 Error::Database(e) => write!(f, "database: {e}"),
221 Error::PoolTimeout => f.write_str("no database connection became free in time"),
222 Error::Migration(m) => write!(f, "migration: {m}"),
223 Error::Config(m) => write!(f, "configuration: {m}"),
224 Error::Unsupported(m) => write!(f, "not supported here: {m}"),
225 }
226 }
227}
228
229impl std::error::Error for Error {
230 /// For [`Error::Database`], the driver's error (as in 0.1.0; the [`DatabaseError`] is
231 /// this error's own text, so a chain of sources does not repeat it).
232 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
233 match self {
234 Error::Invalid(e) => Some(e),
235 Error::Database(e) => std::error::Error::source(e),
236 _ => None,
237 }
238 }
239}
240
241/// `?` on the driver's results, inside the crate: `.db()?` makes an [`Error::Database`].
242pub(crate) trait Db<T> {
243 fn db(self) -> Result<T>;
244}
245
246impl<T> Db<T> for core::result::Result<T, postgres::Error> {
247 fn db(self) -> Result<T> {
248 self.map_err(|e| Error::Database(DatabaseError::new(e)))
249 }
250}
251
252#[cfg(feature = "sqlite")]
253impl<T> Db<T> for core::result::Result<T, rusqlite::Error> {
254 fn db(self) -> Result<T> {
255 self.map_err(|e| Error::Database(DatabaseError::sqlite(e)))
256 }
257}
258
259impl From<datumesh_core::Error> for Error {
260 fn from(e: datumesh_core::Error) -> Error {
261 Error::Invalid(e)
262 }
263}
264
265/// `Result` with the store's [`Error`].
266pub type Result<T> = core::result::Result<T, Error>;