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