Skip to main content

Error

Struct Error 

Source
pub struct Error { /* private fields */ }
Expand description

Structured failure returned by a public C² operation.

The classification and operation are stable programmatic fields. The wrapped io::Error retains the detailed cause, its raw OS error when one exists, and the complete Error::source chain.

§Error handling

C² separates normal cache outcomes from failures. A miss, stale hit, L1 bypass, eviction, rejected recovery image, or transition to read miss-only mode is not an error. Public operations return Result<T, Error>, where Error is the C² error type.

An error has three independent pieces of information:

  • Error::kind() is the stable, actionable C² classification.
  • Error::operation() identifies the public operation that failed.
  • Error::as_io_error() retains the detailed cause, standard I/O kind, raw OS code, and source chain.

Display text is intended for people and logs. Do not parse it or use it as a metric label; use ErrorKind::as_str() and ErrorOperation::as_str() instead. Both enums are non-exhaustive, so external matches must include a wildcard.

§Handling request pressure

Overloaded is an expected result of bounded admission. A lookaside-cache caller should normally continue through its authoritative data path or perform a bounded retry rather than fail the application request.

use cache2::{Cache, Error, ErrorKind};

fn cache_value(cache: &Cache, key: &[u8], value: &[u8]) -> Result<(), Error> {
    match cache.put(key, value) {
        Ok(_) => Ok(()),
        Err(error) if error.kind() == ErrorKind::Overloaded => {
            // Cache admission is saturated. The authoritative write can still
            // proceed, so skipping this cache fill is safe.
            Ok(())
        }
        Err(error) => Err(error),
    }
}

Do not retry without a bound. C² deliberately exposes pressure instead of building unbounded queues. With the default immediate-read policy, read-pool or buffer pressure is Ok(None). When read waiting is enabled, queue saturation, buffer pressure, and deadline expiry are ErrorKind::Overloaded.

With FillControlOptions::Adaptive, new fills also return ErrorKind::Overloaded during controller pauses or paced-flush back-pressure; inspect CacheSnapshot::fill_control to distinguish controller pauses from staging pressure. Pre-timeout pauses leave CacheHealth::Running unchanged and do not affect reads or deletes.

§Classifications

ErrorKindMeaningUsual response
InvalidInputStorage/runtime options or a request key/value is invalid.Fix the input; retrying it unchanged cannot succeed.
UnsupportedThe selected I/O engine, mode, or platform capability is unavailable.Select a supported configuration or build target; inspect the I/O source for the missing requirement.
Busyopen could not acquire exclusive ownership of the cache files.Coordinate ownership or retry later with a bound.
OverloadedA bounded request-path slot, queue, buffer, or deadline is exhausted.Fall through to the authoritative path or retry with a bound.
ResourceExhaustedStartup or lifecycle work could not satisfy a required allocation/resource requirement.Reduce the configured footprint or provide more resources.
UnavailableThe runtime, worker, or required service has stopped or was interrupted.Stop using this cache instance and reopen or replace it.
CorruptDataCache data or internal structure failed validation.Treat the cache as disposable; inspect logs/device health and reopen it.
IoA filesystem or device operation failed.Inspect io_kind(), raw_os_error(), and the source chain.
InternalA worker, synchronization primitive, or internal invariant failed without an OS error.Record diagnostics and replace the cache instance.

The classification is contextual. For example, WouldBlock during open is Busy, while WouldBlock during put is Overloaded. A managed read-buffer allocation failure during get is also Overloaded; the same low-level kind during startup is ResourceExhausted. A get wait-deadline expiry is Overloaded, while a device completion timeout reported by drain or close is Io.

§Operation context

ErrorOperation mirrors the fallible public API: storage and complete configuration construction, open, each request operation, snapshots, draining, and both close modes. Disk and memory queries on validated configurations are infallible. Operation context makes telemetry and policy precise without relying on the source message.

use cache2::{Error, ErrorKind, ErrorOperation};

fn record(error: &Error) {
    let kind = error.kind();
    let operation = error.operation();
    eprintln!(
        "cache operation={} outcome={} io_kind={:?} os_error={:?}",
        operation.as_str(),
        kind.as_str(),
        error.io_kind(),
        error.raw_os_error(),
    );

    match (operation, kind) {
        (ErrorOperation::Open, ErrorKind::Busy) => {
            // Another process or cache instance owns the files.
        }
        (_, ErrorKind::Overloaded) => {
            // Apply the caller's bounded overload policy.
        }
        _ => {}
    }
}

Keys and values are intentionally absent from errors and their display text so that diagnostics do not leak cache contents.

§Standard I/O interoperability

Existing functions that return std::io::Result can continue to use ? on a C² result. From<cache2::Error> for std::io::Error returns the original I/O error, preserving its raw OS code and source chain. The conversion discards the C² operation and classification:

use cache2::Cache;

async fn flush_cache(cache: Cache) -> std::io::Result<()> {
    cache.close_warm().await?;
    Ok(())
}

Error::into_io_error() performs the same lossless conversion explicitly. Use Error::into_io_error_with_context() when retaining the C² operation and classification in the source chain is more important. That contextual wrapper keeps the original I/O kind, but its outer raw_os_error() is None; the wrapped cache2::Error still exposes the original code.

§Configuration and open failures

StorageOptions::build reports BuildStorage; CacheConfig::new reports BuildConfig. Correct invalid options or an insufficient managed-memory limit before trying again. Successful results retain the checked layout and resource requirements, so inspecting their disk and memory bounds cannot fail.

Cache::open and Cache::open_with_handle report Open. A valid configuration can still encounter a busy file, unavailable device support, an allocation failure, or an unavailable runtime. Handle these according to ErrorKind just like other lifecycle failures.

§Transient background timeouts

A background write or reclaim timeout enters CacheHealth::Recovering instead of failing the cache immediately: new fills return ErrorKind::Overloaded while reads and deletes continue, and fills resume after the timed-out background operations finish. RuntimeOptions::io_recovery_timeout defaults to None (wait until completion or close); set Some(duration) to limit the additional recovery wait, or Some(Duration::ZERO) to cancel immediately. Finite-budget exhaustion, actual I/O errors, and invalid completions remain terminal failures.

Implementations§

Source§

impl Error

Source

pub const fn kind(&self) -> ErrorKind

Returns the actionable C² error classification.

Source

pub const fn operation(&self) -> ErrorOperation

Returns the public operation that failed.

Source

pub fn io_kind(&self) -> ErrorKind

Returns the underlying standard-library I/O error kind.

Prefer Self::kind for application policy; reserve this method for detailed diagnostics.

Source

pub fn raw_os_error(&self) -> Option<i32>

Returns the raw OS error code carried by the underlying I/O failure.

Source

pub const fn as_io_error(&self) -> &Error

Borrows the underlying standard-library I/O error.

Source

pub fn into_io_error(self) -> Error

Removes the structured C² context and returns the underlying I/O error.

This preserves the original raw OS error code and source chain. The From<Error> conversion uses the same lossless path.

Source

pub fn into_io_error_with_context(self) -> Error

Wraps this error in a standard-library I/O error.

This keeps the C² operation and classification in the source chain, but the returned outer error does not expose the underlying raw OS error directly. Use Self::into_io_error when preserving that code is more important than retaining the structured context.

Trait Implementations§

Source§

impl Debug for Error

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for Error

Source§

fn fmt(&self, formatter: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Error for Error

Source§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
1.0.0 · Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0:

use the Display impl or to_string()

1.0.0 · Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0:

replaced by Error::source, which can support downcasting

Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
Source§

impl From<Error> for Error

Source§

fn from(error: Error) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

§

impl !RefUnwindSafe for Error

§

impl !UnwindSafe for Error

§

impl Forget for Error

§

impl Freeze for Error

§

impl Move for Error

§

impl Send for Error

§

impl Sync for Error

§

impl Unpin for Error

§

impl UnsafeUnpin for Error

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.