Skip to content

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

5.4 KB
Raw Blame
//! Developer aid: the *shape* of what the gateway sends (field names, types,
//! how many of each), never the content. For working out a format Discord
//! changed without putting account data on disk. Off unless the app turns it
//! on (its `RUSTCORD_DUMP_SHAPES` developer hook).
//!
//! One file per event name, written the first time that event is seen, and
//! `events.json` with how often each has come.

use serde_json::{json, Map, Value};
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::sync::{Mutex, OnceLock};
use std::time::{Duration, Instant};

static DIR: OnceLock<PathBuf> = OnceLock::new();
/// How often each event has come, and when that was last written out.
static SEEN: Mutex<(BTreeMap<String, u64>, Option<Instant>)> = Mutex::new((BTreeMap::new(), None));
/// The counts are written at most this often.
const WRITE_EVERY: Duration = Duration::from_secs(2);

/// Arrays and ID-keyed maps are described from at most this many entries.
const SAMPLE: usize = 500;

/// Start recording shapes into `dir`.
pub fn record_to(dir: PathBuf) {
    if std::fs::create_dir_all(&dir).is_ok() {
        let _ = DIR.set(dir);
    }
}

/// One gateway message arrived (its whole text). Does nothing unless recording.
pub fn note(text: &str) {
    let Some(dir) = DIR.get() else { return };
    let Ok(v) = serde_json::from_str::<Value>(text) else { return };
    let name = v["t"].as_str().map_or_else(|| format!("op{}", v["op"]), String::from);
    let Ok(mut state) = SEEN.lock() else { return };
    let (seen, written) = &mut *state;
    let count = seen.entry(name.clone()).or_insert(0);
    *count += 1;
    let first = *count == 1;
    if first {
        write(&dir.join(format!("{name}.json")), &describe(&v["d"], true));
    }
    if first || written.is_none_or(|t| t.elapsed() >= WRITE_EVERY) {
        write(&dir.join("events.json"), &json!(seen));
        *written = Some(Instant::now());
    }
}

fn write(path: &Path, v: &Value) {
    let _ = std::fs::write(path, serde_json::to_string_pretty(v).unwrap_or_default());
}

fn is_id(s: &str) -> bool {
    s.len() >= 15 && s.bytes().all(|b| b.is_ascii_digit())
}

/// `v` without its content. Numbers and booleans outside lists are kept
/// (`exact`): they are versions, flags and counts, and say how a payload is
/// meant to be read.
fn describe(v: &Value, exact: bool) -> Value {
    match v {
        Value::Null => json!("null"),
        Value::Bool(_) | Value::Number(_) if exact => v.clone(),
        Value::Bool(_) => json!("bool"),
        Value::Number(_) => json!("num"),
        Value::String(s) => json!(if is_id(s) { "id" } else { "str" }),
        Value::Array(a) => json!({ "[]": a.len(), "of": union(a.iter()) }),
        Value::Object(m) if !m.is_empty() && m.keys().all(|k| is_id(k)) => json!({ "{id}": m.len(), "of": union(m.values()) }),
        Value::Object(m) => Value::Object(m.iter().map(|(k, x)| (k.clone(), describe(x, exact))).collect()),
    }
}

/// One description covering every entry of a list.
fn union<'a>(items: impl Iterator<Item = &'a Value>) -> Value {
    let mut all = Value::Null;
    for x in items.take(SAMPLE) {
        merge(&mut all, describe(x, false));
    }
    all
}

fn merge(into: &mut Value, other: Value) {
    match (&mut *into, other) {
        (Value::Null, other) => *into = other,
        // An empty list or a null entry says nothing new about the others.
        (_, Value::Null) => {}
        (Value::Object(_), Value::String(s)) if s == "null" => {}
        (Value::String(s), other @ Value::Object(_)) if s == "null" => *into = other,
        (Value::Object(a), Value::Object(b)) => merge_objects(a, b),
        (Value::Number(a), Value::Number(b)) => {
            if b.as_f64() > a.as_f64() {
                *a = b;
            }
        }
        (Value::String(a), Value::String(b)) => {
            if !a.split('|').any(|part| part == b) {
                a.push('|');
                a.push_str(&b);
            }
        }
        (a, b) => {
            let (was, now) = (kind(a).to_string(), kind(&b).to_string());
            *a = json!(if was == now { was } else { format!("{was}|{now}") });
        }
    }
}

fn merge_objects(a: &mut Map<String, Value>, b: Map<String, Value>) {
    for (k, x) in b {
        match a.get_mut(&k) {
            Some(mine) => merge(mine, x),
            None => {
                a.insert(k, x);
            }
        }
    }
}

fn kind(v: &Value) -> &str {
    match v {
        Value::Null => "null",
        Value::Bool(_) => "bool",
        Value::Number(_) => "num",
        Value::String(s) => s,
        Value::Array(_) => "list",
        Value::Object(_) => "object",
    }
}

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

    #[test]
    fn a_shape_has_names_and_counts_but_no_content() {
        let v = json!({
            "version": 7,
            "user": { "id": "123456789012345678", "username": "someone" },
            "entries": [{ "id": "123456789012345678", "mention_count": 2 }, { "id": "223456789012345678", "flags": 1, "last": null }],
            "by_id": { "123456789012345678": ["a"], "223456789012345678": [] },
        });
        let s = describe(&v, true);
        assert_eq!(s["version"], 7);
        assert_eq!(s["user"], json!({ "id": "id", "username": "str" }));
        assert_eq!(s["entries"], json!({ "[]": 2, "of": { "id": "id", "mention_count": "num", "flags": "num", "last": "null" } }));
        assert_eq!(s["by_id"], json!({ "{id}": 2, "of": { "[]": 1, "of": "str" } }));
        assert!(!s.to_string().contains("someone"));
    }
}