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 — and tells it, through
13//! [`<dyn RequestGate>::after`], what each response said is left. Like
14//! [`WriteGuard`](crate::WriteGuard) the gate is task-local, installed by the engine for the
15//! length of each call it makes to a source: a source that never asks — every one that
16//! predates this — sends exactly what it sent, and one that asks outside a gated call is
17//! answered at once.
18
19use std::future::Future;
20use std::sync::Arc;
21
22use chrono::{DateTime, Utc};
23use schemars::JsonSchema;
24use serde::{Deserialize, Serialize};
25
26use crate::SourceError;
27
28/// What one response — or one read of the backend's own allowance endpoint — said about one
29/// rate-limit window of the backend.
30///
31/// **One window, never merged.** A credential may be metered by several windows of the same
32/// resource at once — GitHub was measured answering one token from two concurrent GraphQL
33/// windows, each with its own reset, while `GET /rate_limit` reported only one of them — so a
34/// source reports each reading as the response that carried it said it, with its own
35/// [`resets_at`](Self::resets_at). Choosing the least of several is the caller's.
36#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
37pub struct QuotaReading {
38 /// The backend's own name for what is metered — GitHub's resource names (`graphql`,
39 /// `core`, `search` and so on), Linear's `requests` and `complexity`.
40 // 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.
41 pub resource: String,
42 /// The whole allowance of the window.
43 pub limit: u64,
44 /// What was left of it when the backend answered.
45 pub remaining: u64,
46 /// What the credential had spent of it — everything that shares the credential, not only
47 /// this source.
48 pub used: u64,
49 /// When the window resets and the allowance comes back.
50 pub resets_at: DateTime<Utc>,
51}
52
53/// One request a source is about to send, as a [`RequestGate`] is asked about it.
54#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
55pub struct GatedRequest {
56 /// The resource the request draws on, in [`QuotaReading::resource`]'s vocabulary; `local`
57 /// for a write a source makes to its own files.
58 // 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.
59 pub resource: String,
60 /// Whether the request creates content — an issue, a comment — which a backend may meter
61 /// by a limit of its own (GitHub's secondary content-creation limits).
62 pub content_creating: bool,
63 /// What the source expects the request to cost against `resource`, when it can say.
64 #[serde(default, skip_serializing_if = "Option::is_none")]
65 pub cost_hint: Option<u64>,
66}
67
68tokio::task_local! {
69 static GATE: Arc<dyn RequestGate>;
70}
71
72/// What a caller installs to wait or stop between any two requests a store call sends.
73///
74/// It holds the caller's policy; the store holds none. **A wait** — `before_request` not yet
75/// returned — holds that source's next request and nothing else: a source asks it inline, so
76/// another source's call, and another call to the same engine, go on. **A refusal** —
77/// `before_request` answering `Err` — makes the source send nothing more in that call: what
78/// already landed is answered as it is today, the item in flight as a failure part way
79/// through it, and every later item of a batch with the refusal, nothing sent for it.
80///
81/// **One request is exempt: a stdio peer's `initialize` handshake.** The engine sends it once,
82/// while the engine is being built, before `Engine::with_request_gate` can install a gate, and
83/// it costs no backend quota. Every method sent a peer after the gate is installed is asked of
84/// it first.
85#[async_trait::async_trait]
86pub trait RequestGate: Send + Sync {
87 /// Answer whether `request` may be sent now — after as long a wait as the caller's policy
88 /// asks for — or why not.
89 ///
90 /// # Errors
91 ///
92 /// The refusal the source is to fail its call with, sending nothing more.
93 async fn before_request(&self, request: &GatedRequest) -> Result<(), SourceError>;
94
95 /// What the response to a request said about each window it named.
96 fn after_response(&self, readings: &[QuotaReading]);
97}
98
99impl dyn RequestGate {
100 /// Run `call` with `gate` answering every [`<dyn RequestGate>::before`] and
101 /// [`<dyn RequestGate>::after`] made inside it.
102 pub async fn scope<F: Future>(gate: Arc<dyn RequestGate>, call: F) -> F::Output {
103 GATE.scope(gate, call).await
104 }
105
106 /// The gate of the call in progress, if any — what a call that spawns work of its own
107 /// carries into it with [`Self::scope`].
108 #[must_use]
109 pub fn current() -> Option<Arc<dyn RequestGate>> {
110 GATE.try_with(Arc::clone).ok()
111 }
112
113 /// Ask the gate of the call in progress, if any, whether `request` may be sent now — a
114 /// source calls this immediately before sending each request.
115 ///
116 /// # Errors
117 ///
118 /// The gate's refusal; with no gate installed, never.
119 pub async fn before(request: &GatedRequest) -> Result<(), SourceError> {
120 match Self::current() {
121 Some(gate) => gate.before_request(request).await,
122 None => Ok(()),
123 }
124 }
125
126 /// Tell the gate of the call in progress, if any, what a response said is left; with no
127 /// gate installed, or no readings, nothing happens.
128 pub fn after(readings: &[QuotaReading]) {
129 if readings.is_empty() {
130 return;
131 }
132 if let Some(gate) = Self::current() {
133 gate.after_response(readings);
134 }
135 }
136}
137
138#[cfg(test)]
139mod tests {
140 use super::*;
141 use std::sync::Mutex;
142
143 /// A gate recording what it was asked and told, refusing once it has been asked `refuse_at`
144 /// times.
145 struct Recording {
146 asked: Mutex<Vec<GatedRequest>>,
147 told: Mutex<Vec<QuotaReading>>,
148 refuse_at: usize,
149 }
150
151 #[async_trait::async_trait]
152 impl RequestGate for Recording {
153 async fn before_request(&self, request: &GatedRequest) -> Result<(), SourceError> {
154 let mut asked = self.asked.lock().unwrap();
155 asked.push(request.clone());
156 if asked.len() >= self.refuse_at {
157 return Err(SourceError::Refused {
158 message: "the gate refused".into(),
159 });
160 }
161 Ok(())
162 }
163
164 fn after_response(&self, readings: &[QuotaReading]) {
165 self.told.lock().unwrap().extend_from_slice(readings);
166 }
167 }
168
169 fn request(resource: &str) -> GatedRequest {
170 GatedRequest {
171 resource: resource.into(),
172 content_creating: false,
173 cost_hint: None,
174 }
175 }
176
177 fn reading() -> QuotaReading {
178 QuotaReading {
179 resource: "graphql".into(),
180 limit: 5_000,
181 remaining: 4_000,
182 used: 1_000,
183 resets_at: DateTime::from_timestamp(1_795_306_927, 0).unwrap(),
184 }
185 }
186
187 #[tokio::test]
188 async fn with_no_gate_installed_every_request_may_be_sent_and_nothing_is_told() {
189 assert!(<dyn RequestGate>::before(&request("graphql")).await.is_ok());
190 <dyn RequestGate>::after(&[reading()]);
191 assert!(<dyn RequestGate>::current().is_none());
192 }
193
194 #[tokio::test]
195 async fn inside_a_scope_the_gate_is_asked_told_and_its_refusal_is_answered() {
196 let gate = Arc::new(Recording {
197 asked: Mutex::new(Vec::new()),
198 told: Mutex::new(Vec::new()),
199 refuse_at: 2,
200 });
201 let installed: Arc<dyn RequestGate> = gate.clone();
202 let (first, second) = <dyn RequestGate>::scope(installed, async {
203 let first = <dyn RequestGate>::before(&request("graphql")).await;
204 <dyn RequestGate>::after(&[reading()]);
205 <dyn RequestGate>::after(&[]);
206 let second = <dyn RequestGate>::before(&request("core")).await;
207 (first, second)
208 })
209 .await;
210 assert!(first.is_ok());
211 assert_eq!(
212 second,
213 Err(SourceError::Refused {
214 message: "the gate refused".into()
215 })
216 );
217 assert_eq!(
218 *gate.asked.lock().unwrap(),
219 [request("graphql"), request("core")]
220 );
221 assert_eq!(*gate.told.lock().unwrap(), [reading()]);
222 // Outside the scope, nothing is asked.
223 assert!(<dyn RequestGate>::before(&request("graphql")).await.is_ok());
224 assert_eq!(gate.asked.lock().unwrap().len(), 2);
225 }
226
227 #[test]
228 fn a_reading_serialises_as_the_contract_states_it() {
229 assert_eq!(
230 serde_json::to_value(reading()).unwrap(),
231 serde_json::json!({"resource":"graphql","limit":5000,"remaining":4000,
232 "used":1000,"resets_at":"2026-11-22T00:22:07Z"})
233 );
234 }
235}