Skip to main content

Builder

Struct Builder 

Source
pub struct Builder { /* private fields */ }
Expand description

Configures a BedrockAgentCoreApp. Create one with BedrockAgentCoreApp::builder.

Implementations§

Source§

impl Builder

Source

pub fn invocation<H, M>(self, handler: H) -> Self
where H: InvocationHandler<M>,

Sets the handler for POST /invocations. This setting is required.

See InvocationHandler for the accepted function signatures.

Source

pub fn ping<F, S>(self, handler: F) -> Self
where F: Fn() -> S + Send + Sync + 'static, S: Into<Option<PingStatus>>,

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:

static INDEXING: AtomicBool = AtomicBool::new(false);

// 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.

Source

pub fn bind(self, addr: SocketAddr) -> 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.

Source

pub fn body_limit(self, bytes: usize) -> Self

Sets the largest accepted invocation body in bytes. The default is 1 MiB.

AgentCore Runtime accepts larger payloads than this default.

Source

pub fn stream_heartbeat(self, interval: Duration) -> 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. A Response::stream that is returned from a route outside the app uses the default.

Source

pub fn shutdown_grace(self, grace: Duration) -> 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.

Source

pub fn routes(self, routes: Router) -> Self

Adds routes of your own to the app. Call it more than once to add more.

Handlers of these routes can take RequestContext as an argument and can read it with 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.

Source

pub fn layer<L>(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,

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.

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
}

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 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, 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 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 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.

Source

pub fn warmup_hook(self, hook: WarmupHook) -> 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: its handlers get no RequestContext, and the app keeps its JSON 404 for unknown paths.

Source

pub fn build(self) -> Result<BedrockAgentCoreApp, Error>

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 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 breaks one of its rules, or the hook has the path and method of another route.
  • A layer given to layer panics while it is applied.

Trait Implementations§

Source§

impl Debug for Builder

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl !RefUnwindSafe for Builder

§

impl !UnwindSafe for Builder

§

impl Forget for Builder

§

impl Freeze for Builder
where *const ArcInner<dyn Fn(Bytes, RequestContext) -> Pin<Box<dyn Future<Output = Result<Response, HandlerError>> + Send>> + Send + Sync> is !null: Freeze, PhantomData<ArcInner<dyn Fn(Bytes, RequestContext) -> Pin<Box<dyn Future<Output = Result<Response, HandlerError>> + Send>> + Send + Sync>>: Freeze, *const ArcInner<dyn Fn() -> Option<PingStatus> + Send + Sync> is !null: Freeze, PhantomData<ArcInner<dyn Fn() -> Option<PingStatus> + Send + Sync>>: Freeze, *const u8 is !null: Freeze, PhantomData<Router>: Freeze, PhantomData<Box<dyn Fn(Router) -> Router + Send + Sync>>: Freeze, PhantomData<u8>: Freeze, *const ArcInner<dyn Fn() -> Pin<Box<dyn Future<Output = Result<(), Failure>> + Send>> + Send + Sync> is !null: Freeze, PhantomData<ArcInner<dyn Fn() -> Pin<Box<dyn Future<Output = Result<(), Failure>> + Send>> + Send + Sync>>: Freeze,

§

impl Move for Builder

§

impl Send for Builder
where Arc<dyn Fn(Bytes, RequestContext) -> Pin<Box<dyn Future<Output = Result<Response, HandlerError>> + Send>> + Send + Sync>: Send, Arc<dyn Fn() -> Option<PingStatus> + Send + Sync>: Send, RawVecInner: Send, Arc<RouterInner<()>>: Send, BoxRaw<dyn Fn(Router) -> Router + Send + Sync>: Send, Arc<dyn Fn() -> Pin<Box<dyn Future<Output = Result<(), Failure>> + Send>> + Send + Sync>: Send,

§

impl Sync for Builder
where Arc<dyn Fn(Bytes, RequestContext) -> Pin<Box<dyn Future<Output = Result<Response, HandlerError>> + Send>> + Send + Sync>: Sync, Arc<dyn Fn() -> Option<PingStatus> + Send + Sync>: Sync, RawVecInner: Sync, Arc<RouterInner<()>>: Sync, BoxRaw<dyn Fn(Router) -> Router + Send + Sync>: Sync, Arc<dyn Fn() -> Pin<Box<dyn Future<Output = Result<(), Failure>> + Send>> + Send + Sync>: Sync,

§

impl Unpin for Builder
where Arc<dyn Fn(Bytes, RequestContext) -> Pin<Box<dyn Future<Output = Result<Response, HandlerError>> + Send>> + Send + Sync>: Unpin, Arc<dyn Fn() -> Option<PingStatus> + Send + Sync>: Unpin, *const u8 is !null: Unpin, Arc<RouterInner<()>>: Unpin, Box<dyn Fn(Router) -> Router + Send + Sync>: Unpin, Arc<dyn Fn() -> Pin<Box<dyn Future<Output = Result<(), Failure>> + Send>> + Send + Sync>: Unpin,

§

impl UnsafeUnpin for Builder
where *const ArcInner<dyn Fn(Bytes, RequestContext) -> Pin<Box<dyn Future<Output = Result<Response, HandlerError>> + Send>> + Send + Sync> is !null: UnsafeUnpin, PhantomData<ArcInner<dyn Fn(Bytes, RequestContext) -> Pin<Box<dyn Future<Output = Result<Response, HandlerError>> + Send>> + Send + Sync>>: UnsafeUnpin, *const ArcInner<dyn Fn() -> Option<PingStatus> + Send + Sync> is !null: UnsafeUnpin, PhantomData<ArcInner<dyn Fn() -> Option<PingStatus> + Send + Sync>>: UnsafeUnpin, *const u8 is !null: UnsafeUnpin, PhantomData<Router>: UnsafeUnpin, PhantomData<Box<dyn Fn(Router) -> Router + Send + Sync>>: UnsafeUnpin, PhantomData<u8>: UnsafeUnpin, *const ArcInner<dyn Fn() -> Pin<Box<dyn Future<Output = Result<(), Failure>> + Send>> + Send + Sync> is !null: UnsafeUnpin, PhantomData<ArcInner<dyn Fn() -> Pin<Box<dyn Future<Output = Result<(), Failure>> + Send>> + Send + Sync>>: UnsafeUnpin,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<Unshared, Shared> IntoShared<Shared> for Unshared
where Shared: FromUnshared<Unshared>,

Source§

fn into_shared(self) -> Shared

Creates a shared type from an unshared type.
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more