capsid-database 0.1.0-alpha.1

The schema version check, record encoding, errors, targets, and transaction helpers that Capsid's SQLite databases share.
Documentation
mod epoch;
pub mod records;
pub mod schema;
pub mod sql;
pub mod target;

use std::{borrow::Cow, error::Error as StdError, fmt, io};

use capsid_model::{Category, api::NOT_LEADER};

pub use epoch::AuthorityEpoch;

pub type Result<T, E = StoreError> = std::result::Result<T, E>;

#[derive(Debug, thiserror::Error)]
pub enum StoreError {
    #[error("{resource} not found: {name}")]
    NotFound { resource: Resource, name: String },

    #[error("state filesystem")]
    Io(#[from] io::Error),

    #[error("controller recovery authority: {0}")]
    Authority(Cow<'static, str>),

    #[error("invalid controller authority epoch")]
    Epoch(#[source] uuid::Error),

    #[error("state database")]
    Sqlite(#[from] rusqlite::Error),

    #[error("controller consensus")]
    Raft(#[from] capsid_raft::Error),

    #[error("state record")]
    Json(#[from] serde_json::Error),

    #[error("{0}")]
    Busy(Cow<'static, str>),

    #[error("{0}")]
    QuotaExceeded(Cow<'static, str>),

    #[error("{0}")]
    Conflict(Cow<'static, str>),

    #[error("{0}")]
    Denied(Cow<'static, str>),

    #[error("{0}")]
    Invalid(Cow<'static, str>),

    #[error(transparent)]
    Model(#[from] capsid_model::Error),

    #[error(transparent)]
    Host(capsid_host::Error),

    #[error("corrupt state record: {0}")]
    Corrupt(Cow<'static, str>),

    #[error("{NOT_LEADER}")]
    NotLeader,

    #[error(transparent)]
    Egress(capsid_egress::Error),
}

impl From<capsid_egress::Error> for StoreError {
    fn from(error: capsid_egress::Error) -> Self {
        match error {
            capsid_egress::Error::Io(error) => Self::Io(error),
            capsid_egress::Error::Model(error) => Self::Model(error),
            capsid_egress::Error::Host(error) => error.into(),
            error => Self::Egress(error),
        }
    }
}

impl From<capsid_host::Error> for StoreError {
    fn from(error: capsid_host::Error) -> Self {
        match error {
            capsid_host::Error::Io(error) => Self::Io(error),
            capsid_host::Error::Model(error) => Self::Model(error),
            error => Self::Host(error),
        }
    }
}

impl From<capsid_protocol::Error> for StoreError {
    fn from(error: capsid_protocol::Error) -> Self {
        Self::Model(error.into())
    }
}

impl StoreError {
    pub fn into_io(self) -> io::Error {
        match self {
            Self::Io(error) => error,
            error => io::Error::new(error.category().io_kind(), error),
        }
    }

    pub fn not_found(resource: Resource, name: impl Into<String>) -> Self {
        Self::NotFound {
            resource,
            name: name.into(),
        }
    }

    pub fn invalid(message: impl Into<Cow<'static, str>>) -> Self {
        Self::Invalid(message.into())
    }

    pub fn conflict(message: impl Into<Cow<'static, str>>) -> Self {
        Self::Conflict(message.into())
    }

    pub fn busy(message: impl Into<Cow<'static, str>>) -> Self {
        Self::Busy(message.into())
    }

    pub fn quota_exceeded(message: impl Into<Cow<'static, str>>) -> Self {
        Self::QuotaExceeded(message.into())
    }

    pub fn denied(message: impl Into<Cow<'static, str>>) -> Self {
        Self::Denied(message.into())
    }

    pub fn corrupt(message: impl Into<Cow<'static, str>>) -> Self {
        Self::Corrupt(message.into())
    }

    pub fn authority(message: impl Into<Cow<'static, str>>) -> Self {
        Self::Authority(message.into())
    }

    pub fn is_infrastructure(&self) -> bool {
        matches!(
            self,
            Self::Io(_) | Self::Sqlite(_) | Self::Json(_) | Self::Authority(_)
        )
    }

    pub fn category(&self) -> Category {
        match self {
            Self::NotFound { .. } => Category::NotFound,
            Self::Busy(_) | Self::NotLeader => Category::Busy,
            Self::QuotaExceeded(_) => Category::QuotaExceeded,
            Self::Conflict(_) => Category::Conflict,
            Self::Denied(_) => Category::PermissionDenied,
            Self::Io(error) => io_category(error),
            Self::Sqlite(error)
                if error.sqlite_error_code() == Some(rusqlite::ErrorCode::DiskFull) =>
            {
                Category::StorageFull
            }
            Self::Raft(
                capsid_raft::Error::NotLeader { .. }
                | capsid_raft::Error::NoLeader
                | capsid_raft::Error::NoQuorum
                | capsid_raft::Error::Io(_),
            ) => Category::Busy,
            Self::Invalid(_) => Category::InvalidInput,
            Self::Model(error) => error.category(),
            Self::Host(error) => error.category(),
            Self::Egress(error) => error.category(),
            Self::Authority(_)
            | Self::Epoch(_)
            | Self::Corrupt(_)
            | Self::Sqlite(_)
            | Self::Raft(_)
            | Self::Json(_) => Category::Internal,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Resource {
    Instance,

    Attempt,

    Template,

    Bundle,

    Volume,

    Backup,

    Checkpoint,

    Relocation,

    Workspace,

    Run,

    Workload,

    Ledger,

    Operation,

    Revision,

    JobRun,

    JobGroup,

    Pool,

    PrivateNetwork,

    EgressGrant,

    ManagementIntent,

    Project,

    Token,
}

impl fmt::Display for Resource {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::Instance => "instance",
            Self::Attempt => "attempt",
            Self::Template => "template",
            Self::Bundle => "bundle",
            Self::Volume => "volume",
            Self::Backup => "volume backup",
            Self::Checkpoint => "checkpoint",
            Self::Relocation => "relocation",
            Self::Workspace => "workspace",
            Self::Run => "run request",
            Self::Workload => "workload",
            Self::Ledger => "ledger",
            Self::Operation => "operation",
            Self::Revision => "workload revision",
            Self::JobRun => "job run",
            Self::JobGroup => "job group",
            Self::Pool => "pool or claim",
            Self::PrivateNetwork => "private network",
            Self::EgressGrant => "network grant",
            Self::ManagementIntent => "management intent",
            Self::Project => "project",
            Self::Token => "token",
        })
    }
}

const MAX_CHAIN_DEPTH: usize = 16;

// The category an I/O error carries when it wraps a typed error from below.
fn io_category(error: &io::Error) -> Category {
    let wrapped = error
        .get_ref()
        .map(|inner| inner as &(dyn StdError + 'static));
    std::iter::successors(wrapped, |&inner| inner.source())
        .take(MAX_CHAIN_DEPTH)
        .find_map(|inner| {
            if let Some(store) = inner.downcast_ref::<StoreError>() {
                return Some(store.category());
            }

            if let Some(model) = inner.downcast_ref::<capsid_model::Error>() {
                return Some(model.category());
            }

            match inner.downcast_ref::<capsid_host::Error>()? {
                capsid_host::Error::Io(_) => None,
                host => Some(host.category()),
            }
        })
        .unwrap_or_else(|| Category::from_io_kind(error.kind()))
}