bedrock-agentcore 0.1.0

Amazon Bedrock AgentCore SDK for Rust
Documentation
use std::fmt;

type BoxError = Box<dyn std::error::Error + Send + Sync>;

/// The reason an SDK operation failed. Read it with [`Error::kind`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ErrorKind {
    /// The server could not bind its listen address, for example because the port is in use.
    Bind,
    /// The server could not install its shutdown signal handlers, or it stopped
    /// because of an I/O error.
    Serve,
    /// The builder configuration is incomplete or invalid.
    InvalidConfig,
    /// The server received its shutdown signal, and requests or tracked background
    /// tasks were still running when the grace period ended. The server has cancelled
    /// its requests by then. Tracked background tasks may still be running.
    ShutdownTimeout,
    /// An Identity operation had no workload access token: none was given to the
    /// operation, and the request context held none or the call ran outside one.
    MissingWorkloadToken,
    /// AgentCore Identity answered successfully and returned no API key.
    NoApiKey,
    /// AgentCore Identity answered a request for an OAuth2 token with neither a token
    /// nor an authorization URL.
    NoTokenOrAuthUrl,
    /// The application's function for the authorization URL returned an error, which
    /// is the [`source`](std::error::Error::source).
    AuthorizationCallbackFailed,
    /// No OAuth2 token arrived in the time allowed for the user to give consent.
    AuthorizationTimedOut,
    /// A call to AgentCore Identity failed. The text of the error names the operation,
    /// the error code of the service and the request ID, for example
    /// `GetResourceApiKey failed: AccessDeniedException (request ID: ...)`. A failure
    /// without a response has the classification of the AWS SDK instead, such as
    /// `dispatch failure`. [`source`](std::error::Error::source) is the `SdkError` of
    /// the generated operation.
    Service,
}

impl ErrorKind {
    /// Whether errors of this kind come from the `identity` module. Their source can
    /// hold a credential.
    fn is_identity(self) -> bool {
        matches!(
            self,
            Self::MissingWorkloadToken
                | Self::NoApiKey
                | Self::NoTokenOrAuthUrl
                | Self::AuthorizationCallbackFailed
                | Self::AuthorizationTimedOut
                | Self::Service
        )
    }
}

/// Error returned by this crate.
///
/// Its `Display` text describes this error only. The underlying cause, when there is
/// one, is available from [`source`](std::error::Error::source) and is not repeated
/// in the text.
/// The text of [`ErrorKind::Service`] also has the error code and the request ID of
/// the failed call, which a log needs to tell failures apart.
///
/// # Secrets in the source
///
/// The source of an Identity error can hold a credential. For example, the
/// `SdkError` of a response that could not be decoded keeps the response body, which
/// can contain the API key, and the error of an application's function for the
/// authorization URL can contain that URL. The `Debug` output of an Identity error therefore leaves
/// the source out. The source itself is unchanged: formatting it, or a report that
/// walks the source chain, can print what it holds.
pub struct Error {
    kind: ErrorKind,
    message: String,
    source: Option<BoxError>,
}

impl Error {
    pub(crate) fn new(kind: ErrorKind, message: impl Into<String>) -> Self {
        Self { kind, message: message.into(), source: None }
    }

    #[cfg(any(feature = "runtime", feature = "identity"))]
    pub(crate) fn with_source(mut self, source: impl Into<BoxError>) -> Self {
        self.source = Some(source.into());
        self
    }

    /// The category of this error.
    pub fn kind(&self) -> ErrorKind {
        self.kind
    }

    /// Whether the source must stay out of the log: the source of an Identity error
    /// can hold a credential or the authorization URL.
    #[cfg(feature = "runtime")]
    pub(crate) fn hides_source(&self) -> bool {
        self.kind.is_identity()
    }
}

impl fmt::Debug for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut debug = f.debug_struct("Error");
        debug.field("kind", &self.kind).field("message", &self.message);
        if self.kind.is_identity() {
            debug.finish_non_exhaustive()
        } else {
            debug.field("source", &self.source).finish()
        }
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.message)
    }
}

impl std::error::Error for Error {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        self.source.as_deref().map(|source| source as _)
    }
}

#[cfg(all(test, feature = "runtime"))]
mod tests {
    use std::error::Error as _;

    use super::*;

    /// A reporter that prints an error and then its sources must not print the cause twice.
    #[test]
    fn display_text_does_not_repeat_the_source() {
        let cause = std::io::Error::other("address in use");
        let error = Error::new(ErrorKind::Bind, "failed to bind 127.0.0.1:8080").with_source(cause);
        assert_eq!(error.to_string(), "failed to bind 127.0.0.1:8080");
        assert_eq!(error.source().map(ToString::to_string).as_deref(), Some("address in use"));
    }

    #[test]
    fn debug_output_of_a_runtime_error_includes_its_source() {
        let cause = std::io::Error::other("address in use");
        let error = Error::new(ErrorKind::Bind, "failed to bind").with_source(cause);
        let debug = format!("{error:?}");
        assert!(debug.starts_with("Error { kind: Bind, message: \"failed to bind\", source: Some("), "{debug}");
        assert!(debug.contains("address in use"), "{debug}");
    }
}