epoch_forge/lib_efo/src/error.rs

405 lines
16 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//! 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, Symbols},
};
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<String>,
},
/// 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 prevents the command from executing safely")]
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 optional help message
#[help]
help: Option<String>,
/// The source error
#[source]
src: Option<std::io::Error>,
},
/// 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, so computing `next` would overwrite history.
#[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 already exists, preventing the requested operation.
#[diagnostic(help("Use epoch reset or manually delete the epoch {0}"))]
#[error("Epoch {0} already exists, so the operation was not performed")]
#[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 optional help message
#[help]
help: Option<String>,
/// 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))]
#[diagnostic(help("You may have updated efo to an incompatible version.\n{version}"))]
Serde {
/// The source error
#[source]
source: serde_json::Error,
/// The file that was being written
file_name: String,
/// A version number vs file version number
version: String,
},
/// 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 supplied an acronym that does not match a known statistic.
#[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),
/// The statistic name is recognised but is not stored by this release.
#[error("Statistic `{0}` is not implemented in this release")]
#[diagnostic(code(EpochError::UnsupportedStat))]
#[diagnostic(help(
"Use `efo <entity> add --help` and choose a currently supported statistic."
))]
UnsupportedStat(String),
/// User error with explicit guidance about what happened and what to do.
#[error("A user-facing error occurred")]
#[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]
/// Optional help
help: Option<String>,
},
/// 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 {1:?} 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(EntityIdentifier, Option<EntityType>),
/// 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<EntityIdentifier>),
/// 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<EntityIdentifier>),
/// 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,
},
/// Indicates that the user supplied **mutually‑exclusive** arguments.
///
/// The command line parser accepts a number of optional arguments that belong to
/// *argument groups* – e.g. `--force`, `--dry-run`, `--verbose`, etc.
/// Some of these groups are **incompatible** with each other. If the user
/// specifies an argument from one group together with an argument from a
/// conflicting group, this error is returned.
#[error("Can't use any {category} related argument on {}", e_type.to_symbol())]
#[diagnostic(code(EntityError::IncorrectArgumentCombinaison))]
IncorrectArgumentCombinaison {
/// The argument category that was involved in the conflict
category: &'static str,
/// The entity type for which the conflict was detected.
e_type: EntityType,
/// Optional, user‑friendly guidance on how to fix the issue.
#[help]
advice: Option<String>,
},
}
/// 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!(),
})
}};
}