onetaskgraph_plugin_api/quota.rs
1//! What a source's backend says is left of the allowance it meters the source's credential by,
2//! and the gate a caller installs to wait or stop between any two requests a call sends.
3//!
4//! [`Metering`](crate::Metering) is what this source *spent*; a [`QuotaReading`] is what the
5//! backend says is *left*, which other work drawing on the same credential moves too. The store
6//! reports the reading and decides nothing about it: what it means — a floor to keep, a pause to
7//! take — is the caller's.
8//!
9//! A reading taken before a call of hundreds of requests cannot keep a caller's floor inside
10//! it, so a caller that needs to pace inside one installs a [`RequestGate`]. A source asks it,
11//! through [`<dyn RequestGate>::before`], immediately before each request it sends — reads,
12//! writes, retries and a quota read alike — tells it, through
13//! [`<dyn RequestGate>::after`], what each response said is left, and holds the
14//! [`AdmittedRequest`] that ask answered until the request is over, whose drop tells the gate
15//! so through [`RequestGate::request_ended`]. Like
16//! [`WriteGuard`](crate::WriteGuard) the gate is task-local, installed by the engine for the
17//! length of each call it makes to a source: a source that never asks — every one that
18//! predates this — sends exactly what it sent, and one that asks outside a gated call is
19//! answered at once.
20
21use std::future::Future;
22use std::sync::Arc;
23
24use chrono::{DateTime, Utc};
25use schemars::JsonSchema;
26use serde::{Deserialize, Serialize};
27
28use crate::SourceError;
29
30/// What one response — or one read of the backend's own allowance endpoint — said about one
31/// rate-limit window of the backend.
32///
33/// **One window, never merged.** A credential may be metered by several windows of the same
34/// resource at once — GitHub was measured answering one token from two concurrent GraphQL
35/// windows, each with its own reset, while `GET /rate_limit` reported only one of them — so a
36/// source reports each reading as the response that carried it said it, with its own
37/// [`resets_at`](Self::resets_at). Choosing the least of several is the caller's.
38#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
39pub struct QuotaReading {
40 /// The backend's own name for what is metered — GitHub's resource names (`graphql`,
41 /// `core`, `search` and so on), Linear's `requests` and `complexity`.
42 // llmlint: ignore[invalid_states_unrepresentable] An open vocabulary the backend names and the store interprets none of: the contract three other repositories build against states it as a plain string (`resource: String`), and GitHub adds resources (`code_search` arrived after `search`), so an enumeration here would refuse a reading for being new.
43 pub resource: String,
44 /// The whole allowance of the window.
45 pub limit: u64,
46 /// What was left of it when the backend answered.
47 pub remaining: u64,
48 /// What the credential had spent of it — everything that shares the credential, not only
49 /// this source.
50 pub used: u64,
51 /// When the window resets and the allowance comes back.
52 pub resets_at: DateTime<Utc>,
53}
54
55/// One request a source is about to send, as a [`RequestGate`] is asked about it.
56#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
57pub struct GatedRequest {
58 /// The resource the request draws on, in [`QuotaReading::resource`]'s vocabulary; `local`
59 /// for a write a source makes to its own files.
60 // llmlint: ignore[invalid_states_unrepresentable] The same open vocabulary as `QuotaReading::resource`, which a gate compares it against; the contract states it as a plain string.
61 pub resource: String,
62 /// Whether the request creates content — an issue, a comment — which a backend may meter
63 /// by a limit of its own (GitHub's secondary content-creation limits).
64 pub content_creating: bool,
65 /// What the source expects the request to cost against `resource`, when it can say.
66 #[serde(default, skip_serializing_if = "Option::is_none")]
67 pub cost_hint: Option<u64>,
68}
69
70tokio::task_local! {
71 static GATE: Arc<dyn RequestGate>;
72}
73
74/// What a caller installs to wait or stop between any two requests a store call sends.
75///
76/// It holds the caller's policy; the store holds none. **A wait** — `before_request` not yet
77/// returned — holds that source's next request and nothing else: a source asks it inline, so
78/// another source's call, and another call to the same engine, go on. **A refusal** —
79/// `before_request` answering `Err` — makes the source send nothing more in that call: what
80/// already landed is answered as it is today, the item in flight as a failure part way
81/// through it, and every later item of a batch with the refusal, nothing sent for it.
82///
83/// **One request is exempt: a stdio peer's `initialize` handshake.** The engine sends it once,
84/// while the engine is being built, before `Engine::with_request_gate` can install a gate, and
85/// it costs no backend quota. Every method sent a peer after the gate is installed is asked of
86/// it first.
87///
88/// **Every admitted request ends, exactly once.** For each `before_request` that answered `Ok`
89/// the gate is told [`request_ended`](Self::request_ended) once, whatever became of the
90/// request — answered with readings or without, failed in transport before any header arrived,
91/// a write to a source's own files, or its future dropped mid-flight by a cancellation or by a
92/// sibling failing beside it. A request `before_request` refused is never ended, and neither is
93/// one whose `before_request` future was itself dropped before it answered: a gate that takes
94/// something inside `before_request` gives it back on its own drop path there.
95#[async_trait::async_trait]
96pub trait RequestGate: Send + Sync {
97 /// Answer whether `request` may be sent now — after as long a wait as the caller's policy
98 /// asks for — or why not.
99 ///
100 /// # Errors
101 ///
102 /// The refusal the source is to fail its call with, sending nothing more.
103 async fn before_request(&self, request: &GatedRequest) -> Result<(), SourceError>;
104
105 /// What the response to a request said about each window it named.
106 fn after_response(&self, readings: &[QuotaReading]);
107
108 /// One request this gate admitted is over: nothing more of it will be sent or read, so a
109 /// gate may treat this as proof that it is no longer in flight — a slot it keeps per
110 /// request in flight can be given back. Delivered exactly once per admitted request, after
111 /// any [`after_response`](Self::after_response) its response carried, and never for a
112 /// request `before_request` refused. A gate that keeps no such count needs nothing here.
113 fn request_ended(&self) {}
114}
115
116/// A request a [`RequestGate`] admitted, held by the source for as long as the request is in
117/// flight: dropping it — on every exit, a cancelled or failed one included — tells the gate the
118/// request is over through [`RequestGate::request_ended`], exactly once.
119///
120/// Bind it (`let admitted = …`) and drop it once the response has been read, or the request
121/// failed; never hold it across a wait before a retry or across another request's ask, since a
122/// gate admitting one request at a time would then wait on itself.
123#[must_use = "dropping the admission at once tells the gate the request is over before it is sent"]
124pub struct AdmittedRequest {
125 gate: Option<Arc<dyn RequestGate>>,
126}
127
128impl AdmittedRequest {
129 /// End the request now, rather than when the admission goes out of scope.
130 pub fn end(self) {}
131}
132
133impl std::fmt::Debug for AdmittedRequest {
134 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
135 formatter
136 .debug_struct("AdmittedRequest")
137 .field("gated", &self.gate.is_some())
138 .finish()
139 }
140}
141
142impl Drop for AdmittedRequest {
143 fn drop(&mut self) {
144 if let Some(gate) = self.gate.take() {
145 gate.request_ended();
146 }
147 }
148}
149
150impl dyn RequestGate {
151 /// Run `call` with `gate` answering every [`<dyn RequestGate>::before`] and
152 /// [`<dyn RequestGate>::after`] made inside it.
153 pub async fn scope<F: Future>(gate: Arc<dyn RequestGate>, call: F) -> F::Output {
154 GATE.scope(gate, call).await
155 }
156
157 /// The gate of the call in progress, if any — what a call that spawns work of its own
158 /// carries into it with [`Self::scope`].
159 #[must_use]
160 pub fn current() -> Option<Arc<dyn RequestGate>> {
161 GATE.try_with(Arc::clone).ok()
162 }
163
164 /// Ask the gate of the call in progress, if any, whether `request` may be sent now — a
165 /// source calls this immediately before sending each request, and holds the answer until
166 /// the request is over: see [`AdmittedRequest`]. The admission ends at the gate that
167 /// admitted it, wherever it is dropped.
168 ///
169 /// # Errors
170 ///
171 /// The gate's refusal, which admits nothing and is never ended; with no gate installed,
172 /// never.
173 pub async fn before(request: &GatedRequest) -> Result<AdmittedRequest, SourceError> {
174 match Self::current() {
175 Some(gate) => {
176 gate.before_request(request).await?;
177 Ok(AdmittedRequest { gate: Some(gate) })
178 }
179 None => Ok(AdmittedRequest { gate: None }),
180 }
181 }
182
183 /// Tell the gate of the call in progress, if any, what a response said is left; with no
184 /// gate installed, or no readings, nothing happens.
185 pub fn after(readings: &[QuotaReading]) {
186 if readings.is_empty() {
187 return;
188 }
189 if let Some(gate) = Self::current() {
190 gate.after_response(readings);
191 }
192 }
193}
194
195#[cfg(test)]
196mod tests {
197 use super::*;
198 use std::sync::Mutex;
199
200 /// A gate recording what it was asked and told, refusing once it has been asked `refuse_at`
201 /// times.
202 struct Recording {
203 asked: Mutex<Vec<GatedRequest>>,
204 told: Mutex<Vec<QuotaReading>>,
205 ended: Mutex<usize>,
206 refuse_at: usize,
207 }
208
209 impl Recording {
210 fn refusing_at(refuse_at: usize) -> Arc<Self> {
211 Arc::new(Self {
212 asked: Mutex::new(Vec::new()),
213 told: Mutex::new(Vec::new()),
214 ended: Mutex::new(0),
215 refuse_at,
216 })
217 }
218
219 fn ended(&self) -> usize {
220 *self.ended.lock().unwrap()
221 }
222 }
223
224 #[async_trait::async_trait]
225 impl RequestGate for Recording {
226 async fn before_request(&self, request: &GatedRequest) -> Result<(), SourceError> {
227 let mut asked = self.asked.lock().unwrap();
228 asked.push(request.clone());
229 if asked.len() >= self.refuse_at {
230 return Err(SourceError::Refused {
231 message: "the gate refused".into(),
232 });
233 }
234 Ok(())
235 }
236
237 fn after_response(&self, readings: &[QuotaReading]) {
238 self.told.lock().unwrap().extend_from_slice(readings);
239 }
240
241 fn request_ended(&self) {
242 *self.ended.lock().unwrap() += 1;
243 }
244 }
245
246 fn request(resource: &str) -> GatedRequest {
247 GatedRequest {
248 resource: resource.into(),
249 content_creating: false,
250 cost_hint: None,
251 }
252 }
253
254 fn reading() -> QuotaReading {
255 QuotaReading {
256 resource: "graphql".into(),
257 limit: 5_000,
258 remaining: 4_000,
259 used: 1_000,
260 resets_at: DateTime::from_timestamp(1_795_306_927, 0).unwrap(),
261 }
262 }
263
264 #[tokio::test]
265 async fn with_no_gate_installed_every_request_may_be_sent_and_nothing_is_told() {
266 assert!(<dyn RequestGate>::before(&request("graphql")).await.is_ok());
267 <dyn RequestGate>::after(&[reading()]);
268 assert!(<dyn RequestGate>::current().is_none());
269 }
270
271 #[tokio::test]
272 async fn inside_a_scope_the_gate_is_asked_told_and_its_refusal_is_answered() {
273 let gate = Recording::refusing_at(2);
274 let installed: Arc<dyn RequestGate> = gate.clone();
275 let (first, second) = <dyn RequestGate>::scope(installed, async {
276 let first = <dyn RequestGate>::before(&request("graphql"))
277 .await
278 .map(drop);
279 <dyn RequestGate>::after(&[reading()]);
280 <dyn RequestGate>::after(&[]);
281 let second = <dyn RequestGate>::before(&request("core")).await.map(drop);
282 (first, second)
283 })
284 .await;
285 assert!(first.is_ok());
286 assert_eq!(
287 second,
288 Err(SourceError::Refused {
289 message: "the gate refused".into()
290 })
291 );
292 // The admitted request ended once; the refused one was never admitted, so never ends.
293 assert_eq!(gate.ended(), 1);
294 assert_eq!(
295 *gate.asked.lock().unwrap(),
296 [request("graphql"), request("core")]
297 );
298 assert_eq!(*gate.told.lock().unwrap(), [reading()]);
299 // Outside the scope, nothing is asked and nothing ends.
300 assert!(<dyn RequestGate>::before(&request("graphql")).await.is_ok());
301 assert_eq!(gate.asked.lock().unwrap().len(), 2);
302 assert_eq!(gate.ended(), 1);
303 }
304
305 #[tokio::test]
306 async fn an_admission_ends_once_when_dropped_and_only_then_at_the_gate_that_admitted_it() {
307 let gate = Recording::refusing_at(usize::MAX);
308 let installed: Arc<dyn RequestGate> = gate.clone();
309 let admitted = <dyn RequestGate>::scope(installed, async {
310 <dyn RequestGate>::before(&request("graphql")).await
311 })
312 .await
313 .expect("admitted");
314 // Still in flight while the source holds it, though its scope is over.
315 assert_eq!(gate.ended(), 0);
316 admitted.end();
317 assert_eq!(gate.ended(), 1);
318 }
319
320 #[tokio::test]
321 async fn a_request_future_dropped_in_flight_ends_its_admission_once() {
322 let gate = Recording::refusing_at(usize::MAX);
323 let installed: Arc<dyn RequestGate> = gate.clone();
324 let (started, mut start) = tokio::sync::oneshot::channel::<()>();
325 let in_flight = <dyn RequestGate>::scope(installed, async move {
326 let _admitted = <dyn RequestGate>::before(&request("graphql")).await?;
327 drop(started);
328 // A response that never comes: the future is dropped while it waits.
329 std::future::pending::<()>().await;
330 Ok::<(), SourceError>(())
331 });
332 let in_flight = tokio::spawn(in_flight);
333 // The sender is dropped once the request was admitted and is in flight.
334 assert!((&mut start).await.is_err());
335 assert_eq!(gate.ended(), 0);
336 in_flight.abort();
337 assert!(in_flight.await.unwrap_err().is_cancelled());
338 assert_eq!(gate.ended(), 1);
339 }
340
341 #[test]
342 fn a_reading_serialises_as_the_contract_states_it() {
343 assert_eq!(
344 serde_json::to_value(reading()).unwrap(),
345 serde_json::json!({"resource":"graphql","limit":5000,"remaining":4000,
346 "used":1000,"resets_at":"2026-11-22T00:22:07Z"})
347 );
348 }
349}