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
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
//! HTTP server for hosting an agent on AgentCore Runtime.
//!
//! [`BedrockAgentCoreApp`] serves the two routes of the
//! [Runtime HTTP contract](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/runtime-http-protocol-contract.html):
//!
//! - `POST /invocations` parses the JSON body and calls the invocation handler.
//! - `GET /ping` reports health: `Healthy`, or `HealthyBusy` while background work
//!   is tracked. See [`crate::tasks`] and [`Builder::ping`].
//!
//! With [`Builder::warmup_hook`] it also serves the build warmup hook, as `POST` on
//! the path that you choose. See [`WarmupHook`] for its requests and replies.
//!
//! # Invocation requests
//!
//! The server takes these steps in order. The first failure decides the reply.
//!
//! 1. Read the body. A body over the limit gets `413`. A `Content-Encoding` other than
//!    `identity` gets `415`. The `Content-Type` header is not checked.
//! 2. Parse the body as JSON. A failure gets `400 {"error": "Invalid JSON", "details": ..}`.
//! 3. Find the session ID in the `X-Amzn-Bedrock-AgentCore-Runtime-Session-Id` header,
//!    then in a top-level `sessionId` string of the body. Empty values do not count.
//!    A request without one gets `400`.
//! 4. Decode the body into the handler's request type. A failure gets
//!    `400 {"error": "Invalid request body format", "details": ..}`.
//! 5. Call the handler. An `Err` gets `500 {"error": <Display text of the error>}` and
//!    a panic gets `500 {"error": "Internal error"}`.
//! 6. Encode the handler's value by the `Accept` header, or send its stream as
//!    Server-Sent Events. See [`Response`].
//!
//! Every error reply of the steps above is a JSON object with an `error` string, and
//! so is the `404` for an unknown path. A known path with another method gets `405`
//! with an `Allow` header and an empty body.

mod body;
mod extract;
mod handler;
mod headers;
mod invocations;
mod ping;
mod response;
mod serve;
#[cfg(test)]
mod tests;
mod warmup;

use std::{any::Any, convert::Infallible, fmt, net::SocketAddr, time::Duration};

use axum::{
    Json, Router,
    extract::{DefaultBodyLimit, Request, State},
    middleware,
    response::IntoResponse,
    routing::{Route, get, post},
};
use serde_json::{Value, json};
use tower_layer::Layer;
use tower_service::Service;

pub use self::{
    handler::InvocationHandler,
    ping::PingStatus,
    response::{IntoInvocationResponse, Response},
    warmup::WarmupHook,
};
use crate::{Error, ErrorKind, tasks::AsyncTasks};

const DEFAULT_BODY_LIMIT: usize = 1024 * 1024;

#[derive(Clone)]
struct AppState {
    handler: handler::Erased,
    ping: ping::PingState,
    tasks: AsyncTasks,
    workload_identity_contexts: crate::context::WorkloadIdentityContexts,
    stream_heartbeat: Duration,
    body_limit: usize,
    in_flight: invocations::InFlight,
    runtime: serve::AppRuntime,
}

/// Configures a [`BedrockAgentCoreApp`]. Create one with [`BedrockAgentCoreApp::builder`].
#[must_use]
pub struct Builder {
    handler: Option<handler::Erased>,
    ping: Option<ping::PingHandler>,
    bind: Option<SocketAddr>,
    body_limit: usize,
    stream_heartbeat: Duration,
    shutdown_grace: Duration,
    routes: Vec<Router>,
    layers: Vec<Box<dyn Fn(Router) -> Router + Send + Sync>>,
    warmup_hook: Option<WarmupHook>,
}

impl Builder {
    /// Sets the handler for `POST /invocations`. This setting is required.
    ///
    /// See [`InvocationHandler`] for the accepted function signatures.
    pub fn invocation<H, M>(mut self, handler: H) -> Self
    where
        H: InvocationHandler<M>,
    {
        self.handler = Some(handler.erase());
        self
    }

    /// Sets a function that decides the status of `GET /ping`.
    ///
    /// Without it the status is automatic: `HealthyBusy` while the app's
    /// [`AsyncTasks`] registry has an active task, otherwise `Healthy`. With it, the
    /// function returns a [`PingStatus`], which is used as it is, or `None`, which
    /// means the automatic status:
    ///
    /// ```
    /// # use std::sync::atomic::{AtomicBool, Ordering};
    /// # use bedrock_agentcore::runtime::{BedrockAgentCoreApp, PingStatus};
    /// static INDEXING: AtomicBool = AtomicBool::new(false);
    ///
    /// # let builder = BedrockAgentCoreApp::builder();
    /// // Busy while the index is built, otherwise busy while a task is tracked.
    /// builder.ping(|| INDEXING.load(Ordering::Relaxed).then_some(PingStatus::HealthyBusy));
    /// ```
    ///
    /// The function runs for every ping, so it must return at once and must not
    /// block. If it panics, the server uses the automatic status. It logs a warning
    /// when the function starts to panic, not for each ping. The panic hook of the
    /// process still prints every panic, and AgentCore Runtime pings a session every
    /// two seconds, so the function should never panic.
    pub fn ping<F, S>(mut self, handler: F) -> Self
    where
        F: Fn() -> S + Send + Sync + 'static,
        S: Into<Option<PingStatus>>,
    {
        self.ping = Some(std::sync::Arc::new(move || handler().into()));
        self
    }

    /// Sets the address that [`BedrockAgentCoreApp::run`] listens on.
    ///
    /// The default is port 8080 on `0.0.0.0` inside a container and on `127.0.0.1`
    /// elsewhere. The server treats the process as running in a container when the file
    /// `/.dockerenv` exists or the `DOCKER_CONTAINER` environment variable is not empty.
    pub fn bind(mut self, addr: SocketAddr) -> Self {
        self.bind = Some(addr);
        self
    }

    /// Sets the largest accepted invocation body in bytes. The default is 1 MiB.
    ///
    /// AgentCore Runtime accepts larger payloads than this default.
    pub fn body_limit(mut self, bytes: usize) -> Self {
        self.body_limit = bytes;
        self
    }

    /// Sets how often a quiet [`Response::stream`] sends an SSE comment line to keep
    /// the connection open. The default is 30 seconds. The interval must be greater
    /// than zero. With `Duration::MAX` a stream sends no comment lines.
    ///
    /// Choose an interval that is shorter than the time your callers wait for a
    /// byte. The AWS CLI and boto3 wait 60 seconds by default. AgentCore Runtime
    /// ends a response that sends no byte for 15 minutes.
    ///
    /// The heartbeat starts when the handler has returned the stream. While the
    /// handler runs, the server sends nothing. [`Response::stream`] shows how to do
    /// slow work inside the stream.
    ///
    /// The setting applies to `POST /invocations` and to the routes given to
    /// [`routes`](Self::routes). A [`Response::stream`] that is returned from a
    /// route outside the app uses the default.
    pub fn stream_heartbeat(mut self, interval: Duration) -> Self {
        self.stream_heartbeat = interval;
        self
    }

    /// Sets how long a shutdown waits for requests in flight and tracked background
    /// tasks. The default is 8 seconds. See [`BedrockAgentCoreApp::run`].
    ///
    /// AgentCore Runtime ends the process a short time after it sends SIGTERM: about
    /// 10 seconds in tests against the service. The default leaves the server time
    /// to cancel the requests in flight, to send their callers the `503` and to
    /// write the warnings that name the unfinished work. With a grace period of 10
    /// seconds or more the process ends first, and none of that happens.
    ///
    /// With `Duration::MAX` the shutdown has no deadline and waits until everything
    /// has finished.
    pub fn shutdown_grace(mut self, grace: Duration) -> Self {
        self.shutdown_grace = grace;
        self
    }

    /// Adds routes of your own to the app. Call it more than once to add more.
    ///
    /// Handlers of these routes can take [`RequestContext`](crate::RequestContext) as
    /// an argument and can read it with [`context::current`](crate::context::current),
    /// when the request carries the session header. Supply the state of `routes` with
    /// `Router::with_state` before you pass it.
    ///
    /// With routes of your own, the app has no JSON `404` for unknown paths: the
    /// fallback of `routes` applies, or axum's empty `404`. At most one of the routers
    /// that you give can have a fallback. [`BedrockAgentCoreApp::router`] describes how
    /// that fallback combines with another router.
    pub fn routes(mut self, routes: Router) -> Self {
        // The routers are combined in `build`, which reports a conflict as an error.
        self.routes.push(routes);
        self
    }

    /// Wraps the whole app in a tower layer, as `axum::Router::layer` does for a
    /// router. Use it for middleware such as request tracing, an authorization check
    /// or metrics.
    ///
    /// ```no_run
    /// use axum::{extract::Request, middleware::{self, Next}, response::Response};
    /// use bedrock_agentcore::runtime::BedrockAgentCoreApp;
    ///
    /// async fn timed(request: Request, next: Next) -> Response {
    ///     let started = std::time::Instant::now();
    ///     let response = next.run(request).await;
    ///     tracing::info!(elapsed = ?started.elapsed(), status = %response.status(), "request");
    ///     response
    /// }
    ///
    /// # async fn run() -> Result<(), bedrock_agentcore::Error> {
    /// BedrockAgentCoreApp::builder()
    ///     .invocation(|payload: serde_json::Value| async move { Ok::<_, std::convert::Infallible>(payload) })
    ///     .layer(middleware::from_fn(timed))
    ///     .build()?
    ///     .run()
    ///     .await
    /// # }
    /// ```
    ///
    /// # What the layer wraps
    ///
    /// The layer wraps every reply of the app: `POST /invocations`, `GET /ping`, the
    /// routes given to [`routes`](Self::routes) and their fallback, the JSON `404`
    /// for an unknown path and the `405` for a wrong method. It applies when the app
    /// serves itself and to the router that [`BedrockAgentCoreApp::router`] returns.
    /// [`BedrockAgentCoreApp::run`] keeps its bind rule and its shutdown: a request
    /// that is still inside the layer at the end of the grace period is cancelled
    /// like any other request.
    ///
    /// AgentCore Runtime calls `GET /ping` without the headers of your caller. A
    /// layer that rejects such requests, for example an authorization check, makes
    /// the agent unhealthy. Let `/ping` pass. The same holds for the path of the
    /// [warmup hook](Self::warmup_hook), which the service also calls without them.
    ///
    /// # When the layer runs
    ///
    /// The layer runs after the route is selected and before the app reads the
    /// request. A header that the layer changes is the header that the app reads:
    /// a layer that sets the session header sets the session ID of the invocation.
    /// A layer that changes the URI does not send the request to another route.
    ///
    /// The app creates the context of the request after the layer has passed the
    /// request on, so the layer cannot read it. If the caller of the router has
    /// already established a context,
    /// [`context::current`](crate::context::current) can return that outer context
    /// inside the layer. The layer can read the request headers.
    ///
    /// # Order
    ///
    /// With more than one layer, the layer added last runs first on the request and
    /// last on the response. The order of `layer` and [`routes`](Self::routes) calls
    /// does not matter: every layer wraps every route.
    ///
    /// # Requirements for the layer
    ///
    /// The bounds are those of `axum::Router::layer`, so a layer that works on an
    /// axum router works here.
    ///
    /// The app can call `Layer::layer` more than once for one call of this method,
    /// as axum does for each route. Keep state that all copies must share behind an
    /// `Arc` inside the layer, and give the construction of the service no effect
    /// that must happen only once.
    ///
    /// The error type of the layer's service must be `Infallible`. For a layer whose
    /// service can fail, such as a timeout, put
    /// `axum::error_handling::HandleErrorLayer` around it to turn the error into a
    /// response.
    pub fn layer<L>(mut self, layer: L) -> Self
    where
        L: Layer<Route> + Clone + Send + Sync + 'static,
        L::Service: Service<Request> + Clone + Send + Sync + 'static,
        <L::Service as Service<Request>>::Response: IntoResponse + 'static,
        <L::Service as Service<Request>>::Error: Into<Infallible> + 'static,
        <L::Service as Service<Request>>::Future: Send + 'static,
    {
        self.layers.push(Box::new(move |router| router.layer(layer.clone())));
        self
    }

    /// Serves the build warmup hook of AgentCore Runtime as `POST` on the path of
    /// `hook`, on the same port as the other routes of the app. A later call replaces
    /// the hook of an earlier one.
    ///
    /// The path must equal `hooksConfiguration.build.warmup.action.httpPost.path` of
    /// the agent runtime, and `httpPost.port` must be unset or equal to the serving
    /// port. See [`WarmupHook`] for what the handlers are for and how the route
    /// replies.
    ///
    /// The hook route is not one of the routes of [`routes`](Self::routes): its
    /// handlers get no [`RequestContext`](crate::RequestContext), and the app keeps
    /// its JSON `404` for unknown paths.
    pub fn warmup_hook(mut self, hook: WarmupHook) -> Self {
        self.warmup_hook = Some(hook);
        self
    }

    /// Builds the app.
    ///
    /// # Errors
    ///
    /// Returns [`ErrorKind::InvalidConfig`] in these cases:
    ///
    /// - No invocation handler is set.
    /// - The stream heartbeat interval is zero.
    /// - The routers given to [`routes`](Self::routes) cannot be combined: a route has
    ///   the path and method of another route, or two of the routers have a fallback.
    /// - The path of the [warmup hook](Self::warmup_hook) breaks one of its rules, or
    ///   the hook has the path and method of another route.
    /// - A layer given to [`layer`](Self::layer) panics while it is applied.
    pub fn build(self) -> Result<BedrockAgentCoreApp, Error> {
        let handler = self.handler.ok_or_else(|| {
            Error::new(ErrorKind::InvalidConfig, "an invocation handler is required: call Builder::invocation")
        })?;
        if self.stream_heartbeat.is_zero() {
            return Err(Error::new(
                ErrorKind::InvalidConfig,
                "the stream heartbeat interval must be greater than zero",
            ));
        }
        if let Some(hook) = &self.warmup_hook {
            hook.validate()?;
        }
        let tasks = AsyncTasks::new();
        let state = AppState {
            handler,
            ping: ping::PingState::new(self.ping, tasks.clone()),
            tasks,
            workload_identity_contexts: Default::default(),
            stream_heartbeat: self.stream_heartbeat,
            body_limit: self.body_limit,
            in_flight: Default::default(),
            runtime: Default::default(),
        };
        let (body_limit, routes, layers, warmup_hook) = (self.body_limit, self.routes, self.layers, self.warmup_hook);
        let has_routes = !routes.is_empty();
        // axum panics when two routes have the same path and method, and when two
        // merged routers both have a fallback.
        let router = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            let sdk = Router::new()
                .route("/invocations", post(invocations::invocations))
                .layer(DefaultBodyLimit::max(body_limit))
                .route("/ping", get(ping));
            let sdk = match warmup_hook {
                Some(hook) => hook.add_route(sdk),
                None => sdk,
            }
            .with_state(state.clone());
            match routes.into_iter().reduce(Router::merge) {
                Some(routes) => {
                    sdk.merge(routes.layer(middleware::from_fn_with_state(state.clone(), extract::route_context)))
                }
                None => sdk,
            }
        }))
        .map_err(|panic| rejected("the routes cannot be combined", panic))?;
        // A fallback that is set after a layer is not wrapped by that layer. The JSON
        // 404 is therefore set before the layers are applied, and the served router
        // and the exported router are built apart when only one of them has it.
        let (served, router) = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            // Without its state, axum constructs the layer of a route at each request.
            let layered =
                |router: Router| layers.iter().fold(router, |router, layer| layer(router)).with_state::<()>(());
            if has_routes {
                let router = layered(router);
                (router.clone(), router)
            } else {
                (layered(router.clone().fallback(invocations::not_found)), layered(router))
            }
        }))
        .map_err(|panic| rejected("a layer could not be applied", panic))?;
        Ok(BedrockAgentCoreApp {
            state,
            served,
            router,
            bind: self.bind,
            body_limit,
            shutdown_grace: self.shutdown_grace,
        })
    }
}

impl fmt::Debug for Builder {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Builder")
            .field("handler_set", &self.handler.is_some())
            .field("bind", &self.bind)
            .field("body_limit", &self.body_limit)
            .field("layers", &self.layers.len())
            .finish()
    }
}

/// The configuration error for a panic of axum or of a layer during `build`.
fn rejected(stage: &str, panic: Box<dyn Any + Send>) -> Error {
    Error::new(ErrorKind::InvalidConfig, format!("{stage}: {}", handler::panic_text(panic.as_ref())))
}

/// An HTTP server that implements the AgentCore Runtime contract.
///
/// See the [module documentation](self) for the request handling rules.
pub struct BedrockAgentCoreApp {
    state: AppState,
    served: Router,
    router: Router,
    bind: Option<SocketAddr>,
    body_limit: usize,
    shutdown_grace: Duration,
}

impl BedrockAgentCoreApp {
    /// Starts the configuration of an app.
    pub fn builder() -> Builder {
        Builder {
            handler: None,
            ping: None,
            bind: None,
            body_limit: DEFAULT_BODY_LIMIT,
            stream_heartbeat: response::DEFAULT_STREAM_HEARTBEAT,
            shutdown_grace: Duration::from_secs(8),
            routes: Vec::new(),
            layers: Vec::new(),
            warmup_hook: None,
        }
    }

    /// Binds the configured address and serves until the process receives SIGTERM or
    /// Ctrl-C.
    ///
    /// # Threads
    ///
    /// The server reads requests and answers `GET /ping` on a thread of its own.
    /// The invocation handler, the stream of its reply, the routes given to
    /// [`Builder::routes`] and the warmup handlers run on the tokio runtime that
    /// calls this method, as tasks of that runtime. A handler that blocks its thread
    /// therefore does not stop the health check, as in the Python SDK. It still
    /// delays the other work of that runtime thread, so blocking work belongs in
    /// `tokio::task::spawn_blocking`. A layer given to [`Builder::layer`] runs on the
    /// server thread and must not block.
    ///
    /// The same holds for the `serve` methods. A router from [`router`](Self::router)
    /// that you serve yourself runs all of its code in the task of the connection.
    ///
    /// # Shutdown
    ///
    /// On the signal the server stops accepting connections. It logs one warning for
    /// each invocation in flight, with its request ID and session ID, and one line
    /// with the tracked background tasks. Requests in flight, streams and tracked
    /// background tasks ([`crate::tasks`]) then get the grace period to finish
    /// ([`Builder::shutdown_grace`], 8 seconds by default). The grace period starts
    /// at the signal, not at startup.
    ///
    /// When everything finishes in time, this method returns `Ok`. Otherwise, at the
    /// end of the grace period the server cancels the requests that are still in
    /// flight, on all routes. A handler that is still running is dropped and its
    /// client gets a `503` reply. A response body that is still being sent fails, and
    /// its stream is dropped. The server then waits up to half a second for its
    /// connections to close and returns [`ErrorKind::ShutdownTimeout`].
    ///
    /// A caller behind AgentCore Runtime does not see a reply that the agent cuts. In
    /// tests against the service it received such a reply as a complete one.
    ///
    /// Cancellation takes effect when the handler or the stream is next polled. Two
    /// kinds of work can therefore outlast the return of this method, until they end
    /// or the process exits:
    ///
    /// - A handler, a stream or a destructor that blocks its thread without yielding.
    /// - A stream whose client has stopped reading. The server does not poll the
    ///   stream while it cannot write, so the stream is dropped only when the
    ///   connection closes.
    ///
    /// The server also cannot stop work that it does not own: tasks that your code
    /// spawned, including tracked background tasks, and blocking work that has
    /// started.
    ///
    /// # Errors
    ///
    /// Returns [`ErrorKind::Bind`] when the address cannot be bound. Returns
    /// [`ErrorKind::Serve`] when the signal handlers cannot be installed or the server
    /// stops with an I/O error. Returns [`ErrorKind::ShutdownTimeout`] as described
    /// above.
    pub async fn run(self) -> Result<(), Error> {
        let signal = serve::os_shutdown_signal()?;
        let listener = serve::bind(self.bind.unwrap_or_else(serve::default_bind_addr)).await?;
        self.serve_until(listener, signal).await
    }

    /// Serves on a listener that the caller has bound, until the process receives
    /// SIGTERM or Ctrl-C. Shutdown works as described for [`run`](Self::run).
    ///
    /// Use it to listen on an ephemeral port: bind port 0 and read the address from
    /// the listener before calling this method.
    ///
    /// # Errors
    ///
    /// Returns [`ErrorKind::Serve`] when the signal handlers cannot be installed or
    /// the server stops with an I/O error, and [`ErrorKind::ShutdownTimeout`] as
    /// described for [`run`](Self::run).
    pub async fn serve(self, listener: tokio::net::TcpListener) -> Result<(), Error> {
        let signal = serve::os_shutdown_signal()?;
        self.serve_until(listener, signal).await
    }

    /// Serves on a listener that the caller has bound, until `shutdown` completes.
    /// Shutdown then works as described for [`run`](Self::run). This method installs
    /// no signal handlers.
    ///
    /// # Errors
    ///
    /// Returns [`ErrorKind::Serve`] when the server stops with an I/O error, and
    /// [`ErrorKind::ShutdownTimeout`] as described for [`run`](Self::run).
    pub async fn serve_with_shutdown(
        self,
        listener: tokio::net::TcpListener,
        shutdown: impl Future<Output = ()> + Send + 'static,
    ) -> Result<(), Error> {
        self.serve_until(listener, shutdown).await
    }

    async fn serve_until(
        self,
        listener: tokio::net::TcpListener,
        signal: impl Future<Output = ()> + Send + 'static,
    ) -> Result<(), Error> {
        let router = self.standalone_router();
        let AppState { tasks, in_flight, runtime, .. } = self.state;
        let shutdown = serve::Shutdown { grace: self.shutdown_grace, tasks, in_flight, runtime };
        serve::serve(listener, router, signal, shutdown).await
    }

    /// The router that the app serves by itself. An app without routes of the
    /// customer answers unknown paths with the JSON 404.
    fn standalone_router(&self) -> Router {
        self.served.clone()
    }

    /// The routes of the app as an axum router: `POST /invocations`, `GET /ping`, the
    /// [warmup hook](Builder::warmup_hook) and the routes given to [`Builder::routes`]. Use it to mount the app in a server
    /// that you run yourself, for example with `Router::merge`, or to wrap it in
    /// middleware with `Router::layer`. A layer that you add wraps the app's routes,
    /// so it sees each request before the app does.
    ///
    /// The layers given to [`Builder::layer`] are part of this router. They wrap what
    /// the router holds: its routes and a fallback given through [`Builder::routes`].
    /// They do not wrap a route or a fallback that you add to the router afterwards,
    /// or the fallback of a router that you merge it into.
    ///
    /// # Fallback
    ///
    /// The JSON `404` that the app sends for unknown paths when it serves itself is
    /// not part of this router. A fallback that you gave through
    /// [`Builder::routes`] is part of it.
    ///
    /// axum cannot merge two routers that both have a fallback: `Router::merge`
    /// panics. So combine the routers in one of these ways:
    ///
    /// - Give the app no fallback, and set one on the router that you merge it into.
    /// - Give the app the fallback through [`Builder::routes`], and merge its router
    ///   into a router without one. The app's fallback then answers every unknown
    ///   path of the combined router.
    ///
    /// # Serving
    ///
    /// Shutdown and the listen address are yours to handle when you serve this
    /// router yourself: the settings [`Builder::bind`] and
    /// [`Builder::shutdown_grace`] apply only to [`run`](Self::run) and the `serve`
    /// methods.
    pub fn router(&self) -> Router {
        self.router.clone()
    }

    /// The registry of background work of this app. Every invocation's
    /// [`RequestContext::tasks`](crate::RequestContext::tasks) returns the same registry.
    pub fn tasks(&self) -> &AsyncTasks {
        &self.state.tasks
    }
}

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

async fn ping(State(state): State<AppState>) -> Json<Value> {
    let (status, changed) = state.ping.current();
    Json(json!({ "status": status.as_str(), "time_of_last_update": changed }))
}