use essential_types::{ContentAddress, Word};
use thiserror::Error;
pub type Result<T> = std::result::Result<T, Error>;
pub(crate) type InternalResult<T> = std::result::Result<T, InternalError>;
#[derive(Debug, Error)]
pub(crate) enum InternalError {
#[error("a critical error occurred: {0}")]
Critical(#[from] Error),
#[error("a recoverable error occurred: {0}")]
Recoverable(#[from] RecoverableError),
}
pub(crate) type CriticalError = Error;
#[derive(Debug, Error)]
pub enum Error {
#[error("an error occurred when parsing the server url")]
UrlParse,
#[error("an overflow occurred when converting a number")]
Overflow,
#[error("a data sync error occurred: {0}")]
DataSyncFailed(#[from] DataSyncError),
#[error("an error occurred while building the http client: {0}")]
HttpClientBuild(reqwest::Error),
#[error("failed to acquire or use a DB connection: {0}")]
DbPoolRusqlite(#[from] essential_node_db::pool::AcquireThenRusqliteError),
}
#[derive(Debug, Error)]
pub(crate) enum RecoverableError {
#[error("an error occurred in the stream from the server: {0}")]
Stream(#[from] std::io::Error),
#[error("an error occurred in a request to the server: {0}")]
BadServerResponse(reqwest::StatusCode),
#[error("an error occurred in the http client: {0}")]
HttpClient(#[from] reqwest::Error),
#[error("a new block was not sequentially after the last block. Got: {0}, expected: {1}")]
NonSequentialBlock(Word, Word),
#[error("the stream returned an error: {0}")]
StreamError(String),
#[error("a DB error occurred: {0}")]
Rusqlite(rusqlite::Error),
}
#[derive(Debug, Error)]
pub enum DataSyncError {
#[error(
"While syncing blocks a fork was detected at block number {0}. Got: {1}, expected: {}", display_address(.2)
)]
Fork(Word, ContentAddress, Option<ContentAddress>),
}
fn display_address<T>(addr: &Option<T>) -> String
where
T: core::fmt::Display,
{
match addr {
Some(addr) => format!("{}", addr),
None => "None".to_string(),
}
}
impl From<std::io::Error> for InternalError {
fn from(e: std::io::Error) -> Self {
InternalError::Recoverable(RecoverableError::Stream(e))
}
}