Files
arena-tracker/crates/core/tests/import.rs
T
nessarandClaude Fable 5.2 c44cf52a6a Add core: Match import, statistics and game client following
Core half of tickets #4 to #12, behind one public interface tested with
fake sources and a real SQLite database:

- import of Arena Match history from the Riot API, idempotent and
  resumable, with a sync mark written only when a sync completes
- Season table, champion catalog, Challenge summary, champion rows,
  chart series, Season and Format scopes
- game client port and adapter: signed-in Account, end of an Arena
  game fetched by its id, Official Progress cross-check
- update problems reported for banners while stored data stays readable

The app crate is adapted in the next commit.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-16 19:06:52 +01:00

625 lines
20 KiB
Rust

mod common;
use std::path::Path;
use std::sync::atomic::Ordering;
use std::sync::mpsc;
use std::thread;
use std::time::Duration;
use arena_tracker_core::{
Account, Error, Format, Match, SourceError, SyncProgress, SyncReport, Tracker,
};
use common::{
FakeHistory, SELF_PUUID, payload, played_by, recorded_account, recorded_matches, with_game_mode,
};
use serde_json::Value;
const RIOT_ID: &str = "Joueur#EUW";
fn open(db: &Path, history: FakeHistory) -> Tracker {
Tracker::open(db, Box::new(history)).unwrap()
}
fn sync(tracker: &Tracker) -> SyncReport {
tracker.sync(RIOT_ID, &mut |_| {}).unwrap()
}
/// The expectation for a recorded payload, read from the payload itself.
fn expected(raw: &str) -> Match {
let v: Value = serde_json::from_str(raw).unwrap();
let me = v["info"]["participants"]
.as_array()
.unwrap()
.iter()
.find(|p| p["puuid"] == SELF_PUUID)
.unwrap();
let format = match v["info"]["queueId"].as_u64().unwrap() {
1700 => Format::Arena16,
1740 => Format::BraveryArena,
1750 => Format::Arena3x6,
queue => panic!("unexpected queue {queue}"),
};
Match {
match_id: v["metadata"]["matchId"].as_str().unwrap().into(),
format,
champion_id: me["championId"].as_u64().unwrap() as u32,
champion_name: me["championName"].as_str().unwrap().into(),
placement: me["placement"].as_u64().unwrap() as u8,
win: me["win"].as_bool().unwrap(),
started_at_ms: v["info"]["gameStartTimestamp"].as_i64().unwrap(),
}
}
/// Five Arena 3x6 Matches, one every 1000 s starting at `from_s`.
fn five_matches(from_s: i64) -> Vec<String> {
five_matches_every(from_s, 1000)
}
/// Five Arena 3x6 Matches, one every `step_s` seconds starting at `from_s`.
fn five_matches_every(from_s: i64, step_s: i64) -> Vec<String> {
(0..5)
.map(|i| {
payload(
&format!("EUW1_{i}"),
1750,
10 + i as u32,
"Champion",
(i % 8 + 1) as u8,
i % 2 == 0,
(from_s + i * step_s) * 1000,
)
})
.collect()
}
fn started_at(matches: &[Match]) -> Vec<i64> {
matches.iter().map(|m| m.started_at_ms).collect()
}
#[test]
fn tracker_can_be_shared_between_threads() {
fn assert_send_sync<T: Send + Sync>() {}
assert_send_sync::<Tracker>();
}
#[test]
fn imports_the_recorded_matches() {
let dir = tempfile::tempdir().unwrap();
let tracker = open(
&dir.path().join("arena.db"),
FakeHistory::new(recorded_account(), recorded_matches()),
);
let report = sync(&tracker);
assert_eq!(report.account, recorded_account());
assert_eq!((report.added, report.stored), (6, 6));
let mut want: Vec<Match> = recorded_matches().iter().map(|raw| expected(raw)).collect();
want.sort_by_key(|m| m.started_at_ms);
assert_eq!(tracker.matches(SELF_PUUID).unwrap(), want);
assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 6);
assert_eq!(tracker.accounts().unwrap(), [recorded_account()]);
}
#[test]
fn importing_twice_changes_nothing_and_fetches_nothing() {
let dir = tempfile::tempdir().unwrap();
let fake = FakeHistory::new(recorded_account(), recorded_matches());
let fetches = fake.fetch_counter();
let tracker = open(&dir.path().join("arena.db"), fake);
sync(&tracker);
let first = tracker.matches(SELF_PUUID).unwrap();
let report = sync(&tracker);
assert_eq!((report.added, report.stored), (0, 6));
assert_eq!(fetches.load(Ordering::SeqCst), 6);
assert_eq!(tracker.matches(SELF_PUUID).unwrap(), first);
}
#[test]
fn interrupted_import_keeps_what_was_stored_and_resumes_with_the_rest() {
let dir = tempfile::tempdir().unwrap();
let db = dir.path().join("arena.db");
let flaky = open(
&db,
FakeHistory::new(recorded_account(), five_matches(1_000_000)).failing_after(2),
);
let err = flaky.sync(RIOT_ID, &mut |_| {}).unwrap_err();
assert!(matches!(err, Error::Source(SourceError::Network(_))));
assert_eq!(flaky.match_count(SELF_PUUID).unwrap(), 2);
drop(flaky);
let healthy = FakeHistory::new(recorded_account(), five_matches(1_000_000));
let fetches = healthy.fetch_counter();
let tracker = open(&db, healthy);
assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 2);
let report = sync(&tracker);
// The two stored are the newest ones: the missing older ones are still found.
assert_eq!((report.added, report.stored), (3, 5));
assert_eq!(fetches.load(Ordering::SeqCst), 3);
assert_eq!(tracker.matches(SELF_PUUID).unwrap().len(), 5);
}
#[test]
fn later_sync_fetches_only_newer_matches() {
let dir = tempfile::tempdir().unwrap();
let db = dir.path().join("arena.db");
let days_apart = |from_s| five_matches_every(from_s, 10 * 24 * 3600);
sync(&open(
&db,
FakeHistory::new(recorded_account(), days_apart(1_000_000)),
));
let mut now_on_riot = days_apart(1_000_000);
now_on_riot.push(payload(
"EUW1_new1",
1750,
1,
"Annie",
1,
true,
4_500_000_000,
));
now_on_riot.push(payload(
"EUW1_new2",
1740,
2,
"Olaf",
3,
true,
4_501_000_000,
));
let fake = FakeHistory::new(recorded_account(), now_on_riot);
let (fetches, listed) = (fake.fetch_counter(), fake.listed_counter());
let tracker = open(&db, fake);
let report = sync(&tracker);
assert_eq!((report.added, report.stored), (2, 7));
assert_eq!(fetches.load(Ordering::SeqCst), 2);
// Riot is only asked for recent Matches: the newest stored one (listed again) and the new ones.
assert_eq!(listed.load(Ordering::SeqCst), 3);
}
#[test]
fn matches_are_returned_oldest_first_whatever_the_delivery_order() {
let dir = tempfile::tempdir().unwrap();
let mut payloads = five_matches(1_000_000);
payloads.swap(0, 3);
payloads.swap(1, 4);
let delivered: Vec<i64> = payloads.iter().map(|p| started_ms(p)).collect();
assert!(!delivered.is_sorted() && !delivered.iter().rev().is_sorted());
let tracker = open(
&dir.path().join("arena.db"),
FakeHistory::new(recorded_account(), payloads).delivered_as_given(),
);
sync(&tracker);
let started = started_at(&tracker.matches(SELF_PUUID).unwrap());
assert_eq!(started.len(), 5);
assert!(started.is_sorted());
}
fn started_ms(payload: &str) -> i64 {
let v: Value = serde_json::from_str(payload).unwrap();
v["info"]["gameStartTimestamp"].as_i64().unwrap()
}
#[test]
fn a_catch_up_cut_short_fetches_the_older_matches_next_time() {
let dir = tempfile::tempdir().unwrap();
let db = dir.path().join("arena.db");
let at = |hours: i64| (1_000_000 + hours * 3600) * 1000;
let known = payload("EUW1_1", 1750, 1, "A", 4, false, at(0));
sync(&open(
&db,
FakeHistory::new(recorded_account(), vec![known.clone()]),
));
// Three Matches played while the app was closed.
let mut on_riot = vec![known];
for i in 2..=4 {
let id = format!("EUW1_{i}");
on_riot.push(payload(&id, 1750, i, "B", 4, false, at(i64::from(i))));
}
// The catch-up stores the newest one, then dies.
let cut = open(
&db,
FakeHistory::new(recorded_account(), on_riot.clone()).failing_after(1),
);
assert!(cut.sync(RIOT_ID, &mut |_| {}).is_err());
assert_eq!(cut.match_count(SELF_PUUID).unwrap(), 2);
drop(cut);
let report = sync(&open(&db, FakeHistory::new(recorded_account(), on_riot)));
assert_eq!((report.added, report.stored), (2, 4));
}
#[test]
fn a_match_that_started_earlier_but_was_published_later_is_still_imported() {
let dir = tempfile::tempdir().unwrap();
let db = dir.path().join("arena.db");
let at = |hours: i64| (1_000_000 + hours * 3600) * 1000;
let first = payload("EUW1_1", 1750, 1, "A", 4, false, at(0));
let newest = payload("EUW1_2", 1750, 2, "B", 4, false, at(30));
let fake = FakeHistory::new(recorded_account(), vec![first, newest]);
let tracker = open(&db, fake);
sync(&tracker);
// A game that began before the newest stored one ends only now.
let late = FakeHistory::new(
recorded_account(),
vec![
payload("EUW1_1", 1750, 1, "A", 4, false, at(0)),
payload("EUW1_2", 1750, 2, "B", 4, false, at(30)),
payload("EUW1_3", 1750, 3, "C", 1, true, at(10)),
],
);
drop(tracker);
let report = sync(&open(&db, late));
assert_eq!((report.added, report.stored), (1, 3));
}
#[test]
fn a_match_that_cannot_be_delivered_or_read_does_not_block_the_others() {
let dir = tempfile::tempdir().unwrap();
let at = |hours: i64| (1_000_000 + hours * 3600) * 1000;
let fake = FakeHistory::new(
recorded_account(),
vec![
payload("EUW1_1", 1750, 1, "A", 4, false, at(1)),
payload("EUW1_2", 1750, 2, "B", 2, true, at(3)),
],
);
fake.add_missing("EUW1_gone", at(4));
fake.add_unreadable("EUW1_garbled", at(2), "<html>pas du JSON</html>");
fake.add_unreadable("EUW1_empty_object", at(0), "{}");
let tracker = open(&dir.path().join("arena.db"), fake);
let mut progress = Vec::new();
let report = tracker.sync(RIOT_ID, &mut |p| progress.push(p)).unwrap();
assert_eq!((report.added, report.stored), (2, 2));
assert_eq!(
progress.last(),
Some(&SyncProgress {
fetched: 5,
to_fetch: 5
})
);
let again = sync(&tracker);
assert_eq!((again.added, again.stored), (0, 2));
}
#[test]
fn other_participants_may_lack_any_field() {
let dir = tempfile::tempdir().unwrap();
let thin = common::without_fields_for_others(
&payload("EUW1_1", 1750, 7, "Zed", 2, true, 1_000_000_000),
&["placement", "win", "championId", "championName", "teamId"],
);
let tracker = open(
&dir.path().join("arena.db"),
FakeHistory::new(recorded_account(), vec![thin]),
);
let report = sync(&tracker);
assert_eq!(report.added, 1);
let stored = tracker.matches(SELF_PUUID).unwrap();
assert_eq!((stored[0].champion_id, stored[0].placement), (7, 2));
}
#[test]
fn an_account_resolved_to_another_puuid_is_a_second_account() {
let dir = tempfile::tempdir().unwrap();
let db = dir.path().join("arena.db");
let at = |hours: i64| (1_000_000 + hours * 3600) * 1000;
let build = |puuid: &str, ids: &[u32]| -> Vec<String> {
ids.iter()
.map(|&i| {
let raw = payload(
&format!("EUW1_{i}"),
1750,
i,
"A",
1,
true,
at(i64::from(i)),
);
played_by(&raw, puuid)
})
.collect()
};
// Under the development key, Joueur#EUW is P1.
let account = |puuid: &str| Account {
puuid: puuid.into(),
..recorded_account()
};
let first = open(&db, FakeHistory::new(account("P1"), build("P1", &[1, 2])));
sync(&first);
let before = first.matches("P1").unwrap();
drop(first);
// Under the personal key it is P2: nothing proves it is the same Account.
let tracker = open(
&db,
FakeHistory::new(account("P2"), build("P2", &[1, 2, 3])),
);
let report = sync(&tracker);
assert_eq!(report.account.puuid, "P2");
assert_eq!((report.added, report.stored), (3, 3));
assert_eq!(tracker.matches("P1").unwrap(), before);
let mut puuids: Vec<String> = tracker
.accounts()
.unwrap()
.into_iter()
.map(|a| a.puuid)
.collect();
puuids.sort();
assert_eq!(puuids, ["P1", "P2"]);
}
const LEGACY_SCHEMA: &str = "
CREATE TABLE accounts (
puuid TEXT PRIMARY KEY, game_name TEXT NOT NULL, tag_line TEXT NOT NULL,
full_import_done INTEGER NOT NULL DEFAULT 0
);
CREATE TABLE matches (
puuid TEXT NOT NULL, match_id TEXT NOT NULL, queue_id INTEGER NOT NULL,
champion_id INTEGER NOT NULL, champion_name TEXT NOT NULL, placement INTEGER NOT NULL,
win INTEGER NOT NULL, started_at_ms INTEGER NOT NULL, raw TEXT NOT NULL,
PRIMARY KEY (puuid, match_id)
);
INSERT INTO accounts VALUES ('fixture-puuid-self', 'Joueur', 'EUW', 1);
INSERT INTO matches VALUES ('fixture-puuid-self', 'EUW1_1', 1750, 1, 'A', 4, 0, 1000000000, '{}');";
#[test]
fn a_database_written_before_the_sync_mark_keeps_working() {
let dir = tempfile::tempdir().unwrap();
let db = dir.path().join("arena.db");
rusqlite::Connection::open(&db)
.unwrap()
.execute_batch(LEGACY_SCHEMA)
.unwrap();
let other = Account {
puuid: "fixture-puuid-other".into(),
game_name: "Autre".into(),
tag_line: "FIX".into(),
};
let theirs = vec![played_by(
&payload("EUW1_9", 1750, 9, "I", 1, true, 1_000_005_000),
&other.puuid,
)];
let tracker = open(
&db,
FakeHistory::new(
recorded_account(),
vec![
payload("EUW1_1", 1750, 1, "A", 4, false, 1_000_000_000),
payload("EUW1_2", 1750, 2, "B", 1, true, 1_000_003_000),
],
)
.with_account(other.clone(), theirs),
);
// No mark yet: everything is listed, what is stored is not fetched again.
let report = sync(&tracker);
assert_eq!((report.added, report.stored), (1, 2));
// A new Account can be added to the old table.
let report = tracker.sync("Autre#FIX", &mut |_| {}).unwrap();
assert_eq!((report.added, report.stored), (1, 1));
assert_eq!(tracker.accounts().unwrap().len(), 2);
}
#[test]
fn queues_map_to_formats_and_non_matches_are_skipped() {
let dir = tempfile::tempdir().unwrap();
let at = |i: i64| (1_000_000 + i) * 1000;
let fake = FakeHistory::new(
recorded_account(),
vec![
payload("EUW1_1", 1750, 1, "A", 1, true, at(1)),
payload("EUW1_2", 1740, 2, "B", 2, true, at(2)),
payload("EUW1_3", 1700, 3, "C", 3, true, at(3)),
payload("EUW1_4", 1710, 4, "D", 4, true, at(4)),
],
)
.listed_under(1700, payload("EUW1_5", 1704, 5, "E", 1, true, at(5)))
.listed_under(1700, payload("EUW1_6", 9999, 6, "F", 5, false, at(6)))
.listed_under(
1700,
with_game_mode(&payload("EUW1_7", 1700, 7, "G", 1, true, at(7)), "ARAM"),
);
let tracker = open(&dir.path().join("arena.db"), fake);
let report = sync(&tracker);
assert_eq!((report.added, report.stored), (5, 5));
let formats: Vec<_> = tracker
.matches(SELF_PUUID)
.unwrap()
.into_iter()
.map(|m| (m.match_id, m.format))
.collect();
assert_eq!(
formats,
[
("EUW1_1".into(), Format::Arena3x6),
("EUW1_2".into(), Format::BraveryArena),
("EUW1_3".into(), Format::Arena16),
("EUW1_4".into(), Format::Arena16),
("EUW1_6".into(), Format::Other(9999)),
]
);
}
#[test]
fn a_rate_limit_is_waited_out_and_the_import_completes() {
let dir = tempfile::tempdir().unwrap();
let tracker = open(
&dir.path().join("arena.db"),
FakeHistory::new(recorded_account(), recorded_matches()).rate_limited_once(),
);
let report = sync(&tracker);
assert_eq!((report.added, report.stored), (6, 6));
}
#[test]
fn progress_goes_from_nothing_fetched_to_everything_fetched() {
let dir = tempfile::tempdir().unwrap();
let tracker = open(
&dir.path().join("arena.db"),
FakeHistory::new(recorded_account(), recorded_matches()),
);
let mut progress = Vec::new();
tracker.sync(RIOT_ID, &mut |p| progress.push(p)).unwrap();
let want: Vec<_> = (0..=6)
.map(|fetched| SyncProgress {
fetched,
to_fetch: 6,
})
.collect();
assert_eq!(progress, want);
progress.clear();
tracker.sync(RIOT_ID, &mut |p| progress.push(p)).unwrap();
assert_eq!(
progress,
[SyncProgress {
fetched: 0,
to_fetch: 0
}]
);
}
#[test]
fn two_accounts_keep_separate_matches() {
let dir = tempfile::tempdir().unwrap();
let db = dir.path().join("arena.db");
sync(&open(
&db,
FakeHistory::new(recorded_account(), five_matches(1_000_000)),
));
let other = Account {
puuid: "fixture-puuid-other".into(),
game_name: "Autre".into(),
tag_line: "FIX".into(),
};
let theirs: Vec<String> = five_matches(5_000_000)[..2]
.iter()
.map(|raw| played_by(raw, &other.puuid))
.collect();
let tracker = open(&db, FakeHistory::new(other.clone(), theirs));
let report = tracker.sync("Autre#FIX", &mut |_| {}).unwrap();
assert_eq!((report.added, report.stored), (2, 2));
assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 5);
assert_eq!(tracker.match_count(&other.puuid).unwrap(), 2);
assert!(
tracker
.matches(&other.puuid)
.unwrap()
.iter()
.all(|m| m.started_at_ms >= 5_000_000_000)
);
assert_eq!(tracker.accounts().unwrap().len(), 2);
}
#[test]
fn matches_without_the_account_are_skipped() {
let dir = tempfile::tempdir().unwrap();
let stranger = Account {
puuid: "fixture-puuid-stranger".into(),
game_name: "Joueur".into(),
tag_line: "EUW".into(),
};
let tracker = open(
&dir.path().join("arena.db"),
FakeHistory::new(stranger, recorded_matches()),
);
let report = sync(&tracker);
assert_eq!((report.added, report.stored), (0, 0));
}
#[test]
fn riot_ids_are_validated_and_must_exist() {
let dir = tempfile::tempdir().unwrap();
let tracker = open(
&dir.path().join("arena.db"),
FakeHistory::new(recorded_account(), recorded_matches()),
);
for bad in ["Joueur", "#EUW", "Joueur#"] {
let err = tracker.sync(bad, &mut |_| {}).unwrap_err();
assert!(matches!(err, Error::InvalidRiotId(_)), "{bad}");
}
let err = tracker.sync("Inconnu#EUW", &mut |_| {}).unwrap_err();
assert!(matches!(err, Error::Source(SourceError::NotFound)));
}
#[test]
fn readers_are_not_blocked_while_a_fetch_is_in_flight() {
let dir = tempfile::tempdir().unwrap();
let (entered_tx, entered_rx) = mpsc::channel();
let (release_tx, release_rx) = mpsc::channel();
let fake = FakeHistory::new(recorded_account(), recorded_matches()[..1].to_vec())
.gated(entered_tx, release_rx);
let tracker = open(&dir.path().join("arena.db"), fake);
thread::scope(|scope| {
let import = scope.spawn(|| sync(&tracker));
entered_rx.recv().unwrap();
// The import is now waiting on the source; the UI thread must still get answers.
assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 0);
assert_eq!(tracker.accounts().unwrap().len(), 1);
release_tx.send(()).unwrap();
assert_eq!(import.join().unwrap().added, 1);
});
}
#[test]
fn concurrent_syncs_run_one_after_the_other_and_fetch_each_match_once() {
let dir = tempfile::tempdir().unwrap();
let (entered_tx, entered_rx) = mpsc::channel();
let (release_tx, release_rx) = mpsc::channel();
let fake = FakeHistory::new(recorded_account(), recorded_matches()[..1].to_vec())
.gated(entered_tx, release_rx);
let fetches = fake.fetch_counter();
let tracker = open(&dir.path().join("arena.db"), fake);
let (overlapped, added) = thread::scope(|scope| {
let first = scope.spawn(|| sync(&tracker));
entered_rx.recv().unwrap();
let second = scope.spawn(|| sync(&tracker));
// Without the lock, the second sync would reach the source while the first waits there.
let overlapped = entered_rx.recv_timeout(Duration::from_millis(300)).is_ok();
release_tx.send(()).unwrap();
release_tx.send(()).unwrap();
let added = (first.join().unwrap().added, second.join().unwrap().added);
(overlapped, added)
});
assert!(!overlapped);
assert_eq!(added, (1, 0));
assert_eq!(fetches.load(Ordering::SeqCst), 1);
}