32 Commits
Author SHA1 Message Date
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
83 changed files with 3997 additions and 225 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/>.
+9
View File
@@ -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();
}
+15 -7
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;
@@ -374,12 +377,16 @@ fn startup() -> Result<Setup, (Vec<String>, Preferences)> {
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 +394,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);
+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)),
)
+6 -3
View File
@@ -3,6 +3,7 @@
//! 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 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};
@@ -304,9 +305,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")
+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.;
+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;
+6 -3
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;
@@ -226,9 +227,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(),
)
}
+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(),
);
+1
View File
@@ -42,3 +42,4 @@ mod portraits;
mod ring_hover;
mod sorting;
mod sorting_fixtures;
mod statistics_tiles;
+32 -33
View File
@@ -9,50 +9,52 @@ 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(
@@ -66,18 +68,15 @@ fn in_a_narrow_window_the_link_goes_under_a_long_season_without_covering_it(
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);
}
+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();
+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);
@@ -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);
}
+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()
});
+50 -29
View File
@@ -10,6 +10,7 @@ use gpui_kit::component::input::{Input, InputEvent, InputState};
use gpui_kit::component::{ActiveTheme as _, StyledExt as _};
use gpui_kit::*;
use crate::input_frame::input_frame;
use crate::logon::LogonLaunch;
use crate::release::{self, channel};
use crate::tray::{Tray, UNAVAILABLE};
@@ -27,6 +28,7 @@ pub use appearance::apply_theme;
#[cfg(test)]
use appearance::theme_mode;
mod logs;
mod preferences;
mod store;
pub use store::KeyStore;
@@ -52,6 +54,8 @@ pub struct KeyForm {
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,
@@ -140,6 +144,7 @@ impl KeyForm {
tray,
launches_at_logon: false,
logon_launch,
open_folder: logs::explorer,
notice_shown,
ready: None,
check_outcome: None,
@@ -414,35 +419,51 @@ impl Render for KeyForm {
.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),
)
// 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(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_frame(
&self.input,
Input::new(&self.input).mask_toggle(),
))
.children(
self.error
.clone()
.map(|error| div().text_color(danger).child(error)),
)
.child(buttons)
.child(
div()
.id("riot-notice")
.text_xs()
.text_color(muted)
.debug_selector(|| "riot-notice".into())
.child(crate::text::RIOT_NOTICE),
),
),
)
}
}
+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::KeyForm;
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 KeyForm {
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();
}
}
+1
View File
@@ -153,6 +153,7 @@ impl KeyForm {
)
})),
)
.child(self.logs_section(cx))
.children(
(self.preference_error.clone()).map(|error| div().text_color(danger).child(error)),
)
+5
View File
@@ -15,6 +15,11 @@ impl KeyStore {
KeyStore { path, config, api }
}
/// 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 has_key(&self) -> bool {
!self.config.riot_api_key.is_empty()
}
+103 -1
View File
@@ -2,10 +2,14 @@ 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 crate::logon::tests::Scratch;
use crate::title_bar::MIN_WINDOW_SIZE;
use crate::worker::UpdateChecked;
/// The settings' Accounts: none stored.
@@ -202,6 +206,39 @@ 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 api = Arc::new(RiotApi::new(String::new(), &config.region));
let store = KeyStore::new("unused.toml".into(), config, api);
gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| {
cx.new(|cx| KeyForm::new(store, tracker(), false, 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 +247,68 @@ 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 api = Arc::new(RiotApi::new(String::new(), &config.region));
let store = KeyStore::new(dir.join("config.toml"), config, api);
gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| {
cx.new(|cx| KeyForm::new(store, tracker(), false, 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}");
}
}
}
+3 -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."
@@ -220,7 +218,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."
+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);
+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"] }
+11 -2
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};
@@ -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>,
@@ -289,6 +292,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 +327,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 +362,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());
}
+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);
+13
View File
@@ -1,6 +1,19 @@
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 {
+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: the API 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 and headers (the key): 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};
+40 -11
View File
@@ -45,12 +45,14 @@ impl RiotApi {
*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, &|| {})
/// `kind` names the call in the log: the URL may hold a full PUUID and is never logged.
fn get(&self, kind: &str, path_and_query: &str) -> Result<String, SourceError> {
self.get_on(kind, &self.host, path_and_query, &|| {})
}
fn get_on(
&self,
kind: &str,
host: &str,
path_and_query: &str,
before_send: &dyn Fn(),
@@ -72,10 +74,33 @@ impl RiotApi {
if wait.is_zero() {
break;
}
log::info!(
"Riot {kind}: waiting {} ms for the request quota",
wait.as_millis()
);
thread::sleep(wait);
}
let url = format!("{host}{path_and_query}");
get(&self.agent, &url, Some(&key), |body| body.read_to_string())
let started = Instant::now();
let result = get(&self.agent, &url, Some(&key), |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::InvalidKey) => log::warn!("Riot {kind}: key refused (401/403) in {ms} ms"),
Err(e) => log::warn!("Riot {kind}: {e} in {ms} ms"),
}
}
@@ -127,7 +152,7 @@ impl MatchHistorySource for RiotApi {
encode(game_name),
encode(tag_line)
);
decode_account(&self.get(&path)?)
decode_account(&self.get("account-by-riot-id", &path)?)
}
fn match_ids(
@@ -157,7 +182,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_on("match-ids", &self.host, &path, before_send)?)
}
fn fetch_match(&self, match_id: &str) -> Result<String, SourceError> {
@@ -170,6 +195,7 @@ impl MatchHistorySource for RiotApi {
before_send: &dyn Fn(),
) -> Result<String, SourceError> {
self.get_on(
"match",
&self.host,
&format!("/lol/match/v5/matches/{}", encode(match_id)),
before_send,
@@ -178,10 +204,10 @@ impl MatchHistorySource for RiotApi {
/// Same regional host and limiter 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",
&format!("/lol/match/v5/matches/{}/timeline", encode(match_id)),
)
}
/// Mastery lives on the platform host (e.g. `euw1`), not on the regional one.
@@ -212,7 +238,7 @@ impl MatchHistorySource for RiotApi {
"/lol/champion-mastery/v4/champion-masteries/by-puuid/{}",
encode(puuid)
);
decode_mastery(&self.get_on(&host, &path, before_send)?)
decode_mastery(&self.get_on("mastery", &host, &path, before_send)?)
}
/// Asked on the routing host, like the Account itself.
@@ -221,7 +247,7 @@ impl MatchHistorySource for RiotApi {
"/riot/account/v1/region/by-game/lol/by-puuid/{}",
encode(puuid)
);
decode_platform(&self.get(&path)?)
decode_platform(&self.get("platform", &path)?)
}
fn serves_platform(&self, platform: &str) -> bool {
@@ -318,6 +344,9 @@ fn reserve_slot(sent: &mut VecDeque<Instant>, now: Instant) -> Duration {
wait
}
#[cfg(test)]
mod call_log;
#[cfg(test)]
mod tests {
use super::*;
+109
View File
@@ -0,0 +1,109 @@
//! What a Riot call writes to the application log: its type, outcome and duration, never its
//! URL (it may hold a full PUUID) nor the key.
use std::io::{Read, Write};
use std::net::TcpListener;
use std::thread;
use super::*;
use crate::journal::capture::captured;
/// Answers each connection with the next response, then closes it.
fn serve<S, I>(responses: I) -> 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());
thread::spawn(move || {
for response in responses {
let (mut stream, _) = listener.accept().unwrap();
let _ = stream.read(&mut [0; 4096]);
let _ = stream.write_all(response.as_ref().as_bytes());
}
});
host
}
#[test]
fn calls_are_logged_by_type_and_outcome_without_url_or_key() {
let key = "RGAPI-12345678-abcd-ef01-2345-6789abcdef01";
let mut api = RiotApi::new(key.into(), "europe");
api.host = serve([
"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\n[]",
"HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
"HTTP/1.1 429 Too Many Requests\r\nRetry-After: 7\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
]);
let puuid = "p".repeat(78);
// The HTTP client's own debug and trace lines hold the URL and the key: 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 [key, &puuid, "127.0.0.1", "/lol/", "EUW1_1"] {
assert!(!line.contains(secret), "{secret}: {line}");
}
}
}
#[test]
fn a_whole_sync_logs_neither_the_key_nor_a_full_puuid() {
let key = "RGAPI-12345678-abcd-ef01-2345-6789abcdef01";
let puuid = "q".repeat(78);
let ok = |body: &str| {
format!(
"HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
body.len()
)
};
let mut api = RiotApi::new(key.into(), "europe");
api.host = 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("[]"),
"HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".into(),
]);
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(key) && !line.contains(&puuid), "{line}");
}
}
+2
View File
@@ -108,6 +108,7 @@ 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()))?;
log::info!("Sync of {riot_id} started");
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.
{
@@ -141,6 +142,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,
+5 -1
View File
@@ -158,6 +158,8 @@ impl Tracker {
on_progress: &mut dyn FnMut(SyncProgress),
) -> Result<SyncReport, Error> {
let account = self.stored_account(puuid)?;
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 => {
@@ -171,10 +173,12 @@ impl Tracker {
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,
})
}
+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))
}
+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::{
+4 -2
View File
@@ -13,8 +13,8 @@ use arena_tracker_core::{
};
use common::{
CLIENT_PUUID, FakeClient, FakeHistory, PlayedMatch, RawChampSelect, S2, S2_TRACK, SELF_PUUID,
at, date, end_of_game_block, payload, payloads, played_by, played_match, recorded_account, run,
seasons,
at, captured, date, end_of_game_block, payload, payloads, played_by, played_match,
recorded_account, run, seasons,
};
const OTHER_PUUID: &str = "fixture-puuid-other";
@@ -202,6 +202,8 @@ fn reported_round(tracker: &Tracker) -> Vec<FollowedMatch> {
#[path = "follow/accounts.rs"]
mod accounts;
#[path = "follow/app_log.rs"]
mod app_log;
#[path = "follow/champ_select.rs"]
mod champ_select;
#[path = "follow/death_recaps.rs"]
+87
View File
@@ -0,0 +1,87 @@
//! What the follower writes to the application log (#142).
use super::provisional_matches::{game, start_game};
use super::*;
fn has(lines: &[String], text: &str) -> bool {
lines.iter().any(|line| line.contains(text))
}
#[test]
fn a_block_that_builds_no_match_leaves_a_warning_saying_why() {
let world = World::new(&s2_matches());
let tracker = world.tracker();
// A decoder that does not know the Placement's key reads no Placement.
let block = end_of_game_block(game().0, 222, 3).replace("subteamStanding", "teamRank");
let (_, lines) = captured(|| {
start_game(&world, &tracker);
world.client.create_end_of_game_block(&block);
world.client.set_phase("EndOfGame", true);
for _ in 0..3 {
reported_round(&tracker);
}
});
let waits: Vec<_> = lines.iter().filter(|l| l.starts_with("WARN ")).collect();
// Once, though three rounds tried it again.
assert_eq!(waits.len(), 1, "{lines:#?}");
assert!(
waits[0].contains("champion or Placement is missing"),
"{waits:?}"
);
assert!(has(&lines, "INFO End-of-game block received and stored"));
assert!(lines.iter().all(|l| !l.contains(&block)));
}
#[test]
fn a_block_taken_before_the_account_is_adopted_waits_for_its_account() {
let world = World::new(&s2_matches());
world.history.fail_with(Some(SourceError::InvalidKey));
let tracker = world.tracker();
world.client.set_summoner_puuid(Some(CLIENT_PUUID));
let (_, lines) = captured(|| {
reported_round(&tracker);
world.client.set_game_id(Some(game().0));
world.client.set_phase("InProgress", true);
world
.client
.create_end_of_game_block(&end_of_game_block(game().0, 222, 3));
world.client.return_to_lobby();
reported_round(&tracker);
});
assert!(has(&lines, "WARN Update problem: InvalidKey"), "{lines:#?}");
assert!(has(&lines, "WARN End-of-game block (game"), "{lines:#?}");
assert!(has(&lines, "Account is unknown"), "{lines:#?}");
}
#[test]
fn a_followed_game_is_logged_without_a_full_puuid() {
let world = World::new(&s2_matches());
let tracker = world.tracker();
let block = end_of_game_block(game().0, 222, 3);
let (_, lines) = captured(|| {
start_game(&world, &tracker);
world.client.create_end_of_game_block(&block);
world.client.set_phase("EndOfGame", true);
reported_round(&tracker);
let _ = tracker.sync("Joueur#EUW", &mut |_| {});
});
for expected in [
"League client: Joueur#EUW signed in",
"is the active one",
"Sync of Joueur#EUW started",
"Sync of Joueur#EUW done",
"Game phase: Idle -> InGame",
"Game phase: InGame -> Ended",
"stored as Provisional Match EUW1_",
] {
assert!(has(&lines, expected), "{expected}: {lines:#?}");
}
for puuid in [SELF_PUUID, CLIENT_PUUID] {
assert!(
lines.iter().all(|l| !l.contains(puuid)),
"{puuid}: {lines:#?}"
);
}
}
+20
View File
@@ -0,0 +1,20 @@
//! The application log as the app installs it (#142). The writer's own tests are in
//! `src/journal/tests.rs`.
use std::fs;
use arena_tracker_core::init_journal;
/// The only test that installs the process's logger.
#[test]
fn launching_creates_the_file_with_the_version_and_the_channel() {
let data = tempfile::tempdir().unwrap();
init_journal(data.path(), false, "9.8.7", "beta", || {}).unwrap();
log::info!(target: "arena_tracker", "after the launch");
log::logger().flush();
let text = fs::read_to_string(data.path().join("logs").join("arena-tracker.log")).unwrap();
let lines: Vec<_> = text.lines().collect();
assert_eq!(lines.len(), 2, "{text}");
assert!(lines[0].contains("INFO Arena Tracker 9.8.7 started (update channel: beta)"));
assert!(lines[1].ends_with("INFO after the launch"), "{text}");
}
+11
View File
@@ -0,0 +1,11 @@
[package]
name = "arena-tracker-relay"
edition.workspace = true
rust-version.workspace = true
version.workspace = true
license.workspace = true
[dependencies]
log = "0.4"
tiny_http = "0.12"
ureq = "3.5.2"
+18
View File
@@ -0,0 +1,18 @@
# The relay's image (docs/service-relais.md). Build from the repository root:
# docker build -f crates/relay/Dockerfile .
# A static musl binary on an empty image: ureq carries its own root certificates.
FROM rust:1.98-alpine AS build
RUN apk add --no-cache musl-dev
WORKDIR /src
COPY . .
RUN --mount=type=cache,target=/usr/local/cargo/registry \
--mount=type=cache,target=/src/target \
cargo build --release --locked -p arena-tracker-relay \
&& cp target/release/arena-tracker-relay /relay
FROM scratch
COPY --from=build /relay /relay
ENV RELAY_LISTEN=0.0.0.0:8080
EXPOSE 8080
USER 65534:65534
ENTRYPOINT ["/relay"]
+169
View File
@@ -0,0 +1,169 @@
//! The relay's settings, read from the environment (docs/service-relais.md).
use std::net::{IpAddr, SocketAddr};
use std::time::Duration;
use crate::limit::Limit;
/// Riot's production limits, per routing value.
pub const ROUTE_LIMITS: &str = "500/10,30000/600";
/// Per client address.
pub const CLIENT_LIMITS: &str = "100/10,3000/600";
pub const LISTEN: &str = "127.0.0.1:8080";
/// `{routing}` is replaced by the routing value.
pub const UPSTREAM: &str = "https://{routing}.api.riotgames.com";
/// The longest limit window, in seconds.
const MAX_WINDOW: u64 = 86_400;
/// Deliberately has no `Debug`: it holds the key.
pub struct Config {
pub(crate) key: String,
pub(crate) listen: SocketAddr,
pub(crate) upstream: String,
/// The reverse proxy: only its requests' `X-Forwarded-For` is believed.
pub(crate) trusted_proxy: Option<Network>,
pub(crate) route_limits: Vec<Limit>,
pub(crate) client_limits: Vec<Limit>,
}
impl Config {
/// Reads `RIOT_API_KEY` (required) and the optional `RELAY_*` variables through `var`.
pub fn from_env(var: impl Fn(&str) -> Option<String>) -> Result<Config, String> {
let key = var("RIOT_API_KEY")
.filter(|k| !k.trim().is_empty())
.ok_or("RIOT_API_KEY is missing")?;
let or = |name: &str, default: &str| var(name).unwrap_or_else(|| default.into());
let listen = or("RELAY_LISTEN", LISTEN);
Ok(Config {
key: key.trim().into(),
listen: listen
.parse()
.map_err(|_| format!("RELAY_LISTEN is not an address: {listen}"))?,
upstream: or("RELAY_UPSTREAM", UPSTREAM),
trusted_proxy: var("RELAY_TRUSTED_PROXY")
.map(|text| {
Network::parse(&text).ok_or(format!(
"RELAY_TRUSTED_PROXY is not an IP address or network: {text}"
))
})
.transpose()?,
route_limits: limits(
"RELAY_ROUTE_LIMITS",
&or("RELAY_ROUTE_LIMITS", ROUTE_LIMITS),
)?,
client_limits: limits(
"RELAY_CLIENT_LIMITS",
&or("RELAY_CLIENT_LIMITS", CLIENT_LIMITS),
)?,
})
}
}
/// An address, or a network such as `172.18.0.0/16`: a proxy in a container network changes
/// address when it restarts.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct Network {
addr: IpAddr,
prefix: u32,
}
impl Network {
fn parse(text: &str) -> Option<Network> {
let (addr, prefix) = match text.split_once('/') {
Some((addr, prefix)) => (addr, Some(prefix)),
None => (text, None),
};
let addr: IpAddr = addr.trim().parse().ok()?;
let len = bits(addr).1;
let prefix = match prefix {
Some(p) => p.trim().parse().ok().filter(|&p| p <= len)?,
None => len,
};
Some(Network { addr, prefix })
}
pub(crate) fn contains(&self, ip: IpAddr) -> bool {
let ((net, len), (ip, ip_len)) = (bits(self.addr), bits(ip.to_canonical()));
len == ip_len && (self.prefix == 0 || (net ^ ip) >> (len - self.prefix) == 0)
}
}
/// The address as a number, and its length in bits.
fn bits(ip: IpAddr) -> (u128, u32) {
match ip {
IpAddr::V4(v4) => (u32::from(v4).into(), 32),
IpAddr::V6(v6) => (v6.into(), 128),
}
}
/// `"500/10,30000/600"`: requests per seconds, comma-separated.
fn limits(name: &str, text: &str) -> Result<Vec<Limit>, String> {
text.split(',')
.map(|limit| {
let (max, secs) = limit.trim().split_once('/').unwrap_or_default();
match (max.parse(), secs.parse::<u64>()) {
(Ok(max), Ok(secs)) if (1..=MAX_WINDOW).contains(&secs) => Ok(Limit {
max,
window: Duration::from_secs(secs),
}),
_ => Err(format!("{name}: expected requests/seconds, got {limit:?}")),
}
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn defaults_are_the_production_limits() {
let config =
Config::from_env(|name| (name == "RIOT_API_KEY").then(|| "RGAPI-k ".into())).unwrap();
assert_eq!(config.key, "RGAPI-k");
assert_eq!(config.listen, LISTEN.parse().unwrap());
assert_eq!(config.trusted_proxy, None);
let limit = |max, secs| Limit {
max,
window: Duration::from_secs(secs),
};
assert_eq!(config.route_limits, [limit(500, 10), limit(30_000, 600)]);
assert_eq!(config.client_limits, [limit(100, 10), limit(3_000, 600)]);
}
#[test]
fn a_missing_key_or_a_bad_value_stops_the_start() {
assert!(Config::from_env(|_| None).is_err());
for (name, value) in [
("RELAY_ROUTE_LIMITS", "500"),
("RELAY_ROUTE_LIMITS", "500/0"),
("RELAY_ROUTE_LIMITS", "1/18446744073709551615"),
("RELAY_CLIENT_LIMITS", "a/10"),
("RELAY_LISTEN", "localhost"),
("RELAY_TRUSTED_PROXY", "proxy"),
("RELAY_TRUSTED_PROXY", "172.18.0.0/33"),
("RELAY_TRUSTED_PROXY", "172.18.0.0/"),
] {
let var = |n: &str| match n {
"RIOT_API_KEY" => Some("RGAPI-k".into()),
n if n == name => Some(value.into()),
_ => None,
};
assert!(Config::from_env(var).is_err(), "{name}={value}");
}
}
#[test]
fn a_trusted_proxy_is_an_address_or_a_network() {
let net = |text| Network::parse(text).unwrap();
let ip = |text: &str| text.parse::<IpAddr>().unwrap();
assert!(net("172.18.0.7").contains(ip("172.18.0.7")));
assert!(!net("172.18.0.7").contains(ip("172.18.0.8")));
assert!(net("172.18.0.0/16").contains(ip("172.18.255.1")));
assert!(net("172.18.0.0/16").contains(ip("::ffff:172.18.0.9")));
assert!(!net("172.18.0.0/16").contains(ip("172.19.0.1")));
assert!(net("fd00::/8").contains(ip("fd12::1")));
assert!(!net("fd00::/8").contains(ip("172.18.0.1")));
assert!(net("0.0.0.0/0").contains(ip("203.0.113.1")));
}
}
+271
View File
@@ -0,0 +1,271 @@
//! The Arena Tracker relay: holds the Riot key, serves the app's six Riot calls and shares the
//! quota between clients, and serves the Arena Tracker site (ADR-0008, docs/service-relais.md).
//! Nothing is stored, nothing cached.
mod config;
mod limit;
mod route;
mod site;
use std::io::{self, Write};
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use std::sync::{Arc, Mutex, PoisonError};
use std::thread;
use std::time::{Duration, Instant};
use tiny_http::{Header, Method, Request, Response, Server};
use ureq::Agent;
pub use config::Config;
use limit::Limiter;
/// Requests answered at once; the others wait in the server's queue.
const WORKERS: usize = 64;
/// Suspension after a Riot 429 that gives no delay (the app's own default).
const DEFAULT_RETRY_AFTER: Duration = Duration::from_secs(10);
/// The longest suspension a Riot 429 may ask for.
const MAX_RETRY_AFTER: u64 = 86_400;
pub struct Relay {
server: Server,
state: State,
}
struct State {
key: String,
upstream: String,
trusted_proxy: Option<config::Network>,
agent: Agent,
routes: Mutex<Limiter<&'static str>>,
clients: Mutex<Limiter<IpAddr>>,
}
/// What a request gets, and why (for the log).
struct Reply {
status: u16,
body: Vec<u8>,
content_type: Option<String>,
retry_after: Option<Duration>,
origin: &'static str,
}
impl Reply {
fn empty(status: u16, origin: &'static str) -> Reply {
Reply {
status,
body: Vec::new(),
content_type: None,
retry_after: None,
origin,
}
}
fn too_many(wait: Duration, origin: &'static str) -> Reply {
Reply {
retry_after: Some(wait),
..Reply::empty(429, origin)
}
}
}
impl Relay {
pub fn bind(config: Config) -> io::Result<Relay> {
let server = Server::http(config.listen).map_err(io::Error::other)?;
let now = Instant::now();
Ok(Relay {
server,
state: State {
key: config.key,
upstream: config.upstream,
trusted_proxy: config.trusted_proxy,
agent: Agent::config_builder()
.http_status_as_error(false)
.max_redirects(0)
.user_agent("arena-tracker-relay")
.timeout_global(Some(Duration::from_secs(30)))
.build()
.into(),
routes: Mutex::new(Limiter::new(config.route_limits, now)),
clients: Mutex::new(Limiter::new(config.client_limits, now)),
},
})
}
/// The address it listens on (the port the system chose for port 0).
pub fn local_addr(&self) -> Option<SocketAddr> {
self.server.server_addr().to_ip()
}
/// Answers requests until the process ends.
pub fn run(self) {
let relay = Arc::new(self);
let workers: Vec<_> = (0..WORKERS)
.map(|_| {
let relay = Arc::clone(&relay);
thread::spawn(move || {
while let Ok(request) = relay.server.recv() {
relay.state.handle(request);
}
})
})
.collect();
for worker in workers {
let _ = worker.join();
}
}
}
impl State {
fn handle(&self, request: Request) {
let started = Instant::now();
let get = request.method() == &Method::Get;
let call = get.then(|| route::parse(request.url())).flatten();
let page = get.then(|| site::page(request.url())).flatten();
let reply = match (&call, page) {
(Some(call), _) => self.answer(call, self.client(&request)),
(None, Some((content_type, page))) => Reply {
status: 200,
body: page.to_vec(),
content_type: Some(content_type.into()),
retry_after: None,
origin: "site",
},
(None, None) => Reply::empty(404, "refused"),
};
let ms = started.elapsed().as_millis();
// Only the type of call: the URL holds a Riot ID or a PUUID. Page views and refused
// requests are not logged: the site keeps no access log, scanners would fill it.
if let Some(call) = &call {
log::info!(
"{}: {} ({}) in {ms} ms",
call.kind,
reply.status,
reply.origin
);
}
let mut response = Response::from_data(reply.body).with_status_code(reply.status);
if let Some(wait) = reply.retry_after {
response.add_header(header("Retry-After", &whole_seconds(wait).to_string()));
}
if let Some(content_type) = reply.content_type {
response.add_header(header("Content-Type", &content_type));
}
let _ = request.respond(response);
}
fn answer(&self, call: &route::Call, client: IpAddr) -> Reply {
let now = Instant::now();
if let Err(wait) = lock(&self.clients).take(client, now) {
return Reply::too_many(wait, "client limit");
}
if let Err(wait) = lock(&self.routes).take(call.routing, now) {
return Reply::too_many(wait, "quota");
}
let url = format!(
"{}{}",
self.upstream.replace("{routing}", call.routing),
call.riot
);
let response = self
.agent
.get(&url)
.header("X-Riot-Token", &self.key)
.call();
let Ok(mut response) = response else {
return Reply::empty(502, "riot unreachable");
};
let status = response.status().as_u16();
let riot_header = |name| {
response
.headers()
.get(name)
.and_then(|v| v.to_str().ok())
.map(str::to_owned)
};
let retry_after = riot_header("retry-after");
let content_type = riot_header("content-type");
// A refused key is the relay's problem, not the player's; a Match's timeline may be
// refused on its own (the app then asks for the Match).
let timeline_refused = status == 403 && call.kind == "timeline";
if matches!(status, 401 | 403) && !timeline_refused {
return Reply::empty(503, "key refused");
}
let retry_after = (status == 429).then(|| {
let wait = retry_after
.and_then(|v| v.trim().parse::<u64>().ok())
.map_or(DEFAULT_RETRY_AFTER, |s| {
Duration::from_secs(s.min(MAX_RETRY_AFTER))
});
lock(&self.routes).suspend(call.routing, Instant::now() + wait);
wait
});
let Ok(body) = response.body_mut().read_to_vec() else {
return Reply::empty(502, "riot unreadable");
};
Reply {
status,
body,
content_type,
retry_after,
origin: "riot",
}
}
/// The client's address: the peer's, or the one the trusted reverse proxy forwards.
fn client(&self, request: &Request) -> IpAddr {
let peer = request
.remote_addr()
.map_or(IpAddr::V4(Ipv4Addr::UNSPECIFIED), SocketAddr::ip);
if !self.trusted_proxy.is_some_and(|proxy| proxy.contains(peer)) {
return peer;
}
request
.headers()
.iter()
// The proxy appends the address it saw: the last one (of the last header, should the
// proxy add its own) is the only one it vouches for.
.rfind(|h| h.field.equiv("X-Forwarded-For"))
.and_then(|h| h.value.as_str().rsplit(',').next()?.trim().parse().ok())
.unwrap_or(peer)
}
}
fn lock<T>(mutex: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
mutex.lock().unwrap_or_else(PoisonError::into_inner)
}
fn header(name: &str, value: &str) -> Header {
Header::from_bytes(name, value).expect("ASCII header")
}
/// Retry-After is in whole seconds: rounded up, so a client never comes back too early.
fn whole_seconds(wait: Duration) -> u64 {
(wait.as_secs() + u64::from(wait.subsec_nanos() > 0)).max(1)
}
/// Writes the relay's own log lines (info and above) to `out`, one per line. The HTTP crates'
/// lines are left out: theirs may hold a URL, a header or an address.
pub fn log_to(out: Box<dyn Write + Send>) -> Result<(), log::SetLoggerError> {
log::set_logger(Box::leak(Box::new(Logger(Mutex::new(out)))))?;
log::set_max_level(log::LevelFilter::Info);
Ok(())
}
struct Logger(Mutex<Box<dyn Write + Send>>);
impl log::Log for Logger {
fn enabled(&self, metadata: &log::Metadata) -> bool {
metadata.level() <= log::Level::Info
&& metadata.target().starts_with(env!("CARGO_CRATE_NAME"))
}
fn log(&self, record: &log::Record) {
if self.enabled(record.metadata()) {
let _ = writeln!(lock(&self.0), "{} {}", record.level(), record.args());
}
}
fn flush(&self) {
let _ = lock(&self.0).flush();
}
}
+153
View File
@@ -0,0 +1,153 @@
//! Fixed-window request limits per key (a routing value, a client address), like Riot's own:
//! a window opens at its first request and counts up to its maximum.
use std::collections::HashMap;
use std::hash::Hash;
use std::time::{Duration, Instant};
/// At most `max` requests per `window`.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Limit {
pub max: u32,
pub window: Duration,
}
pub(crate) struct Limiter<K> {
limits: Vec<Limit>,
keys: HashMap<K, Counters>,
/// When keys with nothing left to count were last dropped.
swept: Instant,
}
struct Counters {
/// (start, count) per limit.
windows: Vec<(Instant, u32)>,
suspended_until: Option<Instant>,
}
impl<K: Hash + Eq> Limiter<K> {
pub fn new(limits: Vec<Limit>, now: Instant) -> Limiter<K> {
Limiter {
limits,
keys: HashMap::new(),
swept: now,
}
}
/// Counts a request for `key`, or returns how long until it may go (without counting it).
pub fn take(&mut self, key: K, now: Instant) -> Result<(), Duration> {
self.sweep(now);
let limits = &self.limits;
let counters = self.keys.entry(key).or_insert_with(|| Counters {
windows: vec![(now, 0); limits.len()],
suspended_until: None,
});
let mut wait = counters
.suspended_until
.map_or(Duration::ZERO, |t| t.saturating_duration_since(now));
for ((start, count), limit) in counters.windows.iter_mut().zip(limits) {
if now.saturating_duration_since(*start) >= limit.window {
(*start, *count) = (now, 0);
}
if *count >= limit.max {
wait = wait.max((*start + limit.window).saturating_duration_since(now));
}
}
if !wait.is_zero() {
return Err(wait);
}
for (_, count) in &mut counters.windows {
*count += 1;
}
Ok(())
}
/// Refuses every request for `key` until `until`, or longer if it already was.
pub fn suspend(&mut self, key: K, until: Instant) {
if let Some(counters) = self.keys.get_mut(&key) {
counters.suspended_until = counters.suspended_until.max(Some(until));
}
}
/// Once per longest window, drops the keys whose windows and suspension have all ended, so
/// memory follows the clients of the last minutes.
fn sweep(&mut self, now: Instant) {
let longest = self
.limits
.iter()
.map(|l| l.window)
.max()
.unwrap_or_default();
if now.saturating_duration_since(self.swept) < longest {
return;
}
self.swept = now;
let limits = &self.limits;
self.keys.retain(|_, c| {
c.suspended_until.is_some_and(|t| t > now)
|| c.windows
.iter()
.zip(limits)
.any(|(&(start, _), l)| now.saturating_duration_since(start) < l.window)
});
}
}
#[cfg(test)]
mod tests {
use super::*;
const S: Duration = Duration::from_secs(1);
fn limiter(now: Instant) -> Limiter<&'static str> {
Limiter::new(
vec![
Limit {
max: 2,
window: 10 * S,
},
Limit {
max: 3,
window: 60 * S,
},
],
now,
)
}
#[test]
fn each_window_counts_up_to_its_maximum_then_reopens() {
let t0 = Instant::now();
let mut l = limiter(t0);
assert_eq!(l.take("a", t0), Ok(()));
assert_eq!(l.take("a", t0 + S), Ok(()));
assert_eq!(l.take("a", t0 + 4 * S), Err(6 * S));
assert_eq!(l.take("b", t0 + 4 * S), Ok(()), "keys count apart");
assert_eq!(l.take("a", t0 + 10 * S), Ok(()));
// The 60 s window holds 3: the next waits for it, not for the 10 s one.
assert_eq!(l.take("a", t0 + 20 * S), Err(40 * S));
assert_eq!(l.take("a", t0 + 60 * S), Ok(()));
}
#[test]
fn a_suspension_refuses_until_it_ends() {
let t0 = Instant::now();
let mut l = limiter(t0);
l.take("a", t0).unwrap();
l.suspend("a", t0 + 5 * S);
l.suspend("a", t0 + 2 * S); // a shorter one does not cut it
assert_eq!(l.take("a", t0 + S), Err(4 * S));
assert_eq!(l.take("a", t0 + 5 * S), Ok(()));
}
#[test]
fn idle_keys_are_dropped() {
let t0 = Instant::now();
let mut l = limiter(t0);
l.take("a", t0).unwrap();
l.take("b", t0 + 50 * S).unwrap();
l.take("c", t0 + 60 * S).unwrap();
assert!(!l.keys.contains_key("a"));
assert!(l.keys.contains_key("b"));
}
}
+29
View File
@@ -0,0 +1,29 @@
//! Starts the relay from the environment (docs/service-relais.md).
use std::process::ExitCode;
use arena_tracker_relay::{Config, Relay, log_to};
fn main() -> ExitCode {
let _ = log_to(Box::new(std::io::stderr()));
let config = match Config::from_env(|name| std::env::var(name).ok()) {
Ok(config) => config,
Err(e) => {
log::error!("{e}");
return ExitCode::FAILURE;
}
};
match Relay::bind(config) {
Ok(relay) => {
if let Some(addr) = relay.local_addr() {
log::info!("listening on {addr}");
}
relay.run();
ExitCode::SUCCESS
}
Err(e) => {
log::error!("cannot listen: {e}");
ExitCode::FAILURE
}
}
}
+239
View File
@@ -0,0 +1,239 @@
//! The six Riot calls the relay serves. A relay URL is `/{routing value}{Riot path}`; anything
//! else is refused before Riot is called.
const REGIONS: [&str; 4] = ["americas", "asia", "europe", "sea"];
const PLATFORMS: [&str; 17] = [
"br1", "eun1", "euw1", "jp1", "kr", "la1", "la2", "me1", "na1", "oc1", "ph2", "ru", "sg2",
"th2", "tr1", "tw2", "vn2",
];
/// The Arena queues (the core's `QUEUES`).
const ARENA_QUEUES: [&str; 4] = ["1700", "1710", "1740", "1750"];
const MAX_COUNT: u32 = 100;
/// An allowed call: its type (for the log) and the routing value whose quota it uses.
#[derive(Debug, PartialEq)]
pub(crate) struct Call<'a> {
pub kind: &'static str,
pub routing: &'static str,
/// The Riot path and query, unchanged.
pub riot: &'a str,
}
/// The call `url` names, or `None` when it is not one of the six.
pub(crate) fn parse(url: &str) -> Option<Call<'_>> {
let rest = url.strip_prefix('/')?;
let (routing, riot) = rest.split_at(rest.find('/')?);
let (path, query) = match riot.split_once('?') {
Some((path, query)) => (path, Some(query)),
None => (riot, None),
};
let segments: Vec<&str> = path[1..].split('/').collect();
let (kind, routings): (_, &[&'static str]) = match segments[..] {
["riot", "account", "v1", "accounts", "by-riot-id", name, tag]
if segment(name) && segment(tag) =>
{
("account-by-riot-id", &REGIONS)
}
[
"riot",
"account",
"v1",
"region",
"by-game",
"lol",
"by-puuid",
puuid,
] if segment(puuid) => ("platform", &REGIONS),
["lol", "match", "v5", "matches", "by-puuid", puuid, "ids"] if segment(puuid) => {
("match-ids", &REGIONS)
}
["lol", "match", "v5", "matches", id] if segment(id) => ("match", &REGIONS),
["lol", "match", "v5", "matches", id, "timeline"] if segment(id) => ("timeline", &REGIONS),
[
"lol",
"champion-mastery",
"v4",
"champion-masteries",
"by-puuid",
puuid,
] if segment(puuid) => ("mastery", &PLATFORMS),
_ => return None,
};
let query_ok = match kind {
"match-ids" => query.is_some_and(arena_ids_query),
_ => query.is_none(),
};
let routing = *routings.iter().find(|&&r| r == routing)?;
query_ok.then_some(Call {
kind,
routing,
riot,
})
}
/// A path segment as the app encodes it: unreserved characters and `%XX`, never a dot segment
/// nor an encoded dot, slash or backslash that Riot's side could turn back into one.
fn segment(s: &str) -> bool {
if s.is_empty() || s == "." || s == ".." {
return false;
}
let bytes = s.as_bytes();
let mut i = 0;
while i < bytes.len() {
match bytes[i] {
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => i += 1,
b'%' => {
let Some(byte) = s
.get(i + 1..i + 3)
.and_then(|hex| u8::from_str_radix(hex, 16).ok())
else {
return false;
};
if matches!(byte, b'.' | b'/' | b'\\') {
return false;
}
i += 3;
}
_ => return false,
}
}
true
}
/// `queue` (an Arena queue, required), `start`, `count` (at most 100) and `startTime`, each at
/// most once and in digits.
fn arena_ids_query(query: &str) -> bool {
let mut seen: Vec<&str> = Vec::new();
for pair in query.split('&') {
let Some((name, value)) = pair.split_once('=') else {
return false;
};
let digits =
!value.is_empty() && value.len() <= 19 && value.bytes().all(|b| b.is_ascii_digit());
let ok = digits
&& !seen.contains(&name)
&& match name {
"queue" => ARENA_QUEUES.contains(&value),
"count" => value.parse::<u32>().is_ok_and(|c| c <= MAX_COUNT),
"start" | "startTime" => true,
_ => false,
};
if !ok {
return false;
}
seen.push(name);
}
seen.contains(&"queue")
}
#[cfg(test)]
mod tests {
use super::*;
fn kind(url: &str) -> Option<&'static str> {
parse(url).map(|call| call.kind)
}
#[test]
fn the_six_calls_keep_their_riot_path() {
let ids = "/europe/lol/match/v5/matches/by-puuid/p-1_x/ids?queue=1750&start=0&count=100&startTime=1700000000";
assert_eq!(
parse(ids),
Some(Call {
kind: "match-ids",
routing: "europe",
riot: &ids[7..],
})
);
for (url, expected) in [
(
"/europe/riot/account/v1/accounts/by-riot-id/Le%20Joueur/EUW",
"account-by-riot-id",
),
(
"/americas/riot/account/v1/region/by-game/lol/by-puuid/p",
"platform",
),
("/sea/lol/match/v5/matches/EUW1_1", "match"),
("/asia/lol/match/v5/matches/KR_1/timeline", "timeline"),
(
"/euw1/lol/champion-mastery/v4/champion-masteries/by-puuid/p",
"mastery",
),
] {
assert_eq!(kind(url), Some(expected), "{url}");
}
}
#[test]
fn a_routing_value_outside_the_closed_list_or_of_the_wrong_kind_is_refused() {
for url in [
"/eu/lol/match/v5/matches/EUW1_1",
"/EUROPE/lol/match/v5/matches/EUW1_1",
"/euw1/lol/match/v5/matches/EUW1_1",
"/europe/lol/champion-mastery/v4/champion-masteries/by-puuid/p",
"/evil.example/lol/match/v5/matches/EUW1_1",
"//lol/match/v5/matches/EUW1_1",
"/europe",
] {
assert_eq!(kind(url), None, "{url}");
}
}
#[test]
fn other_routes_and_unsafe_segments_are_refused() {
for url in [
"/europe/lol/match/v5/matches",
"/europe/lol/match/v5/matches/",
"/europe/lol/match/v5/matches/EUW1_1/",
"/europe/lol/match/v4/matches/EUW1_1",
"/europe/lol/match/v5/matches/EUW1_1/timeline/x",
"/europe/lol/match/v5/matches/..",
"/europe/lol/match/v5/matches/%2e%2E",
"/europe/lol/match/v5/matches/a%2Fb",
"/europe/lol/match/v5/matches/a%5cb",
"/europe/lol/match/v5/matches/a%zz",
"/europe/lol/match/v5/matches/a%2",
"/europe/lol/match/v5/matches/a b",
"/europe/lol/match/v5/matches/EUW1_1?api_key=x",
"/europe/lol/match/v5/matches/EUW1_1?",
"/europe/riot/account/v1/accounts/by-riot-id/Joueur",
"/europe/lol/status/v4/platform-data",
] {
assert_eq!(kind(url), None, "{url}");
}
}
#[test]
fn match_ids_need_an_arena_queue_and_at_most_100() {
let base = "/europe/lol/match/v5/matches/by-puuid/p/ids";
for query in [
"?queue=1700",
"?queue=1710&count=100",
"?start=20&queue=1740&count=1",
] {
assert_eq!(
kind(&format!("{base}{query}")),
Some("match-ids"),
"{query}"
);
}
for query in [
"",
"?",
"?count=20",
"?queue=420",
"?queue=1700&count=101",
"?queue=1700&count=+1",
"?queue=1700&queue=1710",
"?queue=1700&type=ranked",
"?queue=1700&start=",
"?queue=1700&start=-1",
"?queue=1700&endTime=1",
"?queue=1700&",
"?queue",
] {
assert_eq!(kind(&format!("{base}{query}")), None, "{query}");
}
}
}
+51
View File
@@ -0,0 +1,51 @@
//! The Arena Tracker site (`site/` at the repository root, #145), built into the binary: the
//! relay is the only thing to deploy. Page views are not logged.
const HTML: &str = "text/html; charset=utf-8";
const WEBP: &str = "image/webp";
const TEXT: &str = "text/plain; charset=utf-8";
/// (path, content type, content). A new file in `site/` gets a row here (a test checks it).
const PAGES: [(&str, &str, &[u8]); 8] = [
("/", HTML, include_bytes!("../../../site/index.html")),
(
"/index.html",
HTML,
include_bytes!("../../../site/index.html"),
),
(
"/terms.html",
HTML,
include_bytes!("../../../site/terms.html"),
),
(
"/privacy.html",
HTML,
include_bytes!("../../../site/privacy.html"),
),
(
"/img/defi.webp",
WEBP,
include_bytes!("../../../site/img/defi.webp"),
),
(
"/img/parties.webp",
WEBP,
include_bytes!("../../../site/img/parties.webp"),
),
(
"/img/statistiques.webp",
WEBP,
include_bytes!("../../../site/img/statistiques.webp"),
),
// Riot's check that the product URL is ours (#147).
("/riot.txt", TEXT, include_bytes!("../../../site/riot.txt")),
];
/// The content type and content of the page at `url`, if there is one.
pub(crate) fn page(url: &str) -> Option<(&'static str, &'static [u8])> {
PAGES
.iter()
.find(|(path, ..)| *path == url)
.map(|&(_, content_type, content)| (content_type, content))
}
+181
View File
@@ -0,0 +1,181 @@
//! The six calls go to Riot unchanged with the key; everything else is refused; Riot's statuses
//! are passed or translated; the key never leaves and the log names no one.
mod common;
use std::io::Write;
use std::sync::{Arc, Mutex, OnceLock};
use common::{FakeRiot, KEY, Seen, config, get, request, start};
const PUUID: &str =
"pUuIdOfTheTestAccount-0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRST";
const SIX: [&str; 6] = [
"/europe/riot/account/v1/accounts/by-riot-id/Le%20Joueur/EUW",
"/europe/riot/account/v1/region/by-game/lol/by-puuid/P",
"/americas/lol/match/v5/matches/by-puuid/P/ids?queue=1750&start=0&count=100&startTime=1700000000",
"/sea/lol/match/v5/matches/OC1_7",
"/asia/lol/match/v5/matches/KR_7/timeline",
"/euw1/lol/champion-mastery/v4/champion-masteries/by-puuid/P",
];
#[derive(Clone, Default)]
struct Shared(Arc<Mutex<Vec<u8>>>);
impl Write for Shared {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
self.0.lock().unwrap().write(buf)
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
/// The relay's log for this test binary (one logger per process).
fn log() -> String {
static LOG: OnceLock<Shared> = OnceLock::new();
let shared = LOG.get_or_init(|| {
let shared = Shared::default();
arena_tracker_relay::log_to(Box::new(shared.clone())).unwrap();
shared
});
String::from_utf8(shared.0.lock().unwrap().clone()).unwrap()
}
#[test]
fn the_six_calls_reach_riot_unchanged_with_the_key() {
let riot = FakeRiot::echo();
let relay = start(config(riot.upstream(), &[]));
for path in SIX {
let got = get(&relay, path);
assert_eq!(got.status, 200, "{path}");
assert_eq!(got.body, format!("{{\"path\":\"{path}\"}}"));
assert!(got.headers.contains("application/json"), "{}", got.headers);
}
let expected: Vec<_> = SIX
.iter()
.map(|path| Seen {
path: path.to_string(),
token: Some(KEY.into()),
})
.collect();
assert_eq!(riot.seen(), expected);
}
#[test]
fn anything_else_is_refused_without_calling_riot() {
let riot = FakeRiot::echo();
let relay = start(config(riot.upstream(), &[]));
for path in [
"/europe/lol/status/v4/platform-data",
"/eu/lol/match/v5/matches/EUW1_1",
"/euw1/lol/match/v5/matches/EUW1_1",
"/europe/lol/match/v5/matches/by-puuid/P/ids?queue=420",
"/europe/lol/match/v5/matches/by-puuid/P/ids?queue=1700&count=101",
"/europe/lol/match/v5/matches/by-puuid/P/ids?queue=1700&api_key=x",
"/europe/lol/match/v5/matches/%2E%2E/%2E%2E/status",
] {
assert_eq!(get(&relay, path).status, 404, "{path}");
}
for method in ["POST", "PUT", "DELETE", "HEAD"] {
assert_eq!(
request(method, &relay, SIX[3], None).status,
404,
"{method}"
);
}
assert_eq!(riot.seen(), []);
}
#[test]
fn riot_statuses_are_passed_except_a_refused_key() {
let riot = FakeRiot::start(|path| {
let status = path.rsplit('/').next().unwrap().split('_').next().unwrap();
let status = match status {
"timeline" => 403,
s => s.parse().unwrap_or(200),
};
(status, "", format!("{{\"status\":{status}}}"))
});
let relay = start(config(riot.upstream(), &[]));
let matches = "/europe/lol/match/v5/matches/";
for (id, expected) in [
("404_1", 404),
("400_1", 400),
("500_1", 500),
("401_1", 503),
("403_1", 503),
] {
let got = get(&relay, &format!("{matches}{id}"));
assert_eq!(got.status, expected, "{id}");
if expected == 503 {
assert_eq!(got.body, "", "Riot's body about the key stays on the relay");
} else {
assert_eq!(got.body, format!("{{\"status\":{expected}}}"));
}
}
// A refused timeline is the Match's, not the key's.
let got = get(&relay, &format!("{matches}EUW1_1/timeline"));
assert_eq!((got.status, got.body.as_str()), (403, "{\"status\":403}"));
}
#[test]
fn an_unreachable_riot_gives_502() {
// A port that was free a moment ago.
let addr = std::net::TcpListener::bind("127.0.0.1:0")
.unwrap()
.local_addr()
.unwrap();
let relay = start(config(format!("http://{addr}"), &[]));
assert_eq!(get(&relay, SIX[3]).status, 502);
}
#[test]
fn the_key_is_in_no_response_and_the_log_names_no_one() {
let riot = FakeRiot::start(|path| {
let echo = "X-Echo: RGAPI-12345678-abcd-ef01-2345-6789abcdef01\r\n";
if path.ends_with("/timeline") {
(403, echo, "{}".into()) // passed as is: its body is the Match's
} else {
(401, echo, format!("{{\"key\":\"{KEY}\"}}"))
}
});
let relay = start(config(riot.upstream(), &[]));
let _ = log();
let paths: Vec<String> = SIX
.iter()
.map(|p| p.replace("/P", &format!("/{PUUID}")))
.collect();
for path in &paths {
let got = get(&relay, path);
assert!(
!got.body.contains(KEY) && !got.headers.contains(KEY),
"{path}: {}",
got.headers
);
}
let log = log();
for kind in [
"account-by-riot-id",
"platform",
"match-ids",
"match",
"timeline",
"mastery",
] {
assert!(log.contains(&format!("INFO {kind}: ")), "{kind}: {log}");
}
for secret in [
KEY,
PUUID,
"Le%20Joueur",
"Joueur",
"127.0.0.1",
"/lol/",
"/riot/",
"KR_7",
] {
assert!(!log.contains(secret), "{secret}: {log}");
}
}
+143
View File
@@ -0,0 +1,143 @@
//! A relay on a free port in front of a fake Riot, and a client for it.
#![allow(dead_code)] // each test file uses part of it
use std::io::{BufRead, BufReader, Write};
use std::net::{IpAddr, SocketAddr, TcpListener};
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;
use arena_tracker_relay::{Config, Relay};
pub const KEY: &str = "RGAPI-12345678-abcd-ef01-2345-6789abcdef01";
/// A request Riot received.
#[derive(Clone, Debug, PartialEq)]
pub struct Seen {
pub path: String,
pub token: Option<String>,
}
type Answer = dyn Fn(&str) -> (u16, &'static str, String) + Send + Sync;
/// Answers each request with `answer(path)`: status, extra header lines, body.
pub struct FakeRiot {
pub addr: SocketAddr,
pub seen: Arc<Mutex<Vec<Seen>>>,
}
impl FakeRiot {
pub fn start(
answer: impl Fn(&str) -> (u16, &'static str, String) + Send + Sync + 'static,
) -> FakeRiot {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
let seen = Arc::new(Mutex::new(Vec::new()));
let answer: Arc<Answer> = Arc::new(answer);
let recorded = Arc::clone(&seen);
thread::spawn(move || {
for stream in listener.incoming() {
let Ok(mut stream) = stream else { continue };
let mut lines = BufReader::new(stream.try_clone().unwrap()).lines();
let request_line = lines.next().unwrap().unwrap();
let path = request_line.split(' ').nth(1).unwrap().to_string();
let mut token = None;
for line in lines.map_while(Result::ok).take_while(|l| !l.is_empty()) {
if let Some((name, value)) = line.split_once(':')
&& name.eq_ignore_ascii_case("x-riot-token")
{
token = Some(value.trim().to_string());
}
}
recorded.lock().unwrap().push(Seen {
path: path.clone(),
token,
});
let (status, headers, body) = answer(&path);
let _ = write!(
stream,
"HTTP/1.1 {status} X\r\n{headers}Content-Type: application/json;charset=utf-8\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
body.len()
);
}
});
FakeRiot { addr, seen }
}
/// Echoes the path it was asked, as Riot's 200.
pub fn echo() -> FakeRiot {
FakeRiot::start(|path| (200, "", format!("{{\"path\":\"{path}\"}}")))
}
/// `{routing}` goes into the path, so the fake sees which host the relay chose.
pub fn upstream(&self) -> String {
format!("http://{}/{{routing}}", self.addr)
}
pub fn seen(&self) -> Vec<Seen> {
self.seen.lock().unwrap().clone()
}
}
/// The configuration `from_env` reads, on a free port, with the fake as Riot and `vars` on top
/// of the defaults.
pub fn config(upstream: String, vars: &[(&str, &str)]) -> Config {
Config::from_env(|name| match name {
"RIOT_API_KEY" => Some(KEY.into()),
"RELAY_LISTEN" => Some("127.0.0.1:0".into()),
"RELAY_UPSTREAM" => Some(upstream.clone()),
name => vars
.iter()
.find(|(n, _)| *n == name)
.map(|(_, v)| v.to_string()),
})
.unwrap()
}
/// Starts the relay and returns its base URL.
pub fn start(config: Config) -> String {
let relay = Relay::bind(config).unwrap();
let base = format!("http://{}", relay.local_addr().unwrap());
thread::spawn(move || relay.run());
base
}
pub struct Got {
pub status: u16,
pub retry_after: Option<String>,
pub headers: String,
pub body: String,
pub bytes: Vec<u8>,
}
pub fn get(base: &str, path: &str) -> Got {
request("GET", base, path, None)
}
pub fn request(method: &str, base: &str, path: &str, forwarded_for: Option<IpAddr>) -> Got {
let agent: ureq::Agent = ureq::Agent::config_builder()
.http_status_as_error(false)
.timeout_global(Some(Duration::from_secs(10)))
.build()
.into();
let request = ureq::http::Request::builder()
.method(method)
.uri(format!("{base}{path}"));
let request = match forwarded_for {
Some(ip) => request.header("X-Forwarded-For", format!("203.0.113.9, {ip}")),
None => request,
};
let mut response = agent.run(request.body(()).unwrap()).unwrap();
let mut got = Got {
status: response.status().as_u16(),
retry_after: response
.headers()
.get("retry-after")
.map(|v| v.to_str().unwrap().to_string()),
headers: format!("{:?}", response.headers()),
body: String::new(),
bytes: response.body_mut().read_to_vec().unwrap(),
};
got.body = String::from_utf8_lossy(&got.bytes).into_owned();
got
}
+118
View File
@@ -0,0 +1,118 @@
//! The quota per routing value, the limit per client address and Riot's own 429: each answers
//! 429 with Retry-After at once, without calling Riot.
mod common;
use std::net::IpAddr;
use std::time::{Duration, Instant};
use common::{FakeRiot, config, get, request, start};
const EUROPE: &str = "/europe/lol/match/v5/matches/EUW1_1";
const AMERICAS: &str = "/americas/lol/match/v5/matches/NA1_1";
fn ip(text: &str) -> Option<IpAddr> {
Some(text.parse().unwrap())
}
#[test]
fn a_full_routing_value_answers_429_at_once_and_the_others_go_on() {
let riot = FakeRiot::echo();
let relay = start(config(
riot.upstream(),
&[("RELAY_ROUTE_LIMITS", "2/60,100/600")],
));
assert_eq!(get(&relay, EUROPE).status, 200);
assert_eq!(get(&relay, EUROPE).status, 200);
let asked = Instant::now();
let full = get(&relay, EUROPE);
assert!(asked.elapsed() < Duration::from_secs(1));
assert_eq!(full.status, 429);
assert_eq!(full.retry_after.as_deref(), Some("60"));
assert_eq!(get(&relay, AMERICAS).status, 200);
assert_eq!(riot.seen().len(), 3);
}
#[test]
fn each_client_address_has_its_limit() {
let riot = FakeRiot::echo();
let relay = start(config(riot.upstream(), &[("RELAY_CLIENT_LIMITS", "2/10")]));
assert_eq!(get(&relay, EUROPE).status, 200);
assert_eq!(get(&relay, AMERICAS).status, 200);
let full = get(&relay, EUROPE);
assert_eq!(
(full.status, full.retry_after.as_deref()),
(429, Some("10"))
);
// Not from the trusted proxy: the forwarded address is not believed.
assert_eq!(
request("GET", &relay, EUROPE, ip("198.51.100.1")).status,
429
);
assert_eq!(riot.seen().len(), 2);
}
#[test]
fn behind_the_trusted_proxy_the_forwarded_address_counts() {
let riot = FakeRiot::echo();
let relay = start(config(
riot.upstream(),
&[
("RELAY_CLIENT_LIMITS", "1/10"),
("RELAY_TRUSTED_PROXY", "127.0.0.1"),
],
));
for client in ["198.51.100.1", "198.51.100.2", "2001:db8::1"] {
assert_eq!(
request("GET", &relay, EUROPE, ip(client)).status,
200,
"{client}"
);
}
assert_eq!(
request("GET", &relay, EUROPE, ip("198.51.100.1")).status,
429
);
}
#[test]
fn a_riot_429_is_passed_with_its_delay_and_suspends_its_routing_value() {
let riot = FakeRiot::start(|path| match path.starts_with("/europe/") {
true => (429, "Retry-After: 7\r\n", "{\"status\":429}".into()),
false => (200, "", "{}".into()),
});
let relay = start(config(riot.upstream(), &[]));
let got = get(&relay, EUROPE);
assert_eq!((got.status, got.retry_after.as_deref()), (429, Some("7")));
assert_eq!(got.body, "{\"status\":429}");
let again = get(
&relay,
"/europe/riot/account/v1/region/by-game/lol/by-puuid/P",
);
assert_eq!(again.status, 429);
let left: u64 = again.retry_after.unwrap().parse().unwrap();
assert!((6..=7).contains(&left), "{left}");
assert_eq!(get(&relay, AMERICAS).status, 200);
assert_eq!(
riot.seen().len(),
2,
"the suspended call did not reach Riot"
);
}
#[test]
fn a_riot_429_without_a_delay_suspends_for_10_s() {
let riot = FakeRiot::start(|_| (429, "", String::new()));
let relay = start(config(riot.upstream(), &[]));
assert_eq!(get(&relay, EUROPE).retry_after.as_deref(), Some("10"));
assert_eq!(get(&relay, EUROPE).status, 429);
assert_eq!(riot.seen().len(), 1);
}
#[test]
fn a_riot_429_asking_for_ever_is_capped_at_a_day() {
let riot = FakeRiot::start(|_| (429, "Retry-After: 18446744073709551615\r\n", String::new()));
let relay = start(config(riot.upstream(), &[]));
assert_eq!(get(&relay, EUROPE).retry_after.as_deref(), Some("86400"));
assert_eq!(get(&relay, EUROPE).status, 429, "the relay is still up");
}
+65
View File
@@ -0,0 +1,65 @@
//! The site's files come from the relay itself, without calling Riot.
mod common;
use std::fs;
use std::path::Path;
use common::{FakeRiot, config, get, request, start};
/// Every file of `site/`, relative to it, with `/` separators.
fn files(dir: &Path, prefix: &str, out: &mut Vec<String>) {
for entry in fs::read_dir(dir).unwrap() {
let entry = entry.unwrap();
let name = format!("{prefix}{}", entry.file_name().to_str().unwrap());
if entry.file_type().unwrap().is_dir() {
files(&entry.path(), &format!("{name}/"), out);
} else {
out.push(name);
}
}
}
#[test]
fn every_file_of_the_site_is_served_with_its_type() {
let site = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../site");
let mut all = Vec::new();
files(&site, "", &mut all);
assert!(all.contains(&"index.html".into()), "{all:?}");
let riot = FakeRiot::echo();
let relay = start(config(riot.upstream(), &[]));
for file in &all {
let got = get(&relay, &format!("/{file}"));
assert_eq!(
got.status, 200,
"{file}: a new file needs a row in src/site.rs"
);
assert_eq!(got.bytes, fs::read(site.join(file)).unwrap(), "{file}");
let content_type = match file.rsplit('.').next() {
Some("html") => "text/html; charset=utf-8",
Some("webp") => "image/webp",
Some("txt") => "text/plain; charset=utf-8",
other => panic!("{file}: no content type for {other:?}"),
};
assert!(
got.headers.contains(content_type),
"{file}: {}",
got.headers
);
}
assert_eq!(
get(&relay, "/").bytes,
fs::read(site.join("index.html")).unwrap()
);
for path in [
"/site/index.html",
"/terms",
"/../site/terms.html",
"/index.html?x=1",
"/img/",
] {
assert_eq!(get(&relay, path).status, 404, "{path}");
}
assert_eq!(request("POST", &relay, "/", None).status, 404);
assert_eq!(riot.seen(), []);
}
@@ -6,6 +6,8 @@ status: accepted
The app reads the local League client API for the active Account and for live state (champ select, end of a Match), and the Riot web API for Match history. We accept the cost of a second integration and a personal Riot API key because the client alone cannot backfill: measured on 2026-11-15, its match history endpoint returns only the 20 most recent games across all game modes and ignores paging, while the Riot API keeps about two years.
The personal key is replaced by a relay holding the production key: ADR-0008.
## Considered Options
- **Client only**: no API key, but history limited to 20 recent games, so past Seasons and any Match played while the app was closed for long would be lost.
@@ -0,0 +1,23 @@
---
status: accepted
---
# Riot calls go through a relay that holds the production key
This replaces the "personal Riot API key" part of ADR-0001; its two data sources stand. The app no longer sends a key: it calls a relay run by the maintainer, which holds Arena Tracker's production key, forwards only the app's six Riot calls and shares the quota between players (spec #144). Riot forbids opening an app to the public on a personal key and shipping a key inside a distributed binary, and a personal key (100 requests per 2 minutes) makes an import slow.
The relay (`crates/relay`) is a request in, a request out: `/{routing value}{Riot path}`, a closed list of routing values and routes, no cache and nothing stored. It counts requests per routing value at the production limits and per client address, and answers 429 with Retry-After at once when either is full, or when Riot itself answered 429 for that routing value. A refused key (401, 403) becomes 503: it is the relay's problem, not the player's. A 403 on a Match's timeline is passed as is: Riot refuses some timelines on their own. The same process serves the Arena Tracker site (`site/`, #145), built into its binary, so there is one thing to deploy on the home server and the pages describe the service that serves them. Running it: `docs/service-relais.md`.
## Considered Options
- **Each player's own personal key** (ADR-0001): not allowed for a public app, and a key to request, enter and renew for every player.
- **The production key in the binary**: forbidden by Riot, and readable by anyone who has the app.
- **The site apart, served by the reverse proxy**: one less job for the process that holds the key, but two things to deploy and keep in step.
- **An async server (tokio, axum)**: more throughput than the quota allows; the relay uses threads and the `ureq` client the core already uses.
## Consequences
- When the relay is down, imports stop; what is stored stays readable.
- The relay sees each player's address and Riot IDs in transit; it logs only the type of call, the status and the duration.
- A PUUID depends on the key's Riot application: switching to the production key changes every stored one (#150).
- Not built yet: a cache of Matches (if the quota is reached), Riot's per-method limits (its 429 is respected).
+38
View File
@@ -0,0 +1,38 @@
# Demande de clé de production Riot (#147)
Le formulaire « Register Product » du portail développeur de Riot (https://developer.riotgames.com), rempli tel que ci-dessous. La description est un seul champ de texte brut, limité à 1 500 caractères (celle-ci en fait 1 434), à coller tel quel. La réponse de Riot et les limites accordées se notent dans #147, jamais la clé.
| Champ | Valeur |
|---|---|
| Product Name | Arena Tracker |
| Product Group | Default Group |
| Product URL | https://arena-tracker.nessar.fr/ |
| Product Game Focus | League of Legends |
| Are you organizing tournaments? | No |
## Product Description
```text
Arena Tracker is a free Windows app (AGPL 3.0) that tracks a player's League of Legends Arena challenge: placing first with every champion. It imports the player's Arena matches and shows, per Season, which champions they have played and placed first with, each match's recap with its Death Recap, and stats. In champion select it highlights the champions still needed; it only reads the local client, never acts. A player can add a friend by Riot ID to see their progress. All data stays on the player's computer.
APIs (GET only):
- ACCOUNT-V1 by-riot-id and region by-puuid: adding an account or friend
- MATCH-V5 ids by puuid (Arena queues only, count <= 100), match by id (fetched once, kept), timeline (only when a Death Recap is opened)
- CHAMPION-MASTERY-V4 by puuid: sorting champions
The key stays on our server (arena-tracker.nessar.fr): the app calls it, and it forwards only these calls and refuses anything else. It enforces the key's limits per routing value, honors Riot's 429 and Retry-After, and limits each client IP so no one uses the whole quota. It stores and caches nothing and logs no Riot ID, PUUID or IP. About 500 requests for a heavy player's first import, then a few per day; tens of players at first, mostly EUW.
No monetization. Today players use personal keys; the service version ships once this key is granted.
Terms: arena-tracker.nessar.fr/terms.html
Privacy: arena-tracker.nessar.fr/privacy.html
```
## À garder exact
Ce texte engage le projet auprès de Riot. Quand l'un de ces points change, mettre la page à jour et, si la demande est en cours d'examen, le signaler à Riot :
- les six appels et quand ils partent (`crates/core/src/riot.rs`, `crates/relay/src/route.rs`) ;
- les limites du service (`crates/relay/src/config.rs`) ;
- ce qu'il journalise et garde (rien) ;
- l'absence de statistiques d'objets et d'améliorations (#46 à #48) ;
- la clé personnelle de chaque joueur, qui disparaît avec #149.
+11 -2
View File
@@ -2,9 +2,9 @@
## Défi et Statistiques
L’appli s’ouvre sur **Défi** : la bannière du Défi de la Saison, puis les cartes de vos champions. À côté des onglets, le sélecteur de **Compte** liste les Comptes déjà connectés au client sur ce PC, le Compte actif (celui du client) en premier, et choisit le Compte que montrent **Défi**, **Statistiques** et **Parties** (les Comptes sous « Vos Comptes », vos Amis sous « Amis »). Pour un autre Compte, la bannière commence par « Défi de Pseudo · », et la Progression officielle et l’animation de fin de Partie sont réservées au Compte actif. Le filtre **Tous** revient à chaque changement de Compte ; le tri et le thème restent les mêmes. L’appli revient sur le Compte actif quand une Sélection ou une Partie en cours commence, et à la fin d’une Partie suivie. Pour l’analyse détaillée (courbe des champions validés, Placements, Tentatives, tableau des champions, avec les sélecteurs de Saison et de Format), ouvrez **Statistiques ›**, le lien au bout de la ligne de la Saison, en haut de la bannière. La page porte **‹ Défi** en haut à gauche, qui ramène au Défi ; l’onglet **Défi** de la barre du haut y ramène aussi. Au clavier, Tab atteint le lien et le retour, Entrée ou Espace les active. Survolez l’anneau de la bannière : la graduation visée s’allume et la bannière présente ce champion (« X · validé le 12 nov. · 3 Tentatives », « X · 2 Parties · meilleur Placement 3ᵉ » ou « X · jamais joué ») ; elle revient à son état habituel quand vous quittez l’anneau.
L’appli s’ouvre sur **Défi** : la bannière du Défi de la Saison, puis les cartes de vos champions. À côté des onglets, le sélecteur de **Compte** liste les Comptes déjà connectés au client sur ce PC, le Compte actif (celui du client) en premier, et choisit le Compte que montrent **Défi**, **Statistiques** et **Parties** (les Comptes sous « Vos Comptes », vos Amis sous « Amis »). Pour un autre Compte, la bannière commence par « Défi de Pseudo · », et la Progression officielle et l’animation de fin de Partie sont réservées au Compte actif. Le filtre **Tous** revient à chaque changement de Compte ; le tri et le thème restent les mêmes. L’appli revient sur le Compte actif quand une Sélection ou une Partie en cours commence, et à la fin d’une Partie suivie. Pour l’analyse détaillée (courbe des champions validés, Placements, Tentatives, tableau des champions, avec les sélecteurs de Saison et de Format), cliquez l’icône de courbe **Statistiques**, dans le coin inférieur droit de la bannière (une bulle la nomme au survol). La page porte **‹ Défi** en haut à gauche, qui ramène au Défi ; l’onglet **Défi** de la barre du haut y ramène aussi. Au clavier, Tab atteint l’icône et le retour, Entrée ou Espace les active. Survolez l’anneau de la bannière : la graduation visée s’allume et la bannière présente ce champion (« X · validé le 12 nov. · 3 Tentatives », « X · 2 Parties · meilleur Placement 3ᵉ » ou « X · jamais joué ») ; elle revient à son état habituel quand vous quittez l’anneau.
Au début d’une Sélection des champions Arena, l’onglet **Sélection** apparaît à droite de **Défi** et **Parties** et l’appli l’affiche d’elle-même, où que vous soyez. Il montre les Champions de l’Enclume et « Autres champions ». Pendant la sélection, l’onglet **Défi** montre l’accueil habituel (et **Statistiques ›**) ; revenez sur **Sélection** quand vous voulez, la main y est posée. Les bans et les choix des alliés ne vous ramènent pas sur **Sélection**. À la fin de la sélection, l’onglet disparaît et l’appli affiche le Défi, ou **En partie** si la partie est lancée.
Au début d’une Sélection des champions Arena, l’onglet **Sélection** apparaît à droite de **Défi** et **Parties** et l’appli l’affiche d’elle-même, où que vous soyez. Il montre les Champions de l’Enclume et « Autres champions ». Pendant la sélection, l’onglet **Défi** montre l’accueil habituel (et son icône **Statistiques**) ; revenez sur **Sélection** quand vous voulez, la main y est posée. Les bans et les choix des alliés ne vous ramènent pas sur **Sélection**. À la fin de la sélection, l’onglet disparaît et l’appli affiche le Défi, ou **En partie** si la partie est lancée.
Au lancement d’une Partie Arena, y compris quand l’appli démarre ou retrouve le client en pleine partie, l’onglet **En partie** apparaît à la place de **Sélection** et l’appli l’affiche, où que vous soyez. Sa bannière montre le champion que vous jouez sur son illustration, avec la Saison et le compteur du Défi, l’anneau où sa graduation est allumée, et l’enjeu : « Un top 1 validerait X : 88 / 172 », ou le jour où il a été validé. Dessous, sa fiche (Parties, Victoires, meilleur Placement, Tentatives, points de maîtrise, premier top 1) et ses 5 dernières Parties de la Saison, avec date, Format et Placement. Tant que le client n’a pas dit quel champion vous jouez (en Bravery, par exemple), la bannière indique « Champion en cours d’identification ». **Défi** et **Statistiques** restent accessibles pendant la partie. L’onglet reste jusqu’au résultat de la Partie ; une partie hors Arena ne fait rien apparaître.
@@ -55,12 +55,20 @@ Dans **Paramètres**, la section **Comptes** liste vos Comptes puis vos Amis, ch
Le Compte connecté au client ne peut pas être supprimé tant qu’il l’est : son bouton est grisé, avec « Compte connecté au client ». Un de vos Comptes supprimé redevient l’un de vos Comptes, avec un nouvel import, dès qu’il se reconnecte au client. Un Ami supprimé se rajoute comme un autre, avec un import complet.
## Mention légale de Riot
En bas de **Paramètres**, et donc aussi de l’écran de la clé API du premier lancement, qui est le même formulaire, la mention légale de Riot, en anglais, précise qu’Arena Tracker n’est pas approuvé par Riot Games. Quand la fenêtre est petite, **Paramètres** défile pour qu’elle reste accessible.
## Fermer la fenêtre
Par défaut, le bouton de fermeture cache la fenêtre dans la zone de notification, et Arena Tracker continue de suivre les Parties. Un double-clic sur son icône rouvre la fenêtre ; un clic droit propose « Ouvrir » et « Quitter ». L’option **Fermer dans la zone de notification** des Paramètres désactive ce comportement : la fermeture quitte alors l’application.
Relancer Arena Tracker depuis le menu Démarrer pendant qu’il tourne ramène simplement sa fenêtre. Au début d’une Sélection des champions Arena, la fenêtre réduite ou cachée se rouvre d’elle-même, sans prendre le focus ; au lancement d’une Partie Arena aussi, sans prendre le focus (le jeu garde le clavier), mais une fenêtre seulement recouverte le reste.
## Journal de l’application
Arena Tracker tient un journal pour comprendre un problème sans avoir à le reproduire, par exemple pourquoi la fin d’une Partie n’a pas donné de Partie provisoire. Dans **Paramètres**, **Ouvrir le dossier des journaux** ouvre `%APPDATA%\arena-tracker\logs`, où `arena-tracker.log` garde les événements récents (lancement, client League, phases de la partie, fin de Partie, appels à Riot, synchronisations, erreurs). À 1 Mo, il devient `arena-tracker.1.log`, qui remplace l’ancien : le journal ne dépasse jamais deux fichiers. Il ne contient ni votre clé API, ni le texte brut des données de Riot ou du client, ni un PUUID entier ; vos Riot ID y figurent. Il ne part nulle part : joignez-le vous-même à un signalement si vous le voulez.
## Données
La clé Riot, les préférences, les Parties et les Saisons sont dans `%APPDATA%\arena-tracker` :
@@ -72,6 +80,7 @@ La clé Riot, les préférences, les Parties et les Saisons sont dans `%APPDATA%
| `seasons.toml` | Table des Saisons, modifiable, relue au lancement |
| `portraits` | Portraits des champions |
| `game-data` | Noms et icônes des objets et des améliorations |
| `logs` | Journal de l’application (`arena-tracker.log`, 1 Mo, et `arena-tracker.1.log`) |
Les mises à jour, la désinstallation et la réinstallation conservent ce dossier. Le paquet de mise à jour téléchargé est conservé à part, dans `%LOCALAPPDATA%\arena-tracker\updates`. Pour tout effacer, supprimer ces deux dossiers après la désinstallation.
+14 -6
View File
@@ -34,7 +34,7 @@ Au survol ou au focus clavier, la fiche du champion apparaît en glissant sur la
### Pendant la sélection Arena
1. La détection d’une sélection Arena fait apparaître l’onglet « Sélection » à droite de « Défi » et « Parties » dans la barre du haut, et l’appli l’affiche, d’où que l’on soit (« Défi », « Statistiques », « Parties ») ; « Paramètres » se ferme. L’onglet montre la rangée de cartes sous la bannière de sélection. La règle de bascule est « la phase décide » : seule l’entrée dans une nouvelle phase déplace le joueur. Pendant la sélection, l’onglet « Défi » montre l’accueil habituel (bannière du Défi, grille, filtres, recherche, lien « Statistiques › »), pour le Compte connecté et la Saison en cours ; revenir sur « Sélection » montre la main posée, sans rejouer la distribution. Les bans et les choix qui arrivent pendant qu’un autre onglet est affiché ne ramènent pas sur « Sélection ». À la fin de la sélection (annulée ou partie lancée), l’onglet disparaît et l’appli affiche le Défi, ou « En partie » quand la Partie est lancée (voir « Pendant une Partie en cours »). Une sélection hors Arena ne fait rien apparaître. Le joueur garde le focus dans League : à l’entrée en sélection, la fenêtre passe au-dessus des autres fenêtres (League compris), qu’elle soit réduite, cachée dans la zone de notification ou seulement recouverte, sans prendre le focus, et reste ouverte à la fin de la sélection. Ce comportement n’a pas de réglage.
1. La détection d’une sélection Arena fait apparaître l’onglet « Sélection » à droite de « Défi » et « Parties » dans la barre du haut, et l’appli l’affiche, d’où que l’on soit (« Défi », « Statistiques », « Parties ») ; « Paramètres » se ferme. L’onglet montre la rangée de cartes sous la bannière de sélection. La règle de bascule est « la phase décide » : seule l’entrée dans une nouvelle phase déplace le joueur. Pendant la sélection, l’onglet « Défi » montre l’accueil habituel (bannière du Défi, grille, filtres, recherche, icône « Statistiques »), pour le Compte connecté et la Saison en cours ; revenir sur « Sélection » montre la main posée, sans rejouer la distribution. Les bans et les choix qui arrivent pendant qu’un autre onglet est affiché ne ramènent pas sur « Sélection ». À la fin de la sélection (annulée ou partie lancée), l’onglet disparaît et l’appli affiche le Défi, ou « En partie » quand la Partie est lancée (voir « Pendant une Partie en cours »). Une sélection hors Arena ne fait rien apparaître. Le joueur garde le focus dans League : à l’entrée en sélection, la fenêtre passe au-dessus des autres fenêtres (League compris), qu’elle soit réduite, cachée dans la zone de notification ou seulement recouverte, sans prendre le focus, et reste ouverte à la fin de la sélection. Ce comportement n’a pas de réglage.
2. La rangée « Champions de l’Enclume » contient **tous** les champions marqués d’une enclume dans la sélection en cours, dans le tri choisi. Au-dessous, « Autres champions » est replié par défaut. L’ouvrir affiche tous les champions sans enclume, avec le même tri et les mêmes cartes. Sa recherche par nom filtre uniquement cette section. La sélection défile comme une seule page (bannière, enclumes, « Autres champions »), avec une seule barre de défilement.
3. Dans les deux sections, les cartes gardent leur place lorsqu’un champion est validé, banni ou pris par un allié (dans la main, une carte prise par un allié s’abaisse seulement de 8 px). Son portrait est grisé et la carte indique les raisons applicables : « Validé », « Banni », « Pris par un allié », et « Indisponible » pour un champion que le client ne propose pas (non possédé ou désactivé). Un champion validé et banni porte les deux indications.
4. Une présélection alliée laisse la carte dans son état courant. « Pris par un allié » apparaît à la confirmation du choix. Les bans et les choix alliés expirent avec la sélection : ils n’affectent ni les coches personnelles, ni le compteur du Défi, ni la sélection suivante.
@@ -43,7 +43,7 @@ Au survol ou au focus clavier, la fiche du champion apparaît en glissant sur la
1. Au lancement d’une Partie en cours Arena (le client en partie, phases « GameStart », « InProgress » ou « Reconnect », y compris quand l’appli démarre ou retrouve le client en pleine partie), l’onglet « En partie » apparaît à droite de « Défi » et « Parties », « Sélection » disparaît, et l’appli l’affiche, d’où que l’on soit ; « Paramètres » se ferme. C’est la règle « la phase décide » de la sélection. Lancée depuis la sélection, la Partie attend la sortie de la main si « Sélection » est affichée, puis « En partie » sort du voile à la place du Défi ; ailleurs, il arrive avec le voile des transitions, ou d’un coup dans une fenêtre cachée ou réduite. Une fenêtre réduite ou cachée dans la zone de notification se rouvre sans prendre le focus (le jeu garde le clavier) ; une fenêtre seulement recouverte le reste : contrairement à la sélection, l’appli ne passe pas au-dessus des autres fenêtres. Un client trouvé sur l’écran de fin d’une partie n’ouvre rien : la Partie en cours n’a pas commencé sous ses yeux.
2. Pendant la Partie en cours, comme pendant une sélection, l’appli est celle du Compte connecté au client et de la Saison en cours : « Défi » montre son accueil, le sélecteur de Compte est grisé (son entrée a ramené le Compte actif), et « Défi » et « Statistiques » restent accessibles ; revenir sur « En partie » le montre tel qu’il était, sans rien recalculer. Seule l’entrée dans une nouvelle phase déplace le joueur.
3. **Bannière.** La bannière de l’accueil, sans le lien « Statistiques › » : l’illustration du champion joué, en surtitre la Saison et le compteur du Défi (« SAISON 2 · 2026 · 87 / 172 validés »), le nom du champion en titre, et l’anneau avec la graduation de ce champion allumée (aucune graduation éteinte). Sa ligne donne l’enjeu : « Un top 1 validerait X : 88 / 172 » (le compteur qu’il atteindrait) pour un champion non validé, « X validé le 12 nov. » pour un champion validé. Le champion joué est celui que dit la session de jeu ; lancée depuis la sélection, la Partie prend en attendant celui que la sélection a choisi. Tant que ni l’une ni l’autre ne l’a dit (Bravery, par exemple), la bannière n’a pas d’illustration, son titre est « Champion en cours d’identification », sa ligne est vide et aucune graduation n’est allumée. Le champion connu mais ses statistiques pas encore lues (client trouvé en pleine partie), ou absent des statistiques (un champion que le catalogue ne connaît pas encore), le titre est « Partie en cours ».
3. **Bannière.** La bannière de l’accueil, sans l’icône « Statistiques » : l’illustration du champion joué, en surtitre la Saison et le compteur du Défi (« SAISON 2 · 2026 · 87 / 172 validés »), le nom du champion en titre, et l’anneau avec la graduation de ce champion allumée (aucune graduation éteinte). Sa ligne donne l’enjeu : « Un top 1 validerait X : 88 / 172 » (le compteur qu’il atteindrait) pour un champion non validé, « X validé le 12 nov. » pour un champion validé. Le champion joué est celui que dit la session de jeu ; lancée depuis la sélection, la Partie prend en attendant celui que la sélection a choisi. Tant que ni l’une ni l’autre ne l’a dit (Bravery, par exemple), la bannière n’a pas d’illustration, son titre est « Champion en cours d’identification », sa ligne est vide et aucune graduation n’est allumée. Le champion connu mais ses statistiques pas encore lues (client trouvé en pleine partie), ou absent des statistiques (un champion que le catalogue ne connaît pas encore), le titre est « Partie en cours ».
4. **Fiche.** Sous la bannière, « Fiche du champion » reprend les lignes de la fiche de sa carte : Parties, Victoires, meilleur Placement, Tentatives, points de maîtrise, et « Premier top 1 » s’il est validé. À côté (dessous dans une fenêtre étroite), « Dernières Parties de la Saison » liste ses 5 dernières Parties de la Saison, de la plus récente à la plus ancienne, avec date et heure, Format et Placement coloré comme dans « Parties » (« Provisoire » le cas échéant) ; sans Partie, « Première Partie avec X cette Saison ». Sans statistiques, la ligne d’attente de l’accueil (« Chargement des statistiques… », « Compte indisponible ») tient leur place.
5. **Fin.** La Partie en cours dure jusqu’à l’arrivée de son bloc de fin, ou au retour au salon (ou la fermeture du client) sans bloc : son écran de fin en fait encore partie. Le bloc en fait une Partie : l’onglet disparaît et l’ouverture en fin de Partie décide (« Parties » sur son récapitulatif, ou le Défi si le réglage est coupé, voir « Page « Parties » ») ; le retour au salon qui suit ne déplace rien. Sans bloc, le retour au salon fait disparaître l’onglet et affiche le Défi, d’où que l’on soit. Si la fin ne choisit aucun écran alors que « En partie » est affiché (bloc d’un autre Compte, fin déjà décidée), le Défi s’affiche aussi. Un client fermé en pleine partie la termine ; rouvert sur elle (« Reconnect »), il la reprend, et c’est sa vraie fin qui décide à nouveau. Une partie hors Arena ne fait rien apparaître.
6. **Règle n° 1.** L’écran suit les événements du client déjà écoutés (session de jeu), sans lecture périodique : le champion est lu dans la session de jeu que chaque événement fait relire, et la Partie en cours démarre, change de champion ou s’arrête avec elle. Le texte de l’écran est préparé à son affichage, puis quand la Partie en cours ou les statistiques changent pendant qu’il est affiché, jamais au rendu ni caché ; les 5 Parties sont lues en arrière-plan, à basse priorité, quand le champion est connu, puis seulement si les Parties enregistrées ont changé (une nouvelle Partie, ou une Partie Provisoire publiée). Les listes d’objets et d’améliorations de #48 s’y ajouteront en v3.
@@ -56,7 +56,7 @@ Cette section décrit l’identité « L’Anneau ». [La page de référence](p
**Police.** Unbounded est embarquée et réservée au nom de l’appli, aux titres et au compteur. Tout le reste reste en Inter.
**Bannière d’accueil.** Un surtitre (la Saison), un titre-compteur, les deux lignes du critère 2 et l’anneau, sur l’illustration du champion de la Partie enregistrée la plus récente de la Saison affichée, tous Formats confondus : celle de la ligne « Dernière Partie » (aucune illustration sans Partie dans la Saison). Au bout droit de la ligne de la Saison (ou de la ligne « Aucune Saison en cours »), en petit, à la taille de cette ligne, un lien « Statistiques › » ouvre la page « Statistiques » (voir plus bas) ; dans une fenêtre étroite, il reste sur cette ligne si la place le permet, sinon il passe dessous sans la recouvrir ; la bannière de sélection n’a pas ce lien. Sans champion validé, la première ligne devient « Aucun champion validé pour l’instant. ».
**Bannière d’accueil.** Un surtitre (la Saison), un titre-compteur, les deux lignes du critère 2 et l’anneau, sur l’illustration du champion de la Partie enregistrée la plus récente de la Saison affichée, tous Formats confondus : celle de la ligne « Dernière Partie » (aucune illustration sans Partie dans la Saison). Dans le coin inférieur droit de la bannière, sur l’illustration, une icône de courbe (« Statistiques » en bulle de survol) ouvre la page « Statistiques » (voir plus bas) ; elle est posée dans les marges de la bannière et ne déplace jamais le texte ni l’anneau, ni au survol ni au focus ; à la même place dans une fenêtre étroite (anneau au-dessus du texte), le texte y garde ses distances (une marge de 40 px à sa droite, si bien que les longues lignes y passent à la ligne plus tôt) ; la bannière de sélection et celle de « En partie » n’ont pas cette icône. Sans champion validé, la première ligne devient « Aucun champion validé pour l’instant. ».
**Bannière de sélection.** Elle ouvre l’onglet « Sélection » pendant une sélection Arena ; « Défi » garde la bannière d’accueil. Son surtitre porte le compteur, son titre est « Sélection des champions », et sa ligne indique « Champions de l’Enclume · k à valider et disponibles ». Seules les graduations des Champions de l’Enclume y restent vives. L’illustration suit la carte survolée ; au repos, c’est celle du premier Champion de l’Enclume à valider et disponible. La barre du haut n’affiche pas d’autre indicateur de sélection que l’onglet « Sélection ».
@@ -70,13 +70,13 @@ Cette section décrit l’identité « L’Anneau ». [La page de référence](p
- Entrée en sélection, dès que la fenêtre montre l’onglet « Sélection » : une bande de lumière dorée traverse la fenêtre (≈ 0,9 s), « Sélection des champions » arrive en fondu en montant de 8 px, puis les Champions de l’Enclume montent du bas de la fenêtre l’un après l’autre (départ à 380 ms, puis toutes les 110 ms), sans rotation. L’onglet « Sélection » s’affiche d’un coup, sans voile, d’où que l’on soit : la bande de lumière tient lieu de transition. Elle ne joue qu’une fois par sélection : quitter « Sélection » pendant la distribution pose la main, et y revenir la montre posée. Une carte encore en mouvement ne réagit au survol ou au focus clavier qu’une fois posée ; si le pointeur bouge avant, le focus clavier en attente est oublié. Les motifs qui arrivent pendant la distribution s’affichent sur leur carte sans la relancer. Réglage Windows coupé : la main apparaît posée, sans balayage.
- Confirmation d’un allié : « Pris par un allié » apparaît sur sa carte de la main, qui s’abaisse de 8 px et se grise, même levée sous le pointeur ou le clavier ; elle reste 8 px plus bas que les autres. Rien d’autre ne bouge.
- Sortie de sélection, si « Sélection » est affichée : les cartes de la main descendent en s’effaçant (≈ 0,3 s, de la dernière à la première), chacune depuis là où elle est : une sortie pendant la distribution reprend les cartes en mouvement où elles en sont, celles pas encore parties restent invisibles ; une carte levée part de sa hauteur, toujours levée, les autres gardent le voile de la main, et une carte qu’une confirmation abaissait part d’où elle en était, sa version d’avant toujours en fondu par-dessus. Puis l’accueil revient comme après un changement d’onglet, dans l’état décrit plus haut (« Tous », recherche vide). Si le voile d’un changement d’onglet couvrait déjà « Sélection », il reste où il en est pendant que la main sort. Depuis « Défi », la sélection disparaît simplement ; depuis « Statistiques », le Défi revient avec le voile des transitions. Quand la sélection a lancé la Partie, c’est « En partie » qui revient à la place du Défi.
- Transitions entre « Défi », « Statistiques », « Parties », « Sélection » et « En partie » (le lien de la bannière, « ‹ Défi » ou les onglets les déclenchent) : l’écran sortant passe sous un voile de la couleur du fond (≈ 130 ms), puis l’entrant en sort (≈ 280 ms). La barre du haut ne bouge pas. Changer d’écran pendant une transition repart de là où en est le voile. Les sélecteurs de Saison et de Format sont sur la ligne du titre « Statistiques », sous le voile : la barre du haut, commune aux deux écrans, garde sa hauteur. Pas de glissement : déplacer l’écran redessinerait à chaque image la grille, l’anneau et les graphiques, qui sont en cache.
- Transitions entre « Défi », « Statistiques », « Parties », « Sélection » et « En partie » (l’icône de la bannière, « ‹ Défi » ou les onglets les déclenchent) : l’écran sortant passe sous un voile de la couleur du fond (≈ 130 ms), puis l’entrant en sort (≈ 280 ms). La barre du haut ne bouge pas. Changer d’écran pendant une transition repart de là où en est le voile. Les sélecteurs de Saison et de Format sont sur la ligne du titre « Statistiques », sous le voile : la barre du haut, commune aux deux écrans, garde sa hauteur. Pas de glissement : déplacer l’écran redessinerait à chaque image la grille, l’anneau et les graphiques, qui sont en cache.
- Survol et focus clavier : le même sur toutes les cartes (grille de l’accueil, main de la sélection, « Autres champions »), en ≈ 350 ms. Une carte jouable monte de 10 px avec une ombre dorée ; une carte grisée monte de 4 px, sans ombre dorée. L’illustration zoome à 107 % dans la carte, qui garde sa taille, pendant que le nom et les coches s’effacent et que la fiche glisse depuis le bas. Quitter une carte en cours d’animation repart de là où elle en est. Une seule carte est levée à la fois : une carte levée au clavier redescend dès que le pointeur bouge. Une molette la repose aussitôt, même en haut ou en bas de la liste. Le voile sur les cartes voisines ne s’applique que dans la main de la sélection. Réglage Windows coupé : la fiche apparaît sans glisser et la carte ne monte pas.
- Limites de GPUI, sans le modifier (ADR-0004) : pas de rotation, pas d’espacement des lettres animé, une montée de la carte au lieu d’un grossissement, un voile au lieu d’un filtre ou d’un fondu de l’écran entier.
### Page « Statistiques »
La barre du haut n’a pas d’onglet « Statistiques » : la page est le détail du Défi. On l’ouvre par le lien « Statistiques › » de la bannière du Défi, avec le voile des transitions. Elle porte « ‹ Défi » en haut à gauche, avant le titre, qui ramène au Défi ; l’onglet « Défi » de la barre du haut reste allumé sur « Statistiques » et y ramène aussi. Le lien et le retour sont des boutons que le clavier atteint (Tab, puis Entrée ou Espace). Pendant une sélection Arena, la page reste accessible depuis « Défi », pour le Compte connecté au client ; la bannière de sélection n’a pas le lien, et l’entrée en sélection affiche « Sélection ».
La barre du haut n’a pas d’onglet « Statistiques » : la page est le détail du Défi. On l’ouvre par l’icône « Statistiques » du coin inférieur droit de la bannière du Défi, avec le voile des transitions. Elle porte « ‹ Défi » en haut à gauche, avant le titre, qui ramène au Défi ; l’onglet « Défi » de la barre du haut reste allumé sur « Statistiques » et y ramène aussi. L’icône et le retour sont des boutons que le clavier atteint (Tab, puis Entrée ou Espace). Pendant une sélection Arena, la page reste accessible depuis « Défi », pour le Compte connecté au client ; la bannière de sélection n’a pas l’icône, et l’entrée en sélection affiche « Sélection ».
Pour une Saison, présenter d’abord la courbe cumulée des champions validés, puis la répartition des Placements et les Tentatives nécessaires pour valider un champion. Réutiliser les statistiques existantes et conserver la consultation par Compte (choisi dans la barre du haut), Saison et Format. Dans « Toutes les Saisons », seules les statistiques qui ont un sens sur cette période s’appliquent. Le Défi reste propre à une Saison.
@@ -94,7 +94,7 @@ L’onglet permanent « Parties », à droite de « Défi » dans la barre du ha
- **Détails d’un joueur.** La ligne d’un joueur est un bouton (chevron à droite) : un clic, ou Entrée ou Espace une fois la ligne atteinte avec Tab, déplie ses détails dessous, un autre clic ou la même touche les replie. Un seul joueur est déplié à la fois ; l’état est gardé tant que la même Partie est décodée de nouveau (le joueur est retrouvé à sa nouvelle place quand un Placement corrigé réordonne les équipes ; replié si on ne le retrouve pas avec certitude), et oublié dès qu’on choisit une autre Partie, qu’on quitte l’écran ou qu’on change de Compte. Cinq rangées, dessinées en barres. « Dégâts aux champions » et « Dégâts reçus » sont chacune une seule barre, toujours de même longueur, partagée par type (Physiques, Magiques, Bruts, chacun sa couleur : rouge, bleu, et la couleur du texte pour les Bruts : blanc en thème sombre, encre foncée en thème clair), la part d’un type étant sa part de la somme des types (barre vide quand un type manque, comme dans une Partie provisoire, ou que leur somme est 0) ; le Total s’écrit à côté de la barre et la valeur de chaque type dans une petite légende dessous. « Protection », « Or » et « Contrôle » ont une barre par mesure, pleine pour le meilleur joueur de la Partie sur cette mesure, la valeur écrite en petit à côté de chaque barre ; une valeur absente laisse la barre vide et garde son mot. Les mesures sont : « Protection » (Dégâts atténués (sur soi), Soins aux alliés, Boucliers sur les alliés), « Or » (Or gagné, Or dépensé, suivis de « or ») et « Contrôle » (Contrôle infligé, en secondes ou « 1 min 23 s », puis Score de contrôle, le nombre brut de Riot, sans unité : une bulle sur son titre le précise, « Score Riot, sans unité »). Dégâts, soins et boucliers sont des points ; les milliers sont séparés par une espace fine insécable. Chaque total est celui que Riot publie, jamais la somme des types : ils peuvent différer. Une valeur absente s’affiche « Indisponible » (« En attente » dans une Partie provisoire), jamais 0 ; 0 n’apparaît que si la source le donne. Les valeurs sont écrites avec le récapitulatif, mais les éléments des détails ne sont construits que pour le joueur déplié : replié, le détail ne coûte rien à l’affichage.
- **Dégâts observés dans les récaps de mort.** Sous les cinq rangées des détails d’un joueur, une section titrée « Dégâts observés dans les récaps de mort ». Seule la chronologie Match‑V5 donne des dégâts par effet, et seulement ceux qu’un champion reçoit avant de mourir : chaque entrée de récap de mort est comptée une seule fois, pour le joueur qui l’a infligée et son effet. Les dégâts infligés à un champion qui survit ne sont jamais attribués ; le total de la Partie par effet est indisponible, ce que la section dit une fois, en gris (« Le total de la Partie par effet est indisponible : seuls les dégâts subis avant une élimination sont détaillés. Les dégâts infligés à un champion qui survit ne sont jamais attribués. »). Une ligne par objet ou amélioration du joueur reconnu (icône et nom du catalogue, comme dans le récapitulatif, total des dégâts, puis les types qui ont infligé quelque chose, « Physiques 120 · Magiques 80 »), du plus au moins dommageable, puis « Autres effets » (attaques de base, sorts du champion, effets qui ne sont pas un objet ou une amélioration de sa fin de Partie). La correspondance est automatique quand le nom de l’effet est l’`augmentNameId` d’une amélioration du joueur (sans tenir compte de la casse) ; les objets, et les améliorations dont le nom diffère, passent par une table d’exceptions tenue à la main (`death_recap/exceptions.tsv` du cœur) ; elle est refaite à chaque lecture, si bien qu’un catalogue renouvelé ou une exception ajoutée s’applique aux Parties déjà récupérées. États de la section : « En attente » pour une Partie provisoire (pas de chronologie, rien n’est demandé) ; « Chargement… » pendant la requête ; « Indisponible » quand Riot refuse la chronologie de cette Partie (403, retenu : elle n’est plus redemandée) ; un bouton « Réessayer » avec un message en cas d’échec passager (réseau, limiteur), qui redemande ; « Aucun dégât observé » quand aucune entrée ne nomme ce joueur. La chronologie est récupérée une fois par Partie : en arrière-plan, à basse priorité, dès qu’une nouvelle Partie suivie est publiée ; à la première ouverture du récapitulatif pour une Partie plus ancienne, sans jamais rattraper l’historique en masse ni pendant une synchronisation. Seules les entrées des récaps de mort sont gardées en base, jamais la chronologie. Les requêtes passent par le limiteur existant et respectent `Retry-After`. Le récapitulatif ouvert se relit quand la récupération en arrière-plan de sa Partie se termine. Une même chronologie n’est jamais demandée deux fois à la fois : une Partie publiée pendant que son récapitulatif est ouvert (ou ouverte alors qu’elle est en file) attend la récupération en cours. Un récap de mort mis en correspondance avec un ancien catalogue (récupération en cours quand les données du jeu changent) est relu avec le catalogue courant. La page ne lit qu’un récap de mort à la fois : pendant une lecture, seule la dernière demandée attend (une demande à Riot pour la même Partie n’est pas perdue), et quitter l’écran l’oublie ; parcourir la liste quand Riot est lent ne lance pas un thread par Partie.
- **Valeurs absentes.** Une valeur que la source ne donne pas s’affiche « Indisponible », en gris ; 0 seulement si la source donne 0. Dans une Partie provisoire, dont la source est le bloc de fin de partie du client, l’absence s’affiche « En attente ».
- **Disposition.** La bannière du Défi est en haut (#110) : la Saison (« Défi de Pseudo · » pour un autre Compte), le compteur, les lignes « Dernier champion validé » et « Dernière Partie », le lien « Statistiques › » et l’anneau, sur l’illustration du champion de la Partie choisie dans la liste, dont la graduation est allumée comme celle du champion joué sur « En partie » ; l’illustration passe en fondu quand le choix change. Sans Partie choisie (liste vide, filtres qui n’en gardent aucune), ni illustration ni graduation allumée. Dans une fenêtre basse, la colonne défile sous la bannière : la liste et le récapitulatif gardent au moins 240 px. Dessous, la liste (≈ 320 px, défilante, sous sa rangée de filtres) et le récapitulatif (défilant) côte à côte. Sous ≈ 900 px de large, la liste passe derrière un bouton « Parties » à chevron qui l’ouvre par-dessus le récapitulatif ; choisir une Partie la referme.
- **Disposition.** La bannière du Défi est en haut (#110) : la Saison (« Défi de Pseudo · » pour un autre Compte), le compteur, les lignes « Dernier champion validé » et « Dernière Partie », l’icône « Statistiques » dans le coin inférieur droit et l’anneau, sur l’illustration du champion de la Partie choisie dans la liste, dont la graduation est allumée comme celle du champion joué sur « En partie » ; l’illustration passe en fondu quand le choix change. Sans Partie choisie (liste vide, filtres qui n’en gardent aucune), ni illustration ni graduation allumée. Dans une fenêtre basse, la colonne défile sous la bannière : la liste et le récapitulatif gardent au moins 240 px. Dessous, la liste (≈ 320 px, défilante, sous sa rangée de filtres) et le récapitulatif (défilant) côte à côte. Sous ≈ 900 px de large, la liste passe derrière un bouton « Parties » à chevron qui l’ouvre par-dessus le récapitulatif ; choisir une Partie la referme.
- **Synchronisation.** Le bandeau, la ligne d’état et le bouton « Actualiser » de la barre de titre restent ceux des autres pages. Les Parties déjà connues restent consultables pendant la synchronisation et après un échec, qui s’affiche en une ligne au-dessus.
- **États vides.** Sans Compte, « Compte indisponible » ; sans Partie, « Aucune Partie enregistrée » ; Parties enregistrées mais aucune gardée par les filtres, « Aucune Partie ne correspond aux filtres » sous les filtres.
- **Règle n° 1.** La liste est la seule partie de l’écran à état propre (sélection, défilement, survol) : une vue en cache, dont seules les lignes visibles sont construites, et que le reste de la page redessiné ne redessine pas. La liste est lue en arrière-plan à l’ouverture de l’écran, puis quand les Parties enregistrées changent pendant qu’il est affiché ; caché, il est seulement marqué à relire, et il ne l’est que si les Parties enregistrées ont changé entre-temps (ou qu’une lecture a été coupée ou a échoué) : rouvrir l’écran sans changement ne relit pas la base, et choisit de nouveau la Partie la plus récente gardée. Un récapitulatif qui n’a pas pu être décodé l’est de nouveau quand la liste est relue ou que l’écran se rouvre. Un seul décodage de récapitulatif à la fois, un résultat périmé est jeté. Rien ne tourne au repos, et les portraits sont rendus en quittant l’écran.
@@ -103,6 +103,14 @@ L’onglet permanent « Parties », à droite de « Défi » dans la barre du ha
La section « Comptes » liste vos Comptes puis vos Amis, chacun avec « Supprimer ». Une confirmation est toujours demandée : « Supprimer Pseudo#TAG et ses N Parties enregistrées ? » (« sa Partie enregistrée » pour une seule, aucune mention pour zéro), suivie de « Les détails venus du client League ne pourront pas être récupérés. » quand le Compte a des détails que seul le client a donnés (Partie provisoire, bloc de fin de Partie conservé). La suppression efface les Parties et toutes les données enregistrées du Compte, points de maîtrise compris, puis la page relit ses Comptes : si le Compte supprimé était affiché, elle revient sur le Compte actif. Le Compte connecté au client ne se supprime pas : son bouton est grisé, avec « Compte connecté au client ». La liste est lue à l’ouverture de « Paramètres » et après une suppression ; la suppression et le décompte se font en arrière-plan, à basse priorité.
### « Paramètres » : mention légale de Riot
En bas de « Paramètres », et de l’écran de la clé API du premier lancement (même formulaire), la mention légale de Riot, en anglais, précise qu’Arena Tracker n’est pas approuvé par Riot Games. « Paramètres » défile à la hauteur minimale de la fenêtre, de sorte que la mention y reste accessible ; tant que tout tient, le formulaire reste centré.
### « Paramètres » : Journal
Le bouton « Ouvrir le dossier des journaux » ouvre dans l’Explorateur Windows le dossier `%APPDATA%\arena-tracker\logs` (créé au besoin ; si l’Explorateur ne démarre pas, la section dit « Impossible d’ouvrir le dossier des journaux. »). Il contient le journal de l’application (#142), `arena-tracker.log`, qui tourne à 1 Mo : le fichier plein devient `arena-tracker.1.log` (le précédent est remplacé), jamais plus de deux fichiers. Une ligne par événement, de niveau info, ou warn et error pour une attente et une erreur : le lancement (version de la release, ou `<version>-dev` dans une version de développement, et canal de mise à jour), le client League qui apparaît ou disparaît et le Compte connecté, les changements de phase de la partie, le bloc de fin de Partie (reçu, converti en Partie provisoire, ou en attente avec sa raison, en warn, une fois par raison), les appels à l’API Riot (type, résultat, durée) et leurs attentes de quota, le début et la fin d’une synchronisation ou d’un import (nombre de Parties) et chaque problème que la ligne d’état affiche. Jamais la clé API, le texte brut d’un bloc ou d’une réponse de Riot, ni un PUUID entier (ses 8 premiers caractères, au plus) ; les Riot ID y figurent, et l’adresse d’un appel Riot, qui peut contenir un PUUID, n’y figure pas : seul son type. Des autres bibliothèques (GPUI…), seules les erreurs y entrent, et jamais rien du client HTTP. Un second lancement, relayé à l’instance ouverte, n’écrit rien dans le journal. Les lignes sont mises en forme sur le thread qui les émet, puis écrites par un thread dédié, en priorité inférieure à la normale et bloqué au repos : pas de minuterie, ce qui est en mémoire tampon est écrit à la ligne suivante et à la fermeture. Dans la version de développement (`scripts/win run`), les mêmes lignes vont aussi sur la sortie d’erreur de la console.
## Décisions d’implémentation
- L’application cible reste l’application Windows native en GPUI via gpui-kit. L’accueil et la sélection réutilisent une seule représentation de carte. La logique de progression provient des Parties enregistrées, y compris pour les données antérieures à la refonte. La Progression officielle sert au contrôle du total.
+1 -1
View File
@@ -55,7 +55,7 @@ GPUI and gpui-component are not modified to meet a budget: the app's own renderi
The release benchmark runs these scenarios, in this order, on the reference machine (#32). Builds come from `scripts/prod build`, then `scripts/prod build --features profile`; each `arena-tracker.exe` is copied out of the target directory before the next build overwrites it, and started from that copy. `scripts/budget-probe.ps1` (from WSL: `powershell.exe -ExecutionPolicy Bypass -File scripts/budget-probe.ps1 <action>`) reads the app's own counters (process CPU time, each thread's CPU time and context switches, process GPU time and memory), never system-wide ones, and drives the window with posted messages.
- **Conditions.** Each probe prints the machine and the build first: check the CPU is the Ryzen 5 7640U and the build is the copy meant. The laptop is on mains power, the user is away (`info` prints the time since their last input) and no game runs; stop and wait otherwise. The data folder (`%APPDATA%\arena-tracker`) holds a Riot key, the imported Matches and the portraits: an empty page measures nothing. Each phase lasts under a minute; split a longer scenario into phases.
- **Idle, window visible (budget 2).** Start the release build, wait 30 s, `front`, then `cursor -X 0.5 -Y 0.012` (the real cursor still over the title). Run `sample -Seconds 30` twice on « Défi » and once on « Statistiques » (open it with `click` on the « Statistiques › » link at the end of the banner's Season line, its position read on a screenshot of the reference window; « Défi » is at `-X 0.03`). The budget is the process CPU; the table names each thread waking. The `IDLE cpu` line of the move and hover probes is not this budget: their ping thread wakes the UI thread hundreds of times per second.
- **Idle, window visible (budget 2).** Start the release build, wait 30 s, `front`, then `cursor -X 0.5 -Y 0.012` (the real cursor still over the title). Run `sample -Seconds 30` twice on « Défi » and once on « Statistiques » (open it with `click` on the chart icon in the banner's bottom-right corner, its position read on a screenshot of the reference window; « Défi » is at `-X 0.03`). The budget is the process CPU; the table names each thread waking. The `IDLE cpu` line of the move and hover probes is not this budget: their ping thread wakes the UI thread hundreds of times per second.
- **Interactions (budget 1).** On « Défi »: the move probe with `-Seconds 20`, then `wheel -X 0.5 -Y 0.75 -Count 300` (300 steps down at 20 per second) and the same with `-Delta 120` back up. On « Statistiques »: the hover probe and the move probe, `-Seconds 20` each. Then again on the profile build, started with `ARENA_TRACKER_PROFILE`, noting the CSV's line count at each phase's start and end to cut it into phases.
- **Minimised and hidden (budget 3).** `minimize`, wait 3 s, `sample -Seconds 30` twice; `restore`, then `close` (the window goes to the notification area, as `close_to_tray` is on), wait 3 s, `sample -Seconds 30`. Starting the app again shows the window again. On the profile build, the CSV shows no frame drawn during these phases.
- **Memory, full page loaded (budget 4).** From a fresh start, wait 15 s, `front`; scroll the home grid to its end (`wheel -X 0.5 -Y 0.75 -Count 150`), open « Statistiques » and scroll the table to its end (`wheel -X 0.5 -Y 0.85 -Count 120`), wait 10 s, then `memory`. Run it twice. To split the memory, the profile build runs the same scenario with `ARENA_TRACKER_HIDE` set to `cards`, `banner`, then `table,cards`.
+2 -2
View File
@@ -12,9 +12,9 @@ Le travail arrive sur develop en fast-forward, par pull request ou par push dire
## Fusion conditionnée à la CI
Une pull request vers develop ou main ne se fusionne que si le contrôle `CI / core (pull_request)` a réussi sur son dernier commit : un contrôle en échec ou en cours bloque le bouton de fusion, pour tout le monde, administrateur compris. Ce n’est pas dans le dépôt mais dans Gitea, **Paramètres → Branches**, une règle par branche (develop et main) :
Une pull request vers develop ou main ne se fusionne que si les contrôles `CI / core (pull_request)` et `CI / relay (pull_request)` ont réussi sur son dernier commit : un contrôle en échec ou en cours bloque le bouton de fusion, pour tout le monde, administrateur compris. Ce n’est pas dans le dépôt mais dans Gitea, **Paramètres → Branches**, une règle par branche (develop et main) :
- **Activer le contrôle de statut**, avec le contexte `CI / core (pull_request)` (le nom du workflow, du job et de l’événement, tel que Gitea l’affiche sur la pull request). Renommer le workflow `ci.yml` ou son job `core` oblige à corriger la règle, sinon la fusion reste bloquée.
- **Activer le contrôle de statut**, avec les contextes `CI / core (pull_request)` et `CI / relay (pull_request)` (le nom du workflow, du job et de l’événement, tel que Gitea l’affiche sur la pull request). Renommer le workflow `ci.yml` ou l’un de ses jobs `core` et `relay` oblige à corriger la règle, sinon la fusion reste bloquée.
- **Bloquer le contournement par les administrateurs** (`block_admin_merge_override`).
- **Liste blanche du push** : le mainteneur seul. Le push direct de develop et la promotion vers main restent possibles ; ils ne passent pas par une pull request et le contrôle de statut ne s’y applique pas.
- Push forcé désactivé.
+124
View File
@@ -0,0 +1,124 @@
# Service intermédiaire (relais Riot)
Le service garde la clé Riot d’Arena Tracker et relaie à Riot les six appels de l’application, en partageant le quota entre les joueurs. Il sert aussi le site d’Arena Tracker (ADR-0008). Il tourne sous Linux, derrière le proxy inverse du serveur maison. Il n’enregistre rien et n’a pas de cache.
## Lancer
```sh
RIOT_API_KEY=RGAPI-… cargo run --release -p arena-tracker-relay
```
Pour essayer en privé, la clé personnelle du mainteneur suffit (le quota réel est alors celui de cette clé : baisser `RELAY_ROUTE_LIMITS` à `20/1,100/120`). Le journal va sur la sortie d’erreur, une ligne par appel : son type, le statut et son origine, la durée.
| Variable | Défaut | Rôle |
|---|---|---|
| `RIOT_API_KEY` | (obligatoire) | La clé Riot. Jamais journalisée ni renvoyée. |
| `RELAY_LISTEN` | `127.0.0.1:8080` | Adresse d’écoute. |
| `RELAY_TRUSTED_PROXY` | aucun | Adresse IP du proxy inverse, ou son réseau (`172.18.0.0/16`) quand il tourne dans un conteneur dont l’adresse change : seul son en-tête `X-Forwarded-For` est cru (la dernière adresse de la liste, celle que le proxy a vue). Sans elle, l’adresse comptée est celle de la connexion. |
| `RELAY_ROUTE_LIMITS` | `500/10,30000/600` | Quota par valeur de routage : requêtes/secondes, séparés par des virgules. |
| `RELAY_CLIENT_LIMITS` | `100/10,3000/600` | Limite par adresse IP, même format. La politique de confidentialité dit qu’une adresse est gardée en mémoire 10 minutes au plus : une fenêtre plus longue oblige à la corriger. |
| `RELAY_UPSTREAM` | `https://{routing}.api.riotgames.com` | L’adresse de Riot, `{routing}` remplacé par la valeur de routage. |
Une valeur invalide ou une clé absente arrête le service au démarrage, avec un message.
Le proxy inverse ne doit pas tenir de journal d’accès pour le service : ses URL contiennent des Riot ID et des PUUID, et il voit l’adresse de chaque joueur.
## Conteneur
L’image ne contient que le binaire (statique, avec ses certificats racines), lancé sans droits ; elle écoute sur le port 8080. Pour la publier dans le registre de Gitea, depuis un commit poussé de develop ou de main, sans changements locaux :
```sh
docker login gitea.nessar.fr # une fois
scripts/publish-relay # gitea.nessar.fr/nessar/arena-tracker-relay:<commit> et :latest
```
Sur le serveur maison, le service tourne dans une stack Komodo, derrière Nginx Proxy Manager (NPM), lui-même derrière Cloudflare.
### Stack Komodo
```yaml
services:
arena-relay:
image: gitea.nessar.fr/nessar/arena-tracker-relay:latest
restart: unless-stopped
init: true # transmet l'arrêt au service : sans lui, docker stop attend 10 s
read_only: true
cap_drop: [ALL]
security_opt: [no-new-privileges:true]
environment:
RIOT_API_KEY: ${RIOT_API_KEY:?RIOT_API_KEY missing in the Komodo environment}
RELAY_TRUSTED_PROXY: ${RELAY_TRUSTED_PROXY:?RELAY_TRUSTED_PROXY missing}
RELAY_ROUTE_LIMITS: ${RELAY_ROUTE_LIMITS:-500/10,30000/600}
networks: [proxy] # le réseau de NPM ; aucun port publié
networks:
proxy:
external: true
```
Section **Environment** de la stack (Komodo en fait un `.env` qui ne sert qu'à remplir les `${…}` : chaque variable doit aussi figurer sous `environment:`) :
```sh
RIOT_API_KEY=[[RIOT_API_KEY]] # un Secret Komodo (Settings → Variables), masqué dans l'interface et les journaux
RELAY_TRUSTED_PROXY=172.18.0.0/16 # le sous-réseau de « proxy » : docker network inspect proxy
RELAY_ROUTE_LIMITS=20/1,100/120 # les limites de la clé personnelle, jusqu'à #152
```
Si le paquet de l'image est privé, Komodo a besoin d'un compte de registre Gitea (jeton `read:package`), choisi dans la configuration de la stack.
### NPM
Un Proxy Host pour `arena-tracker.nessar.fr` : hôte `arena-relay`, port 8080, certificat Let’s Encrypt (défi DNS par l'API de Cloudflare si le défi HTTP échoue), HTTPS forcé. Dans l’onglet **Advanced** :
```nginx
access_log off;
real_ip_header CF-Connecting-IP;
```
NPM ajoute à `X-Forwarded-For` l'adresse qui l'appelle. Derrière Cloudflare, c'est celle de Cloudflare : `real_ip_header` la remplace par l'adresse du joueur que Cloudflare transmet, crue seulement depuis les plages de Cloudflare (lignes `set_real_ip_from` que NPM écrit au démarrage dans `/etc/nginx/conf.d/include/ip_ranges.conf` ; les ajouter depuis https://www.cloudflare.com/ips/ si ce fichier est vide). Sans elle, tous les joueurs partageraient la limite de quelques adresses de Cloudflare.
Le service est public. Avec la clé personnelle, un tiers qui le trouverait consommerait son quota, et Riot n'admet pas une clé personnelle derrière un service public : c'est un choix du mainteneur jusqu'à #152. Pour le restreindre, ajouter dans **Advanced** un bloc qui ne laisse passer les appels Riot que depuis son adresse, le site restant public :
```nginx
location ~ ^/[a-z0-9]+/(riot|lol)/ {
allow 203.0.113.7; # l'adresse du mainteneur
deny all;
include conf.d/include/proxy.conf;
}
```
### Cloudflare
Pour ce sous-domaine : aucun défi (Bot Fight Mode, « Under Attack », défi géré), sinon les appels de l'application reçoivent une page JavaScript ; aucune règle « Cache Everything », sinon un 429 ou un 503 mis en cache toucherait tous les joueurs ; SSL en **Full (strict)**. Cloudflare voit passer les requêtes, adresse et URL comprises : la politique de confidentialité le dit.
### Procédures
- **Mettre à jour** : `git switch develop && git pull --ff-only && scripts/publish-relay`, puis **Redeploy** de la stack dans Komodo.
- **Changer de clé** : modifier le Secret `RIOT_API_KEY` dans Komodo, puis **Redeploy** : la valeur changée recrée le conteneur. La clé n’est lue qu’au démarrage.
- **Vérifier le redémarrage** : en root sur le serveur, `pkill -9 -x relay` ; `docker inspect -f '{{.RestartCount}}' <conteneur>` augmente et le site répond de nouveau. (`docker kill` ne convient pas : Docker le traite comme un arrêt voulu.)
- **Vérifier la limite par adresse** : mettre `RELAY_CLIENT_LIMITS=3/600` (dans l'environnement et sous `environment:`), redéployer ; depuis le PC, le quatrième appel à `/europe/riot/account/v1/accounts/by-riot-id/{nom}/{tag}` répond 429, et au même moment depuis le téléphone en 4G, 200. Retirer la variable et redéployer.
## Site
Les pages de `site/` (#145) sont intégrées au binaire : `/` et `/index.html` (accueil), `/terms.html`, `/privacy.html` et les captures de `/img/`, en `GET`. Modifier une page demande de recompiler et de redéployer le service ; un nouveau fichier s’ajoute à la table de `crates/relay/src/site.rs` (un test échoue sinon). Les captures ne montrent pas le Riot ID d’autres joueurs : floutés. Les visites ne sont pas journalisées. `/riot.txt` porte le code de vérification du produit sur le portail de Riot (#147) ; le Product URL s'y écrit sans `/` final, sinon Riot cherche `//riot.txt`.
## Requêtes
`GET /{valeur de routage}{chemin Riot}`, par exemple `/europe/lol/match/v5/matches/EUW1_1`. Les valeurs de routage sont les régions `americas`, `asia`, `europe`, `sea` (Comptes et Parties) et les plateformes (`euw1`, `na1`, `kr`… pour la Maîtrise).
| Appel | Chemin Riot |
|---|---|
| Compte par Riot ID | `/riot/account/v1/accounts/by-riot-id/{nom}/{tag}` |
| Plateforme d’un Compte | `/riot/account/v1/region/by-game/lol/by-puuid/{puuid}` |
| Parties d’un Compte | `/lol/match/v5/matches/by-puuid/{puuid}/ids?queue=…` : `queue` Arena obligatoire (1700, 1710, 1740, 1750), `start`, `count` (100 au plus), `startTime` |
| Partie | `/lol/match/v5/matches/{id}` |
| Chronologie | `/lol/match/v5/matches/{id}/timeline` |
| Maîtrise | `/lol/champion-mastery/v4/champion-masteries/by-puuid/{puuid}` |
Toute autre route, méthode ou valeur répond 404 sans appeler Riot.
## Réponses
- Le statut et le corps de Riot, avec son `Content-Type`.
- **429** avec `Retry-After`, tout de suite : quota de la valeur de routage plein, limite de l’adresse atteinte, ou valeur de routage suspendue après un 429 de Riot (pendant son `Retry-After`, 10 s s’il n’en donne pas).
- **503** quand Riot refuse la clé (401 ou 403), sauf le 403 d’une chronologie, transmis tel quel.
- **502** quand Riot est injoignable.
+23
View File
@@ -0,0 +1,23 @@
#!/usr/bin/env bash
# Builds the relay's image from a pushed commit of develop or main and pushes it to Gitea's
# registry, tagged with the commit and `latest` (docs/service-relais.md). Run from the repository
# root, after `docker login gitea.nessar.fr` once.
set -euo pipefail
image="${RELAY_IMAGE:-gitea.nessar.fr/nessar/arena-tracker-relay}"
if [[ -n "$(git status --porcelain)" ]]; then
echo "Le dépôt a des changements : l'image doit correspondre à un commit." >&2
exit 1
fi
git fetch -q origin
commit="$(git rev-parse --short HEAD)"
if ! git merge-base --is-ancestor HEAD origin/develop && ! git merge-base --is-ancestor HEAD origin/main; then
echo "Le commit $commit n'est ni sur origin/develop ni sur origin/main." >&2
exit 1
fi
docker build -f crates/relay/Dockerfile -t "$image:$commit" -t "$image:latest" .
docker push "$image:$commit"
docker push "$image:latest"
echo "Publiée : $image:$commit"
Binary file not shown.

After

Width:  |  Height:  |  Size: 87 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 71 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 62 KiB

+26
View File
@@ -0,0 +1,26 @@
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Arena Tracker</title>
<style>body{max-width:42rem;margin:2rem auto;padding:0 1rem;font:1rem/1.6 system-ui,sans-serif;color-scheme:light dark}footer{margin-top:3rem;font-size:.85rem}figure{margin:1.5rem 0}img{max-width:100%;height:auto;border-radius:.5rem}figcaption{font-size:.9rem;opacity:.8}</style>
<h1>Arena Tracker</h1>
<p>A free Windows app that follows your League of Legends Arena Matches and your progress toward placing first with every champion. The interface is in French.</p>
<h2>What it does</h2>
<ul>
<li>Imports your Arena Match history and shows which champions you have played, won with and placed first with, per Season.</li>
<li>Shows each Match's recap, including death recaps.</li>
<li>During champion select, shows which available champions you still need. It only reads from the game client and never acts for you.</li>
<li>Lets you add a friend by Riot ID to see their progress.</li>
</ul>
<h2>Screenshots</h2>
<figure><img src="img/defi.webp" width="1280" height="860" alt="The Challenge tab: 56 of 173 champions placed first this Season, and the player's champions with their status."><figcaption>Progress through the Challenge.</figcaption></figure>
<figure><img src="img/parties.webp" width="1280" height="795" alt="The Matches tab: the list of Arena Matches and the recap of the selected one, other players' Riot IDs blurred."><figcaption>Match history and recap (other players' Riot IDs blurred).</figcaption></figure>
<figure><img src="img/statistiques.webp" width="1280" height="860" alt="Statistics: champions placed first over the Season, placements, attempts per champion, and a table per champion."><figcaption>Season statistics.</figcaption></figure>
<p><a href="https://gitea.nessar.fr/nessar/arena-tracker/releases">Download</a> · <a href="terms.html">Terms of Service</a> · <a href="privacy.html">Privacy Policy</a> · Contact: <a href="mailto:arena@nessar.fr">arena@nessar.fr</a></p>
<footer>Arena Tracker is not endorsed by Riot Games and does not 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.</footer>
</html>
+40
View File
@@ -0,0 +1,40 @@
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Privacy Policy · Arena Tracker</title>
<style>body{max-width:42rem;margin:2rem auto;padding:0 1rem;font:1rem/1.6 system-ui,sans-serif;color-scheme:light dark}footer{margin-top:3rem;font-size:.85rem}</style>
<p><a href="index.html">Arena Tracker</a></p>
<h1>Privacy Policy</h1>
<p>Effective 27 November 2026. Data controller: Nessar, <a href="mailto:arena@nessar.fr">arena@nessar.fr</a>.</p>
<p>Arena Tracker has no user accounts, advertising, analytics or telemetry, and we do not sell data.</p>
<h2>Stored on your computer</h2>
<p>In your Windows user folder, the app stores your settings, the Riot IDs and Riot player identifiers (PUUIDs) of your accounts and of friends you add, match results and details (which include the other players in those matches), champion mastery, data received from the League of Legends client on your computer, and game images. We cannot access these files. You can delete an account or friend in the app's settings (version 1.1 and later), or delete the app's data folder, which uninstalling leaves in place.</p>
<h2>Sent to the Arena Tracker service</h2>
<p>To import history, the app sends our server in France the Riot ID or PUUID being looked up, match identifiers, the game region and, as with any internet connection, your IP address. The server forwards the request to Riot Games and returns the answer. It does not save these requests or answers. It does not log Riot IDs, PUUIDs or IP addresses; your IP address is held in memory for up to 10 minutes to limit request rates. Technical logs record only the kind of request, its result and its duration.</p>
<p>Requests to our server and to this website pass through Cloudflare, Inc., which delivers and protects them. Cloudflare sees them in transit, including your IP address and the Riot ID or PUUID being looked up, and processes them under its own privacy policy and data processing terms, possibly outside the European Union.</p>
<p>Earlier versions of the app do not use this service: they contact Riot Games directly with an API key you provide.</p>
<p>Legal basis: providing the feature you ask for, and our legitimate interest in protecting the service from abuse.</p>
<h2>Other services the app contacts</h2>
<ul>
<li>Riot Games, for match data and game images (Data Dragon).</li>
<li>CommunityDragon, for game data and images.</li>
<li>gitea.nessar.fr, run by us, to check for and download updates. This server may keep standard access logs, including IP addresses, for 14 days.</li>
</ul>
<p>Those operated by others receive your IP address and apply their own privacy policies.</p>
<h2>Other players</h2>
<p>Match results and friend lookups show data that Riot Games provides about other players. It is stored only on the computer of the person using the app.</p>
<h2>Your rights</h2>
<p>You may ask to access, correct or erase personal data we hold about you, or object to its processing, by writing to <a href="mailto:arena@nessar.fr">arena@nessar.fr</a>. You may also complain to your data protection authority (in France, the CNIL).</p>
<h2>Changes</h2>
<p>Updates to this policy appear on this page with a new date.</p>
<footer>Arena Tracker is not endorsed by Riot Games and does not 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.</footer>
</html>
+1
View File
@@ -0,0 +1 @@
52d8252b-5aef-4311-8eed-7a07af38e2cf
+29
View File
@@ -0,0 +1,29 @@
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Terms of Service · Arena Tracker</title>
<style>body{max-width:42rem;margin:2rem auto;padding:0 1rem;font:1rem/1.6 system-ui,sans-serif;color-scheme:light dark}footer{margin-top:3rem;font-size:.85rem}</style>
<p><a href="index.html">Arena Tracker</a></p>
<h1>Terms of Service</h1>
<p>Effective 27 November 2026. Arena Tracker (the app and its online service) is run by Nessar ("we"). By using it you accept these terms.</p>
<h2>The service</h2>
<p>Arena Tracker is free. The app keeps your history on your computer. Its online service relays requests to the Riot Games API.</p>
<h2>Acceptable use</h2>
<p>Use the online service only through the official app, for personal use. Do not call it with other software, try to get around its limits, disrupt it, or use it to harass or profile other players. We may block abusive use.</p>
<h2>Riot Games</h2>
<p>Your use of League of Legends and of your Riot account remains subject to Riot Games' own terms.</p>
<h2>Availability and liability</h2>
<p>The app and service are provided "as is", without any guarantee of availability or accuracy. The service may be slowed, interrupted or stopped at any time; history already stored on your computer stays there. To the extent the law allows, we are not liable for indirect loss or loss of data. Nothing here limits rights that consumer law gives you.</p>
<h2>Changes and law</h2>
<p>We may change these terms; the new version and its date will appear on this page. French law applies.</p>
<p>Contact: <a href="mailto:arena@nessar.fr">arena@nessar.fr</a></p>
<footer>Arena Tracker is not endorsed by Riot Games and does not 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.</footer>
</html>