Skip to content

Lightweight native Discord client for Windows, Linux and macOS, written in Rust. No Electron, no browser engine.

7.8 KB
Raw Blame
//! Pacing for Discord's REST API.
//!
//! Every response says how many more requests its route may make
//! (`X-RateLimit-Remaining`) and when that count resets
//! (`X-RateLimit-Reset-After`). Requests wait for the reset instead of
//! running into a 429; a 429 holds back every request on its route, or all of
//! them for the global limit. Pages of older messages are paced on top of
//! that: scrolling back through years of history at network speed stays under
//! every per-route limit, yet looks like scraping to Discord's anti-spam,
//! which suspends accounts for it.

use reqwest::header::HeaderMap;
use reqwest::Method;
use std::collections::HashMap;
use std::sync::{LazyLock, Mutex};
use std::time::{Duration, Instant};

/// Longest a single wait may be: a route that asks for more is tried again
/// after this and told to wait again.
const MAX_WAIT: Duration = Duration::from_secs(60);

/// What Discord last said about a route.
struct Route {
    remaining: u32,
    reset_at: Instant,
}

static ROUTES: LazyLock<Mutex<HashMap<String, Route>>> = LazyLock::new(|| Mutex::new(HashMap::new()));
/// Until when every request waits (a global 429).
static GLOBAL_UNTIL: Mutex<Option<Instant>> = Mutex::new(None);

/// The route a request counts against: its method and path, with every ID
/// but the first channel, guild or webhook ID (Discord's "major parameter",
/// which gets its own limits) replaced, and without the query string.
pub fn route_key(method: &Method, path: &str) -> String {
    let path = path.split('?').next().unwrap_or(path);
    let mut key = String::with_capacity(path.len() + 8);
    key.push_str(method.as_str());
    let mut prev = "";
    let mut major_seen = false;
    for seg in path.split('/').filter(|s| !s.is_empty()) {
        key.push('/');
        let is_id = seg.bytes().all(|b| b.is_ascii_digit());
        if is_id && !major_seen && matches!(prev, "channels" | "guilds" | "webhooks") {
            major_seen = true;
            key.push_str(seg);
        } else if is_id {
            key.push_str(":id");
        } else {
            key.push_str(seg);
        }
        prev = seg;
    }
    key
}

/// How long `route` must wait now; zero means go, and counts the request.
fn reserve(route: &str, now: Instant) -> Duration {
    let global = GLOBAL_UNTIL.lock().unwrap().map_or(Duration::ZERO, |t| t.saturating_duration_since(now));
    if !global.is_zero() {
        return global;
    }
    let mut routes = ROUTES.lock().unwrap();
    let Some(r) = routes.get_mut(route) else { return Duration::ZERO };
    if r.reset_at <= now {
        // Its window is over; the next response says what the new one allows.
        routes.remove(route);
        Duration::ZERO
    } else if r.remaining == 0 {
        r.reset_at - now
    } else {
        r.remaining -= 1;
        Duration::ZERO
    }
}

/// Wait until `route` (and the API as a whole) may take another request, and
/// count this one against it.
pub async fn acquire(route: &str) {
    loop {
        let delay = reserve(route, Instant::now());
        if delay.is_zero() {
            return;
        }
        log::info!("rate limit: holding {route} for {:.1}s", delay.as_secs_f64());
        tokio::time::sleep(delay.min(MAX_WAIT)).await;
    }
}

/// Remember what a response's headers say about its route.
pub fn update(route: &str, headers: &HeaderMap) {
    let num = |name: &str| headers.get(name).and_then(|v| v.to_str().ok()).and_then(|s| s.parse::<f64>().ok());
    let (Some(remaining), Some(reset_after)) = (num("x-ratelimit-remaining"), num("x-ratelimit-reset-after")) else {
        return;
    };
    if !remaining.is_finite() || !reset_after.is_finite() {
        return;
    }
    let reset_at = Instant::now() + Duration::from_secs_f64(reset_after.clamp(0.0, MAX_WAIT.as_secs_f64()));
    let mut routes = ROUTES.lock().unwrap();
    // Routes whose window is over say nothing any more: drop them now and
    // then, so the map doesn't keep one per channel ever opened.
    if routes.len() >= 256 {
        let now = Instant::now();
        routes.retain(|_, r| r.reset_at > now);
    }
    routes.insert(route.to_string(), Route { remaining: remaining as u32, reset_at });
}

/// Discord answered 429: hold the route (or, for the global limit, every
/// request) for `retry_after` seconds.
pub fn limited(route: &str, retry_after: f64, global: bool) {
    let retry_after = if retry_after.is_finite() { retry_after } else { MAX_WAIT.as_secs_f64() };
    let until = Instant::now() + Duration::from_secs_f64(retry_after.clamp(0.0, MAX_WAIT.as_secs_f64()) + 0.05);
    if global {
        let mut g = GLOBAL_UNTIL.lock().unwrap();
        *g = Some(g.map_or(until, |t| t.max(until)));
    } else {
        ROUTES.lock().unwrap().insert(route.to_string(), Route { remaining: 0, reset_at: until });
    }
}

/// A token bucket: `capacity` at once, refilled at `per_sec`. Taking from an
/// empty one reserves the next token, so callers queue up instead of racing.
struct Bucket {
    tokens: f64,
    capacity: f64,
    per_sec: f64,
    at: Instant,
}

impl Bucket {
    fn new(capacity: f64, per_sec: f64) -> Self {
        Self { tokens: capacity, capacity, per_sec, at: Instant::now() }
    }

    /// Take a token; how long to wait before using it.
    fn take(&mut self, now: Instant) -> Duration {
        let refill = now.saturating_duration_since(self.at).as_secs_f64() * self.per_sec;
        self.tokens = (self.tokens + refill).min(self.capacity) - 1.0;
        self.at = now;
        if self.tokens >= 0.0 {
            Duration::ZERO
        } else {
            Duration::from_secs_f64(-self.tokens / self.per_sec)
        }
    }
}

/// Older-message pages, across all channels: 3 at once, then one every 2 s;
/// a long scroll back (30 pages, about 1,500 messages, within a few minutes)
/// slows to one every 10 s. Discord's own client never pages faster than a
/// person reads, so neither does this.
static HISTORY: LazyLock<Mutex<(Bucket, Bucket)>> =
    LazyLock::new(|| Mutex::new((Bucket::new(3.0, 0.5), Bucket::new(30.0, 0.1))));

/// Wait for the turn of the next page of older messages; how long that was.
pub async fn history_page() -> Duration {
    let delay = {
        let now = Instant::now();
        let mut h = HISTORY.lock().unwrap();
        let (short, long) = &mut *h;
        short.take(now).max(long.take(now))
    };
    if !delay.is_zero() {
        log::info!("history: next older page in {:.1}s", delay.as_secs_f64());
        tokio::time::sleep(delay).await;
    }
    delay
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn route_keys_keep_only_the_major_id() {
        assert_eq!(route_key(&Method::GET, "/channels/123/messages?limit=50&before=9"), "GET/channels/123/messages");
        assert_eq!(route_key(&Method::DELETE, "/channels/123/messages/456"), "DELETE/channels/123/messages/:id");
        assert_eq!(route_key(&Method::GET, "/users/42/profile"), "GET/users/:id/profile");
        assert_eq!(route_key(&Method::POST, "/channels/7/call/ring"), "POST/channels/7/call/ring");
    }

    #[test]
    fn bucket_bursts_then_spaces_out() {
        let t0 = Instant::now();
        let mut b = Bucket { tokens: 3.0, capacity: 3.0, per_sec: 0.5, at: t0 };
        for _ in 0..3 {
            assert!(b.take(t0).is_zero());
        }
        assert_eq!(b.take(t0), Duration::from_secs(2));
        // The next caller queues behind the one already waiting.
        assert_eq!(b.take(t0), Duration::from_secs(4));
    }

    #[test]
    fn exhausted_route_waits_for_its_reset() {
        let route = "GET/test/exhausted";
        let now = Instant::now();
        ROUTES.lock().unwrap().insert(route.into(), Route { remaining: 1, reset_at: now + Duration::from_secs(5) });
        assert!(reserve(route, now).is_zero());
        assert_eq!(reserve(route, now), Duration::from_secs(5));
        assert!(reserve(route, now + Duration::from_secs(6)).is_zero());
    }
}