a2a_protocol_server/handler/load.rs
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Tom F. <[email protected]> (https://github.com/tomtom215)
3
4//! The load signal (audit H7, ADR 0046): what a replica holds, for a
5//! balancer, and the saturation readiness that may follow it.
6//!
7//! Readiness stays a dependency check. Load is reported beside it, at
8//! `GET /load` and in the `endpoint-load-metrics` header, when the handler
9//! is built with
10//! [`with_load_reporting`](crate::RequestHandlerBuilder::with_load_reporting);
11//! it drives readiness only when
12//! [`HandlerLimits::with_saturation_readiness`](crate::handler::HandlerLimits::with_saturation_readiness)
13//! is set. Every number is read without a lock on the queue map.
14
15use std::sync::atomic::Ordering;
16
17use super::RequestHandler;
18
19/// The response header carrying the load, in the text form of an ORCA load
20/// report: `TEXT application_utilization=0.250, named_metrics.running=3,
21/// named_metrics.queued=0`.
22pub const LOAD_HEADER: &str = "endpoint-load-metrics";
23
24/// Whether a handler reports its load (ADR 0046).
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26pub enum LoadReporting {
27 /// No `/load`, no header: the default.
28 Off,
29 /// `/load` is served and responses carry [`LOAD_HEADER`].
30 On,
31}
32
33/// What one replica holds now: see [`RequestHandler::load`].
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35#[non_exhaustive]
36pub struct LoadReport {
37 /// Turns running: the live event queues, one per running turn.
38 pub running: usize,
39 /// Sends waiting in the admission gate (ADR 0045); `0` without one.
40 pub queued: usize,
41 /// The admission gate's capacity when there is a gate, else the
42 /// concurrent-stream cap, else `None` (unbounded).
43 pub capacity: Option<usize>,
44 /// The replica is [draining](RequestHandler::begin_draining).
45 pub draining: bool,
46 /// A halt of every tenant is held ([`HaltScope::All`](crate::HaltScope::All)).
47 pub halted: bool,
48}
49
50impl LoadReport {
51 /// `(running + queued) / capacity` in thousandths, rounded down, which
52 /// passes 1000 when sends are queued; `None` with no capacity or a
53 /// capacity of 0.
54 #[must_use]
55 pub fn utilization_permille(&self) -> Option<u64> {
56 let demand = wide(self.running) + wide(self.queued);
57 let permille = (demand * 1000).checked_div(wide(self.capacity?))?;
58 Some(u64::try_from(permille).unwrap_or(u64::MAX))
59 }
60
61 /// [`utilization_permille`](Self::utilization_permille) as a decimal
62 /// with three places, as the header and `/load` write it.
63 fn utilization_text(&self) -> Option<String> {
64 self.utilization_permille()
65 .map(|p| format!("{}.{:03}", p / 1000, p % 1000))
66 }
67
68 /// The `/load` body.
69 #[must_use]
70 pub fn to_json(&self) -> serde_json::Value {
71 let utilization = self
72 .utilization_text()
73 .and_then(|text| text.parse::<serde_json::Number>().ok());
74 serde_json::json!({
75 "running": self.running,
76 "queued": self.queued,
77 "capacity": self.capacity,
78 "utilization": utilization,
79 "draining": self.draining,
80 "halted": self.halted,
81 })
82 }
83
84 /// The [`LOAD_HEADER`] value; with no capacity it has no utilization.
85 #[must_use]
86 pub fn header_value(&self) -> String {
87 let named = format!(
88 "named_metrics.running={}, named_metrics.queued={}",
89 self.running, self.queued
90 );
91 self.utilization_text().map_or_else(
92 || format!("TEXT {named}"),
93 |u| format!("TEXT application_utilization={u}, {named}"),
94 )
95 }
96}
97
98/// `n` as a `u128`, which holds every `usize`.
99fn wide(n: usize) -> u128 {
100 u128::try_from(n).unwrap_or(u128::MAX)
101}
102
103/// Whether a replica is saturated after a probe that read `permille`, given
104/// whether it was before: it becomes so at `unready_at` percent and stays so
105/// until it is at or below `ready_at` percent. The band between the two is
106/// the hysteresis.
107fn next_saturated(was: bool, permille: u64, unready_at: u8, ready_at: u8) -> bool {
108 if was {
109 permille > u64::from(ready_at) * 10
110 } else {
111 permille >= u64::from(unready_at) * 10
112 }
113}
114
115impl RequestHandler {
116 /// What this replica holds now (ADR 0046). Cheap: atomics and two short
117 /// locks, no store call and no lock on the queue map.
118 #[must_use]
119 pub fn load(&self) -> LoadReport {
120 let admission = self.admission_load();
121 LoadReport {
122 running: self.event_queue_manager.live_queues(),
123 queued: admission.map_or(0, |load| load.queued),
124 capacity: admission
125 .map(|load| load.capacity)
126 .or_else(|| self.event_queue_manager.max_concurrent_queues()),
127 draining: self.is_draining(),
128 halted: self.is_halted_everywhere(),
129 }
130 }
131
132 /// Whether readiness should answer `"saturated"`, updating the
133 /// hysteresis state; always `false` unless saturation readiness is set
134 /// and there is a capacity to measure against.
135 pub(crate) fn saturated(&self) -> bool {
136 let Some((unready_at, ready_at)) = self.limits.saturation_readiness else {
137 return false;
138 };
139 let Some(permille) = self.load().utilization_permille() else {
140 return false;
141 };
142 let was = self.saturated.load(Ordering::Acquire);
143 let now = next_saturated(was, permille, unready_at, ready_at);
144 self.saturated.store(now, Ordering::Release);
145 now
146 }
147
148 /// Adds [`LOAD_HEADER`] to a response, when load reporting is on.
149 pub(crate) fn stamp_load(&self, headers: &mut hyper::HeaderMap) {
150 if !self.reports_load() {
151 return;
152 }
153 if let Ok(value) = hyper::header::HeaderValue::try_from(self.load().header_value()) {
154 headers.insert(LOAD_HEADER, value);
155 }
156 }
157
158 /// Whether load reporting is on: `/load` is served and responses carry
159 /// [`LOAD_HEADER`].
160 #[must_use]
161 pub const fn reports_load(&self) -> bool {
162 matches!(self.load_reporting, LoadReporting::On)
163 }
164}
165
166#[cfg(test)]
167#[path = "load_tests.rs"]
168mod tests;