//! 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`. use std::{num::ParseIntError, path::PathBuf}; use thiserror::Error; use crate::epoch_struct::EpochId; use miette::Diagnostic; /// Errors that can be returned by the storage layer. #[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). #[derive(Error, Debug, Diagnostic)] pub enum EpochError { /// Problems with the `.epochconfig` file #[error("Failed to read epoch configuration")] ConfigRead(#[source] std::io::Error), #[error("Failed to write epoch configuration")] ConfigWrite(#[source] std::io::Error), #[error("Failed to create the epoch configuration")] #[help("Make sure the path is writable")] ConfigCreation(String, #[source] std::io::Error), #[error("This directory is already an epoch folder and thus cannot be initialized")] #[diagnostic(code(EpochError::AlreadyInitialized))] AlreadyInitialized { #[help] advice: Option, }, #[error("This directory isn't empty and thus cannot be initialized")] #[diagnostic(code(EpochError::FolderNotEmpty))] #[diagnostic(help("Empty the folder or remove its content first"))] // #[diagnostic(label((1,1)))] FolderNotEmpty { #[source_code] name: Option, #[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}")] EpochInfoParse(EpochId, PathBuf, #[source] serde_json::Error), #[error("Failed to write `.epochinfo` in epoch {id} ({path})")] #[diagnostic(code(EpochError::EpochInfoWrite))] EpochInfoWrite { id: EpochId, path: PathBuf, #[help] help: Option, #[source] src: Option, }, /// The user supplied an epoch id or tag that does not exist #[error("No epoch found for id/tag `{}`", .0)] EpochNotFound(String), /// The user attempted to resolve an epoch that is *ambiguous* – e.g. two /// tags with the same name or a tag that points to a non‑existent id #[error("Tag `{}` resolves to either multiple epochs or invalid epoch", .0)] AmbiguousTag(String), /// The epoch folder for the target id is missing #[error("Missing directory for epoch {} at `{}`", .0, .1.display())] EpochFolderMissing(EpochId, PathBuf), /// There are *future* events left in the current epoch, so you cannot compute `next` #[error("Cannot compute `next` because there are pending future events")] FutureEventsExist, /// Attempt to switch to an epoch that has already been *advanced* past /// the current world state (e.g. you are at epoch 5 but try to switch /// to epoch 7 while epoch 6 is still in the past) #[error("Cannot switch to epoch `{}` – the world has already advanced beyond it", .0)] SwitchPastEpoch(EpochId), /// The supplied epoch id is out of bounds (negative, zero or too large) #[error("Invalid epoch id `{}` – must be a positive, non‑overflowing integer", .0)] InvalidEpochId(EpochId), /// A tag that the user tried to assign already exists #[error("Tag `{}` already exists for epoch {}", .1, .0)] TagAlreadyExists(EpochId, String), // /// An attempt to delete or reset events failed because the world // /// was in an inconsistent state (e.g. `reset` called before any `switch`) // #[error("Reset failed: no epoch has been switched to yet")] // ResetBeforeSwitch, /// The parent epoch referenced in an `EpochInfo` cannot be found #[error("Parent epoch {} referenced by epoch {} does not exist", .0, .1)] ParentEpochMissing(EpochId, EpochId), /// Generic I/O errors that bubble up from other sub‑tasks #[error("I/O error")] #[diagnostic(code(EpochError::GenericIO))] Io { #[source] source: std::io::Error, #[help] help: Option, }, /// Serialization / deserialization errors that are not caught above #[error("Serialization error from {file_name}")] #[diagnostic(code(EpochError::SerdeError))] Serde { #[source] source: serde_json::Error, file_name: String, #[help] help: Option, }, /// The epoch tree is in an incorrect state #[error("Invalid epoch tree at {0}")] TreeInvalid(EpochId, String), /// The main folder is not an epoch folder #[error("The given directory ({0:?}) is not an epoch folder")] MainFolderInvalid(String), /// Couldn't parse an EpochId #[error("The id ({0}) couldn't be converted to a valid EpochId")] #[diagnostic(code(EpochError::ConversionIdImpossible))] ParsingEpochId(#[from] ParseIntError), /// Any other error that didn't fit into the above categories #[error("An unknown error occurred: {0}")] Unknown(String), } // macro_rules! err_with { // ($expr:expr, $err_ty:ty {$($field:ident : $value:expr),* $(,)?}) => {{ // $expr.map_err(|e| { $err_ty { $($field: $value),* } }) // }}; // } #[macro_export] macro_rules! io_err_with_help { // $expr: the expression that produces the Result // $help: string literal with the help message ($expr:expr, $help:expr) => {{ $expr.map_err(|e| EpochError::Io { source: e, help: Some($help.to_owned()), }) }}; }