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
ErrorKind | Meaning | Usual response |
|---|---|---|
InvalidInput | Storage/runtime options or a request key/value is invalid. | Fix the input; retrying it unchanged cannot succeed. |
Unsupported | The 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. |
Busy | open could not acquire exclusive ownership of the cache files. | Coordinate ownership or retry later with a bound. |
Overloaded | A bounded request-path slot, queue, buffer, or deadline is exhausted. | Fall through to the authoritative path or retry with a bound. |
ResourceExhausted | Startup or lifecycle work could not satisfy a required allocation/resource requirement. | Reduce the configured footprint or provide more resources. |
Unavailable | The runtime, worker, or required service has stopped or was interrupted. | Stop using this cache instance and reopen or replace it. |
CorruptData | Cache data or internal structure failed validation. | Treat the cache as disposable; inspect logs/device health and reopen it. |
Io | A filesystem or device operation failed. | Inspect io_kind(), raw_os_error(), and the source chain. |
Internal | A 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
impl Error
Sourcepub const fn operation(&self) -> ErrorOperation
pub const fn operation(&self) -> ErrorOperation
Returns the public operation that failed.
Sourcepub fn io_kind(&self) -> ErrorKind
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.
Sourcepub fn raw_os_error(&self) -> Option<i32>
pub fn raw_os_error(&self) -> Option<i32>
Returns the raw OS error code carried by the underlying I/O failure.
Sourcepub const fn as_io_error(&self) -> &Error
pub const fn as_io_error(&self) -> &Error
Borrows the underlying standard-library I/O error.
Sourcepub fn into_io_error(self) -> Error
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.
Sourcepub fn into_io_error_with_context(self) -> Error
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 Error for Error
impl Error for Error
Source§fn source(&self) -> Option<&(dyn Error + 'static)>
fn source(&self) -> Option<&(dyn Error + 'static)>
1.0.0 · Source§fn description(&self) -> &str
fn description(&self) -> &str
use the Display impl or to_string()