app: read the history a page at a time and open clips on demand

Every launch parsed all 313 timelines, raw responses and all, which put
2.1 GB of JSON on the heap at startup.

The list now holds `Summary` rows: `history::summaries` parses a file,
keeps the champion, queue, scoreline, LP change and event count, then
drops the timeline. Files are listed by write time, and `poll` reads the
next 20 when the list is scrolled near its end or when the filtered rows
do not fill the screen. Selecting a row hands its id to the review
screen, which reads that one timeline on a thread.

Peak memory over 313 recordings: 165 MB.
This commit is contained in:
vhaudiquet committed 2026-11-16 23:48:58 +01:00
1 parent 4efc2f3968
commit 6584b2f92f
7 files changed
+318 -86

No files matched your search

+120 -39
View File
@@ -130,64 +130,123 @@ pub fn timeline_dir() -> PathBuf {
daemon::recordings_dir().join("timelines")
}
/// Every timeline on disk, newest first. Files that fail to parse are skipped.
/// Every timeline on disk, newest first. The raw API responses make each file large (hundreds
/// of kilobytes), so the files are parsed in parallel.
pub fn load_all() -> Vec<Timeline> {
/// Timeline files on disk, most recently written first.
///
/// The name is a recording id, so the write time is the only cheap order there is. A
/// recording is written when its game ends, which matches when it started closely enough for
/// a list that gets re-sorted by `start_time` as pages arrive.
pub fn timeline_paths() -> Vec<PathBuf> {
let dir = timeline_dir();
let Ok(entries) = std::fs::read_dir(&dir) else {
return Vec::new();
};
let paths: Vec<PathBuf> = entries
let mut found: Vec<(std::time::SystemTime, PathBuf)> = entries
.flatten()
.map(|entry| entry.path())
.filter(|path| path.extension().and_then(|e| e.to_str()) == Some("json"))
.filter_map(|path| {
let written = std::fs::metadata(&path).ok()?.modified().ok()?;
Some((written, path))
})
.collect();
found.sort_by_key(|(written, _)| std::cmp::Reverse(*written));
found.into_iter().map(|(_, path)| path).collect()
}
let next = std::sync::atomic::AtomicUsize::new(0);
let parsed = std::sync::Mutex::new(Vec::with_capacity(paths.len()));
let threads = std::thread::available_parallelism()
.map(|count| count.get())
.unwrap_or(4)
.clamp(1, 8);
std::thread::scope(|scope| {
for _ in 0..threads {
scope.spawn(|| {
loop {
let index = next.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let Some(path) = paths.get(index) else {
break;
};
let Ok(text) = std::fs::read_to_string(path) else {
continue;
};
match serde_json::from_str::<Timeline>(&text) {
Ok(timeline) => parsed.lock().unwrap().push(timeline),
Err(e) => eprintln!("skipping {}: {e}", path.display()),
}
}
});
/// The rows for a page of timelines.
///
/// Each file is parsed whole, because the champion, the scoreline and the queue only exist
/// inside the raw responses, and the [`Timeline`] is dropped as soon as its [`Summary`] is
/// built. Only the summaries are kept, so the events and the raw JSON do not pile up.
pub fn summaries(paths: &[PathBuf]) -> Vec<Summary> {
paths.iter().filter_map(|path| summary_of(path)).collect()
}
fn summary_of(path: &Path) -> Option<Summary> {
let text = std::fs::read_to_string(path).ok()?;
match serde_json::from_str::<Timeline>(&text) {
Ok(timeline) => Some(timeline.summary()),
Err(e) => {
eprintln!("skipping {}: {e}", path.display());
None
}
});
}
}
/// What the match history list needs from a recording.
///
/// The list shows 309 rows of this at a time and the events and raw responses of the timeline
/// stay on disk until a row is opened, so this carries only the values they were read for.
#[derive(Debug, Clone)]
pub struct Summary {
pub recording_id: String,
pub start_time: DateTime<Utc>,
pub duration_secs: i64,
champion: Option<String>,
summoner: Option<String>,
queue_label: String,
category: QueueCategory,
outcome: Outcome,
stats: Option<Stats>,
lp: Option<LpChange>,
pub event_count: usize,
}
impl Summary {
pub fn champion(&self) -> Option<String> {
self.champion.clone()
}
pub fn summoner(&self) -> Option<String> {
self.summoner.clone()
}
pub fn queue_label(&self) -> &str {
&self.queue_label
}
let mut out = parsed.into_inner().unwrap();
out.sort_by_key(|timeline| std::cmp::Reverse(timeline.start_time));
out
pub fn category(&self) -> QueueCategory {
self.category
}
pub fn outcome(&self) -> Outcome {
self.outcome
}
pub fn stats(&self) -> Option<Stats> {
self.stats
}
pub fn lp_change(&self) -> Option<LpChange> {
self.lp.clone()
}
}
impl Timeline {
/// The list row for this recording, computed before the timeline is dropped.
pub fn summary(&self) -> Summary {
Summary {
recording_id: self.recording_id.clone(),
start_time: self.start_time,
duration_secs: self.duration_secs,
champion: self.champion(),
summoner: self.summoner(),
queue_label: self.queue_label(),
category: self.category(),
outcome: self.outcome(),
stats: self.stats(),
lp: self.lp_change(),
event_count: self.events.len(),
}
}
}
/// One timeline by recording id.
#[allow(dead_code)]
pub fn load(recording_id: &str) -> Option<Timeline> {
let path = timeline_dir().join(format!("{recording_id}.json"));
let text = std::fs::read_to_string(path).ok()?;
serde_json::from_str(&text).ok()
}
// ---------------------------------------------------------------------------
// Extractors, from types/timeline.ts
// ---------------------------------------------------------------------------
impl Timeline {
fn end_stats(&self) -> Option<&Value> {
self.raw_end_game_stats.as_ref()
@@ -586,7 +645,29 @@ mod tests {
assert_eq!(lp.tier, "EMERALD");
assert_eq!(lp.league_points, 74);
}
#[test]
fn a_summary_keeps_what_the_row_shows() {
let summary = parsed().summary();
assert_eq!(summary.recording_id, "0b7d3f6e-2f4a-4b83-9f0e-0d5c9f1a2b3c");
assert_eq!(summary.champion().as_deref(), Some("Kai'Sa"));
assert_eq!(summary.queue_label(), "Ranked Solo");
assert_eq!(summary.outcome(), Outcome::Victory);
assert_eq!(summary.event_count, 2);
assert_eq!(summary.stats().unwrap().kills, 9);
assert_eq!(summary.lp_change().unwrap().delta, 21);
}
#[test]
fn pages_read_summaries_from_disk() {
let dir = std::env::temp_dir().join(format!("leaguerecorder-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("game.json");
std::fs::write(&path, TIMELINE).unwrap();
let rows = summaries(&[path, dir.join("missing.json")]);
assert_eq!(rows.len(), 1, "a file that cannot be read is skipped");
assert_eq!(rows[0].champion().as_deref(), Some("Kai'Sa"));
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn a_video_is_found_by_its_timestamp_prefix() {
let dir = std::env::temp_dir().join(format!("leaguerecorder-{}", uuid::Uuid::new_v4()));