bedrock_agentcore/runtime/mod.rs
1//! HTTP server for hosting an agent on AgentCore Runtime.
2//!
3//! [`BedrockAgentCoreApp`] serves the two routes of the
4//! [Runtime HTTP contract](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/runtime-http-protocol-contract.html):
5//!
6//! - `POST /invocations` parses the JSON body and calls the invocation handler.
7//! - `GET /ping` reports health: `Healthy`, or `HealthyBusy` while background work
8//! is tracked. See [`crate::tasks`] and [`Builder::ping`].
9//!
10//! With [`Builder::warmup_hook`] it also serves the build warmup hook, as `POST` on
11//! the path that you choose. See [`WarmupHook`] for its requests and replies.
12//!
13//! # Invocation requests
14//!
15//! The server takes these steps in order. The first failure decides the reply.
16//!
17//! 1. Read the body. A body over the limit gets `413`. A `Content-Encoding` other than
18//! `identity` gets `415`. The `Content-Type` header is not checked.
19//! 2. Parse the body as JSON. A failure gets `400 {"error": "Invalid JSON", "details": ..}`.
20//! 3. Find the session ID in the `X-Amzn-Bedrock-AgentCore-Runtime-Session-Id` header,
21//! then in a top-level `sessionId` string of the body. Empty values do not count.
22//! A request without one gets `400`.
23//! 4. Decode the body into the handler's request type. A failure gets
24//! `400 {"error": "Invalid request body format", "details": ..}`.
25//! 5. Call the handler. An `Err` gets `500 {"error": <Display text of the error>}` and
26//! a panic gets `500 {"error": "Internal error"}`.
27//! 6. Encode the handler's value by the `Accept` header, or send its stream as
28//! Server-Sent Events. See [`Response`].
29//!
30//! Every error reply of the steps above is a JSON object with an `error` string, and
31//! so is the `404` for an unknown path. A known path with another method gets `405`
32//! with an `Allow` header and an empty body.
33
34mod body;
35mod extract;
36mod handler;
37mod headers;
38mod invocations;
39mod ping;
40mod response;
41mod serve;
42#[cfg(test)]
43mod tests;
44mod warmup;
45
46use std::{any::Any, convert::Infallible, fmt, net::SocketAddr, time::Duration};
47
48use axum::{
49 Json, Router,
50 extract::{DefaultBodyLimit, Request, State},
51 middleware,
52 response::IntoResponse,
53 routing::{Route, get, post},
54};
55use serde_json::{Value, json};
56use tower_layer::Layer;
57use tower_service::Service;
58
59pub use self::{
60 handler::InvocationHandler,
61 ping::PingStatus,
62 response::{IntoInvocationResponse, Response},
63 warmup::WarmupHook,
64};
65use crate::{Error, ErrorKind, tasks::AsyncTasks};
66
67const DEFAULT_BODY_LIMIT: usize = 1024 * 1024;
68
69#[derive(Clone)]
70struct AppState {
71 handler: handler::Erased,
72 ping: ping::PingState,
73 tasks: AsyncTasks,
74 workload_identity_contexts: crate::context::WorkloadIdentityContexts,
75 stream_heartbeat: Duration,
76 body_limit: usize,
77 in_flight: invocations::InFlight,
78 runtime: serve::AppRuntime,
79}
80
81/// Configures a [`BedrockAgentCoreApp`]. Create one with [`BedrockAgentCoreApp::builder`].
82#[must_use]
83pub struct Builder {
84 handler: Option<handler::Erased>,
85 ping: Option<ping::PingHandler>,
86 bind: Option<SocketAddr>,
87 body_limit: usize,
88 stream_heartbeat: Duration,
89 shutdown_grace: Duration,
90 routes: Vec<Router>,
91 layers: Vec<Box<dyn Fn(Router) -> Router + Send + Sync>>,
92 warmup_hook: Option<WarmupHook>,
93}
94
95impl Builder {
96 /// Sets the handler for `POST /invocations`. This setting is required.
97 ///
98 /// See [`InvocationHandler`] for the accepted function signatures.
99 pub fn invocation<H, M>(mut self, handler: H) -> Self
100 where
101 H: InvocationHandler<M>,
102 {
103 self.handler = Some(handler.erase());
104 self
105 }
106
107 /// Sets a function that decides the status of `GET /ping`.
108 ///
109 /// Without it the status is automatic: `HealthyBusy` while the app's
110 /// [`AsyncTasks`] registry has an active task, otherwise `Healthy`. With it, the
111 /// function returns a [`PingStatus`], which is used as it is, or `None`, which
112 /// means the automatic status:
113 ///
114 /// ```
115 /// # use std::sync::atomic::{AtomicBool, Ordering};
116 /// # use bedrock_agentcore::runtime::{BedrockAgentCoreApp, PingStatus};
117 /// static INDEXING: AtomicBool = AtomicBool::new(false);
118 ///
119 /// # let builder = BedrockAgentCoreApp::builder();
120 /// // Busy while the index is built, otherwise busy while a task is tracked.
121 /// builder.ping(|| INDEXING.load(Ordering::Relaxed).then_some(PingStatus::HealthyBusy));
122 /// ```
123 ///
124 /// The function runs for every ping, so it must return at once and must not
125 /// block. If it panics, the server uses the automatic status. It logs a warning
126 /// when the function starts to panic, not for each ping. The panic hook of the
127 /// process still prints every panic, and AgentCore Runtime pings a session every
128 /// two seconds, so the function should never panic.
129 pub fn ping<F, S>(mut self, handler: F) -> Self
130 where
131 F: Fn() -> S + Send + Sync + 'static,
132 S: Into<Option<PingStatus>>,
133 {
134 self.ping = Some(std::sync::Arc::new(move || handler().into()));
135 self
136 }
137
138 /// Sets the address that [`BedrockAgentCoreApp::run`] listens on.
139 ///
140 /// The default is port 8080 on `0.0.0.0` inside a container and on `127.0.0.1`
141 /// elsewhere. The server treats the process as running in a container when the file
142 /// `/.dockerenv` exists or the `DOCKER_CONTAINER` environment variable is not empty.
143 pub fn bind(mut self, addr: SocketAddr) -> Self {
144 self.bind = Some(addr);
145 self
146 }
147
148 /// Sets the largest accepted invocation body in bytes. The default is 1 MiB.
149 ///
150 /// AgentCore Runtime accepts larger payloads than this default.
151 pub fn body_limit(mut self, bytes: usize) -> Self {
152 self.body_limit = bytes;
153 self
154 }
155
156 /// Sets how often a quiet [`Response::stream`] sends an SSE comment line to keep
157 /// the connection open. The default is 30 seconds. The interval must be greater
158 /// than zero. With `Duration::MAX` a stream sends no comment lines.
159 ///
160 /// Choose an interval that is shorter than the time your callers wait for a
161 /// byte. The AWS CLI and boto3 wait 60 seconds by default. AgentCore Runtime
162 /// ends a response that sends no byte for 15 minutes.
163 ///
164 /// The heartbeat starts when the handler has returned the stream. While the
165 /// handler runs, the server sends nothing. [`Response::stream`] shows how to do
166 /// slow work inside the stream.
167 ///
168 /// The setting applies to `POST /invocations` and to the routes given to
169 /// [`routes`](Self::routes). A [`Response::stream`] that is returned from a
170 /// route outside the app uses the default.
171 pub fn stream_heartbeat(mut self, interval: Duration) -> Self {
172 self.stream_heartbeat = interval;
173 self
174 }
175
176 /// Sets how long a shutdown waits for requests in flight and tracked background
177 /// tasks. The default is 8 seconds. See [`BedrockAgentCoreApp::run`].
178 ///
179 /// AgentCore Runtime ends the process a short time after it sends SIGTERM: about
180 /// 10 seconds in tests against the service. The default leaves the server time
181 /// to cancel the requests in flight, to send their callers the `503` and to
182 /// write the warnings that name the unfinished work. With a grace period of 10
183 /// seconds or more the process ends first, and none of that happens.
184 ///
185 /// With `Duration::MAX` the shutdown has no deadline and waits until everything
186 /// has finished.
187 pub fn shutdown_grace(mut self, grace: Duration) -> Self {
188 self.shutdown_grace = grace;
189 self
190 }
191
192 /// Adds routes of your own to the app. Call it more than once to add more.
193 ///
194 /// Handlers of these routes can take [`RequestContext`](crate::RequestContext) as
195 /// an argument and can read it with [`context::current`](crate::context::current),
196 /// when the request carries the session header. Supply the state of `routes` with
197 /// `Router::with_state` before you pass it.
198 ///
199 /// With routes of your own, the app has no JSON `404` for unknown paths: the
200 /// fallback of `routes` applies, or axum's empty `404`. At most one of the routers
201 /// that you give can have a fallback. [`BedrockAgentCoreApp::router`] describes how
202 /// that fallback combines with another router.
203 pub fn routes(mut self, routes: Router) -> Self {
204 // The routers are combined in `build`, which reports a conflict as an error.
205 self.routes.push(routes);
206 self
207 }
208
209 /// Wraps the whole app in a tower layer, as `axum::Router::layer` does for a
210 /// router. Use it for middleware such as request tracing, an authorization check
211 /// or metrics.
212 ///
213 /// ```no_run
214 /// use axum::{extract::Request, middleware::{self, Next}, response::Response};
215 /// use bedrock_agentcore::runtime::BedrockAgentCoreApp;
216 ///
217 /// async fn timed(request: Request, next: Next) -> Response {
218 /// let started = std::time::Instant::now();
219 /// let response = next.run(request).await;
220 /// tracing::info!(elapsed = ?started.elapsed(), status = %response.status(), "request");
221 /// response
222 /// }
223 ///
224 /// # async fn run() -> Result<(), bedrock_agentcore::Error> {
225 /// BedrockAgentCoreApp::builder()
226 /// .invocation(|payload: serde_json::Value| async move { Ok::<_, std::convert::Infallible>(payload) })
227 /// .layer(middleware::from_fn(timed))
228 /// .build()?
229 /// .run()
230 /// .await
231 /// # }
232 /// ```
233 ///
234 /// # What the layer wraps
235 ///
236 /// The layer wraps every reply of the app: `POST /invocations`, `GET /ping`, the
237 /// routes given to [`routes`](Self::routes) and their fallback, the JSON `404`
238 /// for an unknown path and the `405` for a wrong method. It applies when the app
239 /// serves itself and to the router that [`BedrockAgentCoreApp::router`] returns.
240 /// [`BedrockAgentCoreApp::run`] keeps its bind rule and its shutdown: a request
241 /// that is still inside the layer at the end of the grace period is cancelled
242 /// like any other request.
243 ///
244 /// AgentCore Runtime calls `GET /ping` without the headers of your caller. A
245 /// layer that rejects such requests, for example an authorization check, makes
246 /// the agent unhealthy. Let `/ping` pass. The same holds for the path of the
247 /// [warmup hook](Self::warmup_hook), which the service also calls without them.
248 ///
249 /// # When the layer runs
250 ///
251 /// The layer runs after the route is selected and before the app reads the
252 /// request. A header that the layer changes is the header that the app reads:
253 /// a layer that sets the session header sets the session ID of the invocation.
254 /// A layer that changes the URI does not send the request to another route.
255 ///
256 /// The app creates the context of the request after the layer has passed the
257 /// request on, so the layer cannot read it. If the caller of the router has
258 /// already established a context,
259 /// [`context::current`](crate::context::current) can return that outer context
260 /// inside the layer. The layer can read the request headers.
261 ///
262 /// # Order
263 ///
264 /// With more than one layer, the layer added last runs first on the request and
265 /// last on the response. The order of `layer` and [`routes`](Self::routes) calls
266 /// does not matter: every layer wraps every route.
267 ///
268 /// # Requirements for the layer
269 ///
270 /// The bounds are those of `axum::Router::layer`, so a layer that works on an
271 /// axum router works here.
272 ///
273 /// The app can call `Layer::layer` more than once for one call of this method,
274 /// as axum does for each route. Keep state that all copies must share behind an
275 /// `Arc` inside the layer, and give the construction of the service no effect
276 /// that must happen only once.
277 ///
278 /// The error type of the layer's service must be `Infallible`. For a layer whose
279 /// service can fail, such as a timeout, put
280 /// `axum::error_handling::HandleErrorLayer` around it to turn the error into a
281 /// response.
282 pub fn layer<L>(mut self, layer: L) -> Self
283 where
284 L: Layer<Route> + Clone + Send + Sync + 'static,
285 L::Service: Service<Request> + Clone + Send + Sync + 'static,
286 <L::Service as Service<Request>>::Response: IntoResponse + 'static,
287 <L::Service as Service<Request>>::Error: Into<Infallible> + 'static,
288 <L::Service as Service<Request>>::Future: Send + 'static,
289 {
290 self.layers.push(Box::new(move |router| router.layer(layer.clone())));
291 self
292 }
293
294 /// Serves the build warmup hook of AgentCore Runtime as `POST` on the path of
295 /// `hook`, on the same port as the other routes of the app. A later call replaces
296 /// the hook of an earlier one.
297 ///
298 /// The path must equal `hooksConfiguration.build.warmup.action.httpPost.path` of
299 /// the agent runtime, and `httpPost.port` must be unset or equal to the serving
300 /// port. See [`WarmupHook`] for what the handlers are for and how the route
301 /// replies.
302 ///
303 /// The hook route is not one of the routes of [`routes`](Self::routes): its
304 /// handlers get no [`RequestContext`](crate::RequestContext), and the app keeps
305 /// its JSON `404` for unknown paths.
306 pub fn warmup_hook(mut self, hook: WarmupHook) -> Self {
307 self.warmup_hook = Some(hook);
308 self
309 }
310
311 /// Builds the app.
312 ///
313 /// # Errors
314 ///
315 /// Returns [`ErrorKind::InvalidConfig`] in these cases:
316 ///
317 /// - No invocation handler is set.
318 /// - The stream heartbeat interval is zero.
319 /// - The routers given to [`routes`](Self::routes) cannot be combined: a route has
320 /// the path and method of another route, or two of the routers have a fallback.
321 /// - The path of the [warmup hook](Self::warmup_hook) breaks one of its rules, or
322 /// the hook has the path and method of another route.
323 /// - A layer given to [`layer`](Self::layer) panics while it is applied.
324 pub fn build(self) -> Result<BedrockAgentCoreApp, Error> {
325 let handler = self.handler.ok_or_else(|| {
326 Error::new(ErrorKind::InvalidConfig, "an invocation handler is required: call Builder::invocation")
327 })?;
328 if self.stream_heartbeat.is_zero() {
329 return Err(Error::new(
330 ErrorKind::InvalidConfig,
331 "the stream heartbeat interval must be greater than zero",
332 ));
333 }
334 if let Some(hook) = &self.warmup_hook {
335 hook.validate()?;
336 }
337 let tasks = AsyncTasks::new();
338 let state = AppState {
339 handler,
340 ping: ping::PingState::new(self.ping, tasks.clone()),
341 tasks,
342 workload_identity_contexts: Default::default(),
343 stream_heartbeat: self.stream_heartbeat,
344 body_limit: self.body_limit,
345 in_flight: Default::default(),
346 runtime: Default::default(),
347 };
348 let (body_limit, routes, layers, warmup_hook) = (self.body_limit, self.routes, self.layers, self.warmup_hook);
349 let has_routes = !routes.is_empty();
350 // axum panics when two routes have the same path and method, and when two
351 // merged routers both have a fallback.
352 let router = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
353 let sdk = Router::new()
354 .route("/invocations", post(invocations::invocations))
355 .layer(DefaultBodyLimit::max(body_limit))
356 .route("/ping", get(ping));
357 let sdk = match warmup_hook {
358 Some(hook) => hook.add_route(sdk),
359 None => sdk,
360 }
361 .with_state(state.clone());
362 match routes.into_iter().reduce(Router::merge) {
363 Some(routes) => {
364 sdk.merge(routes.layer(middleware::from_fn_with_state(state.clone(), extract::route_context)))
365 }
366 None => sdk,
367 }
368 }))
369 .map_err(|panic| rejected("the routes cannot be combined", panic))?;
370 // A fallback that is set after a layer is not wrapped by that layer. The JSON
371 // 404 is therefore set before the layers are applied, and the served router
372 // and the exported router are built apart when only one of them has it.
373 let (served, router) = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
374 // Without its state, axum constructs the layer of a route at each request.
375 let layered =
376 |router: Router| layers.iter().fold(router, |router, layer| layer(router)).with_state::<()>(());
377 if has_routes {
378 let router = layered(router);
379 (router.clone(), router)
380 } else {
381 (layered(router.clone().fallback(invocations::not_found)), layered(router))
382 }
383 }))
384 .map_err(|panic| rejected("a layer could not be applied", panic))?;
385 Ok(BedrockAgentCoreApp {
386 state,
387 served,
388 router,
389 bind: self.bind,
390 body_limit,
391 shutdown_grace: self.shutdown_grace,
392 })
393 }
394}
395
396impl fmt::Debug for Builder {
397 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
398 f.debug_struct("Builder")
399 .field("handler_set", &self.handler.is_some())
400 .field("bind", &self.bind)
401 .field("body_limit", &self.body_limit)
402 .field("layers", &self.layers.len())
403 .finish()
404 }
405}
406
407/// The configuration error for a panic of axum or of a layer during `build`.
408fn rejected(stage: &str, panic: Box<dyn Any + Send>) -> Error {
409 Error::new(ErrorKind::InvalidConfig, format!("{stage}: {}", handler::panic_text(panic.as_ref())))
410}
411
412/// An HTTP server that implements the AgentCore Runtime contract.
413///
414/// See the [module documentation](self) for the request handling rules.
415pub struct BedrockAgentCoreApp {
416 state: AppState,
417 served: Router,
418 router: Router,
419 bind: Option<SocketAddr>,
420 body_limit: usize,
421 shutdown_grace: Duration,
422}
423
424impl BedrockAgentCoreApp {
425 /// Starts the configuration of an app.
426 pub fn builder() -> Builder {
427 Builder {
428 handler: None,
429 ping: None,
430 bind: None,
431 body_limit: DEFAULT_BODY_LIMIT,
432 stream_heartbeat: response::DEFAULT_STREAM_HEARTBEAT,
433 shutdown_grace: Duration::from_secs(8),
434 routes: Vec::new(),
435 layers: Vec::new(),
436 warmup_hook: None,
437 }
438 }
439
440 /// Binds the configured address and serves until the process receives SIGTERM or
441 /// Ctrl-C.
442 ///
443 /// # Threads
444 ///
445 /// The server reads requests and answers `GET /ping` on a thread of its own.
446 /// The invocation handler, the stream of its reply, the routes given to
447 /// [`Builder::routes`] and the warmup handlers run on the tokio runtime that
448 /// calls this method, as tasks of that runtime. A handler that blocks its thread
449 /// therefore does not stop the health check, as in the Python SDK. It still
450 /// delays the other work of that runtime thread, so blocking work belongs in
451 /// `tokio::task::spawn_blocking`. A layer given to [`Builder::layer`] runs on the
452 /// server thread and must not block.
453 ///
454 /// The same holds for the `serve` methods. A router from [`router`](Self::router)
455 /// that you serve yourself runs all of its code in the task of the connection.
456 ///
457 /// # Shutdown
458 ///
459 /// On the signal the server stops accepting connections. It logs one warning for
460 /// each invocation in flight, with its request ID and session ID, and one line
461 /// with the tracked background tasks. Requests in flight, streams and tracked
462 /// background tasks ([`crate::tasks`]) then get the grace period to finish
463 /// ([`Builder::shutdown_grace`], 8 seconds by default). The grace period starts
464 /// at the signal, not at startup.
465 ///
466 /// When everything finishes in time, this method returns `Ok`. Otherwise, at the
467 /// end of the grace period the server cancels the requests that are still in
468 /// flight, on all routes. A handler that is still running is dropped and its
469 /// client gets a `503` reply. A response body that is still being sent fails, and
470 /// its stream is dropped. The server then waits up to half a second for its
471 /// connections to close and returns [`ErrorKind::ShutdownTimeout`].
472 ///
473 /// A caller behind AgentCore Runtime does not see a reply that the agent cuts. In
474 /// tests against the service it received such a reply as a complete one.
475 ///
476 /// Cancellation takes effect when the handler or the stream is next polled. Two
477 /// kinds of work can therefore outlast the return of this method, until they end
478 /// or the process exits:
479 ///
480 /// - A handler, a stream or a destructor that blocks its thread without yielding.
481 /// - A stream whose client has stopped reading. The server does not poll the
482 /// stream while it cannot write, so the stream is dropped only when the
483 /// connection closes.
484 ///
485 /// The server also cannot stop work that it does not own: tasks that your code
486 /// spawned, including tracked background tasks, and blocking work that has
487 /// started.
488 ///
489 /// # Errors
490 ///
491 /// Returns [`ErrorKind::Bind`] when the address cannot be bound. Returns
492 /// [`ErrorKind::Serve`] when the signal handlers cannot be installed or the server
493 /// stops with an I/O error. Returns [`ErrorKind::ShutdownTimeout`] as described
494 /// above.
495 pub async fn run(self) -> Result<(), Error> {
496 let signal = serve::os_shutdown_signal()?;
497 let listener = serve::bind(self.bind.unwrap_or_else(serve::default_bind_addr)).await?;
498 self.serve_until(listener, signal).await
499 }
500
501 /// Serves on a listener that the caller has bound, until the process receives
502 /// SIGTERM or Ctrl-C. Shutdown works as described for [`run`](Self::run).
503 ///
504 /// Use it to listen on an ephemeral port: bind port 0 and read the address from
505 /// the listener before calling this method.
506 ///
507 /// # Errors
508 ///
509 /// Returns [`ErrorKind::Serve`] when the signal handlers cannot be installed or
510 /// the server stops with an I/O error, and [`ErrorKind::ShutdownTimeout`] as
511 /// described for [`run`](Self::run).
512 pub async fn serve(self, listener: tokio::net::TcpListener) -> Result<(), Error> {
513 let signal = serve::os_shutdown_signal()?;
514 self.serve_until(listener, signal).await
515 }
516
517 /// Serves on a listener that the caller has bound, until `shutdown` completes.
518 /// Shutdown then works as described for [`run`](Self::run). This method installs
519 /// no signal handlers.
520 ///
521 /// # Errors
522 ///
523 /// Returns [`ErrorKind::Serve`] when the server stops with an I/O error, and
524 /// [`ErrorKind::ShutdownTimeout`] as described for [`run`](Self::run).
525 pub async fn serve_with_shutdown(
526 self,
527 listener: tokio::net::TcpListener,
528 shutdown: impl Future<Output = ()> + Send + 'static,
529 ) -> Result<(), Error> {
530 self.serve_until(listener, shutdown).await
531 }
532
533 async fn serve_until(
534 self,
535 listener: tokio::net::TcpListener,
536 signal: impl Future<Output = ()> + Send + 'static,
537 ) -> Result<(), Error> {
538 let router = self.standalone_router();
539 let AppState { tasks, in_flight, runtime, .. } = self.state;
540 let shutdown = serve::Shutdown { grace: self.shutdown_grace, tasks, in_flight, runtime };
541 serve::serve(listener, router, signal, shutdown).await
542 }
543
544 /// The router that the app serves by itself. An app without routes of the
545 /// customer answers unknown paths with the JSON 404.
546 fn standalone_router(&self) -> Router {
547 self.served.clone()
548 }
549
550 /// The routes of the app as an axum router: `POST /invocations`, `GET /ping`, the
551 /// [warmup hook](Builder::warmup_hook) and the routes given to [`Builder::routes`]. Use it to mount the app in a server
552 /// that you run yourself, for example with `Router::merge`, or to wrap it in
553 /// middleware with `Router::layer`. A layer that you add wraps the app's routes,
554 /// so it sees each request before the app does.
555 ///
556 /// The layers given to [`Builder::layer`] are part of this router. They wrap what
557 /// the router holds: its routes and a fallback given through [`Builder::routes`].
558 /// They do not wrap a route or a fallback that you add to the router afterwards,
559 /// or the fallback of a router that you merge it into.
560 ///
561 /// # Fallback
562 ///
563 /// The JSON `404` that the app sends for unknown paths when it serves itself is
564 /// not part of this router. A fallback that you gave through
565 /// [`Builder::routes`] is part of it.
566 ///
567 /// axum cannot merge two routers that both have a fallback: `Router::merge`
568 /// panics. So combine the routers in one of these ways:
569 ///
570 /// - Give the app no fallback, and set one on the router that you merge it into.
571 /// - Give the app the fallback through [`Builder::routes`], and merge its router
572 /// into a router without one. The app's fallback then answers every unknown
573 /// path of the combined router.
574 ///
575 /// # Serving
576 ///
577 /// Shutdown and the listen address are yours to handle when you serve this
578 /// router yourself: the settings [`Builder::bind`] and
579 /// [`Builder::shutdown_grace`] apply only to [`run`](Self::run) and the `serve`
580 /// methods.
581 pub fn router(&self) -> Router {
582 self.router.clone()
583 }
584
585 /// The registry of background work of this app. Every invocation's
586 /// [`RequestContext::tasks`](crate::RequestContext::tasks) returns the same registry.
587 pub fn tasks(&self) -> &AsyncTasks {
588 &self.state.tasks
589 }
590}
591
592impl fmt::Debug for BedrockAgentCoreApp {
593 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
594 f.debug_struct("BedrockAgentCoreApp")
595 .field("bind", &self.bind)
596 .field("body_limit", &self.body_limit)
597 .field("shutdown_grace", &self.shutdown_grace)
598 .finish_non_exhaustive()
599 }
600}
601
602async fn ping(State(state): State<AppState>) -> Json<Value> {
603 let (status, changed) = state.ping.current();
604 Json(json!({ "status": status.as_str(), "time_of_last_update": changed }))
605}