//! Error types that arise when interacting with the storage layer. //! //! These are the only errors emitted by the `Storage` abstraction. They are //! lightweight, strongly-typed, and can be converted to the top-level //! `AppError` via `thiserror`. //! //! The public items below are all lightweight error types that can be //! produced by the storage layer or the epoch handling subsystem. #![warn(missing_docs, clippy::missing_docs_in_private_items)] use derive_more::Display; use std::{num::ParseIntError, path::PathBuf}; use uuid::Uuid; use thiserror::Error; use crate::{entity::EntityIdentifier, epoch::EpochId, stats::EntityType}; use miette::Diagnostic; /// Errors that can be returned by the storage layer. /// /// The variants are intentionally small - each one carries all the /// information required to surface a helpful message to the user. // TODO(2): Remove or rethink these errors #[derive(Debug, Error, Diagnostic)] pub enum StorageError { /// Problems with serialisation / deserialisation. #[error("Data error: {0}")] Serialisation(#[from] serde_json::Error), /// Database connection failed for the provided reason. #[error("Database connection failed: {0}")] Connection(String), /// An error occurred while executing a database query. #[error("Query error: {0}")] Query(String), /// The requested record could not be found. #[error("Record not found")] NotFound, } /// All errors that can occur while working with epochs. /// /// The enum is deliberately _small_ - each variant is self-contained and /// carries the information you need to surface a friendly message /// to the user (and to the test-suite). // TODO(2): Split effectively user errors to avoid the usage of advice and such #[derive(Error, Debug, Diagnostic)] pub enum EpochError { /// Problems with the `.epochconfig` file. #[error("Failed to read epoch configuration")] #[diagnostic(code(EpochError::ConfigRead))] ConfigRead(#[source] std::io::Error), /// Failed to write the epoch configuration. #[error("Failed to write epoch configuration")] #[diagnostic(code(EpochError::ConfigWrite))] ConfigWrite(#[source] std::io::Error), /// Failed to create the epoch configuration. #[error("Failed to create the epoch configuration")] #[diagnostic(help("Make sure the path is writable"))] #[diagnostic(code(EpochError::ConfigCreation))] ConfigCreation(String, #[source] std::io::Error), /// This directory is already an epoch folder and thus cannot be initialized. #[error("This directory is already an epoch folder and thus cannot be initialized")] #[diagnostic(code(EpochError::AlreadyInitialized))] AlreadyInitialized { #[help] /// User given advice advice: Option, }, /// This directory isn't empty and thus cannot be initialized. #[error("This directory {name} isn't empty and thus cannot be initialized")] #[diagnostic(code(EpochError::FolderNotEmpty))] #[diagnostic(help("Empty the folder contents first"))] FolderNotEmpty { #[source_code] /// Name of the file causing problem name: String, /// Trick used to have a cute line showing the following error message #[label("This file is present and forbid the command to execute properly")] show_label: Option<(usize, usize)>, }, /// Problems while serialising / deserialising an `EpochInfo`. #[error("Failed to parse `.epochinfo` in epoch {0} ({1}): {2}")] #[diagnostic(code(EpochError::EpochInfoParse))] EpochInfoParse(EpochId, PathBuf, #[source] serde_json::Error), /// Failed to write `.epochinfo` in epoch {id} ({path}). #[error("Failed to write `.epochinfo` in epoch {id} ({path})")] #[diagnostic(code(EpochError::EpochInfoWrite))] EpochInfoWrite { /// The id of the epoch id: EpochId, /// The path of the epoch path: PathBuf, /// An optionnal help message #[help] help: Option, /// The source error #[source] src: Option, }, /// The user supplied an epoch id or tag that does not exist. #[error("No epoch found for id/tag `{0}`")] #[diagnostic(code(EpochError::EpochNotFound))] EpochNotFound(String), /// The user attempted to resolve an epoch that is ambiguous. #[error("Tag `{0}` resolves to either multiple epochs or invalid epoch")] #[diagnostic(code(EpochError::AmbiguousTag))] AmbiguousTag(String), /// The epoch folder for the target id is missing. #[error("Missing directory for epoch {0} at `{1}`")] #[diagnostic(code(EpochError::EpochFolderMissing))] #[diagnostic(help( "Ensure that the epoch was initialized and {0} refers to an existing epoch" ))] EpochFolderMissing(EpochId, PathBuf), /// A future epoch exists, forbidding you to compute `next` and overriding them. #[diagnostic(help("Use epoch reset if you want to erase all future epochs first"))] #[error("Cannot compute `next` because future epoch exists")] #[diagnostic(code(EpochError::FutureEpochExist))] FutureEpochExist, /// A specific epoch exists, forbidding the further execution of the command. #[diagnostic(help("Use epoch reset or manually delete the epoch {0}"))] #[error("The epoch {0} exists forbidding the execution of the command")] #[diagnostic(code(EpochError::EpochAlreadyExists))] EpochAlreadyExists(EpochId), /// Attempt to switch to an epoch that has already been advanced past. #[error("Cannot switch to epoch `{0}` - the world has already advanced beyond it")] #[diagnostic(code(EpochError::SwitchPastEpoch))] SwitchPastEpoch(EpochId), /// The supplied epoch id is out of bounds (negative, zero or too large). #[error("Invalid epoch id `{0}` - must be a positive, non-overflowing integer")] #[diagnostic(code(EpochError::InvalidEpochId))] InvalidEpochId(EpochId), /// A tag that the user tried to assign already exists. #[error("Tag `{1}` already exists for epoch {0}")] #[diagnostic(code(EpochError::InvalidEpochId))] TagAlreadyExists(EpochId, String), /// The parent epoch referenced in an `EpochInfo` cannot be found. #[error("Parent epoch {} referenced by epoch {} does not exist", .0, .1)] #[diagnostic(code(EpochError::ParentEpochMissing))] ParentEpochMissing(EpochId, EpochId), /// Generic I/O errors that bubble up from other sub-tasks. #[error("I/O error")] #[diagnostic(code(EpochError::GenericIO))] Io { /// The source error #[source] source: std::io::Error, /// An optionnal help message #[help] help: Option, /// Where the error originated from error_line: u32, }, /// Serialization / deserialization errors that are not caught above. #[error("Serialization error from {file_name}")] #[diagnostic(code(EpochError::SerdeError))] Serde { /// The source error #[source] source: serde_json::Error, /// The file that was being written file_name: String, /// An optionnal help message #[help] help: Option, }, /// The epoch tree is in an incorrect state. #[error("Invalid epoch tree at {0}")] #[diagnostic(code(EpochError::TreeInvalid))] TreeInvalid(EpochId, String), /// The main folder is not an epoch folder. #[error("The given directory ({0:?}) is not an epoch folder")] #[diagnostic(code(EpochError::MainFolderInvalid))] MainFolderInvalid(String), /// Couldn't parse an `EpochId`. #[error("The id ({0}) couldn't be converted to a valid EpochId")] #[diagnostic(code(EpochError::ParsingEpochId))] ParsingEpochId(#[from] ParseIntError), /// Impossible to load the given epoch #[error("The id ({0}) couldn't be loaded")] #[diagnostic(code(EpochError::LoadingEpochId))] LoadingEpochId(EpochId), /// Any other error that didn't fit into the above categories. #[error("An unknown error occurred: {0}")] #[diagnostic(code(EpochError::Unknown))] Unknown(String), /// The user tried to parse an acronim that doen't match any stats known to the system. #[error("Unknown stat acronym: {0}")] #[diagnostic(code(EpochError::UnknownStatAcronim))] UnknownStatAcronim(String), /// The user gave a stat:identifier pair that was incorrect #[error("Expected a stat and a number (e.g. fod:12 or mil=22), got: {0}")] #[diagnostic(code(EpochError::IllFormedStatQualifier))] IllFormedStatQualifier(String), /// User error, meant to be very explicit over what happened and what to do. #[error("An user facing error")] #[diagnostic(code(EpochError::UserError))] UserError(#[help] UserErrors), /// An error happened when picking a rng event #[error("An error happened when trying to pick a rng event for {cause}")] #[diagnostic(code(EpochError::RNGPickError))] RNGPickError { /// The root cause originating the error cause: String, #[help] /// Optionnal help help: Option, }, /// A non-recoverable error while hashing an epoch identifier. /// /// This error should never happen in normal operation. It is surfaced only /// when the hashing routine fails to produce a unique identifier for a /// given epoch index. #[error("Epoch hashing failed for `{0}` (index {1})")] #[diagnostic(code(EpochError::EpochHashingImpossible))] #[diagnostic(help("This is an internal error. Please file a bug report."))] EpochHashingImpossible(&'static str, u32), /// The entity with id **`{0}`** could not be found. #[error("Entity of type with id {0:?} not found")] #[diagnostic(code(epoch::entity_not_found_by_id))] #[diagnostic(help( "Verify that the identifier is correct and that the entity exists in the current epoch." ))] EntityNotFoundById(Uuid), /// The entity could not be found #[error("Entity of type {0:?} with name {1:?} not found")] #[diagnostic(code(epoch::entity_not_found))] #[diagnostic(help( "Verify that the identifier is correct and that the entity exists in the current epoch." ))] EntityNotFound(EntityType, Option), /// The requested uniform RNG could not be created because the supplied /// distribution parameters were invalid. #[error("Failed to create uniform RNG: {0}")] #[diagnostic(code(EpochError::UniformRngCreation))] #[diagnostic(help("Ensure that the supplied range bounds satisfy `min < max`."))] UniformRngCreation(#[from] rand::distr::uniform::Error), /// The string did not contain exactly two comma-separated values. #[error("Invalid position format: expected \"x,y\" found {0}")] #[diagnostic(code(EpochError::InvalidPositionFormat))] #[diagnostic(help("Provide exactly two numbers separated by a comma."))] InvalidPositionFormat(String), /// One of the components failed to parse as an `isize`. #[error("Failed to parse integer: {0}")] #[diagnostic(code(EpochError::ParsePositionError))] #[diagnostic(help("Ensure that the input is a valid integer."))] ParsePositionError(String), /// Failed to render a table into its string representation. #[error("Failed to render table {name} [{id}] as string")] #[diagnostic(code(EpochError::TableStringConversion))] #[diagnostic(help( "Verify that the table data and schema are compatible with string rendering." ))] TableStringConversionError { /// The logical name of the table that failed to convert. name: String, /// The UUID that uniquely identifies the table instance. id: Uuid, }, /// Failed to parse a duration string. #[error("Failed to parse duration: {0}:{1}")] #[diagnostic(code(EpochError::ParsingDuration))] #[diagnostic(help( "Verify that the duration string follows the expected syntax, `permanent` or `duration:X` or `done`." ))] ParsingDuration(&'static str, String), /// Failed to parse a bounds string. #[error("Failed to parse bounds: {0}:{1}")] #[diagnostic(code(EpochError::ParsingBounds))] #[diagnostic(help( "Verify that the bounds string follows the expected syntax, `X-X` or `X:X`." ))] ParsingBounds(&'static str, String), /// The value started with `@` but the remainder was not a valid id or the name was empty. #[error("Failed to parse identifier or name")] #[diagnostic(code(EntityIdentifierError::InvalidIdentifier))] #[diagnostic(help("Verify that the UUID after `@` is a valid id."))] EmptyIdentifier, /// The entity already exists. #[error("Failed to create entity: {0:?} already exists")] #[diagnostic(code(EntityError::EntityAlreadyExist))] #[diagnostic(help( "Ensure that the entity name or ID is unique before creating a new one. \ You may need to delete or rename the existing entity." ))] EntityAlreadyExist(Option), /// The argument could not be parsed. #[error("Failed to parse argument '{argument_parsed}': {while_parsing}")] #[diagnostic(code(EntityError::ParsingArgument))] #[diagnostic(help( "Verify that the value supplied for the argument '{argument_parsed}' matches the expected format. \ Refer to the command reference for the correct syntax and examples." ))] ParsingArgument { /// The argument that was being parsed argument_parsed: String, /// The thing that was being parsed while_parsing: &'static str, }, } /// A small enum of explicit user-facing error messages. /// /// The variants are deliberately simple; each one is rendered with a /// clear message via `derive_more::Display`. #[derive(Debug, Display, Diagnostic, Error)] pub enum UserErrors { /// The classic mistake #[display("The user did a very bad thing")] #[diagnostic(code(UserErrors::DSItF))] DSItF, } // macro_rules! err_with { // ($expr:expr, $err_ty:ty {$($field:ident : $value:expr),* $(,)?}) => {{ // $expr.map_err(|e| { $err_ty { $($field: $value),* } }) // }}; // } /// Helper macro to convert a `std::io::Error` into an `EpochError::Io` /// with an attached help message. /// /// The macro captures the current line number for debugging purposes. #[macro_export] macro_rules! io_err_with_help { ($expr:expr, $($help:expr),*) => {{ $expr.map_err(|e| EpochError::Io { source: e, help: Some(format!($($help),*)), error_line: line!(), }) }}; }