42 Commits
Author SHA1 Message Date
nessarandClaude Opus 5.5 a23e7ffbac Bring the window forward at the end of a game, as at a champ select
CI / relay (pull_request) Successful in 30s
CI / core (pull_request) Successful in 2m1s
CI / relay (push) Successful in 38s
CI / core (push) Successful in 56s
Every end of a game the page decides on (recap opened, Challenge with the
preference off, or a game left without its block) emits MatchEndShown,
formerly RecapOpened: « Paramètres » gives way and the window is raised
above the others without taking the focus, through tray::reveal.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 21:17:36 +01:00
nessarandClaude Opus 5.5 1f0e92194a Center the player's row on the Match chosen when « Parties » opens
The Match the screen or a filter chooses now centers the displayed
Account's row, as a click in the list already did.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 21:17:36 +01:00
nessarandClaude Fable 5.2 88acc1b0df Prove a changed PUUID by champion and Placement, and fix the review findings (#150, #140)
CI / relay (pull_request) Successful in 41s
CI / core (pull_request) Successful in 58s
CI / relay (push) Successful in 42s
CI / core (push) Successful in 2m13s
A champion is unique only within a team of an Arena Match, so the proof
of a changed PUUID now requires the same champion and Placement in the
shared Match. A Friend's Riot ID resolution waits for the follower
again before each retry. The page resolves the signed-in Account once
per change instead of at each progress message, the arc's circle is
kept across counts, and the ring's paint no longer returns a value only
a test reads. Tests: a real import of twelve Matches drives the arc,
the structural test hovers a card and scrolls the grid, and Death
Recaps, blocks and Provisional Matches are read after a rekey.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-28 20:06:41 +01:00
nessarandClaude Fable 5.2 7b0b9863e0 Fix the verification findings of the rekey and the import arc (#150, #140)
The proof of a changed PUUID also requires the same champion in the
shared Match: anyone who played in it passed before, so a Friend whose
stale Riot ID was taken by a co-player could be merged into them. A
quota wait on a Friend's Riot ID resolution is told. The arc's paths
are built once per size and progress instead of at each paint of the
ring, and a signed-in Account the page has not read yet shows no arc.
Tests now cover the session state and the sync mark of a rekey.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-28 19:51:52 +01:00
nessarandClaude Fable 5.2 5343e49996 Show the import on the ring and the Riot quota wait (#140)
An import of 10 Matches or more of the Account shown draws a thin arc
around the ring's ticks, filled from noon as Matches arrive and gone
when the import ends. The ring stays a cached view, told at most once a
second. While the import waits for a 429's Retry-After, the progress
carries the wait and the status line counts it down each second
(« Quota Riot atteint : reprise dans 12 s »), on a timer that only
exists during the wait.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-28 19:32:12 +01:00
nessarandClaude Fable 5.2 6140bc34fb Follow an Account to its new PUUID on proof of identity (#150)
A PUUID depends on the Riot application of the API key, so the relay's
production key gives every stored Account another one. Before a request
that carries a stored PUUID (a sync, a Friend's import), the Riot ID is
resolved; when its PUUID differs and a stored published Match is among
the new PUUID's, the Account, its Matches (stored Riot responses
included), Mastery, sync mark, platform, last active mark and Friend
status move to it in one transaction. A new PUUID already stored is
merged, the published Match winning. Without proof nothing changes.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-28 19:21:52 +01:00
nessarandClaude Fable 5.2 073ed58bba Fix the review findings of the end-of-game key names (#154)
CI / relay (pull_request) Successful in 40s
CI / core (pull_request) Successful in 56s
CI / relay (push) Successful in 39s
CI / core (push) Successful in 1m56s
A. The fixture's game id is the synthetic one every fixture uses; the test no longer rewrites it.
B. The decoder tries the key names verified on the capture first, the other spellings after.
C. The synthetic end-of-game blocks use the real block's shape: PUUID only, no names, the real
   key spellings. The Riot-ID fallback test adds the names to its own block.
D. The captured-block follow test states that the fixture's player is the client's PUUID.
E. The recap of a Provisional Match flags the player with the Match's champion and Placement,
   not every player on that champion; a test covers a champion played by two teams.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-28 18:02:04 +01:00
nessarandClaude Opus 5.5 529b1c9370 Read the end-of-game block's real key names (#154)
CI / relay (pull_request) Successful in 30s
CI / core (pull_request) Successful in 2m0s
A block captured at the end of an Arena 3x6 game on Windows spells the
player's key `PUUID` and names no player, so the decoder never found the
signed-in one: every game waited for Riot's publication, and the page,
told of no Match, showed « Défi » without the end-of-game animation.

The decoder now also reads the names of that block (`PUUID`, `itemIds`,
`augmentPlatformIds`, `playerKills`, `playerDeaths`, `playerAssists`,
`damageDealtToChampions`, `damageTaken`). The capture is kept as an
anonymised fixture; a unit test decodes it and a follow test builds its
Provisional Match from it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 17:53:09 +01:00
nessarandClaude Opus 5.5 a7387c61ce Cap Retry-After at ten minutes and fix the review's wording (#149)
CI / relay (pull_request) Successful in 45s
CI / core (pull_request) Successful in 1m20s
CI / core (push) Successful in 2m0s
CI / relay (push) Successful in 37s
The relay forwards a Retry-After of up to a day, and an import waits out
each one: the app now clamps it to between a second and ten minutes (the
relay's longest quota window) where the header is read, and says so on
SourceError::RateLimited and with_retry.

The Death Recap comments now say what happens: the relay passes any
timeline 403, a rejected key included, and the Match asked next tells
the two apart. A test plays that case (timeline refused, Match
unavailable). The shared get and SourceError no longer speak only of
the relay, the routing docs tell a region from a platform, and test
names and comments no longer speak of a key the app does not have.

The riot suites share one local server and response builder, and the
app's first-launch setup reuses open_app.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 13:44:58 +01:00
nessarandClaude Opus 5.5 1eebb86902 Call Riot through the relay, without a key (#149)
Every Riot call goes to {relay}/{routing value}{Riot path} and sends no
key. The relay's address is built in (arena-tracker.nessar.fr);
relay_url in config.toml replaces it for development. A riot_api_key
left by an older version is never read, and is written back on save.

The personal keys' local pacing is gone. An import waits out each
Retry-After as often as it comes (at least a second each time), and so
do Mastery requests. A 5xx is the service unavailable, with its own
banner; a 401/403 is a refusal, which for a timeline the Match itself
confirms before it is stored, so a key failing on the relay's side
stores no refused Death Recap.

The first-launch key prompt, the key field in « Paramètres » and the
Friend refusal's « Paramètres » button are removed; the follower starts
with the app. KeyForm, KeyStore and KeyEvent become SettingsForm,
SettingsStore and SettingsEvent. README, user guide and interface spec
no longer ask for a key.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 13:44:58 +01:00
nessarandClaude Opus 5.5 b50f429f2a Document the relay as deployed: Komodo, NPM behind Cloudflare, public (#151)
CI / relay (pull_request) Successful in 27s
CI / core (pull_request) Successful in 1m40s
CI / relay (push) Successful in 40s
CI / core (push) Successful in 57s
The stack passes its variables through environment: (Komodo's .env only
fills the placeholders), the key is a Komodo Secret, and the personal key's
limits apply until #152. NPM takes the player's address from
CF-Connecting-IP and keeps no access log. Cloudflare must not challenge or
cache the subdomain. The service is public by choice, with the location
block that would restrict it. Updates and key changes go through Redeploy.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 18:48:43 +01:00
nessarandClaude Opus 5.5 90aeda60dd Publish Riot's new verification code (#147)
CI / relay (push) Successful in 28s
CI / core (push) Successful in 1m45s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 18:44:19 +01:00
nessarandClaude Opus 5.5 86b149135c Count the Riot request's description as sent (#147)
CI / relay (pull_request) Successful in 53s
CI / core (pull_request) Successful in 1m12s
CI / relay (push) Successful in 27s
CI / core (push) Successful in 1m47s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 18:39:46 +01:00
nessarandClaude Opus 5.5 be0ddfabfe Publish Riot's verification code at /riot.txt (#147)
CI / relay (pull_request) Successful in 52s
CI / core (pull_request) Successful in 1m16s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 18:39:39 +01:00
nessar 324a092c47 Update docs/demande-cle-production.md
CI / relay (pull_request) Successful in 25s
CI / core (pull_request) Successful in 1m47s
2026-11-27 18:38:19 +01:00
nessarandClaude Opus 5.5 c9cb0f4ed7 Fit the Riot request's description in the form's 1,500 characters (#147)
CI / relay (pull_request) Successful in 31s
CI / core (pull_request) Successful in 1m50s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 18:36:28 +01:00
nessarandClaude Opus 5.5 1a9dea471d Name the real subdomain, arena-tracker.nessar.fr, in the Riot request (#147)
CI / relay (pull_request) Successful in 40s
CI / core (pull_request) Successful in 57s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 18:34:17 +01:00
nessarandClaude Opus 5.5 e7103ae0bd Record the production key request as Riot's form takes it (#147)
CI / relay (pull_request) Successful in 34s
CI / core (pull_request) Successful in 1m40s
The description is one plain-text field: the text is now the exact block
pasted, with the other fields in a table, and what must stay true of it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 18:34:01 +01:00
nessarandClaude Opus 5.5 003ba4872c License under the AGPL 3.0 or later, and draft the production key request (#147)
CI / relay (pull_request) Successful in 42s
CI / core (pull_request) Successful in 1m0s
LICENSE holds the FSF's AGPL 3.0 text; the three crates declare
AGPL-3.0-or-later. The README says what stays under its own license: the
Inter and Unbounded fonts (OFL) and Riot Games' images, data and
certificate. Every dependency's license is compatible.

docs/demande-cle-production.md is the text for Riot's developer portal:
the app, the six Riot calls and when each is made, the relay and its
limits, the friend lookup by Riot ID, no item or augment statistics, and
that today's app still uses each player's personal key.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 18:32:11 +01:00
nessarandClaude Opus 5.5 24691306fb Fill the site's placeholders, name Cloudflare, add screenshots (#145)
CI / relay (pull_request) Successful in 30s
CI / core (pull_request) Successful in 2m1s
CI / relay (push) Successful in 43s
CI / core (push) Successful in 1m3s
Operator Nessar, contact arena@nessar.fr, effective 27 November 2026,
14 days for gitea.nessar.fr access logs. The privacy policy now says
requests pass through Cloudflare, which sees them in transit.

Three screenshots of the app on the home page (Challenge, Matches,
Statistics), WebP at 1280 px, other players' Riot IDs blurred. The relay
serves them like the pages; its test now walks all of site/, so a file
left out of src/site.rs fails CI.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 18:24:48 +01:00
nessarandClaude Opus 5.5 c7d0395502 Package the relay as a container image, published by a local script (#151)
CI / relay (pull_request) Successful in 36s
CI / core (pull_request) Successful in 52s
CI / relay (push) Successful in 27s
CI / core (push) Successful in 2m5s
A static musl binary on an empty image, run as nobody, listening on 8080.
scripts/publish-relay builds it from a clean, pushed commit of develop or
main and pushes it to Gitea's registry, tagged with the commit and latest.
The build context is an allowlist: never .env nor target/.

RELAY_TRUSTED_PROXY also takes a network: Nginx Proxy Manager's address on
the Docker network changes when it restarts.

docs/service-relais.md gives the compose service, the env file, the NPM
proxy host (no access log, Access List until #152), and how to update,
change the key and check the restart and the per-address limit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 17:42:56 +01:00
nessarandClaude Opus 5.5 fe36a431dc Relay the app's Riot calls with the key and the quota, and serve the site (#148, #145)
CI / relay (pull_request) Successful in 37s
CI / core (pull_request) Successful in 52s
CI / relay (push) Successful in 40s
CI / core (push) Successful in 1m6s
New workspace member arena-tracker-relay: it holds the Riot key from the
environment and serves the app's six Riot calls as /{routing value}{Riot path}.
Any other route, method, routing value, queue or count above 100 gets 404
without calling Riot. Fixed-window limits per routing value (production
limits) and per client address answer 429 with Retry-After at once; a Riot
429 is passed with its delay and suspends its routing value. Riot's 401/403
become 503 (except a timeline's 403), an unreachable Riot 502. The log holds
the call type, status and duration only; nothing is written to disk.

The same binary serves the site pages of site/ (#145), built in, unlogged.

Tested over HTTP against a local fake Riot. A separate `relay` CI job, now
required on develop and main. ADR-0008 replaces ADR-0001's personal key;
docs/service-relais.md says how to run it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 17:20:34 +01:00
nessarandClaude Sonnet 5.5 a694cbd8e7 Draft the Arena Tracker website pages (#145)
Home page, Terms of Service and Privacy Policy for the production key
application (#144). Bracketed fields and screenshots are still to be filled in.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-27 17:20:34 +01:00
nessarandClaude Opus 5.5 67caf7861c Wait for the log writer in its tests instead of Log::flush's 2 s (#142)
CI / core (pull_request) Successful in 1m48s
CI / core (push) Successful in 49s
On the slower CI runner, flush gave up while the writer was still
rotating 3.5 MB, and the test saw only the old file. The tests now send
the writer the same flush message and wait for its answer without limit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 16:58:03 +01:00
nessarandClaude Opus 5.5 3d4c8bbc83 Address review: Journal private, client found/gone, sync redaction test (#142)
CI / core (pull_request) Failing after 1m45s
- Rule #3: Journal and its open/launch are private again; the writer's
  tests move to src/journal/tests.rs, only the launch test stays an
  integration test. The « Ouvrir le dossier des journaux » selector sits
  on the button itself, not on a div drawn for the test.
- The log notes the League client found and gone (its event stream
  connects or drops), and a client without anyone signed in reads
  "nobody signed in" instead of "absent".
- Other libraries (GPUI…) reach the log only with errors: their info and
  warnings may come per frame. The HTTP client stays out entirely.
- The log opens after the single-instance check: a relayed launch no
  longer writes to, nor rotates, the running instance's log.
- A whole sync through the Riot adapter is tested to log neither the key
  nor a full PUUID. The URL comment follows the spec: Riot IDs may be
  logged, a full PUUID may not.
- --verify-release keeps its eprintln: the publishing script reads it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 16:52:48 +01:00
nessarandClaude Opus 5.5 cb6fbcadaf Follow Rule #3: no wrapper drawn only for a test (#143, #142)
CI / core (pull_request) Successful in 1m56s
Each alert sat in a div that only gave tests a selector; it is gone, and
the tile test keeps what #143 asks: the tiles never get taller with the
official count. The folder opener's comment states its production role.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 16:22:11 +01:00
nessar 556e95eadc Merge #142: keep an application log, open its folder from « Paramètres » 2026-11-27 16:22:11 +01:00
nessar 04b1204432 Merge #141: open « Statistiques » from a chart icon in the banner's corner 2026-11-27 16:22:11 +01:00
nessar c25dc99db4 Merge #138: a click anywhere in a text field gives it the keyboard 2026-11-27 16:22:11 +01:00
nessarandClaude Opus 5.5 4ac19df72b Address review: release version, rotation failure, low priority (#142)
The launch line carries the release version (`-dev` suffix on a dev build). A failed
rotation keeps writing to the current file and retries after another MB. The writer thread
runs an `on_start` hook, which the app uses to lower its priority. Tests for the rotation
failure and the `ureq`/debug exclusion. The profile CSV errors go to the log. Opening the
logs folder only clears its own error.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 16:22:04 +01:00
nessarandClaude Opus 5.5 be2eee469e Address review: ring structural test, doc fixes, kit icon_assets! macro (#141)
Hovering the icon leaves the cached ring unrendered (asserted in the grid
test). performance.md opens « Statistiques » by the chart icon, and
interface.md no longer claims the icon leaves the text untouched in a
narrow window. The chart icon comes from gpui_kit::assets::icon_assets!, so
the vendored SVG and Lucide license are removed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 16:22:04 +01:00
nessar ffe71de4da Merge #143: drop the official count note from the « Statistiques » tiles 2026-11-27 16:22:04 +01:00
nessarandClaude Opus 5.5 78cbc87e68 Address review: state that the field buttons also focus the field (#138)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 16:22:04 +01:00
nessarandClaude Opus 5.5 200a1f380c Keep an application log in a rotating file, and open its folder from « Paramètres » (#142)
Lines are queued to one writer thread, idle at rest, that flushes once the
queue is drained and on quit. Riot calls are logged by type, never by URL;
PUUIDs are cut to 8 characters and the key never appears.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 16:22:04 +01:00
nessarandClaude Opus 5.5 771f6f3d31 Put « Statistiques » on a chart icon in the banner's bottom-right corner (#141)
The text link at the end of the Season line is gone. The one Lucide icon the
kit's default bundle lacks is served by the app's own asset source.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 16:22:04 +01:00
nessar 5be6093a40 Merge #146: show Riot's legal notice in « Paramètres » 2026-11-27 16:22:04 +01:00
nessarandClaude Opus 5.5 8fa4779e2d Address review: correct two comments on the official note tests (#143)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 16:22:04 +01:00
nessarandClaude Opus 5.5 aa5db4036e Give a text field the keyboard on a click in its padding or border (#138)
gpui-component's Input frame tracks its own focus handle, apart from the
editor's: a click off the text line focused the frame and typing went
nowhere. One app-side wrapper focuses the field's state instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 16:22:04 +01:00
nessarandClaude Opus 5.5 bb6ab65559 Address review: prove the Riot notice is reachable, fix the top being cut off, move docs (#146)
The test now scrolls the settings down and checks the notice ends inside the
window and the title starts inside it. Doing so showed the my_auto centring
pushed the overflowing column's top out of the scroll range; a min-height
wrapper centres it instead. The notice sentence moves to its own doc section
and mentions the first-launch key screen.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 16:22:04 +01:00
nessarandClaude Opus 5.5 45adf219d7 Drop the official count note from the « Statistiques » tiles (#143)
The tiles are now all built the same way; the mismatch alert stays the only
signal of an incomplete history.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 16:22:04 +01:00
nessarandClaude Opus 5.5 dd8af3f9e7 Show Riot's legal notice at the bottom of « Paramètres » (#146)
The settings now scroll, so the notice stays reachable at the window's
minimum size.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 16:22:04 +01:00
nessarandClaude Opus 5.5 c3003930f1 Ignore .scratch/, the local working drafts
CI / core (push) Successful in 1m51s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 14:59:04 +01:00
148 changed files with 7581 additions and 1158 deletions

No files matched your search

+7
View File
@@ -0,0 +1,7 @@
# Only what the relay's image needs goes into the build context: never .env nor target/.
*
!Cargo.toml
!Cargo.lock
!crates/
crates/*/target/
!site/
+21 -1
View File
@@ -1,4 +1,5 @@
# Only the core crate is checked: the app crate (GPUI) only builds on Windows (ADR-0003).
# The core and the relay are checked, each in its own job: the app crate (GPUI) only builds on
# Windows (ADR-0003). Both jobs are required checks for merging (docs/publication.md).
# Betas of develop and stables of main are published from the build PC once these checks pass (docs/publication.md).
name: CI
@@ -35,3 +36,22 @@ jobs:
- name: Publication tests
run: python3 scripts/test_publish.py
relay:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install Rust stable (rustfmt, clippy)
run: |
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --component rustfmt,clippy
echo "$HOME/.cargo/bin" >> "$GITHUB_PATH"
- name: Format
run: cargo fmt -p arena-tracker-relay --check
- name: Clippy
run: cargo clippy -p arena-tracker-relay --all-targets --locked -- -D warnings
- name: Tests
run: cargo test -p arena-tracker-relay --locked
+1
View File
@@ -2,3 +2,4 @@
*.local.toml
.env
__pycache__/
.scratch/
Generated
+41
View File
@@ -227,6 +227,7 @@ dependencies = [
"gpui-kit",
"gpui-pre",
"image",
"log",
"raw-window-handle",
"serde_json",
"windows 0.62.2",
@@ -238,6 +239,7 @@ version = "1.1.0"
dependencies = [
"base64 0.23.1",
"image",
"log",
"ring",
"rusqlite",
"rustls",
@@ -249,6 +251,15 @@ dependencies = [
"ureq",
]
[[package]]
name = "arena-tracker-relay"
version = "1.1.0"
dependencies = [
"log",
"tiny_http",
"ureq",
]
[[package]]
name = "arg_enum_proc_macro"
version = "0.3.4"
@@ -293,6 +304,12 @@ dependencies = [
"stable_deref_trait",
]
[[package]]
name = "ascii"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d92bec98840b8f03a5ff5413de5293bfcd8bf96467cf5452609f939ec6f5de16"
[[package]]
name = "ash"
version = "0.38.0+1.3.281"
@@ -926,6 +943,12 @@ dependencies = [
"windows-link 0.2.1",
]
[[package]]
name = "chunked_transfer"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e4de3bc4ea267985becf712dc6d9eed8b04c953b3fcfb339ebc87acd9804901"
[[package]]
name = "ciborium"
version = "0.2.2"
@@ -3170,6 +3193,12 @@ version = "1.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"
[[package]]
name = "httpdate"
version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"
[[package]]
name = "hybrid-array"
version = "0.4.15"
@@ -6910,6 +6939,18 @@ dependencies = [
"strict-num",
]
[[package]]
name = "tiny_http"
version = "0.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "389915df6413a2e74fb181895f933386023c71110878cd0825588928e64cdc82"
dependencies = [
"ascii",
"chunked_transfer",
"httpdate",
"log",
]
[[package]]
name = "tinystr"
version = "0.8.5"
+3 -2
View File
@@ -1,9 +1,10 @@
[workspace]
resolver = "3"
members = ["crates/core", "crates/app"]
default-members = ["crates/core"]
members = ["crates/core", "crates/app", "crates/relay"]
default-members = ["crates/core", "crates/relay"]
[workspace.package]
edition = "2024"
rust-version = "1.98"
version = "1.1.0"
license = "AGPL-3.0-or-later"
+661
View File
@@ -0,0 +1,661 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.
+13 -4
View File
@@ -34,19 +34,19 @@ magick -background none -density 384 logo.svg -resize 1024x1024 -define icon:aut
## Configuration
L'application lit `%APPDATA%\arena-tracker\config.toml`, en dehors du dépôt. Le fichier est facultatif : au premier lancement, l'application demande la clé API Riot (à demander sur le portail développeur Riot), l'enregistre dans ce fichier et la prend en compte sans redémarrage. La clé se change ensuite dans `Paramètres`. Exemple de fichier, avec des valeurs fictives :
L'application lit `%APPDATA%\arena-tracker\config.toml`, en dehors du dépôt. Le fichier est facultatif, et aucune clé API Riot n'est à saisir : les appels à Riot passent par le service d'Arena Tracker, qui garde la clé (ADR-0008, [service intermédiaire](docs/service-relais.md)). Exemple de fichier, avec des valeurs fictives :
```toml
riot_api_key = "RGAPI-xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" # clé du portail développeur Riot
riot_id = "NomDeJeu#TAG" # facultatif
region = "europe" # facultatif, "europe" par défaut
relay_url = "http://127.0.0.1:8080" # facultatif, pour le développement : un autre service que https://arena-tracker.nessar.fr
```
Le Compte connecté au client de League of Legends est suivi automatiquement. `riot_id` ne sert que de repli, quand le client est fermé au premier lancement.
Le Compte connecté au client de League of Legends est suivi automatiquement. `riot_id` ne sert que de repli, quand le client est fermé au premier lancement. Le `riot_api_key` d'une version antérieure est ignoré et laissé dans le fichier.
L'application y écrit aussi ses préférences (`close_to_tray`, `theme`, `update_channel` : `stable` ou `beta`, absent tant que le canal de la version installée s'applique, `champion_sort` : `mastery` ou `name`, absent tant que le joueur n'a pas choisi, le tri se faisant alors par points de maîtrise) et `tray_notice_shown`, qui passe à `true` une fois affichée la notification indiquant que la fenêtre fermée continue dans la zone de notification. Le remettre à `false` la fait réapparaître à la prochaine fermeture.
La base des Parties, `arena-tracker.db`, est créée dans le même dossier, ainsi que `seasons.toml`, la table des Saisons : elle peut être modifiée, et les changements sont pris en compte au lancement suivant. La clé API ne doit jamais être commitée.
La base des Parties, `arena-tracker.db`, est créée dans le même dossier, ainsi que `seasons.toml`, la table des Saisons : elle peut être modifiée, et les changements sont pris en compte au lancement suivant.
## Tests
@@ -61,3 +61,12 @@ cargo test
- À chaque pull request et à chaque push sur `main`, un workflow Gitea Actions (`.gitea/workflows/ci.yml`) vérifie le formatage (`cargo fmt --check`), lance le linter (`cargo clippy`, avertissements traités comme des erreurs) et exécute les tests (`cargo test`) du coeur `arena-tracker-core`, avec `--locked` : un `Cargo.lock` non à jour fait échouer la CI.
- La crate applicative (GPUI) n'est pas compilée en CI, car elle ne se compile que sous Windows (ADR-0003). La CI ne compile ni ne publie l'exécutable Windows.
- Le workflow nécessite un runner Linux (`act_runner`) enregistré sur l'instance Gitea.
## Licence
Arena Tracker est un logiciel libre sous licence [GNU AGPL 3.0](LICENSE) ou toute version ultérieure (`AGPL-3.0-or-later`). Elle couvre aussi l'usage par le réseau : qui fait tourner une version modifiée du service intermédiaire (`crates/relay`) doit en publier le code.
Restent sous leur propre licence :
- les polices Inter et Unbounded (SIL Open Font License, `crates/app/assets/*-LICENSE.txt`) ;
- les images, noms et données de League of Legends (captures du site, portrait des tests, ce que l'application télécharge) et le certificat `riotgames.pem` : propriété de Riot Games. Arena Tracker n'est pas approuvé par Riot Games et ne reflète pas les opinions de Riot Games ni de quiconque officiellement impliqué dans la production ou la gestion des propriétés de Riot Games. Riot Games et toutes les propriétés associées sont des marques commerciales ou des marques déposées de Riot Games, Inc.
+2
View File
@@ -3,6 +3,7 @@ name = "arena-tracker"
edition.workspace = true
rust-version.workspace = true
version.workspace = true
license.workspace = true
[features]
profile = ["gpui-kit/profiler"]
@@ -11,6 +12,7 @@ profile = ["gpui-kit/profiler"]
arena-tracker-core = { path = "../core" }
base64 = { version = "0.23.1", default-features = false, features = ["std"] }
gpui-kit = "=0.9.1"
log = "0.4"
# Decodes the banner's splash at low priority (the same version as GPUI's and the core's).
image = { version = "0.25.10", default-features = false, features = ["jpeg"] }
+50
View File
@@ -0,0 +1,50 @@
//! The app's asset source: the kit's default bundle, plus the one Lucide icon it does not
//! embed (`chart-line`). `AllAssets` would embed the whole catalog for this one icon.
use std::borrow::Cow;
use gpui_kit::{AssetSource, Result, SharedString};
gpui_kit::assets::icon_assets!(ExtraIcons, [ChartLine]);
pub struct Assets;
impl AssetSource for Assets {
fn load(&self, path: &str) -> Result<Option<Cow<'static, [u8]>>> {
if let Some(bytes) = ExtraIcons.load(path)? {
return Ok(Some(bytes));
}
gpui_kit::assets::Assets.load(path)
}
fn list(&self, path: &str) -> Result<Vec<SharedString>> {
let mut paths = gpui_kit::assets::Assets.list(path)?;
paths.extend(ExtraIcons.list(path)?);
paths.sort();
paths.dedup();
Ok(paths)
}
}
#[cfg(test)]
mod tests {
use super::*;
const CHART_LINE: &str = "icons/chart-line.svg";
#[test]
fn serves_chart_line_and_delegates_the_rest() {
assert!(matches!(Assets.load(CHART_LINE), Ok(Some(_))));
use gpui_kit::component::{IconName, IconNamed as _};
assert_eq!(gpui_kit::assets::IconName::ChartLine.path(), CHART_LINE);
let path = IconName::Settings.path();
assert!(matches!(Assets.load(&path), Ok(Some(_))));
assert!(
Assets
.list("icons/")
.unwrap()
.iter()
.any(|p| p == CHART_LINE)
);
}
}
+23
View File
@@ -0,0 +1,23 @@
//! A click anywhere in a text field's frame gives it the keyboard.
//!
//! gpui-component's `Input` tracks a focus handle of its own on the frame, apart from the
//! editor's: a click in the padding or the border focused the frame, and typing wrote nothing.
use gpui_kit::component::input::{Input, InputState};
use gpui_kit::*;
/// `input` in a wrapper that focuses `state` on a left click the editor did not take (the
/// padding, the border). The text line and the buttons run first and keep their own click, but
/// the field's own buttons (the clear cross, the mask toggle) do not stop the event, so a click
/// on one also focuses the field. The wrapper does nothing once the editor has the focus. Size
/// the wrapper, not the `Input`.
pub fn input_frame(state: &Entity<InputState>, input: Input) -> Div {
let state = state.clone();
div()
.on_mouse_down(MouseButton::Left, move |_, window, cx| {
if !state.read(cx).focus_handle(cx).is_focused(window) {
state.update(cx, |state, cx| state.focus(window, cx));
}
})
.child(input)
}
+46
View File
@@ -0,0 +1,46 @@
//! The application log's start and end (#142): the file is `logs\arena-tracker.log` under the
//! data folder, also on stderr in debug builds. Nothing is lost on a way out of `main`.
use arena_tracker_core::{Config, data_dir, init_journal};
use crate::release::{self, channel};
use crate::worker::lower_priority;
/// Opens the log with its launch line. A log that cannot be opened is not worth stopping for.
pub fn start() -> Flush {
if let Some(dir) = data_dir() {
let preferences = Config::load_or_default(&dir.join("config.toml"))
.map(|config| config.preferences)
.unwrap_or_default();
let channel = format!("{:?}", channel(preferences)).to_lowercase();
// A dev build must not look like the stable release.
let version = release::VERSION.unwrap_or(concat!(env!("CARGO_PKG_VERSION"), "-dev"));
if let Err(error) = init_journal(
&dir,
cfg!(debug_assertions),
version,
&channel,
lower_priority,
) {
eprintln!("Failed to open the log: {error}");
}
}
Flush
}
/// Writes what is still buffered when it is dropped, at the end of `main`.
pub struct Flush;
impl Drop for Flush {
fn drop(&mut self) {
log::logger().flush();
}
}
/// The app quits through `cx.quit()`: what is buffered is written before it does.
pub fn flush_on_quit(cx: &gpui_kit::App) {
cx.on_app_quit(|_| {
log::logger().flush();
async {}
})
.detach();
}
+49 -80
View File
@@ -1,5 +1,6 @@
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
mod assets;
mod banner_art;
mod card;
mod card_grid;
@@ -7,6 +8,8 @@ mod card_images;
mod card_lift;
mod card_order;
mod champion_table;
mod input_frame;
mod journal;
mod local_time;
mod logon;
mod minimized;
@@ -31,33 +34,26 @@ use arena_tracker_core::{
Config, DataDragon, GameData, LeagueClient, Preferences, RiotApi, Tracker, data_dir,
default_seasons, load_seasons,
};
use gpui_kit::base::async_util::{Sender, unbounded};
use gpui_kit::base::async_util::unbounded;
use gpui_kit::component::*;
use gpui_kit::*;
use page::{ChampionSortChosen, Launch, LiveMatchStarted, Page, RecapOpened, SettingsRequested};
use settings::{KeyEvent, KeyForm, KeyStore, apply_theme};
use page::{ChampionSortChosen, Launch, LiveMatchStarted, MatchEndShown, Page};
use settings::{SettingsEvent, SettingsForm, SettingsStore, apply_theme};
use title_bar::{MIN_WINDOW_SIZE, refresh_button, settings_button, title_bar, update_button};
use worker::{CatalogRefresh, Msg, spawn_follower};
use worker::{CatalogRefresh, spawn_follower};
#[derive(Clone, Copy, PartialEq)]
enum Screen {
/// True first launch: the key form stands in for the page until a key is saved.
Prompt,
Page,
Settings,
}
struct RootView {
page: Entity<Page>,
form: Entity<KeyForm>,
form: Entity<SettingsForm>,
focus: FocusHandle,
screen: Screen,
tracker: Arc<Tracker>,
catalog_refresh: Option<Arc<CatalogRefresh>>,
/// The configured Riot ID, used when the game client is closed on first launch.
fallback_riot_id: String,
tx: Sender<Msg>,
/// Started hidden at logon: the first frame, which GPUI draws as the window
/// opens, paints no page, so no portrait is decoded before the window is shown.
blank: bool,
@@ -65,7 +61,6 @@ struct RootView {
_champ_select: Subscription,
_recap: Subscription,
_live_match: Subscription,
_settings: Subscription,
_sort: Subscription,
}
@@ -78,9 +73,6 @@ impl RootView {
notice,
store,
} = setup;
// Without a key the page still shows what is stored; only a true first launch (no key
// and nothing stored) has nothing to show, so the key form stands in for the page.
let first_launch = !store.has_key() && tracker.accounts().unwrap_or_default().is_empty();
let preferences = store.preferences();
let (tx, rx) = unbounded();
let catalog_refresh = game_data.map(|data| CatalogRefresh::start(data, tx.clone()));
@@ -89,7 +81,6 @@ impl RootView {
tracker.clone(),
Launch {
notice,
following: !first_launch,
champion_sort: preferences.champion_sort,
open_recap_at_match_end: preferences.open_recap_at_match_end,
},
@@ -99,33 +90,22 @@ impl RootView {
cx,
)
});
let form = cx.new(|cx| KeyForm::new(store, tracker.clone(), first_launch, window, cx));
let form_events =
cx.subscribe_in(&form, window, |this, _, event: &KeyEvent, window, cx| {
let form = cx.new(|cx| SettingsForm::new(store, tracker.clone(), window, cx));
let form_events = cx.subscribe_in(
&form,
window,
|this, _, event: &SettingsEvent, window, cx| {
match event {
KeyEvent::Saved if this.screen == Screen::Prompt => {
// Nothing is imported before a key exists: the follower starts now.
let (tracker, riot_id) =
(this.tracker.clone(), this.fallback_riot_id.clone());
spawn_follower(
tracker,
riot_id,
this.catalog_refresh.clone(),
this.tx.clone(),
);
this.page.update(cx, |page, cx| page.following(cx));
}
KeyEvent::Saved => this.page.update(cx, |page, cx| page.request_refresh(cx)),
KeyEvent::Back => {}
SettingsEvent::Back => {}
// « Paramètres » stays open.
KeyEvent::AccountDeleted(puuid) => {
SettingsEvent::AccountDeleted(puuid) => {
return this
.page
.update(cx, |page, cx| page.account_deleted(puuid, window, cx));
}
// Only the title bar changes.
KeyEvent::UpdateReady => return cx.notify(),
KeyEvent::Preferences(preferences) => {
SettingsEvent::UpdateReady => return cx.notify(),
SettingsEvent::Preferences(preferences) => {
let open = preferences.open_recap_at_match_end;
return this
.page
@@ -133,7 +113,8 @@ impl RootView {
}
}
this.show_page(window, cx);
});
},
);
let champ_select = cx.subscribe_in(
&page,
window,
@@ -152,19 +133,17 @@ impl RootView {
}
},
);
// The end of a Match showed its recap: « Paramètres » gives way as for a champ select,
// but the window stays as it is, hidden, minimised or behind League: never in front.
let recap = cx.subscribe_in(&page, window, |this, _, _: &RecapOpened, window, cx| {
// The end of a game showed its recap or the Challenge: as for a champ select, « Paramètres »
// gives way and the window comes above the others, League keeping the keyboard.
let recap = cx.subscribe_in(&page, window, |this, _, _: &MatchEndShown, window, cx| {
if let Some(hwnd) = tray::window_hwnd(window) {
cx.spawn(async move |_, _| tray::reveal(hwnd, true))
.detach();
}
if this.screen == Screen::Settings {
this.show_page(window, cx);
}
});
// A Friend was refused for want of a key.
let settings = cx.subscribe_in(
&page,
window,
|this, _, _: &SettingsRequested, window, cx| this.open_settings(window, cx),
);
// A Live Match started: « Paramètres » gives way, and a window minimised or hidden in the
// notification area opens again without the focus; unlike a champ select, it is not
// brought above the others, the game's included (#109).
@@ -189,17 +168,7 @@ impl RootView {
.update(cx, |form, cx| form.save_champion_sort(*sort, cx));
},
);
let screen = if first_launch {
Screen::Prompt
} else {
spawn_follower(
tracker.clone(),
riot_id.clone(),
catalog_refresh.clone(),
tx.clone(),
);
Screen::Page
};
spawn_follower(tracker, riot_id, catalog_refresh, tx);
if hidden {
// Runs once GPUI's first frame is drawn. A hidden or minimized window gets no
// other frame: the page is painted when the window is shown.
@@ -212,23 +181,18 @@ impl RootView {
page,
form,
focus: initial_focus(window, cx),
screen,
tracker,
catalog_refresh,
fallback_riot_id: riot_id,
tx,
screen: Screen::Page,
blank: hidden,
_form_events: form_events,
_champ_select: champ_select,
_recap: recap,
_live_match: live_match,
_settings: settings,
_sort: sort,
}
}
fn can_refresh(&self, cx: &App) -> bool {
self.screen != Screen::Prompt && self.form.read(cx).has_key() && !self.page.read(cx).busy()
!self.page.read(cx).busy()
}
fn open_settings(&mut self, window: &mut Window, cx: &mut Context<Self>) {
@@ -245,9 +209,9 @@ impl RootView {
}
}
/// Leaves the key form for the page, discarding half-typed edits.
/// Leaves « Paramètres » for the page.
fn show_page(&mut self, window: &mut Window, cx: &mut Context<Self>) {
self.form.update(cx, |form, cx| form.reset(window, cx));
self.form.update(cx, |form, cx| form.reset(cx));
self.screen = Screen::Page;
self.page.update(cx, |page, cx| page.uncovered(window, cx));
self.focus.focus(window, cx);
@@ -274,7 +238,7 @@ impl Render for RootView {
let content = match self.screen {
_ if self.blank => div().into_any_element(),
Screen::Page => self.page.clone().into_any_element(),
Screen::Prompt | Screen::Settings => self.form.clone().into_any_element(),
Screen::Settings => self.form.clone().into_any_element(),
};
div()
.id("arena-tracker")
@@ -330,11 +294,11 @@ struct Setup {
game_data: Option<GameData>,
riot_id: String,
notice: Option<String>,
store: KeyStore,
store: SettingsStore,
}
/// Loads the configuration and opens the database, or gives the lines to show instead. A
/// missing config file is fine: the app then asks for the key.
/// missing config file is fine: the defaults apply.
fn startup() -> Result<Setup, (Vec<String>, Preferences)> {
let bad_config = |error: String| {
(
@@ -357,8 +321,8 @@ fn startup() -> Result<Setup, (Vec<String>, Preferences)> {
Some(format!("Table des Saisons invalide : {e}")),
),
};
let api = Arc::new(RiotApi::new(config.riot_api_key.clone(), &config.region));
let tracker = Tracker::open(&dir.join("arena-tracker.db"), Box::new(api.clone()))
let api = RiotApi::new(config.relay_url(), &config.region);
let tracker = Tracker::open(&dir.join("arena-tracker.db"), Box::new(api))
.map_err(|e| (vec![e.to_string()], config.preferences))?
.with_seasons(seasons)
.with_champions(Box::new(DataDragon::new()), dir.join("portraits"))
@@ -368,18 +332,22 @@ fn startup() -> Result<Setup, (Vec<String>, Preferences)> {
game_data: Some(GameData::new(dir.join("game-data"))),
riot_id: config.riot_id.clone(),
notice,
store: KeyStore::new(path, config, api),
store: SettingsStore::new(path, config),
})
}
fn main() {
release::handle_command();
let Some(single_instance::Primary {
instance: _instance,
starting,
}) = single_instance::launch()
else {
return;
// The log opens after the single-instance check: a relayed launch must not write to the
// running instance's log, nor rotate it from under it. Flushes when main returns.
let (_instance, starting, _journal) = match single_instance::launch() {
Ok(Some(primary)) => (primary.instance, primary.starting, journal::start()),
Ok(None) => return,
Err(error) => {
let _journal = journal::start();
log::error!("Failed to check for a running instance: {error}");
return;
}
};
// Started by the logon entry: hidden, or minimized (#67).
let at_logon = logon::launched_at_logon();
@@ -387,9 +355,10 @@ fn main() {
let ControlFlow::Continue(update_notice) = release::update_at_launch(at_logon) else {
return;
};
let app = gpui_kit::application().with_assets(gpui_kit::assets::Assets);
let app = gpui_kit::application().with_assets(assets::Assets);
app.run(move |cx| {
gpui_kit::init(cx);
journal::flush_on_quit(cx);
card_grid::init(cx);
page::init(cx);
theme::init(cx);
+6 -10
View File
@@ -34,6 +34,7 @@ mod displayed;
mod friends;
mod home;
mod hover;
mod import_view;
mod in_game;
mod lifecycle;
mod links;
@@ -100,8 +101,6 @@ impl SelectItem for AccountItem {
/// What the page starts from.
pub struct Launch {
pub notice: Option<String>,
/// A follower thread is already running, its first round is pending.
pub following: bool,
/// The sort saved by an earlier run.
pub champion_sort: Option<ChampionSort>,
/// The preference: the end-of-game block of a Match shows it in « Parties ».
@@ -114,14 +113,10 @@ pub struct ChampSelectTransition {
}
impl EventEmitter<ChampSelectTransition> for Page {}
/// The end of a Match opened its recap in « Parties »: « Paramètres » gives way, as for a champ
/// select, but the window is left as it is (#129).
pub struct RecapOpened;
impl EventEmitter<RecapOpened> for Page {}
/// The Account selector's field refused a Friend for want of a key: « Paramètres » opens.
pub struct SettingsRequested;
impl EventEmitter<SettingsRequested> for Page {}
/// The end of a game was decided: « Parties » opened its recap, or « Défi » shows. As for a champ
/// select, « Paramètres » gives way and the window comes above the others (#129).
pub struct MatchEndShown;
impl EventEmitter<MatchEndShown> for Page {}
/// The player chose a sort for the cards: to be saved with the other preferences.
pub struct ChampionSortChosen(pub ChampionSort);
@@ -240,6 +235,7 @@ pub struct Page {
/// The Account of the last requested statistics.
shown: Option<String>,
progress: Option<SyncProgress>,
import_view: import_view::ImportView,
refresh: RefreshGate,
stats_job: RefreshGate,
stats_generation: u64,
+7 -4
View File
@@ -1,5 +1,6 @@
use super::UNKNOWN_ANVIL;
use crate::card_grid::MAX_WIDTH;
use crate::input_frame::input_frame;
use crate::page::{
Page,
home::{StatsNotice, count_badge, notice_line},
@@ -191,10 +192,12 @@ impl Page {
.gap_x_3()
.gap_y_2()
.child(
Input::new(&self.others_search_input)
.cleanable(true)
.w(px(260.))
.min_w(px(150.)),
input_frame(
&self.others_search_input,
Input::new(&self.others_search_input).cleanable(true),
)
.w(px(260.))
.min_w(px(150.)),
)
.child(self.sort_selector(cx)),
)
+5 -9
View File
@@ -1,6 +1,6 @@
use super::{PAGE_PADDING, Page, Tab, shown};
use crate::stage;
use crate::text::{CLIENT_ABSENT, official_differs, sync_line};
use crate::text::{CLIENT_ABSENT, official_differs};
#[cfg(test)]
use arena_tracker_core::{ChampionSort, StateFilter};
use arena_tracker_core::{ProgressCheck, UpdateProblem};
@@ -17,9 +17,9 @@ impl Page {
if let Some(problem) = &self.status.problem {
let message = problem.message();
banners.push(match problem {
UpdateProblem::MatchPending
| UpdateProblem::RateLimited
| UpdateProblem::NoAccount => Alert::warning("problem", message),
UpdateProblem::MatchPending | UpdateProblem::NoAccount => {
Alert::warning("problem", message)
}
_ => Alert::error("problem", message),
});
}
@@ -105,11 +105,7 @@ impl Render for Page {
.and_then(|entry| entry.sweep(now))
.map(|progress| stage::sweep(progress, window.viewport_size(), cx));
let muted = cx.theme().muted_foreground;
let busy = self.busy();
let status_line = (!busy)
.then(|| self.friend_status())
.flatten()
.unwrap_or_else(|| sync_line(busy, self.progress, self.crashed, self.stored).into());
let status_line = self.status_line(now);
div()
// The pointer takes over from the keyboard: the card it lifted goes down.
+1
View File
@@ -70,6 +70,7 @@ impl Page {
self.home_filter = StateFilter::All;
}
self.rescope(window, cx);
self.show_import(true, cx);
}
/// The Account whose data the page shows: during a champ select or a Live Match the one
+68 -20
View File
@@ -2,7 +2,9 @@
//! takes a Riot ID, and the import of a Friend's history. Nothing here runs on a timer: a Friend's
//! Matches are fetched when it is added, when it is chosen in the selector and on « Actualiser ».
use super::{AccountItem, AccountList, Page, RELOAD_EVERY, SettingsRequested};
use super::import_view::wait_until;
use super::{AccountItem, AccountList, Page, RELOAD_EVERY};
use crate::input_frame::input_frame;
use crate::text::friend_sync_line;
use crate::worker::{spawn_add_friend, spawn_friend_import};
use arena_tracker_core::{AddFriendError, AddedFriend, SyncProgress};
@@ -23,14 +25,14 @@ pub(super) struct Friends {
open: bool,
/// The Riot ID is being looked up: Enter does nothing meanwhile.
pending: bool,
/// Why the last Riot ID was refused, and whether « Paramètres » is the way out.
refusal: Option<(String, bool)>,
/// Why the last Riot ID was refused.
refusal: Option<String>,
/// The puuids of the Friends, as of the last read of the Accounts.
pub(super) ids: HashSet<String>,
import: Import,
}
/// At most one Friend's import at a time, so the key's limits are shared with the active Account
/// At most one Friend's import at a time, so the relay's quota is shared with the active Account
/// and no more than one thread waits on the network.
#[derive(Default)]
struct Import {
@@ -38,11 +40,23 @@ struct Import {
/// Asked for while another ran: the latest Friend asked for wins.
queued: Option<String>,
line: Option<SharedString>,
/// The last progress of the import running.
progress: Option<SyncProgress>,
/// The Friend whose last import failed, and why.
error: Option<(String, String)>,
}
impl Friends {
/// The puuid of the Friend whose import runs.
pub(super) fn import_running(&self) -> Option<&str> {
self.import.running.as_deref()
}
/// The last progress of the import running, if it has told one.
pub(super) fn import_progress(&self) -> Option<SyncProgress> {
self.import.progress
}
pub(super) fn new(window: &mut Window, cx: &mut Context<Page>) -> (Friends, Subscription) {
let input = cx.new(|cx| InputState::new(window, cx).placeholder("Pseudo#TAG"));
let enter = cx.subscribe(&input, |page, _, event: &InputEvent, cx| {
@@ -192,10 +206,7 @@ impl Page {
self.set_tab(super::Tab::Challenge, window, cx);
}
}
Err(refused) => {
let missing_key = matches!(refused, AddFriendError::MissingKey);
self.friends.refusal = Some((refused.message(), missing_key));
}
Err(refused) => self.friends.refusal = Some(refused.message()),
}
}
@@ -215,6 +226,7 @@ impl Page {
let import = &mut self.friends.import;
import.error.take_if(|(failed, _)| *failed == puuid);
import.queued = None;
import.progress = None;
import.line = self
.accounts
.iter()
@@ -232,9 +244,14 @@ impl Page {
window: &mut Window,
cx: &mut Context<Self>,
) {
let puuid = self.current_puuid(puuid, window, cx);
let puuid = puuid.as_str();
if self.friends.import.running.as_deref() != Some(puuid) {
return;
}
let now = cx.background_executor().now();
self.import_view.friend_until = wait_until(progress, now);
self.friends.import.progress = Some(progress);
self.friends.import.line = self
.accounts
.iter()
@@ -253,9 +270,11 @@ impl Page {
window: &mut Window,
cx: &mut Context<Self>,
) {
let puuid = self.current_puuid(&puuid, window, cx);
let import = &mut self.friends.import;
import.running = None;
import.line = None;
import.progress = None;
if let Err(message) = outcome {
import.error = Some((puuid.clone(), message));
}
@@ -267,6 +286,40 @@ impl Page {
}
}
/// What an import message names may have changed PUUID since the import started (a new Riot
/// key, `Tracker::replaced_puuid`): the Accounts are read again, so the page follows it.
fn current_puuid(
&mut self,
puuid: &str,
window: &mut Window,
cx: &mut Context<Self>,
) -> String {
let Some(new) = self.tracker.replaced_puuid(puuid) else {
return puuid.into();
};
if self.friends.import.running.as_deref() == Some(puuid) {
self.reload_accounts(window, cx);
}
new
}
/// The PUUIDs the page holds follow the ones that replaced them (see `current_puuid`), so
/// the Account shown stays the same.
pub(in crate::page) fn follow_replaced_puuids(&mut self) {
let import = &mut self.friends.import;
let held = [
self.pinned.as_mut(),
import.running.as_mut(),
import.queued.as_mut(),
import.error.as_mut().map(|(puuid, _)| puuid),
];
for puuid in held.into_iter().flatten() {
if let Some(new) = self.tracker.replaced_puuid(puuid) {
*puuid = new;
}
}
}
/// A Friend's addition or import panicked: nothing is known to run any more.
pub(in crate::page) fn friend_crashed(&mut self) {
self.friends.pending = false;
@@ -294,7 +347,6 @@ impl Page {
return None;
}
let (muted, danger) = (cx.theme().muted_foreground, cx.theme().danger);
let missing_key = matches!(self.friends.refusal, Some((_, true)));
Some(
div()
.h_flex()
@@ -304,9 +356,11 @@ impl Page {
.gap_y_2()
.on_action(cx.listener(|page, _: &Escape, _, cx| page.close_friend_field(cx)))
.child(
div()
.w(px(260.))
.child(gpui_kit::component::input::Input::new(&self.friends.input)),
input_frame(
&self.friends.input,
gpui_kit::component::input::Input::new(&self.friends.input),
)
.w(px(260.)),
)
.child(
Button::new("friend-cancel")
@@ -320,15 +374,9 @@ impl Page {
.child("Recherche du Compte…")
}))
.children(
(self.friends.refusal.as_ref()).map(|(message, _)| {
div().text_sm().text_color(danger).child(message.clone())
}),
(self.friends.refusal.clone())
.map(|message| div().text_sm().text_color(danger).child(message)),
)
.children(missing_key.then(|| {
Button::new("friend-settings")
.label("Paramètres")
.on_click(cx.listener(|_, _, _, cx| cx.emit(SettingsRequested)))
}))
.into_any_element(),
)
}
+39 -13
View File
@@ -54,9 +54,7 @@ fn submit(page: &Entity<Page>, cx: &mut VisualTestContext) {
}
fn refusal(page: &Entity<Page>, cx: &mut VisualTestContext) -> Option<String> {
page.read_with(cx, |p, _| {
p.friends.refusal.as_ref().map(|(m, _)| m.clone())
})
page.read_with(cx, |p, _| p.friends.refusal.clone())
}
fn status_line(page: &Entity<Page>, cx: &mut VisualTestContext) -> Option<String> {
@@ -187,18 +185,14 @@ async fn a_riot_id_that_cannot_be_added_says_why_and_keeps_the_text(cx: &mut Tes
draw(&mut window);
}
// Without a key, « Paramètres » is the way out.
handles.no_key.store(true, Ordering::SeqCst);
// The relay is down: trying again later may work.
handles.relay_down.store(true, Ordering::SeqCst);
add(&page, &mut window, "Carl#EUW");
cx.condition(&page, |p, _| !p.friends.pending).await;
page.read_with(&window, |p, _| {
let (message, settings) = p.friends.refusal.clone().unwrap();
assert_eq!(
message,
"Ajoutez une clé API Riot dans « Paramètres » pour ajouter un Ami."
);
assert!(settings);
});
assert_eq!(
refusal(&page, &mut window).as_deref(),
Some("Le service Arena Tracker est indisponible : réessayez plus tard.")
);
draw(&mut window);
assert_eq!(selected(&page, &mut window).as_deref(), Some("Alice"));
}
@@ -338,3 +332,35 @@ async fn a_friend_who_signs_in_to_the_client_stays_a_friend_and_is_not_imported(
assert_eq!(items, [("Alice", false), ("Bob", false), ("Carl", true)]);
});
}
#[gpui::test]
async fn a_friend_shown_while_its_puuid_changes_stays_shown_and_its_import_goes_on(
cx: &mut TestAppContext,
) {
let (page, mut window, handles) = on_carl(cx).await;
handles.new_key.store(true, Ordering::SeqCst);
handles.third.store(true, Ordering::SeqCst);
handles.gate.set(false);
// Chosen again, Carl is rekeyed before its new Match is awaited.
pick(&page, &mut window, "Carl");
cx.condition(&page, |p, _| p.pinned.as_deref() == Some("Carl2"))
.await;
page.read_with(&window, |p, _| {
assert_eq!(p.friends.import.running.as_deref(), Some("Carl2"));
assert_eq!(p.viewed().map(|a| a.puuid.as_str()), Some("Carl2"));
assert_eq!(
p.friend_status().as_deref(),
Some("Import de Carl : 0 / 1 Parties")
);
});
assert_eq!(selected(&page, &mut window).as_deref(), Some("Carl2"));
handles.gate.set(true);
imported(&page, cx, 3).await;
assert_eq!(status_line(&page, &mut window), None);
page.read_with(&window, |p, _| {
assert_eq!(p.pinned.as_deref(), Some("Carl2"));
assert!(p.friends.ids.contains("Carl2") && p.friend_error().is_none());
});
}
+8 -4
View File
@@ -18,6 +18,7 @@ pub(in crate::page) use content::{BannerContent, Line};
use super::{Page, shown};
use crate::card_grid::MAX_WIDTH;
use crate::input_frame::input_frame;
use crate::theme::heading;
/// The filters on offer, whatever the Season.
@@ -246,10 +247,13 @@ impl Page {
.items_center()
.gap_3()
.child(
Input::new(&self.home_search_input)
.cleanable(true)
.w(px(260.))
.min_w(px(150.)),
input_frame(
&self.home_search_input,
Input::new(&self.home_search_input).cleanable(true),
)
.w(px(260.))
.min_w(px(150.))
.debug_selector(|| "home-search".into()),
)
.child(
TabBar::new("home-filter")
+45 -32
View File
@@ -1,4 +1,7 @@
use gpui_kit::component::{ActiveTheme as _, StyledExt as _};
use gpui_kit::assets::IconName;
use gpui_kit::base::Button as BaseButton;
use gpui_kit::component::tooltip::Tooltip;
use gpui_kit::component::{ActiveTheme as _, Icon, StyledExt as _};
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::*;
@@ -72,41 +75,16 @@ impl Page {
.debug_selector(|| "no-season".into())
.child(NO_SEASON)
});
// A phase's banner is about the phase only.
let link = (!self.shown_tab.is_phase()).then(|| {
// At the size of the line it ends. Its padding and border (5 px a side) hang out of
// the row, which keeps the text line's height.
self.tab_link(
"statistics-link",
"Statistiques ›",
Tab::Statistics,
ink,
cx,
)
.self_center()
.ml_auto()
.my(px(-5.))
.when(season_line.is_some(), |link| link.text_xs())
});
let copy = div()
.v_flex()
.min_w_0()
.when(!layout.narrow, |copy| copy.max_w(relative(0.46)))
.map(|copy| match link {
// Wrapping, the link goes under the line, clear of its text.
Some(link) => copy.child(
div()
.h_flex()
.flex_wrap()
.items_center()
.gap_x(px(12.))
.gap_y(px(10.))
.children(season_line)
.children(no_season_line)
.child(link),
),
None => copy.children(season_line).children(no_season_line),
// Full width in a narrow window: its last lines keep clear of the corner icon.
.when(layout.narrow && !self.shown_tab.is_phase(), |copy| {
copy.pr(px(40.))
})
.children(season_line)
.children(no_season_line)
.children((!text.title.text.is_empty()).then(|| {
div()
.v_flex()
@@ -177,15 +155,50 @@ impl Page {
})
.gap(px(layout.gap))
.px(px(layout.padding))
.py(px(24.))
.py(px(BANNER_PADDING_Y))
.debug_selector(|| "banner".into())
.child(self.banner_art.clone())
// Cached: only a change of its ticks or of the lit one draws the ring again.
.child(self.ring_slot(layout.ring, now, cx))
.child(copy)
// A phase's banner is about the phase only.
.children((!self.shown_tab.is_phase()).then(|| self.statistics_button(ink, layout, cx)))
}
/// « Statistiques », a chart icon in the banner's bottom-right corner, over the
/// illustration. Absolute, so it moves neither the text nor the ring and keeps the banner's
/// height. A real button: Tab reaches it, Enter or Space opens the page.
fn statistics_button(
&self,
ink: Hsla,
layout: BannerLayout,
cx: &mut Context<Page>,
) -> impl IntoElement {
const LABEL: &str = "Statistiques";
let theme = cx.theme();
let (ring, hover, hover_foreground) = (theme.ring, theme.accent, theme.accent_foreground);
BaseButton::new("statistics-link")
.absolute()
.right(px(layout.padding))
.bottom(px(BANNER_PADDING_Y))
.p_1()
.rounded_md()
.border_1()
.border_color(transparent_black())
.focus_visible(|style| style.border_color(ring))
.text_color(ink)
.hover(|style| style.bg(hover).text_color(hover_foreground))
.accessibility_label(LABEL)
.tooltip(|window, cx| Tooltip::new(LABEL).build(window, cx))
.debug_selector(|| "statistics-link".into())
.child(Icon::new(IconName::ChartLine))
.on_click(cx.listener(|this, _, window, cx| this.set_tab(Tab::Statistics, window, cx)))
}
}
/// The banner's vertical padding.
const BANNER_PADDING_Y: f32 = 24.;
/// The banner's rounded corners.
const RADIUS: f32 = 16.;
+163
View File
@@ -0,0 +1,163 @@
//! What an import shows beyond its count (#140): the arc around the ring and the status line's
//! countdown while the Riot quota makes it wait. No timer runs outside a wait, and the ring is
//! told at most once a second (rule #1).
use std::time::{Duration, Instant};
use arena_tracker_core::{SyncProgress, account_riot_id};
use gpui_kit::*;
use super::Page;
use crate::text::{quota_line, sync_line};
/// An import of fewer Matches than this shows no arc: a short sync must not flash it.
const ARC_FROM: usize = 10;
const EVERY: Duration = Duration::from_secs(1);
#[derive(Default)]
pub(super) struct ImportView {
/// When the quota wait told by the own sync, or by the Friend's import, ends.
pub(super) own_until: Option<Instant>,
pub(super) friend_until: Option<Instant>,
/// The countdown's timer, while a wait is on: dropped, it stops.
counting: Option<Task<()>>,
/// The signed-in Riot ID and the puuid of the Account it names, once resolved: forgotten
/// when the Accounts are read again.
pub(super) signed_in: Option<(std::sync::Arc<str>, Option<String>)>,
/// What the ring was given last, and when.
arc: Option<(usize, usize)>,
arc_at: Option<Instant>,
}
/// When the wait `progress` tells ends, from `now`.
pub(super) fn wait_until(progress: SyncProgress, now: Instant) -> Option<Instant> {
progress.quota_wait.map(|wait| now + wait)
}
impl Page {
/// The header's status line: the quota wait, else the import or sync going on, else the
/// last result.
pub(super) fn status_line(&self, now: Instant) -> SharedString {
if let Some(secs) = self.quota_secs_left(now) {
return quota_line(secs).into();
}
let busy = self.busy();
(!busy)
.then(|| self.friend_status())
.flatten()
.unwrap_or_else(|| sync_line(busy, self.progress, self.crashed, self.stored).into())
}
/// The seconds left, rounded up, of the quota wait the status line tells: the own sync's,
/// which comes first as its line does, else the Friend's.
fn quota_secs_left(&self, now: Instant) -> Option<u64> {
let (progress, until) = if self.busy() {
(self.progress?, self.import_view.own_until?)
} else {
(
self.friends.import_progress()?,
self.import_view.friend_until?,
)
};
progress.quota_wait?;
let left = until.checked_duration_since(now).filter(|d| !d.is_zero())?;
Some(left.as_millis().div_ceil(1000) as u64)
}
/// After a message of an import or a change of the Account shown: starts the countdown if a
/// wait is on, and gives the ring what it shows.
pub(super) fn show_import(&mut self, force: bool, cx: &mut Context<Self>) {
self.count_down(cx);
self.show_arc(force, cx);
}
/// One timer for the whole wait: it draws the status line again each second and ends with it.
fn count_down(&mut self, cx: &mut Context<Self>) {
if self
.quota_secs_left(cx.background_executor().now())
.is_none()
{
self.import_view.counting = None;
return;
}
if self.import_view.counting.is_some() {
return;
}
self.import_view.counting = Some(cx.spawn(async move |page, cx| {
loop {
cx.background_executor().timer(EVERY).await;
let more = page.update(cx, |page, cx| {
cx.notify();
page.show_arc(false, cx);
let more = page
.quota_secs_left(cx.background_executor().now())
.is_some();
if !more {
page.import_view.counting = None;
}
more
});
if !more.unwrap_or(false) {
return;
}
}
}));
}
/// (fetched, to fetch) of the import of the Account shown, once it is long enough to show.
fn arc_wanted(&mut self) -> Option<(usize, usize)> {
let own = self.progress.filter(|p| p.to_fetch >= ARC_FROM);
if own.is_some() {
self.resolve_signed_in();
}
let shown = self.displayed()?.puuid.as_str();
let friend = (self.friends.import_running() == Some(shown))
.then(|| self.friends.import_progress())
.flatten();
let progress = friend.or_else(|| {
// The Account the follower or the refresh imports is the one signed in to the client;
// one not read yet shows no arc, rather than the previous Account's.
let imported = match &self.import_view.signed_in {
Some((_, puuid)) => puuid.as_deref(),
None => self.active_account().map(|a| a.puuid.as_str()),
};
(imported? == shown).then_some(own?)
})?;
(progress.to_fetch >= ARC_FROM).then_some((progress.fetched, progress.to_fetch))
}
/// Resolves the Account of the signed-in Riot ID when it changes, so an own import builds no
/// Riot ID per Account at each message (see `phase_account`).
fn resolve_signed_in(&mut self) {
let Some(id) = self.tracker.signed_in_riot_id_folded() else {
self.import_view.signed_in = None;
return;
};
if self
.import_view
.signed_in
.as_ref()
.is_none_or(|(known, _)| *known != id)
{
let named = (self.accounts.iter()).find(|a| account_riot_id(a).to_lowercase() == *id);
self.import_view.signed_in = Some((id, named.map(|a| a.puuid.clone())));
}
}
/// Gives the ring the arc: at once when it appears, disappears or `force`, else at most once
/// a second.
fn show_arc(&mut self, force: bool, cx: &mut Context<Self>) {
let wanted = self.arc_wanted();
let now = cx.background_executor().now();
let view = &mut self.import_view;
let toggled = wanted.is_some() != view.arc.is_some();
let due = view.arc_at.is_none_or(|at| now.duration_since(at) >= EVERY);
if wanted == view.arc || !(force || toggled || due) {
return;
}
view.arc = wanted;
view.arc_at = Some(now);
self.ring
.update(cx, |ring, cx| ring.set_progress(wanted, cx));
}
}
-6
View File
@@ -3,12 +3,6 @@ use crate::worker::spawn_refresh;
use gpui_kit::*;
impl Page {
/// The follower thread was just started.
pub(crate) fn following(&mut self, cx: &mut Context<Self>) {
self.pending_round = true;
cx.notify();
}
/// The page gives way to another screen (« Paramètres »): what it shows is given back, the
/// grids' and the table's portraits and the banner's splash, in memory and in the window's
/// atlas. They load again when it is drawn.
+3 -2
View File
@@ -1,5 +1,6 @@
//! The page's text links: « Statistiques › » on the Challenge's banner and « ‹ Défi » on the
//! statistics page. Real buttons, so the keyboard reaches them (Tab, then Enter or Space).
//! The page's text link « ‹ Défi » on the statistics page (the banner's « Statistiques » is an
//! icon button, see `home::banner`). A real button, so the keyboard reaches it (Tab, then Enter
//! or Space).
use super::Tab;
use gpui_kit::base::Button as BaseButton;
+5 -3
View File
@@ -1,11 +1,11 @@
//! The end of a Match opens its recap (#129): when its end-of-game block arrives, « Parties »
//! shows the new Match, from any screen, never bringing the window forward nor taking the focus.
//! shows the new Match, from any screen; the window comes forward without taking the focus.
//! With the preference off, or when the game ended without a block, the Challenge shows instead.
//! The animation of the end of the Match plays on « Parties » then (#110). Each game's end is
//! decided once: nothing brings the player back to either screen afterwards.
//! During a Live Match, « En partie » stays until the block or the lobby (#109).
use crate::page::{ALL_SEASONS, Page, RecapOpened, Tab};
use crate::page::{ALL_SEASONS, MatchEndShown, Page, Tab};
use crate::worker::MatchEntry;
use arena_tracker_core::{FollowedMatch, GameEnd, SeasonScope};
use gpui_kit::component::IndexPath;
@@ -54,6 +54,7 @@ impl Page {
self.show_account(None, window, cx);
}
self.set_tab(Tab::Challenge, window, cx);
cx.emit(MatchEndShown);
}
return;
}
@@ -82,6 +83,7 @@ impl Page {
self.show_account(None, window, cx);
}
self.set_tab(Tab::Challenge, window, cx);
cx.emit(MatchEndShown);
}
}
@@ -118,7 +120,7 @@ impl Page {
// Already drawn, the screen does not open again by itself: an earlier recap goes.
self.open_matches(cx);
}
cx.emit(RecapOpened);
cx.emit(MatchEndShown);
}
/// The Season and Format of « Statistiques » hide the Match that just ended: to its Season
+8 -4
View File
@@ -15,6 +15,7 @@ use gpui_kit::*;
use super::list::{MatchRow, Outcome};
use super::shown::Champions;
use crate::input_frame::input_frame;
use crate::page::{Page, Tab};
use crate::text::ordinal;
use crate::worker::MatchEntry;
@@ -159,7 +160,8 @@ impl Page {
.list
.update(cx, |list, cx| list.set_rows(rows, selected.as_deref(), cx));
if choose {
self.request_recap(false);
// The Match chosen for the player, as one they click, shows their row.
self.request_recap(true);
}
self.dress_banner(cx);
}
@@ -226,9 +228,11 @@ impl Page {
)
.child(self.placement_control(cx))
.child(
Input::new(&self.matches.filters.input)
.cleanable(true)
.w_full(),
input_frame(
&self.matches.filters.input,
Input::new(&self.matches.filters.input).cleanable(true),
)
.w_full(),
)
}
+3 -2
View File
@@ -35,7 +35,6 @@ impl Page {
) -> Self {
let Launch {
notice,
following,
champion_sort,
open_recap_at_match_end,
} = launch;
@@ -218,10 +217,12 @@ impl Page {
pinned: None,
shown: None,
progress: None,
import_view: Default::default(),
refresh: RefreshGate::default(),
stats_job: RefreshGate::default(),
stats_generation: 0,
pending_round: following,
// The follower starts with the page: its first round is pending.
pending_round: true,
crashed: false,
last_reload: Instant::now(),
current_season,
+16 -40
View File
@@ -3,7 +3,7 @@
mod data;
use arena_tracker_core::{ChallengeSummary, Charts, ProgressCheck, StateFilter};
use arena_tracker_core::{ChallengeSummary, Charts, StateFilter};
use gpui_kit::component::chart::{AreaChart, BarChart};
use gpui_kit::component::input::Input;
use gpui_kit::component::select::Select;
@@ -13,7 +13,8 @@ use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::*;
use super::{Page, Tab as Screen, shown};
use crate::text::{decimal, official_note};
use crate::input_frame::input_frame;
use crate::text::decimal;
use crate::theme::{heading, surface};
const NO_MATCH: &str = "Aucune Partie";
@@ -37,13 +38,9 @@ fn filters(in_season: bool) -> &'static [(&'static str, StateFilter)] {
}
}
fn tile(
label: &'static str,
value: String,
note: Option<String>,
theme: &Theme,
) -> impl IntoElement {
fn tile(label: &'static str, value: String, theme: &Theme) -> impl IntoElement {
div()
.debug_selector(move || format!("tile-{label}"))
.v_flex()
.flex_1()
.gap_1()
@@ -64,44 +61,21 @@ fn tile(
.font_weight(FontWeight::SEMIBOLD)
.child(value),
)
.children(note.map(|note| {
div()
.text_xs()
.text_color(theme.muted_foreground)
.child(note)
}))
}
fn challenge_tiles(
c: &ChallengeSummary,
official: Option<&ProgressCheck>,
theme: &Theme,
) -> impl IntoElement {
fn challenge_tiles(c: &ChallengeSummary, theme: &Theme) -> impl IntoElement {
let average = c.average_attempts.map_or("-".into(), |a| decimal(a, 2));
// Next to the count whether the app agrees or not; the banner covers the difference.
let note = match official {
Some(ProgressCheck::Agrees(n)) | Some(ProgressCheck::Differs { official: n, .. }) => {
Some(official_note(*n))
}
_ => None,
};
div()
.h_flex()
.gap_3()
.child(tile(
"Champions validés",
format!("{} / {}", c.completed, c.total),
note,
theme,
))
.child(tile("Tentatives", c.attempts.to_string(), None, theme))
.child(tile("Tentatives par champion validé", average, None, theme))
.child(tile(
"Du premier coup",
c.first_tries.to_string(),
None,
theme,
))
.child(tile("Tentatives", c.attempts.to_string(), theme))
.child(tile("Tentatives par champion validé", average, theme))
.child(tile("Du premier coup", c.first_tries.to_string(), theme))
}
/// A titled card holding a chart, or `empty` in its place.
@@ -353,7 +327,7 @@ impl Page {
if shown("tiles")
&& let Some(c) = challenge
{
content.push(challenge_tiles(c, self.official(), cx.theme()).into_any_element());
content.push(challenge_tiles(c, cx.theme()).into_any_element());
}
content.push(
self.charts
@@ -382,10 +356,12 @@ impl Page {
})),
)
.child(
Input::new(&self.search_input)
.cleanable(true)
.w(px(260.))
.min_w(px(150.)),
input_frame(
&self.search_input,
Input::new(&self.search_input).cleanable(true),
)
.w(px(260.))
.min_w(px(150.)),
)
.into_any_element(),
);
+2
View File
@@ -32,6 +32,7 @@ impl Page {
self.accounts.clone_from(&directory.accounts);
self.last_active.clone_from(&directory.last_active);
self.friends.ids.clone_from(&directory.friends);
self.follow_replaced_puuids();
if self.pinned.as_ref() == self.status.updating.as_ref().map(|a| &a.puuid) {
self.pinned = None;
}
@@ -41,6 +42,7 @@ impl Page {
if changed {
// The live champ select's Account may now be in the list: resolve it again.
self.phase_riot_id = None;
self.import_view.signed_in = None;
}
if changed {
(self.account_select).update(cx, |select, cx| {
+3
View File
@@ -18,6 +18,8 @@ pub(crate) mod client_fixtures;
pub(crate) mod friends_fixtures;
mod grid;
mod home;
mod import_arc;
mod import_quota;
mod in_game;
mod in_game_end;
mod in_game_fixtures;
@@ -42,3 +44,4 @@ mod portraits;
mod ring_hover;
mod sorting;
mod sorting_fixtures;
mod statistics_tiles;
+35 -39
View File
@@ -9,75 +9,71 @@ fn bounds(cx: &mut VisualTestContext, id: &'static str) -> Bounds<Pixels> {
cx.debug_bounds(id).unwrap()
}
fn same_line(a: Bounds<Pixels>, b: Bounds<Pixels>) -> bool {
(a.center().y - b.center().y).abs() < px(1.)
/// The icon sits in the banner's bottom-right corner, inside its padding (16 to 36 px a side,
/// 24 px under it), and covers none of the text.
fn assert_in_the_corner(cx: &mut VisualTestContext) {
let (link, banner) = (bounds(cx, "statistics-link"), bounds(cx, "banner"));
let right = banner.right() - link.right();
assert!(right >= px(15.) && right <= px(37.), "{link:?} {banner:?}");
assert!(
(banner.bottom() - link.bottom() - px(24.)).abs() < px(1.),
"{link:?} {banner:?}"
);
// A button of the icon's size, not a line of text.
assert!(
link.size.width < px(40.) && link.size.height < px(40.),
"{link:?}"
);
for id in ["banner-season", "no-season", "banner-title"] {
if let Some(text) = cx.debug_bounds(id) {
assert!(!link.intersects(&text), "{id} {text:?} {link:?}");
}
}
}
#[gpui::test]
fn the_link_ends_the_seasons_line_and_the_banner_has_no_line_under_the_last_match(
cx: &mut TestAppContext,
) {
fn the_icon_is_in_the_banners_bottom_right_corner_not_on_the_seasons_line(cx: &mut TestAppContext) {
let (page, cx) = super::page_fixtures::open_page_in_season(cx);
let cx = &mut { cx };
show(&page, cx, statistics(0, 170, champions(170)));
draw(cx);
let (link, season, title) = (
bounds(cx, "statistics-link"),
bounds(cx, "banner-season"),
bounds(cx, "banner-title"),
);
assert!(same_line(link, season), "{link:?} {season:?}");
assert!(season.right() <= link.left(), "{season:?} {link:?}");
// The title's block spans the text column: the link is at its right edge, above the title.
assert!(
(link.right() - title.right()).abs() < px(1.),
"{link:?} {title:?}"
);
assert!(link.bottom() <= title.top(), "{link:?} {title:?}");
// Its label is the Season's size, and the line keeps the height of its text.
assert!(link.size.height < px(30.), "{link:?}");
assert_in_the_corner(cx);
// The Season's line keeps the height of its text, the link no longer sits on it.
let (link, season) = (bounds(cx, "statistics-link"), bounds(cx, "banner-season"));
assert!(season.size.height < px(20.), "{season:?}");
assert!(link.top() > season.bottom(), "{link:?} {season:?}");
}
#[gpui::test]
fn without_a_season_the_link_ends_the_no_season_line(cx: &mut TestAppContext) {
fn without_a_season_the_icon_is_in_the_corner_too(cx: &mut TestAppContext) {
let (_page, cx) = open_page(cx);
let cx = &mut { cx };
draw(cx);
let (link, line) = (bounds(cx, "statistics-link"), bounds(cx, "no-season"));
assert!(same_line(link, line), "{link:?} {line:?}");
assert!(line.right() <= link.left(), "{line:?} {link:?}");
assert!(cx.debug_bounds("no-season").is_some());
assert_in_the_corner(cx);
}
#[gpui::test]
fn in_a_narrow_window_the_link_goes_under_a_long_season_without_covering_it(
cx: &mut TestAppContext,
) {
fn in_a_narrow_window_the_icon_stays_in_the_corner_with_a_long_season(cx: &mut TestAppContext) {
let name =
"Saison très longue qui prend toute la largeur de la bannière étroite et plus encore";
let tracker = Tracker::open(
Path::new(":memory:"),
Box::new(RiotApi::new(String::new(), "europe")),
)
.unwrap()
.with_seasons(vec![season(name, 2020)]);
let tracker = Tracker::open(Path::new(":memory:"), Box::new(RiotApi::new("", "europe")))
.unwrap()
.with_seasons(vec![season(name, 2020)]);
let (page, cx) = open_page_with_tracker(cx, tracker);
let cx = &mut { cx };
show(&page, cx, statistics(0, 170, champions(170)));
cx.simulate_resize(size(px(480.), px(800.)));
draw(cx);
let (link, season) = (bounds(cx, "statistics-link"), bounds(cx, "banner-season"));
assert!(season.bottom() <= link.top(), "{season:?} {link:?}");
assert_in_the_corner(cx);
}
#[gpui::test]
fn in_a_narrow_window_the_link_stays_on_a_short_seasons_line(cx: &mut TestAppContext) {
fn in_a_narrow_window_the_icon_is_in_the_corner_with_a_short_season(cx: &mut TestAppContext) {
let (page, cx) = super::page_fixtures::open_page_in_season(cx);
let cx = &mut { cx };
show(&page, cx, statistics(0, 170, champions(170)));
cx.simulate_resize(size(px(480.), px(800.)));
draw(cx);
let (link, season) = (bounds(cx, "statistics-link"), bounds(cx, "banner-season"));
assert!(same_line(link, season), "{link:?} {season:?}");
assert!(season.right() <= link.left(), "{season:?} {link:?}");
assert_in_the_corner(cx);
}
+44 -13
View File
@@ -1,6 +1,6 @@
//! The Riot source of the Friends' tests: Alice and Bob as in `TwoAccounts`, and Carl (a Friend
//! of the key's region, two Matches) and Dora (another region). A gate holds Carl's Matches
//! back, so a test sees an import under way.
//! of the app's region, two Matches) and Dora (another region). A gate holds Carl's Matches
//! back the first time each is fetched, so a test sees an import under way.
use super::client_fixtures::FakeClient;
use super::matches_fixtures::TwoAccounts;
@@ -41,8 +41,17 @@ pub(in crate::page) struct Handles {
pub(in crate::page) fetched: Arc<Mutex<Vec<String>>>,
/// Carl has played a third Match.
pub(in crate::page) third: Arc<AtomicBool>,
/// The key is gone: Riot answers for no Riot ID.
pub(in crate::page) no_key: Arc<AtomicBool>,
/// The relay is down: it answers for no Riot ID.
pub(in crate::page) relay_down: Arc<AtomicBool>,
/// Carl has twelve Matches, `long` ones, instead: an import long enough to draw the arc.
pub(in crate::page) many: Arc<AtomicBool>,
/// Riot's key changed: Carl is now `Carl2`, his Matches the same.
pub(in crate::page) new_key: Arc<AtomicBool>,
}
/// The id of Carl's `i`th long Match.
fn long(i: usize) -> String {
format!("EUW1_92000000{i:02}")
}
struct Riot {
@@ -52,10 +61,15 @@ struct Riot {
impl MatchHistorySource for Riot {
fn resolve_account(&self, game_name: &str, tag_line: &str) -> Result<Account, SourceError> {
if self.handles.no_key.load(Ordering::SeqCst) {
return Err(SourceError::MissingKey);
if self.handles.relay_down.load(Ordering::SeqCst) {
return Err(SourceError::Unavailable);
}
match game_name {
"Carl" if self.handles.new_key.load(Ordering::SeqCst) => Ok(Account {
puuid: "Carl2".into(),
game_name: game_name.into(),
tag_line: tag_line.into(),
}),
"Alice" | "Bob" | "Carl" | "Dora" => self.inner.resolve_account(game_name, tag_line),
_ => Err(SourceError::NotFound),
}
@@ -69,27 +83,42 @@ impl MatchHistorySource for Riot {
count: usize,
since: Option<i64>,
) -> Result<Vec<String>, SourceError> {
if puuid != "Carl" {
if !matches!(puuid, "Carl" | "Carl2") {
return self.inner.match_ids(puuid, queue_id, start, count, since);
}
if queue_id != 1750 || start != 0 {
return Ok(Vec::new());
}
if self.handles.many.load(Ordering::SeqCst) {
return Ok((0..12).map(long).collect());
}
let skip = usize::from(!self.handles.third.load(Ordering::SeqCst));
Ok(CARL[skip..].iter().map(|id| id.to_string()).collect())
}
fn fetch_match(&self, id: &str) -> Result<String, SourceError> {
let Some(at) = CARL.iter().position(|carl| *carl == id) else {
let long_at = (0..12).find(|i| long(*i) == id);
let Some(at) = CARL.iter().position(|carl| *carl == id).or(long_at) else {
return self.inner.fetch_match(id);
};
self.handles.gate.pass();
// A Match fetched again (the proof of a changed PUUID) is not one the import waits for.
if !self.handles.fetched.lock().unwrap().iter().any(|f| f == id) {
self.handles.gate.pass();
}
self.handles.fetched.lock().unwrap().push(id.into());
let start = ["1794000000000", "1792000000000", "1790000000000"][at];
let carl = if self.handles.new_key.load(Ordering::SeqCst) {
"Carl2"
} else {
"Carl"
};
let start = match long_at {
Some(i) => (1_790_000_000_000_i64 + i as i64 * 1000).to_string(),
None => ["1794000000000", "1792000000000", "1790000000000"][at].into(),
};
Ok(MATCH_1750
.replace("EUW1_9000000006", id)
.replace("1794763752767", start)
.replace("fixture-puuid-self", "Carl"))
.replace("1794763752767", &start)
.replace("fixture-puuid-self", carl))
}
fn account_platform(&self, puuid: &str) -> Result<String, SourceError> {
@@ -111,7 +140,9 @@ pub(in crate::page) fn tracker() -> (Tracker, Arc<Mutex<String>>, Handles) {
}),
fetched: Arc::default(),
third: Arc::default(),
no_key: Arc::default(),
many: Arc::default(),
relay_down: Arc::default(),
new_key: Arc::default(),
};
let client = FakeClient::new("Alice");
let source = Riot {
+4 -1
View File
@@ -1,3 +1,4 @@
use super::banner_fixtures::ring_renders;
use super::page_fixtures::{
center, champions, count_hovers, draw, grid_names, open_page_in_season, settle, show,
statistics, switch_tab,
@@ -193,8 +194,9 @@ fn hovering_outside_the_grid_does_not_render_the_cards(cx: &mut TestAppContext)
let grid = page.read_with(cx, |page, _| page.home_grid.clone());
let renders = grid.read_with(cx, |grid, _| grid.renders);
assert!(renders > 0);
let ring = ring_renders(&page, cx);
// A navigation button's hover style redraws the window.
// A navigation button's hover style redraws the window (the icon from where no tick is lit).
for _ in 0..2 {
let button = center(cx, "statistics-link");
cx.simulate_mouse_move(button, None, Modifiers::none());
@@ -203,6 +205,7 @@ fn hovering_outside_the_grid_does_not_render_the_cards(cx: &mut TestAppContext)
draw(cx);
}
assert_eq!(grid.read_with(cx, |grid, _| grid.renders), renders);
assert_eq!(ring_renders(&page, cx), ring);
// The count does move when the grid changes.
grid.update(cx, |_, cx| cx.notify());
+26
View File
@@ -165,6 +165,32 @@ fn the_counter_keeps_its_total_while_a_search_and_a_filter_reduce_the_list(
assert_eq!(counter(cx), "1 / 4 champions validés");
}
#[gpui::test]
fn a_click_in_the_padding_of_the_search_field_gives_it_the_keyboard(cx: &mut TestAppContext) {
use gpui_kit::{Modifiers, point, px};
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(&page, cx, statistics(0, 3, champions(3)));
draw(cx);
let input = page.read_with(cx, |p, _| p.home_search_input.clone());
let field = cx.debug_bounds("home-search").unwrap();
let text = |cx: &mut VisualTestContext| input.read_with(cx, |i, _| i.value().to_string());
// Just inside the left border, above the text line: nothing but the frame is there.
cx.simulate_click(
point(field.left() + px(2.), field.top() + px(2.)),
Modifiers::none(),
);
cx.simulate_input("an");
assert_eq!(text(cx), "an");
// The text line still takes its own click, and the field keeps working.
cx.update(|window, cx| window.blur(cx));
cx.simulate_click(field.center(), Modifiers::none());
cx.simulate_input("x");
assert_eq!(text(cx), "anx");
}
#[gpui::test]
fn the_home_follows_the_season_of_the_statistics_but_not_their_format(cx: &mut TestAppContext) {
cx.executor().allow_parking();
+284
View File
@@ -0,0 +1,284 @@
//! The import's arc on the ring (#140): shown for the import of the Account displayed, once it
//! is 10 Matches long, and the ring stays a cached view while it advances. The Riot source of
//! the Friend's import is simulated (`friends_fixtures`); the own sync's progress arrives as the
//! follower's does, through `Page::apply`.
use super::banner_fixtures::ring_renders;
use super::friends_fixtures::{Handles, tracker};
use super::page_fixtures::{champions, draw, open_page_with_tracker, show, statistics};
use crate::card_grid::CardHovered;
use crate::page::Page;
use crate::worker::Msg;
use arena_tracker_core::SyncProgress;
use gpui_kit::{
Entity, Modifiers, ScrollDelta, ScrollEvent, TestAppContext, VisualTestContext, point, px,
};
use std::cell::Cell;
use std::rc::Rc;
use std::sync::atomic::Ordering;
use std::time::Duration;
/// The page on Alice (signed in to the client), Carl stored as a Friend and not imported yet.
pub(super) async fn on_alice(
cx: &mut TestAppContext,
) -> (Entity<Page>, VisualTestContext, Handles) {
cx.executor().allow_parking();
let (tracker, _, handles) = tracker();
tracker.add_friend("Carl#EUW").unwrap();
let (page, window) = open_page_with_tracker(cx, tracker);
cx.condition(&page, |p, _| p.stats.is_some() && !p.pending_round)
.await;
(page, window, handles)
}
pub(super) fn progress(fetched: usize, to_fetch: usize) -> SyncProgress {
SyncProgress {
fetched,
to_fetch,
..Default::default()
}
}
/// A message of the worker, as the page receives it.
pub(super) fn tell(page: &Entity<Page>, cx: &mut VisualTestContext, msg: Msg) {
cx.update(|window, cx| page.update(cx, |page, cx| page.apply(msg, window, cx)));
}
pub(super) fn arc(page: &Entity<Page>, cx: &mut VisualTestContext) -> Option<(usize, usize)> {
page.read_with(cx, |p, cx| p.ring.read(cx).progress())
}
pub(super) fn choose(page: &Entity<Page>, cx: &mut VisualTestContext, puuid: &str) {
cx.update(|window, cx| page.update(cx, |p, cx| p.choose_account(puuid, window, cx)));
}
/// One second of the test clock, the timers having fired.
pub(super) fn second(cx: &mut VisualTestContext) {
cx.executor().advance_clock(Duration::from_secs(1));
cx.run_until_parked();
draw(cx);
}
fn round(page: &Entity<Page>, cx: &mut VisualTestContext) -> Msg {
Msg::Round {
status: page.read_with(cx, |p, _| p.tracker.status()),
reload: false,
matches: Vec::new(),
game_end: None,
}
}
#[gpui::test]
async fn the_own_sync_of_the_account_shown_draws_the_arc_until_it_ends(cx: &mut TestAppContext) {
let (page, mut window, _) = on_alice(cx).await;
let cx = &mut window;
assert_eq!(arc(&page, cx), None);
// A sync of fewer than 10 Matches never flashes it.
tell(&page, cx, Msg::Progress(progress(1, 9)));
assert_eq!(arc(&page, cx), None);
tell(&page, cx, Msg::Progress(progress(0, 12)));
assert_eq!(arc(&page, cx), Some((0, 12)));
second(cx);
tell(&page, cx, Msg::Progress(progress(5, 12)));
assert_eq!(arc(&page, cx), Some((5, 12)));
// It goes with the sync, and does not come back for the next short one.
let end = round(&page, cx);
tell(&page, cx, end);
assert_eq!(arc(&page, cx), None);
tell(&page, cx, Msg::Progress(progress(1, 2)));
assert_eq!(arc(&page, cx), None);
}
#[gpui::test]
async fn the_sync_of_another_account_than_the_one_shown_draws_no_arc(cx: &mut TestAppContext) {
let (page, mut window, _) = on_alice(cx).await;
let cx = &mut window;
choose(&page, cx, "Bob");
tell(&page, cx, Msg::Progress(progress(2, 12)));
assert_eq!(arc(&page, cx), None);
// Back on Alice, whose sync it is: the arc is there at once.
choose(&page, cx, "Alice");
assert_eq!(arc(&page, cx), Some((2, 12)));
choose(&page, cx, "Bob");
assert_eq!(arc(&page, cx), None);
}
#[gpui::test]
async fn a_friends_import_draws_the_arc_while_the_friend_is_shown_and_ends_with_it(
cx: &mut TestAppContext,
) {
let (page, mut window, handles) = on_alice(cx).await;
handles.gate.set(false);
choose(&page, &mut window, "Carl");
cx.condition(&page, |p, _| {
p.friend_status().as_deref() == Some("Import de Carl : 0 / 2 Parties")
})
.await;
let cx = &mut window;
// Two Matches: no arc.
assert_eq!(arc(&page, cx), None);
let friend = |progress| Msg::FriendProgress {
puuid: "Carl".into(),
progress,
};
tell(&page, cx, friend(progress(3, 12)));
assert_eq!(arc(&page, cx), Some((3, 12)));
second(cx);
tell(&page, cx, friend(progress(4, 12)));
assert_eq!(arc(&page, cx), Some((4, 12)));
// Another Account shown: only the status line tells the import goes on.
choose(&page, cx, "Alice");
assert_eq!(arc(&page, cx), None);
choose(&page, cx, "Carl");
assert_eq!(arc(&page, cx), Some((4, 12)));
handles.gate.set(true);
cx.condition(&page, |p, _| p.friends.import_running().is_none())
.await;
assert_eq!(arc(&page, &mut window), None);
}
// The worker runs the import, the simulated Riot source gives Carl twelve Matches.
#[gpui::test]
async fn a_real_import_of_twelve_matches_draws_the_arc_while_it_runs_and_not_after(
cx: &mut TestAppContext,
) {
let (page, mut window, handles) = on_alice(cx).await;
handles.many.store(true, Ordering::SeqCst);
handles.gate.set(false);
choose(&page, &mut window, "Carl");
cx.condition(&page, |p, cx| p.ring.read(cx).progress() == Some((0, 12)))
.await;
handles.gate.set(true);
cx.condition(&page, |p, _| p.friends.import_running().is_none())
.await;
assert_eq!(arc(&page, &mut window), None);
assert_eq!(handles.fetched.lock().unwrap().len(), 12);
}
#[gpui::test]
async fn a_crash_takes_the_arc_away(cx: &mut TestAppContext) {
let (page, mut window, _) = on_alice(cx).await;
let cx = &mut window;
tell(&page, cx, Msg::Progress(progress(0, 12)));
assert_eq!(arc(&page, cx), Some((0, 12)));
tell(&page, cx, Msg::Crashed);
assert_eq!(arc(&page, cx), None);
}
// Rule #1: the ring is drawn again for the arc appearing, disappearing and a new count at most
// once a second, never by a second of waiting, a hover or a scroll elsewhere.
#[gpui::test]
async fn the_ring_is_drawn_again_only_for_the_arc_and_at_most_once_a_second(
cx: &mut TestAppContext,
) {
let (page, mut window, _) = on_alice(cx).await;
let cx = &mut window;
show(&page, cx, statistics(0, 170, champions(170)));
draw(cx);
let renders = ring_renders(&page, cx);
let tessellations = |page: &Entity<Page>, cx: &mut VisualTestContext| {
page.read_with(cx, |p, cx| p.ring.read(cx).tessellations.get())
};
tell(&page, cx, Msg::Progress(progress(1, 12)));
draw(cx);
assert_eq!(ring_renders(&page, cx), renders + 1);
// Two messages within the same second: no more drawing.
tell(&page, cx, Msg::Progress(progress(2, 12)));
tell(&page, cx, Msg::Progress(progress(3, 12)));
draw(cx);
assert_eq!(ring_renders(&page, cx), renders + 1);
// The pointer on a card lights its tick, once; elsewhere on the card nothing changes.
let grid = page.read_with(cx, |p, _| p.home_grid.clone());
let card = cx.debug_bounds("card-1").unwrap();
cx.simulate_mouse_move(card.center(), None, Modifiers::none());
draw(cx);
assert_eq!(page.read_with(cx, |p, cx| p.ring.read(cx).lit()), Some(1));
assert_eq!(ring_renders(&page, cx), renders + 2);
cx.simulate_mouse_move(
card.center() + point(px(10.), px(10.)),
None,
Modifiers::none(),
);
draw(cx);
assert_eq!(ring_renders(&page, cx), renders + 2);
// The grid scrolls under the pointer: the ring is drawn again only for each change of the
// card under it, and the arc is not tessellated again.
let changes = Rc::new(Cell::new(0));
let _subscription = cx.update(|_, cx| {
let changes = changes.clone();
cx.subscribe(&grid, move |_, _: &CardHovered, _| {
changes.set(changes.get() + 1)
})
});
let at = card.center();
let made = tessellations(&page, cx);
for _ in 0..3 {
let (was_changed, was_drawn) = (changes.get(), ring_renders(&page, cx));
cx.simulate_event(ScrollEvent {
position: at,
delta: ScrollDelta::Pixels(point(px(0.), px(-200.))),
..Default::default()
});
draw(cx);
assert_eq!(
ring_renders(&page, cx) - was_drawn,
changes.get() - was_changed
);
}
assert!(
changes.get() > 0,
"no scroll changed the card under the pointer"
);
assert!(grid.read_with(cx, |grid, _| grid.scrolled()) > px(0.));
assert_eq!(tessellations(&page, cx), made);
let scrolled = ring_renders(&page, cx);
// The next second brings the count, once, however many messages.
second(cx);
tell(&page, cx, Msg::Progress(progress(4, 12)));
tell(&page, cx, Msg::Progress(progress(5, 12)));
draw(cx);
assert_eq!(arc(&page, cx), Some((4, 12)));
assert_eq!(ring_renders(&page, cx), scrolled + 1);
// Another tick lit draws the ring again, but tessellates nothing: the arc is kept.
let made = tessellations(&page, cx);
let lit = page.read_with(cx, |p, cx| p.ring.read(cx).lit());
let other = if lit == Some(2) { 3 } else { 2 };
cx.update(|_, cx| {
page.update(cx, |p, cx| {
p.ring.update(cx, |r, cx| r.set_lit(Some(other), cx))
})
});
draw(cx);
assert_eq!(ring_renders(&page, cx), scrolled + 2);
assert_eq!(tessellations(&page, cx), made);
// The end: it goes, once.
let end = round(&page, cx);
tell(&page, cx, end);
draw(cx);
assert_eq!(ring_renders(&page, cx), scrolled + 3);
}
// An Account signed in to the client that the page has not read yet is not the previous one.
#[gpui::test]
async fn an_import_of_a_signed_in_account_not_read_yet_draws_no_arc(cx: &mut TestAppContext) {
let (page, mut window, _) = on_alice(cx).await;
let cx = &mut window;
page.update(cx, |p, _| p.accounts.retain(|a| a.puuid != "Alice"));
tell(&page, cx, Msg::Progress(progress(0, 12)));
assert_eq!(arc(&page, cx), None);
}
+150
View File
@@ -0,0 +1,150 @@
//! The status line while the import waits for the Riot quota (#140): the seconds left, counted
//! down by one timer that exists only for the wait.
use super::banner_fixtures::ring_renders;
use super::import_arc::{arc, choose, on_alice, progress, second, tell};
use super::page_fixtures::draw;
use crate::page::Page;
use crate::worker::Msg;
use arena_tracker_core::SyncProgress;
use gpui_kit::{Entity, TestAppContext, VisualTestContext};
use std::cell::Cell;
use std::rc::Rc;
use std::time::Duration;
fn line(page: &Entity<Page>, cx: &mut VisualTestContext) -> String {
page.read_with(cx, |p, cx| {
p.status_line(cx.background_executor().now()).to_string()
})
}
fn waiting(fetched: usize, to_fetch: usize, secs: u64) -> SyncProgress {
SyncProgress {
quota_wait: Some(Duration::from_secs(secs)),
..progress(fetched, to_fetch)
}
}
/// How many times the page is told it changed from now on.
fn notifications(page: &Entity<Page>, cx: &mut VisualTestContext) -> Rc<Cell<usize>> {
let told = Rc::new(Cell::new(0));
let counted = told.clone();
cx.update(|_, cx| {
cx.observe(page, move |_, _| counted.set(counted.get() + 1))
.detach()
});
told
}
#[gpui::test]
async fn the_own_sync_counts_the_wait_down_then_the_import_line_comes_back(
cx: &mut TestAppContext,
) {
let (page, mut window, _) = on_alice(cx).await;
let cx = &mut window;
tell(&page, cx, Msg::Progress(progress(3, 12)));
assert_eq!(line(&page, cx), "Import en cours : 3 / 12 Parties");
tell(&page, cx, Msg::Progress(waiting(3, 12, 12)));
assert_eq!(line(&page, cx), "Quota Riot atteint : reprise dans 12 s");
second(cx);
assert_eq!(line(&page, cx), "Quota Riot atteint : reprise dans 11 s");
cx.executor().advance_clock(Duration::from_millis(500));
// Rounded up: 10.5 s left say 11.
assert_eq!(line(&page, cx), "Quota Riot atteint : reprise dans 11 s");
for _ in 0..10 {
second(cx);
}
assert_eq!(line(&page, cx), "Quota Riot atteint : reprise dans 1 s");
tell(&page, cx, Msg::Progress(progress(3, 12)));
assert_eq!(line(&page, cx), "Import en cours : 3 / 12 Parties");
}
#[gpui::test]
async fn a_wait_that_passed_without_news_falls_back_to_the_import_line(cx: &mut TestAppContext) {
let (page, mut window, _) = on_alice(cx).await;
let cx = &mut window;
tell(&page, cx, Msg::Progress(waiting(3, 12, 2)));
second(cx);
second(cx);
assert_eq!(line(&page, cx), "Import en cours : 3 / 12 Parties");
}
#[gpui::test]
async fn nothing_ticks_before_a_wait_nor_after_it(cx: &mut TestAppContext) {
let (page, mut window, _) = on_alice(cx).await;
let cx = &mut window;
let told = notifications(&page, cx);
for _ in 0..3 {
second(cx);
}
assert_eq!(told.get(), 0);
// The wait: the page is drawn again each second, and the ring is not.
tell(&page, cx, Msg::Progress(progress(3, 12)));
draw(cx);
let renders = ring_renders(&page, cx);
tell(&page, cx, Msg::Progress(waiting(3, 12, 30)));
let before = told.get();
for _ in 0..3 {
second(cx);
}
assert_eq!(told.get() - before, 3);
assert_eq!(ring_renders(&page, cx), renders);
assert_eq!(arc(&page, cx), Some((3, 12)));
// Resumed: the timer has ended itself.
tell(&page, cx, Msg::Progress(progress(4, 12)));
let before = told.get();
for _ in 0..3 {
second(cx);
}
assert_eq!(told.get(), before);
}
#[gpui::test]
async fn a_friends_import_tells_its_wait_too_and_the_own_sync_keeps_its_priority(
cx: &mut TestAppContext,
) {
let (page, mut window, handles) = on_alice(cx).await;
handles.gate.set(false);
choose(&page, &mut window, "Carl");
cx.condition(&page, |p, _| {
p.friend_status().as_deref() == Some("Import de Carl : 0 / 2 Parties")
})
.await;
let cx = &mut window;
let friend = |progress| Msg::FriendProgress {
puuid: "Carl".into(),
progress,
};
tell(&page, cx, friend(waiting(0, 2, 5)));
assert_eq!(line(&page, cx), "Quota Riot atteint : reprise dans 5 s");
second(cx);
assert_eq!(line(&page, cx), "Quota Riot atteint : reprise dans 4 s");
// The own sync's line comes first, waiting or not.
tell(&page, cx, Msg::Progress(progress(1, 12)));
assert_eq!(line(&page, cx), "Import en cours : 1 / 12 Parties");
tell(&page, cx, Msg::Progress(waiting(1, 12, 20)));
assert_eq!(line(&page, cx), "Quota Riot atteint : reprise dans 20 s");
// Its end brings the Friend's wait back, still counting.
let status = page.read_with(cx, |p, _| p.tracker.status());
let end = Msg::Round {
status,
reload: false,
matches: Vec::new(),
game_end: None,
};
tell(&page, cx, end);
assert_eq!(line(&page, cx), "Quota Riot atteint : reprise dans 4 s");
second(cx);
assert_eq!(line(&page, cx), "Quota Riot atteint : reprise dans 3 s");
tell(&page, cx, friend(progress(0, 2)));
assert_eq!(line(&page, cx), "Import de Carl : 0 / 2 Parties");
handles.gate.set(true);
}
+3 -1
View File
@@ -69,11 +69,13 @@ async fn with_the_preference_off_the_block_of_the_live_match_shows_the_challenge
game_ends(&page, &fake, &mut window);
settle_tabs(&page, &mut window);
assert_eq!(tabs(&page, &mut window), (Tab::Challenge, Tab::Challenge));
assert_eq!(opened.get(), 0);
assert_eq!(opened.get(), 1);
client.lobby();
client.read(&page, &mut window);
settle_tabs(&page, &mut window);
assert_eq!(tabs(&page, &mut window), (Tab::Challenge, Tab::Challenge));
// The lobby that follows decides nothing more.
assert_eq!(opened.get(), 1);
draw(&mut window);
assert!(window.debug_bounds("tab-in-game").is_none());
}
@@ -7,7 +7,7 @@ use super::matches_provisional::{GAME, LEFT_AT_MS, MATCH, block, tracker_before_
use super::page_fixtures::{draw, frame_after, open_page_with_tracker, season, switch_tab};
use crate::page::ALL_SEASONS;
use crate::page::matches::Recap;
use crate::page::{Page, RecapOpened, Tab};
use crate::page::{MatchEndShown, Page, Tab};
use crate::worker::Msg;
use arena_tracker_core::{ChampSelect, FollowedMatch, Format, GameEnd, MatchEnd, SeasonScope};
use gpui_kit::component::select::SelectEvent;
@@ -16,7 +16,7 @@ use std::cell::Cell;
use std::rc::Rc;
/// The page on Alice's Matches before the game ends, Alice's client, which holds its block, and
/// how many times the page said it opened a recap.
/// how many times the page said it showed the end of a game.
pub(super) fn before_the_end(
cx: &mut TestAppContext,
) -> (Entity<Page>, VisualTestContext, FakeClient, Rc<Cell<usize>>) {
@@ -33,7 +33,7 @@ fn before_the_end_in(
let opened = Rc::new(Cell::new(0));
let counted = opened.clone();
window.update(|_, cx| {
cx.subscribe(&page, move |_, _: &RecapOpened, _| {
cx.subscribe(&page, move |_, _: &MatchEndShown, _| {
counted.set(counted.get() + 1)
})
.detach()
@@ -224,7 +224,7 @@ async fn with_the_preference_off_the_challenge_shows_and_the_match_is_listed(
settle_tabs(&page, &mut window);
assert_eq!(tabs(&page, &mut window), (Tab::Challenge, Tab::Challenge));
assert_eq!(opened.get(), 0);
assert_eq!(opened.get(), 1);
// In the history all the same: « Parties » opened by hand chooses it, the most recent.
switch_tab(&page, &mut window, Tab::Matches);
its_recap(&page, cx).await;
@@ -306,7 +306,7 @@ async fn a_game_that_ends_without_its_block_shows_the_challenge(cx: &mut TestApp
game_ends_without_its_block(&page, &mut window, 9_000_000_022);
settle_tabs(&page, &mut window);
assert_eq!(tabs(&page, &mut window), (Tab::Challenge, Tab::Challenge));
assert_eq!(opened.get(), 0);
assert_eq!(opened.get(), 2);
left_alone(&mut window, true);
}
@@ -78,7 +78,7 @@ impl MatchHistorySource for Timelines {
let mut script = self.script.lock().unwrap();
match *script {
Script::Serve => Ok(TIMELINE.into()),
Script::Refuse => Err(SourceError::InvalidKey),
Script::Refuse => Err(SourceError::Refused),
Script::Fail(n) => {
*script = if n > 1 {
Script::Fail(n - 1)
@@ -236,6 +236,26 @@ async fn the_details_are_not_kept_from_one_match_to_another(cx: &mut TestAppCont
assert_eq!(unfolded(&page, &mut window), None);
}
#[gpui::test]
async fn opening_the_screen_centers_the_displayed_accounts_row(cx: &mut TestAppContext) {
use gpui_kit::{px, size};
let (page, mut window) = open_matches(cx).await;
switch_tab(&page, &mut window, Tab::Challenge);
let banner = window.debug_bounds("banner").unwrap().size.height;
window.simulate_resize(size(px(1280.), banner + px(380.)));
switch_tab(&page, &mut window, Tab::Matches);
recap_ready(&page, cx).await;
window.run_until_parked();
draw(&mut window);
let row = window.debug_bounds("recap-account").unwrap();
let viewport = window.debug_bounds("recap-viewport").unwrap();
assert!(
(row.center().y - viewport.center().y).abs() < px(1.),
"{row:?} in {viewport:?}"
);
}
#[gpui::test]
async fn choosing_a_match_centers_the_displayed_accounts_row(cx: &mut TestAppContext) {
use gpui_kit::{px, size};
+1 -1
View File
@@ -66,7 +66,7 @@ fn the_banner_link_and_the_back_button_work_with_the_keyboard(cx: &mut TestAppCo
let cx = &mut { cx };
let tab = |cx: &mut VisualTestContext| page.read_with(cx, |page, _| page.tab);
draw(cx);
// Tab reaches « Défi », « Parties », then the account selector, then « Statistiques › » in
// Tab reaches « Défi », « Parties », then the account selector, then « Statistiques » in
// the banner.
tab_then_enter(cx, 4);
assert_eq!(tab(cx), Tab::Statistics);
+19 -15
View File
@@ -1,6 +1,7 @@
use crate::card_grid::CardGrid;
use crate::champion_table::tests::row;
use crate::page::{Page, Tab};
use crate::worker::Msg;
use arena_tracker_core::{
Account, ChallengeSummary, Champion, ChampionChallenge, ChampionRow, ChampionSort,
ChampionState, Charts, Date, Format, GameData, MatchHistorySource, RiotApi, Season,
@@ -35,12 +36,9 @@ pub(in crate::page) fn switch_tab(page: &Entity<Page>, cx: &mut VisualTestContex
pub(super) fn open_page(cx: &mut TestAppContext) -> (Entity<Page>, VisualTestContext) {
open_page_with_tracker(
cx,
Tracker::open(
Path::new(":memory:"),
Box::new(RiotApi::new(String::new(), "europe")),
)
.unwrap()
.with_seasons(Vec::new()),
Tracker::open(Path::new(":memory:"), Box::new(RiotApi::new("", "europe")))
.unwrap()
.with_seasons(Vec::new()),
)
}
@@ -86,11 +84,11 @@ pub(super) fn open_page_launched(
};
gpui_kit::open_window(options, cx, |window, cx| {
cx.new(|cx| {
Page::new(
let status = tracker.status();
let mut page = Page::new(
tracker,
crate::page::Launch {
notice: None,
following: false,
champion_sort,
open_recap_at_match_end: true,
},
@@ -98,7 +96,16 @@ pub(super) fn open_page_launched(
tx,
window,
cx,
)
);
// The follower's first round, which changed nothing.
let round = Msg::Round {
status,
reload: false,
matches: Vec::new(),
game_end: None,
};
page.apply(round, window, cx);
page
})
})
.unwrap()
@@ -179,12 +186,9 @@ pub(super) fn season(name: &str, year: i32) -> Season {
pub(super) fn open_page_in_season(cx: &mut TestAppContext) -> (Entity<Page>, VisualTestContext) {
open_page_with_tracker(
cx,
Tracker::open(
Path::new(":memory:"),
Box::new(RiotApi::new(String::new(), "europe")),
)
.unwrap()
.with_seasons(vec![season("Saison", 2020)]),
Tracker::open(Path::new(":memory:"), Box::new(RiotApi::new("", "europe")))
.unwrap()
.with_seasons(vec![season("Saison", 2020)]),
)
}
+3 -6
View File
@@ -105,12 +105,9 @@ fn without_any_known_value_the_cards_are_a_to_z_and_the_preference_is_untouched(
#[gpui::test]
fn a_saved_sort_is_there_at_the_first_draw(cx: &mut TestAppContext) {
let tracker = Tracker::open(
Path::new(":memory:"),
Box::new(RiotApi::new(String::new(), "europe")),
)
.unwrap()
.with_seasons(vec![season("Saison", 2020)]);
let tracker = Tracker::open(Path::new(":memory:"), Box::new(RiotApi::new("", "europe")))
.unwrap()
.with_seasons(vec![season("Saison", 2020)]);
let (page, cx) = open_page_with_sort(cx, tracker, Some(ChampionSort::Name));
let cx = &mut { cx };
show(&page, cx, statistics(0, 6, rows_with_points()));
@@ -0,0 +1,72 @@
//! The « Statistiques » tiles never carry the official count (#143).
use super::page_fixtures::{draw, open_page_in_season, show, statistics, switch_tab};
use crate::page::{Page, Tab};
use crate::worker::Msg;
use arena_tracker_core::{Account, ProgressCheck, Status};
use gpui_kit::{Entity, TestAppContext, VisualTestContext};
/// The page on Alice's Challenge in the current Season, with `official` as the game's count.
fn with_official(page: &Entity<Page>, cx: &mut VisualTestContext, official: ProgressCheck) {
cx.update(|window, cx| {
page.update(cx, |page, cx| {
let status = Status {
updating: Some(Account {
puuid: "p".into(),
game_name: "Alice".into(),
tag_line: "EUW".into(),
}),
official_progress: official,
..page.status.clone()
};
page.apply(
Msg::Round {
status,
reload: false,
matches: Vec::new(),
game_end: None,
},
window,
cx,
)
})
});
}
/// The drawn height of the tile `label`, once the page is drawn again.
fn tile_height(window: &mut VisualTestContext, label: &'static str) -> f32 {
draw(window);
let bounds = window.debug_bounds(label).expect("the tile is drawn");
bounds.size.height.into()
}
#[gpui::test]
async fn the_tiles_stay_without_the_official_count(cx: &mut TestAppContext) {
cx.executor().allow_parking();
let (page, mut window) = open_page_in_season(cx);
cx.condition(&page, |p, _| !p.busy()).await;
show(&page, &mut window, statistics(52, 100, Vec::new()));
switch_tab(&page, &mut window, Tab::Statistics);
// Without the game's count, the « Champions validés » tile has its own height, measured here;
// a note under it would make it taller. The « Tentatives » tile keeps its own height whatever
// happens to the first, so those assertions only check that it is unaffected.
let plain = tile_height(&mut window, "tile-Champions validés");
assert_eq!(tile_height(&mut window, "tile-Tentatives"), plain);
// The game agrees: the tiles are as tall as without the count.
with_official(&page, &mut window, ProgressCheck::Agrees(52));
assert_eq!(tile_height(&mut window, "tile-Champions validés"), plain);
assert_eq!(tile_height(&mut window, "tile-Tentatives"), plain);
// The game differs: the tiles are still as tall as before.
with_official(
&page,
&mut window,
ProgressCheck::Differs {
app: 50,
official: 52,
},
);
assert_eq!(tile_height(&mut window, "tile-Champions validés"), plain);
assert_eq!(tile_height(&mut window, "tile-Tentatives"), plain);
}
+4
View File
@@ -1,3 +1,4 @@
use super::import_view::wait_until;
use super::{Page, RELOAD_EVERY, Tab};
use crate::worker::{Msg, spawn_refresh};
use gpui_kit::*;
@@ -6,6 +7,8 @@ impl Page {
pub(in crate::page) fn apply(&mut self, msg: Msg, window: &mut Window, cx: &mut Context<Self>) {
match msg {
Msg::Progress(progress) => {
let now = cx.background_executor().now();
self.import_view.own_until = wait_until(progress, now);
self.progress = Some(progress);
if self.last_reload.elapsed() >= RELOAD_EVERY {
self.reload_in_background(window, cx);
@@ -148,6 +151,7 @@ impl Page {
self.mark_crashed();
}
}
self.show_import(false, cx);
cx.notify();
}
+2 -2
View File
@@ -16,7 +16,7 @@ pub fn start(cx: &mut App) {
let mut file = match csv_file(Path::new(&path)) {
Ok(file) => file,
Err(error) => {
eprintln!("Could not open profile CSV: {error}");
log::error!("Could not open profile CSV: {error}");
return;
}
};
@@ -87,7 +87,7 @@ pub fn start(cx: &mut App) {
if let Err(error) = result
&& !write_failed
{
eprintln!("Could not write profile CSV: {error}");
log::error!("Could not write profile CSV: {error}");
write_failed = true;
}
}
+1
View File
@@ -47,6 +47,7 @@ pub fn handle_command() {
Some("--verify-release") => {
let ok = args.next().is_some_and(|dir| {
verify_release(Path::new(&dir))
// The publishing script reads this from the terminal: not a log line.
.inspect_err(|err| eprintln!("{err}"))
.is_ok()
});
+32 -1
View File
@@ -4,7 +4,7 @@
//! two by Mastery Points (A to Z while the points are unknown, as the cards).
//!
//! A cached view (rule #1): laid out from the style its parent gives, drawn again only when its
//! ticks or the lit one change, never by a hover or a scroll elsewhere.
//! ticks, the lit one or the import's arc change, never by a hover or a scroll elsewhere.
use std::cell::RefCell;
use std::f32::consts::{FRAC_PI_2, TAU};
@@ -18,6 +18,7 @@ use crate::motion::{MATCH_SETTLE, MatchAnimation, MatchEnd, ease_out};
use crate::theme::{ring_never, ring_played};
mod aim;
mod arc;
mod ticks;
pub use ticks::{Tick, ticks};
@@ -185,8 +186,12 @@ pub struct Ring {
ticks: Rc<[Tick]>,
/// The champion whose card is under the pointer.
lit: Option<u32>,
/// The import of the Account shown, as (fetched, to fetch): its arc is drawn around the ticks.
progress: Option<(usize, usize)>,
/// Made by the paint, for its size; forgotten with the ticks.
geometry: Rc<RefCell<Option<Geometry>>>,
/// The arc's paths, made by the paint for its size and progress.
arc: Rc<RefCell<arc::Cache>>,
/// How many times it was drawn: the tests check it stays light.
#[cfg(test)]
pub(crate) renders: usize,
@@ -201,7 +206,9 @@ impl Ring {
ticks: Rc::new([]),
anvil: None,
lit: None,
progress: None,
geometry: Rc::default(),
arc: Rc::default(),
#[cfg(test)]
renders: 0,
#[cfg(test)]
@@ -255,6 +262,14 @@ impl Ring {
}
}
/// Shows the import's arc, or none; the ring is drawn again only when it changes.
pub fn set_progress(&mut self, progress: Option<(usize, usize)>, cx: &mut Context<Self>) {
if self.progress != progress {
self.progress = progress;
cx.notify();
}
}
#[cfg(test)]
pub(crate) fn ticks(&self) -> &[Tick] {
&self.ticks
@@ -265,6 +280,11 @@ impl Ring {
self.anvil.as_deref()
}
#[cfg(test)]
pub(crate) fn progress(&self) -> Option<(usize, usize)> {
self.progress
}
pub(crate) fn lit(&self) -> Option<u32> {
self.lit
}
@@ -401,8 +421,10 @@ impl Render for Ring {
]
.map(|state| (state, color(state)));
let (disc, crown, lit_color) = (theme.background, theme.primary, theme.foreground);
let (progress, rest) = (self.progress, ring_never(theme));
let ticks = self.ticks.clone();
let geometry = self.geometry.clone();
let arcs = self.arc.clone();
let anvil = self.anvil.clone();
#[cfg(test)]
let tessellations = self.tessellations.clone();
@@ -439,6 +461,15 @@ impl Render for Ring {
if let Some(path) = &geometry.crown {
window.paint_path(moved(path, bounds.origin), crown);
}
let mut arcs = arcs.borrow_mut();
if !arcs.fits(bounds.size, progress) {
#[cfg(test)]
if progress.is_some() {
tessellations.set(tessellations.get() + 1);
}
arcs.remake(bounds.size, progress);
}
arcs.paint(bounds.origin, (rest, crown), window);
// Only the lit tick is tessellated when the pointer changes card.
if let Some((index, state)) = lit {
let mut path = PathBuilder::fill();
+141
View File
@@ -0,0 +1,141 @@
//! The import's arc (#140): a thin circle outside the ticks, its done part from noon clockwise.
//! Pure geometry, in the ring's SVG units.
use std::f32::consts::TAU;
use gpui_kit::*;
use super::{C, Frame, moved};
/// Just outside the ticks, which end at `R2`.
const RADIUS: f32 = 256.;
const WIDTH: f32 = 3.;
/// Segments of a full turn.
const STEPS: f32 = 120.;
/// How much of the import is done, from 0 to 1.
pub(super) fn fraction(fetched: usize, to_fetch: usize) -> f32 {
if to_fetch == 0 {
return 0.;
}
(fetched as f32 / to_fetch as f32).clamp(0., 1.)
}
/// The polyline of the first `fraction` of the turn: from noon, clockwise. Empty for nothing.
pub(super) fn points(fraction: f32) -> Vec<(f32, f32)> {
let sweep = fraction.clamp(0., 1.) * TAU;
if sweep == 0. {
return Vec::new();
}
let steps = (sweep / TAU * STEPS).ceil();
(0..=steps as usize)
.map(|i| {
let angle = sweep * i as f32 / steps;
(C + RADIUS * angle.sin(), C - RADIUS * angle.cos())
})
.collect()
}
/// The arc's paths, made at the origin and moved where the ring is painted: the circle for a
/// size, the part done for a progress, so a paint for the same ones tessellates nothing.
#[derive(Default)]
pub(super) struct Cache {
size: Size<Pixels>,
progress: Option<(usize, usize)>,
rest: Option<Path<Pixels>>,
done: Option<Path<Pixels>>,
}
/// The polyline of the first `fraction` of the turn, stroked in `frame`.
fn stroke(frame: Frame, fraction: f32) -> Option<Path<Pixels>> {
let mut points = points(fraction).into_iter().map(|(x, y)| frame.point(x, y));
let mut stroke = PathBuilder::stroke(px(WIDTH * frame.scale));
stroke.move_to(points.next()?);
for at in points {
stroke.line_to(at);
}
stroke.build().ok()
}
impl Cache {
/// Whether what is held is what `progress` in `size` needs.
pub(super) fn fits(&self, size: Size<Pixels>, progress: Option<(usize, usize)>) -> bool {
self.progress == progress && (progress.is_none() || self.size == size)
}
/// Makes the paths for `progress` in `size`, or lets go of them without progress.
pub(super) fn remake(&mut self, size: Size<Pixels>, progress: Option<(usize, usize)>) {
let Some((fetched, to_fetch)) = progress else {
*self = Cache::default();
return;
};
let frame = Frame::of(Bounds {
origin: Point::default(),
size,
});
if self.size != size || self.rest.is_none() {
self.rest = stroke(frame, 1.);
}
self.done = stroke(frame, fraction(fetched, to_fetch));
(self.size, self.progress) = (size, progress);
}
/// Paints the whole circle in `rest`, then the part done in `done`.
pub(super) fn paint(
&self,
origin: Point<Pixels>,
(rest, done): (Hsla, Hsla),
window: &mut Window,
) {
for (path, color) in [(&self.rest, rest), (&self.done, done)] {
if let Some(path) = path {
window.paint_path(moved(path, origin), color);
}
}
}
}
#[cfg(test)]
mod tests {
use super::{C, RADIUS, WIDTH, fraction, points};
use crate::ring::{R2, shape};
use arena_tracker_core::ChampionState;
fn near(a: (f32, f32), b: (f32, f32)) -> bool {
(a.0 - b.0).abs() < 0.01 && (a.1 - b.1).abs() < 0.01
}
#[test]
fn the_arc_starts_at_noon_and_turns_clockwise() {
let quarter = points(0.25);
assert!(near(quarter[0], (C, C - RADIUS)));
assert!(near(*quarter.last().unwrap(), (C + RADIUS, C)));
assert!(near(*points(0.5).last().unwrap(), (C, C + RADIUS)));
// A full turn closes on noon.
let circle = points(1.);
assert!(near(circle[0], *circle.last().unwrap()));
}
#[test]
fn nothing_done_draws_no_arc_and_the_fraction_is_clamped() {
assert!(points(0.).is_empty() && points(-1.).is_empty());
assert_eq!(points(7.), points(1.));
assert_eq!(fraction(0, 12), 0.);
assert_eq!(fraction(3, 12), 0.25);
assert_eq!(fraction(20, 12), 1.);
assert_eq!(fraction(5, 0), 0.);
}
#[test]
fn the_arc_lies_just_outside_the_ticks() {
let outermost = [
ChampionState::Completed,
ChampionState::InProgress,
ChampionState::NeverPlayed,
]
.map(|state| shape(state).1)
.into_iter()
.fold(R2, f32::max);
assert!(RADIUS - WIDTH / 2. > outermost);
}
}
+63 -141
View File
@@ -1,12 +1,11 @@
//! The first-launch Riot API key prompt and the settings view.
//! The settings view, « Paramètres ».
use std::rc::Rc;
use std::sync::Arc;
use arena_tracker_core::{ChampionSort, Preferences, Tracker, UpdateChannel};
use gpui_kit::base::async_util::{Sender, unbounded};
use gpui_kit::component::button::{Button, ButtonVariants as _};
use gpui_kit::component::input::{Input, InputEvent, InputState};
use gpui_kit::component::button::Button;
use gpui_kit::component::{ActiveTheme as _, StyledExt as _};
use gpui_kit::*;
@@ -15,8 +14,6 @@ use crate::release::{self, channel};
use crate::tray::{Tray, UNAVAILABLE};
use crate::worker::{RefreshGate, UpdateChecked, spawn_update_check};
const PLACEHOLDER_SAVED: &str = "Clé enregistrée";
const PLACEHOLDER_EMPTY: &str = "Clé API Riot";
const STABLE_AFTER_BETA: &str =
"La bêta installée reste en place jusqu’à une version stable plus récente.";
const LOGON_ERROR: &str = "Impossible de modifier le lancement à l’ouverture de session.";
@@ -27,12 +24,12 @@ pub use appearance::apply_theme;
#[cfg(test)]
use appearance::theme_mode;
mod logs;
mod preferences;
mod store;
pub use store::KeyStore;
pub use store::SettingsStore;
pub enum KeyEvent {
Saved,
pub enum SettingsEvent {
Back,
/// An update became ready or stopped being ready: the title bar shows it.
UpdateReady,
@@ -42,16 +39,14 @@ pub enum KeyEvent {
AccountDeleted(String),
}
pub struct KeyForm {
store: KeyStore,
input: Entity<InputState>,
/// The first-launch prompt (no key and nothing stored yet) has no way back.
first_launch: bool,
error: Option<String>,
pub struct SettingsForm {
store: SettingsStore,
preference_error: Option<SharedString>,
accounts: accounts::Accounts,
tray: Option<Rc<Tray>>,
logon_launch: LogonLaunch,
/// How a folder is opened: in the Windows Explorer.
open_folder: fn(&std::path::Path) -> std::io::Result<()>,
/// What Windows said when the settings were last shown or changed: it holds the choice.
/// Read only then, not at launch: the settings always open through `read_logon_launch`.
launches_at_logon: bool,
@@ -65,22 +60,17 @@ pub struct KeyForm {
/// One update check at a time: at launch, on a channel change and on « Rechercher une mise à jour ».
update_checks: RefreshGate,
updates: Sender<UpdateChecked>,
_subscriptions: [Subscription; 2],
_appearance: Subscription,
_notice_listener: Task<()>,
_update_listener: Task<()>,
}
impl EventEmitter<KeyEvent> for KeyForm {}
impl KeyForm {
pub fn has_key(&self) -> bool {
self.store.has_key()
}
impl EventEmitter<SettingsEvent> for SettingsForm {}
impl SettingsForm {
pub fn new(
store: KeyStore,
store: SettingsStore,
tracker: Arc<Tracker>,
first_launch: bool,
window: &mut Window,
cx: &mut Context<Self>,
) -> Self {
@@ -113,39 +103,21 @@ impl KeyForm {
let appearance = cx.observe_window_appearance(window, |this, window, cx| {
apply_theme(this.store.preferences().theme, window, cx);
});
let placeholder = if store.has_key() {
PLACEHOLDER_SAVED
} else {
PLACEHOLDER_EMPTY
};
let input = cx.new(|cx| {
InputState::new(window, cx)
.masked(true)
.placeholder(placeholder)
});
let subscription =
cx.subscribe_in(&input, window, |this, _, event: &InputEvent, window, cx| {
if matches!(event, InputEvent::PressEnter { .. }) {
this.save(window, cx);
}
});
let logon_launch = LogonLaunch::installed();
let mut form = KeyForm {
first_launch,
let mut form = SettingsForm {
store,
input,
error: None,
preference_error: None,
accounts: accounts::Accounts::new(tracker),
tray,
launches_at_logon: false,
logon_launch,
open_folder: logs::explorer,
notice_shown,
ready: None,
check_outcome: None,
update_checks: RefreshGate::default(),
updates,
_subscriptions: [subscription, appearance],
_appearance: appearance,
_notice_listener: notice_listener,
_update_listener: update_listener,
};
@@ -230,7 +202,7 @@ impl KeyForm {
fn set_ready(&mut self, ready: Option<SharedString>, cx: &mut Context<Self>) {
if self.ready != ready {
self.ready = ready;
cx.emit(KeyEvent::UpdateReady);
cx.emit(SettingsEvent::UpdateReady);
cx.notify();
}
}
@@ -242,13 +214,11 @@ impl KeyForm {
(self.ready.clone()).or_else(|| (beta && stable).then_some(STABLE_AFTER_BETA.into()))
}
/// Back to an empty field, as when the form is opened again.
pub fn reset(&mut self, window: &mut Window, cx: &mut Context<Self>) {
self.error = None;
/// As when the form is opened again.
pub fn reset(&mut self, cx: &mut Context<Self>) {
self.preference_error = None;
self.check_outcome = None;
self.accounts.reset();
self.clear(window, cx);
cx.notify();
}
@@ -281,7 +251,7 @@ impl KeyForm {
self.check_outcome = None;
self.check_updates();
}
cx.emit(KeyEvent::Preferences(preferences));
cx.emit(SettingsEvent::Preferences(preferences));
None
};
if !self.store.preferences().close_to_tray
@@ -349,100 +319,52 @@ impl KeyForm {
}
}
}
fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let placeholder = if self.store.has_key() {
PLACEHOLDER_SAVED
} else {
PLACEHOLDER_EMPTY
};
self.input.update(cx, |input, cx| {
input.set_value("", window, cx);
input.set_placeholder(placeholder, window, cx);
});
}
fn save(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let key = self.input.read(cx).value();
let key = key.trim();
if key.is_empty() {
self.error = Some("Saisissez une clé API.".into());
} else {
match self.store.save(key) {
Ok(()) => {
self.error = None;
self.first_launch = false;
self.clear(window, cx);
cx.emit(KeyEvent::Saved);
}
Err(e) => self.error = Some(format!("Enregistrement impossible : {e}")),
}
}
cx.notify();
}
}
impl Render for KeyForm {
impl Render for SettingsForm {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let (title, explanation) = if self.first_launch {
(
"Clé API Riot",
"Une clé API Riot est nécessaire pour importer vos Parties : demandez-en une sur le portail développeur Riot (developer.riotgames.com). Elle reste enregistrée sur cet ordinateur.",
)
} else {
(
"Paramètres",
"Saisissez une nouvelle clé API Riot pour remplacer celle qui est enregistrée. Elle reste enregistrée sur cet ordinateur.",
)
};
let (muted, danger) = (cx.theme().muted_foreground, cx.theme().danger);
let buttons = div()
.h_flex()
.gap_2()
.child(
Button::new("save")
.primary()
.label(if self.first_launch {
"Enregistrer"
} else {
"Enregistrer la clé"
})
.on_click(cx.listener(|this, _, window, cx| this.save(window, cx))),
)
.children((!self.first_launch).then(|| {
Button::new("back")
.label("Retour")
.on_click(cx.listener(|_, _, _, cx| cx.emit(KeyEvent::Back)))
}));
div()
.size_full()
.flex()
.items_center()
.justify_center()
.child(
div()
.v_flex()
.w(px(520.))
.max_w_full()
.px_4()
.gap_3()
.child(
div()
.text_xl()
.font_weight(FontWeight::SEMIBOLD)
.child(title),
)
.children((!self.first_launch).then(|| self.preferences(cx)))
.children((!self.first_launch).then(|| self.accounts_section(cx)))
.child(div().text_color(muted).child(explanation))
.child(Input::new(&self.input).mask_toggle())
.children(
self.error
.clone()
.map(|error| div().text_color(danger).child(error)),
)
.child(buttons),
)
let muted = cx.theme().muted_foreground;
// Scrolls at the window's minimum height; the wrapper is at least as tall as the window and
// centres the column while it fits (an auto margin would also push the top out of reach).
div().id("settings").size_full().overflow_y_scroll().child(
div()
.min_h_full()
.flex()
.justify_center()
.items_center()
.child(
div()
.v_flex()
.w(px(520.))
.max_w_full()
.px_4()
.gap_3()
.child(
div()
.text_xl()
.font_weight(FontWeight::SEMIBOLD)
.debug_selector(|| "settings-title".into())
.child("Paramètres"),
)
.child(self.preferences(cx))
.child(self.accounts_section(cx))
.child(
div().h_flex().child(
Button::new("back").label("Retour").on_click(
cx.listener(|_, _, _, cx| cx.emit(SettingsEvent::Back)),
),
),
)
.child(
div()
.id("riot-notice")
.text_xs()
.text_color(muted)
.debug_selector(|| "riot-notice".into())
.child(crate::text::RIOT_NOTICE),
),
),
)
}
}
+3 -3
View File
@@ -8,7 +8,7 @@ use gpui_kit::component::button::{Button, ButtonVariants as _};
use gpui_kit::component::{ActiveTheme as _, Disableable as _, StyledExt as _};
use gpui_kit::*;
use super::{KeyEvent, KeyForm};
use super::{SettingsEvent, SettingsForm};
const CONNECTED: &str = "Compte connecté au client";
const CLIENT_ONLY: &str = "Les détails venus du client League ne pourront pas être récupérés.";
@@ -97,7 +97,7 @@ impl Accounts {
}
}
impl KeyForm {
impl SettingsForm {
/// « Supprimer » on a row: reads what the deletion would lose, then asks.
fn ask_deletion(&mut self, account: Account, cx: &mut Context<Self>) {
let accounts = &mut self.accounts;
@@ -167,7 +167,7 @@ impl KeyForm {
form.accounts.deleting = false;
form.accounts.read();
match deleted {
Ok(()) => cx.emit(KeyEvent::AccountDeleted(account.puuid)),
Ok(()) => cx.emit(SettingsEvent::AccountDeleted(account.puuid)),
Err(e) => form.accounts.error = Some(format!("{DELETE_ERROR}{e}").into()),
}
cx.notify();
@@ -6,8 +6,8 @@ use crate::page::tests::client_fixtures::FakeClient;
use crate::page::tests::matches_fixtures::TwoAccounts;
use crate::page::tests::matches_provisional::{LEFT_AT_MS, block, tracker_before_block};
use crate::page::tests::page_fixtures::MATCH_1750;
use crate::settings::{KeyEvent, KeyForm, KeyStore};
use arena_tracker_core::{Account, Config, MatchHistorySource, RiotApi, SourceError, Tracker};
use crate::settings::{SettingsEvent, SettingsForm, SettingsStore};
use arena_tracker_core::{Account, Config, MatchHistorySource, SourceError, Tracker};
use gpui_kit::{AppContext as _, Entity, TestAppContext, VisualTestContext, WindowOptions};
use std::cell::RefCell;
use std::rc::Rc;
@@ -74,23 +74,26 @@ fn with_a_friend() -> (Tracker, FakeClient) {
fn open_settings(
cx: &mut TestAppContext,
tracker: Arc<Tracker>,
) -> (Entity<KeyForm>, VisualTestContext, Rc<RefCell<Vec<String>>>) {
) -> (
Entity<SettingsForm>,
VisualTestContext,
Rc<RefCell<Vec<String>>>,
) {
cx.executor().allow_parking();
cx.update(gpui_kit::init);
let deleted = Rc::new(RefCell::new(Vec::new()));
let (window, form) = cx.update(|cx| {
let config = Config::load_or_default(std::path::Path::new(":memory:")).unwrap();
let api = Arc::new(RiotApi::new(String::new(), &config.region));
let store = KeyStore::new("unused.toml".into(), config, api);
let store = SettingsStore::new("unused.toml".into(), config);
gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| {
cx.new(|cx| KeyForm::new(store, tracker, false, window, cx))
cx.new(|cx| SettingsForm::new(store, tracker, window, cx))
})
.unwrap()
});
let log = deleted.clone();
cx.update(|cx| {
cx.subscribe(&form, move |_, event: &KeyEvent, _| {
if let KeyEvent::AccountDeleted(puuid) = event {
cx.subscribe(&form, move |_, event: &SettingsEvent, _| {
if let SettingsEvent::AccountDeleted(puuid) = event {
log.borrow_mut().push(puuid.clone());
}
})
@@ -117,7 +120,7 @@ fn names(accounts: &[super::AccountRow]) -> Vec<&str> {
}
async fn ask(
form: &Entity<KeyForm>,
form: &Entity<SettingsForm>,
cx: &mut TestAppContext,
window: &mut VisualTestContext,
puuid: &str,
+48
View File
@@ -0,0 +1,48 @@
//! « Ouvrir le dossier des journaux »: the folder of the application log (#142).
use std::io;
use std::path::{Path, PathBuf};
use std::process::Command;
use gpui_kit::component::StyledExt as _;
use gpui_kit::component::button::Button;
use gpui_kit::*;
use super::SettingsForm;
pub(super) const LOGS_ERROR: &str = "Impossible d’ouvrir le dossier des journaux.";
/// Opens the folder in Windows' file explorer. Not waited for: explorer.exe answers with an
/// exit code that does not tell whether it worked.
pub(super) fn explorer(dir: &Path) -> io::Result<()> {
Command::new("explorer").arg(dir).spawn().map(drop)
}
impl SettingsForm {
pub(super) fn logs_section(&self, cx: &mut Context<Self>) -> impl IntoElement {
div().h_flex().child(
Button::new("open-logs")
.debug_selector(|| "open-logs".into())
.label("Ouvrir le dossier des journaux")
.on_click(cx.listener(|this, _, _, cx| this.open_logs(cx))),
)
}
/// The folder is made first: the log may have failed to open it.
pub(super) fn open_logs(&mut self, cx: &mut Context<Self>) {
let opened = (self.store.logs_dir())
.ok_or_else(|| io::Error::other("no data folder"))
.and_then(|dir: PathBuf| {
std::fs::create_dir_all(&dir)?;
(self.open_folder)(&dir)
});
if let Err(error) = &opened {
log::warn!("Cannot open the logs folder: {error}");
}
if opened.is_err() {
self.preference_error = Some(LOGS_ERROR.into());
} else if self.preference_error.as_deref() == Some(LOGS_ERROR) {
self.preference_error = None;
}
cx.notify();
}
}
+5 -4
View File
@@ -5,7 +5,7 @@ use gpui_kit::component::switch::Switch;
use gpui_kit::component::{ActiveTheme as _, Disableable as _, StyledExt as _};
use gpui_kit::*;
use super::KeyForm;
use super::SettingsForm;
use crate::release::{self, channel};
const THEMES: [(ThemePreference, &str); 3] = [
@@ -19,12 +19,12 @@ const CHANNELS: [(UpdateChannel, &str); 2] = [
];
const LOGON_LABEL: &str = "Lancer à l’ouverture de session Windows";
const RECAP_LABEL: &str = "Ouvrir le récapitulatif en fin de Partie";
const RECAP_HINT: &str = "À la fin d’une Partie Arena, « Parties » l’affiche, sans mettre la fenêtre \
au premier plan. Désactivé, le Défi reste affiché.";
const RECAP_HINT: &str = "À la fin d’une Partie Arena, « Parties » l’affiche et la fenêtre passe \
au premier plan. Désactivé, le Défi s’affiche.";
// Not « Disponible »: the interface word of a Pickable champion (CONTEXT.md).
const LOGON_UNAVAILABLE: &str = "Réservé à la version installée.";
impl KeyForm {
impl SettingsForm {
pub(super) fn preferences(&self, cx: &mut Context<Self>) -> impl IntoElement {
let preferences = self.store.preferences();
let (muted, danger) = (cx.theme().muted_foreground, cx.theme().danger);
@@ -153,6 +153,7 @@ impl KeyForm {
)
})),
)
.child(self.logs_section(cx))
.children(
(self.preference_error.clone()).map(|error| div().text_color(danger).child(error)),
)
+9 -21
View File
@@ -1,22 +1,21 @@
use std::path::PathBuf;
use std::sync::Arc;
use arena_tracker_core::{Config, Error, Preferences, RiotApi};
use arena_tracker_core::{Config, Error, Preferences};
/// The local config file and the running Riot client that uses its key.
pub struct KeyStore {
/// The local config file.
pub struct SettingsStore {
path: PathBuf,
config: Config,
api: Arc<RiotApi>,
}
impl KeyStore {
pub fn new(path: PathBuf, config: Config, api: Arc<RiotApi>) -> KeyStore {
KeyStore { path, config, api }
impl SettingsStore {
pub fn new(path: PathBuf, config: Config) -> SettingsStore {
SettingsStore { path, config }
}
pub fn has_key(&self) -> bool {
!self.config.riot_api_key.is_empty()
/// The application log's folder, beside the configuration file.
pub(super) fn logs_dir(&self) -> Option<PathBuf> {
Some(self.path.parent()?.join("logs"))
}
pub fn preferences(&self) -> Preferences {
@@ -27,17 +26,6 @@ impl KeyStore {
self.config.tray_notice_shown
}
/// Writes the key to the config file and hands it to the Riot client, no restart needed.
pub(super) fn save(&mut self, key: &str) -> Result<(), Error> {
let previous = std::mem::replace(&mut self.config.riot_api_key, key.to_string());
if let Err(e) = self.config.save(&self.path) {
self.config.riot_api_key = previous;
return Err(e);
}
self.api.set_key(key.to_string());
Ok(())
}
/// A failed write only means the notice is shown again at the next launch.
pub(super) fn record_tray_notice(&mut self) {
self.config.tray_notice_shown = true;
+112 -17
View File
@@ -2,15 +2,19 @@ use std::sync::Arc;
use arena_tracker_core::{Config, Preferences, RiotApi, ThemePreference, Tracker, UpdateChannel};
use gpui_kit::component::ThemeMode;
use gpui_kit::{AppContext as _, TestAppContext, VisualTestContext, WindowOptions};
use gpui_kit::{
AppContext as _, ScrollDelta, ScrollEvent, TestAppContext, VisualTestContext, WindowOptions,
point, px,
};
use super::{KeyForm, KeyStore, theme_mode};
use super::{SettingsForm, SettingsStore, theme_mode};
use crate::logon::tests::Scratch;
use crate::title_bar::MIN_WINDOW_SIZE;
use crate::worker::UpdateChecked;
/// The settings' Accounts: none stored.
fn tracker() -> Arc<Tracker> {
let api = RiotApi::new(String::new(), "europe");
let api = RiotApi::new("", "europe");
Arc::new(Tracker::open(std::path::Path::new(":memory:"), Box::new(api)).unwrap())
}
@@ -22,10 +26,9 @@ fn the_chosen_channel_is_saved_and_only_its_check_offers_a_restart(cx: &mut Test
let _ = std::fs::remove_dir_all(&dir);
let (window, form) = cx.update(|cx| {
let config = Config::load_or_default(&path).unwrap();
let api = Arc::new(RiotApi::new(String::new(), &config.region));
let store = KeyStore::new(path.clone(), config, api);
let store = SettingsStore::new(path.clone(), config);
gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| {
cx.new(|cx| KeyForm::new(store, tracker(), false, window, cx))
cx.new(|cx| SettingsForm::new(store, tracker(), window, cx))
})
.unwrap()
});
@@ -100,10 +103,9 @@ fn the_last_check_is_told_until_the_settings_are_shown_again(cx: &mut TestAppCon
cx.update(gpui_kit::init);
let (window, form) = cx.update(|cx| {
let config = Config::load_or_default(std::path::Path::new(":memory:")).unwrap();
let api = Arc::new(RiotApi::new(String::new(), &config.region));
let store = KeyStore::new("unused.toml".into(), config, api);
let store = SettingsStore::new("unused.toml".into(), config);
gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| {
cx.new(|cx| KeyForm::new(store, tracker(), false, window, cx))
cx.new(|cx| SettingsForm::new(store, tracker(), window, cx))
})
.unwrap()
});
@@ -145,11 +147,9 @@ fn the_last_check_is_told_until_the_settings_are_shown_again(cx: &mut TestAppCon
Some("Vous avez la dernière version")
);
});
cx.update(|window, cx| {
form.update(cx, |form, cx| {
form.reset(window, cx);
assert_eq!(form.check_status(), None);
})
form.update(cx, |form, cx| {
form.reset(cx);
assert_eq!(form.check_status(), None);
});
}
@@ -158,10 +158,9 @@ fn the_logon_switch_shows_what_windows_holds(cx: &mut TestAppContext) {
cx.update(gpui_kit::init);
let (window, form) = cx.update(|cx| {
let config = Config::load_or_default(std::path::Path::new(":memory:")).unwrap();
let api = Arc::new(RiotApi::new(String::new(), &config.region));
let store = KeyStore::new("unused.toml".into(), config, api);
let store = SettingsStore::new("unused.toml".into(), config);
gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| {
cx.new(|cx| KeyForm::new(store, tracker(), false, window, cx))
cx.new(|cx| SettingsForm::new(store, tracker(), window, cx))
})
.unwrap()
});
@@ -202,6 +201,38 @@ fn the_logon_switch_shows_what_windows_holds(cx: &mut TestAppContext) {
cx.update(|window, cx| window.draw(cx).clear(cx));
}
#[gpui::test]
fn the_riot_notice_is_drawn_inside_the_window_at_its_minimum_size(cx: &mut TestAppContext) {
cx.update(gpui_kit::init);
let (window, _form) = cx.update(|cx| {
let config = Config::load_or_default(std::path::Path::new(":memory:")).unwrap();
let store = SettingsStore::new("unused.toml".into(), config);
gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| {
cx.new(|cx| SettingsForm::new(store, tracker(), window, cx))
})
.unwrap()
});
let cx = &mut VisualTestContext::from_window(window, cx);
cx.simulate_resize(MIN_WINDOW_SIZE);
cx.update(|window, cx| window.draw(cx).clear(cx));
// Debug bounds are recorded even for clipped elements: the title must start on screen, and
// after scrolling down the notice must end on screen.
let title = cx
.debug_bounds("settings-title")
.expect("the title is drawn");
assert!(title.top() >= px(0.), "{title:?}");
cx.simulate_event(ScrollEvent {
position: point(px(100.), px(100.)),
delta: ScrollDelta::Pixels(point(px(0.), px(-2000.))),
..Default::default()
});
cx.update(|window, cx| window.draw(cx).clear(cx));
let notice = cx.debug_bounds("riot-notice").expect("the notice is drawn");
assert!(notice.right() <= MIN_WINDOW_SIZE.width, "{notice:?}");
assert!(notice.top() >= px(0.), "{notice:?}");
assert!(notice.bottom() <= MIN_WINDOW_SIZE.height, "{notice:?}");
}
#[test]
fn system_tracks_the_current_appearance_and_manual_choices_override_it() {
for system in [ThemeMode::Light, ThemeMode::Dark] {
@@ -210,3 +241,67 @@ fn system_tracks_the_current_appearance_and_manual_choices_override_it() {
assert_eq!(theme_mode(ThemePreference::Dark, system), ThemeMode::Dark);
}
}
static OPENED: std::sync::Mutex<Vec<std::path::PathBuf>> = std::sync::Mutex::new(Vec::new());
#[gpui::test]
fn the_logs_button_opens_the_logs_folder_beside_the_configuration(cx: &mut TestAppContext) {
cx.update(gpui_kit::init);
let dir = std::env::temp_dir().join(format!("arena-logs-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let (window, form) = cx.update(|cx| {
let config = Config::load_or_default(std::path::Path::new(":memory:")).unwrap();
let store = SettingsStore::new(dir.join("config.toml"), config);
gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| {
cx.new(|cx| SettingsForm::new(store, tracker(), window, cx))
})
.unwrap()
});
let cx = &mut VisualTestContext::from_window(window, cx);
form.update(cx, |form, _| {
form.open_folder = |dir| {
OPENED.lock().unwrap().push(dir.to_path_buf());
Ok(())
};
});
cx.update(|window, cx| window.draw(cx).clear(cx));
let button = cx.debug_bounds("open-logs").unwrap().center();
cx.simulate_click(button, gpui_kit::Modifiers::none());
assert_eq!(*OPENED.lock().unwrap(), [dir.join("logs")]);
assert!(dir.join("logs").is_dir());
form.update(cx, |form, _| {
assert_eq!(form.preference_error, None);
// An unrelated error is not wiped by opening the folder.
form.preference_error = Some("autre erreur".into());
});
cx.update(|window, cx| window.draw(cx).clear(cx));
let button = cx.debug_bounds("open-logs").unwrap().center();
cx.simulate_click(button, gpui_kit::Modifiers::none());
form.update(cx, |form, _| {
assert_eq!(form.preference_error.as_deref(), Some("autre erreur"));
form.preference_error = None;
});
assert_eq!(OPENED.lock().unwrap().len(), 2);
cx.update(|window, cx| window.draw(cx).clear(cx));
let button = cx.debug_bounds("open-logs").unwrap().center();
// The explorer cannot be started: the settings say so.
form.update(cx, |form, _| {
form.open_folder = |_| Err(std::io::Error::other("refused"));
});
cx.simulate_click(button, gpui_kit::Modifiers::none());
form.update(cx, |form, _| {
assert_eq!(
form.preference_error.as_deref(),
Some(super::logs::LOGS_ERROR)
);
form.open_folder = |_| Ok(());
});
cx.update(|window, cx| window.draw(cx).clear(cx));
let button = cx.debug_bounds("open-logs").unwrap().center();
// Its own error goes away once the folder opens.
cx.simulate_click(button, gpui_kit::Modifiers::none());
form.update(cx, |form, _| assert_eq!(form.preference_error, None));
let _ = std::fs::remove_dir_all(&dir);
}
+5 -8
View File
@@ -69,11 +69,8 @@ fn marked(hwnd: HWND) -> bool {
}
/// `None` means exit without starting: the launch was relayed, or another instance is alive.
pub fn launch() -> Option<Primary> {
claim(STARTING, INSTANCE, relay).unwrap_or_else(|error| {
eprintln!("Failed to check for a running instance: {error}");
None
})
pub fn launch() -> Result<Option<Primary>> {
claim(STARTING, INSTANCE, relay)
}
fn claim(
@@ -144,16 +141,16 @@ fn relay() -> Result<Option<OwnedHandle>> {
pub fn accept_relaunches(window: &Window) {
let Some(hwnd) = crate::tray::window_hwnd(window) else {
eprintln!("Failed to get the window handle for relaunches");
log::error!("Failed to get the window handle for relaunches");
return;
};
unsafe {
if !SetWindowSubclass(hwnd, Some(window_proc), REOPEN_SUBCLASS, 0).as_bool() {
eprintln!("Failed to install the window reopen handler");
log::error!("Failed to install the window reopen handler");
return;
}
if let Err(error) = SetPropW(hwnd, WINDOW_MARKER, Some(MARKED)) {
eprintln!("Failed to publish the window: {error}");
log::error!("Failed to publish the window: {error}");
}
}
}
+43 -72
View File
@@ -4,27 +4,33 @@ use std::sync::Arc;
use arena_tracker_core::{ChampionSort, Config, Preferences, RiotApi, Tracker, UpdateChannel};
use gpui_kit::{
AppContext as _, Entity, KeyDownEvent, KeyUpEvent, Keystroke, Modifiers, TestAppContext,
VisualTestContext, WindowOptions, WindowVisibility, point,
VisualTestContext, WindowOptions, point,
};
use super::{KeyStore, LiveMatchStarted, RecapOpened, RootView, Screen, Setup};
use super::{LiveMatchStarted, MatchEndShown, RootView, Screen, SettingsStore, Setup};
use crate::card_images::tests::TestDir;
use crate::title_bar::{BAR_HEIGHT, BUTTON_WIDTH};
use crate::worker::UpdateChecked;
/// A first launch: no key and nothing stored.
fn first_launch(cx: &mut TestAppContext) -> (VisualTestContext, Entity<RootView>) {
/// The app opened on the config file at `path` (the file is read, or missing).
fn open_app(
cx: &mut TestAppContext,
path: &Path,
load: fn(&Path) -> Result<Config, arena_tracker_core::Error>,
) -> (VisualTestContext, Entity<RootView>) {
// The app starts the follower, whose threads report to the page.
cx.executor().allow_parking();
cx.update(gpui_kit::init);
let (window, root) = cx.update(|cx| {
let config = Config::load_or_default(Path::new(":memory:")).unwrap();
let api = Arc::new(RiotApi::new(String::new(), &config.region));
let config = load(path).unwrap();
let api = RiotApi::new("", &config.region);
let setup = Setup {
tracker: Arc::new(Tracker::open(Path::new(":memory:"), Box::new(api.clone())).unwrap()),
tracker: Arc::new(Tracker::open(Path::new(":memory:"), Box::new(api)).unwrap()),
// No cache read on a thread of its own: the test scheduler only allows its own.
game_data: None,
riot_id: String::new(),
notice: None,
store: KeyStore::new("unused.toml".into(), config, api),
store: SettingsStore::new(path.to_path_buf(), config),
};
gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| {
cx.new(|cx| RootView::new(setup, false, window, cx))
@@ -34,14 +40,17 @@ fn first_launch(cx: &mut TestAppContext) -> (VisualTestContext, Entity<RootView>
(VisualTestContext::from_window(window, cx), root)
}
/// A first launch: no configuration and nothing stored.
fn first_launch(cx: &mut TestAppContext) -> (VisualTestContext, Entity<RootView>) {
open_app(cx, Path::new("unused.toml"), |_| {
Config::load_or_default(Path::new(":memory:"))
})
}
#[gpui::test]
fn a_ready_update_adds_a_title_bar_button_that_opens_the_settings(cx: &mut TestAppContext) {
let (mut cx, root) = first_launch(cx);
let cx = &mut cx;
root.update(cx, |root, cx| {
root.screen = Screen::Page;
cx.notify();
});
// Centre of the third action button, title-bar drag area until an update is ready.
let update = point(BUTTON_WIDTH * 2.5, BAR_HEIGHT / 2.);
cx.update(|window, cx| window.draw(cx).clear(cx));
@@ -62,58 +71,32 @@ fn a_ready_update_adds_a_title_bar_button_that_opens_the_settings(cx: &mut TestA
}
#[gpui::test]
fn settings_in_the_title_bar_respects_the_initial_key_prompt(cx: &mut TestAppContext) {
let (mut cx, root) = first_launch(cx);
let cx = &mut cx;
async fn a_first_launch_shows_the_page_and_can_refresh_without_a_key(cx: &mut TestAppContext) {
let (mut window, root) = first_launch(cx);
assert!(root.read_with(&window, |root, _| root.screen == Screen::Page));
// Centre of the second action button.
let settings = point(BUTTON_WIDTH * 1.5, BAR_HEIGHT / 2.);
cx.update(|window, cx| window.draw(cx).clear(cx));
cx.simulate_click(settings, Modifiers::none());
assert!(root.read_with(cx, |root, _| root.screen == Screen::Prompt));
window.update(|window, cx| window.draw(cx).clear(cx));
window.simulate_click(settings, Modifiers::none());
assert!(root.read_with(&window, |root, _| root.screen == Screen::Settings));
// Model a keyless launch with stored data, where Settings is available.
root.update(cx, |root, cx| {
root.screen = Screen::Page;
cx.notify();
});
assert!(!root.read_with(cx, |root, cx| root.can_refresh(cx)));
cx.update(|window, cx| window.draw(cx).clear(cx));
cx.simulate_keystrokes("tab");
// The follower started with the app: once its first round is in, « Actualiser » is
// available, and « Paramètres » follows it from the keyboard.
window.update(|window, cx| root.update(cx, |root, cx| root.show_page(window, cx)));
let page = root.read_with(&window, |root, _| root.page.clone());
cx.condition(&page, |page, _| !page.busy()).await;
assert!(root.read_with(&window, |root, cx| root.can_refresh(cx)));
window.update(|window, cx| window.draw(cx).clear(cx));
window.simulate_keystrokes("tab tab");
let enter =
cx.update(|_, cx| Keystroke::parse_with_os("enter", cx.platform_info().os).unwrap());
cx.simulate_event(KeyDownEvent {
window.update(|_, cx| Keystroke::parse_with_os("enter", cx.platform_info().os).unwrap());
window.simulate_event(KeyDownEvent {
keystroke: enter.clone(),
is_held: false,
prefer_character_input: false,
});
cx.simulate_event(KeyUpEvent { keystroke: enter });
assert!(root.read_with(cx, |root, _| root.screen == Screen::Settings));
}
/// The app opened on the config file at `path` (the file is read, or missing).
fn open_app(
cx: &mut TestAppContext,
path: &Path,
load: fn(&Path) -> Result<Config, arena_tracker_core::Error>,
) -> (VisualTestContext, Entity<RootView>) {
cx.update(gpui_kit::init);
let (window, root) = cx.update(|cx| {
let config = load(path).unwrap();
let api = Arc::new(RiotApi::new(String::new(), &config.region));
let setup = Setup {
tracker: Arc::new(Tracker::open(Path::new(":memory:"), Box::new(api.clone())).unwrap()),
// No cache read on a thread of its own: the test scheduler only allows its own.
game_data: None,
riot_id: String::new(),
notice: None,
store: KeyStore::new(path.to_path_buf(), config, api),
};
gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| {
cx.new(|cx| RootView::new(setup, false, window, cx))
})
.unwrap()
});
(VisualTestContext::from_window(window, cx), root)
window.simulate_event(KeyUpEvent { keystroke: enter });
assert!(root.read_with(&window, |root, _| root.screen == Screen::Settings));
}
#[gpui::test]
@@ -146,28 +129,20 @@ fn the_chosen_sort_is_saved_with_the_preferences_and_found_again_at_the_next_lau
}
#[gpui::test]
fn the_end_of_a_match_closes_the_settings_and_leaves_the_window_as_it_is(cx: &mut TestAppContext) {
fn the_end_of_a_game_closes_the_settings_without_activating_the_window(cx: &mut TestAppContext) {
let dir = TestDir::new("recap-129");
let (mut window, root) = open_app(cx, &dir.path().join("config.toml"), Config::load_or_default);
let cx = &mut window;
root.update(cx, |root, cx| {
root.screen = Screen::Page;
cx.notify();
});
cx.update(|window, cx| root.update(cx, |root, cx| root.open_settings(window, cx)));
// In League, the window hidden in the notification area.
// In League: the game has the keyboard.
cx.deactivate_window();
cx.simulate_visibility_change(WindowVisibility::Hidden);
let page = root.read_with(cx, |root, _| root.page.clone());
page.update(cx, |_, cx| cx.emit(RecapOpened));
page.update(cx, |_, cx| cx.emit(MatchEndShown));
cx.run_until_parked();
assert!(root.read_with(cx, |root, _| root.screen == Screen::Page));
cx.update(|window, cx| {
assert_eq!(cx.active_window(), None, "the window was activated");
assert!(!window.is_visible(), "the window was shown");
});
cx.update(|_, cx| assert_eq!(cx.active_window(), None, "the window was activated"));
}
#[gpui::test]
@@ -175,10 +150,6 @@ fn a_live_match_closes_the_settings_without_activating_the_window(cx: &mut TestA
let dir = TestDir::new("live-match-109");
let (mut window, root) = open_app(cx, &dir.path().join("config.toml"), Config::load_or_default);
let cx = &mut window;
root.update(cx, |root, cx| {
root.screen = Screen::Page;
cx.notify();
});
cx.update(|window, cx| root.update(cx, |root, cx| root.open_settings(window, cx)));
// In League: the game has the keyboard.
cx.deactivate_window();
+17 -6
View File
@@ -94,15 +94,13 @@ pub fn state_label(state: Option<ChampionState>) -> &'static str {
}
}
/// Riot's required legal notice, in English, as its policy words it.
pub const RIOT_NOTICE: &str = "Arena Tracker isn't endorsed by Riot Games and doesn't reflect the views or opinions of Riot Games or anyone officially involved in producing or managing Riot Games properties. Riot Games, and all associated properties are trademarks or registered trademarks of Riot Games, Inc.";
pub const CLIENT_ABSENT: &str =
"Client League of Legends non détecté : affichage des données enregistrées.";
const INTERNAL_ERROR: &str = "Mise à jour impossible : erreur interne.";
/// The discreet line under the Challenge tile.
pub fn official_note(official: u32) -> String {
format!("Progression officielle : {official}")
}
pub fn official_differs(app: usize, official: u32) -> String {
format!(
"La Progression officielle du jeu indique {official} champions validés, l'application en compte {app} : des Parties manquent peut-être."
@@ -137,6 +135,11 @@ pub fn friend_sync_line(name: &str, progress: Option<SyncProgress>) -> String {
}
}
/// The status line while the import waits for the Riot quota, `secs` left.
pub fn quota_line(secs: u64) -> String {
format!("Quota Riot atteint : reprise dans {secs} s")
}
#[cfg(test)]
mod tests {
use super::*;
@@ -220,7 +223,6 @@ mod tests {
#[test]
fn official_progress_texts() {
assert_eq!(official_note(52), "Progression officielle : 52");
assert_eq!(
official_differs(50, 52),
"La Progression officielle du jeu indique 52 champions validés, l'application en compte 50 : des Parties manquent peut-être."
@@ -232,6 +234,7 @@ mod tests {
let progress = SyncProgress {
fetched: 3,
to_fetch: 10,
..Default::default()
};
assert_eq!(
friend_sync_line("Bob", Some(progress)),
@@ -240,11 +243,18 @@ mod tests {
assert_eq!(friend_sync_line("Bob", None), "Import de Bob…");
}
#[test]
fn the_quota_line_counts_the_seconds_left() {
assert_eq!(quota_line(12), "Quota Riot atteint : reprise dans 12 s");
assert_eq!(quota_line(1), "Quota Riot atteint : reprise dans 1 s");
}
#[test]
fn the_sync_line_follows_what_is_running() {
let progress = SyncProgress {
fetched: 3,
to_fetch: 10,
..Default::default()
};
assert_eq!(
sync_line(true, Some(progress), false, Some(5)),
@@ -257,6 +267,7 @@ mod tests {
let nothing = SyncProgress {
fetched: 0,
to_fetch: 0,
..Default::default()
};
assert_eq!(
sync_line(true, Some(nothing), false, Some(5)),
+1 -1
View File
@@ -75,7 +75,7 @@ pub fn heading(cx: &App) -> Div {
fn load_font(cx: &App, bytes: &'static [u8], family: &'static str, weight: FontWeight) -> bool {
let text = cx.text_system();
if let Err(error) = text.add_fonts(vec![Cow::Borrowed(bytes)]) {
eprintln!("Failed to load {family}: {error}");
log::error!("Failed to load {family}: {error}");
return false;
}
// Naming a missing family incurs a fallback lookup on every text run.
+1 -1
View File
@@ -204,7 +204,7 @@ unsafe extern "system" {
/// UI (rule #1, budget 5). Best effort: on failure the work still runs.
// shortcut: ureq starts a short DNS thread per request (the core's agents set a timeout) and it
// runs at normal priority; resolve on the calling thread if those threads ever show up in a profile.
fn lower_priority() {
pub(crate) fn lower_priority() {
#[cfg(windows)]
unsafe {
SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL);
+1 -1
View File
@@ -1,7 +1,7 @@
//! The Death Recaps of « Parties » (#128): one job for the Match opened, which reads what is
//! stored or asks Riot for the timeline, and the thread that serves the followed Matches the
//! core queues when they are published. Both run below normal priority: a timeline request
//! waits on the shared limiter and on `Retry-After`.
//! waits on `Retry-After`.
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::sync::Arc;
+6 -3
View File
@@ -23,11 +23,14 @@ pub fn spawn_friend_import(tracker: Arc<Tracker>, puuid: String, tx: Sender<Msg>
let mut last = None;
let result = tracker.import_friend(&puuid, &mut |progress| {
let now = std::time::Instant::now();
if last.is_some_and(|last| now.duration_since(last) < std::time::Duration::from_secs(1))
{
// The start and the end of a quota wait always pass.
if last.is_some_and(|(at, wait): (_, Option<_>)| {
wait == progress.quota_wait
&& now.duration_since(at) < std::time::Duration::from_secs(1)
}) {
return;
}
last = Some(now);
last = Some((now, progress.quota_wait));
let _ = tx.try_send(Msg::FriendProgress {
puuid: puuid.clone(),
progress,
+3 -6
View File
@@ -24,12 +24,9 @@ fn guarded_workers_deliver_messages_and_report_panics() {
#[test]
fn statistics_workers_deliver_the_generation_count_and_errors() {
let tracker = Arc::new(
Tracker::open(
Path::new(":memory:"),
Box::new(RiotApi::new(String::new(), "europe")),
)
.unwrap()
.with_seasons(Vec::new()),
Tracker::open(Path::new(":memory:"), Box::new(RiotApi::new("", "europe")))
.unwrap()
.with_seasons(Vec::new()),
);
let (tx, rx) = unbounded();
spawn_statistics(
+2
View File
@@ -3,10 +3,12 @@ name = "arena-tracker-core"
edition.workspace = true
rust-version.workspace = true
version.workspace = true
license.workspace = true
[dependencies]
base64 = { version = "0.23.1", default-features = false, features = ["std"] }
image = { version = "0.25", default-features = false, features = ["jpeg", "png"] }
log = "0.4"
ring = "0.17.14"
rusqlite = { version = "0.43.0", features = ["bundled"] }
rustls = { version = "0.23.46", default-features = false, features = ["ring", "std", "tls12"] }
+5 -8
View File
@@ -62,15 +62,12 @@ impl Default for DataDragon {
impl ChampionSource for DataDragon {
fn latest_version(&self) -> Result<String, SourceError> {
let url = format!("{HOST}/api/versions.json");
decode_latest_version(&get(&self.agent, &url, None, |b| b.read_to_string())?)
decode_latest_version(&get(&self.agent, &url, |b| b.read_to_string())?)
}
fn catalog(&self, version: &str) -> Result<ChampionCatalog, SourceError> {
let url = format!("{HOST}/cdn/{}/data/fr_FR/champion.json", encode(version));
decode_catalog(
version,
&get(&self.agent, &url, None, |b| b.read_to_string())?,
)
decode_catalog(version, &get(&self.agent, &url, |b| b.read_to_string())?)
}
fn portrait(&self, version: &str, key: &str) -> Result<Vec<u8>, SourceError> {
@@ -79,18 +76,18 @@ impl ChampionSource for DataDragon {
encode(version),
encode(key)
);
get(&self.agent, &url, None, |b| b.read_to_vec())
get(&self.agent, &url, |b| b.read_to_vec())
}
fn card_portrait(&self, key: &str) -> Result<Vec<u8>, SourceError> {
// The loading art's path carries no game version.
let url = format!("{HOST}/cdn/img/champion/loading/{}_0.jpg", encode(key));
get(&self.agent, &url, None, |b| b.read_to_vec())
get(&self.agent, &url, |b| b.read_to_vec())
}
fn splash(&self, key: &str) -> Result<Vec<u8>, SourceError> {
let url = format!("{HOST}/cdn/img/champion/splash/{}_0.jpg", encode(key));
get(&self.agent, &url, None, |b| b.read_to_vec())
get(&self.agent, &url, |b| b.read_to_vec())
}
}
+69 -34
View File
@@ -4,15 +4,20 @@ use serde::{Deserialize, Serialize};
use crate::error::Error;
/// User settings from a TOML file. Deliberately has no `Debug`: it holds the API key.
/// The relay that makes the app's Riot calls (ADR-0008).
const RELAY_URL: &str = "https://arena-tracker.nessar.fr";
/// User settings from a TOML file. Deliberately has no `Debug`: the `riot_api_key` of an older
/// version, never read, stays in `other` and is written back.
#[derive(Deserialize, Serialize)]
pub struct Config {
#[serde(default)]
pub riot_api_key: String,
#[serde(default)]
pub riot_id: String,
#[serde(default = "default_region")]
pub region: String,
/// Another relay, for development. Saved only when set.
#[serde(default, skip_serializing_if = "Option::is_none")]
relay_url: Option<String>,
/// Whether the one-time notice about closing to the notification area was shown.
#[serde(default)]
pub tray_notice_shown: bool,
@@ -105,16 +110,21 @@ impl Config {
return Config::load(path);
}
Ok(Config {
riot_api_key: String::new(),
riot_id: String::new(),
region: default_region(),
relay_url: None,
tray_notice_shown: false,
preferences: Preferences::default(),
other: toml::Table::new(),
})
}
/// Writes the file, creating its folder. It is the only place the key is ever stored.
/// The address of the relay: the configured one, else the built-in one.
pub fn relay_url(&self) -> &str {
self.relay_url.as_deref().unwrap_or(RELAY_URL)
}
/// Writes the file, creating its folder.
pub fn save(&self, path: &Path) -> Result<(), Error> {
let io_error = |e: std::io::Error| Error::Config(format!("{} : {e}", path.display()));
if let Some(dir) = path.parent() {
@@ -122,7 +132,7 @@ impl Config {
}
let text = toml::to_string(self)
.map_err(|e| Error::Config(format!("{} : {e}", path.display())))?;
// Written aside first so a crash cannot leave a half-written key file.
// Written aside first so a crash cannot leave a half-written file.
let partial = path.with_extension("part");
std::fs::write(&partial, text).map_err(io_error)?;
std::fs::rename(&partial, path).map_err(io_error)
@@ -147,7 +157,7 @@ mod tests {
#[test]
fn region_defaults_to_europe() {
let config = load("riot_api_key = \"k\"\nriot_id = \"Joueur#EUW\"\n").unwrap();
let config = load("riot_id = \"Joueur#EUW\"\n").unwrap();
assert_eq!(config.riot_id, "Joueur#EUW");
assert_eq!(config.region, "europe");
assert!(!config.tray_notice_shown);
@@ -212,23 +222,17 @@ mod tests {
#[test]
fn region_can_be_set() {
let config =
load("riot_api_key = \"k\"\nriot_id = \"J#NA\"\nregion = \"americas\"\n").unwrap();
let config = load("riot_id = \"J#NA\"\nregion = \"americas\"\n").unwrap();
assert_eq!(config.region, "americas");
}
#[test]
fn a_partial_file_gets_empty_values_and_the_default_region() {
let config = load("riot_id = \"Joueur#EUW\"\n").unwrap();
assert_eq!(
(config.riot_api_key.as_str(), config.region.as_str()),
("", "europe")
);
assert_eq!(config.region, "europe");
let config = load("").unwrap();
assert_eq!(
(config.riot_api_key.as_str(), config.riot_id.as_str()),
("", "")
);
assert_eq!(config.riot_id, "");
assert_eq!(config.relay_url(), RELAY_URL);
}
#[test]
@@ -236,13 +240,10 @@ mod tests {
let dir = tempfile::tempdir().unwrap();
let config = Config::load_or_default(&dir.path().join("config.toml")).unwrap();
assert_eq!(
(
config.riot_api_key.as_str(),
config.riot_id.as_str(),
config.region.as_str()
),
("", "", "europe")
(config.riot_id.as_str(), config.region.as_str()),
("", "europe")
);
assert_eq!(config.relay_url(), RELAY_URL);
assert!(!dir.path().join("config.toml").exists());
assert!(config.preferences.close_to_tray);
assert_eq!(config.preferences.theme, ThemePreference::System);
@@ -255,7 +256,7 @@ mod tests {
let path = dir.path().join("config.toml");
std::fs::write(
&path,
"riot_api_key = \"RGAPI-secret\"\nriot_id = \"Joueur#EUW\"\nregion = \"americas\"\n\n[other]\nvalue = 42\n",
"riot_id = \"Joueur#EUW\"\nregion = \"americas\"\n\n[other]\nvalue = 42\n",
)
.unwrap();
let mut config = Config::load(&path).unwrap();
@@ -278,7 +279,6 @@ mod tests {
assert_eq!(loaded.preferences, config.preferences);
assert!(loaded.tray_notice_shown);
assert_eq!(loaded.other["other"]["value"].as_integer(), Some(42));
assert_eq!(loaded.riot_api_key, "RGAPI-secret");
assert_eq!(
(loaded.riot_id.as_str(), loaded.region.as_str()),
("Joueur#EUW", "americas")
@@ -286,18 +286,53 @@ mod tests {
}
#[test]
fn a_failed_save_does_not_echo_the_key() {
fn the_relay_is_built_in_and_another_one_can_be_configured() {
assert_eq!(
load("").unwrap().relay_url(),
"https://arena-tracker.nessar.fr"
);
let config = load("relay_url = \"http://127.0.0.1:8080\"\n").unwrap();
assert_eq!(config.relay_url(), "http://127.0.0.1:8080");
// The built-in address is never written: a later version may change it.
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("config.toml");
Config::load_or_default(&path).unwrap().save(&path).unwrap();
assert!(
!std::fs::read_to_string(&path)
.unwrap()
.contains("relay_url")
);
}
#[test]
fn the_key_of_an_older_version_is_kept_but_never_read() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("config.toml");
std::fs::write(
&path,
"riot_api_key = \"RGAPI-old\"\nriot_id = \"Joueur#EUW\"\n",
)
.unwrap();
let mut config = Config::load(&path).unwrap();
config.preferences.theme = ThemePreference::Dark;
config.save(&path).unwrap();
let saved = std::fs::read_to_string(&path).unwrap();
assert!(saved.contains("riot_api_key = \"RGAPI-old\""), "{saved}");
assert_eq!(
Config::load(&path).unwrap().preferences.theme,
ThemePreference::Dark
);
}
#[test]
fn a_failed_save_does_not_echo_an_older_key() {
let dir = tempfile::tempdir().unwrap();
let blocker = dir.path().join("file");
std::fs::write(&blocker, "").unwrap();
let config = Config {
riot_api_key: "RGAPI-secret".into(),
riot_id: String::new(),
region: "europe".into(),
tray_notice_shown: false,
preferences: Preferences::default(),
other: toml::Table::new(),
};
let config = load("riot_api_key = \"RGAPI-secret\"\n").unwrap();
let Err(err) = config.save(&blocker.join("config.toml")) else {
panic!("saving under a file must fail");
+9 -8
View File
@@ -33,9 +33,9 @@ impl Tracker {
/// `death_recap`, asking Riot first when the Match was never fetched: the first opening of
/// an older Match, and « Réessayer » after a failure. A Match already stored or refused
/// costs no request, and so does one the queue (or another opening) is downloading right
/// now: it waits for that download and reads what it stored. Blocks on the shared limiter and on `Retry-After`: call it from a
/// background thread. An `Err` is transient and stores nothing; a Provisional Match is not
/// asked for.
/// now: it waits for that download and reads what it stored. Blocks on `Retry-After`: call it
/// from a background thread. An `Err` is transient and stores nothing; a Provisional Match
/// is not asked for.
pub fn fetch_death_recap(
&self,
recap: &MatchRecap,
@@ -147,14 +147,15 @@ impl Tracker {
None
}
/// One timeline request (after the limiter and `Retry-After`), then storage. Riot answers
/// 403 both for a Match whose timeline it refuses and for a key it rejects: the Match
/// itself, asked right after, tells them apart (one more request, only in that case). Only
/// a refusal is stored.
/// One timeline request (after any `Retry-After`), then storage. The relay passes any 403
/// Riot gives for a timeline: Riot refusing that Match's timeline, or rejecting the relay's
/// key. The Match itself, asked right after (one more request, only in that case), tells
/// them apart: with a rejected key, the relay answers it 503. Only a confirmed refusal is
/// stored.
fn download_death_recap(&self, match_id: &str) -> Result<(), Error> {
match with_retry(|| self.history.fetch_timeline(match_id)) {
Ok(raw) => self.store_death_recap(match_id, &extract(&raw)?),
Err(SourceError::InvalidKey) => {
Err(SourceError::Refused) => {
with_retry(|| self.history.fetch_match(match_id))?;
self.store_death_recap_refused(match_id)
}
+33 -26
View File
@@ -1,11 +1,16 @@
//! The game client's end-of-game block (`/lol-end-of-game/v1/gameclient-eog-stats-block`), read
//! leniently: no capture of one is in the repository yet.
//! leniently.
//!
//! Seen on real blocks (docs/research/arena-match-statistics.md): `gameId`,
//! `statsBlock.players[]`, each player's `puuid` and `subteamStanding`. Every other key name here
//! is a likely name still to verify on Windows against a real block. A key not found leaves its
//! value `None`, and the block is stored as received (`tracker/blocks.rs`): one that built no
//! Match is read again by later rounds and by a corrected decoder.
//! Key names checked on a block captured on Windows at the end of an Arena 3x6 game
//! (`tests/fixtures/client/end_of_game_block_arena.json`, #154): `gameId`, `gameMode`, `queueId`,
//! `statsBlock.gameLengthSeconds` and `statsBlock.players[]`, each with `PUUID`, `championId`,
//! `championName`, `championLevel`, `subteamId`, `subteamStanding`, `playerKills`,
//! `playerDeaths`, `playerAssists`, `goldEarned`, `itemIds`, `augmentPlatformIds`,
//! `damageDealtToChampions` and `damageTaken`. That block gives no platform and no player name:
//! the signed-in player is found by the client's PUUID alone. The other names are unverified
//! spellings. A key not found leaves its value `None`, and the block is stored as received
//! (`tracker/blocks.rs`): one that built no Match is read again by later rounds and by a
//! corrected decoder.
use serde_json::Value;
@@ -126,7 +131,7 @@ pub(crate) fn decode(content: &str) -> Option<Block> {
.filter(|&id| id != 0)?,
game_mode: at(&["gameMode"]).and_then(text),
queue_id,
duration_s: at(&["gameLength", "gameDuration", "gameLengthSeconds"])
duration_s: at(&["gameLengthSeconds", "gameLength", "gameDuration"])
.and_then(number)
.map(seconds),
platform_id: at(&["platformId"]).and_then(platform),
@@ -148,28 +153,29 @@ fn player(entry: &Value) -> BlockPlayer {
let at = |names: &[&str]| field(entry, "stats", names);
let int = |names: &[&str]| at(names).and_then(number);
let small = |names: &[&str]| int(names).and_then(|n| u32::try_from(n).ok());
let items = match at(&["items"]).and_then(Value::as_array) {
let items = match at(&["itemIds", "items"]).and_then(Value::as_array) {
Some(list) => std::array::from_fn(|i| list.get(i).and_then(id)),
None => std::array::from_fn(|i| {
let names = [format!("item{i}"), format!("ITEM{i}")];
small(&[&names[0], &names[1]])
}),
};
let augments = match at(&["augments", "playerAugments"]).and_then(Value::as_array) {
Some(list) => Some(list.iter().filter_map(id).collect()),
None => {
let slots: Vec<Option<u32>> = (1..=6)
.map(|i| {
let names = [format!("playerAugment{i}"), format!("PLAYER_AUGMENT_{i}")];
small(&[&names[0], &names[1]])
})
.collect();
(slots.iter().any(Option::is_some)).then(|| slots.into_iter().flatten().collect())
let augments =
match at(&["augmentPlatformIds", "augments", "playerAugments"]).and_then(Value::as_array) {
Some(list) => Some(list.iter().filter_map(id).collect()),
None => {
let slots: Vec<Option<u32>> = (1..=6)
.map(|i| {
let names = [format!("playerAugment{i}"), format!("PLAYER_AUGMENT_{i}")];
small(&[&names[0], &names[1]])
})
.collect();
(slots.iter().any(Option::is_some)).then(|| slots.into_iter().flatten().collect())
}
}
}
.map(|ids: Vec<u32>| ids.into_iter().filter(|&id| id != 0).collect());
.map(|ids: Vec<u32>| ids.into_iter().filter(|&id| id != 0).collect());
BlockPlayer {
puuid: at(&["puuid"]).and_then(text),
puuid: at(&["PUUID", "puuid"]).and_then(text),
game_name: at(&["riotIdGameName", "gameName"]).and_then(text),
tag_line: at(&["riotIdTagLine", "riotIdTagline", "tagLine"]).and_then(text),
summoner_name: at(&["summonerName", "displayName"]).and_then(text),
@@ -184,18 +190,19 @@ fn player(entry: &Value) -> BlockPlayer {
])
.and_then(|n| u8::try_from(n).ok())
.filter(|&p| p != 0),
level: small(&["level", "champLevel", "championLevel", "LEVEL"]),
kills: small(&["kills", "CHAMPIONS_KILLED"]),
deaths: small(&["deaths", "NUM_DEATHS"]),
assists: small(&["assists", "ASSISTS"]),
level: small(&["championLevel", "level", "champLevel", "LEVEL"]),
kills: small(&["playerKills", "kills", "CHAMPIONS_KILLED"]),
deaths: small(&["playerDeaths", "deaths", "NUM_DEATHS"]),
assists: small(&["playerAssists", "assists", "ASSISTS"]),
gold_earned: int(&["goldEarned", "GOLD_EARNED"]),
items,
augments,
damage_to_champions: int(&[
"damageDealtToChampions",
"totalDamageDealtToChampions",
"TOTAL_DAMAGE_DEALT_TO_CHAMPIONS",
]),
damage_taken: int(&["totalDamageTaken", "TOTAL_DAMAGE_TAKEN"]),
damage_taken: int(&["damageTaken", "totalDamageTaken", "TOTAL_DAMAGE_TAKEN"]),
}
}
+34
View File
@@ -157,3 +157,37 @@ fn the_platform_is_upper_case_and_alphanumeric_or_ignored() {
assert_eq!(with(bad), None, "{bad:?}");
}
}
/// A block the client gave at the end of an Arena 3x6 game, PUUIDs and game id anonymised.
const CAPTURED: &str = include_str!("../../tests/fixtures/client/end_of_game_block_arena.json");
#[test]
fn decodes_a_captured_block() {
let block = decode(CAPTURED).unwrap();
assert_eq!(block.game_id, 9000000099);
assert_eq!(block.game_mode.as_deref(), Some("CHERRY"));
assert_eq!((block.queue_id, block.duration_s), (Some(1750), Some(1415)));
assert_eq!(block.platform_id, None);
assert_eq!((block.players.len(), block.team_count()), (18, 6));
let me = block.player(Some("client-puuid-self"), None).unwrap();
assert_eq!(
(me.champion_id, me.subteam_id, me.placement),
(Some(23), Some(2), Some(1))
);
assert_eq!(
(me.level, me.kills, me.deaths, me.assists),
(Some(18), Some(16), Some(6), Some(7))
);
assert_eq!(me.gold_earned, Some(16258));
assert_eq!(
me.items.map(Option::unwrap),
[223091, 447100, 223031, 223033, 226672, 223156, 3348]
);
assert_eq!(me.augments, Some(vec![116, 225, 310]));
assert_eq!(
(me.damage_to_champions, me.damage_taken),
(Some(61810), Some(35648))
);
// The block names no player: only the PUUID finds the signed-in one.
assert_eq!(me.riot_id(), None);
}
+9 -5
View File
@@ -3,9 +3,13 @@ use std::time::Duration;
#[derive(Clone, Debug, PartialEq)]
pub enum SourceError {
/// No API key configured yet (as opposed to one Riot rejected).
MissingKey,
InvalidKey,
/// A 401 or 403: the server refuses this request. The relay turns Riot's refusals into 503,
/// except a timeline's 403, which it passes through whatever the cause: Riot refusing that
/// Match's timeline, or rejecting the relay's key.
Refused,
/// A 5xx: the server is down or cannot do the request, e.g. the relay cannot reach Riot.
Unavailable,
/// A 429. `retry_after` is bounded by the source: at least a second, at most ten minutes.
RateLimited {
retry_after: Duration,
},
@@ -17,8 +21,8 @@ pub enum SourceError {
impl fmt::Display for SourceError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
SourceError::MissingKey => write!(f, "Aucune clé API Riot n'est configurée."),
SourceError::InvalidKey => write!(f, "Clé API Riot refusée ou expirée."),
SourceError::Refused => write!(f, "Accès refusé."),
SourceError::Unavailable => write!(f, "Service indisponible : réessayez plus tard."),
SourceError::RateLimited { retry_after } => write!(
f,
"Limite de requêtes Riot atteinte (nouvel essai dans {} s).",
+20 -3
View File
@@ -11,6 +11,7 @@ mod watch;
pub use game_end::GameEnd;
pub use status::{ProgressCheck, Status, UpdateProblem};
use std::collections::HashMap;
use std::sync::{MutexGuard, PoisonError};
use std::thread;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
@@ -28,7 +29,7 @@ use crate::tracker::{Tracker, account_from_row};
/// does not wait for).
pub const MATCH_RETRIES: usize = 90;
pub const RETRY_EVERY_MS: i64 = 20_000;
/// Rounds try a failed adoption again at most this often (an expired key fails every time).
/// Rounds try a failed adoption again at most this often (an unavailable service fails every time).
const ADOPT_RETRY_MS: i64 = 60_000;
const WAIT_WHILE_PENDING: Duration = Duration::from_millis(RETRY_EVERY_MS as u64);
const WAIT_OTHERWISE: Duration = Duration::from_secs(60);
@@ -86,6 +87,8 @@ pub(crate) struct Follow {
blocks_give_up_ms: Option<i64>,
/// A try found no such block: only a new one makes rounds query again.
no_open_blocks: bool,
/// The reason each open block last waited for (logged once per reason).
block_waits: HashMap<i64, provisional::Why>,
/// The latest round that saw the client out of game.
out_of_game_ms: Option<i64>,
pending: Vec<Pending>,
@@ -118,6 +121,14 @@ impl Follow {
self.blocks_synced = true;
}
/// The Account's PUUID changed (`tracker/rekey.rs`): what the session holds follows it.
pub(crate) fn rekey(&mut self, old: &str, new: &str) {
if let Some(a) = self.updating.as_mut().filter(|a| a.puuid == old) {
a.puuid = new.into();
}
self.watches.iter_mut().for_each(|w| w.rekey(old, new));
}
/// The Account was deleted: nothing of it stays to keep its Riot ID from being adopted
/// again (with a full import) or its Matches from being stored again.
pub(crate) fn forget(&mut self, account: &Account) {
@@ -289,6 +300,12 @@ impl Tracker {
if follow.signed_in_folded.as_deref() != folded.as_deref() {
follow.signed_in_folded = folded.map(Into::into);
follow.adopt_retry_after_ms = None;
log::info!(
"League client: {}",
signed_in
.as_deref()
.map_or("nobody signed in".into(), |id| format!("{id} signed in"))
);
}
follow.signed_in.clone_from(&signed_in);
}
@@ -318,7 +335,7 @@ impl Tracker {
Ok(report) => added += report.added,
Err(_) => self.follow().adopt_retry_after_ms = Some(now_ms + ADOPT_RETRY_MS),
},
None => self.follow().problem = Some(UpdateProblem::NoAccount),
None => self.follow().set_problem(UpdateProblem::NoAccount),
}
}
@@ -353,7 +370,7 @@ impl Tracker {
!over && p.tries < MATCH_RETRIES
});
if expired && follow.problem.is_none() {
follow.problem = Some(UpdateProblem::MatchPending);
follow.set_problem(UpdateProblem::MatchPending);
}
}
self.look_up_provisional(now_ms);
+9 -1
View File
@@ -1,5 +1,6 @@
use super::{Tracker, UpdateProblem, account_riot_id, same_riot_id};
use crate::error::Error;
use crate::journal::short;
use crate::model::{Account, SyncProgress, SyncReport};
impl Tracker {
@@ -77,7 +78,7 @@ impl Tracker {
}
pub(super) fn record(&self, problem: UpdateProblem) -> UpdateProblem {
self.follow().problem = Some(problem.clone());
self.follow().set_problem(problem.clone());
problem
}
@@ -140,6 +141,13 @@ impl Tracker {
}) {
return Err(UpdateProblem::NoAccount);
}
if let Some(a) = account.as_ref().filter(|_| result.is_ok()) {
log::info!(
"Account {} is the active one ({})",
account_riot_id(a),
short(&a.puuid)
);
}
follow.updating = account;
follow.adopted = result.is_ok().then(|| account_id.into());
follow.adopt_retry_after_ms = follow.adopt_retry_after_ms.filter(|_| result.is_err());
+8
View File
@@ -21,6 +21,14 @@ impl Tracker {
pub(super) fn follow_gameflow(&self, gameflow: Gameflow, now_ms: i64) -> Option<Option<u64>> {
let mut follow = self.follow();
let previous = std::mem::replace(&mut follow.gameflow, gameflow);
if previous.phase != follow.gameflow.phase {
log::info!(
"Game phase: {:?} -> {:?} (game {:?})",
previous.phase,
follow.gameflow.phase,
follow.gameflow.game_id
);
}
if follow.gameflow.game_id.is_some() {
follow.last_game = Some(follow.gameflow.clone());
}
+2 -2
View File
@@ -1,6 +1,6 @@
//! The active Account first: a Friend's import makes each of its requests only while the
//! follower has no Riot work running and no finished game waits for its Match. Both share the
//! key's limiter, so together they stay within its limits.
//! follower has no Riot work running and no finished game waits for its Match. Both wait out
//! the relay's `Retry-After` when its quota is full.
use std::sync::PoisonError;
+94 -16
View File
@@ -18,10 +18,40 @@ const BLOCK_RETRY_MS: i64 = 7 * 24 * 3_600_000;
/// publish the Match, during which a key or the Account may come right.
const REPORT_WITHIN_MS: i64 = MATCH_RETRIES as i64 * RETRY_EVERY_MS;
/// Why a block cannot be built yet, for the log.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Why {
Unreadable,
UnknownAccount,
ModeUnreadable,
QueueUnreadable,
PlayerMissing,
ChampionOrPlacementMissing,
UnknownPlatform,
NotStored,
}
impl Why {
fn text(self) -> &'static str {
match self {
Why::Unreadable => "the block cannot be decoded",
Why::UnknownAccount => {
"its Account is unknown (none signed in when it arrived, or not stored yet)"
}
Why::ModeUnreadable => "the game mode cannot be read",
Why::QueueUnreadable => "the queue cannot be read or is not an Arena queue",
Why::PlayerMissing => "the signed-in player is not in the block",
Why::ChampionOrPlacementMissing => "the player's champion or Placement is missing",
Why::UnknownPlatform => "no platform for the Match id",
Why::NotStored => "the Provisional Match could not be stored",
}
}
}
/// What came of one try at a block.
enum Built {
/// Not yet: another round, or a corrected decoder, may build it.
Wait,
Wait(Why),
/// Nothing to build: not an Arena game.
Never,
/// The Match of the game is stored under this id; `stored` when this try stored it.
@@ -32,6 +62,25 @@ enum Built {
},
}
fn log_built(game_id: u64, built: &Built) {
match built {
Built::Wait(_) => {}
Built::Never => {
log::info!("End-of-game block (game {game_id}): not an Arena game, dropped")
}
Built::Match {
match_id, stored, ..
} => log::info!(
"End-of-game block (game {game_id}): {}",
if *stored {
format!("stored as Provisional Match {match_id}")
} else {
format!("Match {match_id} already stands for it")
}
),
}
}
impl Tracker {
/// From the wait for the client's events: the block an event delivered is written at once,
/// whatever a round is busy with (a sync may hold it for long), and the next round builds
@@ -71,7 +120,13 @@ impl Tracker {
// Not when its block is already here.
ended
.filter(|game| game.is_none() || *game != received)
.and_then(|_| client.read_end_of_game_block())
.and_then(|game| {
let read = client.read_end_of_game_block();
if read.is_none() {
log::info!("Game {game:?} ended: the client gave no end-of-game block");
}
read
})
});
let new = block.map_or(0, |block| {
self.keep_end_of_game_block(&block, now_ms, on_match)
@@ -115,10 +170,17 @@ impl Tracker {
raw: block.content.clone(),
};
let id = match self.save_end_of_game_block(game_id, &row) {
Ok(Some(id)) => Some(id),
Ok(Some(id)) => {
log::info!(
"End-of-game block received and stored (game {game_id:?}, {} bytes)",
block.content.len()
);
Some(id)
}
// Already stored: its own tries go on.
Ok(None) => return None,
Err(e) => {
log::error!("End-of-game block (game {game_id:?}) could not be stored: {e}");
self.record(UpdateProblem::from(&e));
None
}
@@ -185,18 +247,24 @@ impl Tracker {
on_match: &mut dyn FnMut(FollowedMatch),
) -> bool {
let Some(game) = game.or_else(|| end_of_game::decode(&row.raw)) else {
self.log_wait(row, None, Why::Unreadable);
return false;
};
let built = self.build_provisional(row, &game, now_ms);
log_built(game.game_id, &built);
let finished = match &built {
Built::Wait => return false,
Built::Wait(why) => {
self.log_wait(row, Some(game.game_id), *why);
return false;
}
Built::Never => None,
Built::Match { match_id, .. } => Some(match_id.as_str()),
};
if let Some(id) = row.id
&& let Err(e) = self.finish_end_of_game_block(id, finished)
{
self.record(UpdateProblem::from(&e));
if let Some(id) = row.id {
self.follow().block_waits.remove(&id);
if let Err(e) = self.finish_end_of_game_block(id, finished) {
self.record(UpdateProblem::from(&e));
}
}
match built {
Built::Match {
@@ -212,6 +280,16 @@ impl Tracker {
}
}
/// Warns why a block waits, once per reason: rounds try it again every few seconds.
fn log_wait(&self, row: &StoredBlock, game_id: Option<u64>, why: Why) {
let repeated = row
.id
.is_some_and(|id| self.follow().block_waits.insert(id, why) == Some(why));
if !repeated {
log::warn!("End-of-game block (game {game_id:?}) waits: {}", why.text());
}
}
/// The block becomes a Provisional Match of the Account signed in when it arrived, whatever
/// Account is active when it is built or when Riot publishes it. Without what it takes (that
/// Account known, an Arena game, the signed-in player's entry with its champion and
@@ -220,7 +298,7 @@ impl Tracker {
/// nothing.
fn build_provisional(&self, row: &StoredBlock, game: &Block, now_ms: i64) -> Built {
let Some(signed_in) = row.signed_in_riot_id.as_deref() else {
return Built::Wait;
return Built::Wait(Why::UnknownAccount);
};
let (updating, seen): (Option<Account>, _) = {
let follow = self.follow();
@@ -233,7 +311,7 @@ impl Tracker {
(self.accounts().ok()?.into_iter()).find(owns)
});
let Some(account) = account else {
return Built::Wait;
return Built::Wait(Why::UnknownAccount);
};
let puuid = account.puuid.clone();
// Riot may have published it since: the Match stands for the game.
@@ -250,24 +328,24 @@ impl Tracker {
Some(true) => {}
Some(false) => return Built::Never,
// Its mode may yet be read (a corrected decoder): it stays.
None => return Built::Wait,
None => return Built::Wait(Why::ModeUnreadable),
}
let Some((queue_id, format)) = queue_id.and_then(|q| Some((q, Format::from_queue(q)?)))
else {
return Built::Wait;
return Built::Wait(Why::QueueUnreadable);
};
let Some(player) = game.player(row.client_puuid.as_deref(), Some(signed_in)) else {
return Built::Wait;
return Built::Wait(Why::PlayerMissing);
};
let (Some(champion_id), Some(placement)) = (player.champion_id, player.placement) else {
return Built::Wait;
return Built::Wait(Why::ChampionOrPlacementMissing);
};
// Riot's Match id is the platform and the client's game id. The block's own platform
// first: after a region transfer the Account's older Matches name another one.
let platform =
(game.platform_id.clone()).or_else(|| self.platform_of(&account.puuid).ok().flatten());
let Some(platform) = platform else {
return Built::Wait;
return Built::Wait(Why::UnknownPlatform);
};
let teams = match game.team_count() {
n if n >= 2 => n,
@@ -293,7 +371,7 @@ impl Tracker {
Ok(stored) => stored,
Err(e) => {
self.record(UpdateProblem::from(&e));
return Built::Wait;
return Built::Wait(Why::NotStored);
}
};
self.game_has_a_match(&puuid, &m.match_id, game.game_id, now_ms);
+19 -16
View File
@@ -1,13 +1,25 @@
use crate::error::{Error, SourceError};
use crate::model::Account;
impl super::Follow {
/// Sets the problem, writing it to the log when it is not already the current one.
pub(super) fn set_problem(&mut self, problem: UpdateProblem) {
if self.problem.as_ref() != Some(&problem) {
match &problem {
UpdateProblem::Other(reason) => log::error!("Update problem: {reason}"),
other => log::warn!("Update problem: {other:?}"),
}
}
self.problem = Some(problem);
}
}
/// Why the last update did not (fully) happen.
#[derive(Debug, Clone, PartialEq)]
pub enum UpdateProblem {
MissingKey,
InvalidKey,
Network,
RateLimited,
/// The relay is down, or cannot reach Riot.
Unavailable,
/// Client absent and no Account known yet.
NoAccount,
/// A finished Arena game is not available from the Riot API yet.
@@ -19,18 +31,11 @@ impl UpdateProblem {
/// The French banner text.
pub fn message(&self) -> String {
match self {
UpdateProblem::MissingKey => {
"Aucune clé API Riot n'est configurée : ajoutez-la dans les Paramètres.".into()
}
UpdateProblem::InvalidKey => {
"La clé API Riot est refusée (invalide ou expirée) : renouvelez-la dans les Paramètres."
.into()
}
UpdateProblem::Network => {
"L'API Riot est injoignable : vérifiez votre connexion.".into()
"Le service Arena Tracker est injoignable : vérifiez votre connexion.".into()
}
UpdateProblem::RateLimited => {
"L'API Riot limite les requêtes : la mise à jour reprendra plus tard.".into()
UpdateProblem::Unavailable => {
"Le service Arena Tracker est indisponible : réessayez plus tard.".into()
}
UpdateProblem::NoAccount => {
"Aucun Compte connu : lancez le client de League of Legends et connectez-vous."
@@ -48,10 +53,8 @@ impl UpdateProblem {
impl From<&Error> for UpdateProblem {
fn from(error: &Error) -> Self {
match error {
Error::Source(SourceError::MissingKey) => UpdateProblem::MissingKey,
Error::Source(SourceError::InvalidKey) => UpdateProblem::InvalidKey,
Error::Source(SourceError::Network(_)) => UpdateProblem::Network,
Error::Source(SourceError::RateLimited { .. }) => UpdateProblem::RateLimited,
Error::Source(SourceError::Unavailable) => UpdateProblem::Unavailable,
other => UpdateProblem::Other(other.to_string()),
}
}
+7 -11
View File
@@ -1,7 +1,6 @@
use super::*;
use crate::error::SourceError;
use std::collections::HashSet;
use std::time::Duration;
#[test]
fn account_riot_ids_join_name_and_tag() {
@@ -16,10 +15,8 @@ fn account_riot_ids_join_name_and_tag() {
#[test]
fn every_problem_has_its_own_message() {
let messages: HashSet<String> = [
UpdateProblem::MissingKey,
UpdateProblem::InvalidKey,
UpdateProblem::Network,
UpdateProblem::RateLimited,
UpdateProblem::Unavailable,
UpdateProblem::NoAccount,
UpdateProblem::MatchPending,
UpdateProblem::Other("panne".into()),
@@ -27,23 +24,22 @@ fn every_problem_has_its_own_message() {
.iter()
.map(UpdateProblem::message)
.collect();
assert_eq!(messages.len(), 7);
assert_eq!(messages.len(), 5);
assert!(messages.iter().all(|m| !m.is_empty()));
}
#[test]
fn errors_map_to_problems() {
let source = |e| UpdateProblem::from(&Error::Source(e));
assert_eq!(source(SourceError::MissingKey), UpdateProblem::MissingKey);
assert_eq!(source(SourceError::InvalidKey), UpdateProblem::InvalidKey);
assert_eq!(source(SourceError::Unavailable), UpdateProblem::Unavailable);
assert_eq!(
source(SourceError::Network("x".into())),
UpdateProblem::Network
);
let limited = SourceError::RateLimited {
retry_after: Duration::ZERO,
};
assert_eq!(source(limited), UpdateProblem::RateLimited);
assert!(matches!(
source(SourceError::Refused),
UpdateProblem::Other(_)
));
assert!(matches!(
source(SourceError::NotFound),
UpdateProblem::Other(_)
+6
View File
@@ -16,6 +16,12 @@ impl Watch {
pub(super) fn is_of(&self, puuid: &str) -> bool {
self.puuid == puuid
}
pub(super) fn rekey(&mut self, old: &str, new: &str) {
if self.puuid == old {
self.puuid = new.into();
}
}
}
impl Tracker {
+1 -1
View File
@@ -30,6 +30,6 @@ impl Default for HttpCatalog {
impl CatalogSource for HttpCatalog {
fn get(&self, url: &str) -> Result<Vec<u8>, SourceError> {
get(&self.agent, url, None, |body| body.read_to_vec())
get(&self.agent, url, |body| body.read_to_vec())
}
}
+237
View File
@@ -0,0 +1,237 @@
//! The application log: lines go to `logs/arena-tracker.log` under the data folder, rotating at
//! 1 MB with one old file kept (`arena-tracker.1.log`), and in debug builds to stderr too.
//!
//! The `log` macros only format the line and queue it: one background thread, blocked on its
//! channel at rest, writes it through a `BufWriter` and flushes (a write call, never an fsync)
//! once what was queued is drained. No timer: what is buffered leaves at the next line or at
//! `Log::flush`, which the app calls on quit.
//!
//! Never logged: a key, a raw block or Riot response, a full PUUID. The writer masks any
//! long token of letters, digits, `-` and `_` (a PUUID has 78 characters, a key 42) as a last
//! guard against one slipping into an error text.
use std::fs::{self, File, OpenOptions};
use std::io::{self, BufWriter, Write};
use std::path::{Path, PathBuf};
use std::sync::mpsc::{self, Receiver, Sender};
use std::thread;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use log::{Level, LevelFilter, Log, Metadata, Record};
use crate::date::Date;
const FILE: &str = "arena-tracker.log";
const OLD_FILE: &str = "arena-tracker.1.log";
const MAX_BYTES: u64 = 1_000_000;
/// Tokens of at least this many characters are masked (a key has 42, a PUUID 78).
const LONGEST_TOKEN: usize = 40;
/// How long `flush` waits for the writer.
const FLUSH_WAIT: Duration = Duration::from_secs(2);
enum Msg {
Line(String),
Flush(Sender<()>),
}
struct Journal {
tx: Sender<Msg>,
}
impl Journal {
/// Opens (creating the folder) the log in `dir`. `echo` receives each line too. `on_start`
/// runs first on the writer thread (the app lowers its priority there).
fn open(
dir: &Path,
echo: Option<Box<dyn Write + Send>>,
on_start: fn(),
) -> io::Result<Journal> {
fs::create_dir_all(dir)?;
let mut sink = Sink::open(dir.to_path_buf(), echo)?;
let (tx, rx) = mpsc::channel();
thread::Builder::new()
.name("journal".into())
.spawn(move || {
on_start();
sink.run(&rx);
})?;
Ok(Journal { tx })
}
/// The first line of a run.
fn launch(&self, version: &str, channel: &str) {
let args = format_args!("Arena Tracker {version} started (update channel: {channel})");
self.log(
&Record::builder()
.level(Level::Info)
.target(module_path!())
.args(args)
.build(),
);
}
}
/// Installs the log of this process under `data_dir/logs`, with the launch line, and returns
/// the failure to open it (the app goes on without a log). `echo`: also on stderr. `on_start`:
/// see [`Journal::open`].
pub fn init(
data_dir: &Path,
echo: bool,
version: &str,
channel: &str,
on_start: fn(),
) -> io::Result<()> {
let echo = echo.then(|| Box::new(io::stderr()) as Box<dyn Write + Send>);
let journal = Journal::open(&data_dir.join("logs"), echo, on_start)?;
journal.launch(version, channel);
log::set_logger(Box::leak(Box::new(journal))).map_err(|e| io::Error::other(e.to_string()))?;
log::set_max_level(LevelFilter::Info);
Ok(())
}
impl Log for Journal {
fn enabled(&self, metadata: &Metadata) -> bool {
// The HTTP client logs URLs (a PUUID) and headers: never take it. Other libraries (GPUI…)
// only for errors: their info and warnings may come per frame.
let target = metadata.target();
let floor = if target.starts_with("arena_tracker") {
Level::Info
} else {
Level::Error
};
metadata.level() <= floor && !target.starts_with("ureq")
}
fn log(&self, record: &Record) {
if !self.enabled(record.metadata()) {
return;
}
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default();
let ms = i64::try_from(now.as_millis()).unwrap_or(0);
let Date { year, month, day } = Date::from_ms(ms);
let (h, m, s) = ((ms / 3_600_000) % 24, (ms / 60_000) % 60, (ms / 1000) % 60);
let line = format!(
"{year:04}-{month:02}-{day:02}T{h:02}:{m:02}:{s:02}.{:03}Z {:<5} {}\n",
ms % 1000,
record.level(),
record.args()
);
let _ = self.tx.send(Msg::Line(line));
}
fn flush(&self) {
let (ack, done) = mpsc::channel();
if self.tx.send(Msg::Flush(ack)).is_ok() {
let _ = done.recv_timeout(FLUSH_WAIT);
}
}
}
struct Sink {
dir: PathBuf,
file: BufWriter<File>,
size: u64,
echo: Option<Box<dyn Write + Send>>,
}
impl Sink {
fn open(dir: PathBuf, echo: Option<Box<dyn Write + Send>>) -> io::Result<Sink> {
let (file, size) = append_to(&dir)?;
Ok(Sink {
dir,
file: BufWriter::new(file),
size,
echo,
})
}
fn run(&mut self, rx: &Receiver<Msg>) {
// Blocks at rest: nothing wakes this thread but a line or a flush.
while let Ok(first) = rx.recv() {
let mut acks = Vec::new();
for msg in std::iter::once(first).chain(std::iter::from_fn(|| rx.try_recv().ok())) {
match msg {
Msg::Line(line) => self.write(&mask_long_tokens(&line)),
Msg::Flush(ack) => acks.push(ack),
}
}
let _ = self.file.flush();
for ack in acks {
let _ = ack.send(());
}
}
}
/// A write failure loses the line: a log must not take the app down. A failed rotation (the
/// old file held open elsewhere) keeps writing to the current file and tries again after
/// another megabyte, not at every line.
fn write(&mut self, line: &str) {
if self.size + line.len() as u64 > MAX_BYTES && self.rotate().is_err() {
self.size = 0;
}
if self.file.write_all(line.as_bytes()).is_ok() {
self.size += line.len() as u64;
}
if let Some(echo) = &mut self.echo {
let _ = echo.write_all(line.as_bytes());
}
}
/// The current file becomes the old one (the previous old one is replaced). On failure the
/// current handle is kept. A missing current file (renamed, then not recreated) is not an
/// error: it is recreated.
fn rotate(&mut self) -> io::Result<()> {
self.file.flush()?;
match fs::rename(self.dir.join(FILE), self.dir.join(OLD_FILE)) {
Err(e) if e.kind() != io::ErrorKind::NotFound => return Err(e),
_ => {}
}
let (file, size) = append_to(&self.dir)?;
(self.file, self.size) = (BufWriter::new(file), size);
Ok(())
}
}
fn append_to(dir: &Path) -> io::Result<(File, u64)> {
let file = OpenOptions::new()
.create(true)
.append(true)
.open(dir.join(FILE))?;
let size = file.metadata()?.len();
Ok((file, size))
}
/// Replaces each long token by its first 8 characters and `…`.
fn mask_long_tokens(line: &str) -> String {
let word = |c: char| c.is_ascii_alphanumeric() || c == '-' || c == '_';
let mut out = String::with_capacity(line.len());
let mut rest = line;
while let Some(start) = rest.find(word) {
out.push_str(&rest[..start]);
rest = &rest[start..];
let end = rest.find(|c| !word(c)).unwrap_or(rest.len());
let (token, after) = rest.split_at(end);
if token.len() >= LONGEST_TOKEN {
out.push_str(&token[..8]);
out.push('…');
} else {
out.push_str(token);
}
rest = after;
}
out + rest
}
/// Abbreviates a PUUID to its first 8 characters, the only form the log carries.
pub(crate) fn short(puuid: &str) -> &str {
puuid.get(..8).unwrap_or(puuid)
}
#[cfg(test)]
#[path = "../tests/common/capture.rs"]
pub(crate) mod capture;
#[cfg(test)]
mod tests;
+199
View File
@@ -0,0 +1,199 @@
//! The log's file, its rotation, its echo and what it never holds (#142).
use std::fs;
use std::io::{self, Write};
use std::path::Path;
use std::sync::{Arc, Mutex};
use log::{Level, Log, Metadata, Record};
use super::*;
fn write(journal: &Journal, text: &str) {
journal.log(
&Record::builder()
.level(Level::Info)
.target("arena_tracker_core::follow")
.args(format_args!("{text}"))
.build(),
);
}
/// Waits until the writer has written all that was queued. Unlike `Log::flush`, which gives up
/// after `FLUSH_WAIT` (a slow machine may still be rotating), it waits as long as it takes.
fn drain(journal: &Journal) {
let (ack, done) = mpsc::channel();
journal.tx.send(Msg::Flush(ack)).unwrap();
done.recv().unwrap();
}
fn read(dir: &Path, name: &str) -> String {
fs::read_to_string(dir.join(name)).unwrap_or_default()
}
fn names(dir: &Path) -> Vec<String> {
let mut names: Vec<_> = fs::read_dir(dir)
.unwrap()
.map(|e| e.unwrap().file_name().into_string().unwrap())
.collect();
names.sort();
names
}
#[test]
fn long_tokens_are_masked_and_the_rest_kept() {
let puuid = "x".repeat(78);
assert_eq!(
mask_long_tokens(&format!("a {puuid} é#EUW, EUW1_7 {puuid}")),
"a xxxxxxxx… é#EUW, EUW1_7 xxxxxxxx…"
);
assert_eq!(short("abcdefghij"), "abcdefgh");
assert_eq!(short("abc"), "abc");
}
#[test]
fn past_one_megabyte_the_file_becomes_the_old_one_and_never_more_than_two_exist() {
let dir = tempfile::tempdir().unwrap();
let journal = Journal::open(dir.path(), None, || {}).unwrap();
let line = format!("{}end", "word ".repeat(200));
// About 3.5 MB: the file rotates three times.
for i in 0..3500 {
write(&journal, &format!("{i} {line}"));
}
drain(&journal);
assert_eq!(
names(dir.path()),
["arena-tracker.1.log", "arena-tracker.log"]
);
for name in ["arena-tracker.log", "arena-tracker.1.log"] {
let size = fs::metadata(dir.path().join(name)).unwrap().len();
assert!((1..=1_000_000).contains(&size), "{name}: {size}");
}
assert!(read(dir.path(), "arena-tracker.log").contains("3499 word"));
// The old file holds the lines just before the current one's first.
let first: u32 = (read(dir.path(), "arena-tracker.log")
.split_whitespace()
.nth(2))
.and_then(|n| n.parse().ok())
.unwrap();
let old = read(dir.path(), "arena-tracker.1.log");
assert!(
old.lines()
.last()
.unwrap()
.contains(&format!(" {} word", first - 1))
);
}
#[test]
fn an_existing_file_is_appended_to_and_rotates_from_its_size() {
let dir = tempfile::tempdir().unwrap();
fs::write(dir.path().join("arena-tracker.log"), "x ".repeat(400_000)).unwrap();
let journal = Journal::open(dir.path(), None, || {}).unwrap();
write(&journal, "first");
drain(&journal);
assert_eq!(names(dir.path()), ["arena-tracker.log"]);
assert!(read(dir.path(), "arena-tracker.log").ends_with("first\n"));
write(&journal, &"long ".repeat(50_000));
drain(&journal);
assert_eq!(
names(dir.path()),
["arena-tracker.1.log", "arena-tracker.log"]
);
}
#[derive(Clone, Default)]
struct Echo(Arc<Mutex<Vec<u8>>>);
impl Write for Echo {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.0.lock().unwrap().extend_from_slice(buf);
Ok(buf.len())
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
#[test]
fn an_echo_sink_gets_the_same_lines_as_the_file() {
let dir = tempfile::tempdir().unwrap();
let echo = Echo::default();
let journal = Journal::open(dir.path(), Some(Box::new(echo.clone())), || {}).unwrap();
journal.launch("1.2.3", "stable");
write(&journal, "hello");
drain(&journal);
let echoed = String::from_utf8(echo.0.lock().unwrap().clone()).unwrap();
assert_eq!(echoed, read(dir.path(), "arena-tracker.log"));
assert_eq!(echoed.lines().count(), 2);
}
#[test]
fn a_key_or_a_full_puuid_in_a_line_is_masked() {
let dir = tempfile::tempdir().unwrap();
let journal = Journal::open(dir.path(), None, || {}).unwrap();
let key = "RGAPI-12345678-abcd-ef01-2345-6789abcdef01";
let puuid = "a1b2c3d4".repeat(9) + "-_";
write(
&journal,
&format!("key {key}, puuid {puuid}, id Joueur#EUW, EUW1_7"),
);
drain(&journal);
let text = read(dir.path(), "arena-tracker.log");
assert!(!text.contains(key) && !text.contains(&puuid), "{text}");
assert!(
text.contains("RGAPI-12…, puuid a1b2c3d4…, id Joueur#EUW, EUW1_7"),
"{text}"
);
}
#[test]
fn a_folder_that_cannot_be_created_is_an_error_not_a_panic() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("file");
fs::write(&file, "").unwrap();
assert!(Journal::open(&file.join("logs"), None, || {}).is_err());
}
#[test]
fn a_failed_rotation_keeps_writing_to_the_current_file() {
let dir = tempfile::tempdir().unwrap();
// A non-empty folder where the old file goes: the rename fails.
let old = dir.path().join("arena-tracker.1.log");
fs::create_dir(&old).unwrap();
fs::write(old.join("held"), "").unwrap();
let journal = Journal::open(dir.path(), None, || {}).unwrap();
let line = format!("{}end", "word ".repeat(200));
for i in 0..1500 {
write(&journal, &format!("{i} {line}"));
}
write(&journal, "the last line");
drain(&journal);
let text = read(dir.path(), "arena-tracker.log");
assert!(text.contains(" 0 word") && text.contains(" 1499 word"));
assert!(text.ends_with("the last line\n"));
}
#[test]
fn only_the_app_s_lines_and_other_libraries_errors_are_taken() {
let dir = tempfile::tempdir().unwrap();
let journal = Journal::open(dir.path(), None, || {}).unwrap();
let enabled =
|level, target| journal.enabled(&Metadata::builder().level(level).target(target).build());
assert!(enabled(Level::Info, "arena_tracker"));
assert!(enabled(Level::Warn, "arena_tracker_core::riot"));
assert!(!enabled(Level::Debug, "arena_tracker"));
assert!(!enabled(Level::Trace, "arena_tracker"));
// A library's info or warning may come per frame; its errors are kept.
assert!(!enabled(Level::Info, "gpui::window"));
assert!(!enabled(Level::Warn, "gpui::window"));
assert!(enabled(Level::Error, "gpui::window"));
// The HTTP client's lines may hold the URL or the key.
assert!(!enabled(Level::Info, "ureq::unversioned::transport"));
assert!(!enabled(Level::Error, "ureq"));
}
+4
View File
@@ -264,6 +264,7 @@ impl GameClientSource for LeagueClient {
*events = self.connect();
// Re-read the snapshot after subscribing.
if events.is_some() {
log::info!("League client: found");
return ClientEvent::Other;
}
}
@@ -299,6 +300,9 @@ impl GameClientSource for LeagueClient {
if matches!(e.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut) => {}
Err(_) => *events = None,
}
if events.is_none() {
log::info!("League client: gone");
}
return ClientEvent::Other;
}
}
+2
View File
@@ -9,6 +9,7 @@ mod end_of_game;
mod error;
mod follow;
mod game_data;
mod journal;
mod league_client;
mod model;
mod recap;
@@ -38,6 +39,7 @@ pub use follow::{
riot_id, same_riot_id,
};
pub use game_data::{Augment, CatalogDisplay, CatalogSource, GameCatalog, GameData, HttpCatalog};
pub use journal::init as init_journal;
pub use league_client::{LeagueClient, decode_gameflow};
pub use model::{Account, FollowedMatch, Format, Match, MatchEnd, SyncProgress, SyncReport};
pub use recap::{DamageByType, MatchRecap, RecapPlayer, RecapTeam};
+3 -1
View File
@@ -106,10 +106,12 @@ pub struct FollowedMatch {
pub end: MatchEnd,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct SyncProgress {
pub fetched: usize,
pub to_fetch: usize,
/// Set while the import waits for the Riot quota: how long from now.
pub quota_wait: Option<std::time::Duration>,
}
#[derive(Clone, Debug)]
+3 -1
View File
@@ -82,7 +82,7 @@ impl Tracker {
pub fn match_recap(&self, puuid: &str, match_id: &str) -> Result<Option<MatchRecap>, Error> {
// The lock is released before the decoding.
let row = rusqlite::OptionalExtension::optional(self.db().query_row(
"SELECT raw, provisional, queue_id, started_at_ms, champion_id FROM matches
"SELECT raw, provisional, queue_id, started_at_ms, champion_id, placement FROM matches
WHERE puuid = ?1 AND match_id = ?2",
[puuid, match_id],
|row| {
@@ -91,6 +91,7 @@ impl Tracker {
queue_id: row.get(2)?,
started_at_ms: row.get(3)?,
champion_id: row.get(4)?,
placement: row.get(5)?,
};
Ok((row.get::<_, String>(0)?, row.get::<_, bool>(1)?, stored))
},
@@ -117,6 +118,7 @@ struct Stored {
queue_id: u32,
started_at_ms: i64,
champion_id: u32,
placement: u8,
}
#[derive(Deserialize)]
+6 -4
View File
@@ -7,13 +7,14 @@ use crate::end_of_game::{self, BlockPlayer};
use crate::model::Format;
/// `None` when the block is not readable. The Account's player is the one with the Match's
/// champion: the block's PUUIDs are the client's, and a champion is picked once per Arena game.
/// champion and Placement: the block's PUUIDs are the client's, and teammates never share a
/// champion (two players of another team may).
pub(super) fn decode(raw: &str, stored: &Stored, catalog: &[Champion]) -> Option<MatchRecap> {
let block = end_of_game::decode(raw)?;
let duration_s = block.duration_s;
let players = block.players.into_iter().map(|p| {
let (subteam, placement) = (p.subteam_id, p.placement);
(subteam, placement, player(p, stored.champion_id, catalog))
(subteam, placement, player(p, stored, catalog))
});
Some(MatchRecap {
match_id: stored.match_id.clone(),
@@ -26,7 +27,7 @@ pub(super) fn decode(raw: &str, stored: &Stored, catalog: &[Champion]) -> Option
})
}
fn player(p: BlockPlayer, account_champion: u32, catalog: &[Champion]) -> RecapPlayer {
fn player(p: BlockPlayer, stored: &Stored, catalog: &[Champion]) -> RecapPlayer {
let champion_id = p.champion_id.unwrap_or(0);
// The key, as a Riot payload names the champion.
let champion_name = (catalog.iter().find(|c| c.id == champion_id))
@@ -34,7 +35,8 @@ fn player(p: BlockPlayer, account_champion: u32, catalog: &[Champion]) -> RecapP
.or_else(|| p.champion_name.clone())
.unwrap_or_default();
RecapPlayer {
is_account: p.champion_id == Some(account_champion),
is_account: p.champion_id == Some(stored.champion_id)
&& p.placement == Some(stored.placement),
riot_id: p.riot_id(),
puuid: p.puuid,
champion_id,
+78 -164
View File
@@ -1,6 +1,3 @@
use std::collections::VecDeque;
use std::sync::{Mutex, PoisonError};
use std::thread;
use std::time::{Duration, Instant};
use serde::Deserialize;
@@ -10,72 +7,64 @@ use crate::error::SourceError;
use crate::model::Account;
use crate::tracker::MatchHistorySource;
/// Personal-key limits: (requests, window).
const LIMITS: [(usize, Duration); 2] = [
(20, Duration::from_secs(1)),
(100, Duration::from_secs(120)),
];
const DEFAULT_RETRY_AFTER: Duration = Duration::from_secs(10);
/// The relay's longest quota window: asking again sooner is harmless, the relay answers 429
/// again with what is left.
const MAX_RETRY_AFTER_S: u64 = 600;
/// Riot web API adapter. Deliberately has no `Debug`: it holds the API key.
/// The Riot web API through the Arena Tracker relay, which holds the key and the quota
/// (ADR-0008): no key is ever sent.
pub struct RiotApi {
key: Mutex<String>,
/// The routing value, e.g. "europe".
/// The regional routing value, e.g. "europe".
region: String,
host: String,
/// The relay's address, without a trailing slash.
relay: String,
agent: Agent,
/// Send times of recent requests, oldest first.
sent: Mutex<VecDeque<Instant>>,
}
impl RiotApi {
/// `region` is the routing value, e.g. "europe".
pub fn new(api_key: String, region: &str) -> RiotApi {
/// `relay` is the relay's address, e.g. "https://arena-tracker.nessar.fr"; `region` the
/// regional routing value, e.g. "europe".
pub fn new(relay: &str, region: &str) -> RiotApi {
RiotApi {
key: Mutex::new(api_key),
region: region.to_ascii_lowercase(),
host: format!("https://{region}.api.riotgames.com"),
relay: relay.trim_end_matches('/').into(),
agent: agent(),
sent: Mutex::new(VecDeque::new()),
}
}
/// Replaces the key used by all later requests.
pub fn set_key(&self, api_key: String) {
*self.key.lock().unwrap_or_else(PoisonError::into_inner) = api_key;
}
fn get(&self, path_and_query: &str) -> Result<String, SourceError> {
self.get_on(&self.host, path_and_query, &|| {})
}
fn get_on(
/// The relay's URL is `/{routing}{Riot path}`, `routing` being this call's routing value: the
/// region, or a platform (e.g. "euw1"). `kind` names the call in the log: the URL may hold a
/// full PUUID and is never logged.
fn get(
&self,
host: &str,
kind: &str,
routing: &str,
path_and_query: &str,
before_send: &dyn Fn(),
) -> Result<String, SourceError> {
let key = self
.key
.lock()
.unwrap_or_else(PoisonError::into_inner)
.clone();
if key.is_empty() {
return Err(SourceError::MissingKey);
}
loop {
before_send();
let wait = reserve_slot(
&mut self.sent.lock().unwrap_or_else(PoisonError::into_inner),
Instant::now(),
);
if wait.is_zero() {
break;
}
thread::sleep(wait);
}
let url = format!("{host}{path_and_query}");
get(&self.agent, &url, Some(&key), |body| body.read_to_string())
before_send();
let url = format!("{}/{routing}{path_and_query}", self.relay);
let started = Instant::now();
let result = get(&self.agent, &url, |body| body.read_to_string());
log_call(kind, &result, started.elapsed());
result
}
}
/// One line per call: type, outcome and duration. A missing Match is expected (info); any other
/// failure is a warning.
fn log_call(kind: &str, result: &Result<String, SourceError>, took: Duration) {
let ms = took.as_millis();
match result {
Ok(_) => log::info!("Riot {kind}: ok in {ms} ms"),
Err(SourceError::NotFound) => log::info!("Riot {kind}: not found (404) in {ms} ms"),
Err(SourceError::RateLimited { retry_after }) => log::warn!(
"Riot {kind}: rate limited (429), Retry-After {} s, in {ms} ms",
retry_after.as_secs()
),
Err(SourceError::Refused) => log::warn!("Riot {kind}: refused (401/403) in {ms} ms"),
Err(e) => log::warn!("Riot {kind}: {e} in {ms} ms"),
}
}
@@ -89,24 +78,19 @@ pub(crate) fn agent() -> Agent {
.into()
}
/// GETs `url` (sending the Riot token when given) and reads a successful body with `read`;
/// other statuses become `SourceError`s.
/// GETs `url` and reads a successful body with `read`; other statuses become `SourceError`s.
pub(crate) fn get<T>(
agent: &Agent,
url: &str,
riot_token: Option<&str>,
read: impl FnOnce(&mut Body) -> Result<T, ureq::Error>,
) -> Result<T, SourceError> {
let mut request = agent.get(url);
if let Some(token) = riot_token {
request = request.header("X-Riot-Token", token);
}
let mut response = request
let mut response = agent
.get(url)
.call()
.map_err(|e| SourceError::Network(e.to_string()))?;
match response.status().as_u16() {
200..=299 => read(response.body_mut()).map_err(|e| SourceError::Network(e.to_string())),
401 | 403 => Err(SourceError::InvalidKey),
401 | 403 => Err(SourceError::Refused),
404 => Err(SourceError::NotFound),
429 => Err(SourceError::RateLimited {
retry_after: response
@@ -114,8 +98,14 @@ pub(crate) fn get<T>(
.get("retry-after")
.and_then(|v| v.to_str().ok())
.and_then(|v| v.trim().parse().ok())
.map_or(DEFAULT_RETRY_AFTER, Duration::from_secs),
// At least a second, so a 429 waited out as often as it comes never spins; at
// most the cap, so one 429 never parks an import for a day.
.map_or(DEFAULT_RETRY_AFTER, |s: u64| {
Duration::from_secs(s.clamp(1, MAX_RETRY_AFTER_S))
}),
}),
// Any 5xx, e.g. Cloudflare's 52x when the relay behind it is down.
500..=599 => Err(SourceError::Unavailable),
status => Err(SourceError::Other(format!("HTTP {status}"))),
}
}
@@ -127,7 +117,7 @@ impl MatchHistorySource for RiotApi {
encode(game_name),
encode(tag_line)
);
decode_account(&self.get(&path)?)
decode_account(&self.get("account-by-riot-id", &self.region, &path, &|| {})?)
}
fn match_ids(
@@ -157,7 +147,7 @@ impl MatchHistorySource for RiotApi {
if let Some(t) = start_time_s {
path.push_str(&format!("&startTime={t}"));
}
decode_ids(&self.get_on(&self.host, &path, before_send)?)
decode_ids(&self.get("match-ids", &self.region, &path, before_send)?)
}
fn fetch_match(&self, match_id: &str) -> Result<String, SourceError> {
@@ -169,22 +159,25 @@ impl MatchHistorySource for RiotApi {
match_id: &str,
before_send: &dyn Fn(),
) -> Result<String, SourceError> {
self.get_on(
&self.host,
self.get(
"match",
&self.region,
&format!("/lol/match/v5/matches/{}", encode(match_id)),
before_send,
)
}
/// Same regional host and limiter as the Match; Riot answers 403 for some Matches.
/// Same routing value as the Match; Riot answers 403 for some Matches.
fn fetch_timeline(&self, match_id: &str) -> Result<String, SourceError> {
self.get(&format!(
"/lol/match/v5/matches/{}/timeline",
encode(match_id)
))
self.get(
"timeline",
&self.region,
&format!("/lol/match/v5/matches/{}/timeline", encode(match_id)),
&|| {},
)
}
/// Mastery lives on the platform host (e.g. `euw1`), not on the regional one.
/// Mastery is routed by platform (e.g. `euw1`), not by region.
fn champion_mastery(
&self,
platform: &str,
@@ -204,24 +197,21 @@ impl MatchHistorySource for RiotApi {
"Plateforme invalide : {platform}"
)));
}
let host = format!(
"https://{}.api.riotgames.com",
platform.to_ascii_lowercase()
);
let path = format!(
"/lol/champion-mastery/v4/champion-masteries/by-puuid/{}",
encode(puuid)
);
decode_mastery(&self.get_on(&host, &path, before_send)?)
let platform = platform.to_ascii_lowercase();
decode_mastery(&self.get("mastery", &platform, &path, before_send)?)
}
/// Asked on the routing host, like the Account itself.
/// Routed by region, like the Account itself.
fn account_platform(&self, puuid: &str) -> Result<String, SourceError> {
let path = format!(
"/riot/account/v1/region/by-game/lol/by-puuid/{}",
encode(puuid)
);
decode_platform(&self.get(&path)?)
decode_platform(&self.get("platform", &self.region, &path, &|| {})?)
}
fn serves_platform(&self, platform: &str) -> bool {
@@ -229,7 +219,7 @@ impl MatchHistorySource for RiotApi {
}
}
/// A platform id goes into a host name: nothing but letters and digits goes through.
/// A platform id is the relay's routing value: nothing but letters and digits goes through.
pub(crate) fn valid_platform(platform: &str) -> bool {
!platform.is_empty() && platform.bytes().all(|b| b.is_ascii_alphanumeric())
}
@@ -295,57 +285,21 @@ pub(crate) fn encode(segment: &str) -> String {
out
}
/// Takes an available slot, or returns when to compete for it again.
fn reserve_slot(sent: &mut VecDeque<Instant>, now: Instant) -> Duration {
let longest = LIMITS[1].1;
while sent
.front()
.is_some_and(|&t| now.saturating_duration_since(t) >= longest)
{
sent.pop_front();
}
// A window of `max` requests is full when `max` requests are booked inside it; the new
// one may go once the oldest of them leaves.
let wait = LIMITS
.iter()
.filter(|&&(max, _)| sent.len() >= max)
.map(|&(max, window)| (sent[sent.len() - max] + window).saturating_duration_since(now))
.max()
.unwrap_or_default();
if wait.is_zero() {
sent.push_back(now);
}
wait
}
#[cfg(test)]
mod call_log;
#[cfg(test)]
mod requests;
#[cfg(test)]
mod test_server;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn without_a_key_no_request_is_sent() {
let api = RiotApi::new(String::new(), "europe");
assert_eq!(
api.resolve_account("Joueur", "EUW"),
Err(SourceError::MissingKey)
);
assert_eq!(
api.match_ids("p", 1700, 0, 100, None),
Err(SourceError::MissingKey)
);
assert_eq!(api.fetch_match("EUW1_1"), Err(SourceError::MissingKey));
assert_eq!(api.fetch_timeline("EUW1_1"), Err(SourceError::MissingKey));
assert_eq!(
api.champion_mastery("EUW1", "p"),
Err(SourceError::MissingKey)
);
assert_eq!(api.account_platform("p"), Err(SourceError::MissingKey));
}
#[test]
fn an_invalid_platform_is_rejected_without_a_request() {
// With a key, a request would be attempted (and fail on the network, not as `Other`).
let api = RiotApi::new("RGAPI-test".into(), "europe");
// Nothing listens there: a request would fail on the network, not as `Other`.
let api = RiotApi::new("http://127.0.0.1:9", "europe");
for platform in ["", "euw1.evil.example/", "eu w1", "euw1@host", "é"] {
assert!(
matches!(
@@ -355,16 +309,6 @@ mod tests {
"{platform:?}"
);
}
assert!(api.sent.lock().unwrap().is_empty());
}
#[test]
fn the_key_can_be_replaced_without_rebuilding_the_adapter() {
let api = RiotApi::new(String::new(), "europe");
api.set_key("RGAPI-new".into());
assert_eq!(*api.key.lock().unwrap(), "RGAPI-new");
api.set_key(String::new());
assert_eq!(api.fetch_match("EUW1_1"), Err(SourceError::MissingKey));
}
#[test]
@@ -410,7 +354,7 @@ mod tests {
}
assert_eq!(routing_region("pbe1"), None);
let api = RiotApi::new(String::new(), "Europe");
let api = RiotApi::new("", "Europe");
assert!(api.serves_platform("euw1"));
assert!(api.serves_platform("EUN1"));
assert!(!api.serves_platform("NA1"));
@@ -431,34 +375,4 @@ mod tests {
assert_eq!(encode("Joueur"), "Joueur");
assert_eq!(encode("Été #1/é"), "%C3%89t%C3%A9%20%231%2F%C3%A9");
}
#[test]
fn throttle_spaces_requests_under_both_limits() {
let t0 = Instant::now();
let mut sent = VecDeque::new();
for _ in 0..20 {
assert_eq!(reserve_slot(&mut sent, t0), Duration::ZERO);
}
// 21st request waits for the 1 s window.
assert_eq!(reserve_slot(&mut sent, t0), Duration::from_secs(1));
// Waiting did not book a future slot: the follower can take it first.
assert_eq!(sent.len(), 20);
assert_eq!(
reserve_slot(&mut sent, t0 + Duration::from_secs(1)),
Duration::ZERO
);
// 100 requests fit in 120 s: spread over time so only the long window is full.
let mut sent = VecDeque::new();
for i in 0..100u64 {
let now = t0 + Duration::from_secs(i);
assert_eq!(reserve_slot(&mut sent, now), Duration::ZERO);
}
let now = t0 + Duration::from_secs(100);
assert_eq!(reserve_slot(&mut sent, now), Duration::from_secs(20));
// Once the oldest request left the window, no wait is needed.
let later = t0 + Duration::from_secs(121);
assert_eq!(reserve_slot(&mut sent, later), Duration::ZERO);
}
}
+82
View File
@@ -0,0 +1,82 @@
//! What a Riot call writes to the application log: its type, outcome and duration, never its
//! URL (it may hold a full PUUID).
use super::test_server::{response, serve};
use super::*;
use crate::journal::capture::captured;
#[test]
fn calls_are_logged_by_type_and_outcome_without_url() {
let (relay, _) = serve([
response("200 OK", &[], "[]"),
response("404 Not Found", &[], ""),
response("429 Too Many Requests", &["Retry-After: 7"], ""),
]);
let api = RiotApi::new(&relay, "europe");
let puuid = "p".repeat(78);
// The HTTP client's own debug and trace lines hold the URL: the journal never takes them
// (info and above, not `ureq`).
let (_, lines) = captured(|| {
api.match_ids(&puuid, 1700, 0, 100, None).unwrap();
assert_eq!(api.fetch_match("EUW1_1"), Err(SourceError::NotFound));
assert!(api.account_platform(&puuid).is_err());
});
let lines: Vec<_> = lines
.iter()
.filter(|l| l.starts_with("INFO") || l.starts_with("WARN"))
.collect();
assert_eq!(lines.len(), 3, "{lines:#?}");
assert!(
lines[0].starts_with("INFO Riot match-ids: ok in "),
"{lines:#?}"
);
assert!(
lines[1].starts_with("INFO Riot match: not found (404) in "),
"{lines:#?}"
);
assert!(
lines[2].starts_with("WARN Riot platform: rate limited (429), Retry-After 7 s, in "),
"{lines:#?}"
);
for line in lines {
for secret in [&puuid, "127.0.0.1", "/lol/", "EUW1_1"] {
assert!(!line.contains(secret), "{secret}: {line}");
}
}
}
#[test]
fn a_whole_sync_never_logs_a_full_puuid() {
let puuid = "q".repeat(78);
let ok = |body: &str| response("200 OK", &[], body);
let (relay, _) = serve([
ok(&format!(
r#"{{"puuid":"{puuid}","gameName":"Joueur","tagLine":"EUW"}}"#
)),
// One list per Arena queue, then the listed Match, which Riot does not have.
ok(r#"["EUW1_1"]"#),
ok("[]"),
ok("[]"),
ok("[]"),
response("404 Not Found", &[], ""),
]);
let api = RiotApi::new(&relay, "europe");
let tracker = crate::Tracker::open(std::path::Path::new(":memory:"), Box::new(api)).unwrap();
let (synced, lines) = captured(|| tracker.sync("Joueur#EUW", &mut |_| {}));
// What the journal takes: the HTTP client's own lines never reach it.
let lines: Vec<_> = lines
.into_iter()
.filter(|l| l.starts_with("INFO") || l.starts_with("WARN") || l.starts_with("ERROR"))
.collect();
assert!(synced.is_ok(), "{synced:?}: {lines:#?}");
assert!(
lines.iter().any(|l| l.contains("Sync of Joueur#EUW done")),
"{lines:#?}"
);
for line in &lines {
assert!(!line.contains(&puuid), "{line}");
}
}
+83
View File
@@ -0,0 +1,83 @@
//! What the app asks the relay: each call under its routing value, never with a key; and the
//! relay's answers the app tells apart.
use std::time::Duration;
use super::test_server::{response, serve};
use super::*;
fn status(line: &str) -> String {
response(line, &[], "")
}
#[test]
fn each_call_goes_to_the_relay_under_its_routing_value_without_a_key() {
let (relay, heads) = serve(vec![status("404 Not Found"); 6]);
// A configured address may end with a slash; the region may be in capitals.
let api = RiotApi::new(&format!("{relay}/"), "Europe");
let _ = api.resolve_account("Le Joueur", "EUW");
let _ = api.account_platform("p");
let _ = api.match_ids("p", 1750, 0, 100, Some(1_700_000_000));
let _ = api.fetch_match("EUW1_1");
let _ = api.fetch_timeline("EUW1_1");
let _ = api.champion_mastery("EUW1", "p");
let heads: Vec<String> = heads.iter().take(6).collect();
let lines: Vec<&str> = heads.iter().filter_map(|h| h.lines().next()).collect();
assert_eq!(
lines,
[
"GET /europe/riot/account/v1/accounts/by-riot-id/Le%20Joueur/EUW HTTP/1.1",
"GET /europe/riot/account/v1/region/by-game/lol/by-puuid/p HTTP/1.1",
"GET /europe/lol/match/v5/matches/by-puuid/p/ids?queue=1750&start=0&count=100&startTime=1700000000 HTTP/1.1",
"GET /europe/lol/match/v5/matches/EUW1_1 HTTP/1.1",
"GET /europe/lol/match/v5/matches/EUW1_1/timeline HTTP/1.1",
"GET /euw1/lol/champion-mastery/v4/champion-masteries/by-puuid/p HTTP/1.1",
]
);
for head in &heads {
assert!(
!head.to_ascii_lowercase().contains("x-riot-token"),
"{head}"
);
}
}
#[test]
fn the_relays_answers_are_told_apart() {
let (relay, _) = serve([
status("503 Service Unavailable"),
status("502 Bad Gateway"),
// Cloudflare's, when the relay behind it is down.
status("522 Origin Connection Time-out"),
status("403 Forbidden"),
response("429 Too Many Requests", &["Retry-After: 12"], ""),
response("429 Too Many Requests", &["Retry-After: 0"], ""),
// The relay forwards up to a day.
response("429 Too Many Requests", &["Retry-After: 86400"], ""),
]);
let api = RiotApi::new(&relay, "europe");
for _ in 0..3 {
assert_eq!(api.fetch_match("EUW1_1"), Err(SourceError::Unavailable));
}
assert_eq!(api.fetch_timeline("EUW1_1"), Err(SourceError::Refused));
assert_eq!(
api.fetch_match("EUW1_1"),
Err(SourceError::RateLimited {
retry_after: Duration::from_secs(12)
})
);
assert_eq!(
api.fetch_match("EUW1_1"),
Err(SourceError::RateLimited {
retry_after: Duration::from_secs(1)
})
);
assert_eq!(
api.fetch_match("EUW1_1"),
Err(SourceError::RateLimited {
retry_after: Duration::from_secs(MAX_RETRY_AFTER_S)
})
);
}
+42
View File
@@ -0,0 +1,42 @@
//! A stand-in for the relay in the riot suites: canned HTTP responses on a local port.
use std::io::{Read, Write};
use std::net::TcpListener;
use std::sync::mpsc::{self, Receiver};
use std::thread;
/// Answers each connection with the next response, then closes it. Gives the address, and the
/// head of each request as it arrives.
pub(super) fn serve<S, I>(responses: I) -> (String, Receiver<String>)
where
S: AsRef<str>,
I: IntoIterator<Item = S> + Send + 'static,
{
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let host = format!("http://{}", listener.local_addr().unwrap());
let (heads, received) = mpsc::channel();
thread::spawn(move || {
for response in responses {
let (mut stream, _) = listener.accept().unwrap();
let mut head = Vec::new();
let mut buf = [0; 4096];
while !head.ends_with(b"\r\n\r\n") {
match stream.read(&mut buf) {
Ok(0) | Err(_) => break,
Ok(n) => head.extend_from_slice(&buf[..n]),
}
}
let _ = heads.send(String::from_utf8_lossy(&head).into_owned());
let _ = stream.write_all(response.as_ref().as_bytes());
}
});
(host, received)
}
/// An HTTP response with this status (e.g. "429 Too Many Requests"), header lines and body.
pub(super) fn response(status: &str, headers: &[&str], body: &str) -> String {
let headers: String = headers.iter().map(|h| format!("{h}\r\n")).collect();
format!(
"HTTP/1.1 {status}\r\n{headers}Content-Length: {}\r\nConnection: close\r\n\r\n{body}",
body.len()
)
}
+38 -88
View File
@@ -5,21 +5,24 @@ mod deletion;
mod directory;
pub use directory::AccountDirectory;
mod friends;
mod import;
mod mastery;
mod payload;
mod provisional;
mod rekey;
mod storage;
pub(crate) use blocks::StoredBlock;
pub use deletion::AccountSummary;
pub use friends::{AddFriendError, AddedFriend};
use payload::decode_match;
use std::collections::HashSet;
use std::collections::{HashMap, HashSet};
use std::ops::Range;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError};
use std::thread;
use std::time::Duration;
use storage::store_match;
use rusqlite::{Connection, OptionalExtension, Row, params};
@@ -32,10 +35,7 @@ use crate::follow::Follow;
use crate::model::{Account, Format, Match, SyncProgress, SyncReport};
use crate::seasons::{Season, default_seasons};
/// Arena queues Riot lists Matches under (the PBE queue 1704 is left out on purpose).
const QUEUES: [u32; 4] = [1700, 1710, 1740, 1750];
const PAGE_SIZE: usize = 100;
const RATE_LIMIT_RETRIES: usize = 5;
/// A Match is published when the whole game ends, so one that started before the newest
/// stored Match (a player eliminated early who queued again) can show up later.
const OVERLAP_S: i64 = 48 * 3600;
@@ -58,6 +58,8 @@ pub struct Tracker {
corrections: AtomicUsize,
/// Captured before selecting an account. A later deletion invalidates an in-flight lookup.
deletions: AtomicUsize,
/// The PUUIDs replaced since the tracker opened, old to new (`replaced_puuid`).
replaced: Mutex<HashMap<String, String>>,
/// Followed Matches whose Death Recap is to be fetched, for the app's background thread.
pub(crate) death_recaps: DeathRecapQueue,
}
@@ -78,6 +80,7 @@ impl Tracker {
sync_lock: Mutex::new(()),
corrections: AtomicUsize::new(0),
deletions: AtomicUsize::new(0),
replaced: Mutex::default(),
death_recaps: DeathRecapQueue::default(),
})
}
@@ -108,8 +111,14 @@ impl Tracker {
.unwrap_or_else(PoisonError::into_inner);
let (game_name, tag_line) =
split_riot_id(riot_id).ok_or_else(|| Error::InvalidRiotId(riot_id.into()))?;
let account = with_retry(|| self.history.resolve_account(game_name, tag_line))?;
// shortcut: Riot API puuids are scoped to the API key's application, so the same Riot ID under another key becomes a second Account; merging them safely needs proof of identity.
log::info!("Sync of {riot_id} started");
let account = import::told(SyncProgress::default(), on_progress, |on_wait| {
with_retry_told(
|| self.history.resolve_account(game_name, tag_line),
on_wait,
)
})?;
self.rekey(&account, &|| {})?;
{
let db = self.db();
if self.deletion_count() != deletions
@@ -141,6 +150,7 @@ impl Tracker {
let stored = self.match_count(&account.puuid)?;
self.clear_problem(added);
self.follow().synced();
log::info!("Sync of {riot_id} done: {added} added, {stored} stored");
Ok(SyncReport {
account,
added,
@@ -152,7 +162,7 @@ impl Tracker {
/// A Match Riot does not have or that cannot be read is skipped rather than failing the
/// caller: one bad id must not block the rest.
pub(crate) fn fetch_and_store(&self, puuid: &str, match_id: &str) -> Result<Fetched, Error> {
self.fetch_match_when(puuid, match_id, &|| {})
self.fetch_match_when(puuid, match_id, &|| {}, &mut |_| {})
}
fn fetch_match_when(
@@ -160,8 +170,10 @@ impl Tracker {
puuid: &str,
match_id: &str,
before_send: &dyn Fn(),
on_wait: &mut dyn FnMut(Duration),
) -> Result<Fetched, Error> {
let raw = match with_retry(|| self.history.fetch_match_when(match_id, before_send)) {
let fetch = || self.history.fetch_match_when(match_id, before_send);
let raw = match with_retry_told(fetch, on_wait) {
Ok(raw) => raw,
Err(SourceError::NotFound) => return Ok(Fetched::NotFound),
Err(e) => return Err(e.into()),
@@ -313,7 +325,7 @@ impl Tracker {
}
/// The ids of the Account's published Matches.
fn match_ids_stored(&self, puuid: &str) -> Result<HashSet<String>, Error> {
pub(super) fn match_ids_stored(&self, puuid: &str) -> Result<HashSet<String>, Error> {
let db = self.db();
let mut stmt =
db.prepare("SELECT match_id FROM matches WHERE puuid = ?1 AND provisional = 0")?;
@@ -322,80 +334,6 @@ impl Tracker {
.collect::<Result<_, _>>()?;
Ok(ids)
}
/// Downloads each missing Match once across the ordered listing steps.
fn import_matches(
&self,
puuid: &str,
steps: impl IntoIterator<Item = Option<i64>>,
friend_gate: Option<&dyn Fn()>,
on_progress: &mut dyn FnMut(SyncProgress),
) -> Result<usize, Error> {
let before_send = friend_gate.unwrap_or(&|| {});
let friend = friend_gate.is_some();
let mut known = self.match_ids_stored(puuid)?;
let mut progress = SyncProgress {
fetched: 0,
to_fetch: 0,
};
let mut added = 0;
for (step, since_s) in steps.into_iter().enumerate() {
let mut to_fetch = self.list_match_ids(puuid, since_s, friend_gate)?;
if step == 0 {
// Looked for until Riot publishes them, like a sync does.
to_fetch.extend(self.provisional_ids(puuid)?);
}
to_fetch.retain(|id| known.insert(id.clone()));
progress.to_fetch += to_fetch.len();
on_progress(progress);
for match_id in &to_fetch {
if friend {
self.stored_account(puuid)?;
}
if self.fetch_match_when(puuid, match_id, before_send)? == Fetched::Added {
added += 1;
}
progress.fetched += 1;
on_progress(progress);
}
}
Ok(added)
}
/// Lists every queue, yielding to higher-priority requests at each dispatch.
fn list_match_ids(
&self,
puuid: &str,
since_s: Option<i64>,
friend_gate: Option<&dyn Fn()>,
) -> Result<Vec<String>, Error> {
let mut ids = Vec::new();
for queue_id in QUEUES {
let mut start = 0;
loop {
if friend_gate.is_some() {
self.stored_account(puuid)?;
}
let page = with_retry(|| {
self.history.match_ids_when(
puuid,
queue_id,
start,
PAGE_SIZE,
since_s,
friend_gate.unwrap_or(&|| {}),
)
})?;
let full_page = page.len() == PAGE_SIZE;
ids.extend(page);
if !full_page {
break;
}
start += PAGE_SIZE;
}
}
Ok(ids)
}
}
pub(crate) fn account_from_row(row: &Row) -> rusqlite::Result<Account> {
@@ -450,17 +388,29 @@ pub(crate) enum Fetched {
Published,
}
/// Waits out `RateLimited` and retries the same call, giving up after a few attempts.
/// Waits out each `RateLimited` and retries the same call, as many times as needed: a full
/// quota frees up in time, and an import must not stop for it. The source bounds each wait
/// (at least a second, at most ten minutes, see `SourceError::RateLimited`).
pub(crate) fn with_retry<T>(
mut call: impl FnMut() -> Result<T, SourceError>,
call: impl FnMut() -> Result<T, SourceError>,
) -> Result<T, SourceError> {
for _ in 0..RATE_LIMIT_RETRIES {
with_retry_told(call, &mut |_| {})
}
/// `with_retry` that tells each wait to `on_wait` before sleeping it.
pub(crate) fn with_retry_told<T>(
mut call: impl FnMut() -> Result<T, SourceError>,
on_wait: &mut dyn FnMut(Duration),
) -> Result<T, SourceError> {
loop {
match call() {
Err(SourceError::RateLimited { retry_after }) => thread::sleep(retry_after),
Err(SourceError::RateLimited { retry_after }) => {
on_wait(retry_after);
thread::sleep(retry_after);
}
result => return result,
}
}
call()
}
#[cfg(test)]
+35 -14
View File
@@ -1,12 +1,13 @@
//! Friends: Accounts added by their Riot ID to view their Challenge. Their Matches come from
//! the Riot API alone, with the user's key: `import_friend` imports them on the app's
//! the Riot API alone, through the relay: `import_friend` imports them on the app's
//! background thread, each request after the active Account's. A Friend who signs in to the
//! client stays a Friend; the follower then keeps it up to date like any active Account, and
//! the two may fetch the same Match at once: the second store of a Match changes nothing.
use rusqlite::{OptionalExtension, params};
use super::{OVERLAP_S, Tracker, account_from_row, split_riot_id, with_retry};
use super::import::told;
use super::{OVERLAP_S, Tracker, account_from_row, split_riot_id, with_retry, with_retry_told};
use crate::error::{Error, SourceError};
use crate::follow::{UpdateProblem, account_riot_id, riot_id, same_riot_id, wall_clock_ms};
use crate::model::{Account, SyncProgress, SyncReport};
@@ -28,11 +29,9 @@ pub enum AddFriendError {
Malformed,
/// No Account has this Riot ID, or it has never played League of Legends.
NotFound,
/// It plays in another region than the key reads: its Matches cannot be imported.
/// It plays in another region than the app reads: its Matches cannot be imported.
OtherRegion,
/// No Riot API key is configured yet.
MissingKey,
/// Riot or the storage failed (a rejected key, the network…): trying again may work.
/// The relay, Riot or the storage failed (the network…): trying again may work.
Failed(Error),
}
@@ -43,9 +42,6 @@ impl AddFriendError {
AddFriendError::Malformed => "Saisissez un Riot ID de la forme Pseudo#TAG.".into(),
AddFriendError::NotFound => "Aucun Compte ne porte ce Riot ID.".into(),
AddFriendError::OtherRegion => "Ce Compte joue dans une autre région.".into(),
AddFriendError::MissingKey => {
"Ajoutez une clé API Riot dans « Paramètres » pour ajouter un Ami.".into()
}
AddFriendError::Failed(e) => match UpdateProblem::from(e) {
UpdateProblem::Other(_) => format!("Ajout impossible : {e}"),
problem => problem.message(),
@@ -58,7 +54,6 @@ impl From<SourceError> for AddFriendError {
fn from(e: SourceError) -> Self {
match e {
SourceError::NotFound => AddFriendError::NotFound,
SourceError::MissingKey => AddFriendError::MissingKey,
e => AddFriendError::Failed(e.into()),
}
}
@@ -148,8 +143,10 @@ impl Tracker {
/// Challenge fills meanwhile. `on_progress` counts the Matches of the whole call: its
/// `to_fetch` grows when the older Matches are listed.
///
/// A new Riot key may have changed its PUUID: that is looked at first (`rekey.rs`).
///
/// Each request waits for the active Account's (a round, a refresh, a finished game's
/// Match not published yet); the shared limiter keeps both within the key's limits. Blocks
/// Match not published yet); the relay keeps both within the quota. Blocks
/// for long: call it from a low-priority background thread, never the follower's. Fails
/// with `Error::UnknownAccount` once the Account is deleted, even during the import.
pub fn import_friend(
@@ -157,7 +154,30 @@ impl Tracker {
puuid: &str,
on_progress: &mut dyn FnMut(SyncProgress),
) -> Result<SyncReport, Error> {
let account = self.stored_account(puuid)?;
let gate = || self.wait_for_follower();
let mut account = self.stored_account(puuid)?;
// Before any request that carries the stored PUUID: a new key may have changed it.
let resolved = told(SyncProgress::default(), on_progress, |on_wait| {
let resolve = || {
gate();
(self.history).resolve_account(&account.game_name, &account.tag_line)
};
with_retry_told(resolve, on_wait)
});
match resolved {
Ok(resolved) if resolved.puuid != account.puuid => {
self.rekey(&resolved, &gate)?;
// Without proof nothing moved: the requested Account stays.
let current = self.replaced_puuid(puuid);
account = self.stored_account(current.as_deref().unwrap_or(puuid))?;
}
// The Riot ID changed: nothing tells the PUUID changed too.
Ok(_) | Err(SourceError::NotFound) => {}
Err(e) => return Err(e.into()),
}
let puuid = account.puuid.as_str();
let who = account_riot_id(&account);
log::info!("Import of {who} started");
let steps = match self.synced_until_ms(puuid)? {
Some(ms) => vec![Some(ms / 1000 - OVERLAP_S)],
None => {
@@ -166,15 +186,16 @@ impl Tracker {
season_start.into_iter().map(Some).chain([None]).collect()
}
};
let gate = || self.wait_for_follower();
let added = self.import_matches(puuid, steps, Some(&gate), on_progress)?;
self.mark_synced(puuid)?;
self.stored_account(puuid)?;
self.refresh_mastery_when(puuid, &gate);
let stored = self.match_count(puuid)?;
log::info!("Import of {who} done: {added} added, {stored} stored");
Ok(SyncReport {
account,
added,
stored: self.match_count(puuid)?,
stored,
})
}
+3 -3
View File
@@ -16,8 +16,8 @@ pub trait MatchHistorySource: Send + Sync {
/// The raw Match payload (JSON text) exactly as the API returned it.
fn fetch_match(&self, match_id: &str) -> Result<String, SourceError>;
/// The raw Match-V5 timeline of a Match (JSON text), of which only the Death Recap entries
/// are kept. Riot refuses it for some Matches (answered like a rejected key); sources that
/// have none answer an error.
/// are kept. Riot refuses it for some Matches (`SourceError::Refused`); sources that have
/// none answer an error.
fn fetch_timeline(&self, _match_id: &str) -> Result<String, SourceError> {
Err(SourceError::NotFound)
}
@@ -67,7 +67,7 @@ pub trait MatchHistorySource: Send + Sync {
self.champion_mastery(platform, puuid)
}
/// Whether this source holds the Matches played on `platform` (in any case): a key reads
/// Whether this source holds the Matches played on `platform` (in any case): the app reads
/// one routing region only.
fn serves_platform(&self, _platform: &str) -> bool {
true
+113
View File
@@ -0,0 +1,113 @@
//! The import of an Account's Matches: listing what is missing, then fetching each Match.
use std::time::Duration;
use super::{Fetched, PAGE_SIZE, Tracker, with_retry_told};
use crate::error::Error;
use crate::model::SyncProgress;
/// Arena queues Riot lists Matches under (the PBE queue 1704 is left out on purpose).
const QUEUES: [u32; 4] = [1700, 1710, 1740, 1750];
/// Runs one request of an import: each Riot quota wait it tells is reported as `progress` with
/// the wait, and the import line comes back (`progress` alone) once the request has answered.
pub(super) fn told<T>(
progress: SyncProgress,
on_progress: &mut dyn FnMut(SyncProgress),
request: impl FnOnce(&mut dyn FnMut(Duration)) -> T,
) -> T {
let mut waited = false;
let result = request(&mut |wait| {
waited = true;
on_progress(SyncProgress {
quota_wait: Some(wait),
..progress
});
});
if waited {
on_progress(progress);
}
result
}
impl Tracker {
/// Downloads each missing Match once across the ordered listing steps.
pub(super) fn import_matches(
&self,
puuid: &str,
steps: impl IntoIterator<Item = Option<i64>>,
friend_gate: Option<&dyn Fn()>,
on_progress: &mut dyn FnMut(SyncProgress),
) -> Result<usize, Error> {
let before_send = friend_gate.unwrap_or(&|| {});
let friend = friend_gate.is_some();
let mut known = self.match_ids_stored(puuid)?;
let mut progress = SyncProgress::default();
let mut added = 0;
for (step, since_s) in steps.into_iter().enumerate() {
let mut to_fetch =
self.list_match_ids(puuid, since_s, friend_gate, progress, on_progress)?;
if step == 0 {
// Looked for until Riot publishes them, like a sync does.
to_fetch.extend(self.provisional_ids(puuid)?);
}
to_fetch.retain(|id| known.insert(id.clone()));
progress.to_fetch += to_fetch.len();
on_progress(progress);
for match_id in &to_fetch {
if friend {
self.stored_account(puuid)?;
}
let fetched = told(progress, on_progress, |on_wait| {
self.fetch_match_when(puuid, match_id, before_send, on_wait)
})?;
if fetched == Fetched::Added {
added += 1;
}
progress.fetched += 1;
on_progress(progress);
}
}
Ok(added)
}
/// Lists every queue, yielding to higher-priority requests at each dispatch.
fn list_match_ids(
&self,
puuid: &str,
since_s: Option<i64>,
friend_gate: Option<&dyn Fn()>,
progress: SyncProgress,
on_progress: &mut dyn FnMut(SyncProgress),
) -> Result<Vec<String>, Error> {
let mut ids = Vec::new();
for queue_id in QUEUES {
let mut start = 0;
loop {
if friend_gate.is_some() {
self.stored_account(puuid)?;
}
let page = told(progress, on_progress, |on_wait| {
let list = || {
self.history.match_ids_when(
puuid,
queue_id,
start,
PAGE_SIZE,
since_s,
friend_gate.unwrap_or(&|| {}),
)
};
with_retry_told(list, on_wait)
})?;
let full_page = page.len() == PAGE_SIZE;
ids.extend(page);
if !full_page {
break;
}
start += PAGE_SIZE;
}
}
Ok(ids)
}
}
+8 -8
View File
@@ -4,7 +4,7 @@ use std::collections::HashMap;
use rusqlite::{OptionalExtension, params};
use super::Tracker;
use super::{Tracker, with_retry};
use crate::error::Error;
impl Tracker {
@@ -33,10 +33,11 @@ impl Tracker {
Ok(Some(points))
}
/// One request for the Account's Mastery Points, on the platform of its latest stored
/// Match, else the one a Friend's region gave (neither: no request). A success replaces the stored list in one transaction;
/// a failure changes nothing, so the last values stay. Called only when the tracker is
/// already talking to Riot about this Account; its errors are not reported anywhere.
/// One request for the Account's Mastery Points (a full quota is waited out), on the
/// platform of its latest stored Match, else the one a Friend's region gave (neither: no
/// request). A success replaces the stored list in one transaction; a failure changes
/// nothing, so the last values stay. Called only when the tracker is already talking to Riot
/// about this Account; its errors are not reported anywhere.
pub(crate) fn refresh_mastery(&self, puuid: &str) {
self.refresh_mastery_when(puuid, &|| {});
}
@@ -45,9 +46,8 @@ impl Tracker {
let Ok(Some(platform)) = self.platform_of(puuid) else {
return;
};
let Ok(list) = self
.history
.champion_mastery_when(&platform, puuid, before_send)
let Ok(list) =
with_retry(|| (self.history).champion_mastery_when(&platform, puuid, before_send))
else {
return;
};
+173
View File
@@ -0,0 +1,173 @@
//! Follows an Account when its PUUID changes: a PUUID depends on the Riot application of the
//! API key, so a new key gives every Account another one for the same Riot ID (#150). A stored
//! Account takes the new PUUID only on proof that it is the same Account, never on the Riot ID
//! alone (a Friend may have been renamed, its name taken by someone else); without proof
//! nothing changes.
use rusqlite::{OptionalExtension, params};
use super::{
OVERLAP_S, PAGE_SIZE, Tracker, friends::platform_key, mastery::mastery_key,
payload::decode_match, synced_until_key, with_retry,
};
use crate::error::{Error, SourceError};
use crate::follow::{account_riot_id, same_riot_id};
use crate::journal::short;
use crate::model::Account;
impl Tracker {
/// The PUUID that replaced this one since the tracker opened: the app uses it to keep
/// showing the same Account.
pub fn replaced_puuid(&self, puuid: &str) -> Option<String> {
let replaced = self.replaced.lock().unwrap_or_else(|e| e.into_inner());
replaced.get(puuid).cloned()
}
/// Moves every stored Account with the Riot ID of `resolved` (what Riot answers now) to its
/// PUUID, when the proof holds (`is_same_account`). `gate` runs before each request of it.
pub(super) fn rekey(&self, resolved: &Account, gate: &dyn Fn()) -> Result<(), Error> {
let riot_id = account_riot_id(resolved);
let stored = self.account_directory();
let stale = (stored.accounts.iter())
.filter(|a| a.puuid != resolved.puuid && same_riot_id(&account_riot_id(a), &riot_id));
for old in stale {
if self.is_same_account(&old.puuid, &resolved.puuid, gate)? {
self.move_puuid(&old.puuid, resolved)?;
}
}
Ok(())
}
/// Whether a published Match stored for `old` is listed for `new` too, and `new` has the
/// same champion and Placement in it: anyone who shared the Match would pass the first, and
/// (champion, Placement) names one participant of an Arena Match (a Placement is a team's,
/// a champion is unique within a team).
fn is_same_account(&self, old: &str, new: &str, gate: &dyn Fn()) -> Result<bool, Error> {
let newest: Option<(u32, i64)> = self
.db()
.query_row(
"SELECT queue_id, started_at_ms FROM matches
WHERE puuid = ?1 AND provisional = 0 ORDER BY started_at_ms DESC LIMIT 1",
[old],
|row| Ok((row.get(0)?, row.get(1)?)),
)
.optional()?;
let Some((queue_id, started_at_ms)) = newest else {
return Ok(false);
};
// shortcut: one page (the 100 newest Matches of that queue since the stored one), so an Account not synced for more than 100 Matches of one queue stays unproven; page through if that ever happens.
let listed = with_retry(|| {
let since_s = Some(started_at_ms / 1000 - OVERLAP_S);
(self.history).match_ids_when(new, queue_id, 0, PAGE_SIZE, since_s, gate)
})?;
let stored = self.match_ids_stored(old)?;
let Some(id) = listed.into_iter().find(|id| stored.contains(id)) else {
return Ok(false);
};
let raw = match with_retry(|| self.history.fetch_match_when(&id, gate)) {
Ok(raw) => raw,
Err(SourceError::NotFound) => return Ok(false),
Err(e) => return Err(e.into()),
};
let Ok(Some((played, _))) = decode_match(&raw, new) else {
return Ok(false);
};
let kept = self.stored_match(old, &id)?;
Ok(kept.is_some_and(|m| {
(m.champion_id, m.placement) == (played.champion_id, played.placement)
}))
}
/// Replaces the PUUID everywhere in one transaction; a new PUUID already stored is merged,
/// its own marks and published Matches winning.
fn move_puuid(&self, old: &str, resolved: &Account) -> Result<(), Error> {
let new = resolved.puuid.as_str();
let mut db = self.db();
let tx = db.transaction()?;
// Another caller may have moved it already, or it was deleted during the proof.
if !(tx.prepare("SELECT 1 FROM accounts WHERE puuid = ?1")?).exists([old])? {
return Ok(());
}
for sql in [
"DELETE FROM matches WHERE puuid = ?2 AND provisional = 1 AND match_id IN
(SELECT match_id FROM matches WHERE puuid = ?1 AND provisional = 0)",
"DELETE FROM matches WHERE puuid = ?1 AND match_id IN
(SELECT match_id FROM matches WHERE puuid = ?2)",
// The stored Riot responses name the Account's participant by PUUID (`match_recap` reads it).
"UPDATE matches SET puuid = ?2, raw = replace(raw, ?1, ?2) WHERE puuid = ?1",
"UPDATE OR IGNORE mastery SET puuid = ?2 WHERE puuid = ?1",
"UPDATE meta SET value = ?2 WHERE name = 'last_active_puuid' AND value = ?1",
] {
tx.execute(sql, params![old, new])?;
}
tx.execute("DELETE FROM mastery WHERE puuid = ?1", [old])?;
for key in [synced_until_key, mastery_key, platform_key] {
let (from, to) = (key(old), key(new));
tx.execute(
"UPDATE OR IGNORE meta SET name = ?2 WHERE name = ?1",
[&from, &to],
)?;
tx.execute("DELETE FROM meta WHERE name = ?1", [&from])?;
}
if tx
.prepare("SELECT 1 FROM accounts WHERE puuid = ?1")?
.exists([new])?
{
tx.execute(
"UPDATE accounts SET friend = MAX(friend,
(SELECT friend FROM accounts WHERE puuid = ?1)) WHERE puuid = ?2",
params![old, new],
)?;
tx.execute("DELETE FROM accounts WHERE puuid = ?1", [old])?;
} else {
tx.execute(
"UPDATE accounts SET puuid = ?2, game_name = ?3, tag_line = ?4 WHERE puuid = ?1",
params![old, new, resolved.game_name, resolved.tag_line],
)?;
}
tx.commit()?;
self.refresh_directory(&db)?;
self.follow().rekey(old, new);
(self.replaced.lock().unwrap_or_else(|e| e.into_inner())).insert(old.into(), new.into());
log::info!(
"Account {} moved to another PUUID ({} to {})",
account_riot_id(resolved),
short(old),
short(new)
);
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::tracker::tests::NoHistory;
use std::path::Path;
#[test]
fn moving_a_puuid_twice_or_one_not_stored_changes_nothing() {
let tracker = Tracker::open(Path::new(":memory:"), Box::new(NoHistory)).unwrap();
tracker
.db()
.execute(
"INSERT INTO accounts (puuid, game_name, tag_line, friend) VALUES ('old', 'P', 'EUW', 1)",
[],
)
.unwrap();
let new = Account {
puuid: "new".into(),
game_name: "P".into(),
tag_line: "EUW".into(),
};
tracker.move_puuid("old", &new).unwrap();
// Two callers proved the same change: the second finds nothing to move.
tracker.move_puuid("old", &new).unwrap();
tracker.move_puuid("never-stored", &new).unwrap();
assert_eq!(tracker.friends().unwrap(), [new]);
assert_eq!(tracker.replaced_puuid("old").as_deref(), Some("new"));
assert_eq!(tracker.replaced_puuid("never-stored"), None);
}
}
+10 -8
View File
@@ -59,16 +59,18 @@ fn raw_payload_is_stored_unmodified_and_only_once() {
}
#[test]
fn rate_limit_is_retried_a_few_times_then_reported() {
fn a_rate_limit_is_waited_out_as_many_times_as_needed() {
let mut calls = 0;
let result: Result<(), _> = with_retry(|| {
let result = with_retry(|| {
calls += 1;
Err(SourceError::RateLimited {
retry_after: Duration::ZERO,
})
if calls <= 20 {
return Err(SourceError::RateLimited {
retry_after: Duration::ZERO,
});
}
Ok(calls)
});
assert!(matches!(result, Err(SourceError::RateLimited { .. })));
assert_eq!(calls, RATE_LIMIT_RETRIES + 1);
assert_eq!(result, Ok(21));
}
#[test]
@@ -150,7 +152,7 @@ fn a_database_of_the_previous_version_gains_the_provisional_flag_and_keeps_its_m
assert_eq!(open().matches("p").unwrap(), matches);
}
struct NoHistory;
pub(super) struct NoHistory;
impl MatchHistorySource for NoHistory {
fn resolve_account(&self, _: &str, _: &str) -> Result<Account, SourceError> {
+41
View File
@@ -0,0 +1,41 @@
//! Captures the log lines the calling thread writes while a closure runs. `log::set_logger` is
//! global and once per process while tests run in parallel threads: one logger is installed for
//! all, and each thread has its own buffer. Code that logs from another thread is not seen.
// Each test binary uses its own subset of these helpers.
#![allow(dead_code)]
use std::cell::RefCell;
use std::sync::Once;
use log::{LevelFilter, Log, Metadata, Record};
struct Capture;
thread_local! {
static LINES: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) };
}
impl Log for Capture {
fn enabled(&self, _: &Metadata) -> bool {
true
}
fn log(&self, record: &Record) {
let line = format!("{} {}", record.level(), record.args());
LINES.with(|lines| lines.borrow_mut().push(line));
}
fn flush(&self) {}
}
/// The result of `run` and the lines it logged on this thread, as `LEVEL message`.
pub fn captured<T>(run: impl FnOnce() -> T) -> (T, Vec<String>) {
static INSTALL: Once = Once::new();
INSTALL.call_once(|| {
let _ = log::set_logger(&Capture);
log::set_max_level(LevelFilter::Trace);
});
LINES.with(|lines| lines.borrow_mut().clear());
let result = run();
(result, LINES.with(RefCell::take))
}
+80 -10
View File
@@ -45,8 +45,19 @@ pub struct FakeHistory {
listings: Mutex<Vec<Listing>>,
/// Every call fails with this until it is cleared.
failure: Mutex<Option<SourceError>>,
/// Match requests fail with this (after the general failure) until it is cleared.
match_failure: Mutex<Option<SourceError>>,
/// Match id listings fail with this (after the general failure) until it is cleared.
listing_failure: Mutex<Option<SourceError>>,
fail_after: Option<usize>,
rate_limit_once: AtomicBool,
/// The next Match and timeline requests answer "rate limited", this many times.
rate_limits: AtomicUsize,
/// The next Match id listings answer "rate limited", this many times.
listing_rate_limits: AtomicUsize,
/// The next Riot ID resolutions answer "rate limited", this many times.
resolve_rate_limits: AtomicUsize,
/// What a "rate limited" answer asks to wait; none by default so tests do not sleep.
retry_after: Duration,
/// Lists in the order the Matches were added instead of newest first.
as_given: bool,
/// Called at the start of every fetch: announces it, then waits to be released.
@@ -80,8 +91,13 @@ impl FakeHistory {
accounts: Vec::new(),
listings: Mutex::default(),
failure: Mutex::default(),
match_failure: Mutex::default(),
listing_failure: Mutex::default(),
fail_after: None,
rate_limit_once: AtomicBool::new(false),
rate_limits: AtomicUsize::new(0),
listing_rate_limits: AtomicUsize::new(0),
resolve_rate_limits: AtomicUsize::new(0),
retry_after: Duration::ZERO,
as_given: false,
resolve_gate: None,
gate: None,
@@ -171,18 +187,67 @@ impl FakeHistory {
*self.failure.lock().unwrap() = error;
}
/// Every Match request fails with this error until `None` is set (timelines are not
/// affected).
pub fn fail_match_with(&self, error: Option<SourceError>) {
*self.match_failure.lock().unwrap() = error;
}
/// Every Match id listing fails with this error until `None` is set (the other requests are
/// not affected).
pub fn fail_listing_with(&self, error: Option<SourceError>) {
*self.listing_failure.lock().unwrap() = error;
}
/// Every fetch after the first `n` fails with a network error.
pub fn failing_after(mut self, n: usize) -> FakeHistory {
self.fail_after = Some(n);
self
}
/// The first fetch answers "rate limited" once.
pub fn rate_limited_once(mut self) -> FakeHistory {
self.rate_limit_once = AtomicBool::new(true);
/// The first `n` Match or timeline requests answer "rate limited".
pub fn rate_limited(self, n: usize) -> FakeHistory {
self.rate_limit_next(n);
self
}
/// The next `n` Match or timeline requests answer "rate limited", with no delay.
pub fn rate_limit_next(&self, n: usize) {
self.rate_limits.store(n, Ordering::SeqCst);
}
/// The next `n` Match id listings answer "rate limited".
pub fn rate_limit_listing_next(&self, n: usize) {
self.listing_rate_limits.store(n, Ordering::SeqCst);
}
/// The next `n` Riot ID resolutions answer "rate limited".
pub fn rate_limit_resolution_next(&self, n: usize) {
self.resolve_rate_limits.store(n, Ordering::SeqCst);
}
/// A "rate limited" answer asks to wait this long.
pub fn retry_after(mut self, wait: Duration) -> FakeHistory {
self.retry_after = wait;
self
}
fn rate_limit(&self) -> Result<(), SourceError> {
self.limit_by(&self.rate_limits)
}
fn limit_by(&self, limits: &AtomicUsize) -> Result<(), SourceError> {
let limited = limits
.try_update(Ordering::SeqCst, Ordering::SeqCst, |n| n.checked_sub(1))
.is_ok();
match limited {
true => Err(SourceError::RateLimited {
retry_after: self.retry_after,
}),
false => Ok(()),
}
}
pub fn gated_resolution(mut self, entered: Sender<()>, release: Receiver<()>) -> Self {
self.resolve_gate = Some((entered, Mutex::new(release)));
self
@@ -261,7 +326,7 @@ impl FakeHistory {
self.timeline_calls.clone()
}
/// The Account plays on this platform (the key reads "EUW1" only).
/// The Account plays on this platform (the app reads "EUW1" only).
pub fn set_platform(&self, puuid: &str, platform: &str) {
(self.platforms.lock().unwrap()).insert(puuid.into(), platform.into());
}
@@ -291,6 +356,7 @@ impl FakeHistory {
impl MatchHistorySource for FakeHistory {
fn resolve_account(&self, game_name: &str, tag_line: &str) -> Result<Account, SourceError> {
self.enter(format!("account {game_name}#{tag_line}"))?;
self.limit_by(&self.resolve_rate_limits)?;
if let Some((entered, release)) = &self.resolve_gate {
entered.send(()).unwrap();
release.lock().unwrap().recv().unwrap();
@@ -315,6 +381,10 @@ impl MatchHistorySource for FakeHistory {
start_time_s: Option<i64>,
) -> Result<Vec<String>, SourceError> {
self.enter(format!("ids {puuid}"))?;
self.limit_by(&self.listing_rate_limits)?;
if let Some(error) = &*self.listing_failure.lock().unwrap() {
return Err(error.clone());
}
let mut found: Vec<_> = self
.listings
.lock()
@@ -343,10 +413,9 @@ impl MatchHistorySource for FakeHistory {
entered.send(()).unwrap();
release.lock().unwrap().recv().unwrap();
}
if self.rate_limit_once.swap(false, Ordering::SeqCst) {
return Err(SourceError::RateLimited {
retry_after: Duration::ZERO,
});
self.rate_limit()?;
if let Some(error) = &*self.match_failure.lock().unwrap() {
return Err(error.clone());
}
if self
.fail_after
@@ -369,6 +438,7 @@ impl MatchHistorySource for FakeHistory {
fn fetch_timeline(&self, id: &str) -> Result<String, SourceError> {
self.enter(format!("timeline {id}"))?;
self.timeline_calls.fetch_add(1, Ordering::SeqCst);
self.rate_limit()?;
if let Some((entered, release)) = &self.timeline_gate {
entered.send(()).unwrap();
let _ = release.lock().unwrap().recv();
+2
View File
@@ -16,6 +16,7 @@ use arena_tracker_core::{
};
use serde_json::Value;
mod capture;
mod champions;
mod client;
mod game_data;
@@ -25,6 +26,7 @@ mod scenarios;
#[allow(unused_imports)]
pub use {
capture::captured,
champions::{FakeChampions, card_art, splash_art},
client::{FakeClient, RawChampSelect, recorded_game_id},
game_data::{
Loaded 100 of 148 files, more files were not shown because too many files have changed in this diff. Show more