Lightweight native Discord client for Windows, Linux and macOS, written in Rust. No Electron, no browser engine.
Rust desktop-appdiscorddiscord-clienteguielectron-alternativelightweightlinuxmacosnative-apprustwindows
//! Settings → Experimental → Request Log: a window that lists every request
//! RustCord sends (Discord's API, and pictures / media) as it happens, with
//! the last minute's rate on top. It floats over the app, so it can stay
//! open while you use RustCord.
//!
//! Recording lives in `discord::reqlog` and only runs while the experiment
//! is on; the log is in memory only.
use crate::app::RustCord;
use crate::style::{medium, overlay, Theme};
use discord::reqlog::{self, Entry, Kind};
use eframe::egui::{self, pos2, vec2, Align2, Color32, FontFamily, FontId, Order, Rect, RichText, ScrollArea, Sense, Stroke, TextEdit, Ui};
use std::time::Duration;
const GREEN: Color32 = Color32::from_rgb(0x23, 0xa5, 0x5a);
const AMBER: Color32 = Color32::from_rgb(0xf0, 0xb2, 0x32);
const ROW: f32 = 24.0;
/// The Request Log window's state.
pub struct RequestLog {
pub open: bool,
filter: String,
api: bool,
media: bool,
/// Showing the log as it was up to this request (newer ones are hidden).
paused: Option<u64>,
}
impl Default for RequestLog {
fn default() -> Self {
Self { open: false, filter: String::new(), api: true, media: false, paused: None }
}
}
fn semibold(size: f32) -> FontId {
FontId::new(size, FontFamily::Name(crate::style::BOLD.into()))
}
fn size(bytes: u64) -> String {
match bytes {
0 => "–".into(),
b if b < 1024 => format!("{b} B"),
b if b < 1024 * 1024 => format!("{:.1} KB", b as f64 / 1024.0),
b => format!("{:.1} MB", b as f64 / 1_048_576.0),
}
}
fn ms(d: Duration) -> String {
if d.as_secs() >= 10 {
format!("{:.0} s", d.as_secs_f64())
} else if d.as_millis() >= 1000 {
format!("{:.1} s", d.as_secs_f64())
} else {
format!("{} ms", d.as_millis())
}
}
fn status_text(e: &Entry) -> (String, Color32) {
match e.status {
None => ("ERR".into(), Color32::from_rgb(0xf2, 0x3f, 0x43)),
Some(429) => ("429".into(), Color32::from_rgb(0xf2, 0x3f, 0x43)),
Some(s) if s >= 400 => (s.to_string(), AMBER),
Some(s) => (s.to_string(), GREEN),
}
}
/// What the last minute looked like: totals and a count per second.
struct Minute {
api: usize,
media: usize,
limited: usize,
held: usize,
per_second: [(u16, u16); 60],
}
fn last_minute(log: &std::collections::VecDeque<Entry>) -> Minute {
let mut m = Minute { api: 0, media: 0, limited: 0, held: 0, per_second: [(0, 0); 60] };
for e in log.iter().rev() {
let age = e.sent.elapsed().as_secs() as usize;
if age >= 60 {
break;
}
let slot = &mut m.per_second[59 - age];
match e.kind {
Kind::Api => {
m.api += 1;
slot.0 += 1;
}
Kind::Media => {
m.media += 1;
slot.1 += 1;
}
}
m.limited += usize::from(e.status == Some(429));
m.held += usize::from(e.held >= Duration::from_millis(50));
}
m
}
impl RustCord {
/// The Request Log window, while open (and the experiment is on).
pub fn request_log_ui(&mut self, ctx: &egui::Context) {
if !self.request_log.open || !self.prefs.experiments.request_log {
return;
}
let t = self.theme.clone();
let mut open = true;
let frame = egui::Frame::none().fill(t.surface_high).rounding(12.0).stroke(Stroke::new(1.0_f32, super::modal_border(&t))).inner_margin(16.0).shadow(egui::epaint::Shadow {
offset: vec2(0.0, 8.0),
blur: 24.0,
spread: 0.0,
color: Color32::from_black_alpha(140),
});
egui::Window::new(RichText::new("Request Log").font(semibold(16.0)).color(t.header_primary))
.id(egui::Id::new("request_log"))
.order(Order::Tooltip)
.open(&mut open)
.frame(frame)
.collapsible(false)
.resizable(true)
.default_size(vec2(820.0, 480.0))
.min_size(vec2(560.0, 280.0))
.show(ctx, |ui| self.request_log_body(ui, &t));
self.request_log.open = open;
// Live: new requests show within half a second.
ctx.request_repaint_after(Duration::from_millis(500));
}
fn request_log_body(&mut self, ui: &mut Ui, t: &Theme) {
let st = &mut self.request_log;
let minute = reqlog::read(last_minute);
// ---- the last minute: totals, then a bar per second ----
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = 4.0;
for (i, (value, label, color)) in [
(minute.api, "to Discord's API", t.header_primary),
(minute.media, "pictures & media", t.header_primary),
(minute.limited, "rate limited (429)", if minute.limited > 0 { Color32::from_rgb(0xf2, 0x3f, 0x43) } else { t.header_primary }),
(minute.held, "held back by RustCord", t.header_primary),
]
.into_iter()
.enumerate()
{
if i > 0 {
ui.add_space(14.0);
}
ui.label(RichText::new(value.to_string()).font(semibold(15.0)).color(color));
ui.label(RichText::new(label).size(13.0).color(t.text_muted));
}
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
ui.label(RichText::new("last minute").size(13.0).color(t.text_muted));
});
});
ui.add_space(6.0);
let (chart, _) = ui.allocate_exact_size(vec2(ui.available_width(), 40.0), Sense::hover());
ui.painter().rect_filled(chart, 6.0, overlay(0.04));
let peak = minute.per_second.iter().map(|(a, m)| a + m).max().unwrap_or(0).max(5) as f32;
let w = chart.width() / 60.0;
for (i, (api, media)) in minute.per_second.iter().enumerate() {
let x = chart.left() + w * i as f32;
let h_api = *api as f32 / peak * (chart.height() - 6.0);
let h_media = *media as f32 / peak * (chart.height() - 6.0);
let base = chart.bottom() - 3.0;
if h_media > 0.0 {
ui.painter().rect_filled(Rect::from_min_max(pos2(x + 1.0, base - h_media), pos2(x + w - 1.0, base)), 1.0, t.text_muted.gamma_multiply(0.5));
}
if h_api > 0.0 {
ui.painter().rect_filled(Rect::from_min_max(pos2(x + 1.0, base - h_media - h_api), pos2(x + w - 1.0, base - h_media)), 1.0, t.accent);
}
}
ui.painter().text(pos2(chart.left() + 6.0, chart.top() + 4.0), Align2::LEFT_TOP, format!("{peak:.0}/s"), FontId::proportional(11.0), t.text_muted);
ui.add_space(10.0);
// ---- filter, kinds, pause, clear ----
let mut clear = false;
ui.horizontal(|ui| {
ui.add(TextEdit::singleline(&mut st.filter).hint_text("Filter by method, path or status").desired_width(260.0));
ui.checkbox(&mut st.api, "API");
ui.checkbox(&mut st.media, "Pictures & media");
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
clear = ui.button("Clear").on_hover_cursor(egui::CursorIcon::PointingHand).clicked();
let paused = st.paused.is_some();
if ui.selectable_label(paused, if paused { "Paused" } else { "Pause" }).clicked() {
st.paused = if paused { None } else { Some(reqlog::latest()) };
}
});
});
if clear {
reqlog::clear();
st.paused = None;
}
ui.add_space(6.0);
// ---- the requests, newest first ----
let cols = [("Time", 92.0), ("Method", 62.0), ("Status", 52.0)];
let right = [("Took", 70.0), ("Size", 70.0)];
let width = ui.available_width();
let (head, _) = ui.allocate_exact_size(vec2(width, 22.0), Sense::hover());
let mut x = head.left() + 6.0;
for (label, w) in cols {
ui.painter().text(pos2(x, head.center().y), Align2::LEFT_CENTER, label, semibold(12.0), t.text_muted);
x += w;
}
ui.painter().text(pos2(x, head.center().y), Align2::LEFT_CENTER, "Request", semibold(12.0), t.text_muted);
let mut rx = head.right() - 6.0;
for (label, w) in right.iter().rev() {
ui.painter().text(pos2(rx, head.center().y), Align2::RIGHT_CENTER, *label, semibold(12.0), t.text_muted);
rx -= w;
}
ui.painter().hline(head.x_range(), head.bottom(), Stroke::new(1.0_f32, t.border_subtle));
let needle = st.filter.trim().to_lowercase();
let (api, media, paused) = (st.api, st.media, st.paused);
let mut copy: Option<String> = None;
reqlog::read(|log| {
let rows: Vec<&Entry> = log
.iter()
.rev()
.filter(|e| paused.is_none_or(|p| e.seq <= p))
.filter(|e| match e.kind {
Kind::Api => api,
Kind::Media => media,
})
.filter(|e| {
needle.is_empty()
|| e.target.to_lowercase().contains(&needle)
|| e.method.to_lowercase() == needle
|| e.status.is_some_and(|s| s.to_string() == needle)
})
.collect();
if rows.is_empty() {
ui.add_space(12.0);
let empty = if log.is_empty() { "Nothing yet: requests show here as RustCord sends them." } else { "No requests match." };
ui.label(RichText::new(empty).size(14.0).color(t.text_muted));
return;
}
ScrollArea::vertical().auto_shrink([false, false]).show_rows(ui, ROW, rows.len(), |ui, range| {
for e in &rows[range] {
let (r, resp) = ui.allocate_exact_size(vec2(width, ROW), Sense::click());
let resp = resp.on_hover_cursor(egui::CursorIcon::PointingHand);
if resp.hovered() {
ui.painter().rect_filled(r, 4.0, overlay(0.06));
}
let y = r.center().y;
let mut x = r.left() + 6.0;
let time = chrono::DateTime::<chrono::Local>::from(e.at).format("%H:%M:%S%.3f").to_string();
ui.painter().text(pos2(x, y), Align2::LEFT_CENTER, time, FontId::monospace(12.0), t.text_muted);
x += cols[0].1;
let method_color = if e.method == "GET" { t.text_normal } else { t.accent };
ui.painter().text(pos2(x, y), Align2::LEFT_CENTER, &e.method, medium(13.0), method_color);
x += cols[1].1;
let (status, color) = status_text(e);
ui.painter().text(pos2(x, y), Align2::LEFT_CENTER, status, medium(13.0), color);
x += cols[2].1;
// The path, cut to fit before the figures.
let path_right = r.right() - 6.0 - right.iter().map(|c| c.1).sum::<f32>() - 8.0;
let clip = ui.painter_at(Rect::from_min_max(pos2(x, r.top()), pos2(path_right, r.bottom())));
let mut path = e.target.clone();
if let Some(note) = &e.note {
path.push_str(" · ");
path.push_str(note);
}
clip.text(pos2(x, y), Align2::LEFT_CENTER, path, FontId::proportional(13.0), if e.kind == Kind::Api { t.header_primary } else { t.text_normal });
let took = if e.held >= Duration::from_millis(50) { format!("{} +{}", ms(e.took), ms(e.held)) } else { ms(e.took) };
let mut rx = r.right() - 6.0;
ui.painter().text(pos2(rx, y), Align2::RIGHT_CENTER, size(e.bytes), FontId::proportional(12.0), t.text_muted);
rx -= right[1].1;
ui.painter().text(pos2(rx, y), Align2::RIGHT_CENTER, took, FontId::proportional(12.0), t.text_muted);
let mut tip = format!("#{} {} {}\nStatus: {}\nTook: {}", e.seq, e.method, e.target, e.status.map_or("no answer".into(), |s| s.to_string()), ms(e.took));
if e.held >= Duration::from_millis(50) {
tip.push_str(&format!("\nHeld back first: {} (rate limits / history pacing)", ms(e.held)));
}
if let Some(note) = &e.note {
tip.push_str(&format!("\n{note}"));
}
tip.push_str("\nRight-click to copy the address.");
let resp = resp.on_hover_text(tip);
if resp.secondary_clicked() {
copy = Some(e.target.clone());
}
}
});
});
if let Some(text) = copy {
ui.ctx().copy_text(text);
self.toast("Copied.", false);
}
}
}