a2a_protocol_server/handler/
turn_slots.rs1use 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#[derive(Debug)]
20pub struct TurnSlots {
21 pub tenant: Option<OwnedSemaphorePermit>,
22 pub admission: Option<AdmissionPermit>,
23}
24
25impl TurnSlots {
26 pub fn into_parts(self) -> (Option<OwnedSemaphorePermit>, Option<AdmissionPermit>) {
28 (self.tenant, self.admission)
29 }
30}
31
32impl RequestHandler {
33 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 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 #[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}