Skip to main content

a2a_protocol_server/admission/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Tom F. <[email protected]> (https://github.com/tomtom215)
3
4//! An opt-in admission gate for sends: a capacity, slots reserved per
5//! tenant, a bounded wait, priority classes and weighted fairness, all set by
6//! the server (audit H9, ADR 0045).
7//!
8//! Without one, which is the default, a send the server has no room for is
9//! refused at once with `Overloaded` (503 with `Retry-After`). With one:
10//!
11//! * at most [`Admission::capacity`] turns run at once through the gate;
12//! * a tenant given [`TenantShare::with_reserved`] slots can always take
13//!   them, and no other tenant can;
14//! * a send that finds no slot waits, if the queue has room
15//!   ([`Admission::with_max_queued`]), for at most
16//!   [`Admission::with_max_wait`] or what remains of its budget, whichever is
17//!   shorter;
18//! * a freed slot goes to the highest [priority](TenantShare::with_priority)
19//!   with a send waiting, and within a priority round the tenants waiting,
20//!   [`weight`](TenantShare::with_weight) sends each per round.
21//!
22//! The tenant is the one the handler resolved for the request
23//! ([`TenantResolver`](crate::TenantResolver)); nothing the caller sends sets
24//! a priority.
25//!
26//! ```rust
27//! use std::time::Duration;
28//! use a2a_protocol_server::admission::{Admission, TenantShare};
29//!
30//! let admission = Admission::new(256)
31//!     .with_max_queued(1024)
32//!     .with_max_wait(Duration::from_millis(500))
33//!     .with_tenant(
34//!         "premium",
35//!         TenantShare::new().with_priority(1).with_weight(4).with_reserved(32),
36//!     );
37//! assert_eq!(admission.capacity(), 256);
38//! assert_eq!(admission.share("premium").reserved(), 32);
39//! assert_eq!(admission.share("anyone").weight(), 1);
40//! ```
41
42use std::collections::HashMap;
43use std::time::Duration;
44
45pub(crate) mod gate;
46
47/// What one tenant gets from an [`Admission`] gate.
48///
49/// A tenant with no share of its own gets the gate's
50/// [default share](Admission::with_default_share), which reserves nothing.
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub struct TenantShare {
53    weight: u32,
54    priority: u8,
55    reserved: usize,
56}
57
58impl TenantShare {
59    /// Weight 1, priority 0, nothing reserved.
60    #[must_use]
61    pub const fn new() -> Self {
62        Self {
63            weight: 1,
64            priority: 0,
65            reserved: 0,
66        }
67    }
68
69    /// How many sends of this tenant are admitted per round, among tenants
70    /// of the same priority that are waiting. `0` is taken as `1`.
71    #[must_use]
72    pub const fn with_weight(mut self, weight: u32) -> Self {
73        self.weight = if weight == 0 { 1 } else { weight };
74        self
75    }
76
77    /// The tenant's class: a freed slot goes to the highest class with a
78    /// send waiting that may take it. Higher is served first.
79    #[must_use]
80    pub const fn with_priority(mut self, priority: u8) -> Self {
81        self.priority = priority;
82        self
83    }
84
85    /// Slots of the gate's capacity only this tenant may use.
86    #[must_use]
87    pub const fn with_reserved(mut self, reserved: usize) -> Self {
88        self.reserved = reserved;
89        self
90    }
91
92    /// The weight.
93    #[must_use]
94    pub const fn weight(&self) -> u32 {
95        self.weight
96    }
97
98    /// The priority.
99    #[must_use]
100    pub const fn priority(&self) -> u8 {
101        self.priority
102    }
103
104    /// The slots reserved.
105    #[must_use]
106    pub const fn reserved(&self) -> usize {
107        self.reserved
108    }
109}
110
111impl Default for TenantShare {
112    /// [`TenantShare::new`].
113    fn default() -> Self {
114        Self::new()
115    }
116}
117
118/// The admission gate's configuration; see the [module docs](self). Set it
119/// with [`RequestHandlerBuilder::with_admission`](crate::RequestHandlerBuilder::with_admission).
120#[derive(Debug, Clone, PartialEq, Eq)]
121pub struct Admission {
122    capacity: usize,
123    max_queued: usize,
124    max_wait: Duration,
125    default_share: TenantShare,
126    shares: HashMap<String, TenantShare>,
127}
128
129impl Admission {
130    /// A gate admitting `capacity` turns at once, refusing the rest (no
131    /// queue until [`with_max_queued`](Self::with_max_queued) and
132    /// [`with_max_wait`](Self::with_max_wait) are set).
133    #[must_use]
134    pub fn new(capacity: usize) -> Self {
135        Self {
136            capacity,
137            max_queued: 0,
138            max_wait: Duration::ZERO,
139            default_share: TenantShare::new(),
140            shares: HashMap::new(),
141        }
142    }
143
144    /// How many sends may wait at once, across tenants. `0`, the default,
145    /// waits for nothing.
146    #[must_use]
147    pub const fn with_max_queued(mut self, max_queued: usize) -> Self {
148        self.max_queued = max_queued;
149        self
150    }
151
152    /// How long a send may wait for a slot. Zero, the default, waits for
153    /// nothing. A send whose budget ends sooner waits only that long.
154    #[must_use]
155    pub const fn with_max_wait(mut self, max_wait: Duration) -> Self {
156        self.max_wait = max_wait;
157        self
158    }
159
160    /// What a tenant with no share of its own gets. It must reserve nothing:
161    /// every tenant the server has not named would otherwise get a
162    /// reservation of its own.
163    #[must_use]
164    pub const fn with_default_share(mut self, share: TenantShare) -> Self {
165        self.default_share = share;
166        self
167    }
168
169    /// Gives `tenant` its own share.
170    #[must_use]
171    pub fn with_tenant(mut self, tenant: impl Into<String>, share: TenantShare) -> Self {
172        self.shares.insert(tenant.into(), share);
173        self
174    }
175
176    /// How many turns run at once through the gate.
177    #[must_use]
178    pub const fn capacity(&self) -> usize {
179        self.capacity
180    }
181
182    /// How many sends may wait at once.
183    #[must_use]
184    pub const fn max_queued(&self) -> usize {
185        self.max_queued
186    }
187
188    /// How long a send may wait.
189    #[must_use]
190    pub const fn max_wait(&self) -> Duration {
191        self.max_wait
192    }
193
194    /// The share `tenant` gets: its own, or the default.
195    #[must_use]
196    pub fn share(&self, tenant: &str) -> TenantShare {
197        self.shares
198            .get(tenant)
199            .copied()
200            .unwrap_or(self.default_share)
201    }
202
203    /// The slots reserved across every named tenant.
204    fn reserved(&self) -> usize {
205        self.shares
206            .values()
207            .fold(0usize, |sum, share| sum.saturating_add(share.reserved))
208    }
209
210    /// Why this gate cannot work beside a queue cap of `queue_cap`, or `None`.
211    pub(crate) fn invalid(&self, queue_cap: usize) -> Option<String> {
212        if self.capacity == 0 {
213            return Some("the admission gate's capacity must be at least 1".to_owned());
214        }
215        if self.capacity > queue_cap {
216            return Some(format!(
217                "the admission gate's capacity ({}) is above the concurrent-stream cap ({queue_cap}), \
218                 which would refuse what the gate admitted: lower it, or raise \
219                 with_max_concurrent_streams",
220                self.capacity
221            ));
222        }
223        if self.default_share.reserved != 0 {
224            return Some(
225                "the admission gate's default share reserves slots: every tenant not named \
226                 would get a reservation of its own; reserve slots per tenant with with_tenant"
227                    .to_owned(),
228            );
229        }
230        let reserved = self.reserved();
231        if reserved > self.capacity {
232            return Some(format!(
233                "the admission gate's reservations ({reserved}) are more than its capacity ({})",
234                self.capacity
235            ));
236        }
237        None
238    }
239}
240
241/// What an admission gate holds now: see
242/// [`RequestHandler::admission_load`](crate::RequestHandler::admission_load).
243#[derive(Debug, Clone, Copy, PartialEq, Eq)]
244#[non_exhaustive]
245pub struct AdmissionLoad {
246    /// Turns running through the gate.
247    pub running: usize,
248    /// Sends waiting for a slot.
249    pub queued: usize,
250    /// The gate's capacity.
251    pub capacity: usize,
252}
253
254#[cfg(test)]
255mod tests;