bedrock-agentcore 0.1.0

Amazon Bedrock AgentCore SDK for Rust
Documentation
use std::{
    panic::{AssertUnwindSafe, catch_unwind},
    pin::Pin,
    task::{Context, Poll},
    time::Instant,
};

use axum::{
    body::{Body, Bytes, HttpBody},
    http::StatusCode,
};
use http_body::{Frame, SizeHint};
use tracing::Span;

use super::{handler::panic_text, invocations::Entered, response::StreamFailed};
use crate::{RequestContext, context};

/// The time since `started` in seconds, rounded to milliseconds. An unrounded value
/// is logged as `6.2e-5` for a short call and with up to 17 digits for a long one.
pub(crate) fn seconds_since(started: Instant) -> f64 {
    (started.elapsed().as_secs_f64() * 1e3).round() / 1e3
}

/// The body of an invocation response. It does two things for as long as the server
/// reads it, which for a stream is long after the handler's future has completed:
///
/// - It keeps the invocation's context and tracing span in place during each poll and
///   during the drop of the inner body.
/// - It logs the outcome of the invocation once, when the body ends, fails or is
///   dropped before its end.
pub(crate) struct ScopedBody {
    // `None` only while the body is being dropped.
    inner: Option<Body>,
    // `None` for a rejection that was sent before the context existed.
    ctx: Option<RequestContext>,
    span: Span,
    status: StatusCode,
    started: Instant,
    // Present for a stream. It tells whether the stream ended with its error event.
    stream_failed: Option<StreamFailed>,
    logged: bool,
    // Keeps the invocation in the list that the shutdown logs, until the body is dropped.
    _entered: Option<Entered>,
}

impl ScopedBody {
    /// The body of an invocation response.
    pub(crate) fn wrap(
        inner: Body,
        ctx: Option<RequestContext>,
        span: Span,
        status: StatusCode,
        started: Instant,
        stream_failed: Option<StreamFailed>,
        entered: Entered,
    ) -> Body {
        // From here on the outcome line reports a failure of the stream.
        if let Some(stream_failed) = &stream_failed {
            stream_failed.claim();
        }
        let _entered = Some(entered);
        let mut body = Self { inner: Some(inner), ctx, span, status, started, stream_failed, logged: false, _entered };
        // The server does not poll a body that is already at its end.
        body.log_if_ended();
        Body::new(body)
    }

    /// The body of a response of a customer route. It keeps the context in place
    /// and logs nothing.
    pub(crate) fn wrap_route(inner: Body, ctx: RequestContext) -> Body {
        // `logged` is set from the start: the server reports no outcome for this route.
        let (status, started) = (StatusCode::OK, Instant::now());
        let span = Span::current();
        let ctx = Some(ctx);
        Body::new(Self {
            inner: Some(inner),
            ctx,
            span,
            status,
            started,
            stream_failed: None,
            logged: true,
            _entered: None,
        })
    }

    fn scoped<R>(ctx: &Option<RequestContext>, span: &Span, f: impl FnOnce() -> R) -> R {
        match ctx {
            Some(ctx) => context::sync_scope(ctx.clone(), || span.in_scope(f)),
            None => span.in_scope(f),
        }
    }

    fn log_if_ended(&mut self) {
        if self.inner.as_ref().is_none_or(Body::is_end_stream) {
            self.log(Outcome::Sent);
        }
    }

    fn log(&mut self, outcome: Outcome) {
        if std::mem::replace(&mut self.logged, true) {
            return;
        }
        let (status, seconds) = (self.status.as_u16(), seconds_since(self.started));
        let failure = self.stream_failed.as_ref().and_then(StreamFailed::get);
        self.span.in_scope(|| match Logged::of(self.status, outcome, failure.is_some()) {
            Logged::BodyFailed => tracing::error!(status, seconds, "invocation response body failed"),
            Logged::BodyPanicked => tracing::error!(status, seconds, "invocation response body panicked"),
            Logged::Dropped => tracing::warn!(status, seconds, "invocation response dropped before its end"),
            Logged::StreamFailed => {
                let (error, causes) = failure.map(|failure| (&failure.error, &failure.causes)).unzip();
                let causes = causes.and_then(Option::as_ref);
                tracing::error!(status, seconds, error, causes, "invocation failed: its stream ended with an error")
            }
            Logged::Failed => tracing::error!(status, seconds, "invocation failed"),
            Logged::Rejected => tracing::warn!(status, seconds, "invocation rejected"),
            Logged::Completed => tracing::info!(status, seconds, "invocation completed"),
        });
    }
}

/// The one line that reports how an invocation ended.
#[derive(Debug, PartialEq)]
enum Logged {
    Completed,
    Rejected,
    Failed,
    /// The body was sent to its end, but it was a stream that ended with its error
    /// event. The status is 200, and the invocation still failed.
    StreamFailed,
    BodyFailed,
    BodyPanicked,
    Dropped,
}

impl Logged {
    fn of(status: StatusCode, outcome: Outcome, stream_failed: bool) -> Self {
        match outcome {
            Outcome::Failed => Self::BodyFailed,
            Outcome::Panicked => Self::BodyPanicked,
            Outcome::Dropped => Self::Dropped,
            Outcome::Sent if stream_failed => Self::StreamFailed,
            Outcome::Sent if status.is_server_error() => Self::Failed,
            Outcome::Sent if status.is_client_error() => Self::Rejected,
            Outcome::Sent => Self::Completed,
        }
    }
}

enum Outcome {
    Sent,
    Failed,
    Panicked,
    /// The client disconnected, or the server ended the connection at the shutdown deadline.
    Dropped,
}

impl HttpBody for ScopedBody {
    type Data = Bytes;
    type Error = axum::Error;

    fn poll_frame(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Result<Frame<Bytes>, axum::Error>>> {
        let this = self.get_mut();
        let Some(inner) = this.inner.as_mut() else { return Poll::Ready(None) };
        // A raw body is customer code. Without this boundary its panic is logged as
        // a caller that left.
        let polled =
            Self::scoped(&this.ctx, &this.span, || catch_unwind(AssertUnwindSafe(|| Pin::new(inner).poll_frame(cx))));
        let frame = match polled {
            Ok(frame) => frame,
            Err(panic) => {
                let inner = this.inner.take();
                let _ = Self::scoped(&this.ctx, &this.span, || catch_unwind(AssertUnwindSafe(|| drop(inner))));
                let panic = panic_text(panic.as_ref());
                this.span.in_scope(|| tracing::error!(panic, "the invocation response body panicked"));
                this.log(Outcome::Panicked);
                return Poll::Ready(Some(Err(axum::Error::new("the response body panicked"))));
            }
        };
        match &frame {
            Poll::Pending => {}
            Poll::Ready(None) => this.log(Outcome::Sent),
            Poll::Ready(Some(Err(error))) => {
                this.span.in_scope(|| tracing::error!(%error, "the invocation response body returned an error"));
                this.log(Outcome::Failed)
            }
            Poll::Ready(Some(Ok(_))) => this.log_if_ended(),
        }
        frame
    }

    fn is_end_stream(&self) -> bool {
        self.inner.as_ref().is_none_or(Body::is_end_stream)
    }

    fn size_hint(&self) -> SizeHint {
        self.inner.as_ref().map_or_else(SizeHint::default, Body::size_hint)
    }
}

/// The source of a streaming body can read the context in its destructor, for
/// example to release what it holds for the session.
impl Drop for ScopedBody {
    fn drop(&mut self) {
        self.log(Outcome::Dropped);
        let inner = self.inner.take();
        Self::scoped(&self.ctx, &self.span, || drop(inner));
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn outcome_line_separates_a_failed_stream_from_a_completed_one() {
        let (ok, bad_request, error) = (StatusCode::OK, StatusCode::BAD_REQUEST, StatusCode::INTERNAL_SERVER_ERROR);
        // (status, how the body ended, the stream sent its error event, the line that is logged)
        let cases = [
            (ok, Outcome::Sent, false, Logged::Completed),
            (ok, Outcome::Sent, true, Logged::StreamFailed),
            (bad_request, Outcome::Sent, false, Logged::Rejected),
            (error, Outcome::Sent, false, Logged::Failed),
            (ok, Outcome::Failed, false, Logged::BodyFailed),
            (ok, Outcome::Panicked, false, Logged::BodyPanicked),
            (ok, Outcome::Dropped, false, Logged::Dropped),
            // The client left after the error event and before the end of the body.
            (ok, Outcome::Dropped, true, Logged::Dropped),
        ];
        for (status, outcome, stream_failed, logged) in cases {
            assert_eq!(Logged::of(status, outcome, stream_failed), logged, "{status} stream_failed={stream_failed}");
        }
    }
}