Skip to main content

bedrock_agentcore/runtime/
response.rs

1use std::{
2    convert::Infallible,
3    fmt,
4    panic::{AssertUnwindSafe, catch_unwind},
5    pin::Pin,
6    sync::{
7        Arc, OnceLock,
8        atomic::{AtomicBool, Ordering},
9    },
10    task::{Context, Poll},
11    time::Duration,
12};
13
14use axum::{
15    body::Body,
16    http::{self, StatusCode, header},
17    response::{
18        IntoResponse,
19        sse::{Event, KeepAlive, Sse},
20    },
21};
22use futures_core::Stream;
23use serde::Serialize;
24
25use super::{
26    handler::{BoxError, Failure, panic_text},
27    invocations::{error_response, refused},
28};
29
30pub(crate) const DEFAULT_STREAM_HEARTBEAT: Duration = Duration::from_secs(30);
31/// A longer interval, such as `Duration::MAX`, cannot be added to the clock. tokio
32/// caps its own sleeps at the same 30 years.
33const MAX_STREAM_HEARTBEAT: Duration = Duration::from_secs(86400 * 365 * 30);
34
35tokio::task_local! {
36    /// The heartbeat of the app, in place around the routes given to `Builder::routes`.
37    pub(crate) static ROUTE_HEARTBEAT: Duration;
38}
39
40const STREAM_NOT_ACCEPTED: &str = "Streaming response requires Accept: text/event-stream header. \
41     Please include this header in your request to receive streaming data.";
42
43type Events = Pin<Box<dyn Stream<Item = Result<Event, Infallible>> + Send>>;
44
45/// The reply of an invocation handler.
46///
47/// A handler can also return any [`Serialize`] value directly, which is the same as
48/// [`Response::json`]. Use `Response` to set the status, to send a raw HTTP response,
49/// or when one handler has to choose between several kinds of reply.
50///
51/// # Encoding
52///
53/// A value from [`json`](Self::json) or [`with_status`](Self::with_status) is encoded
54/// by the `Accept` header of the request:
55///
56/// | `Accept` allows | Reply |
57/// | --- | --- |
58/// | `application/json`, or the header is absent | `application/json` |
59/// | otherwise `text/plain` | `text/plain`: a string value as it is, any other value as JSON text |
60/// | otherwise `application/octet-stream` | `application/octet-stream`: the bytes of the JSON text |
61/// | none of these | `application/json` |
62///
63/// A type is allowed by its own media range, by a wildcard for its kind such as
64/// `application/*`, or by `*/*`. The most specific of these decides, and a range with
65/// `q=0` refuses the type: `application/json;q=0, */*` does not allow JSON. Other `q`
66/// values and parameters have no effect. Media types match without regard to case,
67/// and several `Accept` fields count as one list.
68///
69/// # Streaming
70///
71/// [`stream`](Self::stream) sends Server-Sent Events. A request with no `Accept` header
72/// gets the stream, as the Python SDK sends it. A request whose `Accept` header does
73/// not allow `text/event-stream`, by the rules above, receives `406`. The server
74/// decides this after the handler has returned the stream and before it reads the
75/// stream. See [`stream`](Self::stream) for the event format and the error rules.
76///
77/// # Status codes behind AgentCore Runtime
78///
79/// A direct HTTP caller receives the status and body that the agent sends. A caller of
80/// the `InvokeAgentRuntime` API does not: the service documents that it reports a
81/// `4xx` or `5xx` reply of the agent as a `RuntimeClientError` with HTTP status 424.
82/// In tests against the service, a `201` reply was reported the same way. Use status
83/// `200` for a reply that the API caller must receive, and put the outcome in the body.
84///
85/// `Response` also implements axum's [`IntoResponse`]. Returned from a route that is
86/// not the invocation route, a value is always encoded as JSON and a stream is always
87/// sent. The stream uses the heartbeat of the app on a route given to
88/// [`Builder::routes`](super::Builder::routes), and the default of 30 seconds on any
89/// other route.
90pub struct Response {
91    kind: Kind,
92}
93
94enum Kind {
95    Value { status: StatusCode, json: Result<Vec<u8>, serde_json::Error> },
96    Http(Box<http::Response<Body>>),
97    Stream(Events, StreamFailed),
98}
99
100impl Response {
101    /// A `200` reply holding `value`.
102    ///
103    /// If `value` fails to serialize, the client receives a `500` JSON error.
104    pub fn json<T: Serialize>(value: T) -> Self {
105        Self::with_status(StatusCode::OK, value)
106    }
107
108    /// A reply with the given status holding `value`.
109    ///
110    /// If `value` fails to serialize, the client receives a `500` JSON error. HTTP
111    /// allows no body for a `1xx`, `204` or `304` status, so the server sends such a
112    /// reply without `value`.
113    pub fn with_status<T: Serialize>(status: StatusCode, value: T) -> Self {
114        Self { kind: Kind::Value { status, json: serde_json::to_vec(&value) } }
115    }
116
117    /// A raw HTTP response. The server sends its status, headers and body unchanged
118    /// and does not look at the `Accept` header.
119    ///
120    /// The body can be a stream. The request context stays available through
121    /// [`context::current`](crate::context::current) while the server reads it.
122    ///
123    /// When the body fails or panics, the server logs the cause and closes the
124    /// connection. A direct caller sees a reply that was cut. In tests against
125    /// AgentCore Runtime, the caller of `InvokeAgentRuntime` received such a reply
126    /// as a complete one. Send a last item that the caller checks when it must know
127    /// that the reply is complete.
128    pub fn from_http(response: http::Response<Body>) -> Self {
129        Self { kind: Kind::Http(Box::new(response)) }
130    }
131
132    /// A stream of Server-Sent Events. Each item is sent as soon as the stream yields
133    /// it, as one event whose data is the JSON encoding of the item:
134    ///
135    /// ```text
136    /// data: {"text":"hello"}
137    /// ```
138    ///
139    /// The stream runs after the handler has returned, so it must own what it uses.
140    /// The request context stays available through
141    /// [`context::current`](crate::context::current) while the stream runs.
142    ///
143    /// # Do the work inside the stream
144    ///
145    /// The server sends nothing while the handler runs, not even the status, and it
146    /// checks the `Accept` header only when the handler has returned. A handler
147    /// should therefore return the stream at once and do its work as the first step
148    /// of the stream. The work then starts no earlier than the reply, the heartbeat
149    /// covers it, and a request that gets `406` starts none of it:
150    ///
151    /// ```
152    /// use std::convert::Infallible;
153    ///
154    /// use bedrock_agentcore::runtime::Response;
155    /// use futures_util::{StreamExt, stream};
156    ///
157    /// async fn handler(prompt: String) -> Result<Response, Infallible> {
158    ///     let reply = stream::once(async move {
159    ///         let words = slow_lookup(prompt).await;
160    ///         stream::iter(words.into_iter().map(Ok::<_, Infallible>))
161    ///     })
162    ///     .flatten();
163    ///     Ok(Response::stream(reply))
164    /// }
165    /// # async fn slow_lookup(prompt: String) -> Vec<String> { vec![prompt] }
166    /// ```
167    ///
168    /// A handler that must decide before it starts work can read the `Accept` header
169    /// from [`RequestContext::request_headers`](crate::RequestContext::request_headers).
170    ///
171    /// When the connection to the agent closes, the server drops the stream. Behind
172    /// AgentCore Runtime that connection belongs to the service, not to the caller of
173    /// `InvokeAgentRuntime`. In tests against the service, a caller that disconnected
174    /// did not close it: the service read the stream to its end. Do not rely on a
175    /// caller's disconnect to stop work in a deployed agent.
176    ///
177    /// # Errors in the stream
178    ///
179    /// The response status is already `200` when the stream starts. An `Err` item ends
180    /// the stream with one last event, and the server logs the invocation as failed:
181    ///
182    /// ```text
183    /// event: error
184    /// data: {"error":"<Display text of the error>"}
185    /// ```
186    ///
187    /// An item that fails to serialize ends it the same way with the text
188    /// `Failed to serialize response`. So does an unwinding panic in the stream, in the
189    /// serializer of an item, in the conversion of an error or in the destructors of a
190    /// stream that has ended, with the text `Internal error`. The log line of the
191    /// failure names the cause in each case.
192    /// To reply with a JSON `500` instead, return `Err` from the handler before it
193    /// creates the stream.
194    ///
195    /// # Quiet streams
196    ///
197    /// While the stream yields nothing, the server sends an SSE comment line every 30
198    /// seconds so that proxies keep the connection open. Change the interval with
199    /// [`Builder::stream_heartbeat`](super::Builder::stream_heartbeat). Clients ignore
200    /// comment lines.
201    pub fn stream<S, T, E>(stream: S) -> Self
202    where
203        S: Stream<Item = Result<T, E>> + Send + 'static,
204        T: Serialize,
205        E: Into<BoxError>,
206    {
207        let failed = StreamFailed::default();
208        Self { kind: Kind::Stream(Box::pin(EventStream(Some(Box::pin(stream)), failed.clone())), failed) }
209    }
210
211    /// `accept` is `None` on routes other than the invocation route, where the reply
212    /// is not negotiated.
213    pub(crate) fn into_http(self, accept: Option<&str>, heartbeat: Duration) -> axum::response::Response {
214        let (status, json) = match self.kind {
215            Kind::Http(response) => return *response,
216            Kind::Stream(events, failed) => {
217                // A request with no Accept header accepts every type, as `*/*` does.
218                let allows_stream = |accept: &str| {
219                    let ranges = media_ranges(accept);
220                    ranges.is_empty() || allows(&ranges, "text/event-stream")
221                };
222                if accept.is_some_and(|accept| !allows_stream(accept)) {
223                    // Dropping the stream runs the handler's destructors, which can panic.
224                    let _ = catch_unwind(AssertUnwindSafe(|| drop(events)));
225                    return refused(StatusCode::NOT_ACCEPTABLE, STREAM_NOT_ACCEPTED, None);
226                }
227                let keep_alive = KeepAlive::new().interval(heartbeat.min(MAX_STREAM_HEARTBEAT));
228                let mut response = Sse::new(events).keep_alive(keep_alive).into_response();
229                response.extensions_mut().insert(failed);
230                return response;
231            }
232            Kind::Value { json: Err(error), .. } => {
233                tracing::error!(%error, "failed to serialize the invocation response");
234                return error_response(StatusCode::INTERNAL_SERVER_ERROR, "Failed to serialize response", None);
235            }
236            // HTTP allows no body for these statuses.
237            Kind::Value { status, .. }
238                if status.is_informational()
239                    || status == StatusCode::NO_CONTENT
240                    || status == StatusCode::NOT_MODIFIED =>
241            {
242                return status.into_response();
243            }
244            Kind::Value { status, json: Ok(json) } => (status, json),
245        };
246        let (content_type, body) = match negotiate(accept.unwrap_or_default()) {
247            Encoding::Json => ("application/json", json),
248            Encoding::Binary => ("application/octet-stream", json),
249            // A JSON string is sent without its quotes and escapes.
250            Encoding::Text => match json.first() {
251                Some(b'"') => (
252                    "text/plain; charset=utf-8",
253                    serde_json::from_slice::<String>(&json).map_or(json, String::into_bytes),
254                ),
255                _ => ("text/plain; charset=utf-8", json),
256            },
257        };
258        (status, [(header::CONTENT_TYPE, content_type)], body).into_response()
259    }
260}
261
262impl IntoResponse for Response {
263    fn into_response(self) -> axum::response::Response {
264        let heartbeat = ROUTE_HEARTBEAT.try_with(|heartbeat| *heartbeat).unwrap_or(DEFAULT_STREAM_HEARTBEAT);
265        self.into_http(None, heartbeat)
266    }
267}
268
269impl fmt::Debug for Response {
270    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
271        f.debug_struct("Response").finish_non_exhaustive()
272    }
273}
274
275#[derive(Debug, PartialEq)]
276enum Encoding {
277    Json,
278    Text,
279    Binary,
280}
281
282/// The media ranges of an `Accept` value in lowercase, each with whether the client
283/// allows it. A range with `q=0` is refused.
284fn media_ranges(accept: &str) -> Vec<(String, bool)> {
285    accept
286        .split(',')
287        .filter_map(|range| {
288            let mut parts = range.split(';').map(str::trim);
289            let media = parts.next().filter(|media| !media.is_empty())?.to_ascii_lowercase();
290            let refused = parts.any(|parameter| {
291                let quality = parameter.split_once('=').filter(|(name, _)| name.trim().eq_ignore_ascii_case("q"));
292                quality.is_some_and(|(_, value)| value.trim().parse::<f32>() == Ok(0.0))
293            });
294            Some((media, !refused))
295        })
296        .collect()
297}
298
299/// Whether the client allows `media_type`. The most specific range that covers the
300/// type decides, so `application/json;q=0` refuses JSON even next to `*/*`.
301fn allows(ranges: &[(String, bool)], media_type: &str) -> bool {
302    let kind = media_type.split('/').next().unwrap_or_default();
303    [media_type.to_owned(), format!("{kind}/*"), "*/*".to_owned()]
304        .iter()
305        .find_map(|candidate| ranges.iter().find(|(range, _)| range == candidate).map(|(_, allowed)| *allowed))
306        .unwrap_or(false)
307}
308
309fn negotiate(accept: &str) -> Encoding {
310    let ranges = media_ranges(accept);
311    if allows(&ranges, "application/json") {
312        Encoding::Json
313    } else if allows(&ranges, "text/plain") {
314        Encoding::Text
315    } else if allows(&ranges, "application/octet-stream") {
316        Encoding::Binary
317    } else {
318        Encoding::Json
319    }
320}
321
322/// Turns the items of a handler's stream into SSE events. An error, a failed
323/// serialization or a panic becomes one last `error` event, then the stream ends.
324struct EventStream<S>(Option<Pin<Box<S>>>, StreamFailed);
325
326/// How a stream failed. The response status is 200 by then, so the outcome log reads
327/// this value to report the invocation as failed.
328#[derive(Clone, Default)]
329pub(crate) struct StreamFailed(Arc<(OnceLock<Failure>, AtomicBool)>);
330
331impl StreamFailed {
332    /// The failure, when the stream has ended with the error event.
333    pub(crate) fn get(&self) -> Option<&Failure> {
334        self.0.0.get()
335    }
336
337    /// The outcome line of the invocation reports the failure. Without this call,
338    /// on a route that has no outcome line, the stream logs its failure itself.
339    pub(crate) fn claim(&self) {
340        self.0.1.store(true, Ordering::Relaxed);
341    }
342
343    fn set(&self, failure: Failure) {
344        if !self.0.1.load(Ordering::Relaxed) {
345            tracing::error!(error = failure.error, causes = failure.causes, "the response stream failed");
346        }
347        let _ = self.0.0.set(failure);
348    }
349}
350
351/// What one poll of the handler's stream produced.
352enum Step {
353    Pending,
354    End,
355    Data(String),
356    Failure(Failure),
357}
358
359fn internal_error(cause: &str) -> Failure {
360    Failure { error: "Internal error".to_owned(), causes: Some(cause.to_owned()) }
361}
362
363impl<S> EventStream<S> {
364    /// Dropping the stream runs the handler's destructors. Returns whether one panicked.
365    fn drop_stream(&mut self) -> bool {
366        let stream = self.0.take();
367        catch_unwind(AssertUnwindSafe(|| drop(stream))).is_err()
368    }
369}
370
371impl<S, T, E> Stream for EventStream<S>
372where
373    S: Stream<Item = Result<T, E>>,
374    T: Serialize,
375    E: Into<BoxError>,
376{
377    type Item = Result<Event, Infallible>;
378
379    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
380        let Some(stream) = self.0.as_mut() else { return Poll::Ready(None) };
381        // The handler's code runs in three places here: the poll of its stream, the
382        // serializer of an item and the conversion of an error. A panic in any of
383        // them ends the stream with the error event.
384        let step = catch_unwind(AssertUnwindSafe(|| match stream.as_mut().poll_next(cx) {
385            Poll::Pending => Step::Pending,
386            Poll::Ready(None) => Step::End,
387            Poll::Ready(Some(Ok(item))) => match serde_json::to_string(&item) {
388                Ok(json) => Step::Data(json),
389                // The caller gets a fixed text. The cause is for the log.
390                Err(error) => Step::Failure(Failure {
391                    error: "Failed to serialize response".to_owned(),
392                    causes: Some(error.to_string()),
393                }),
394            },
395            Poll::Ready(Some(Err(error))) => Step::Failure(Failure::of(error.into())),
396        }));
397        let step = step.unwrap_or_else(|panic| Step::Failure(internal_error(panic_text(panic.as_ref()))));
398        let failure = match step {
399            Step::Pending => return Poll::Pending,
400            Step::Data(json) => return Poll::Ready(Some(Ok(Event::default().data(json)))),
401            Step::End if self.drop_stream() => internal_error("a destructor of the stream panicked"),
402            Step::End => return Poll::Ready(None),
403            Step::Failure(failure) => {
404                // The stream has already failed. A panic in its destructors adds nothing.
405                self.drop_stream();
406                failure
407            }
408        };
409        let data = serde_json::json!({ "error": failure.error }).to_string();
410        self.1.set(failure);
411        Poll::Ready(Some(Ok(Event::default().event("error").data(data))))
412    }
413}
414
415/// Conversion of a handler's return value into a [`Response`].
416///
417/// It is implemented for every [`Serialize`] type and for [`Response`]. A stream is
418/// not a value: wrap it with [`Response::stream`].
419pub trait IntoInvocationResponse {
420    /// Converts `self` into a response.
421    fn into_invocation_response(self) -> Response;
422}
423
424impl<T: Serialize> IntoInvocationResponse for T {
425    fn into_invocation_response(self) -> Response {
426        Response::json(self)
427    }
428}
429
430impl IntoInvocationResponse for Response {
431    fn into_invocation_response(self) -> Response {
432        self
433    }
434}
435
436#[cfg(test)]
437mod tests {
438    use super::{Encoding::*, *};
439
440    #[test]
441    fn accept_negotiation() {
442        let cases = [
443            ("", Json),
444            ("application/json", Json),
445            ("*/*", Json),
446            ("application/*", Json),
447            ("text/plain", Text),
448            ("text/*", Text),
449            ("TEXT/Plain; charset=utf-8", Text),
450            ("application/octet-stream", Binary),
451            ("text/html", Json),
452            ("text/event-stream", Json),
453            ("text/plain, application/json", Json),
454            ("application/octet-stream, text/plain", Text),
455            ("text/plain;q=0.1, application/octet-stream;q=0.9", Text),
456            ("application/json;q=0, text/plain", Text),
457            ("*/*; Q=0.0, application/octet-stream", Binary),
458            ("text/plain;q=0", Json),
459            ("application/jsonx", Json),
460            // An explicit refusal is kept next to a wildcard that would allow the type.
461            ("application/json;q=0, */*;q=1, text/plain;q=0.5", Text),
462            ("application/json;q=0, text/plain;q=0, */*", Binary),
463            ("application/*;q=0, application/json", Json),
464            ("application/json;q=0, application/*", Binary),
465            ("text/event-stream, text/plain", Text),
466            // Two Accept fields reach the policy joined by a comma.
467            ("text/plain,application/json", Json),
468        ];
469        for (accept, encoding) in cases {
470            assert_eq!(negotiate(accept), encoding, "Accept: {accept:?}");
471        }
472    }
473
474    #[test]
475    fn response_returned_from_another_axum_route_is_json() {
476        let response = Response::with_status(StatusCode::CREATED, "text").into_response();
477        assert_eq!(response.status(), StatusCode::CREATED);
478        assert_eq!(response.headers()[header::CONTENT_TYPE], "application/json");
479    }
480}