Skip to main content

RequestHandler

Struct RequestHandler 

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

The core protocol logic handler.

Orchestrates task lifecycle, event streaming, push notifications, and interceptor chains for all A2A methods.

RequestHandler is not generic — it stores the executor as Arc<dyn AgentExecutor>, enabling dynamic dispatch and simplifying the downstream API (dispatchers, builder, etc.).

§Store ownership

Stores are held as Arc<dyn TaskStore> / Arc<dyn PushConfigStore> rather than Box<dyn ...> so that they can be cheaply cloned into background tasks (e.g. the streaming push-delivery processor).

Implementations§

Source§

impl RequestHandler

Source

pub fn activated_extensions( &self, headers: &HashMap<String, String>, ) -> Vec<String>

Returns the activated extension set for a request: the intersection of the client’s A2A-Extensions declaration and the card’s declared extensions, in request order. HTTP dispatchers echo this back in the response A2A-Extensions header (official-SDK convention) so clients know which requested extensions the agent honored.

Source§

impl RequestHandler

Source

pub fn admission_load(&self) -> Option<AdmissionLoad>

What the admission gate holds now (ADR 0045), or None without one.

Source§

impl RequestHandler

Source

pub async fn halt(&self, scope: HaltScope, by: &str, reason: &str) -> HaltReport

Halts scope: refuses new sends with ServerError::Halted and stops every running task, until resume. Returns once the tokens are fired; each task reaches canceled when its executor returns.

by names the person or system that halted it and reason why; both go into the refusal each caller sees and, with the audit feature, into a halt record in the scope’s chain (the "" chain for HaltScope::All), with the ids of the tasks it stopped. Halting a scope that is already halted replaces its reason and stops whatever is running again.

With a halt store it is written there too, after it holds here: a store that cannot be written does not delay the stop, and the report says so (HaltReport::persisted).

Source

pub async fn resume( &self, scope: HaltScope, by: &str, ) -> Result<bool, ServerError>

Lifts a halt of exactly scope and returns whether there was one. Resuming one tenant does not lift a halt of HaltScope::All.

With a halt store it is removed there first, so every replica resumes within its poll interval.

§Errors

ServerError::Internal when the halt store cannot be written; the halt then still holds, here and everywhere.

Source

pub fn is_halted_everywhere(&self) -> bool

Whether a halt of every tenant (HaltScope::All) is held, which /ready and the load report show (ADR 0046).

Source

pub fn halt_reason(&self, tenant: &str) -> Option<String>

Why every send for tenant is refused, if it is: a halt of HaltScope::All or of the tenant. A halt of one job refuses only that job’s sends; see halt_reason_for_root.

Source

pub fn halt_reason_for_root(&self, tenant: &str, root: &str) -> Option<String>

Why a send of the job root in tenant is refused, if it is: a halt of HaltScope::All, of the tenant, or of that job.

Source

pub async fn running_in_root( &self, tenant: &str, root: &str, ) -> Vec<(TaskId, Lineage)>

The turns of the job root in tenant running in this process, with each one’s lineage, in task-id order: what a halt of HaltScope::Root would stop here now. A live view of one replica; a2a_protocol_types::lineage::tree arranges stored tasks from every agent into the job’s tree.

Source§

impl RequestHandler

Source

pub fn ensure_input_modes_supported( &self, message: &Message, ) -> Result<(), ServerError>

Refuses a message with a part whose explicit media type the card does not declare.

§Errors

ContentTypeNotSupportedError, naming the part and its media type.

Source§

impl RequestHandler

Source

pub async fn active_queue_count(&self) -> usize

Number of event queues currently alive.

One queue exists per in-flight task and is destroyed when the task finishes, so under steady traffic this tracks concurrency rather than throughput. A value that climbs with cumulative request count — instead of settling — means queues are not being reclaimed.

Exposed for monitoring and for the sustained-load tests. The Metrics::on_queue_depth_change callback reports the same quantity as it changes; this is the pull-based counterpart, for a gauge scrape or a health page.

Source

pub async fn task_count(&self) -> Result<u64, A2aError>

Number of tasks currently held by the task store.

Delegates to count on the configured store.

§Errors

Returns whatever the store returned.

Source

pub async fn cancellation_token_count(&self) -> usize

Number of registered cancellation tokens.

One is registered per in-flight task and removed when it finishes, so like active_queue_count this should settle under steady traffic rather than climb. It has its own bound (max_cancellation_tokens), so a leak here eventually rejects new work rather than only consuming memory — which makes it worth watching directly.

Source

pub async fn task_store_health(&self) -> Result<(), A2aError>

Probes the task store, for readiness checks.

Answers the one question a readiness probe needs: can this replica reach the dependency it cannot serve a request without? A liveness probe deliberately cannot answer that — making liveness depend on a downstream turns that downstream’s outage into a restart loop across every replica, which is how a degraded service becomes an unavailable one.

Implemented as health, which the SQL stores answer with one statement whose cost does not grow with the tasks they hold (the PostgreSQL stores also fail on a standby, which takes no writes). It performs no write, so a store at its capacity limit still reports healthy — capacity is not the same question as reachability, and conflating them would drain traffic from a cluster that was merely full.

§Errors

Returns whatever the store returned. Callers exposing this over HTTP should surface metric_label rather than the message, which may name a host or a connection string.

Records no span: a probe is not a call, and every one would otherwise be a trace of its own (a readiness probe every 5 s per replica, seen in Tempo, 2026-10-28). The store’s duration metric is still recorded.

Source

pub async fn readiness(&self) -> Result<(), &'static str>

Whether this replica should be sent traffic: not while it is draining, nor while its task store fails task_store_health, nor while a halt store it was given has not been read, nor, when HandlerLimits::with_saturation_readiness is set, while it is saturated (ADR 0046). This is what /ready answers on the HTTP+JSON dispatcher and the axum router.

The probe is what reads the halt store the first time, so a replica becomes ready by having read it. Until 2026-11-01 it answered ready while refusing every send for want of that read (audit NEW-h-designs-7), and nothing read the store until a send arrived.

§Errors

A bounded reason: "draining", "saturated", "timeout" when the store has not answered within READINESS_TIMEOUT, "halt_store" when the halt store cannot be read, or the store error’s metric_label, never its message, which may name a host or a connection string.

Source

pub fn begin_draining(&self)

Marks this replica as leaving: readiness answers "draining" from now on, so a load balancer that probes it stops sending new requests, while those already sent are still served. A Server does this when its shutdown signal fires, before ServeConfig::drain_delay.

Source

pub fn is_draining(&self) -> bool

Whether begin_draining was called.

Source§

impl RequestHandler

Source

pub async fn on_cancel_task( &self, params: CancelTaskParams, headers: Option<&HashMap<String, String>>, ) -> Result<Task, ServerError>

Handles CancelTask.

§Errors

Returns ServerError::TaskNotFound or ServerError::TaskNotCancelable.

Source§

impl RequestHandler

Source

pub async fn on_get_extended_agent_card( &self, headers: Option<&HashMap<String, String>>, ) -> Result<AgentCard, ServerError>

Handles GetExtendedAgentCard.

§Errors

Returns ServerError::UnsupportedOperation when the public card does not declare capabilities.extendedAgentCard, or when the handler has neither a public nor an extended card; ExtendedAgentCardNotConfigured when the card declares it and no extended card is configured (SPEC §3.1.11, §13.3); a refusal when §13.3’s authentication is not configured; and whatever the interceptor chain refuses.

Source

pub async fn on_get_extended_agent_card_for_tenant( &self, tenant: Option<&str>, headers: Option<&HashMap<String, String>>, ) -> Result<AgentCard, ServerError>

on_get_extended_agent_card for the tenant the request names (GetExtendedAgentCardRequest.tenant, which every binding carries: the JSON-RPC and gRPC field, the REST path prefix or query). The tenant goes through the same admission as every other operation’s: it is resolved (TenantResolver, strict resolution, the halt switch), the call runs in its scope, so an interceptor and the ExtendedCardProvider see it in ctx.tenant(), and the caller’s partition is entered. Before, this was the one operation that dropped the tenant, so a provider could not tell two tenants of one principal apart (adversarial review P3, 2026-11-12).

§Errors

As on_get_extended_agent_card, and a refusal of the tenant, as for any other operation.

Source§

impl RequestHandler

Source

pub async fn on_get_task( &self, params: TaskQueryParams, headers: Option<&HashMap<String, String>>, ) -> Result<Task, ServerError>

Handles GetTask. Returns ServerError::TaskNotFound if missing.

§Errors

Returns ServerError::TaskNotFound if the task does not exist.

Source§

impl RequestHandler

Source

pub async fn on_list_tasks( &self, params: ListTasksParams, headers: Option<&HashMap<String, String>>, ) -> Result<TaskListResponse, ServerError>

Handles ListTasks.

§Errors

Returns a ServerError if the store query fails.

Source§

impl RequestHandler

Source

pub async fn on_subscribe_to_task( &self, params: TaskIdParams, headers: Option<&HashMap<String, String>>, ) -> Result<InMemoryQueueReader, ServerError>

Handles SubscribeToTask.

§Errors

Returns ServerError::TaskNotFound if the task does not exist.

Source§

impl RequestHandler

Source

pub fn load(&self) -> LoadReport

What this replica holds now (ADR 0046). Cheap: atomics and two short locks, no store call and no lock on the queue map.

Source

pub const fn reports_load(&self) -> bool

Whether load reporting is on: /load is served and responses carry LOAD_HEADER.

Source§

impl RequestHandler

Source

pub async fn on_send_message( &self, params: MessageSendParams, streaming: bool, headers: Option<&HashMap<String, String>>, ) -> Result<SendMessageResult, ServerError>

Handles SendMessage / SendStreamingMessage.

The optional headers map carries HTTP request headers for interceptor access-control decisions (e.g. Authorization).

§Errors

Returns ServerError if task creation or execution fails.

Source§

impl RequestHandler

Source

pub async fn on_create_push_config( &self, config: TaskPushNotificationConfig, headers: Option<&HashMap<String, String>>, ) -> Result<TaskPushNotificationConfig, ServerError>

Handles CreateTaskPushNotificationConfig.

§Errors

Returns ServerError::PushNotSupported if the agent card does not advertise push notifications or no push sender is configured.

Source

pub async fn on_get_push_config( &self, params: GetPushConfigParams, headers: Option<&HashMap<String, String>>, ) -> Result<TaskPushNotificationConfig, ServerError>

Handles GetTaskPushNotificationConfig.

§Errors

Returns ServerError::PushNotSupported if the agent card does not advertise push notifications or no push sender is configured, or ServerError::TaskNotFound if the requested configuration does not exist (spec §3.1.8).

Source

pub async fn on_list_push_configs( &self, task_id: &str, tenant: Option<&str>, headers: Option<&HashMap<String, String>>, ) -> Result<Vec<TaskPushNotificationConfig>, ServerError>

Handles ListTaskPushNotificationConfigs.

§Errors

Returns ServerError::PushNotSupported if the agent card does not advertise push notifications or no push sender is configured, ServerError::TaskNotFound if the task does not exist (spec §3.1.9), or another ServerError if the store query fails.

Source

pub async fn on_delete_push_config( &self, params: DeletePushConfigParams, headers: Option<&HashMap<String, String>>, ) -> Result<(), ServerError>

Handles DeleteTaskPushNotificationConfig.

§Errors

Returns ServerError::PushNotSupported if the agent card does not advertise push notifications or no push sender is configured, ServerError::TaskNotFound if the task does not exist (spec §3.1.10), or another ServerError if the delete operation fails.

Source§

impl RequestHandler

Source

pub async fn on_list_push_configs_page( &self, params: &ListPushConfigsParams, headers: Option<&HashMap<String, String>>, ) -> Result<ListPushConfigsResponse, ServerError>

Handles ListTaskPushNotificationConfigs with its pageSize and pageToken (spec §3.1.9), as every binding does.

With neither, every config is returned as on_list_push_configs returns them, and nextPageToken is absent. With either, the configs are ordered by id and at most pageSize are returned (all of them without one), with a nextPageToken while more remain. The token names the last config returned, so a config created or deleted between pages neither repeats nor shifts the rest.

§Errors

ServerError::InvalidField for a pageToken this server did not give; then those of on_list_push_configs.

Source§

impl RequestHandler

Source

pub async fn on_resubscribe( &self, params: TaskIdParams, headers: Option<&HashMap<String, String>>, ) -> Result<InMemoryQueueReader, ServerError>

👎Deprecated since 0.16.0:

use on_subscribe_to_task, named for the SubscribeToTask wire method; removed no earlier than 0.17.0

on_subscribe_to_task, under the name it had before 0.16.0.

§Errors

As on_subscribe_to_task.

Source

pub async fn on_set_push_config( &self, config: TaskPushNotificationConfig, headers: Option<&HashMap<String, String>>, ) -> Result<TaskPushNotificationConfig, ServerError>

👎Deprecated since 0.16.0:

use on_create_push_config, named for the CreateTaskPushNotificationConfig wire method; removed no earlier than 0.17.0

on_create_push_config, under the name it had before 0.16.0.

§Errors

As on_create_push_config.

Source§

impl RequestHandler

Source

pub fn admits_sends(&self) -> bool

Whether this handler still admits sends: false once finish_in_flight, cancel_in_flight or a shutdown method has begun.

Source

pub async fn cancel_in_flight(&self, grace: Duration) -> InFlightReport

Cancels every in-flight task and waits, up to grace, for their executors to act on it.

This is the first thing a graceful shutdown must do, and Server::serve_with_shutdown does it for you. Call it yourself when something else owns the sockets — with Axum, at the end of the future passed to with_graceful_shutdown, so it runs before Axum drains connections (the book’s production chapter and examples/deploy-agent show it).

Each running task’s cancellation_token fires. An executor that observes it — the documented contract of AgentExecutor::execute — can cancel what it delegated and return. If it returns without having written a terminal state, the handler then calls its cancel hook, for what it releases, and ends the task Failed with failure class transient (unless the executor can be re-run and the handler has turn claims: then the turn is handed back to its caller, working, with no hook run; see resumes_after_hand_off) (a Canceled the hook writes is written as that failure), so every open stream ends with a terminal event that tells its caller it may send again, instead of simply stopping. Not Canceled: nobody cancelled the task, and a caller does not repeat a cancelled one (audit E-F2). The call returns once every executor and every background event processor has finished, or when grace runs out.

A send that arrives after this call is refused, as during finish_in_flight’s window. Calling it twice is harmless: the second call cancels nothing new and waits only for what is still running.

An executor that never looks at its token cannot be stopped from here. It is counted in InFlightReport::still_running, and it is cut off when the process exits.

Source

pub async fn finish_in_flight( &self, completion: Duration, grace: Duration, ) -> InFlightReport

Lets in-flight tasks finish on their own for up to completion, then cancels whatever is still running and waits up to grace for it — cancel_in_flight with a window in front.

This is the order Server::serve_with_shutdown uses. Cancelling at once stops a two-second blocking send that would have succeeded, on every rolling deploy, and ends it Failed (transient), so its caller retries work that was nearly done. Waiting without ever cancelling orphans a delegation that will not finish in any window the platform allows. The window serves the first kind and the cancel serves the second; a completion of zero is cancel_in_flight.

A send that arrives once this is called, on a connection still open, is refused before any work begins, with a temporary error that names a retry delay (HTTP 503 with Retry-After, gRPC UNAVAILABLE, a RetryInfo detail on every binding), so a client sends it again, to another replica behind the same address. Admitting it would only have it stopped when the window closes (audit E-F2). Reads, cancels and subscriptions are still served.

It also begins draining, so /ready answers not ready while the window runs.

Source§

impl RequestHandler

Source

pub async fn shutdown(&self) -> ShutdownReport

Finishes shutting the handler down: the last step, after cancel_in_flight has ended the work and the sockets have drained.

This method:

  1. Cancels all in-flight tasks by signalling their cancellation tokens.
  2. Destroys all event queues, causing readers to see EOF.
  3. Releases the turn claims it holds, so other replicas sharing the store can continue those tasks at once.
  4. Runs the executor’s on_shutdown hook. Steps 3 and 4 share one 10-second bound.

It does not wait for executors. Called on its own while tasks are running, it cuts their streams off without a terminal event and leaves whatever they delegated running — which the report now says, in queues_force_destroyed. Server::serve_with_shutdown runs cancel_in_flight before its drain, so calling this after it finds nothing left to cut.

A send after this call is refused, retryably, as during finish_in_flight; see admits_sends.

Source

pub async fn shutdown_with_timeout(&self, timeout: Duration) -> ShutdownReport

Initiates graceful shutdown, returning within timeout.

Cancels all in-flight tasks, waits for event queues to drain, and then runs the executor’s cleanup hook — all inside the one budget. This gives executors a chance to finish writing final events before the queues are torn down.

§timeout is the total, not a per-phase allowance

It was a per-phase allowance until 2026-08-19: the drain loop ran to now + timeout and then on_shutdown was given a fresh full timeout, so the call could take twice what the caller asked for. Measured on paused time with an undrainable queue and a cleanup hook that never returns, shutdown_with_timeout(30s) took 60s — exactly 2×.

That is not an academic overshoot. The number an operator puts here is the number they put in terminationGracePeriodSeconds, and a process that overruns it is SIGKILLed part-way through the cleanup this method exists to perform — truncating precisely the streams a graceful shutdown was protecting.

So the drain phase and the cleanup hook now share one deadline. If draining consumes the whole budget, cleanup is given what is left, which may be nothing; that is reported rather than papered over, because “your queues would not drain” and “your cleanup hook hung” are different problems and the caller can see which they had.

Returns a ShutdownReport: a non-zero queues_force_destroyed means the deadline passed with work still in flight, and executor_cleanup_completed == false means the executor’s cleanup hook was abandoned. Both are invisible from the outside otherwise, which is how a rollout can truncate every in-flight stream without anyone noticing.

Source§

impl RequestHandler

Source

pub fn undeclared_binding(&self, binding: &str) -> Option<String>

Why a listener serving binding would break spec §5.2 (“Agents MUST declare all supported protocols in their AgentCard”), when this handler’s static agent card declares no interface with that protocolBinding; None when it does, or when the card is produced elsewhere (a dynamic handler, no card).

Every listener in this crate asks this when it starts. A binding implemented outside it (a2a-protocol-slimrpc) asks it the same way, with the protocolBinding string it advertises, and decides whether the answer is a warning (warn_if_undeclared) or a refusal.

Not asking costs a card that does not list a transport the agent serves: a client that reads the card never finds it.

Source

pub fn warn_if_undeclared(&self, binding: &str)

Logs undeclared_binding as a warning (target a2a_protocol_server, message undeclared binding, fields binding and reason), as this crate’s listeners do. Nothing is logged without the tracing feature.

Source§

impl RequestHandler

Source

pub const fn profile_report(&self) -> &ProfileReport

What this handler’s deployment profiles guarantee: what build() checked, which escape hatch gave up which guarantee, and what no check at startup can establish (ProfileReport). Log it at startup (it implements Display) so the deployment’s record says what it was built to promise.

Source

pub fn tenant_resolver(&self) -> Option<&(dyn TenantResolver + 'static)>

Returns the tenant resolver, if configured.

Use this in dispatchers or middleware to resolve the tenant identity from a CallContext before processing a request.

Source

pub const fn tenant_config(&self) -> Option<&PerTenantConfig>

Returns the per-tenant limits this handler enforces, if any were set.

The handler applies them itself; this accessor is for inspection, and for handing the same configuration to RateLimitInterceptor::with_tenant_config, which is where rate_limit_rps is applied. See tenant_config.

Trait Implementations§

Source§

impl Debug for RequestHandler

Source§

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

Formats the value using the given formatter. Read more

Auto Trait Implementations§

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
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

§

fn implicit( self, class: Class, constructed: bool, tag: u32, ) -> TaggedParser<'a, Implicit, Self, E>

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
§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> FutureExt for T

§

fn with_context(self, otel_cx: Context) -> WithContext<Self> ⓘ

Attaches the provided Context to this type, returning a WithContext wrapper. Read more
§

fn with_current_context(self) -> WithContext<Self> ⓘ

Attaches the current Context to this type, returning a WithContext wrapper. Read more
§

impl<T> Instrument for T

§

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

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

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
§

impl<T> IntoRequest<T> for T

§

fn into_request(self) -> Request<T>

Wrap the input message T in a tonic::Request
§

impl<L> LayerExt<L> for L

§

fn named_layer<S>(&self, service: S) -> Layered<<L as Layer<S>>::Service, S>
where L: Layer<S>,

Applies the layer to a service and wraps it in [Layered].
§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

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

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

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
§

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

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