use std::future::Future;
use std::sync::Arc;
use chrono::{DateTime, Utc};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use crate::SourceError;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct QuotaReading {
pub resource: String,
pub limit: u64,
pub remaining: u64,
pub used: u64,
pub resets_at: DateTime<Utc>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct GatedRequest {
pub resource: String,
pub content_creating: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cost_hint: Option<u64>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct ReportedCost {
pub resource: String,
pub cost: u64,
}
tokio::task_local! {
static GATE: Arc<dyn RequestGate>;
}
#[async_trait::async_trait]
pub trait RequestGate: Send + Sync {
async fn before_request(&self, request: &GatedRequest) -> Result<(), SourceError>;
fn after_response(&self, readings: &[QuotaReading]);
fn request_ended(&self) {}
#[expect(
unused_variables,
reason = "the contract names the parameter `cost`, and a gate that keeps no costs needs nothing here"
)]
fn cost_reported(&self, cost: &ReportedCost) {}
}
#[must_use = "dropping the admission at once tells the gate the request is over before it is sent"]
pub struct AdmittedRequest {
gate: Option<Arc<dyn RequestGate>>,
}
impl AdmittedRequest {
pub fn end(self) {}
pub fn end_reporting(self, cost: &ReportedCost) {
if let Some(gate) = &self.gate {
gate.cost_reported(cost);
}
}
}
impl std::fmt::Debug for AdmittedRequest {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("AdmittedRequest")
.field("gated", &self.gate.is_some())
.finish()
}
}
impl Drop for AdmittedRequest {
fn drop(&mut self) {
if let Some(gate) = self.gate.take() {
gate.request_ended();
}
}
}
impl dyn RequestGate {
pub async fn scope<F: Future>(gate: Arc<dyn RequestGate>, call: F) -> F::Output {
GATE.scope(gate, call).await
}
#[must_use]
pub fn current() -> Option<Arc<dyn RequestGate>> {
GATE.try_with(Arc::clone).ok()
}
pub async fn before(request: &GatedRequest) -> Result<AdmittedRequest, SourceError> {
match Self::current() {
Some(gate) => {
gate.before_request(request).await?;
Ok(AdmittedRequest { gate: Some(gate) })
}
None => Ok(AdmittedRequest { gate: None }),
}
}
pub fn after(readings: &[QuotaReading]) {
if readings.is_empty() {
return;
}
if let Some(gate) = Self::current() {
gate.after_response(readings);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Mutex;
struct Recording {
asked: Mutex<Vec<GatedRequest>>,
told: Mutex<Vec<QuotaReading>>,
ended: Mutex<usize>,
events: Mutex<Vec<String>>,
refuse_at: usize,
}
impl Recording {
fn refusing_at(refuse_at: usize) -> Arc<Self> {
Arc::new(Self {
asked: Mutex::new(Vec::new()),
told: Mutex::new(Vec::new()),
ended: Mutex::new(0),
events: Mutex::new(Vec::new()),
refuse_at,
})
}
fn ended(&self) -> usize {
*self.ended.lock().unwrap()
}
}
#[async_trait::async_trait]
impl RequestGate for Recording {
async fn before_request(&self, request: &GatedRequest) -> Result<(), SourceError> {
let mut asked = self.asked.lock().unwrap();
asked.push(request.clone());
if asked.len() >= self.refuse_at {
return Err(SourceError::Refused {
message: "the gate refused".into(),
});
}
Ok(())
}
fn after_response(&self, readings: &[QuotaReading]) {
self.told.lock().unwrap().extend_from_slice(readings);
self.events.lock().unwrap().push("readings".into());
}
fn request_ended(&self) {
*self.ended.lock().unwrap() += 1;
self.events.lock().unwrap().push("ended".into());
}
fn cost_reported(&self, cost: &ReportedCost) {
self.events
.lock()
.unwrap()
.push(format!("cost {} {}", cost.resource, cost.cost));
}
}
struct Silent;
#[async_trait::async_trait]
impl RequestGate for Silent {
async fn before_request(&self, _: &GatedRequest) -> Result<(), SourceError> {
Ok(())
}
fn after_response(&self, _: &[QuotaReading]) {}
}
fn charged(cost: u64) -> ReportedCost {
ReportedCost {
resource: "graphql".into(),
cost,
}
}
#[tokio::test]
async fn a_reported_cost_reaches_the_gate_after_the_readings_and_before_the_end_once() {
let gate = Recording::refusing_at(usize::MAX);
let installed: Arc<dyn RequestGate> = gate.clone();
<dyn RequestGate>::scope(installed, async {
let answered = <dyn RequestGate>::before(&request("graphql"))
.await
.unwrap();
<dyn RequestGate>::after(&[reading()]);
answered.end_reporting(&charged(3));
let unpriced = <dyn RequestGate>::before(&request("core")).await.unwrap();
<dyn RequestGate>::after(&[reading()]);
unpriced.end();
})
.await;
assert_eq!(
*gate.events.lock().unwrap(),
["readings", "cost graphql 3", "ended", "readings", "ended"]
);
assert_eq!(gate.ended(), 2);
}
#[tokio::test]
async fn a_gate_keeping_no_costs_is_told_one_by_its_default_and_ungated_requests_tell_none() {
let installed: Arc<dyn RequestGate> = Arc::new(Silent);
<dyn RequestGate>::scope(installed, async {
<dyn RequestGate>::before(&request("graphql"))
.await
.unwrap()
.end_reporting(&charged(1));
})
.await;
<dyn RequestGate>::before(&request("graphql"))
.await
.unwrap()
.end_reporting(&charged(1));
}
#[test]
fn a_reported_cost_serialises_as_the_contract_states_it() {
assert_eq!(
serde_json::to_value(charged(21)).unwrap(),
serde_json::json!({"resource":"graphql","cost":21})
);
}
fn request(resource: &str) -> GatedRequest {
GatedRequest {
resource: resource.into(),
content_creating: false,
cost_hint: None,
}
}
fn reading() -> QuotaReading {
QuotaReading {
resource: "graphql".into(),
limit: 5_000,
remaining: 4_000,
used: 1_000,
resets_at: DateTime::from_timestamp(1_795_306_927, 0).unwrap(),
}
}
#[tokio::test]
async fn with_no_gate_installed_every_request_may_be_sent_and_nothing_is_told() {
assert!(<dyn RequestGate>::before(&request("graphql")).await.is_ok());
<dyn RequestGate>::after(&[reading()]);
assert!(<dyn RequestGate>::current().is_none());
}
#[tokio::test]
async fn inside_a_scope_the_gate_is_asked_told_and_its_refusal_is_answered() {
let gate = Recording::refusing_at(2);
let installed: Arc<dyn RequestGate> = gate.clone();
let (first, second) = <dyn RequestGate>::scope(installed, async {
let first = <dyn RequestGate>::before(&request("graphql"))
.await
.map(drop);
<dyn RequestGate>::after(&[reading()]);
<dyn RequestGate>::after(&[]);
let second = <dyn RequestGate>::before(&request("core")).await.map(drop);
(first, second)
})
.await;
assert!(first.is_ok());
assert_eq!(
second,
Err(SourceError::Refused {
message: "the gate refused".into()
})
);
assert_eq!(gate.ended(), 1);
assert_eq!(
*gate.asked.lock().unwrap(),
[request("graphql"), request("core")]
);
assert_eq!(*gate.told.lock().unwrap(), [reading()]);
assert!(<dyn RequestGate>::before(&request("graphql")).await.is_ok());
assert_eq!(gate.asked.lock().unwrap().len(), 2);
assert_eq!(gate.ended(), 1);
}
#[tokio::test]
async fn an_admission_ends_once_when_dropped_and_only_then_at_the_gate_that_admitted_it() {
let gate = Recording::refusing_at(usize::MAX);
let installed: Arc<dyn RequestGate> = gate.clone();
let admitted = <dyn RequestGate>::scope(installed, async {
<dyn RequestGate>::before(&request("graphql")).await
})
.await
.expect("admitted");
assert_eq!(gate.ended(), 0);
admitted.end();
assert_eq!(gate.ended(), 1);
}
#[tokio::test]
async fn a_request_future_dropped_in_flight_ends_its_admission_once() {
let gate = Recording::refusing_at(usize::MAX);
let installed: Arc<dyn RequestGate> = gate.clone();
let (started, mut start) = tokio::sync::oneshot::channel::<()>();
let in_flight = <dyn RequestGate>::scope(installed, async move {
let _admitted = <dyn RequestGate>::before(&request("graphql")).await?;
drop(started);
std::future::pending::<()>().await;
Ok::<(), SourceError>(())
});
let in_flight = tokio::spawn(in_flight);
assert!((&mut start).await.is_err());
assert_eq!(gate.ended(), 0);
in_flight.abort();
assert!(in_flight.await.unwrap_err().is_cancelled());
assert_eq!(gate.ended(), 1);
}
#[test]
fn a_reading_serialises_as_the_contract_states_it() {
assert_eq!(
serde_json::to_value(reading()).unwrap(),
serde_json::json!({"resource":"graphql","limit":5000,"remaining":4000,
"used":1000,"resets_at":"2026-11-22T00:22:07Z"})
);
}
}