bedrock-agentcore 0.1.0

Amazon Bedrock AgentCore SDK for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
use std::{
    convert::Infallible,
    fmt,
    panic::{AssertUnwindSafe, catch_unwind},
    pin::Pin,
    sync::{
        Arc, OnceLock,
        atomic::{AtomicBool, Ordering},
    },
    task::{Context, Poll},
    time::Duration,
};

use axum::{
    body::Body,
    http::{self, StatusCode, header},
    response::{
        IntoResponse,
        sse::{Event, KeepAlive, Sse},
    },
};
use futures_core::Stream;
use serde::Serialize;

use super::{
    handler::{BoxError, Failure, panic_text},
    invocations::{error_response, refused},
};

pub(crate) const DEFAULT_STREAM_HEARTBEAT: Duration = Duration::from_secs(30);
/// A longer interval, such as `Duration::MAX`, cannot be added to the clock. tokio
/// caps its own sleeps at the same 30 years.
const MAX_STREAM_HEARTBEAT: Duration = Duration::from_secs(86400 * 365 * 30);

tokio::task_local! {
    /// The heartbeat of the app, in place around the routes given to `Builder::routes`.
    pub(crate) static ROUTE_HEARTBEAT: Duration;
}

const STREAM_NOT_ACCEPTED: &str = "Streaming response requires Accept: text/event-stream header. \
     Please include this header in your request to receive streaming data.";

type Events = Pin<Box<dyn Stream<Item = Result<Event, Infallible>> + Send>>;

/// The reply of an invocation handler.
///
/// A handler can also return any [`Serialize`] value directly, which is the same as
/// [`Response::json`]. Use `Response` to set the status, to send a raw HTTP response,
/// or when one handler has to choose between several kinds of reply.
///
/// # Encoding
///
/// A value from [`json`](Self::json) or [`with_status`](Self::with_status) is encoded
/// by the `Accept` header of the request:
///
/// | `Accept` allows | Reply |
/// | --- | --- |
/// | `application/json`, or the header is absent | `application/json` |
/// | otherwise `text/plain` | `text/plain`: a string value as it is, any other value as JSON text |
/// | otherwise `application/octet-stream` | `application/octet-stream`: the bytes of the JSON text |
/// | none of these | `application/json` |
///
/// A type is allowed by its own media range, by a wildcard for its kind such as
/// `application/*`, or by `*/*`. The most specific of these decides, and a range with
/// `q=0` refuses the type: `application/json;q=0, */*` does not allow JSON. Other `q`
/// values and parameters have no effect. Media types match without regard to case,
/// and several `Accept` fields count as one list.
///
/// # Streaming
///
/// [`stream`](Self::stream) sends Server-Sent Events. A request with no `Accept` header
/// gets the stream, as the Python SDK sends it. A request whose `Accept` header does
/// not allow `text/event-stream`, by the rules above, receives `406`. The server
/// decides this after the handler has returned the stream and before it reads the
/// stream. See [`stream`](Self::stream) for the event format and the error rules.
///
/// # Status codes behind AgentCore Runtime
///
/// A direct HTTP caller receives the status and body that the agent sends. A caller of
/// the `InvokeAgentRuntime` API does not: the service documents that it reports a
/// `4xx` or `5xx` reply of the agent as a `RuntimeClientError` with HTTP status 424.
/// In tests against the service, a `201` reply was reported the same way. Use status
/// `200` for a reply that the API caller must receive, and put the outcome in the body.
///
/// `Response` also implements axum's [`IntoResponse`]. Returned from a route that is
/// not the invocation route, a value is always encoded as JSON and a stream is always
/// sent. The stream uses the heartbeat of the app on a route given to
/// [`Builder::routes`](super::Builder::routes), and the default of 30 seconds on any
/// other route.
pub struct Response {
    kind: Kind,
}

enum Kind {
    Value { status: StatusCode, json: Result<Vec<u8>, serde_json::Error> },
    Http(Box<http::Response<Body>>),
    Stream(Events, StreamFailed),
}

impl Response {
    /// A `200` reply holding `value`.
    ///
    /// If `value` fails to serialize, the client receives a `500` JSON error.
    pub fn json<T: Serialize>(value: T) -> Self {
        Self::with_status(StatusCode::OK, value)
    }

    /// A reply with the given status holding `value`.
    ///
    /// If `value` fails to serialize, the client receives a `500` JSON error. HTTP
    /// allows no body for a `1xx`, `204` or `304` status, so the server sends such a
    /// reply without `value`.
    pub fn with_status<T: Serialize>(status: StatusCode, value: T) -> Self {
        Self { kind: Kind::Value { status, json: serde_json::to_vec(&value) } }
    }

    /// A raw HTTP response. The server sends its status, headers and body unchanged
    /// and does not look at the `Accept` header.
    ///
    /// The body can be a stream. The request context stays available through
    /// [`context::current`](crate::context::current) while the server reads it.
    ///
    /// When the body fails or panics, the server logs the cause and closes the
    /// connection. A direct caller sees a reply that was cut. In tests against
    /// AgentCore Runtime, the caller of `InvokeAgentRuntime` received such a reply
    /// as a complete one. Send a last item that the caller checks when it must know
    /// that the reply is complete.
    pub fn from_http(response: http::Response<Body>) -> Self {
        Self { kind: Kind::Http(Box::new(response)) }
    }

    /// A stream of Server-Sent Events. Each item is sent as soon as the stream yields
    /// it, as one event whose data is the JSON encoding of the item:
    ///
    /// ```text
    /// data: {"text":"hello"}
    /// ```
    ///
    /// The stream runs after the handler has returned, so it must own what it uses.
    /// The request context stays available through
    /// [`context::current`](crate::context::current) while the stream runs.
    ///
    /// # Do the work inside the stream
    ///
    /// The server sends nothing while the handler runs, not even the status, and it
    /// checks the `Accept` header only when the handler has returned. A handler
    /// should therefore return the stream at once and do its work as the first step
    /// of the stream. The work then starts no earlier than the reply, the heartbeat
    /// covers it, and a request that gets `406` starts none of it:
    ///
    /// ```
    /// use std::convert::Infallible;
    ///
    /// use bedrock_agentcore::runtime::Response;
    /// use futures_util::{StreamExt, stream};
    ///
    /// async fn handler(prompt: String) -> Result<Response, Infallible> {
    ///     let reply = stream::once(async move {
    ///         let words = slow_lookup(prompt).await;
    ///         stream::iter(words.into_iter().map(Ok::<_, Infallible>))
    ///     })
    ///     .flatten();
    ///     Ok(Response::stream(reply))
    /// }
    /// # async fn slow_lookup(prompt: String) -> Vec<String> { vec![prompt] }
    /// ```
    ///
    /// A handler that must decide before it starts work can read the `Accept` header
    /// from [`RequestContext::request_headers`](crate::RequestContext::request_headers).
    ///
    /// When the connection to the agent closes, the server drops the stream. Behind
    /// AgentCore Runtime that connection belongs to the service, not to the caller of
    /// `InvokeAgentRuntime`. In tests against the service, a caller that disconnected
    /// did not close it: the service read the stream to its end. Do not rely on a
    /// caller's disconnect to stop work in a deployed agent.
    ///
    /// # Errors in the stream
    ///
    /// The response status is already `200` when the stream starts. An `Err` item ends
    /// the stream with one last event, and the server logs the invocation as failed:
    ///
    /// ```text
    /// event: error
    /// data: {"error":"<Display text of the error>"}
    /// ```
    ///
    /// An item that fails to serialize ends it the same way with the text
    /// `Failed to serialize response`. So does an unwinding panic in the stream, in the
    /// serializer of an item, in the conversion of an error or in the destructors of a
    /// stream that has ended, with the text `Internal error`. The log line of the
    /// failure names the cause in each case.
    /// To reply with a JSON `500` instead, return `Err` from the handler before it
    /// creates the stream.
    ///
    /// # Quiet streams
    ///
    /// While the stream yields nothing, the server sends an SSE comment line every 30
    /// seconds so that proxies keep the connection open. Change the interval with
    /// [`Builder::stream_heartbeat`](super::Builder::stream_heartbeat). Clients ignore
    /// comment lines.
    pub fn stream<S, T, E>(stream: S) -> Self
    where
        S: Stream<Item = Result<T, E>> + Send + 'static,
        T: Serialize,
        E: Into<BoxError>,
    {
        let failed = StreamFailed::default();
        Self { kind: Kind::Stream(Box::pin(EventStream(Some(Box::pin(stream)), failed.clone())), failed) }
    }

    /// `accept` is `None` on routes other than the invocation route, where the reply
    /// is not negotiated.
    pub(crate) fn into_http(self, accept: Option<&str>, heartbeat: Duration) -> axum::response::Response {
        let (status, json) = match self.kind {
            Kind::Http(response) => return *response,
            Kind::Stream(events, failed) => {
                // A request with no Accept header accepts every type, as `*/*` does.
                let allows_stream = |accept: &str| {
                    let ranges = media_ranges(accept);
                    ranges.is_empty() || allows(&ranges, "text/event-stream")
                };
                if accept.is_some_and(|accept| !allows_stream(accept)) {
                    // Dropping the stream runs the handler's destructors, which can panic.
                    let _ = catch_unwind(AssertUnwindSafe(|| drop(events)));
                    return refused(StatusCode::NOT_ACCEPTABLE, STREAM_NOT_ACCEPTED, None);
                }
                let keep_alive = KeepAlive::new().interval(heartbeat.min(MAX_STREAM_HEARTBEAT));
                let mut response = Sse::new(events).keep_alive(keep_alive).into_response();
                response.extensions_mut().insert(failed);
                return response;
            }
            Kind::Value { json: Err(error), .. } => {
                tracing::error!(%error, "failed to serialize the invocation response");
                return error_response(StatusCode::INTERNAL_SERVER_ERROR, "Failed to serialize response", None);
            }
            // HTTP allows no body for these statuses.
            Kind::Value { status, .. }
                if status.is_informational()
                    || status == StatusCode::NO_CONTENT
                    || status == StatusCode::NOT_MODIFIED =>
            {
                return status.into_response();
            }
            Kind::Value { status, json: Ok(json) } => (status, json),
        };
        let (content_type, body) = match negotiate(accept.unwrap_or_default()) {
            Encoding::Json => ("application/json", json),
            Encoding::Binary => ("application/octet-stream", json),
            // A JSON string is sent without its quotes and escapes.
            Encoding::Text => match json.first() {
                Some(b'"') => (
                    "text/plain; charset=utf-8",
                    serde_json::from_slice::<String>(&json).map_or(json, String::into_bytes),
                ),
                _ => ("text/plain; charset=utf-8", json),
            },
        };
        (status, [(header::CONTENT_TYPE, content_type)], body).into_response()
    }
}

impl IntoResponse for Response {
    fn into_response(self) -> axum::response::Response {
        let heartbeat = ROUTE_HEARTBEAT.try_with(|heartbeat| *heartbeat).unwrap_or(DEFAULT_STREAM_HEARTBEAT);
        self.into_http(None, heartbeat)
    }
}

impl fmt::Debug for Response {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Response").finish_non_exhaustive()
    }
}

#[derive(Debug, PartialEq)]
enum Encoding {
    Json,
    Text,
    Binary,
}

/// The media ranges of an `Accept` value in lowercase, each with whether the client
/// allows it. A range with `q=0` is refused.
fn media_ranges(accept: &str) -> Vec<(String, bool)> {
    accept
        .split(',')
        .filter_map(|range| {
            let mut parts = range.split(';').map(str::trim);
            let media = parts.next().filter(|media| !media.is_empty())?.to_ascii_lowercase();
            let refused = parts.any(|parameter| {
                let quality = parameter.split_once('=').filter(|(name, _)| name.trim().eq_ignore_ascii_case("q"));
                quality.is_some_and(|(_, value)| value.trim().parse::<f32>() == Ok(0.0))
            });
            Some((media, !refused))
        })
        .collect()
}

/// Whether the client allows `media_type`. The most specific range that covers the
/// type decides, so `application/json;q=0` refuses JSON even next to `*/*`.
fn allows(ranges: &[(String, bool)], media_type: &str) -> bool {
    let kind = media_type.split('/').next().unwrap_or_default();
    [media_type.to_owned(), format!("{kind}/*"), "*/*".to_owned()]
        .iter()
        .find_map(|candidate| ranges.iter().find(|(range, _)| range == candidate).map(|(_, allowed)| *allowed))
        .unwrap_or(false)
}

fn negotiate(accept: &str) -> Encoding {
    let ranges = media_ranges(accept);
    if allows(&ranges, "application/json") {
        Encoding::Json
    } else if allows(&ranges, "text/plain") {
        Encoding::Text
    } else if allows(&ranges, "application/octet-stream") {
        Encoding::Binary
    } else {
        Encoding::Json
    }
}

/// Turns the items of a handler's stream into SSE events. An error, a failed
/// serialization or a panic becomes one last `error` event, then the stream ends.
struct EventStream<S>(Option<Pin<Box<S>>>, StreamFailed);

/// How a stream failed. The response status is 200 by then, so the outcome log reads
/// this value to report the invocation as failed.
#[derive(Clone, Default)]
pub(crate) struct StreamFailed(Arc<(OnceLock<Failure>, AtomicBool)>);

impl StreamFailed {
    /// The failure, when the stream has ended with the error event.
    pub(crate) fn get(&self) -> Option<&Failure> {
        self.0.0.get()
    }

    /// The outcome line of the invocation reports the failure. Without this call,
    /// on a route that has no outcome line, the stream logs its failure itself.
    pub(crate) fn claim(&self) {
        self.0.1.store(true, Ordering::Relaxed);
    }

    fn set(&self, failure: Failure) {
        if !self.0.1.load(Ordering::Relaxed) {
            tracing::error!(error = failure.error, causes = failure.causes, "the response stream failed");
        }
        let _ = self.0.0.set(failure);
    }
}

/// What one poll of the handler's stream produced.
enum Step {
    Pending,
    End,
    Data(String),
    Failure(Failure),
}

fn internal_error(cause: &str) -> Failure {
    Failure { error: "Internal error".to_owned(), causes: Some(cause.to_owned()) }
}

impl<S> EventStream<S> {
    /// Dropping the stream runs the handler's destructors. Returns whether one panicked.
    fn drop_stream(&mut self) -> bool {
        let stream = self.0.take();
        catch_unwind(AssertUnwindSafe(|| drop(stream))).is_err()
    }
}

impl<S, T, E> Stream for EventStream<S>
where
    S: Stream<Item = Result<T, E>>,
    T: Serialize,
    E: Into<BoxError>,
{
    type Item = Result<Event, Infallible>;

    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        let Some(stream) = self.0.as_mut() else { return Poll::Ready(None) };
        // The handler's code runs in three places here: the poll of its stream, the
        // serializer of an item and the conversion of an error. A panic in any of
        // them ends the stream with the error event.
        let step = catch_unwind(AssertUnwindSafe(|| match stream.as_mut().poll_next(cx) {
            Poll::Pending => Step::Pending,
            Poll::Ready(None) => Step::End,
            Poll::Ready(Some(Ok(item))) => match serde_json::to_string(&item) {
                Ok(json) => Step::Data(json),
                // The caller gets a fixed text. The cause is for the log.
                Err(error) => Step::Failure(Failure {
                    error: "Failed to serialize response".to_owned(),
                    causes: Some(error.to_string()),
                }),
            },
            Poll::Ready(Some(Err(error))) => Step::Failure(Failure::of(error.into())),
        }));
        let step = step.unwrap_or_else(|panic| Step::Failure(internal_error(panic_text(panic.as_ref()))));
        let failure = match step {
            Step::Pending => return Poll::Pending,
            Step::Data(json) => return Poll::Ready(Some(Ok(Event::default().data(json)))),
            Step::End if self.drop_stream() => internal_error("a destructor of the stream panicked"),
            Step::End => return Poll::Ready(None),
            Step::Failure(failure) => {
                // The stream has already failed. A panic in its destructors adds nothing.
                self.drop_stream();
                failure
            }
        };
        let data = serde_json::json!({ "error": failure.error }).to_string();
        self.1.set(failure);
        Poll::Ready(Some(Ok(Event::default().event("error").data(data))))
    }
}

/// Conversion of a handler's return value into a [`Response`].
///
/// It is implemented for every [`Serialize`] type and for [`Response`]. A stream is
/// not a value: wrap it with [`Response::stream`].
pub trait IntoInvocationResponse {
    /// Converts `self` into a response.
    fn into_invocation_response(self) -> Response;
}

impl<T: Serialize> IntoInvocationResponse for T {
    fn into_invocation_response(self) -> Response {
        Response::json(self)
    }
}

impl IntoInvocationResponse for Response {
    fn into_invocation_response(self) -> Response {
        self
    }
}

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

    #[test]
    fn accept_negotiation() {
        let cases = [
            ("", Json),
            ("application/json", Json),
            ("*/*", Json),
            ("application/*", Json),
            ("text/plain", Text),
            ("text/*", Text),
            ("TEXT/Plain; charset=utf-8", Text),
            ("application/octet-stream", Binary),
            ("text/html", Json),
            ("text/event-stream", Json),
            ("text/plain, application/json", Json),
            ("application/octet-stream, text/plain", Text),
            ("text/plain;q=0.1, application/octet-stream;q=0.9", Text),
            ("application/json;q=0, text/plain", Text),
            ("*/*; Q=0.0, application/octet-stream", Binary),
            ("text/plain;q=0", Json),
            ("application/jsonx", Json),
            // An explicit refusal is kept next to a wildcard that would allow the type.
            ("application/json;q=0, */*;q=1, text/plain;q=0.5", Text),
            ("application/json;q=0, text/plain;q=0, */*", Binary),
            ("application/*;q=0, application/json", Json),
            ("application/json;q=0, application/*", Binary),
            ("text/event-stream, text/plain", Text),
            // Two Accept fields reach the policy joined by a comma.
            ("text/plain,application/json", Json),
        ];
        for (accept, encoding) in cases {
            assert_eq!(negotiate(accept), encoding, "Accept: {accept:?}");
        }
    }

    #[test]
    fn response_returned_from_another_axum_route_is_json() {
        let response = Response::with_status(StatusCode::CREATED, "text").into_response();
        assert_eq!(response.status(), StatusCode::CREATED);
        assert_eq!(response.headers()[header::CONTENT_TYPE], "application/json");
    }
}