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