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
481
482
483
484
485
486
487
488
489
490
use std::{
    future::{Future, poll_fn},
    net::{Ipv4Addr, SocketAddr},
    panic::{AssertUnwindSafe, catch_unwind},
    pin::Pin,
    sync::{Arc, OnceLock},
    task::{Context, Poll},
    time::Duration,
};

use axum::{
    body::{Body, Bytes, HttpBody},
    extract::Request,
    http::{HeaderValue, StatusCode, Version, header::CONNECTION},
    middleware::{self, Next},
    response::{IntoResponse, Response},
};
use http_body::{Frame, SizeHint};
use tokio::{
    net::TcpListener,
    runtime::Handle,
    sync::{mpsc, oneshot, watch},
    task::JoinHandle,
};
use tracing::Instrument;

use super::invocations::InFlight;
use crate::{Error, ErrorKind, tasks::AsyncTasks};

const PORT: u16 = 8080;

/// Loopback by default. All interfaces inside a container, where the platform must
/// reach the server from outside the network namespace.
pub(crate) fn default_bind_addr() -> SocketAddr {
    let docker_container = std::env::var_os("DOCKER_CONTAINER");
    bind_addr(std::path::Path::new("/.dockerenv").exists(), docker_container.as_deref())
}

fn bind_addr(dockerenv_exists: bool, docker_container: Option<&std::ffi::OsStr>) -> SocketAddr {
    let in_container = dockerenv_exists || docker_container.is_some_and(|value| !value.is_empty());
    let ip = if in_container { Ipv4Addr::UNSPECIFIED } else { Ipv4Addr::LOCALHOST };
    SocketAddr::from((ip, PORT))
}

pub(crate) async fn bind(addr: SocketAddr) -> Result<TcpListener, Error> {
    TcpListener::bind(addr)
        .await
        .map_err(|source| Error::new(ErrorKind::Bind, format!("failed to bind {addr}")).with_source(source))
}

/// The runtime that runs the code of the customer: the invocation handler, the
/// body of its reply, the routes of the customer and the warmup handlers. It is the
/// runtime that called `run` or one of the `serve` methods. The server reads
/// requests and answers `GET /ping` on a thread of its own, as the Python SDK
/// does, so a handler that blocks its thread does not stop the health check.
///
/// It is empty for a router that the customer serves, where all code runs in the
/// task of the connection.
#[derive(Clone, Default)]
pub(crate) struct AppRuntime(Arc<OnceLock<Handle>>);

/// Ends the task when the request that waits for it is dropped: the client has
/// disconnected, or the shutdown deadline has passed.
struct AbortOnDrop<T>(JoinHandle<T>);

impl<T> Drop for AbortOnDrop<T> {
    fn drop(&mut self) {
        self.0.abort();
    }
}

impl AppRuntime {
    fn set_current(&self) {
        let _ = self.0.set(Handle::current());
    }

    /// Runs `future` to its end and returns its output. The future keeps the
    /// tracing span of the caller.
    pub(crate) async fn run<F>(&self, future: F) -> F::Output
    where
        F: Future + Send + 'static,
        F::Output: Send + 'static,
    {
        let Some(handle) = self.0.get() else { return future.await };
        let mut task = AbortOnDrop(handle.spawn(future.in_current_span()));
        match (&mut task.0).await {
            Ok(output) => output,
            Err(error) if error.is_panic() => std::panic::resume_unwind(error.into_panic()),
            // The runtime of the application is shutting down and has dropped the future.
            Err(_) => std::future::pending().await,
        }
    }

    /// Reads a body where `run` runs a future. A body of the application can do
    /// work in each poll, whether it knows its length or not. The returned body has
    /// the size hint of `body`, so the reply keeps its `Content-Length`.
    pub(crate) fn pump(&self, body: Body) -> Body {
        let Some(handle) = self.0.get().filter(|_| !body.is_end_stream()) else { return body };
        let remaining = body.size_hint();
        let (frames, received) = mpsc::channel(1);
        handle.spawn(async move {
            let mut body = body;
            // A body that panics ends with an error. Without this boundary the task
            // would end, and the client would take the reply for a complete one.
            let mut next = poll_fn(|cx| {
                catch_unwind(AssertUnwindSafe(|| Pin::new(&mut body).poll_frame(cx)))
                    .unwrap_or_else(|_| Poll::Ready(Some(Err(axum::Error::new("the response body panicked")))))
            });
            // The body is polled for a frame only when the server has taken the
            // frame before it, so a slow reader stops the source.
            while let Ok(permit) = frames.reserve().await {
                let frame = tokio::select! {
                    biased;
                    _ = frames.closed() => break,
                    frame = &mut next => frame,
                };
                let Some(frame) = frame else { break };
                let failed = frame.is_err();
                permit.send(frame);
                if failed {
                    break;
                }
            }
        });
        Body::new(Pumped { frames: received, remaining })
    }
}

/// The frames of a body that is read on the runtime of the application. Dropping
/// it stops the reading and drops the body there.
struct Pumped {
    frames: mpsc::Receiver<Result<Frame<Bytes>, axum::Error>>,
    /// The size hint of the body, less the data that has passed.
    remaining: SizeHint,
}

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

    fn poll_frame(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Result<Frame<Bytes>, axum::Error>>> {
        let frame = self.frames.poll_recv(cx);
        if let Poll::Ready(Some(Ok(frame))) = &frame
            && let Some(data) = frame.data_ref()
        {
            let sent = data.len() as u64;
            let (lower, upper) = (self.remaining.lower(), self.remaining.upper());
            self.remaining.set_lower(lower.saturating_sub(sent));
            if let Some(upper) = upper {
                self.remaining.set_upper(upper.saturating_sub(sent));
            }
        }
        frame
    }

    fn size_hint(&self) -> SizeHint {
        self.remaining
    }
}

/// What `serve` needs for the shutdown.
pub(crate) struct Shutdown {
    pub(crate) grace: Duration,
    pub(crate) tasks: AsyncTasks,
    pub(crate) in_flight: InFlight,
    pub(crate) runtime: AppRuntime,
}

/// How long the server waits for its connections to close after it has cancelled
/// the requests in flight.
const CLOSE_WAIT: Duration = Duration::from_millis(500);

pub(crate) async fn serve(
    listener: TcpListener,
    router: axum::Router,
    signal: impl Future<Output = ()> + Send + 'static,
    shutdown: Shutdown,
) -> Result<(), Error> {
    if let Ok(addr) = listener.local_addr() {
        tracing::info!(%addr, "AgentCore runtime server listening");
    }
    // Dropping the sender also cancels: a dropped server future ends its requests.
    let (cancel, cancelled) = watch::channel(false);
    let router = cancellable(router, cancelled);
    shutdown.runtime.set_current();
    let (stop, stopped) = oneshot::channel::<()>();
    let mut server = std::pin::pin!(serve_on_its_thread(listener, router, stopped)?);
    let mut closed = tokio::select! {
        _ = server.as_mut() => true,
        _ = signal => {
            let _ = stop.send(());
            false
        }
    };

    // AgentCore Runtime can end the process before the grace period ends. The work
    // that the shutdown interrupts is therefore named now, not at the deadline.
    if !closed {
        let invocations = shutdown.in_flight.log_interrupted();
        let tasks = shutdown.tasks.info();
        let names: Vec<&str> = tasks.running().iter().map(|task| task.name()).collect();
        let grace = shutdown.grace;
        tracing::info!(
            invocations,
            active_tasks = names.len(),
            tasks = ?names,
            ?grace,
            "shutdown started: waiting for requests in flight and tracked tasks"
        );
    }

    // The grace period starts at the signal.
    let deadline = tokio::time::Instant::now().checked_add(shutdown.grace);
    let drained = async {
        if !closed {
            let _ = server.as_mut().await;
            closed = true;
        }
        while shutdown.tasks.active_count() > 0 {
            tokio::time::sleep(Duration::from_millis(10)).await;
        }
    };
    let finished = match deadline {
        Some(deadline) => tokio::time::timeout_at(deadline, drained).await.is_ok(),
        None => {
            drained.await;
            true
        }
    };
    if finished {
        tracing::info!("shutdown finished: no request in flight and no tracked task is left");
        return Ok(());
    }

    // Requests are cancelled only when the server still had some at the deadline.
    let requests_cancelled = !closed;
    let _ = cancel.send(true);
    if !closed {
        closed = tokio::time::timeout(CLOSE_WAIT, server.as_mut()).await.is_ok();
    }
    let active_tasks = shutdown.tasks.active_count();
    tracing::warn!(
        requests_cancelled,
        connections_closed = closed,
        active_tasks,
        "shutdown did not finish within the grace period"
    );
    Err(Error::new(ErrorKind::ShutdownTimeout, timeout_message(shutdown.grace, requests_cancelled, active_tasks)))
}

/// Names the work that outlived the grace period: requests, tracked tasks or both.
fn timeout_message(grace: Duration, requests_cancelled: bool, active_tasks: usize) -> String {
    let tasks = match active_tasks {
        0 => None,
        1 => Some("1 tracked background task is still active".to_owned()),
        count => Some(format!("{count} tracked background tasks are still active")),
    };
    let causes: Vec<&str> =
        requests_cancelled.then_some("requests in flight were cancelled").into_iter().chain(tasks.as_deref()).collect();
    format!("shutdown did not finish within {grace:?}: {}", causes.join(" and "))
}

/// Starts the server on a thread of its own, with a runtime of one thread. The
/// server stops accepting connections when `stop` completes or its sender is
/// dropped. The returned receiver completes when all connections have closed.
/// Dropping the receiver ends the server and its connections at once.
fn serve_on_its_thread(
    listener: TcpListener,
    router: axum::Router,
    stop: oneshot::Receiver<()>,
) -> Result<oneshot::Receiver<()>, Error> {
    let failed =
        |source: std::io::Error| Error::new(ErrorKind::Serve, "failed to start the server thread").with_source(source);
    // The listener moves from the runtime of the application to the runtime of the server.
    let listener = listener.into_std().map_err(failed)?;
    let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().map_err(failed)?;
    // A subscriber that is the default of the calling thread only also gets the lines of the server.
    let dispatch = tracing::dispatcher::get_default(Clone::clone);
    let (mut done, finished) = oneshot::channel::<()>();
    let serve = move || {
        let _default = tracing::dispatcher::set_default(&dispatch);
        runtime.block_on(async move {
            let listener = match TcpListener::from_std(listener) {
                Ok(listener) => listener,
                Err(error) => return tracing::error!(%error, "the server thread could not use the listener"),
            };
            let server = axum::serve(listener, router).with_graceful_shutdown(async move {
                let _ = stop.await;
            });
            tokio::select! {
                _ = server => {}
                _ = done.closed() => {}
            }
        });
        // The runtime is dropped here, and its connections with it.
    };
    std::thread::Builder::new().name("agentcore-server".to_owned()).spawn(serve).map_err(failed)?;
    Ok(finished)
}

/// Makes every request of `router` end when `cancelled` becomes true or its sender
/// is dropped: a handler that still runs is dropped and the client gets a `503`, and
/// a response body that is still being sent fails and drops its source.
fn cancellable(router: axum::Router, cancelled: watch::Receiver<bool>) -> axum::Router {
    router.layer(middleware::from_fn(move |request: Request, next: Next| {
        end_at_deadline(cancelled.clone(), request, next)
    }))
}

async fn end_at_deadline(mut cancelled: watch::Receiver<bool>, request: Request, next: Next) -> Response {
    let (method, path, version) = (request.method().clone(), request.uri().path().to_owned(), request.version());
    let response = tokio::select! {
        response = next.run(request) => response,
        _ = cancelled.wait_for(|cancelled| *cancelled) => {
            tracing::warn!(%method, path, "request cancelled at the shutdown deadline");
            let mut response = StatusCode::SERVICE_UNAVAILABLE.into_response();
            // HTTP/2 has no `Connection` header. The graceful shutdown closes its connection.
            if version < Version::HTTP_2 {
                response.headers_mut().insert(CONNECTION, HeaderValue::from_static("close"));
            }
            return response;
        }
    };
    response.map(|inner| {
        let cancelled = Box::pin(async move {
            let _ = cancelled.wait_for(|cancelled| *cancelled).await;
            tracing::warn!(%method, path, "response body cancelled at the shutdown deadline");
        });
        Body::new(DeadlineBody { inner: Some(inner), cancelled })
    })
}

/// A response body that fails at the shutdown deadline and drops its source.
struct DeadlineBody {
    inner: Option<Body>,
    cancelled: Pin<Box<dyn Future<Output = ()> + Send>>,
}

impl HttpBody for DeadlineBody {
    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) };
        if this.cancelled.as_mut().poll(cx).is_ready() {
            this.inner = None;
            return Poll::Ready(Some(Err(axum::Error::new("the shutdown deadline has passed"))));
        }
        Pin::new(inner).poll_frame(cx)
    }

    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)
    }
}

/// Registers the handlers now, so a failure is reported before the server starts.
/// The returned future completes on SIGTERM or Ctrl-C.
pub(crate) fn os_shutdown_signal() -> Result<impl Future<Output = ()> + Send + 'static, Error> {
    let setup_error = |source: std::io::Error| {
        Error::new(ErrorKind::Serve, "failed to install the shutdown signal handler").with_source(source)
    };
    #[cfg(unix)]
    let (mut interrupt, mut terminate) = {
        use tokio::signal::unix::{SignalKind, signal};
        (signal(SignalKind::interrupt()).map_err(setup_error)?, signal(SignalKind::terminate()).map_err(setup_error)?)
    };
    #[cfg(windows)]
    let (mut interrupt, mut terminate) = {
        use tokio::signal::windows::{ctrl_c, ctrl_close};
        (ctrl_c().map_err(setup_error)?, ctrl_close().map_err(setup_error)?)
    };
    Ok(async move {
        tokio::select! {
            _ = interrupt.recv() => {}
            _ = terminate.recv() => {}
        }
        tracing::info!("shutdown signal received");
    })
}

#[cfg(test)]
mod tests {
    use std::ffi::OsStr;

    use axum::routing::get;
    use tokio::sync::mpsc;
    use tower::ServiceExt;

    use super::*;

    /// Reports when it is dropped.
    struct Flag(mpsc::UnboundedSender<()>);

    impl Drop for Flag {
        fn drop(&mut self) {
            let _ = self.0.send(());
        }
    }

    #[tokio::test]
    async fn cancellation_ends_a_running_handler_and_a_body_that_is_being_sent() {
        let (dropped_tx, mut dropped) = mpsc::unbounded_channel();
        let (entered_tx, mut entered) = mpsc::unbounded_channel();
        let (handler_flag, stream_flag) = (dropped_tx.clone(), dropped_tx);
        let routes = axum::Router::new()
            .route(
                "/handler",
                get(move || {
                    let (flag, entered) = (Flag(handler_flag.clone()), entered_tx.clone());
                    async move {
                        let _flag = flag;
                        let _ = entered.send(());
                        std::future::pending::<()>().await;
                    }
                }),
            )
            .route(
                "/stream",
                get(move || {
                    let flag = Flag(stream_flag.clone());
                    async move {
                        Body::from_stream(futures_util::stream::poll_fn(move |_| {
                            let _held = &flag;
                            Poll::<Option<Result<Bytes, std::io::Error>>>::Pending
                        }))
                    }
                }),
            );
        let request = |path: &str, version| Request::get(path).version(version).body(Body::empty()).unwrap();

        // A handler that does not return. Only HTTP/1 has a `Connection` header.
        for (version, connection) in [(Version::HTTP_11, Some("close")), (Version::HTTP_2, None)] {
            let (cancel, cancelled) = watch::channel(false);
            let reply = tokio::spawn(cancellable(routes.clone(), cancelled).oneshot(request("/handler", version)));
            entered.recv().await.unwrap();
            assert!(dropped.try_recv().is_err());
            cancel.send(true).unwrap();
            let response = reply.await.unwrap().unwrap();
            assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
            assert_eq!(response.headers().get(CONNECTION).map(|value| value.to_str().unwrap()), connection);
            assert_eq!(dropped.recv().await, Some(()));
        }

        // A stream that does not end. A dropped sender cancels like a sent `true`.
        let (cancel, cancelled) = watch::channel(false);
        let response = cancellable(routes, cancelled).oneshot(request("/stream", Version::HTTP_11)).await.unwrap();
        assert_eq!(response.status(), StatusCode::OK);
        let read = tokio::spawn(axum::body::to_bytes(response.into_body(), usize::MAX));
        tokio::task::yield_now().await;
        assert!(dropped.try_recv().is_err());
        drop(cancel);
        assert!(read.await.unwrap().is_err());
        assert_eq!(dropped.recv().await, Some(()));
    }

    #[test]
    fn timeout_message_names_only_the_work_that_outlived_the_grace_period() {
        let cases = [
            (true, 0, "requests in flight were cancelled"),
            (false, 1, "1 tracked background task is still active"),
            (false, 2, "2 tracked background tasks are still active"),
            (true, 3, "requests in flight were cancelled and 3 tracked background tasks are still active"),
        ];
        for (requests_cancelled, active_tasks, causes) in cases {
            let message = timeout_message(Duration::from_secs(3), requests_cancelled, active_tasks);
            assert_eq!(message, format!("shutdown did not finish within 3s: {causes}"));
        }
    }

    #[test]
    fn bind_rule() {
        let cases = [
            (false, None, Ipv4Addr::LOCALHOST),
            (false, Some(""), Ipv4Addr::LOCALHOST),
            (false, Some("1"), Ipv4Addr::UNSPECIFIED),
            (true, None, Ipv4Addr::UNSPECIFIED),
            (true, Some(""), Ipv4Addr::UNSPECIFIED),
        ];
        for (dockerenv, variable, ip) in cases {
            let addr = bind_addr(dockerenv, variable.map(OsStr::new));
            assert_eq!(addr, SocketAddr::from((ip, 8080)), "dockerenv={dockerenv} DOCKER_CONTAINER={variable:?}");
        }
    }
}