standard-plugin-sdk 0.1.1

Write Standard Code plugins in Rust: wasm components against standard:plugin@2.0.0
Documentation
//! The error every fallible SDK call returns.

use alloc::string::String;
use core::fmt;

use crate::surface::Model;

/// Why a host call or a surface operation did not run.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Error {
    /// The manifest does not carry the grant the call needs. `grant` names
    /// it (`values.read:git.main`, `account.read`, ...): add it to
    /// `standard-plugin.json` with a reason.
    GrantDenied { grant: String },
    /// The per-plugin rate limit for this call kind was reached.
    RateLimited,
    /// The backing service is not reachable right now.
    Unavailable(String),
    /// The host rejected the arguments (an unknown surface id, an oversized
    /// value, a key outside the plugin's namespace).
    Invalid(String),
    /// A payload did not serialize or deserialize.
    Json(String),
    /// The surface has no buffer yet: the viewer has not laid it out.
    NotAttached { surface: String },
    /// The manifest declares the surface in the other model.
    WrongModel {
        surface: String,
        expected: Model,
        found: Model,
    },
}

/// `Result<T, Error>`.
pub type Result<T, E = Error> = core::result::Result<T, E>;

impl Error {
    /// The missing grant, for a [`Error::GrantDenied`].
    pub fn denied_grant(&self) -> Option<&str> {
        match self {
            Self::GrantDenied { grant } => Some(grant),
            _ => None,
        }
    }

    pub(crate) fn json(error: serde_json::Error) -> Self {
        Self::Json(alloc::format!("{error}"))
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::GrantDenied { grant } => write!(f, "grant denied: {grant}"),
            Self::RateLimited => f.write_str("rate limited"),
            Self::Unavailable(reason) => write!(f, "unavailable: {reason}"),
            Self::Invalid(reason) => write!(f, "invalid: {reason}"),
            Self::Json(reason) => write!(f, "json: {reason}"),
            Self::NotAttached { surface } => write!(f, "surface {surface:?} has no buffer yet"),
            Self::WrongModel {
                surface,
                expected,
                found,
            } => write!(
                f,
                "surface {surface:?} is declared as {} but used as {}",
                found.as_str(),
                expected.as_str()
            ),
        }
    }
}

impl core::error::Error for Error {}