Skip to content

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

4.4 KB
Raw Blame
//! The Request Log (Settings → Experimental): a record of every request
//! RustCord sends, kept in memory while it is switched on. Off, recording
//! costs one atomic load per request; nothing is ever written to disk.

use std::collections::VecDeque;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::Mutex;
use std::time::{Duration, Instant, SystemTime};

/// How many requests are kept (the oldest go first).
pub const CAPACITY: usize = 2000;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Kind {
    /// Discord's API (discord.com/api): what Discord's rate limits and
    /// anti-spam count.
    Api,
    /// Pictures, emoji, avatars and attachments (Discord's CDN and others).
    Media,
}

#[derive(Clone, Debug)]
pub struct Entry {
    /// Counts up from 1 across the session (also after clearing).
    pub seq: u64,
    pub kind: Kind,
    /// When it was sent (wall clock, for showing) and how long ago (for rates).
    pub at: SystemTime,
    pub sent: Instant,
    pub method: String,
    /// API: the path with its query (`/channels/1/messages?limit=50`). Media:
    /// host and path, without the query (attachment links are signed).
    pub target: String,
    /// The HTTP status, or `None` when no answer came (a network error).
    pub status: Option<u16>,
    /// From sending to the whole answer having arrived.
    pub took: Duration,
    /// How long RustCord held it back first (rate limits, history pacing).
    pub held: Duration,
    /// Size of the answer's body.
    pub bytes: u64,
    /// What went wrong or what Discord asked for ("retry in 1.2 s").
    pub note: Option<String>,
}

static ENABLED: AtomicBool = AtomicBool::new(false);
static SEQ: AtomicU64 = AtomicU64::new(0);
static LOG: Mutex<VecDeque<Entry>> = Mutex::new(VecDeque::new());

pub fn enabled() -> bool {
    ENABLED.load(Ordering::Relaxed)
}

/// Switch recording on or off; switching off forgets what was recorded.
pub fn set_enabled(on: bool) {
    if !ENABLED.swap(on, Ordering::Relaxed) || on {
        return;
    }
    clear();
}

pub fn clear() {
    if let Ok(mut log) = LOG.lock() {
        *log = VecDeque::new();
    }
}

/// Add a request (its `seq` is filled in here). Does nothing while off.
pub fn record(mut e: Entry) {
    if !enabled() {
        return;
    }
    e.seq = SEQ.fetch_add(1, Ordering::Relaxed) + 1;
    if let Ok(mut log) = LOG.lock() {
        if log.len() >= CAPACITY {
            log.pop_front();
        }
        log.push_back(e);
    }
}

/// A request outside Discord's API (a picture, a file going to Discord's
/// storage) that was sent at `sent`: recorded by its host and path, without
/// the query (signed links carry their signature there).
pub fn record_media(method: &str, url: &str, sent: Instant, status: Option<u16>, bytes: u64, note: Option<String>) {
    if !enabled() {
        return;
    }
    let target = url.split(['?', '#']).next().unwrap_or(url);
    let target = target.strip_prefix("https://").unwrap_or(target).to_string();
    let took = sent.elapsed();
    record(Entry {
        seq: 0,
        kind: Kind::Media,
        at: SystemTime::now() - took,
        sent,
        method: method.into(),
        target,
        status,
        took,
        held: Duration::ZERO,
        bytes,
        note,
    });
}

/// The newest `seq` recorded (0 before the first), to tell when there's more.
pub fn latest() -> u64 {
    SEQ.load(Ordering::Relaxed)
}

/// Look at the log, oldest first, without copying it.
pub fn read<R>(f: impl FnOnce(&VecDeque<Entry>) -> R) -> R {
    match LOG.lock() {
        Ok(log) => f(&log),
        Err(poisoned) => f(&poisoned.into_inner()),
    }
}

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

    fn entry() -> Entry {
        Entry {
            seq: 0,
            kind: Kind::Api,
            at: SystemTime::now(),
            sent: Instant::now(),
            method: "GET".into(),
            target: "/users/@me".into(),
            status: Some(200),
            took: Duration::ZERO,
            held: Duration::ZERO,
            bytes: 0,
            note: None,
        }
    }

    #[test]
    fn records_only_while_on_and_forgets_when_switched_off() {
        record(entry());
        assert_eq!(read(|l| l.len()), 0);
        set_enabled(true);
        record(entry());
        record(entry());
        assert_eq!(read(|l| l.len()), 2);
        assert!(read(|l| l[1].seq > l[0].seq));
        set_enabled(false);
        assert_eq!(read(|l| l.len()), 0);
    }
}