1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
use std::{
    array::TryFromSliceError,
    convert::Infallible,
    fmt::{Debug, Display},
};

use backtrace::Backtrace;
use parking_lot::{Mutex, MutexGuard};
use thiserror::Error;

use crate::AbortError;

/// An error from Nebari as well as an associated backtrace.
pub struct Error {
    /// The error that occurred.
    pub kind: ErrorKind,

    backtrace: Mutex<Backtrace>,
}

impl Error {
    pub(crate) fn data_integrity(error: impl Into<Self>) -> Self {
        Self {
            kind: ErrorKind::DataIntegrity(Box::new(error.into())),
            backtrace: Mutex::new(Backtrace::new_unresolved()),
        }
    }

    /// Returns the backtrace of where this error was created.
    pub fn backtrace(&self) -> MutexGuard<'_, Backtrace> {
        let mut backtrace = self.backtrace.lock();
        backtrace.resolve();
        backtrace
    }

    fn format_backtrace_frames(&self) -> Vec<String> {
        let mut backtrace = self.backtrace.lock();
        backtrace.resolve();
        backtrace
            .frames()
            .iter()
            .filter_map(|frame| frame.symbols().first())
            .enumerate()
            .map(|(index, symbol)| {
                let mut line = format!("{index}: ");
                if let Some(name) = symbol.name() {
                    line.push_str(&name.to_string());
                    line.push(' ');
                } else if let Some(addr) = symbol.addr() {
                    line.push_str(&format!("{:x}", addr as usize));
                    line.push(' ');
                } else {
                    // Give up on formatting this one.
                    line.push_str(&format!("{symbol:?}"));
                    return line;
                }

                if let Some(file) = symbol.filename() {
                    if let Some(file) = file.to_str() {
                        line.push_str("at ");
                        line.push_str(file);
                    } else {
                        line.push_str(&format!("at {file:?}"));
                    }

                    if let Some(lineno) = symbol.lineno() {
                        line.push(':');
                        line.push_str(&lineno.to_string());
                        if let Some(col) = symbol.colno() {
                            line.push(':');
                            line.push_str(&col.to_string());
                        }
                    }
                }
                line
            })
            .collect()
    }
}

impl std::error::Error for Error {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        self.kind.source()
    }
}

impl Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        Display::fmt(&self.kind, f)?;

        #[cfg(debug_assertions)]
        {
            f.write_str("\nstack backtrace:")?;

            for (index, frame) in self.format_backtrace_frames().into_iter().enumerate() {
                write!(f, "{index}: {frame}")?;
            }
        }

        Ok(())
    }
}

impl Debug for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let frames = self.format_backtrace_frames();
        f.debug_struct("Error")
            .field("kind", &self.kind)
            .field("backtrace", &&frames[..])
            .finish()
    }
}

impl From<ErrorKind> for Error {
    fn from(kind: ErrorKind) -> Self {
        Self {
            kind,
            backtrace: Mutex::new(Backtrace::new_unresolved()),
        }
    }
}

impl From<AbortError<Infallible>> for Error {
    fn from(ae: AbortError<Infallible>) -> Self {
        ae.infallible()
    }
}

impl From<std::io::Error> for Error {
    fn from(err: std::io::Error) -> Self {
        Self {
            kind: ErrorKind::from(err),
            backtrace: Mutex::new(Backtrace::new_unresolved()),
        }
    }
}

impl From<&'static str> for Error {
    fn from(message: &'static str) -> Self {
        Self {
            kind: ErrorKind::message(message),
            backtrace: Mutex::new(Backtrace::new_unresolved()),
        }
    }
}

impl From<flume::RecvError> for Error {
    fn from(_err: flume::RecvError) -> Self {
        Self {
            kind: ErrorKind::Internal(InternalError::InternalCommunication),
            backtrace: Mutex::new(Backtrace::new_unresolved()),
        }
    }
}

impl<T> From<flume::SendError<T>> for Error {
    fn from(_err: flume::SendError<T>) -> Self {
        Self {
            kind: ErrorKind::Internal(InternalError::InternalCommunication),
            backtrace: Mutex::new(Backtrace::new_unresolved()),
        }
    }
}

impl From<String> for Error {
    fn from(message: String) -> Self {
        Self {
            kind: ErrorKind::message(message),
            backtrace: Mutex::new(Backtrace::new_unresolved()),
        }
    }
}

impl From<TryFromSliceError> for Error {
    fn from(_: TryFromSliceError) -> Self {
        Self {
            kind: ErrorKind::Internal(InternalError::IncorrectByteLength),
            backtrace: Mutex::new(Backtrace::new_unresolved()),
        }
    }
}

/// An error from Nebari.
#[derive(Debug, Error)]
#[error(transparent)]
pub enum ErrorKind {
    /// An error has occurred. The string contains human-readable error message.
    /// This error is only used in situations where a user is not expected to be
    /// able to recover automatically from the error.
    #[error("{0}")]
    Message(String),
    /// An error occurred while performing IO.
    #[error("io error: {0}")]
    Io(#[from] std::io::Error),
    /// An unrecoverable data integrity error was encountered.
    #[error("an unrecoverable error with the data on disk has been found: {0}")]
    DataIntegrity(Box<Error>),
    /// An invalid tree name was provided.
    ///
    /// Valid characters are:
    ///
    /// - `'a'..='z'`
    /// - `'A'..='Z'`
    /// - `'0'..='9'`
    /// - `'-'` (Hyphen)
    /// - `'_'` (Underscore)
    /// - `'.'` (Period)
    #[error("tree name not valid")]
    InvalidTreeName,
    /// A key was too large.
    #[error("key too large")]
    KeyTooLarge,
    /// A value was too large.
    #[error("value too large")]
    ValueTooLarge,
    /// A multi-key operation did not have its keys ordered.
    #[error("multi-key operation did not have its keys ordered")]
    KeysNotOrdered,
    /// An internal error occurred. These errors are not intended to be
    /// recoverable and represent some internal error condition.
    #[error("an internal error occurred: {0}")]
    Internal(InternalError),
    /// The underlying tree file has been compacted, and the request cannot
    /// be completed. Reopen the file and try again.
    #[error("the file has been compacted. reopen the file and try again")]
    TreeCompacted,
    /// An error ocurred in the vault.
    #[error("a vault error occurred: {0}")]
    Vault(Box<dyn SendSyncError>),
    /// An transaction was pushed to the log out of order.
    #[error("transaction pushed out of order")]
    TransactionPushedOutOfOrder,
}

pub trait SendSyncError: std::error::Error + Send + Sync + 'static {}
impl<T> SendSyncError for T where T: std::error::Error + Send + Sync + 'static {}

impl ErrorKind {
    /// Returns a new [`Error::Message`] instance with the message provided.
    pub(crate) fn message<S: Display>(message: S) -> Self {
        Self::Message(message.to_string())
    }

    pub(crate) fn data_integrity(error: impl Into<Error>) -> Self {
        Self::DataIntegrity(Box::new(error.into()))
    }

    pub(crate) fn is_file_not_found(&self) -> bool {
        matches!(self, Self::Io(err) if err.kind() == std::io::ErrorKind::NotFound)
    }
}

impl From<&'static str> for ErrorKind {
    fn from(message: &'static str) -> Self {
        Self::message(message)
    }
}

impl From<flume::RecvError> for ErrorKind {
    fn from(_err: flume::RecvError) -> Self {
        Self::Internal(InternalError::InternalCommunication)
    }
}

impl<T> From<flume::SendError<T>> for ErrorKind {
    fn from(_err: flume::SendError<T>) -> Self {
        Self::Internal(InternalError::InternalCommunication)
    }
}

impl From<String> for ErrorKind {
    fn from(message: String) -> Self {
        Self::message(message)
    }
}

/// An internal database error.
#[derive(Debug, Error)]
pub enum InternalError {
    #[error("the b-tree header is too large")]
    HeaderTooLarge,
    #[error("the transaction manager has stopped")]
    TransactionManagerStopped,
    #[error("an error on an internal channel has occurred")]
    InternalCommunication,
    #[error("an unexpected byte length was encountered")]
    IncorrectByteLength,
}