Skip to main content

a2a_protocol_server/handler/
turn_slots.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Tom F. <[email protected]> (https://github.com/tomtom215)
3
4//! The send path's side of the admission gate (ADR 0045): taking a slot for
5//! the current tenant, and what a refusal is answered with.
6
7use a2a_protocol_types::message::Message;
8use tokio::sync::OwnedSemaphorePermit;
9
10use super::RequestHandler;
11use crate::admission::AdmissionLoad;
12use crate::admission::gate::{AdmissionPermit, Refusal};
13use crate::call_context::CallContext;
14use crate::error::{ServerError, ServerResult};
15use crate::store::tenant::TenantContext;
16
17/// The slots a running turn holds, given back when its executor ends: the
18/// tenant's (`max_concurrent_tasks`) and the admission gate's.
19#[derive(Debug)]
20pub struct TurnSlots {
21    pub tenant: Option<OwnedSemaphorePermit>,
22    pub admission: Option<AdmissionPermit>,
23}
24
25impl TurnSlots {
26    /// Both slots, for the executor's future to hold until it ends.
27    pub fn into_parts(self) -> (Option<OwnedSemaphorePermit>, Option<AdmissionPermit>) {
28        (self.tenant, self.admission)
29    }
30}
31
32impl RequestHandler {
33    /// A slot of the admission gate for the current tenant, or `None` with no
34    /// gate. Waits as the gate is configured, for no longer than what remains
35    /// of the message's budget.
36    ///
37    /// # Errors
38    ///
39    /// [`ServerError::Overloaded`] when the gate is full and its queue is
40    /// too, or the wait reached `max_wait`; [`ServerError::InvalidParams`]
41    /// when the budget's deadline passed first, as for a budget that had
42    /// already run out on arrival (`budget::requested`).
43    pub(crate) async fn take_admission_slot(
44        &self,
45        message: &Message,
46        call_ctx: &CallContext,
47    ) -> ServerResult<Option<AdmissionPermit>> {
48        let Some(gate) = &self.admission else {
49            return Ok(None);
50        };
51        // A malformed budget is refused by the commit, with its own error;
52        // here it only bounds the wait.
53        let budget_left = super::budget::requested(message, call_ctx.received_at())
54            .ok()
55            .flatten()
56            .and_then(|budget| budget.remaining_time());
57        let tenant = TenantContext::current();
58        match gate.acquire(&tenant, budget_left).await {
59            Ok(permit) => Ok(Some(permit)),
60            Err(Refusal::Full) => Err(ServerError::Overloaded(format!(
61                "no admission slot free for tenant '{tenant}', and no room to wait for one"
62            ))),
63            Err(Refusal::Waited(waited)) => Err(ServerError::Overloaded(format!(
64                "no admission slot came free for tenant '{tenant}' within {waited:?}"
65            ))),
66            Err(Refusal::Budget) => Err(ServerError::InvalidParams(
67                "the budget's deadline passed while the send waited for admission".to_owned(),
68            )),
69        }
70    }
71
72    /// What the admission gate holds now (ADR 0045), or `None` without one.
73    #[must_use]
74    pub fn admission_load(&self) -> Option<AdmissionLoad> {
75        self.admission
76            .as_ref()
77            .map(crate::admission::gate::AdmissionGate::load)
78    }
79}