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 /// An operation waited past its time bound (decided 27 Nov, the second review): the barrier's wait
91 /// for a version writer (`PoolOptions::barrier_timeout`, or the SQLite options' barrier timeout), or a
92 /// read under its statement timeout (`slice_member_hashes_within`). The text names the operation. The
93 /// http layer answers 503. Since 0.6.5.
94 Timeout(String),
95 /// A connection option is unusable: a root certificate bundle
96 /// ([`PoolOptions::tls_root_certificates_pem`](crate::PoolOptions::tls_root_certificates_pem))
97 /// with no certificate, or one that does not parse.
98 Config(String),
99}
100
101/// A database failure, [`Error::Database`]: what the database said (PostgreSQL: the
102/// server's message and SQLSTATE; SQLite: its message and result code), or the driver's
103/// description of a failure that is not the database's.
104///
105/// Its [`source`](std::error::Error::source) is the driver's error (type erased: the
106/// drivers' types are not part of this crate's API outside
107/// [`pg_unstable`](crate::pg_unstable)).
108#[derive(Debug)]
109pub struct DatabaseError {
110 message: String,
111 code: Option<String>,
112 source: Box<dyn std::error::Error + Send + Sync + 'static>,
113}
114
115impl DatabaseError {
116 /// The SQLSTATE the server gave (PostgreSQL), when it gave one.
117 pub(crate) fn sqlstate(&self) -> Option<&str> {
118 self.code.as_deref()
119 }
120
121 pub(crate) fn new(e: postgres::Error) -> DatabaseError {
122 let (message, code) = match e.as_db_error() {
123 Some(d) => (d.message().to_string(), Some(d.code().code().to_string())),
124 None => (driver_text(&e), None),
125 };
126 DatabaseError { message, code, source: Box::new(e) }
127 }
128
129 /// A SQLite failure: SQLite's message and the name of its (extended) result code,
130 /// or, for a failure of the driver's own (a value of an unexpected type), its text.
131 #[cfg(feature = "sqlite")]
132 pub(crate) fn sqlite(e: rusqlite::Error) -> DatabaseError {
133 let (message, code) = match &e {
134 rusqlite::Error::SqliteFailure(f, msg) => {
135 (msg.clone().unwrap_or_else(|| f.to_string()), Some(crate::sqlite::result_code_name(f.extended_code)))
136 }
137 other => (other.to_string(), None),
138 };
139 DatabaseError { message, code, source: Box::new(e) }
140 }
141
142 /// A SQLite file that does not exist, for a call that must not create it
143 /// ([`SqliteStore::open_existing`](crate::SqliteStore::open_existing)).
144 #[cfg(feature = "sqlite")]
145 pub(crate) fn no_such_file(path: &std::path::Path) -> DatabaseError {
146 let message = format!("no such database file: {}", path.display());
147 let source = std::io::Error::new(std::io::ErrorKind::NotFound, message.clone());
148 DatabaseError { message, code: Some("SQLITE_CANTOPEN".into()), source: Box::new(source) }
149 }
150
151 /// The database's message (`relation "versions" does not exist`, `no such table:
152 /// versions`), or the driver's text and its causes when the database said nothing
153 /// (`error connecting to server: ...`, `error performing TLS handshake: invalid peer
154 /// certificate: ...`).
155 pub fn message(&self) -> &str {
156 &self.message
157 }
158
159 /// The code the database reported, if it was the database's error: PostgreSQL's
160 /// SQLSTATE (five characters, e.g. `42P01`), or (since 0.4.0) the name of SQLite's
161 /// extended result code (e.g. `SQLITE_ERROR`, `SQLITE_BUSY`,
162 /// `SQLITE_CONSTRAINT_TRIGGER`, `SQLITE_CANTOPEN`).
163 pub fn code(&self) -> Option<&str> {
164 self.code.as_deref()
165 }
166}
167
168/// The driver's error and its sources (`error performing TLS handshake: invalid peer
169/// certificate: UnknownIssuer`): the driver's own text often omits the cause.
170fn driver_text(e: &postgres::Error) -> String {
171 let mut text = e.to_string();
172 let mut source = std::error::Error::source(e);
173 while let Some(s) = source {
174 let s_text = s.to_string();
175 if !text.contains(&s_text) {
176 text.push_str(": ");
177 text.push_str(&s_text);
178 }
179 source = s.source();
180 }
181 text
182}
183
184impl fmt::Display for DatabaseError {
185 /// The message, then the SQLSTATE in parentheses when there is one.
186 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
187 match &self.code {
188 Some(c) => write!(f, "{} ({c})", self.message),
189 None => f.write_str(&self.message),
190 }
191 }
192}
193
194impl std::error::Error for DatabaseError {
195 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
196 Some(&*self.source)
197 }
198}
199
200impl Error {
201 /// The core's error code, for [`Error::Invalid`].
202 pub fn code(&self) -> Option<ErrorCode> {
203 match self {
204 Error::Invalid(e) => Some(e.code()),
205 _ => None,
206 }
207 }
208}
209
210impl fmt::Display for Error {
211 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
212 match self {
213 Error::Invalid(e) => write!(f, "invalid input: {e}"),
214 Error::NotLater { what, key, given, latest } => {
215 write!(f, "{what} {key}: {given} is not later than the latest, {latest}")
216 }
217 Error::NotFound { what, key } => write!(f, "no {what} {key} in the store"),
218 Error::Mismatch { what, expected, found } => {
219 write!(f, "the receipt's {what} is {found}, not {expected}")
220 }
221 Error::Conflict { hash } => {
222 write!(f, "receipt {hash} is stored with another valid signature; kept the stored one")
223 }
224 Error::NamespaceSuspended { host, suspended_at } => {
225 write!(f, "namespace {host} has been suspended since {suspended_at}: no new writes under it")
226 }
227 Error::NameTaken { name, bound_as } => {
228 write!(f, "name {name} is bound as a {bound_as}: class and function names are one namespace")
229 }
230 Error::Database(e) => write!(f, "database: {e}"),
231 Error::PoolTimeout => f.write_str("no database connection became free in time"),
232 Error::Timeout(m) => write!(f, "timed out: {m}"),
233 Error::Migration(m) => write!(f, "migration: {m}"),
234 Error::Config(m) => write!(f, "configuration: {m}"),
235 Error::Unsupported(m) => write!(f, "not supported here: {m}"),
236 }
237 }
238}
239
240impl std::error::Error for Error {
241 /// For [`Error::Database`], the driver's error (as in 0.1.0; the [`DatabaseError`] is
242 /// this error's own text, so a chain of sources does not repeat it).
243 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
244 match self {
245 Error::Invalid(e) => Some(e),
246 Error::Database(e) => std::error::Error::source(e),
247 _ => None,
248 }
249 }
250}
251
252/// `?` on the driver's results, inside the crate: `.db()?` makes an [`Error::Database`].
253pub(crate) trait Db<T> {
254 fn db(self) -> Result<T>;
255}
256
257impl<T> Db<T> for core::result::Result<T, postgres::Error> {
258 fn db(self) -> Result<T> {
259 self.map_err(|e| Error::Database(DatabaseError::new(e)))
260 }
261}
262
263#[cfg(feature = "sqlite")]
264impl<T> Db<T> for core::result::Result<T, rusqlite::Error> {
265 fn db(self) -> Result<T> {
266 self.map_err(|e| Error::Database(DatabaseError::sqlite(e)))
267 }
268}
269
270impl From<datumesh_core::Error> for Error {
271 fn from(e: datumesh_core::Error) -> Error {
272 Error::Invalid(e)
273 }
274}
275
276/// `Result` with the store's [`Error`].
277pub type Result<T> = core::result::Result<T, Error>;
278
279/// `e`, as [`Error::Timeout`] (naming `what`) when the server cancelled the statement for its timeout
280/// (SQLSTATE 57014) or the lock wait timed out (55P03); unchanged otherwise.
281pub(crate) fn timed_out(e: Error, what: &str) -> Error {
282 match &e {
283 Error::Database(d) if matches!(d.sqlstate(), Some("55P03") | Some("57014")) => Error::Timeout(what.to_string()),
284 _ => e,
285 }
286}