lekdan commited on
Commit
be6cbb5
·
verified ·
1 Parent(s): e01b672

Simplify compact v1 metadata contract

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +40 -60
  2. .gitignore +49 -0
  3. .python-version +1 -0
  4. Cargo.lock +3259 -0
  5. Cargo.toml +31 -0
  6. README.md +27 -148
  7. crates/osu_fetcher/Cargo.toml +55 -0
  8. crates/osu_fetcher/README.md +391 -0
  9. crates/osu_fetcher/src/api.rs +241 -0
  10. crates/osu_fetcher/src/auth.rs +894 -0
  11. crates/osu_fetcher/src/config.rs +231 -0
  12. crates/osu_fetcher/src/discover/mod.rs +813 -0
  13. crates/osu_fetcher/src/discover/nekoha.rs +203 -0
  14. crates/osu_fetcher/src/discover/nerinyan.rs +316 -0
  15. crates/osu_fetcher/src/discover/osudirect.rs +303 -0
  16. crates/osu_fetcher/src/discover/sayobot.rs +448 -0
  17. crates/osu_fetcher/src/download.rs +530 -0
  18. crates/osu_fetcher/src/enumerate.rs +356 -0
  19. crates/osu_fetcher/src/lib.rs +113 -0
  20. crates/osu_fetcher/src/main.rs +887 -0
  21. crates/osu_fetcher/src/mirrors/beatconnect.rs +99 -0
  22. crates/osu_fetcher/src/mirrors/catboy.rs +87 -0
  23. crates/osu_fetcher/src/mirrors/mod.rs +1138 -0
  24. crates/osu_fetcher/src/mirrors/nekoha.rs +88 -0
  25. crates/osu_fetcher/src/mirrors/nerinyan.rs +85 -0
  26. crates/osu_fetcher/src/mirrors/nzbasic.rs +102 -0
  27. crates/osu_fetcher/src/mirrors/osuapi.rs +143 -0
  28. crates/osu_fetcher/src/mirrors/osudirect.rs +94 -0
  29. crates/osu_fetcher/src/mirrors/osudl.rs +77 -0
  30. crates/osu_fetcher/src/mirrors/sayobot.rs +90 -0
  31. crates/osu_fetcher/src/progress.rs +612 -0
  32. crates/osu_fetcher/src/ratelimit.rs +132 -0
  33. crates/osu_fetcher/src/runlock.rs +125 -0
  34. crates/osu_fetcher/src/scan.rs +190 -0
  35. crates/osu_fetcher/src/state.rs +1223 -0
  36. crates/osu_fetcher/src/verify.rs +706 -0
  37. crates/osu_fetcher/tests/classify_response.rs +176 -0
  38. crates/osu_fetcher/tests/discover_live.rs +218 -0
  39. crates/osu_fetcher/tests/integration.rs +471 -0
  40. crates/osu_indexer/.gitignore +1 -0
  41. crates/osu_indexer/Cargo.toml +51 -0
  42. crates/osu_indexer/build.rs +87 -0
  43. crates/osu_indexer/src/archive.rs +451 -0
  44. crates/osu_indexer/src/difficulty.rs +441 -0
  45. crates/osu_indexer/src/hitsounds.rs +384 -0
  46. crates/osu_indexer/src/main.rs +0 -0
  47. crates/osu_indexer/src/osu_parse.rs +1778 -0
  48. crates/osu_indexer/src/output.rs +177 -0
  49. crates/osu_indexer/src/paths.rs +315 -0
  50. crates/osu_indexer/src/references.rs +1034 -0
.gitattributes CHANGED
@@ -1,60 +1,40 @@
1
- *.7z filter=lfs diff=lfs merge=lfs -text
2
- *.arrow filter=lfs diff=lfs merge=lfs -text
3
- *.avro filter=lfs diff=lfs merge=lfs -text
4
- *.bin filter=lfs diff=lfs merge=lfs -text
5
- *.bz2 filter=lfs diff=lfs merge=lfs -text
6
- *.ckpt filter=lfs diff=lfs merge=lfs -text
7
- *.ftz filter=lfs diff=lfs merge=lfs -text
8
- *.gz filter=lfs diff=lfs merge=lfs -text
9
- *.h5 filter=lfs diff=lfs merge=lfs -text
10
- *.joblib filter=lfs diff=lfs merge=lfs -text
11
- *.lfs.* filter=lfs diff=lfs merge=lfs -text
12
- *.lz4 filter=lfs diff=lfs merge=lfs -text
13
- *.mds filter=lfs diff=lfs merge=lfs -text
14
- *.mlmodel filter=lfs diff=lfs merge=lfs -text
15
- *.model filter=lfs diff=lfs merge=lfs -text
16
- *.msgpack filter=lfs diff=lfs merge=lfs -text
17
- *.npy filter=lfs diff=lfs merge=lfs -text
18
- *.npz filter=lfs diff=lfs merge=lfs -text
19
- *.onnx filter=lfs diff=lfs merge=lfs -text
20
- *.ot filter=lfs diff=lfs merge=lfs -text
21
- *.parquet filter=lfs diff=lfs merge=lfs -text
22
- *.pb filter=lfs diff=lfs merge=lfs -text
23
- *.pickle filter=lfs diff=lfs merge=lfs -text
24
- *.pkl filter=lfs diff=lfs merge=lfs -text
25
- *.pt filter=lfs diff=lfs merge=lfs -text
26
- *.pth filter=lfs diff=lfs merge=lfs -text
27
- *.rar filter=lfs diff=lfs merge=lfs -text
28
- *.safetensors filter=lfs diff=lfs merge=lfs -text
29
- saved_model/**/* filter=lfs diff=lfs merge=lfs -text
30
- *.tar.* filter=lfs diff=lfs merge=lfs -text
31
- *.tar filter=lfs diff=lfs merge=lfs -text
32
- *.tflite filter=lfs diff=lfs merge=lfs -text
33
- *.tgz filter=lfs diff=lfs merge=lfs -text
34
- *.wasm filter=lfs diff=lfs merge=lfs -text
35
- *.xz filter=lfs diff=lfs merge=lfs -text
36
- *.zip filter=lfs diff=lfs merge=lfs -text
37
- *.zst filter=lfs diff=lfs merge=lfs -text
38
- *tfevents* filter=lfs diff=lfs merge=lfs -text
39
- # Audio files - uncompressed
40
- *.pcm filter=lfs diff=lfs merge=lfs -text
41
- *.sam filter=lfs diff=lfs merge=lfs -text
42
- *.raw filter=lfs diff=lfs merge=lfs -text
43
- # Audio files - compressed
44
- *.aac filter=lfs diff=lfs merge=lfs -text
45
- *.flac filter=lfs diff=lfs merge=lfs -text
46
- *.mp3 filter=lfs diff=lfs merge=lfs -text
47
- *.ogg filter=lfs diff=lfs merge=lfs -text
48
- *.wav filter=lfs diff=lfs merge=lfs -text
49
- # Image files - uncompressed
50
- *.bmp filter=lfs diff=lfs merge=lfs -text
51
- *.gif filter=lfs diff=lfs merge=lfs -text
52
- *.png filter=lfs diff=lfs merge=lfs -text
53
- *.tiff filter=lfs diff=lfs merge=lfs -text
54
- # Image files - compressed
55
- *.jpg filter=lfs diff=lfs merge=lfs -text
56
- *.jpeg filter=lfs diff=lfs merge=lfs -text
57
- *.webp filter=lfs diff=lfs merge=lfs -text
58
- # Video files - compressed
59
- *.mp4 filter=lfs diff=lfs merge=lfs -text
60
- *.webm filter=lfs diff=lfs merge=lfs -text
 
1
+ # Xet tracking for binary/large files.
2
+ # Run `git xet install` once per clone before any of these take effect.
3
+
4
+ # osu! archives and arbitrary content-addressed blobs
5
+ *.osz filter=xet diff=xet merge=xet -text
6
+ *.bin filter=xet diff=xet merge=xet -text
7
+
8
+ # Audio
9
+ *.mp3 filter=xet diff=xet merge=xet -text
10
+ *.ogg filter=xet diff=xet merge=xet -text
11
+ *.wav filter=xet diff=xet merge=xet -text
12
+ *.flac filter=xet diff=xet merge=xet -text
13
+
14
+ # Images
15
+ *.jpg filter=xet diff=xet merge=xet -text
16
+ *.jpeg filter=xet diff=xet merge=xet -text
17
+ *.png filter=xet diff=xet merge=xet -text
18
+ *.gif filter=xet diff=xet merge=xet -text
19
+ *.webp filter=xet diff=xet merge=xet -text
20
+
21
+ # Video
22
+ *.mp4 filter=xet diff=xet merge=xet -text
23
+ *.avi filter=xet diff=xet merge=xet -text
24
+ *.mkv filter=xet diff=xet merge=xet -text
25
+ *.webm filter=xet diff=xet merge=xet -text
26
+
27
+ # Parquet tables (use_content_defined_chunking enables Xet dedup at chunk level)
28
+ *.parquet filter=xet diff=xet merge=xet -text
29
+
30
+ # Force LF and treat as text for source/config files
31
+ *.py text eol=lf
32
+ *.rs text eol=lf
33
+ *.toml text eol=lf
34
+ *.md text eol=lf
35
+ *.json text eol=lf
36
+ *.yaml text eol=lf
37
+ *.yml text eol=lf
38
+ .gitkeep text eol=lf
39
+ .gitignore text eol=lf
40
+ .gitattributes text eol=lf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.gitignore ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Local-only inputs (not part of the dataset)
2
+ osu_archives/
3
+ osu-wiki/
4
+
5
+ # Python / uv
6
+ # NB: pyproject.toml, uv.lock, and .python-version ARE committed (lockfile + pin).
7
+ __pycache__/
8
+ *.pyc
9
+ *.pyo
10
+ .venv/
11
+ venv/
12
+ .env
13
+ *.egg-info/
14
+ .pytest_cache/
15
+ .mypy_cache/
16
+ .ruff_cache/
17
+
18
+ # Rust (workspace target dir + per-crate fallback)
19
+ target/
20
+ crates/*/target/
21
+
22
+ # osu_fetcher state DB + run lock (per-machine; not part of the dataset)
23
+ .fetcher.state.db
24
+ .fetcher.state.db-*
25
+ .fetcher.state.db.run.lock
26
+ *.run.lock
27
+
28
+ # osu_fetcher credentials (real file ignored; .example is committed)
29
+ osu_fetcher.toml
30
+ !osu_fetcher.toml.example
31
+
32
+ # Editors / OS
33
+ .idea/
34
+ .vscode/*
35
+ !.vscode/settings.json
36
+ *.swp
37
+ *.swo
38
+ .DS_Store
39
+ Thumbs.db
40
+
41
+ # Local scratch / logs
42
+ .scratch/
43
+ *.log
44
+
45
+ # Single-writer ingest lock (PID + timestamp; written by python/ingest_osz.py)
46
+ .ingest.lock
47
+
48
+ # Smoke-test sandboxes
49
+ smoke_test_*/
.python-version ADDED
@@ -0,0 +1 @@
 
 
1
+ 3.13
Cargo.lock ADDED
@@ -0,0 +1,3259 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is automatically @generated by Cargo.
2
+ # It is not intended for manual editing.
3
+ version = 4
4
+
5
+ [[package]]
6
+ name = "adler2"
7
+ version = "2.0.1"
8
+ source = "registry+https://github.com/rust-lang/crates.io-index"
9
+ checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
10
+
11
+ [[package]]
12
+ name = "aes"
13
+ version = "0.9.0"
14
+ source = "registry+https://github.com/rust-lang/crates.io-index"
15
+ checksum = "66bd29a732b644c0431c6140f370d097879203d79b80c94a6747ba0872adaef8"
16
+ dependencies = [
17
+ "cipher",
18
+ "cpubits",
19
+ "cpufeatures 0.3.0",
20
+ ]
21
+
22
+ [[package]]
23
+ name = "ahash"
24
+ version = "0.8.12"
25
+ source = "registry+https://github.com/rust-lang/crates.io-index"
26
+ checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75"
27
+ dependencies = [
28
+ "cfg-if",
29
+ "once_cell",
30
+ "version_check",
31
+ "zerocopy",
32
+ ]
33
+
34
+ [[package]]
35
+ name = "aho-corasick"
36
+ version = "1.1.4"
37
+ source = "registry+https://github.com/rust-lang/crates.io-index"
38
+ checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301"
39
+ dependencies = [
40
+ "memchr",
41
+ ]
42
+
43
+ [[package]]
44
+ name = "alloc-no-stdlib"
45
+ version = "2.0.4"
46
+ source = "registry+https://github.com/rust-lang/crates.io-index"
47
+ checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3"
48
+
49
+ [[package]]
50
+ name = "alloc-stdlib"
51
+ version = "0.2.2"
52
+ source = "registry+https://github.com/rust-lang/crates.io-index"
53
+ checksum = "94fb8275041c72129eb51b7d0322c29b8387a0386127718b096429201a5d6ece"
54
+ dependencies = [
55
+ "alloc-no-stdlib",
56
+ ]
57
+
58
+ [[package]]
59
+ name = "anstream"
60
+ version = "1.0.0"
61
+ source = "registry+https://github.com/rust-lang/crates.io-index"
62
+ checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d"
63
+ dependencies = [
64
+ "anstyle",
65
+ "anstyle-parse",
66
+ "anstyle-query",
67
+ "anstyle-wincon",
68
+ "colorchoice",
69
+ "is_terminal_polyfill",
70
+ "utf8parse",
71
+ ]
72
+
73
+ [[package]]
74
+ name = "anstyle"
75
+ version = "1.0.14"
76
+ source = "registry+https://github.com/rust-lang/crates.io-index"
77
+ checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000"
78
+
79
+ [[package]]
80
+ name = "anstyle-parse"
81
+ version = "1.0.0"
82
+ source = "registry+https://github.com/rust-lang/crates.io-index"
83
+ checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e"
84
+ dependencies = [
85
+ "utf8parse",
86
+ ]
87
+
88
+ [[package]]
89
+ name = "anstyle-query"
90
+ version = "1.1.5"
91
+ source = "registry+https://github.com/rust-lang/crates.io-index"
92
+ checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"
93
+ dependencies = [
94
+ "windows-sys 0.61.2",
95
+ ]
96
+
97
+ [[package]]
98
+ name = "anstyle-wincon"
99
+ version = "3.0.11"
100
+ source = "registry+https://github.com/rust-lang/crates.io-index"
101
+ checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"
102
+ dependencies = [
103
+ "anstyle",
104
+ "once_cell_polyfill",
105
+ "windows-sys 0.61.2",
106
+ ]
107
+
108
+ [[package]]
109
+ name = "anyhow"
110
+ version = "1.0.102"
111
+ source = "registry+https://github.com/rust-lang/crates.io-index"
112
+ checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c"
113
+
114
+ [[package]]
115
+ name = "assert-json-diff"
116
+ version = "2.0.2"
117
+ source = "registry+https://github.com/rust-lang/crates.io-index"
118
+ checksum = "47e4f2b81832e72834d7518d8487a0396a28cc408186a2e8854c0f98011faf12"
119
+ dependencies = [
120
+ "serde",
121
+ "serde_json",
122
+ ]
123
+
124
+ [[package]]
125
+ name = "async-compression"
126
+ version = "0.4.42"
127
+ source = "registry+https://github.com/rust-lang/crates.io-index"
128
+ checksum = "e79b3f8a79cccc2898f31920fc69f304859b3bd567490f75ebf51ae1c792a9ac"
129
+ dependencies = [
130
+ "compression-codecs",
131
+ "compression-core",
132
+ "pin-project-lite",
133
+ "tokio",
134
+ ]
135
+
136
+ [[package]]
137
+ name = "async-trait"
138
+ version = "0.1.89"
139
+ source = "registry+https://github.com/rust-lang/crates.io-index"
140
+ checksum = "9035ad2d096bed7955a320ee7e2230574d28fd3c3a0f186cbea1ff3c7eed5dbb"
141
+ dependencies = [
142
+ "proc-macro2",
143
+ "quote",
144
+ "syn",
145
+ ]
146
+
147
+ [[package]]
148
+ name = "atomic-waker"
149
+ version = "1.1.2"
150
+ source = "registry+https://github.com/rust-lang/crates.io-index"
151
+ checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"
152
+
153
+ [[package]]
154
+ name = "base64"
155
+ version = "0.22.1"
156
+ source = "registry+https://github.com/rust-lang/crates.io-index"
157
+ checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
158
+
159
+ [[package]]
160
+ name = "bitflags"
161
+ version = "2.11.1"
162
+ source = "registry+https://github.com/rust-lang/crates.io-index"
163
+ checksum = "c4512299f36f043ab09a583e57bceb5a5aab7a73db1805848e8fef3c9e8c78b3"
164
+
165
+ [[package]]
166
+ name = "block-buffer"
167
+ version = "0.10.4"
168
+ source = "registry+https://github.com/rust-lang/crates.io-index"
169
+ checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
170
+ dependencies = [
171
+ "generic-array",
172
+ ]
173
+
174
+ [[package]]
175
+ name = "block-buffer"
176
+ version = "0.12.0"
177
+ source = "registry+https://github.com/rust-lang/crates.io-index"
178
+ checksum = "cdd35008169921d80bc60d3d0ab416eecb028c4cd653352907921d95084790be"
179
+ dependencies = [
180
+ "hybrid-array",
181
+ "zeroize",
182
+ ]
183
+
184
+ [[package]]
185
+ name = "block2"
186
+ version = "0.6.2"
187
+ source = "registry+https://github.com/rust-lang/crates.io-index"
188
+ checksum = "cdeb9d870516001442e364c5220d3574d2da8dc765554b4a617230d33fa58ef5"
189
+ dependencies = [
190
+ "objc2",
191
+ ]
192
+
193
+ [[package]]
194
+ name = "brotli"
195
+ version = "8.0.2"
196
+ source = "registry+https://github.com/rust-lang/crates.io-index"
197
+ checksum = "4bd8b9603c7aa97359dbd97ecf258968c95f3adddd6db2f7e7a5bef101c84560"
198
+ dependencies = [
199
+ "alloc-no-stdlib",
200
+ "alloc-stdlib",
201
+ "brotli-decompressor",
202
+ ]
203
+
204
+ [[package]]
205
+ name = "brotli-decompressor"
206
+ version = "5.0.0"
207
+ source = "registry+https://github.com/rust-lang/crates.io-index"
208
+ checksum = "874bb8112abecc98cbd6d81ea4fa7e94fb9449648c93cc89aa40c81c24d7de03"
209
+ dependencies = [
210
+ "alloc-no-stdlib",
211
+ "alloc-stdlib",
212
+ ]
213
+
214
+ [[package]]
215
+ name = "bumpalo"
216
+ version = "3.20.2"
217
+ source = "registry+https://github.com/rust-lang/crates.io-index"
218
+ checksum = "5d20789868f4b01b2f2caec9f5c4e0213b41e3e5702a50157d699ae31ced2fcb"
219
+
220
+ [[package]]
221
+ name = "bytes"
222
+ version = "1.11.1"
223
+ source = "registry+https://github.com/rust-lang/crates.io-index"
224
+ checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33"
225
+
226
+ [[package]]
227
+ name = "bzip2"
228
+ version = "0.6.1"
229
+ source = "registry+https://github.com/rust-lang/crates.io-index"
230
+ checksum = "f3a53fac24f34a81bc9954b5d6cfce0c21e18ec6959f44f56e8e90e4bb7c346c"
231
+ dependencies = [
232
+ "libbz2-rs-sys",
233
+ ]
234
+
235
+ [[package]]
236
+ name = "cc"
237
+ version = "1.2.61"
238
+ source = "registry+https://github.com/rust-lang/crates.io-index"
239
+ checksum = "d16d90359e986641506914ba71350897565610e87ce0ad9e6f28569db3dd5c6d"
240
+ dependencies = [
241
+ "find-msvc-tools",
242
+ "jobserver",
243
+ "libc",
244
+ "shlex",
245
+ ]
246
+
247
+ [[package]]
248
+ name = "cfg-if"
249
+ version = "1.0.4"
250
+ source = "registry+https://github.com/rust-lang/crates.io-index"
251
+ checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
252
+
253
+ [[package]]
254
+ name = "cfg_aliases"
255
+ version = "0.2.1"
256
+ source = "registry+https://github.com/rust-lang/crates.io-index"
257
+ checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724"
258
+
259
+ [[package]]
260
+ name = "cipher"
261
+ version = "0.5.1"
262
+ source = "registry+https://github.com/rust-lang/crates.io-index"
263
+ checksum = "e34d8227fe1ba289043aeb13792056ff80fd6de1a9f49137a5f499de8e8c78ea"
264
+ dependencies = [
265
+ "crypto-common 0.2.1",
266
+ "inout",
267
+ ]
268
+
269
+ [[package]]
270
+ name = "clap"
271
+ version = "4.6.1"
272
+ source = "registry+https://github.com/rust-lang/crates.io-index"
273
+ checksum = "1ddb117e43bbf7dacf0a4190fef4d345b9bad68dfc649cb349e7d17d28428e51"
274
+ dependencies = [
275
+ "clap_builder",
276
+ "clap_derive",
277
+ ]
278
+
279
+ [[package]]
280
+ name = "clap_builder"
281
+ version = "4.6.0"
282
+ source = "registry+https://github.com/rust-lang/crates.io-index"
283
+ checksum = "714a53001bf66416adb0e2ef5ac857140e7dc3a0c48fb28b2f10762fc4b5069f"
284
+ dependencies = [
285
+ "anstream",
286
+ "anstyle",
287
+ "clap_lex",
288
+ "strsim",
289
+ "terminal_size",
290
+ ]
291
+
292
+ [[package]]
293
+ name = "clap_derive"
294
+ version = "4.6.1"
295
+ source = "registry+https://github.com/rust-lang/crates.io-index"
296
+ checksum = "f2ce8604710f6733aa641a2b3731eaa1e8b3d9973d5e3565da11800813f997a9"
297
+ dependencies = [
298
+ "heck",
299
+ "proc-macro2",
300
+ "quote",
301
+ "syn",
302
+ ]
303
+
304
+ [[package]]
305
+ name = "clap_lex"
306
+ version = "1.1.0"
307
+ source = "registry+https://github.com/rust-lang/crates.io-index"
308
+ checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9"
309
+
310
+ [[package]]
311
+ name = "cmov"
312
+ version = "0.5.3"
313
+ source = "registry+https://github.com/rust-lang/crates.io-index"
314
+ checksum = "3f88a43d011fc4a6876cb7344703e297c71dda42494fee094d5f7c76bf13f746"
315
+
316
+ [[package]]
317
+ name = "colorchoice"
318
+ version = "1.0.5"
319
+ source = "registry+https://github.com/rust-lang/crates.io-index"
320
+ checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"
321
+
322
+ [[package]]
323
+ name = "compression-codecs"
324
+ version = "0.4.38"
325
+ source = "registry+https://github.com/rust-lang/crates.io-index"
326
+ checksum = "ce2548391e9c1929c21bf6aa2680af86fe4c1b33e6cea9ac1cfeec0bd11218cf"
327
+ dependencies = [
328
+ "brotli",
329
+ "compression-core",
330
+ "flate2",
331
+ "memchr",
332
+ ]
333
+
334
+ [[package]]
335
+ name = "compression-core"
336
+ version = "0.4.32"
337
+ source = "registry+https://github.com/rust-lang/crates.io-index"
338
+ checksum = "cc14f565cf027a105f7a44ccf9e5b424348421a1d8952a8fc9d499d313107789"
339
+
340
+ [[package]]
341
+ name = "condtype"
342
+ version = "1.3.0"
343
+ source = "registry+https://github.com/rust-lang/crates.io-index"
344
+ checksum = "baf0a07a401f374238ab8e2f11a104d2851bf9ce711ec69804834de8af45c7af"
345
+
346
+ [[package]]
347
+ name = "console"
348
+ version = "0.15.11"
349
+ source = "registry+https://github.com/rust-lang/crates.io-index"
350
+ checksum = "054ccb5b10f9f2cbf51eb355ca1d05c2d279ce1804688d0db74b4733a5aeafd8"
351
+ dependencies = [
352
+ "encode_unicode",
353
+ "libc",
354
+ "once_cell",
355
+ "unicode-width",
356
+ "windows-sys 0.59.0",
357
+ ]
358
+
359
+ [[package]]
360
+ name = "const-oid"
361
+ version = "0.10.2"
362
+ source = "registry+https://github.com/rust-lang/crates.io-index"
363
+ checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c"
364
+
365
+ [[package]]
366
+ name = "constant_time_eq"
367
+ version = "0.4.2"
368
+ source = "registry+https://github.com/rust-lang/crates.io-index"
369
+ checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b"
370
+
371
+ [[package]]
372
+ name = "cpubits"
373
+ version = "0.1.0"
374
+ source = "registry+https://github.com/rust-lang/crates.io-index"
375
+ checksum = "5ef0c543070d296ea414df2dd7625d1b24866ce206709d8a4a424f28377f5861"
376
+
377
+ [[package]]
378
+ name = "cpufeatures"
379
+ version = "0.2.17"
380
+ source = "registry+https://github.com/rust-lang/crates.io-index"
381
+ checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
382
+ dependencies = [
383
+ "libc",
384
+ ]
385
+
386
+ [[package]]
387
+ name = "cpufeatures"
388
+ version = "0.3.0"
389
+ source = "registry+https://github.com/rust-lang/crates.io-index"
390
+ checksum = "8b2a41393f66f16b0823bb79094d54ac5fbd34ab292ddafb9a0456ac9f87d201"
391
+ dependencies = [
392
+ "libc",
393
+ ]
394
+
395
+ [[package]]
396
+ name = "crc32fast"
397
+ version = "1.5.0"
398
+ source = "registry+https://github.com/rust-lang/crates.io-index"
399
+ checksum = "9481c1c90cbf2ac953f07c8d4a58aa3945c425b7185c9154d67a65e4230da511"
400
+ dependencies = [
401
+ "cfg-if",
402
+ ]
403
+
404
+ [[package]]
405
+ name = "crossbeam-deque"
406
+ version = "0.8.6"
407
+ source = "registry+https://github.com/rust-lang/crates.io-index"
408
+ checksum = "9dd111b7b7f7d55b72c0a6ae361660ee5853c9af73f70c3c2ef6858b950e2e51"
409
+ dependencies = [
410
+ "crossbeam-epoch",
411
+ "crossbeam-utils",
412
+ ]
413
+
414
+ [[package]]
415
+ name = "crossbeam-epoch"
416
+ version = "0.9.18"
417
+ source = "registry+https://github.com/rust-lang/crates.io-index"
418
+ checksum = "5b82ac4a3c2ca9c3460964f020e1402edd5753411d7737aa39c3714ad1b5420e"
419
+ dependencies = [
420
+ "crossbeam-utils",
421
+ ]
422
+
423
+ [[package]]
424
+ name = "crossbeam-utils"
425
+ version = "0.8.21"
426
+ source = "registry+https://github.com/rust-lang/crates.io-index"
427
+ checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28"
428
+
429
+ [[package]]
430
+ name = "crypto-common"
431
+ version = "0.1.7"
432
+ source = "registry+https://github.com/rust-lang/crates.io-index"
433
+ checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
434
+ dependencies = [
435
+ "generic-array",
436
+ "typenum",
437
+ ]
438
+
439
+ [[package]]
440
+ name = "crypto-common"
441
+ version = "0.2.1"
442
+ source = "registry+https://github.com/rust-lang/crates.io-index"
443
+ checksum = "77727bb15fa921304124b128af125e7e3b968275d1b108b379190264f4423710"
444
+ dependencies = [
445
+ "hybrid-array",
446
+ ]
447
+
448
+ [[package]]
449
+ name = "ctrlc"
450
+ version = "3.5.2"
451
+ source = "registry+https://github.com/rust-lang/crates.io-index"
452
+ checksum = "e0b1fab2ae45819af2d0731d60f2afe17227ebb1a1538a236da84c93e9a60162"
453
+ dependencies = [
454
+ "dispatch2",
455
+ "nix",
456
+ "windows-sys 0.61.2",
457
+ ]
458
+
459
+ [[package]]
460
+ name = "ctutils"
461
+ version = "0.4.2"
462
+ source = "registry+https://github.com/rust-lang/crates.io-index"
463
+ checksum = "7d5515a3834141de9eafb9717ad39eea8247b5674e6066c404e8c4b365d2a29e"
464
+ dependencies = [
465
+ "cmov",
466
+ ]
467
+
468
+ [[package]]
469
+ name = "dashmap"
470
+ version = "6.1.0"
471
+ source = "registry+https://github.com/rust-lang/crates.io-index"
472
+ checksum = "5041cc499144891f3790297212f32a74fb938e5136a14943f338ef9e0ae276cf"
473
+ dependencies = [
474
+ "cfg-if",
475
+ "crossbeam-utils",
476
+ "hashbrown 0.14.5",
477
+ "lock_api",
478
+ "once_cell",
479
+ "parking_lot_core",
480
+ ]
481
+
482
+ [[package]]
483
+ name = "deadpool"
484
+ version = "0.12.3"
485
+ source = "registry+https://github.com/rust-lang/crates.io-index"
486
+ checksum = "0be2b1d1d6ec8d846f05e137292d0b89133caf95ef33695424c09568bdd39b1b"
487
+ dependencies = [
488
+ "deadpool-runtime",
489
+ "lazy_static",
490
+ "num_cpus",
491
+ "tokio",
492
+ ]
493
+
494
+ [[package]]
495
+ name = "deadpool-runtime"
496
+ version = "0.1.4"
497
+ source = "registry+https://github.com/rust-lang/crates.io-index"
498
+ checksum = "092966b41edc516079bdf31ec78a2e0588d1d0c08f78b91d8307215928642b2b"
499
+
500
+ [[package]]
501
+ name = "deflate64"
502
+ version = "0.1.12"
503
+ source = "registry+https://github.com/rust-lang/crates.io-index"
504
+ checksum = "ac6b926516df9c60bfa16e107b21086399f8285a44ca9711344b9e553c5146e2"
505
+
506
+ [[package]]
507
+ name = "deranged"
508
+ version = "0.5.8"
509
+ source = "registry+https://github.com/rust-lang/crates.io-index"
510
+ checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c"
511
+ dependencies = [
512
+ "powerfmt",
513
+ ]
514
+
515
+ [[package]]
516
+ name = "digest"
517
+ version = "0.10.7"
518
+ source = "registry+https://github.com/rust-lang/crates.io-index"
519
+ checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
520
+ dependencies = [
521
+ "block-buffer 0.10.4",
522
+ "crypto-common 0.1.7",
523
+ ]
524
+
525
+ [[package]]
526
+ name = "digest"
527
+ version = "0.11.2"
528
+ source = "registry+https://github.com/rust-lang/crates.io-index"
529
+ checksum = "4850db49bf08e663084f7fb5c87d202ef91a3907271aff24a94eb97ff039153c"
530
+ dependencies = [
531
+ "block-buffer 0.12.0",
532
+ "const-oid",
533
+ "crypto-common 0.2.1",
534
+ "ctutils",
535
+ "zeroize",
536
+ ]
537
+
538
+ [[package]]
539
+ name = "dispatch2"
540
+ version = "0.3.1"
541
+ source = "registry+https://github.com/rust-lang/crates.io-index"
542
+ checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38"
543
+ dependencies = [
544
+ "bitflags",
545
+ "block2",
546
+ "libc",
547
+ "objc2",
548
+ ]
549
+
550
+ [[package]]
551
+ name = "displaydoc"
552
+ version = "0.2.5"
553
+ source = "registry+https://github.com/rust-lang/crates.io-index"
554
+ checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0"
555
+ dependencies = [
556
+ "proc-macro2",
557
+ "quote",
558
+ "syn",
559
+ ]
560
+
561
+ [[package]]
562
+ name = "divan"
563
+ version = "0.1.21"
564
+ source = "registry+https://github.com/rust-lang/crates.io-index"
565
+ checksum = "a405457ec78b8fe08b0e32b4a3570ab5dff6dd16eb9e76a5ee0a9d9cbd898933"
566
+ dependencies = [
567
+ "cfg-if",
568
+ "clap",
569
+ "condtype",
570
+ "divan-macros",
571
+ "libc",
572
+ "regex-lite",
573
+ ]
574
+
575
+ [[package]]
576
+ name = "divan-macros"
577
+ version = "0.1.21"
578
+ source = "registry+https://github.com/rust-lang/crates.io-index"
579
+ checksum = "9556bc800956545d6420a640173e5ba7dfa82f38d3ea5a167eb555bc69ac3323"
580
+ dependencies = [
581
+ "proc-macro2",
582
+ "quote",
583
+ "syn",
584
+ ]
585
+
586
+ [[package]]
587
+ name = "either"
588
+ version = "1.15.0"
589
+ source = "registry+https://github.com/rust-lang/crates.io-index"
590
+ checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719"
591
+
592
+ [[package]]
593
+ name = "encode_unicode"
594
+ version = "1.0.0"
595
+ source = "registry+https://github.com/rust-lang/crates.io-index"
596
+ checksum = "34aa73646ffb006b8f5147f3dc182bd4bcb190227ce861fc4a4844bf8e3cb2c0"
597
+
598
+ [[package]]
599
+ name = "equivalent"
600
+ version = "1.0.2"
601
+ source = "registry+https://github.com/rust-lang/crates.io-index"
602
+ checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
603
+
604
+ [[package]]
605
+ name = "errno"
606
+ version = "0.3.14"
607
+ source = "registry+https://github.com/rust-lang/crates.io-index"
608
+ checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
609
+ dependencies = [
610
+ "libc",
611
+ "windows-sys 0.61.2",
612
+ ]
613
+
614
+ [[package]]
615
+ name = "fallible-iterator"
616
+ version = "0.3.0"
617
+ source = "registry+https://github.com/rust-lang/crates.io-index"
618
+ checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649"
619
+
620
+ [[package]]
621
+ name = "fallible-streaming-iterator"
622
+ version = "0.1.9"
623
+ source = "registry+https://github.com/rust-lang/crates.io-index"
624
+ checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a"
625
+
626
+ [[package]]
627
+ name = "fastrand"
628
+ version = "2.4.1"
629
+ source = "registry+https://github.com/rust-lang/crates.io-index"
630
+ checksum = "9f1f227452a390804cdb637b74a86990f2a7d7ba4b7d5693aac9b4dd6defd8d6"
631
+
632
+ [[package]]
633
+ name = "find-msvc-tools"
634
+ version = "0.1.9"
635
+ source = "registry+https://github.com/rust-lang/crates.io-index"
636
+ checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582"
637
+
638
+ [[package]]
639
+ name = "flate2"
640
+ version = "1.1.9"
641
+ source = "registry+https://github.com/rust-lang/crates.io-index"
642
+ checksum = "843fba2746e448b37e26a819579957415c8cef339bf08564fe8b7ddbd959573c"
643
+ dependencies = [
644
+ "crc32fast",
645
+ "miniz_oxide",
646
+ "zlib-rs",
647
+ ]
648
+
649
+ [[package]]
650
+ name = "fnv"
651
+ version = "1.0.7"
652
+ source = "registry+https://github.com/rust-lang/crates.io-index"
653
+ checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
654
+
655
+ [[package]]
656
+ name = "foldhash"
657
+ version = "0.1.5"
658
+ source = "registry+https://github.com/rust-lang/crates.io-index"
659
+ checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2"
660
+
661
+ [[package]]
662
+ name = "form_urlencoded"
663
+ version = "1.2.2"
664
+ source = "registry+https://github.com/rust-lang/crates.io-index"
665
+ checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"
666
+ dependencies = [
667
+ "percent-encoding",
668
+ ]
669
+
670
+ [[package]]
671
+ name = "futures"
672
+ version = "0.3.32"
673
+ source = "registry+https://github.com/rust-lang/crates.io-index"
674
+ checksum = "8b147ee9d1f6d097cef9ce628cd2ee62288d963e16fb287bd9286455b241382d"
675
+ dependencies = [
676
+ "futures-channel",
677
+ "futures-core",
678
+ "futures-executor",
679
+ "futures-io",
680
+ "futures-sink",
681
+ "futures-task",
682
+ "futures-util",
683
+ ]
684
+
685
+ [[package]]
686
+ name = "futures-channel"
687
+ version = "0.3.32"
688
+ source = "registry+https://github.com/rust-lang/crates.io-index"
689
+ checksum = "07bbe89c50d7a535e539b8c17bc0b49bdb77747034daa8087407d655f3f7cc1d"
690
+ dependencies = [
691
+ "futures-core",
692
+ "futures-sink",
693
+ ]
694
+
695
+ [[package]]
696
+ name = "futures-core"
697
+ version = "0.3.32"
698
+ source = "registry+https://github.com/rust-lang/crates.io-index"
699
+ checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d"
700
+
701
+ [[package]]
702
+ name = "futures-executor"
703
+ version = "0.3.32"
704
+ source = "registry+https://github.com/rust-lang/crates.io-index"
705
+ checksum = "baf29c38818342a3b26b5b923639e7b1f4a61fc5e76102d4b1981c6dc7a7579d"
706
+ dependencies = [
707
+ "futures-core",
708
+ "futures-task",
709
+ "futures-util",
710
+ ]
711
+
712
+ [[package]]
713
+ name = "futures-io"
714
+ version = "0.3.32"
715
+ source = "registry+https://github.com/rust-lang/crates.io-index"
716
+ checksum = "cecba35d7ad927e23624b22ad55235f2239cfa44fd10428eecbeba6d6a717718"
717
+
718
+ [[package]]
719
+ name = "futures-macro"
720
+ version = "0.3.32"
721
+ source = "registry+https://github.com/rust-lang/crates.io-index"
722
+ checksum = "e835b70203e41293343137df5c0664546da5745f82ec9b84d40be8336958447b"
723
+ dependencies = [
724
+ "proc-macro2",
725
+ "quote",
726
+ "syn",
727
+ ]
728
+
729
+ [[package]]
730
+ name = "futures-sink"
731
+ version = "0.3.32"
732
+ source = "registry+https://github.com/rust-lang/crates.io-index"
733
+ checksum = "c39754e157331b013978ec91992bde1ac089843443c49cbc7f46150b0fad0893"
734
+
735
+ [[package]]
736
+ name = "futures-task"
737
+ version = "0.3.32"
738
+ source = "registry+https://github.com/rust-lang/crates.io-index"
739
+ checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393"
740
+
741
+ [[package]]
742
+ name = "futures-timer"
743
+ version = "3.0.3"
744
+ source = "registry+https://github.com/rust-lang/crates.io-index"
745
+ checksum = "f288b0a4f20f9a56b5d1da57e2227c661b7b16168e2f72365f57b63326e29b24"
746
+
747
+ [[package]]
748
+ name = "futures-util"
749
+ version = "0.3.32"
750
+ source = "registry+https://github.com/rust-lang/crates.io-index"
751
+ checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6"
752
+ dependencies = [
753
+ "futures-channel",
754
+ "futures-core",
755
+ "futures-io",
756
+ "futures-macro",
757
+ "futures-sink",
758
+ "futures-task",
759
+ "memchr",
760
+ "pin-project-lite",
761
+ "slab",
762
+ ]
763
+
764
+ [[package]]
765
+ name = "generic-array"
766
+ version = "0.14.7"
767
+ source = "registry+https://github.com/rust-lang/crates.io-index"
768
+ checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
769
+ dependencies = [
770
+ "typenum",
771
+ "version_check",
772
+ ]
773
+
774
+ [[package]]
775
+ name = "getrandom"
776
+ version = "0.2.17"
777
+ source = "registry+https://github.com/rust-lang/crates.io-index"
778
+ checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
779
+ dependencies = [
780
+ "cfg-if",
781
+ "js-sys",
782
+ "libc",
783
+ "wasi",
784
+ "wasm-bindgen",
785
+ ]
786
+
787
+ [[package]]
788
+ name = "getrandom"
789
+ version = "0.3.4"
790
+ source = "registry+https://github.com/rust-lang/crates.io-index"
791
+ checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"
792
+ dependencies = [
793
+ "cfg-if",
794
+ "js-sys",
795
+ "libc",
796
+ "r-efi 5.3.0",
797
+ "wasip2",
798
+ "wasm-bindgen",
799
+ ]
800
+
801
+ [[package]]
802
+ name = "getrandom"
803
+ version = "0.4.2"
804
+ source = "registry+https://github.com/rust-lang/crates.io-index"
805
+ checksum = "0de51e6874e94e7bf76d726fc5d13ba782deca734ff60d5bb2fb2607c7406555"
806
+ dependencies = [
807
+ "cfg-if",
808
+ "js-sys",
809
+ "libc",
810
+ "r-efi 6.0.0",
811
+ "wasip2",
812
+ "wasip3",
813
+ "wasm-bindgen",
814
+ ]
815
+
816
+ [[package]]
817
+ name = "governor"
818
+ version = "0.7.0"
819
+ source = "registry+https://github.com/rust-lang/crates.io-index"
820
+ checksum = "0746aa765db78b521451ef74221663b57ba595bf83f75d0ce23cc09447c8139f"
821
+ dependencies = [
822
+ "cfg-if",
823
+ "dashmap",
824
+ "futures-sink",
825
+ "futures-timer",
826
+ "futures-util",
827
+ "no-std-compat",
828
+ "nonzero_ext",
829
+ "parking_lot",
830
+ "portable-atomic",
831
+ "quanta",
832
+ "rand 0.8.6",
833
+ "smallvec",
834
+ "spinning_top",
835
+ ]
836
+
837
+ [[package]]
838
+ name = "h2"
839
+ version = "0.4.13"
840
+ source = "registry+https://github.com/rust-lang/crates.io-index"
841
+ checksum = "2f44da3a8150a6703ed5d34e164b875fd14c2cdab9af1252a9a1020bde2bdc54"
842
+ dependencies = [
843
+ "atomic-waker",
844
+ "bytes",
845
+ "fnv",
846
+ "futures-core",
847
+ "futures-sink",
848
+ "http",
849
+ "indexmap",
850
+ "slab",
851
+ "tokio",
852
+ "tokio-util",
853
+ "tracing",
854
+ ]
855
+
856
+ [[package]]
857
+ name = "hashbrown"
858
+ version = "0.14.5"
859
+ source = "registry+https://github.com/rust-lang/crates.io-index"
860
+ checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"
861
+ dependencies = [
862
+ "ahash",
863
+ ]
864
+
865
+ [[package]]
866
+ name = "hashbrown"
867
+ version = "0.15.5"
868
+ source = "registry+https://github.com/rust-lang/crates.io-index"
869
+ checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1"
870
+ dependencies = [
871
+ "foldhash",
872
+ ]
873
+
874
+ [[package]]
875
+ name = "hashbrown"
876
+ version = "0.17.0"
877
+ source = "registry+https://github.com/rust-lang/crates.io-index"
878
+ checksum = "4f467dd6dccf739c208452f8014c75c18bb8301b050ad1cfb27153803edb0f51"
879
+
880
+ [[package]]
881
+ name = "hashlink"
882
+ version = "0.9.1"
883
+ source = "registry+https://github.com/rust-lang/crates.io-index"
884
+ checksum = "6ba4ff7128dee98c7dc9794b6a411377e1404dba1c97deb8d1a55297bd25d8af"
885
+ dependencies = [
886
+ "hashbrown 0.14.5",
887
+ ]
888
+
889
+ [[package]]
890
+ name = "heck"
891
+ version = "0.5.0"
892
+ source = "registry+https://github.com/rust-lang/crates.io-index"
893
+ checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
894
+
895
+ [[package]]
896
+ name = "hermit-abi"
897
+ version = "0.5.2"
898
+ source = "registry+https://github.com/rust-lang/crates.io-index"
899
+ checksum = "fc0fef456e4baa96da950455cd02c081ca953b141298e41db3fc7e36b1da849c"
900
+
901
+ [[package]]
902
+ name = "hex"
903
+ version = "0.4.3"
904
+ source = "registry+https://github.com/rust-lang/crates.io-index"
905
+ checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
906
+
907
+ [[package]]
908
+ name = "hmac"
909
+ version = "0.13.0"
910
+ source = "registry+https://github.com/rust-lang/crates.io-index"
911
+ checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f"
912
+ dependencies = [
913
+ "digest 0.11.2",
914
+ ]
915
+
916
+ [[package]]
917
+ name = "http"
918
+ version = "1.4.0"
919
+ source = "registry+https://github.com/rust-lang/crates.io-index"
920
+ checksum = "e3ba2a386d7f85a81f119ad7498ebe444d2e22c2af0b86b069416ace48b3311a"
921
+ dependencies = [
922
+ "bytes",
923
+ "itoa",
924
+ ]
925
+
926
+ [[package]]
927
+ name = "http-body"
928
+ version = "1.0.1"
929
+ source = "registry+https://github.com/rust-lang/crates.io-index"
930
+ checksum = "1efedce1fb8e6913f23e0c92de8e62cd5b772a67e7b3946df930a62566c93184"
931
+ dependencies = [
932
+ "bytes",
933
+ "http",
934
+ ]
935
+
936
+ [[package]]
937
+ name = "http-body-util"
938
+ version = "0.1.3"
939
+ source = "registry+https://github.com/rust-lang/crates.io-index"
940
+ checksum = "b021d93e26becf5dc7e1b75b1bed1fd93124b374ceb73f43d4d4eafec896a64a"
941
+ dependencies = [
942
+ "bytes",
943
+ "futures-core",
944
+ "http",
945
+ "http-body",
946
+ "pin-project-lite",
947
+ ]
948
+
949
+ [[package]]
950
+ name = "httparse"
951
+ version = "1.10.1"
952
+ source = "registry+https://github.com/rust-lang/crates.io-index"
953
+ checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"
954
+
955
+ [[package]]
956
+ name = "httpdate"
957
+ version = "1.0.3"
958
+ source = "registry+https://github.com/rust-lang/crates.io-index"
959
+ checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"
960
+
961
+ [[package]]
962
+ name = "hybrid-array"
963
+ version = "0.4.11"
964
+ source = "registry+https://github.com/rust-lang/crates.io-index"
965
+ checksum = "08d46837a0ed51fe95bd3b05de33cd64a1ee88fc797477ca48446872504507c5"
966
+ dependencies = [
967
+ "typenum",
968
+ ]
969
+
970
+ [[package]]
971
+ name = "hyper"
972
+ version = "1.9.0"
973
+ source = "registry+https://github.com/rust-lang/crates.io-index"
974
+ checksum = "6299f016b246a94207e63da54dbe807655bf9e00044f73ded42c3ac5305fbcca"
975
+ dependencies = [
976
+ "atomic-waker",
977
+ "bytes",
978
+ "futures-channel",
979
+ "futures-core",
980
+ "h2",
981
+ "http",
982
+ "http-body",
983
+ "httparse",
984
+ "httpdate",
985
+ "itoa",
986
+ "pin-project-lite",
987
+ "smallvec",
988
+ "tokio",
989
+ "want",
990
+ ]
991
+
992
+ [[package]]
993
+ name = "hyper-rustls"
994
+ version = "0.27.9"
995
+ source = "registry+https://github.com/rust-lang/crates.io-index"
996
+ checksum = "33ca68d021ef39cf6463ab54c1d0f5daf03377b70561305bb89a8f83aab66e0f"
997
+ dependencies = [
998
+ "http",
999
+ "hyper",
1000
+ "hyper-util",
1001
+ "rustls",
1002
+ "tokio",
1003
+ "tokio-rustls",
1004
+ "tower-service",
1005
+ "webpki-roots",
1006
+ ]
1007
+
1008
+ [[package]]
1009
+ name = "hyper-util"
1010
+ version = "0.1.20"
1011
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1012
+ checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0"
1013
+ dependencies = [
1014
+ "base64",
1015
+ "bytes",
1016
+ "futures-channel",
1017
+ "futures-util",
1018
+ "http",
1019
+ "http-body",
1020
+ "hyper",
1021
+ "ipnet",
1022
+ "libc",
1023
+ "percent-encoding",
1024
+ "pin-project-lite",
1025
+ "socket2",
1026
+ "tokio",
1027
+ "tower-service",
1028
+ "tracing",
1029
+ ]
1030
+
1031
+ [[package]]
1032
+ name = "icu_collections"
1033
+ version = "2.2.0"
1034
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1035
+ checksum = "2984d1cd16c883d7935b9e07e44071dca8d917fd52ecc02c04d5fa0b5a3f191c"
1036
+ dependencies = [
1037
+ "displaydoc",
1038
+ "potential_utf",
1039
+ "utf8_iter",
1040
+ "yoke",
1041
+ "zerofrom",
1042
+ "zerovec",
1043
+ ]
1044
+
1045
+ [[package]]
1046
+ name = "icu_locale_core"
1047
+ version = "2.2.0"
1048
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1049
+ checksum = "92219b62b3e2b4d88ac5119f8904c10f8f61bf7e95b640d25ba3075e6cac2c29"
1050
+ dependencies = [
1051
+ "displaydoc",
1052
+ "litemap",
1053
+ "tinystr",
1054
+ "writeable",
1055
+ "zerovec",
1056
+ ]
1057
+
1058
+ [[package]]
1059
+ name = "icu_normalizer"
1060
+ version = "2.2.0"
1061
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1062
+ checksum = "c56e5ee99d6e3d33bd91c5d85458b6005a22140021cc324cea84dd0e72cff3b4"
1063
+ dependencies = [
1064
+ "icu_collections",
1065
+ "icu_normalizer_data",
1066
+ "icu_properties",
1067
+ "icu_provider",
1068
+ "smallvec",
1069
+ "zerovec",
1070
+ ]
1071
+
1072
+ [[package]]
1073
+ name = "icu_normalizer_data"
1074
+ version = "2.2.0"
1075
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1076
+ checksum = "da3be0ae77ea334f4da67c12f149704f19f81d1adf7c51cf482943e84a2bad38"
1077
+
1078
+ [[package]]
1079
+ name = "icu_properties"
1080
+ version = "2.2.0"
1081
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1082
+ checksum = "bee3b67d0ea5c2cca5003417989af8996f8604e34fb9ddf96208a033901e70de"
1083
+ dependencies = [
1084
+ "icu_collections",
1085
+ "icu_locale_core",
1086
+ "icu_properties_data",
1087
+ "icu_provider",
1088
+ "zerotrie",
1089
+ "zerovec",
1090
+ ]
1091
+
1092
+ [[package]]
1093
+ name = "icu_properties_data"
1094
+ version = "2.2.0"
1095
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1096
+ checksum = "8e2bbb201e0c04f7b4b3e14382af113e17ba4f63e2c9d2ee626b720cbce54a14"
1097
+
1098
+ [[package]]
1099
+ name = "icu_provider"
1100
+ version = "2.2.0"
1101
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1102
+ checksum = "139c4cf31c8b5f33d7e199446eff9c1e02decfc2f0eec2c8d71f65befa45b421"
1103
+ dependencies = [
1104
+ "displaydoc",
1105
+ "icu_locale_core",
1106
+ "writeable",
1107
+ "yoke",
1108
+ "zerofrom",
1109
+ "zerotrie",
1110
+ "zerovec",
1111
+ ]
1112
+
1113
+ [[package]]
1114
+ name = "id-arena"
1115
+ version = "2.3.0"
1116
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1117
+ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
1118
+
1119
+ [[package]]
1120
+ name = "idna"
1121
+ version = "1.1.0"
1122
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1123
+ checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de"
1124
+ dependencies = [
1125
+ "idna_adapter",
1126
+ "smallvec",
1127
+ "utf8_iter",
1128
+ ]
1129
+
1130
+ [[package]]
1131
+ name = "idna_adapter"
1132
+ version = "1.2.1"
1133
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1134
+ checksum = "3acae9609540aa318d1bc588455225fb2085b9ed0c4f6bd0d9d5bcd86f1a0344"
1135
+ dependencies = [
1136
+ "icu_normalizer",
1137
+ "icu_properties",
1138
+ ]
1139
+
1140
+ [[package]]
1141
+ name = "indexmap"
1142
+ version = "2.14.0"
1143
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1144
+ checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9"
1145
+ dependencies = [
1146
+ "equivalent",
1147
+ "hashbrown 0.17.0",
1148
+ "serde",
1149
+ "serde_core",
1150
+ ]
1151
+
1152
+ [[package]]
1153
+ name = "indicatif"
1154
+ version = "0.17.11"
1155
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1156
+ checksum = "183b3088984b400f4cfac3620d5e076c84da5364016b4f49473de574b2586235"
1157
+ dependencies = [
1158
+ "console",
1159
+ "number_prefix",
1160
+ "portable-atomic",
1161
+ "unicode-width",
1162
+ "web-time",
1163
+ ]
1164
+
1165
+ [[package]]
1166
+ name = "inout"
1167
+ version = "0.2.2"
1168
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1169
+ checksum = "4250ce6452e92010fdf7268ccc5d14faa80bb12fc741938534c58f16804e03c7"
1170
+ dependencies = [
1171
+ "hybrid-array",
1172
+ ]
1173
+
1174
+ [[package]]
1175
+ name = "ipnet"
1176
+ version = "2.12.0"
1177
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1178
+ checksum = "d98f6fed1fde3f8c21bc40a1abb88dd75e67924f9cffc3ef95607bad8017f8e2"
1179
+
1180
+ [[package]]
1181
+ name = "iri-string"
1182
+ version = "0.7.12"
1183
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1184
+ checksum = "25e659a4bb38e810ebc252e53b5814ff908a8c58c2a9ce2fae1bbec24cbf4e20"
1185
+ dependencies = [
1186
+ "memchr",
1187
+ "serde",
1188
+ ]
1189
+
1190
+ [[package]]
1191
+ name = "is_terminal_polyfill"
1192
+ version = "1.70.2"
1193
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1194
+ checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"
1195
+
1196
+ [[package]]
1197
+ name = "itoa"
1198
+ version = "1.0.18"
1199
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1200
+ checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
1201
+
1202
+ [[package]]
1203
+ name = "jobserver"
1204
+ version = "0.1.34"
1205
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1206
+ checksum = "9afb3de4395d6b3e67a780b6de64b51c978ecf11cb9a462c66be7d4ca9039d33"
1207
+ dependencies = [
1208
+ "getrandom 0.3.4",
1209
+ "libc",
1210
+ ]
1211
+
1212
+ [[package]]
1213
+ name = "js-sys"
1214
+ version = "0.3.95"
1215
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1216
+ checksum = "2964e92d1d9dc3364cae4d718d93f227e3abb088e747d92e0395bfdedf1c12ca"
1217
+ dependencies = [
1218
+ "cfg-if",
1219
+ "futures-util",
1220
+ "once_cell",
1221
+ "wasm-bindgen",
1222
+ ]
1223
+
1224
+ [[package]]
1225
+ name = "lazy_static"
1226
+ version = "1.5.0"
1227
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1228
+ checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
1229
+
1230
+ [[package]]
1231
+ name = "leb128fmt"
1232
+ version = "0.1.0"
1233
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1234
+ checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2"
1235
+
1236
+ [[package]]
1237
+ name = "libbz2-rs-sys"
1238
+ version = "0.2.3"
1239
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1240
+ checksum = "b3a6a8c165077efc8f3a971534c50ea6a1a18b329ef4a66e897a7e3a1494565f"
1241
+
1242
+ [[package]]
1243
+ name = "libc"
1244
+ version = "0.2.186"
1245
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1246
+ checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66"
1247
+
1248
+ [[package]]
1249
+ name = "libsqlite3-sys"
1250
+ version = "0.30.1"
1251
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1252
+ checksum = "2e99fb7a497b1e3339bc746195567ed8d3e24945ecd636e3619d20b9de9e9149"
1253
+ dependencies = [
1254
+ "cc",
1255
+ "pkg-config",
1256
+ "vcpkg",
1257
+ ]
1258
+
1259
+ [[package]]
1260
+ name = "linux-raw-sys"
1261
+ version = "0.12.1"
1262
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1263
+ checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
1264
+
1265
+ [[package]]
1266
+ name = "litemap"
1267
+ version = "0.8.2"
1268
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1269
+ checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0"
1270
+
1271
+ [[package]]
1272
+ name = "lock_api"
1273
+ version = "0.4.14"
1274
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1275
+ checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"
1276
+ dependencies = [
1277
+ "scopeguard",
1278
+ ]
1279
+
1280
+ [[package]]
1281
+ name = "log"
1282
+ version = "0.4.29"
1283
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1284
+ checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897"
1285
+
1286
+ [[package]]
1287
+ name = "lru-slab"
1288
+ version = "0.1.2"
1289
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1290
+ checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154"
1291
+
1292
+ [[package]]
1293
+ name = "lzma-rust2"
1294
+ version = "0.16.2"
1295
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1296
+ checksum = "47bb1e988e6fb779cf720ad431242d3f03167c1b3f2b1aae7f1a94b2495b36ae"
1297
+ dependencies = [
1298
+ "sha2 0.10.9",
1299
+ ]
1300
+
1301
+ [[package]]
1302
+ name = "matchers"
1303
+ version = "0.2.0"
1304
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1305
+ checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9"
1306
+ dependencies = [
1307
+ "regex-automata",
1308
+ ]
1309
+
1310
+ [[package]]
1311
+ name = "memchr"
1312
+ version = "2.8.0"
1313
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1314
+ checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79"
1315
+
1316
+ [[package]]
1317
+ name = "miniz_oxide"
1318
+ version = "0.8.9"
1319
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1320
+ checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316"
1321
+ dependencies = [
1322
+ "adler2",
1323
+ "simd-adler32",
1324
+ ]
1325
+
1326
+ [[package]]
1327
+ name = "mio"
1328
+ version = "1.2.0"
1329
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1330
+ checksum = "50b7e5b27aa02a74bac8c3f23f448f8d87ff11f92d3aac1a6ed369ee08cc56c1"
1331
+ dependencies = [
1332
+ "libc",
1333
+ "wasi",
1334
+ "windows-sys 0.61.2",
1335
+ ]
1336
+
1337
+ [[package]]
1338
+ name = "nix"
1339
+ version = "0.31.2"
1340
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1341
+ checksum = "5d6d0705320c1e6ba1d912b5e37cf18071b6c2e9b7fa8215a1e8a7651966f5d3"
1342
+ dependencies = [
1343
+ "bitflags",
1344
+ "cfg-if",
1345
+ "cfg_aliases",
1346
+ "libc",
1347
+ ]
1348
+
1349
+ [[package]]
1350
+ name = "no-std-compat"
1351
+ version = "0.4.1"
1352
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1353
+ checksum = "b93853da6d84c2e3c7d730d6473e8817692dd89be387eb01b94d7f108ecb5b8c"
1354
+
1355
+ [[package]]
1356
+ name = "nonzero_ext"
1357
+ version = "0.3.0"
1358
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1359
+ checksum = "38bf9645c8b145698bb0b18a4637dcacbc421ea49bef2317e4fd8065a387cf21"
1360
+
1361
+ [[package]]
1362
+ name = "nu-ansi-term"
1363
+ version = "0.50.3"
1364
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1365
+ checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"
1366
+ dependencies = [
1367
+ "windows-sys 0.61.2",
1368
+ ]
1369
+
1370
+ [[package]]
1371
+ name = "num-conv"
1372
+ version = "0.2.1"
1373
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1374
+ checksum = "c6673768db2d862beb9b39a78fdcb1a69439615d5794a1be50caa9bc92c81967"
1375
+
1376
+ [[package]]
1377
+ name = "num_cpus"
1378
+ version = "1.17.0"
1379
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1380
+ checksum = "91df4bbde75afed763b708b7eee1e8e7651e02d97f6d5dd763e89367e957b23b"
1381
+ dependencies = [
1382
+ "hermit-abi",
1383
+ "libc",
1384
+ ]
1385
+
1386
+ [[package]]
1387
+ name = "number_prefix"
1388
+ version = "0.4.0"
1389
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1390
+ checksum = "830b246a0e5f20af87141b25c173cd1b609bd7779a4617d6ec582abaf90870f3"
1391
+
1392
+ [[package]]
1393
+ name = "objc2"
1394
+ version = "0.6.4"
1395
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1396
+ checksum = "3a12a8ed07aefc768292f076dc3ac8c48f3781c8f2d5851dd3d98950e8c5a89f"
1397
+ dependencies = [
1398
+ "objc2-encode",
1399
+ ]
1400
+
1401
+ [[package]]
1402
+ name = "objc2-encode"
1403
+ version = "4.1.0"
1404
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1405
+ checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33"
1406
+
1407
+ [[package]]
1408
+ name = "once_cell"
1409
+ version = "1.21.4"
1410
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1411
+ checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
1412
+
1413
+ [[package]]
1414
+ name = "once_cell_polyfill"
1415
+ version = "1.70.2"
1416
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1417
+ checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"
1418
+
1419
+ [[package]]
1420
+ name = "osu_fetcher"
1421
+ version = "0.1.0"
1422
+ dependencies = [
1423
+ "anyhow",
1424
+ "async-trait",
1425
+ "bytes",
1426
+ "clap",
1427
+ "console",
1428
+ "futures",
1429
+ "governor",
1430
+ "hex",
1431
+ "indicatif",
1432
+ "nonzero_ext",
1433
+ "reqwest",
1434
+ "rusqlite",
1435
+ "serde",
1436
+ "serde_json",
1437
+ "sha2 0.11.0",
1438
+ "tempfile",
1439
+ "thiserror",
1440
+ "tokio",
1441
+ "tokio-util",
1442
+ "toml",
1443
+ "tracing",
1444
+ "tracing-subscriber",
1445
+ "url",
1446
+ "wiremock",
1447
+ "zip",
1448
+ ]
1449
+
1450
+ [[package]]
1451
+ name = "osu_indexer"
1452
+ version = "0.1.0"
1453
+ dependencies = [
1454
+ "anyhow",
1455
+ "base64",
1456
+ "clap",
1457
+ "crc32fast",
1458
+ "ctrlc",
1459
+ "hex",
1460
+ "rayon",
1461
+ "rosu-map 0.2.1",
1462
+ "rosu-pp",
1463
+ "rosu-storyboard",
1464
+ "serde",
1465
+ "serde_json",
1466
+ "sha2 0.11.0",
1467
+ "tempfile",
1468
+ "thiserror",
1469
+ "tracing",
1470
+ "tracing-subscriber",
1471
+ "unicode-normalization",
1472
+ "zip",
1473
+ ]
1474
+
1475
+ [[package]]
1476
+ name = "parking_lot"
1477
+ version = "0.12.5"
1478
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1479
+ checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a"
1480
+ dependencies = [
1481
+ "lock_api",
1482
+ "parking_lot_core",
1483
+ ]
1484
+
1485
+ [[package]]
1486
+ name = "parking_lot_core"
1487
+ version = "0.9.12"
1488
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1489
+ checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"
1490
+ dependencies = [
1491
+ "cfg-if",
1492
+ "libc",
1493
+ "redox_syscall",
1494
+ "smallvec",
1495
+ "windows-link",
1496
+ ]
1497
+
1498
+ [[package]]
1499
+ name = "pbkdf2"
1500
+ version = "0.13.0"
1501
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1502
+ checksum = "112d82ceb8c5bf524d9af484d4e4970c9fd5a0cc15ba14ad93dccd28873b0629"
1503
+ dependencies = [
1504
+ "digest 0.11.2",
1505
+ "hmac",
1506
+ ]
1507
+
1508
+ [[package]]
1509
+ name = "percent-encoding"
1510
+ version = "2.3.2"
1511
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1512
+ checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
1513
+
1514
+ [[package]]
1515
+ name = "pin-project-lite"
1516
+ version = "0.2.17"
1517
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1518
+ checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
1519
+
1520
+ [[package]]
1521
+ name = "pkg-config"
1522
+ version = "0.3.33"
1523
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1524
+ checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e"
1525
+
1526
+ [[package]]
1527
+ name = "portable-atomic"
1528
+ version = "1.13.1"
1529
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1530
+ checksum = "c33a9471896f1c69cecef8d20cbe2f7accd12527ce60845ff44c153bb2a21b49"
1531
+
1532
+ [[package]]
1533
+ name = "potential_utf"
1534
+ version = "0.1.5"
1535
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1536
+ checksum = "0103b1cef7ec0cf76490e969665504990193874ea05c85ff9bab8b911d0a0564"
1537
+ dependencies = [
1538
+ "zerovec",
1539
+ ]
1540
+
1541
+ [[package]]
1542
+ name = "powerfmt"
1543
+ version = "0.2.0"
1544
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1545
+ checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391"
1546
+
1547
+ [[package]]
1548
+ name = "ppmd-rust"
1549
+ version = "1.4.0"
1550
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1551
+ checksum = "efca4c95a19a79d1c98f791f10aebd5c1363b473244630bb7dbde1dc98455a24"
1552
+
1553
+ [[package]]
1554
+ name = "ppv-lite86"
1555
+ version = "0.2.21"
1556
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1557
+ checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"
1558
+ dependencies = [
1559
+ "zerocopy",
1560
+ ]
1561
+
1562
+ [[package]]
1563
+ name = "prettyplease"
1564
+ version = "0.2.37"
1565
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1566
+ checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b"
1567
+ dependencies = [
1568
+ "proc-macro2",
1569
+ "syn",
1570
+ ]
1571
+
1572
+ [[package]]
1573
+ name = "proc-macro2"
1574
+ version = "1.0.106"
1575
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1576
+ checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"
1577
+ dependencies = [
1578
+ "unicode-ident",
1579
+ ]
1580
+
1581
+ [[package]]
1582
+ name = "quanta"
1583
+ version = "0.12.6"
1584
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1585
+ checksum = "f3ab5a9d756f0d97bdc89019bd2e4ea098cf9cde50ee7564dde6b81ccc8f06c7"
1586
+ dependencies = [
1587
+ "crossbeam-utils",
1588
+ "libc",
1589
+ "once_cell",
1590
+ "raw-cpuid",
1591
+ "wasi",
1592
+ "web-sys",
1593
+ "winapi",
1594
+ ]
1595
+
1596
+ [[package]]
1597
+ name = "quinn"
1598
+ version = "0.11.9"
1599
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1600
+ checksum = "b9e20a958963c291dc322d98411f541009df2ced7b5a4f2bd52337638cfccf20"
1601
+ dependencies = [
1602
+ "bytes",
1603
+ "cfg_aliases",
1604
+ "pin-project-lite",
1605
+ "quinn-proto",
1606
+ "quinn-udp",
1607
+ "rustc-hash",
1608
+ "rustls",
1609
+ "socket2",
1610
+ "thiserror",
1611
+ "tokio",
1612
+ "tracing",
1613
+ "web-time",
1614
+ ]
1615
+
1616
+ [[package]]
1617
+ name = "quinn-proto"
1618
+ version = "0.11.14"
1619
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1620
+ checksum = "434b42fec591c96ef50e21e886936e66d3cc3f737104fdb9b737c40ffb94c098"
1621
+ dependencies = [
1622
+ "bytes",
1623
+ "getrandom 0.3.4",
1624
+ "lru-slab",
1625
+ "rand 0.9.4",
1626
+ "ring",
1627
+ "rustc-hash",
1628
+ "rustls",
1629
+ "rustls-pki-types",
1630
+ "slab",
1631
+ "thiserror",
1632
+ "tinyvec",
1633
+ "tracing",
1634
+ "web-time",
1635
+ ]
1636
+
1637
+ [[package]]
1638
+ name = "quinn-udp"
1639
+ version = "0.5.14"
1640
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1641
+ checksum = "addec6a0dcad8a8d96a771f815f0eaf55f9d1805756410b39f5fa81332574cbd"
1642
+ dependencies = [
1643
+ "cfg_aliases",
1644
+ "libc",
1645
+ "once_cell",
1646
+ "socket2",
1647
+ "tracing",
1648
+ "windows-sys 0.60.2",
1649
+ ]
1650
+
1651
+ [[package]]
1652
+ name = "quote"
1653
+ version = "1.0.45"
1654
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1655
+ checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924"
1656
+ dependencies = [
1657
+ "proc-macro2",
1658
+ ]
1659
+
1660
+ [[package]]
1661
+ name = "r-efi"
1662
+ version = "5.3.0"
1663
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1664
+ checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"
1665
+
1666
+ [[package]]
1667
+ name = "r-efi"
1668
+ version = "6.0.0"
1669
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1670
+ checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
1671
+
1672
+ [[package]]
1673
+ name = "rand"
1674
+ version = "0.8.6"
1675
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1676
+ checksum = "5ca0ecfa931c29007047d1bc58e623ab12e5590e8c7cc53200d5202b69266d8a"
1677
+ dependencies = [
1678
+ "libc",
1679
+ "rand_chacha 0.3.1",
1680
+ "rand_core 0.6.4",
1681
+ ]
1682
+
1683
+ [[package]]
1684
+ name = "rand"
1685
+ version = "0.9.4"
1686
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1687
+ checksum = "44c5af06bb1b7d3216d91932aed5265164bf384dc89cd6ba05cf59a35f5f76ea"
1688
+ dependencies = [
1689
+ "rand_chacha 0.9.0",
1690
+ "rand_core 0.9.5",
1691
+ ]
1692
+
1693
+ [[package]]
1694
+ name = "rand_chacha"
1695
+ version = "0.3.1"
1696
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1697
+ checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88"
1698
+ dependencies = [
1699
+ "ppv-lite86",
1700
+ "rand_core 0.6.4",
1701
+ ]
1702
+
1703
+ [[package]]
1704
+ name = "rand_chacha"
1705
+ version = "0.9.0"
1706
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1707
+ checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"
1708
+ dependencies = [
1709
+ "ppv-lite86",
1710
+ "rand_core 0.9.5",
1711
+ ]
1712
+
1713
+ [[package]]
1714
+ name = "rand_core"
1715
+ version = "0.6.4"
1716
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1717
+ checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"
1718
+ dependencies = [
1719
+ "getrandom 0.2.17",
1720
+ ]
1721
+
1722
+ [[package]]
1723
+ name = "rand_core"
1724
+ version = "0.9.5"
1725
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1726
+ checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c"
1727
+ dependencies = [
1728
+ "getrandom 0.3.4",
1729
+ ]
1730
+
1731
+ [[package]]
1732
+ name = "raw-cpuid"
1733
+ version = "11.6.0"
1734
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1735
+ checksum = "498cd0dc59d73224351ee52a95fee0f1a617a2eae0e7d9d720cc622c73a54186"
1736
+ dependencies = [
1737
+ "bitflags",
1738
+ ]
1739
+
1740
+ [[package]]
1741
+ name = "rayon"
1742
+ version = "1.12.0"
1743
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1744
+ checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d"
1745
+ dependencies = [
1746
+ "either",
1747
+ "rayon-core",
1748
+ ]
1749
+
1750
+ [[package]]
1751
+ name = "rayon-core"
1752
+ version = "1.13.0"
1753
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1754
+ checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91"
1755
+ dependencies = [
1756
+ "crossbeam-deque",
1757
+ "crossbeam-utils",
1758
+ ]
1759
+
1760
+ [[package]]
1761
+ name = "redox_syscall"
1762
+ version = "0.5.18"
1763
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1764
+ checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"
1765
+ dependencies = [
1766
+ "bitflags",
1767
+ ]
1768
+
1769
+ [[package]]
1770
+ name = "regex"
1771
+ version = "1.12.3"
1772
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1773
+ checksum = "e10754a14b9137dd7b1e3e5b0493cc9171fdd105e0ab477f51b72e7f3ac0e276"
1774
+ dependencies = [
1775
+ "aho-corasick",
1776
+ "memchr",
1777
+ "regex-automata",
1778
+ "regex-syntax",
1779
+ ]
1780
+
1781
+ [[package]]
1782
+ name = "regex-automata"
1783
+ version = "0.4.14"
1784
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1785
+ checksum = "6e1dd4122fc1595e8162618945476892eefca7b88c52820e74af6262213cae8f"
1786
+ dependencies = [
1787
+ "aho-corasick",
1788
+ "memchr",
1789
+ "regex-syntax",
1790
+ ]
1791
+
1792
+ [[package]]
1793
+ name = "regex-lite"
1794
+ version = "0.1.9"
1795
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1796
+ checksum = "cab834c73d247e67f4fae452806d17d3c7501756d98c8808d7c9c7aa7d18f973"
1797
+
1798
+ [[package]]
1799
+ name = "regex-syntax"
1800
+ version = "0.8.10"
1801
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1802
+ checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a"
1803
+
1804
+ [[package]]
1805
+ name = "reqwest"
1806
+ version = "0.12.28"
1807
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1808
+ checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147"
1809
+ dependencies = [
1810
+ "base64",
1811
+ "bytes",
1812
+ "futures-core",
1813
+ "futures-util",
1814
+ "http",
1815
+ "http-body",
1816
+ "http-body-util",
1817
+ "hyper",
1818
+ "hyper-rustls",
1819
+ "hyper-util",
1820
+ "js-sys",
1821
+ "log",
1822
+ "percent-encoding",
1823
+ "pin-project-lite",
1824
+ "quinn",
1825
+ "rustls",
1826
+ "rustls-pki-types",
1827
+ "serde",
1828
+ "serde_json",
1829
+ "serde_urlencoded",
1830
+ "sync_wrapper",
1831
+ "tokio",
1832
+ "tokio-rustls",
1833
+ "tokio-util",
1834
+ "tower",
1835
+ "tower-http",
1836
+ "tower-service",
1837
+ "url",
1838
+ "wasm-bindgen",
1839
+ "wasm-bindgen-futures",
1840
+ "wasm-streams",
1841
+ "web-sys",
1842
+ "webpki-roots",
1843
+ ]
1844
+
1845
+ [[package]]
1846
+ name = "ring"
1847
+ version = "0.17.14"
1848
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1849
+ checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"
1850
+ dependencies = [
1851
+ "cc",
1852
+ "cfg-if",
1853
+ "getrandom 0.2.17",
1854
+ "libc",
1855
+ "untrusted",
1856
+ "windows-sys 0.52.0",
1857
+ ]
1858
+
1859
+ [[package]]
1860
+ name = "rosu-map"
1861
+ version = "0.1.2"
1862
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1863
+ checksum = "907d85647905d8de0b5560a8e2d87b7bf457b4b22cdd8f2025c1ff384435ec25"
1864
+
1865
+ [[package]]
1866
+ name = "rosu-map"
1867
+ version = "0.2.1"
1868
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1869
+ checksum = "6b92ea634d8b3eaa4d7fba7bd12045dda1a50ce81401c96af0d9c851b0737544"
1870
+
1871
+ [[package]]
1872
+ name = "rosu-mods"
1873
+ version = "0.4.1"
1874
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1875
+ checksum = "cc58d42f8f2308b4b241de147827af84179d0a318de250495c7c5e47cb701cd9"
1876
+
1877
+ [[package]]
1878
+ name = "rosu-pp"
1879
+ version = "4.0.1"
1880
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1881
+ checksum = "697808a7bff3a12f18f519c7111de1df1846ae5b937561d56117658626cab978"
1882
+ dependencies = [
1883
+ "divan",
1884
+ "rosu-map 0.2.1",
1885
+ "rosu-mods",
1886
+ ]
1887
+
1888
+ [[package]]
1889
+ name = "rosu-storyboard"
1890
+ version = "0.1.1"
1891
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1892
+ checksum = "c1c60c524ce7966ed36c573f40244a0646bd8cf7554841f30de7394403f40218"
1893
+ dependencies = [
1894
+ "rosu-map 0.1.2",
1895
+ ]
1896
+
1897
+ [[package]]
1898
+ name = "rusqlite"
1899
+ version = "0.32.1"
1900
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1901
+ checksum = "7753b721174eb8ff87a9a0e799e2d7bc3749323e773db92e0984debb00019d6e"
1902
+ dependencies = [
1903
+ "bitflags",
1904
+ "fallible-iterator",
1905
+ "fallible-streaming-iterator",
1906
+ "hashlink",
1907
+ "libsqlite3-sys",
1908
+ "smallvec",
1909
+ ]
1910
+
1911
+ [[package]]
1912
+ name = "rustc-hash"
1913
+ version = "2.1.2"
1914
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1915
+ checksum = "94300abf3f1ae2e2b8ffb7b58043de3d399c73fa6f4b73826402a5c457614dbe"
1916
+
1917
+ [[package]]
1918
+ name = "rustix"
1919
+ version = "1.1.4"
1920
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1921
+ checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190"
1922
+ dependencies = [
1923
+ "bitflags",
1924
+ "errno",
1925
+ "libc",
1926
+ "linux-raw-sys",
1927
+ "windows-sys 0.61.2",
1928
+ ]
1929
+
1930
+ [[package]]
1931
+ name = "rustls"
1932
+ version = "0.23.39"
1933
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1934
+ checksum = "7c2c118cb077cca2822033836dfb1b975355dfb784b5e8da48f7b6c5db74e60e"
1935
+ dependencies = [
1936
+ "once_cell",
1937
+ "ring",
1938
+ "rustls-pki-types",
1939
+ "rustls-webpki",
1940
+ "subtle",
1941
+ "zeroize",
1942
+ ]
1943
+
1944
+ [[package]]
1945
+ name = "rustls-pki-types"
1946
+ version = "1.14.1"
1947
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1948
+ checksum = "30a7197ae7eb376e574fe940d068c30fe0462554a3ddbe4eca7838e049c937a9"
1949
+ dependencies = [
1950
+ "web-time",
1951
+ "zeroize",
1952
+ ]
1953
+
1954
+ [[package]]
1955
+ name = "rustls-webpki"
1956
+ version = "0.103.13"
1957
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1958
+ checksum = "61c429a8649f110dddef65e2a5ad240f747e85f7758a6bccc7e5777bd33f756e"
1959
+ dependencies = [
1960
+ "ring",
1961
+ "rustls-pki-types",
1962
+ "untrusted",
1963
+ ]
1964
+
1965
+ [[package]]
1966
+ name = "rustversion"
1967
+ version = "1.0.22"
1968
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1969
+ checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d"
1970
+
1971
+ [[package]]
1972
+ name = "ryu"
1973
+ version = "1.0.23"
1974
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1975
+ checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"
1976
+
1977
+ [[package]]
1978
+ name = "scopeguard"
1979
+ version = "1.2.0"
1980
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1981
+ checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
1982
+
1983
+ [[package]]
1984
+ name = "semver"
1985
+ version = "1.0.28"
1986
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1987
+ checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
1988
+
1989
+ [[package]]
1990
+ name = "serde"
1991
+ version = "1.0.228"
1992
+ source = "registry+https://github.com/rust-lang/crates.io-index"
1993
+ checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"
1994
+ dependencies = [
1995
+ "serde_core",
1996
+ "serde_derive",
1997
+ ]
1998
+
1999
+ [[package]]
2000
+ name = "serde_core"
2001
+ version = "1.0.228"
2002
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2003
+ checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad"
2004
+ dependencies = [
2005
+ "serde_derive",
2006
+ ]
2007
+
2008
+ [[package]]
2009
+ name = "serde_derive"
2010
+ version = "1.0.228"
2011
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2012
+ checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"
2013
+ dependencies = [
2014
+ "proc-macro2",
2015
+ "quote",
2016
+ "syn",
2017
+ ]
2018
+
2019
+ [[package]]
2020
+ name = "serde_json"
2021
+ version = "1.0.149"
2022
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2023
+ checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86"
2024
+ dependencies = [
2025
+ "itoa",
2026
+ "memchr",
2027
+ "serde",
2028
+ "serde_core",
2029
+ "zmij",
2030
+ ]
2031
+
2032
+ [[package]]
2033
+ name = "serde_spanned"
2034
+ version = "0.6.9"
2035
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2036
+ checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3"
2037
+ dependencies = [
2038
+ "serde",
2039
+ ]
2040
+
2041
+ [[package]]
2042
+ name = "serde_urlencoded"
2043
+ version = "0.7.1"
2044
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2045
+ checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd"
2046
+ dependencies = [
2047
+ "form_urlencoded",
2048
+ "itoa",
2049
+ "ryu",
2050
+ "serde",
2051
+ ]
2052
+
2053
+ [[package]]
2054
+ name = "sha1"
2055
+ version = "0.11.0"
2056
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2057
+ checksum = "aacc4cc499359472b4abe1bf11d0b12e688af9a805fa5e3016f9a386dc2d0214"
2058
+ dependencies = [
2059
+ "cfg-if",
2060
+ "cpufeatures 0.3.0",
2061
+ "digest 0.11.2",
2062
+ ]
2063
+
2064
+ [[package]]
2065
+ name = "sha2"
2066
+ version = "0.10.9"
2067
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2068
+ checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
2069
+ dependencies = [
2070
+ "cfg-if",
2071
+ "cpufeatures 0.2.17",
2072
+ "digest 0.10.7",
2073
+ ]
2074
+
2075
+ [[package]]
2076
+ name = "sha2"
2077
+ version = "0.11.0"
2078
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2079
+ checksum = "446ba717509524cb3f22f17ecc096f10f4822d76ab5c0b9822c5f9c284e825f4"
2080
+ dependencies = [
2081
+ "cfg-if",
2082
+ "cpufeatures 0.3.0",
2083
+ "digest 0.11.2",
2084
+ ]
2085
+
2086
+ [[package]]
2087
+ name = "sharded-slab"
2088
+ version = "0.1.7"
2089
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2090
+ checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6"
2091
+ dependencies = [
2092
+ "lazy_static",
2093
+ ]
2094
+
2095
+ [[package]]
2096
+ name = "shlex"
2097
+ version = "1.3.0"
2098
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2099
+ checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
2100
+
2101
+ [[package]]
2102
+ name = "signal-hook-registry"
2103
+ version = "1.4.8"
2104
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2105
+ checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b"
2106
+ dependencies = [
2107
+ "errno",
2108
+ "libc",
2109
+ ]
2110
+
2111
+ [[package]]
2112
+ name = "simd-adler32"
2113
+ version = "0.3.9"
2114
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2115
+ checksum = "703d5c7ef118737c72f1af64ad2f6f8c5e1921f818cdcb97b8fe6fc69bf66214"
2116
+
2117
+ [[package]]
2118
+ name = "slab"
2119
+ version = "0.4.12"
2120
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2121
+ checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
2122
+
2123
+ [[package]]
2124
+ name = "smallvec"
2125
+ version = "1.15.1"
2126
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2127
+ checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03"
2128
+
2129
+ [[package]]
2130
+ name = "socket2"
2131
+ version = "0.6.3"
2132
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2133
+ checksum = "3a766e1110788c36f4fa1c2b71b387a7815aa65f88ce0229841826633d93723e"
2134
+ dependencies = [
2135
+ "libc",
2136
+ "windows-sys 0.61.2",
2137
+ ]
2138
+
2139
+ [[package]]
2140
+ name = "spinning_top"
2141
+ version = "0.3.0"
2142
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2143
+ checksum = "d96d2d1d716fb500937168cc09353ffdc7a012be8475ac7308e1bdf0e3923300"
2144
+ dependencies = [
2145
+ "lock_api",
2146
+ ]
2147
+
2148
+ [[package]]
2149
+ name = "stable_deref_trait"
2150
+ version = "1.2.1"
2151
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2152
+ checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"
2153
+
2154
+ [[package]]
2155
+ name = "strsim"
2156
+ version = "0.11.1"
2157
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2158
+ checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
2159
+
2160
+ [[package]]
2161
+ name = "subtle"
2162
+ version = "2.6.1"
2163
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2164
+ checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
2165
+
2166
+ [[package]]
2167
+ name = "syn"
2168
+ version = "2.0.117"
2169
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2170
+ checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99"
2171
+ dependencies = [
2172
+ "proc-macro2",
2173
+ "quote",
2174
+ "unicode-ident",
2175
+ ]
2176
+
2177
+ [[package]]
2178
+ name = "sync_wrapper"
2179
+ version = "1.0.2"
2180
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2181
+ checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263"
2182
+ dependencies = [
2183
+ "futures-core",
2184
+ ]
2185
+
2186
+ [[package]]
2187
+ name = "synstructure"
2188
+ version = "0.13.2"
2189
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2190
+ checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2"
2191
+ dependencies = [
2192
+ "proc-macro2",
2193
+ "quote",
2194
+ "syn",
2195
+ ]
2196
+
2197
+ [[package]]
2198
+ name = "tempfile"
2199
+ version = "3.27.0"
2200
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2201
+ checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
2202
+ dependencies = [
2203
+ "fastrand",
2204
+ "getrandom 0.4.2",
2205
+ "once_cell",
2206
+ "rustix",
2207
+ "windows-sys 0.61.2",
2208
+ ]
2209
+
2210
+ [[package]]
2211
+ name = "terminal_size"
2212
+ version = "0.4.4"
2213
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2214
+ checksum = "230a1b821ccbd75b185820a1f1ff7b14d21da1e442e22c0863ea5f08771a8874"
2215
+ dependencies = [
2216
+ "rustix",
2217
+ "windows-sys 0.61.2",
2218
+ ]
2219
+
2220
+ [[package]]
2221
+ name = "thiserror"
2222
+ version = "2.0.18"
2223
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2224
+ checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4"
2225
+ dependencies = [
2226
+ "thiserror-impl",
2227
+ ]
2228
+
2229
+ [[package]]
2230
+ name = "thiserror-impl"
2231
+ version = "2.0.18"
2232
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2233
+ checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5"
2234
+ dependencies = [
2235
+ "proc-macro2",
2236
+ "quote",
2237
+ "syn",
2238
+ ]
2239
+
2240
+ [[package]]
2241
+ name = "thread_local"
2242
+ version = "1.1.9"
2243
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2244
+ checksum = "f60246a4944f24f6e018aa17cdeffb7818b76356965d03b07d6a9886e8962185"
2245
+ dependencies = [
2246
+ "cfg-if",
2247
+ ]
2248
+
2249
+ [[package]]
2250
+ name = "time"
2251
+ version = "0.3.47"
2252
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2253
+ checksum = "743bd48c283afc0388f9b8827b976905fb217ad9e647fae3a379a9283c4def2c"
2254
+ dependencies = [
2255
+ "deranged",
2256
+ "js-sys",
2257
+ "num-conv",
2258
+ "powerfmt",
2259
+ "serde_core",
2260
+ "time-core",
2261
+ ]
2262
+
2263
+ [[package]]
2264
+ name = "time-core"
2265
+ version = "0.1.8"
2266
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2267
+ checksum = "7694e1cfe791f8d31026952abf09c69ca6f6fa4e1a1229e18988f06a04a12dca"
2268
+
2269
+ [[package]]
2270
+ name = "tinystr"
2271
+ version = "0.8.3"
2272
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2273
+ checksum = "c8323304221c2a851516f22236c5722a72eaa19749016521d6dff0824447d96d"
2274
+ dependencies = [
2275
+ "displaydoc",
2276
+ "zerovec",
2277
+ ]
2278
+
2279
+ [[package]]
2280
+ name = "tinyvec"
2281
+ version = "1.11.0"
2282
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2283
+ checksum = "3e61e67053d25a4e82c844e8424039d9745781b3fc4f32b8d55ed50f5f667ef3"
2284
+ dependencies = [
2285
+ "tinyvec_macros",
2286
+ ]
2287
+
2288
+ [[package]]
2289
+ name = "tinyvec_macros"
2290
+ version = "0.1.1"
2291
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2292
+ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
2293
+
2294
+ [[package]]
2295
+ name = "tokio"
2296
+ version = "1.52.1"
2297
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2298
+ checksum = "b67dee974fe86fd92cc45b7a95fdd2f99a36a6d7b0d431a231178d3d670bbcc6"
2299
+ dependencies = [
2300
+ "bytes",
2301
+ "libc",
2302
+ "mio",
2303
+ "pin-project-lite",
2304
+ "signal-hook-registry",
2305
+ "socket2",
2306
+ "tokio-macros",
2307
+ "windows-sys 0.61.2",
2308
+ ]
2309
+
2310
+ [[package]]
2311
+ name = "tokio-macros"
2312
+ version = "2.7.0"
2313
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2314
+ checksum = "385a6cb71ab9ab790c5fe8d67f1645e6c450a7ce006a33de03daa956cf70a496"
2315
+ dependencies = [
2316
+ "proc-macro2",
2317
+ "quote",
2318
+ "syn",
2319
+ ]
2320
+
2321
+ [[package]]
2322
+ name = "tokio-rustls"
2323
+ version = "0.26.4"
2324
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2325
+ checksum = "1729aa945f29d91ba541258c8df89027d5792d85a8841fb65e8bf0f4ede4ef61"
2326
+ dependencies = [
2327
+ "rustls",
2328
+ "tokio",
2329
+ ]
2330
+
2331
+ [[package]]
2332
+ name = "tokio-util"
2333
+ version = "0.7.18"
2334
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2335
+ checksum = "9ae9cec805b01e8fc3fd2fe289f89149a9b66dd16786abd8b19cfa7b48cb0098"
2336
+ dependencies = [
2337
+ "bytes",
2338
+ "futures-core",
2339
+ "futures-sink",
2340
+ "futures-util",
2341
+ "pin-project-lite",
2342
+ "tokio",
2343
+ ]
2344
+
2345
+ [[package]]
2346
+ name = "toml"
2347
+ version = "0.8.23"
2348
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2349
+ checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362"
2350
+ dependencies = [
2351
+ "serde",
2352
+ "serde_spanned",
2353
+ "toml_datetime",
2354
+ "toml_edit",
2355
+ ]
2356
+
2357
+ [[package]]
2358
+ name = "toml_datetime"
2359
+ version = "0.6.11"
2360
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2361
+ checksum = "22cddaf88f4fbc13c51aebbf5f8eceb5c7c5a9da2ac40a13519eb5b0a0e8f11c"
2362
+ dependencies = [
2363
+ "serde",
2364
+ ]
2365
+
2366
+ [[package]]
2367
+ name = "toml_edit"
2368
+ version = "0.22.27"
2369
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2370
+ checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a"
2371
+ dependencies = [
2372
+ "indexmap",
2373
+ "serde",
2374
+ "serde_spanned",
2375
+ "toml_datetime",
2376
+ "toml_write",
2377
+ "winnow",
2378
+ ]
2379
+
2380
+ [[package]]
2381
+ name = "toml_write"
2382
+ version = "0.1.2"
2383
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2384
+ checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801"
2385
+
2386
+ [[package]]
2387
+ name = "tower"
2388
+ version = "0.5.3"
2389
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2390
+ checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4"
2391
+ dependencies = [
2392
+ "futures-core",
2393
+ "futures-util",
2394
+ "pin-project-lite",
2395
+ "sync_wrapper",
2396
+ "tokio",
2397
+ "tower-layer",
2398
+ "tower-service",
2399
+ ]
2400
+
2401
+ [[package]]
2402
+ name = "tower-http"
2403
+ version = "0.6.8"
2404
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2405
+ checksum = "d4e6559d53cc268e5031cd8429d05415bc4cb4aefc4aa5d6cc35fbf5b924a1f8"
2406
+ dependencies = [
2407
+ "async-compression",
2408
+ "bitflags",
2409
+ "bytes",
2410
+ "futures-core",
2411
+ "futures-util",
2412
+ "http",
2413
+ "http-body",
2414
+ "http-body-util",
2415
+ "iri-string",
2416
+ "pin-project-lite",
2417
+ "tokio",
2418
+ "tokio-util",
2419
+ "tower",
2420
+ "tower-layer",
2421
+ "tower-service",
2422
+ ]
2423
+
2424
+ [[package]]
2425
+ name = "tower-layer"
2426
+ version = "0.3.3"
2427
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2428
+ checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e"
2429
+
2430
+ [[package]]
2431
+ name = "tower-service"
2432
+ version = "0.3.3"
2433
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2434
+ checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3"
2435
+
2436
+ [[package]]
2437
+ name = "tracing"
2438
+ version = "0.1.44"
2439
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2440
+ checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"
2441
+ dependencies = [
2442
+ "pin-project-lite",
2443
+ "tracing-attributes",
2444
+ "tracing-core",
2445
+ ]
2446
+
2447
+ [[package]]
2448
+ name = "tracing-attributes"
2449
+ version = "0.1.31"
2450
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2451
+ checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da"
2452
+ dependencies = [
2453
+ "proc-macro2",
2454
+ "quote",
2455
+ "syn",
2456
+ ]
2457
+
2458
+ [[package]]
2459
+ name = "tracing-core"
2460
+ version = "0.1.36"
2461
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2462
+ checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"
2463
+ dependencies = [
2464
+ "once_cell",
2465
+ "valuable",
2466
+ ]
2467
+
2468
+ [[package]]
2469
+ name = "tracing-log"
2470
+ version = "0.2.0"
2471
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2472
+ checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3"
2473
+ dependencies = [
2474
+ "log",
2475
+ "once_cell",
2476
+ "tracing-core",
2477
+ ]
2478
+
2479
+ [[package]]
2480
+ name = "tracing-subscriber"
2481
+ version = "0.3.23"
2482
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2483
+ checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319"
2484
+ dependencies = [
2485
+ "matchers",
2486
+ "nu-ansi-term",
2487
+ "once_cell",
2488
+ "regex-automata",
2489
+ "sharded-slab",
2490
+ "smallvec",
2491
+ "thread_local",
2492
+ "tracing",
2493
+ "tracing-core",
2494
+ "tracing-log",
2495
+ ]
2496
+
2497
+ [[package]]
2498
+ name = "try-lock"
2499
+ version = "0.2.5"
2500
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2501
+ checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
2502
+
2503
+ [[package]]
2504
+ name = "typed-path"
2505
+ version = "0.12.3"
2506
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2507
+ checksum = "8e28f89b80c87b8fb0cf04ab448d5dd0dd0ade2f8891bae878de66a75a28600e"
2508
+
2509
+ [[package]]
2510
+ name = "typenum"
2511
+ version = "1.20.0"
2512
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2513
+ checksum = "40ce102ab67701b8526c123c1bab5cbe42d7040ccfd0f64af1a385808d2f43de"
2514
+
2515
+ [[package]]
2516
+ name = "unicode-ident"
2517
+ version = "1.0.24"
2518
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2519
+ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
2520
+
2521
+ [[package]]
2522
+ name = "unicode-normalization"
2523
+ version = "0.1.25"
2524
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2525
+ checksum = "5fd4f6878c9cb28d874b009da9e8d183b5abc80117c40bbd187a1fde336be6e8"
2526
+ dependencies = [
2527
+ "tinyvec",
2528
+ ]
2529
+
2530
+ [[package]]
2531
+ name = "unicode-width"
2532
+ version = "0.2.2"
2533
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2534
+ checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254"
2535
+
2536
+ [[package]]
2537
+ name = "unicode-xid"
2538
+ version = "0.2.6"
2539
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2540
+ checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853"
2541
+
2542
+ [[package]]
2543
+ name = "untrusted"
2544
+ version = "0.9.0"
2545
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2546
+ checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
2547
+
2548
+ [[package]]
2549
+ name = "url"
2550
+ version = "2.5.8"
2551
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2552
+ checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed"
2553
+ dependencies = [
2554
+ "form_urlencoded",
2555
+ "idna",
2556
+ "percent-encoding",
2557
+ "serde",
2558
+ ]
2559
+
2560
+ [[package]]
2561
+ name = "utf8_iter"
2562
+ version = "1.0.4"
2563
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2564
+ checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"
2565
+
2566
+ [[package]]
2567
+ name = "utf8parse"
2568
+ version = "0.2.2"
2569
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2570
+ checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
2571
+
2572
+ [[package]]
2573
+ name = "valuable"
2574
+ version = "0.1.1"
2575
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2576
+ checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65"
2577
+
2578
+ [[package]]
2579
+ name = "vcpkg"
2580
+ version = "0.2.15"
2581
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2582
+ checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"
2583
+
2584
+ [[package]]
2585
+ name = "version_check"
2586
+ version = "0.9.5"
2587
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2588
+ checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
2589
+
2590
+ [[package]]
2591
+ name = "want"
2592
+ version = "0.3.1"
2593
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2594
+ checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e"
2595
+ dependencies = [
2596
+ "try-lock",
2597
+ ]
2598
+
2599
+ [[package]]
2600
+ name = "wasi"
2601
+ version = "0.11.1+wasi-snapshot-preview1"
2602
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2603
+ checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
2604
+
2605
+ [[package]]
2606
+ name = "wasip2"
2607
+ version = "1.0.3+wasi-0.2.9"
2608
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2609
+ checksum = "20064672db26d7cdc89c7798c48a0fdfac8213434a1186e5ef29fd560ae223d6"
2610
+ dependencies = [
2611
+ "wit-bindgen 0.57.1",
2612
+ ]
2613
+
2614
+ [[package]]
2615
+ name = "wasip3"
2616
+ version = "0.4.0+wasi-0.3.0-rc-2026-01-06"
2617
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2618
+ checksum = "5428f8bf88ea5ddc08faddef2ac4a67e390b88186c703ce6dbd955e1c145aca5"
2619
+ dependencies = [
2620
+ "wit-bindgen 0.51.0",
2621
+ ]
2622
+
2623
+ [[package]]
2624
+ name = "wasm-bindgen"
2625
+ version = "0.2.118"
2626
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2627
+ checksum = "0bf938a0bacb0469e83c1e148908bd7d5a6010354cf4fb73279b7447422e3a89"
2628
+ dependencies = [
2629
+ "cfg-if",
2630
+ "once_cell",
2631
+ "rustversion",
2632
+ "wasm-bindgen-macro",
2633
+ "wasm-bindgen-shared",
2634
+ ]
2635
+
2636
+ [[package]]
2637
+ name = "wasm-bindgen-futures"
2638
+ version = "0.4.68"
2639
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2640
+ checksum = "f371d383f2fb139252e0bfac3b81b265689bf45b6874af544ffa4c975ac1ebf8"
2641
+ dependencies = [
2642
+ "js-sys",
2643
+ "wasm-bindgen",
2644
+ ]
2645
+
2646
+ [[package]]
2647
+ name = "wasm-bindgen-macro"
2648
+ version = "0.2.118"
2649
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2650
+ checksum = "eeff24f84126c0ec2db7a449f0c2ec963c6a49efe0698c4242929da037ca28ed"
2651
+ dependencies = [
2652
+ "quote",
2653
+ "wasm-bindgen-macro-support",
2654
+ ]
2655
+
2656
+ [[package]]
2657
+ name = "wasm-bindgen-macro-support"
2658
+ version = "0.2.118"
2659
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2660
+ checksum = "9d08065faf983b2b80a79fd87d8254c409281cf7de75fc4b773019824196c904"
2661
+ dependencies = [
2662
+ "bumpalo",
2663
+ "proc-macro2",
2664
+ "quote",
2665
+ "syn",
2666
+ "wasm-bindgen-shared",
2667
+ ]
2668
+
2669
+ [[package]]
2670
+ name = "wasm-bindgen-shared"
2671
+ version = "0.2.118"
2672
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2673
+ checksum = "5fd04d9e306f1907bd13c6361b5c6bfc7b3b3c095ed3f8a9246390f8dbdee129"
2674
+ dependencies = [
2675
+ "unicode-ident",
2676
+ ]
2677
+
2678
+ [[package]]
2679
+ name = "wasm-encoder"
2680
+ version = "0.244.0"
2681
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2682
+ checksum = "990065f2fe63003fe337b932cfb5e3b80e0b4d0f5ff650e6985b1048f62c8319"
2683
+ dependencies = [
2684
+ "leb128fmt",
2685
+ "wasmparser",
2686
+ ]
2687
+
2688
+ [[package]]
2689
+ name = "wasm-metadata"
2690
+ version = "0.244.0"
2691
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2692
+ checksum = "bb0e353e6a2fbdc176932bbaab493762eb1255a7900fe0fea1a2f96c296cc909"
2693
+ dependencies = [
2694
+ "anyhow",
2695
+ "indexmap",
2696
+ "wasm-encoder",
2697
+ "wasmparser",
2698
+ ]
2699
+
2700
+ [[package]]
2701
+ name = "wasm-streams"
2702
+ version = "0.4.2"
2703
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2704
+ checksum = "15053d8d85c7eccdbefef60f06769760a563c7f0a9d6902a13d35c7800b0ad65"
2705
+ dependencies = [
2706
+ "futures-util",
2707
+ "js-sys",
2708
+ "wasm-bindgen",
2709
+ "wasm-bindgen-futures",
2710
+ "web-sys",
2711
+ ]
2712
+
2713
+ [[package]]
2714
+ name = "wasmparser"
2715
+ version = "0.244.0"
2716
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2717
+ checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe"
2718
+ dependencies = [
2719
+ "bitflags",
2720
+ "hashbrown 0.15.5",
2721
+ "indexmap",
2722
+ "semver",
2723
+ ]
2724
+
2725
+ [[package]]
2726
+ name = "web-sys"
2727
+ version = "0.3.95"
2728
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2729
+ checksum = "4f2dfbb17949fa2088e5d39408c48368947b86f7834484e87b73de55bc14d97d"
2730
+ dependencies = [
2731
+ "js-sys",
2732
+ "wasm-bindgen",
2733
+ ]
2734
+
2735
+ [[package]]
2736
+ name = "web-time"
2737
+ version = "1.1.0"
2738
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2739
+ checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb"
2740
+ dependencies = [
2741
+ "js-sys",
2742
+ "wasm-bindgen",
2743
+ ]
2744
+
2745
+ [[package]]
2746
+ name = "webpki-roots"
2747
+ version = "1.0.7"
2748
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2749
+ checksum = "52f5ee44c96cf55f1b349600768e3ece3a8f26010c05265ab73f945bb1a2eb9d"
2750
+ dependencies = [
2751
+ "rustls-pki-types",
2752
+ ]
2753
+
2754
+ [[package]]
2755
+ name = "winapi"
2756
+ version = "0.3.9"
2757
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2758
+ checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
2759
+ dependencies = [
2760
+ "winapi-i686-pc-windows-gnu",
2761
+ "winapi-x86_64-pc-windows-gnu",
2762
+ ]
2763
+
2764
+ [[package]]
2765
+ name = "winapi-i686-pc-windows-gnu"
2766
+ version = "0.4.0"
2767
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2768
+ checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
2769
+
2770
+ [[package]]
2771
+ name = "winapi-x86_64-pc-windows-gnu"
2772
+ version = "0.4.0"
2773
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2774
+ checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
2775
+
2776
+ [[package]]
2777
+ name = "windows-link"
2778
+ version = "0.2.1"
2779
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2780
+ checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
2781
+
2782
+ [[package]]
2783
+ name = "windows-sys"
2784
+ version = "0.52.0"
2785
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2786
+ checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
2787
+ dependencies = [
2788
+ "windows-targets 0.52.6",
2789
+ ]
2790
+
2791
+ [[package]]
2792
+ name = "windows-sys"
2793
+ version = "0.59.0"
2794
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2795
+ checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"
2796
+ dependencies = [
2797
+ "windows-targets 0.52.6",
2798
+ ]
2799
+
2800
+ [[package]]
2801
+ name = "windows-sys"
2802
+ version = "0.60.2"
2803
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2804
+ checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb"
2805
+ dependencies = [
2806
+ "windows-targets 0.53.5",
2807
+ ]
2808
+
2809
+ [[package]]
2810
+ name = "windows-sys"
2811
+ version = "0.61.2"
2812
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2813
+ checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
2814
+ dependencies = [
2815
+ "windows-link",
2816
+ ]
2817
+
2818
+ [[package]]
2819
+ name = "windows-targets"
2820
+ version = "0.52.6"
2821
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2822
+ checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
2823
+ dependencies = [
2824
+ "windows_aarch64_gnullvm 0.52.6",
2825
+ "windows_aarch64_msvc 0.52.6",
2826
+ "windows_i686_gnu 0.52.6",
2827
+ "windows_i686_gnullvm 0.52.6",
2828
+ "windows_i686_msvc 0.52.6",
2829
+ "windows_x86_64_gnu 0.52.6",
2830
+ "windows_x86_64_gnullvm 0.52.6",
2831
+ "windows_x86_64_msvc 0.52.6",
2832
+ ]
2833
+
2834
+ [[package]]
2835
+ name = "windows-targets"
2836
+ version = "0.53.5"
2837
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2838
+ checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3"
2839
+ dependencies = [
2840
+ "windows-link",
2841
+ "windows_aarch64_gnullvm 0.53.1",
2842
+ "windows_aarch64_msvc 0.53.1",
2843
+ "windows_i686_gnu 0.53.1",
2844
+ "windows_i686_gnullvm 0.53.1",
2845
+ "windows_i686_msvc 0.53.1",
2846
+ "windows_x86_64_gnu 0.53.1",
2847
+ "windows_x86_64_gnullvm 0.53.1",
2848
+ "windows_x86_64_msvc 0.53.1",
2849
+ ]
2850
+
2851
+ [[package]]
2852
+ name = "windows_aarch64_gnullvm"
2853
+ version = "0.52.6"
2854
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2855
+ checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
2856
+
2857
+ [[package]]
2858
+ name = "windows_aarch64_gnullvm"
2859
+ version = "0.53.1"
2860
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2861
+ checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53"
2862
+
2863
+ [[package]]
2864
+ name = "windows_aarch64_msvc"
2865
+ version = "0.52.6"
2866
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2867
+ checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
2868
+
2869
+ [[package]]
2870
+ name = "windows_aarch64_msvc"
2871
+ version = "0.53.1"
2872
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2873
+ checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006"
2874
+
2875
+ [[package]]
2876
+ name = "windows_i686_gnu"
2877
+ version = "0.52.6"
2878
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2879
+ checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
2880
+
2881
+ [[package]]
2882
+ name = "windows_i686_gnu"
2883
+ version = "0.53.1"
2884
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2885
+ checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3"
2886
+
2887
+ [[package]]
2888
+ name = "windows_i686_gnullvm"
2889
+ version = "0.52.6"
2890
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2891
+ checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
2892
+
2893
+ [[package]]
2894
+ name = "windows_i686_gnullvm"
2895
+ version = "0.53.1"
2896
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2897
+ checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c"
2898
+
2899
+ [[package]]
2900
+ name = "windows_i686_msvc"
2901
+ version = "0.52.6"
2902
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2903
+ checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
2904
+
2905
+ [[package]]
2906
+ name = "windows_i686_msvc"
2907
+ version = "0.53.1"
2908
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2909
+ checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2"
2910
+
2911
+ [[package]]
2912
+ name = "windows_x86_64_gnu"
2913
+ version = "0.52.6"
2914
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2915
+ checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
2916
+
2917
+ [[package]]
2918
+ name = "windows_x86_64_gnu"
2919
+ version = "0.53.1"
2920
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2921
+ checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499"
2922
+
2923
+ [[package]]
2924
+ name = "windows_x86_64_gnullvm"
2925
+ version = "0.52.6"
2926
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2927
+ checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
2928
+
2929
+ [[package]]
2930
+ name = "windows_x86_64_gnullvm"
2931
+ version = "0.53.1"
2932
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2933
+ checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1"
2934
+
2935
+ [[package]]
2936
+ name = "windows_x86_64_msvc"
2937
+ version = "0.52.6"
2938
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2939
+ checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
2940
+
2941
+ [[package]]
2942
+ name = "windows_x86_64_msvc"
2943
+ version = "0.53.1"
2944
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2945
+ checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650"
2946
+
2947
+ [[package]]
2948
+ name = "winnow"
2949
+ version = "0.7.15"
2950
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2951
+ checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945"
2952
+ dependencies = [
2953
+ "memchr",
2954
+ ]
2955
+
2956
+ [[package]]
2957
+ name = "wiremock"
2958
+ version = "0.6.5"
2959
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2960
+ checksum = "08db1edfb05d9b3c1542e521aea074442088292f00b5f28e435c714a98f85031"
2961
+ dependencies = [
2962
+ "assert-json-diff",
2963
+ "base64",
2964
+ "deadpool",
2965
+ "futures",
2966
+ "http",
2967
+ "http-body-util",
2968
+ "hyper",
2969
+ "hyper-util",
2970
+ "log",
2971
+ "once_cell",
2972
+ "regex",
2973
+ "serde",
2974
+ "serde_json",
2975
+ "tokio",
2976
+ "url",
2977
+ ]
2978
+
2979
+ [[package]]
2980
+ name = "wit-bindgen"
2981
+ version = "0.51.0"
2982
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2983
+ checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5"
2984
+ dependencies = [
2985
+ "wit-bindgen-rust-macro",
2986
+ ]
2987
+
2988
+ [[package]]
2989
+ name = "wit-bindgen"
2990
+ version = "0.57.1"
2991
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2992
+ checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e"
2993
+
2994
+ [[package]]
2995
+ name = "wit-bindgen-core"
2996
+ version = "0.51.0"
2997
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2998
+ checksum = "ea61de684c3ea68cb082b7a88508a8b27fcc8b797d738bfc99a82facf1d752dc"
2999
+ dependencies = [
3000
+ "anyhow",
3001
+ "heck",
3002
+ "wit-parser",
3003
+ ]
3004
+
3005
+ [[package]]
3006
+ name = "wit-bindgen-rust"
3007
+ version = "0.51.0"
3008
+ source = "registry+https://github.com/rust-lang/crates.io-index"
3009
+ checksum = "b7c566e0f4b284dd6561c786d9cb0142da491f46a9fbed79ea69cdad5db17f21"
3010
+ dependencies = [
3011
+ "anyhow",
3012
+ "heck",
3013
+ "indexmap",
3014
+ "prettyplease",
3015
+ "syn",
3016
+ "wasm-metadata",
3017
+ "wit-bindgen-core",
3018
+ "wit-component",
3019
+ ]
3020
+
3021
+ [[package]]
3022
+ name = "wit-bindgen-rust-macro"
3023
+ version = "0.51.0"
3024
+ source = "registry+https://github.com/rust-lang/crates.io-index"
3025
+ checksum = "0c0f9bfd77e6a48eccf51359e3ae77140a7f50b1e2ebfe62422d8afdaffab17a"
3026
+ dependencies = [
3027
+ "anyhow",
3028
+ "prettyplease",
3029
+ "proc-macro2",
3030
+ "quote",
3031
+ "syn",
3032
+ "wit-bindgen-core",
3033
+ "wit-bindgen-rust",
3034
+ ]
3035
+
3036
+ [[package]]
3037
+ name = "wit-component"
3038
+ version = "0.244.0"
3039
+ source = "registry+https://github.com/rust-lang/crates.io-index"
3040
+ checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2"
3041
+ dependencies = [
3042
+ "anyhow",
3043
+ "bitflags",
3044
+ "indexmap",
3045
+ "log",
3046
+ "serde",
3047
+ "serde_derive",
3048
+ "serde_json",
3049
+ "wasm-encoder",
3050
+ "wasm-metadata",
3051
+ "wasmparser",
3052
+ "wit-parser",
3053
+ ]
3054
+
3055
+ [[package]]
3056
+ name = "wit-parser"
3057
+ version = "0.244.0"
3058
+ source = "registry+https://github.com/rust-lang/crates.io-index"
3059
+ checksum = "ecc8ac4bc1dc3381b7f59c34f00b67e18f910c2c0f50015669dde7def656a736"
3060
+ dependencies = [
3061
+ "anyhow",
3062
+ "id-arena",
3063
+ "indexmap",
3064
+ "log",
3065
+ "semver",
3066
+ "serde",
3067
+ "serde_derive",
3068
+ "serde_json",
3069
+ "unicode-xid",
3070
+ "wasmparser",
3071
+ ]
3072
+
3073
+ [[package]]
3074
+ name = "writeable"
3075
+ version = "0.6.3"
3076
+ source = "registry+https://github.com/rust-lang/crates.io-index"
3077
+ checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4"
3078
+
3079
+ [[package]]
3080
+ name = "yoke"
3081
+ version = "0.8.2"
3082
+ source = "registry+https://github.com/rust-lang/crates.io-index"
3083
+ checksum = "abe8c5fda708d9ca3df187cae8bfb9ceda00dd96231bed36e445a1a48e66f9ca"
3084
+ dependencies = [
3085
+ "stable_deref_trait",
3086
+ "yoke-derive",
3087
+ "zerofrom",
3088
+ ]
3089
+
3090
+ [[package]]
3091
+ name = "yoke-derive"
3092
+ version = "0.8.2"
3093
+ source = "registry+https://github.com/rust-lang/crates.io-index"
3094
+ checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e"
3095
+ dependencies = [
3096
+ "proc-macro2",
3097
+ "quote",
3098
+ "syn",
3099
+ "synstructure",
3100
+ ]
3101
+
3102
+ [[package]]
3103
+ name = "zerocopy"
3104
+ version = "0.8.48"
3105
+ source = "registry+https://github.com/rust-lang/crates.io-index"
3106
+ checksum = "eed437bf9d6692032087e337407a86f04cd8d6a16a37199ed57949d415bd68e9"
3107
+ dependencies = [
3108
+ "zerocopy-derive",
3109
+ ]
3110
+
3111
+ [[package]]
3112
+ name = "zerocopy-derive"
3113
+ version = "0.8.48"
3114
+ source = "registry+https://github.com/rust-lang/crates.io-index"
3115
+ checksum = "70e3cd084b1788766f53af483dd21f93881ff30d7320490ec3ef7526d203bad4"
3116
+ dependencies = [
3117
+ "proc-macro2",
3118
+ "quote",
3119
+ "syn",
3120
+ ]
3121
+
3122
+ [[package]]
3123
+ name = "zerofrom"
3124
+ version = "0.1.7"
3125
+ source = "registry+https://github.com/rust-lang/crates.io-index"
3126
+ checksum = "69faa1f2a1ea75661980b013019ed6687ed0e83d069bc1114e2cc74c6c04c4df"
3127
+ dependencies = [
3128
+ "zerofrom-derive",
3129
+ ]
3130
+
3131
+ [[package]]
3132
+ name = "zerofrom-derive"
3133
+ version = "0.1.7"
3134
+ source = "registry+https://github.com/rust-lang/crates.io-index"
3135
+ checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1"
3136
+ dependencies = [
3137
+ "proc-macro2",
3138
+ "quote",
3139
+ "syn",
3140
+ "synstructure",
3141
+ ]
3142
+
3143
+ [[package]]
3144
+ name = "zeroize"
3145
+ version = "1.8.2"
3146
+ source = "registry+https://github.com/rust-lang/crates.io-index"
3147
+ checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0"
3148
+
3149
+ [[package]]
3150
+ name = "zerotrie"
3151
+ version = "0.2.4"
3152
+ source = "registry+https://github.com/rust-lang/crates.io-index"
3153
+ checksum = "0f9152d31db0792fa83f70fb2f83148effb5c1f5b8c7686c3459e361d9bc20bf"
3154
+ dependencies = [
3155
+ "displaydoc",
3156
+ "yoke",
3157
+ "zerofrom",
3158
+ ]
3159
+
3160
+ [[package]]
3161
+ name = "zerovec"
3162
+ version = "0.11.6"
3163
+ source = "registry+https://github.com/rust-lang/crates.io-index"
3164
+ checksum = "90f911cbc359ab6af17377d242225f4d75119aec87ea711a880987b18cd7b239"
3165
+ dependencies = [
3166
+ "yoke",
3167
+ "zerofrom",
3168
+ "zerovec-derive",
3169
+ ]
3170
+
3171
+ [[package]]
3172
+ name = "zerovec-derive"
3173
+ version = "0.11.3"
3174
+ source = "registry+https://github.com/rust-lang/crates.io-index"
3175
+ checksum = "625dc425cab0dca6dc3c3319506e6593dcb08a9f387ea3b284dbd52a92c40555"
3176
+ dependencies = [
3177
+ "proc-macro2",
3178
+ "quote",
3179
+ "syn",
3180
+ ]
3181
+
3182
+ [[package]]
3183
+ name = "zip"
3184
+ version = "8.6.0"
3185
+ source = "registry+https://github.com/rust-lang/crates.io-index"
3186
+ checksum = "2d04a6b5381502aa6087c94c669499eb1602eb9c5e8198e534de571f7154809b"
3187
+ dependencies = [
3188
+ "aes",
3189
+ "bzip2",
3190
+ "constant_time_eq",
3191
+ "crc32fast",
3192
+ "deflate64",
3193
+ "flate2",
3194
+ "getrandom 0.4.2",
3195
+ "hmac",
3196
+ "indexmap",
3197
+ "lzma-rust2",
3198
+ "memchr",
3199
+ "pbkdf2",
3200
+ "ppmd-rust",
3201
+ "sha1",
3202
+ "time",
3203
+ "typed-path",
3204
+ "zeroize",
3205
+ "zopfli",
3206
+ "zstd",
3207
+ ]
3208
+
3209
+ [[package]]
3210
+ name = "zlib-rs"
3211
+ version = "0.6.3"
3212
+ source = "registry+https://github.com/rust-lang/crates.io-index"
3213
+ checksum = "3be3d40e40a133f9c916ee3f9f4fa2d9d63435b5fbe1bfc6d9dae0aa0ada1513"
3214
+
3215
+ [[package]]
3216
+ name = "zmij"
3217
+ version = "1.0.21"
3218
+ source = "registry+https://github.com/rust-lang/crates.io-index"
3219
+ checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa"
3220
+
3221
+ [[package]]
3222
+ name = "zopfli"
3223
+ version = "0.8.3"
3224
+ source = "registry+https://github.com/rust-lang/crates.io-index"
3225
+ checksum = "f05cd8797d63865425ff89b5c4a48804f35ba0ce8d125800027ad6017d2b5249"
3226
+ dependencies = [
3227
+ "bumpalo",
3228
+ "crc32fast",
3229
+ "log",
3230
+ "simd-adler32",
3231
+ ]
3232
+
3233
+ [[package]]
3234
+ name = "zstd"
3235
+ version = "0.13.3"
3236
+ source = "registry+https://github.com/rust-lang/crates.io-index"
3237
+ checksum = "e91ee311a569c327171651566e07972200e76fcfe2242a4fa446149a3881c08a"
3238
+ dependencies = [
3239
+ "zstd-safe",
3240
+ ]
3241
+
3242
+ [[package]]
3243
+ name = "zstd-safe"
3244
+ version = "7.2.4"
3245
+ source = "registry+https://github.com/rust-lang/crates.io-index"
3246
+ checksum = "8f49c4d5f0abb602a93fb8736af2a4f4dd9512e36f7f570d66e65ff867ed3b9d"
3247
+ dependencies = [
3248
+ "zstd-sys",
3249
+ ]
3250
+
3251
+ [[package]]
3252
+ name = "zstd-sys"
3253
+ version = "2.0.16+zstd.1.5.7"
3254
+ source = "registry+https://github.com/rust-lang/crates.io-index"
3255
+ checksum = "91e19ebc2adc8f83e43039e79776e3fda8ca919132d68a1fed6a5faca2683748"
3256
+ dependencies = [
3257
+ "cc",
3258
+ "pkg-config",
3259
+ ]
Cargo.toml ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [workspace]
2
+ resolver = "2"
3
+ members = [
4
+ "crates/osu_indexer",
5
+ "crates/osu_fetcher",
6
+ ]
7
+
8
+ [workspace.package]
9
+ edition = "2021"
10
+ license = "MIT OR Apache-2.0"
11
+ publish = false
12
+
13
+ [workspace.dependencies]
14
+ # Shared across crates. Versions verified on crates.io 2026-04-26.
15
+ serde = { version = "1", features = ["derive"] }
16
+ serde_json = "1"
17
+ clap = { version = "4", features = ["derive"] }
18
+ anyhow = "1"
19
+ thiserror = "2"
20
+ tracing = "0.1"
21
+ tracing-subscriber = { version = "0.3", features = ["env-filter"] }
22
+ sha2 = "0.11"
23
+ hex = "0.4"
24
+ zip = "8"
25
+ rayon = "1.10"
26
+ ctrlc = { version = "3.4", features = ["termination"] }
27
+
28
+ [profile.release]
29
+ opt-level = 3
30
+ lto = "thin"
31
+ codegen-units = 1
README.md CHANGED
@@ -15,95 +15,6 @@ tags:
15
  - beatmaps
16
  - storyboards
17
  - multimodal
18
- configs:
19
- - config_name: archive_revisions_all
20
- data_files:
21
- - split: all
22
- path: data/v1/all_revisions/archive_revisions/**/*.parquet
23
- - config_name: latest_revisions_all
24
- data_files:
25
- - split: all
26
- path: data/v1/all_revisions/latest_revisions/**/*.parquet
27
- - config_name: set_revisions_all
28
- data_files:
29
- - split: all
30
- path: data/v1/all_revisions/set_revisions/**/*.parquet
31
- - config_name: logical_files_all_revisions
32
- data_files:
33
- - split: all
34
- path: data/v1/all_revisions/logical_files/**/*.parquet
35
- - config_name: beatmaps_latest
36
- data_files:
37
- - split: train
38
- path: data/v1/latest/beatmaps/p_split=train/**/*.parquet
39
- - split: validation
40
- path: data/v1/latest/beatmaps/p_split=validation/**/*.parquet
41
- - split: test
42
- path: data/v1/latest/beatmaps/p_split=test/**/*.parquet
43
- - config_name: beatmaps_all_revisions
44
- data_files:
45
- - split: all
46
- path: data/v1/all_revisions/beatmaps/**/*.parquet
47
- - config_name: hit_objects_latest
48
- data_files:
49
- - split: train
50
- path: data/v1/latest/hit_objects_common/p_split=train/**/*.parquet
51
- - split: validation
52
- path: data/v1/latest/hit_objects_common/p_split=validation/**/*.parquet
53
- - split: test
54
- path: data/v1/latest/hit_objects_common/p_split=test/**/*.parquet
55
- - config_name: difficulty_attributes_latest
56
- data_files:
57
- - split: train
58
- path: data/v1/latest/difficulty_attributes/p_split=train/**/*.parquet
59
- - split: validation
60
- path: data/v1/latest/difficulty_attributes/p_split=validation/**/*.parquet
61
- - split: test
62
- path: data/v1/latest/difficulty_attributes/p_split=test/**/*.parquet
63
- - config_name: storyboard_sources_latest
64
- data_files:
65
- - split: train
66
- path: data/v1/latest/storyboard_sources/p_split=train/**/*.parquet
67
- - split: validation
68
- path: data/v1/latest/storyboard_sources/p_split=validation/**/*.parquet
69
- - split: test
70
- path: data/v1/latest/storyboard_sources/p_split=test/**/*.parquet
71
- - config_name: storyboard_elements_latest
72
- data_files:
73
- - split: train
74
- path: data/v1/latest/storyboard_elements/p_split=train/**/*.parquet
75
- - split: validation
76
- path: data/v1/latest/storyboard_elements/p_split=validation/**/*.parquet
77
- - split: test
78
- path: data/v1/latest/storyboard_elements/p_split=test/**/*.parquet
79
- - config_name: storyboard_commands_latest
80
- data_files:
81
- - split: train
82
- path: data/v1/latest/storyboard_commands/p_split=train/**/*.parquet
83
- - split: validation
84
- path: data/v1/latest/storyboard_commands/p_split=validation/**/*.parquet
85
- - split: test
86
- path: data/v1/latest/storyboard_commands/p_split=test/**/*.parquet
87
- - config_name: storyboard_variables_latest
88
- data_files:
89
- - split: train
90
- path: data/v1/latest/storyboard_variables/p_split=train/**/*.parquet
91
- - split: validation
92
- path: data/v1/latest/storyboard_variables/p_split=validation/**/*.parquet
93
- - split: test
94
- path: data/v1/latest/storyboard_variables/p_split=test/**/*.parquet
95
- - config_name: references_latest
96
- data_files:
97
- - split: train
98
- path: data/v1/latest/asset_references/p_split=train/**/*.parquet
99
- - split: validation
100
- path: data/v1/latest/asset_references/p_split=validation/**/*.parquet
101
- - split: test
102
- path: data/v1/latest/asset_references/p_split=test/**/*.parquet
103
- - config_name: problems_all
104
- data_files:
105
- - split: all
106
- path: data/v1/all_revisions/problems/**/*.parquet
107
  ---
108
 
109
  # osu-everything
@@ -112,10 +23,9 @@ configs:
112
  beatmapset archives and parsed metadata.
113
 
114
  The bucket keeps the original `.osz` archives and compact Parquet metadata.
115
- It does not publish extracted file blobs, per-revision manifests, or the old
116
- global blobs registry. This avoids the previous hundreds-of-thousands of
117
- small files while preserving the raw archive bytes needed for later asset
118
- extraction.
119
 
120
  Canonical bucket:
121
 
@@ -130,19 +40,17 @@ osu-everything/
130
  ├── archives/sha256/aa/bb/<archive_sha256>.osz
131
  ├── data/v1/
132
  │ ├── all_revisions/<table>/part-<batch>.parquet
133
- │ └── latest/<table>/p_split=<split>/part-*.parquet
134
  ├── schemas/v1/*.schema.json
135
  └── state/fetcher/state.db
136
  ```
137
 
138
  `all_revisions` is the append-only metadata history. Its physical layout is
139
- deliberately compact: each table receives one Parquet file per ingest chunk,
140
- with logical partition columns such as `set_shard`, `ruleset`, `key_count`,
141
- and `split` kept inside the Parquet body.
142
 
143
- `latest` is a regenerated convenience view. It contains the latest ingested
144
- revision per beatmapset and is physically split only by `p_split=train`,
145
- `p_split=validation`, or `p_split=test`.
146
 
147
  ## Loading
148
 
@@ -154,36 +62,35 @@ hf sync \
154
  ./osu-everything/data/v1/latest/beatmaps
155
  ```
156
 
157
- Load with Hugging Face Datasets:
158
 
159
  ```python
160
- from datasets import load_dataset
161
 
162
- beatmaps = load_dataset(
163
- "parquet",
164
- data_files="./osu-everything/data/v1/latest/beatmaps/p_split=train/**/*.parquet",
165
- split="train",
166
- )
167
  ```
168
 
169
- Large object streams should be scoped by table and split:
170
 
171
  ```bash
172
  hf sync \
173
- hf://buckets/lekdan/osu-everything/data/v1/latest/hit_objects_mania/p_split=train \
174
- ./osu-everything/data/v1/latest/hit_objects_mania/p_split=train
175
  ```
176
 
177
- `all_revisions` is useful for historical comparisons and custom splits. It is
178
- not physically split by `split`, so loading a whole all-revisions table reads
179
- that whole table.
180
 
181
  ## Raw Assets
182
 
183
  Raw audio, images, videos, and `.osu` text are inside the original `.osz`
184
- archives under `archives/`. Metadata rows still carry `blob_sha256`,
185
- `blob_path`, path, role, and reference fields as logical identifiers, but
186
- there is no published extracted blob byte store.
187
 
188
  Consumers that need bytes should open the archive from
189
  `archive_revisions.archive_path` and then use `logical_files.path_posix` or
@@ -204,47 +111,19 @@ Primary table prefixes:
204
  | `data/v1/all_revisions/storyboard_*` | Storyboard sources, elements, commands, variables. |
205
  | `data/v1/all_revisions/asset_references` | Resolved and missing asset references. |
206
  | `data/v1/all_revisions/difficulty_attributes` | rosu-pp difficulty attributes. |
207
- | `data/v1/latest/<table>` | Latest-only views for training and quick reads. |
208
 
209
  See `schemas/v1/` for complete column definitions.
210
 
211
- ## Splits
212
-
213
- Splits are deterministic per beatmapset key:
214
-
215
- | Hash bucket | Split |
216
- | --- | --- |
217
- | 0-89 | train |
218
- | 90-94 | validation |
219
- | 95-99 | test |
220
-
221
- All revisions of the same beatmapset stay in the same split. The split is
222
- stored in every set-keyed table as the `split` column.
223
-
224
- Training code can import `python/osu_dataset/splits.py` to recompute or
225
- override the split without reading PyArrow:
226
-
227
- ```python
228
- from osu_dataset.splits import custom_hash_split, set_key_from_srid
229
-
230
- def experiment_split(set_revision_id: str) -> str:
231
- return custom_hash_split(
232
- set_key_from_srid(set_revision_id),
233
- seed="my-experiment",
234
- train=80,
235
- validation=10,
236
- )
237
- ```
238
-
239
  ## Updating
240
 
241
  The maintained workflow is documented in `docs/PIPELINE_RUNBOOK.md`.
242
 
243
  Use `scripts/update_maps_v1.sh` for normal updates. A fresh update worker
244
  downloads only `data/`, `schemas/`, and `state/fetcher/`, then fetches and
245
- ingests only new or changed `.osz` files. Upload uses an append-only
246
- `hf buckets sync` for local `archives/` and `--delete` only for regenerated
247
- metadata prefixes such as `data/` and `schemas/`.
248
 
249
  The update wrapper compacts `data/v1/all_revisions/` by default after ingest.
250
  It rewrites metadata fragments into fewer `compact-*.parquet` files, then
 
15
  - beatmaps
16
  - storyboards
17
  - multimodal
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
  ---
19
 
20
  # osu-everything
 
23
  beatmapset archives and parsed metadata.
24
 
25
  The bucket keeps the original `.osz` archives and compact Parquet metadata.
26
+ It does not publish extracted member blobs, per-revision manifests, or a global
27
+ blob registry. This keeps file counts low while preserving the raw archive
28
+ bytes needed for later asset extraction.
 
29
 
30
  Canonical bucket:
31
 
 
40
  ├── archives/sha256/aa/bb/<archive_sha256>.osz
41
  ├── data/v1/
42
  │ ├── all_revisions/<table>/part-<batch>.parquet
43
+ │ └── latest/<table>/part-*.parquet
44
  ├── schemas/v1/*.schema.json
45
  └── state/fetcher/state.db
46
  ```
47
 
48
  `all_revisions` is the append-only metadata history. Its physical layout is
49
+ compact: each table receives one Parquet file per ingest chunk, and compaction
50
+ rewrites older fragments into larger `compact-*.parquet` files.
 
51
 
52
+ `latest` is a regenerated convenience view containing the latest ingested
53
+ revision per beatmapset.
 
54
 
55
  ## Loading
56
 
 
62
  ./osu-everything/data/v1/latest/beatmaps
63
  ```
64
 
65
+ Load with PyArrow:
66
 
67
  ```python
68
+ import pyarrow.dataset as ds
69
 
70
+ beatmaps = ds.dataset(
71
+ "./osu-everything/data/v1/latest/beatmaps",
72
+ format="parquet",
73
+ ).to_table()
 
74
  ```
75
 
76
+ Large tables should be scoped by prefix:
77
 
78
  ```bash
79
  hf sync \
80
+ hf://buckets/lekdan/osu-everything/data/v1/latest/hit_objects_mania \
81
+ ./osu-everything/data/v1/latest/hit_objects_mania
82
  ```
83
 
84
+ `all_revisions` is useful for historical comparisons and custom sampling. It
85
+ is organized by table, so loading a whole all-revisions table reads that whole
86
+ table.
87
 
88
  ## Raw Assets
89
 
90
  Raw audio, images, videos, and `.osu` text are inside the original `.osz`
91
+ archives under `archives/`. Metadata rows carry `blob_sha256`, archive member
92
+ paths, roles, and reference fields as logical identifiers, but there is no
93
+ published extracted blob byte store.
94
 
95
  Consumers that need bytes should open the archive from
96
  `archive_revisions.archive_path` and then use `logical_files.path_posix` or
 
111
  | `data/v1/all_revisions/storyboard_*` | Storyboard sources, elements, commands, variables. |
112
  | `data/v1/all_revisions/asset_references` | Resolved and missing asset references. |
113
  | `data/v1/all_revisions/difficulty_attributes` | rosu-pp difficulty attributes. |
114
+ | `data/v1/latest/<table>` | Latest-only views for quick reads and ML workloads. |
115
 
116
  See `schemas/v1/` for complete column definitions.
117
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
118
  ## Updating
119
 
120
  The maintained workflow is documented in `docs/PIPELINE_RUNBOOK.md`.
121
 
122
  Use `scripts/update_maps_v1.sh` for normal updates. A fresh update worker
123
  downloads only `data/`, `schemas/`, and `state/fetcher/`, then fetches and
124
+ ingests only new or changed `.osz` files. Upload uses append-only sync for
125
+ local `archives/` and `--delete` only for regenerated metadata prefixes such
126
+ as `data/` and `schemas/`.
127
 
128
  The update wrapper compacts `data/v1/all_revisions/` by default after ingest.
129
  It rewrites metadata fragments into fewer `compact-*.parquet` files, then
crates/osu_fetcher/Cargo.toml ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [package]
2
+ name = "osu_fetcher"
3
+ version = "0.1.0"
4
+ edition.workspace = true
5
+ license.workspace = true
6
+ publish.workspace = true
7
+ description = "Discover and download missing osu! beatmapsets via the official osu! API and multiple mirrors."
8
+
9
+ [dependencies]
10
+ # Async runtime + HTTP
11
+ tokio = { version = "1", features = ["rt-multi-thread", "macros", "fs", "sync", "signal", "time", "io-util"] }
12
+ tokio-util = { version = "0.7", features = ["rt"] }
13
+ reqwest = { version = "0.12", default-features = false, features = ["rustls-tls", "json", "gzip", "brotli", "stream"] }
14
+ async-trait = "0.1"
15
+ futures = "0.3"
16
+ bytes = "1"
17
+ url = "2"
18
+
19
+ # Persistent state
20
+ rusqlite = { version = "0.32", features = ["bundled"] }
21
+
22
+ # Config file parsing
23
+ toml = "0.8"
24
+
25
+ # Rate limiting
26
+ governor = "0.7"
27
+ nonzero_ext = "0.3"
28
+
29
+ # Progress reporting (terminal bar + ETA/rate)
30
+ indicatif = "0.17"
31
+ console = "0.15"
32
+
33
+ # Workspace deps
34
+ clap.workspace = true
35
+ serde.workspace = true
36
+ serde_json.workspace = true
37
+ anyhow.workspace = true
38
+ thiserror.workspace = true
39
+ tracing.workspace = true
40
+ tracing-subscriber.workspace = true
41
+ sha2.workspace = true
42
+ hex.workspace = true
43
+ zip.workspace = true
44
+
45
+ [dev-dependencies]
46
+ wiremock = "0.6"
47
+ tempfile = "3"
48
+
49
+ [lib]
50
+ name = "osu_fetcher"
51
+ path = "src/lib.rs"
52
+
53
+ [[bin]]
54
+ name = "osu_fetcher"
55
+ path = "src/main.rs"
crates/osu_fetcher/README.md ADDED
@@ -0,0 +1,391 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # osu_fetcher
2
+
3
+ Discover and download missing osu! beatmapsets via the official osu! API
4
+ plus a fallback chain of public mirrors. Crash-safe, mirror-aware, and
5
+ designed to feed the rest of the `osu-everything` pipeline. The standalone
6
+ default `--archives-dir` is `osu_archives/`; the maintained dataset update
7
+ script overrides it to `incoming_osz/`.
8
+
9
+ ```
10
+ osu_fetcher enumerate → discover → scan → download → status / verify / retry
11
+ (osu! API) (mirrors) (disk) (mirror pool + rate limits)
12
+ ```
13
+
14
+ ## Quick start
15
+
16
+ ```bash
17
+ # 1) Credentials. Copy the template and fill in your OAuth + beatconnect keys:
18
+ cp osu_fetcher.toml.example osu_fetcher.toml
19
+ ${EDITOR:-nano} osu_fetcher.toml
20
+
21
+ # 2) Build the release binary (workspace-aware):
22
+ cargo build --release -p osu_fetcher
23
+
24
+ # 3) Populate the wanted set from the official API:
25
+ ./target/release/osu_fetcher enumerate \
26
+ --statuses ranked,approved,loved,qualified \
27
+ --mode 0
28
+
29
+ # 4) Optional: mirror-index discovery for sets no longer surfaced by API search:
30
+ ./target/release/osu_fetcher discover \
31
+ --statuses ranked,approved,loved,qualified \
32
+ --mode 0 \
33
+ --min-quorum 2
34
+
35
+ # 5) Mark everything you already have on disk as success:
36
+ ./target/release/osu_fetcher scan
37
+
38
+ # 6) Download the gap. Idle workers greedily claim the next pending set.
39
+ ./target/release/osu_fetcher download --concurrency 8
40
+
41
+ # 7) Inspect the queue at any time:
42
+ ./target/release/osu_fetcher status
43
+ ```
44
+
45
+ ## Configuration
46
+
47
+ `osu_fetcher.toml` (gitignored; template at `osu_fetcher.toml.example`):
48
+
49
+ ```toml
50
+ [osu_api]
51
+ client_id = "<numeric_client_id>"
52
+ client_secret = "<client_secret>"
53
+
54
+ [mirrors.beatconnect]
55
+ api_key = "<beatconnect_token>"
56
+ ```
57
+
58
+ Resolution order for every field: env var (e.g. `OSU_CLIENT_ID`) → config
59
+ file → error (osu! API id+secret are required) or skip-mirror (beatconnect
60
+ is optional). Env vars override the file so CI can inject secrets without
61
+ editing the file.
62
+
63
+ ## Subcommands
64
+
65
+ | Command | What it does |
66
+ |---|---|
67
+ | `enumerate` | Paginates `/api/v2/beatmapsets/search?m={mode}&s={status}&sort=updated_desc` for each requested status, upserts every beatmapset into `sets`. Cursor checkpoints saved per-status after each successful page → can resume mid-run. **Incremental by default**: each run saves a `last_updated` high-water mark and the next run stops paginating once it crosses that mark; pass `--full-rescan` to re-walk everything. |
68
+ | `discover` | Walks mirror search/list surfaces for ranked/approved/loved/qualified candidates and promotes sets to `wanted` when at least `--min-quorum` independent mirrors agree. Use after `enumerate` to catch cached sets not surfaced by official API search. |
69
+ | `scan` | Walks `--archives-dir`, parses `<set_id>.osz` filenames, marks each as `success` in the state DB. Optional `--verify` opens each archive and walks its zip entries; corrupt files stay pending. |
70
+ | `download` | Runs a bounded greedy worker pool. Each idle worker claims the next `pending wanted` row in `set_id` order and cycles mirrors per-set. See **Failure modes** below for the resilience guarantees. |
71
+ | `status` | Prints `wanted / pending / in_progress / success / failed / missing` counts. |
72
+ | `verify` | Walks `--archives-dir`, validates every `.osz`. With `--fix`, marks corrupt rows back to pending. |
73
+ | `retry` | Resets every `failed` and `missing` row back to `pending` so the next download run will retry. |
74
+
75
+ ## Global flags
76
+
77
+ | Flag | Default | Purpose |
78
+ |---|---|---|
79
+ | `--config <path>` | `osu_fetcher.toml` | TOML credentials file. |
80
+ | `--state-db <path>` | `.fetcher.state.db` | SQLite WAL state DB; created on first use. |
81
+ | `--archives-dir <path>` | `osu_archives` | Where downloads land + where scan reads. |
82
+ | `--osu-rpm <n>` | `480` | Official osu! API requests-per-minute. Lower it if auth or API responses start throttling. |
83
+ | `--nerinyan-rpm <n>` | `480` | Per-mirror download RPM. Repeated for `--catboy-rpm`, `--sayobot-rpm`, `--nekoha-rpm`, `--beatconnect-rpm`, `--osudirect-rpm`, `--nzbasic-rpm`, `--osudl-rpm`, and `--osuapi-rpm`. Lower individual mirrors if an operator asks us to back off. |
84
+ | `--disable <name>` | — | Disable a mirror by name. Repeatable. |
85
+ | `--no-progress` | off | Disable the live terminal dashboard. Use for CI / quiet logs. |
86
+ | `--force-progress` | off | Render the live download dashboard directly to `/dev/tty`, useful when a wrapper script tees logs inside tmux. |
87
+ | `--verbose` | off | Re-enable per-set INFO logs; visually interrupts the dashboard while events fly. |
88
+
89
+ ## Live dashboard
90
+
91
+ `download`, `enumerate`, `discover`, and `scan` render live terminal
92
+ progress while running. It is auto-disabled when stderr is not a TTY; pass
93
+ `--force-progress` to render the download dashboard through `/dev/tty`, or
94
+ `--no-progress` to keep it quiet.
95
+
96
+ `download` shows a multi-pane view:
97
+
98
+ ```
99
+ osu_fetcher download · 8 workers · running 4m 12s
100
+
101
+ [████████████░░░░░░░░░░░░░░░░░░░░░░░░░░░] 12534/30142 41% · ETA 1h 14m · 4.2 sets/s
102
+ ok 12420 failed 87 missing 27 aborted 0 · 4.2 GiB at 8.3 MiB/s · avg 348.5 KiB · 4 in flight
103
+
104
+ mirror reqs ok miss 429 err inv ms ok% in
105
+ nerinyan 11203 11051 120 12 5 18 412 98.6% 3
106
+ catboy 312 284 0 0 2 6 521 91.0% 1
107
+ sayobot 14 12 0 0 0 2 780 85.7% 0
108
+ nekoha 3 3 0 0 0 0 1024 100.0% 0
109
+ beatconnect 4 4 0 0 0 0 298 100.0% 0
110
+ ```
111
+
112
+ Per-mirror columns: `reqs` total HTTP attempts · `ok` successful · `miss`
113
+ 404s · `429` rate-limit hits · `err` connection / 5xx errors · `inv`
114
+ invalid-archive rejections (200 with non-osz body — the deep-verify catch)
115
+ · `ms` average request duration · `ok%` success rate · `in` current
116
+ in-flight requests against this mirror.
117
+
118
+ Per-set INFO logs ("download ok") are demoted to debug while the dashboard
119
+ is active so the bar isn't repainted by every line; `--verbose` brings them
120
+ back. WARN/ERROR logs (download failures, requeues) still print and will
121
+ visibly interrupt the dashboard, which is intentional.
122
+
123
+ `enumerate`, `discover`, and `scan` use counter spinners showing pages /
124
+ items processed, current cursor, quorum stats, and bad-name /
125
+ bad-archive counts as applicable.
126
+
127
+ ## Architecture
128
+
129
+ ```
130
+ ┌─────────────────────────────────┐
131
+ │ state DB (SQLite, WAL mode) │
132
+ │ sets · mirror_attempts · meta │
133
+ └─────────────────────────────────┘
134
+ ▲ ▲
135
+ │ │
136
+ ┌─────────┴────┐ ┌─────┴───────┐
137
+ │ enumerate │ │ download │ ← run lock (file)
138
+ │ (osu! API) │ │ (workers) │
139
+ └──────────────┘ └─────────────┘
140
+
141
+
142
+ ┌──────────────────────────┐
143
+ │ MirrorPool │
144
+ │ ┌────────────────────┐ │
145
+ │ │ nerinyan (480 rpm) │ │
146
+ │ │ catboy (480 rpm) │ │
147
+ │ │ osudirect(480 rpm) │ │
148
+ │ │ nekoha (480 rpm) │ │
149
+ │ │ nzbasic (480 rpm) │ │
150
+ │ │ sayobot (480 rpm) │ │
151
+ │ │ osudl (480 rpm) │ │
152
+ │ │ osuapi (480 rpm) │ │
153
+ │ │ beatconn.(480 rpm) │ │
154
+ │ └────────────────────┘ │
155
+ │ classify_response → │
156
+ │ deep verify_bytes │
157
+ │ (zip + .osu file) │
158
+ └──────────────────────────┘
159
+
160
+
161
+ atomic_write (.partial → fsync → rename → dir-fsync)
162
+
163
+
164
+ osu_archives/<id>.osz
165
+ ```
166
+
167
+ State machine (per `set_id`):
168
+
169
+ ```
170
+ pending ──claim──▶ in_progress ──finish_success──▶ success
171
+ ▲ │ │
172
+ │ requeue │ ├──finish_failed────────▶ failed
173
+ └───────────────────┘ └──finish_missing───────▶ missing
174
+ (every mirror returned 404)
175
+ ```
176
+
177
+ `retry` flips `{failed, missing}` back to `pending`. `requeue_in_progress`
178
+ fires at the start of every `download` run (and also on `enumerate`'s
179
+ startup as a safety net) to recover orphaned claims from a crashed prior
180
+ run.
181
+
182
+ ## Failure modes
183
+
184
+ The download path is built around the assumption that this thing **will**
185
+ get killed mid-run — laptop closes, power blips, Ctrl-C, OS drops you while
186
+ streaming — and we don't ever want a half-written `.osz`, a state DB that
187
+ disagrees with the disk, or a row stuck in a permanent inconsistent state.
188
+
189
+ ### Ctrl-C / graceful shutdown
190
+ - A signal handler flips a `tokio_util::sync::CancellationToken`.
191
+ - Each worker checks the token before claiming the next row.
192
+ - **Each in-flight worker `select!`s its HTTP future against the token**, so
193
+ Ctrl-C aborts even mid-download (a 100 MB video on a slow mirror used to
194
+ block shutdown for 30+ s; now it tears down within milliseconds).
195
+ - On abort, the worker calls `release_claim(set_id)` so the row goes back
196
+ to `pending`. No abandoned `in_progress`.
197
+
198
+ ### Hard kill / SIGKILL / power off
199
+ - `in_progress` rows are stranded — the process didn't release them.
200
+ - On the next `download`, **`requeue_in_progress()`** flips every
201
+ `in_progress` row back to `pending`. SQLite's WAL mode handles its own
202
+ crash recovery for any in-flight transaction.
203
+ - `.partial` files left behind by a crashed write are removed by
204
+ **`cleanup_orphan_partials()`** at the start of every download run.
205
+ `scan` ignores them too (extension filter).
206
+
207
+ ### Mid-write power loss
208
+ - Bytes go to `<id>.osz.partial`, get `flush()` + `sync_all()` (file fsync),
209
+ then `rename(.partial, .osz)`.
210
+ - After the rename we **`File::open(parent_dir).sync_all()`** to make the
211
+ rename's metadata durable. Without this step, some Linux filesystems can
212
+ lose the directory entry on power-off while the file's contents survive,
213
+ leaving us with bytes nothing references.
214
+ - Rename is atomic on the same filesystem, so an interrupt anywhere along
215
+ this path leaves either the old state (no `.osz`, just a `.partial`) or
216
+ the new (final `.osz`, no `.partial`). Never a half-written `.osz`.
217
+
218
+ ### Mirror returns 200 with garbage
219
+ This is the subtle one. A misconfigured mirror (or one rate-limiting via an
220
+ HTML page) can answer `200 OK` with a body that *isn't* a real `.osz`:
221
+ - HTML status / login page wrapped in zip-like bytes.
222
+ - A truncated archive whose magic byte passes a shallow check.
223
+ - A valid zip that happens to contain no `.osu` file (just a stray asset).
224
+
225
+ A 4-byte magic check would let all three through. **`classify_response`
226
+ runs the full `verify::verify_bytes`** on every successful response —
227
+ opens the zip, walks entries, requires at least one `.osu`. On failure it
228
+ returns `MirrorError::InvalidArchive`, which the pool treats as a
229
+ recoverable error and **advances to the next mirror**. The bad bytes never
230
+ touch disk.
231
+
232
+ ### One mirror down, others up
233
+ - 404: pool advances. If *every* mirror 404s, the row is promoted from
234
+ `failed` to `missing` (so you can distinguish "transient" from "no mirror
235
+ has this anymore").
236
+ - 5xx / network: pool advances. The row counts a regular `failed` and gets
237
+ `attempts` incremented. Run `retry` later to reset.
238
+ - 429: same as 5xx for outcome — but the per-mirror rate limiter holds the
239
+ next call back automatically, so you don't need to babysit it.
240
+ - Final failure logs include the full attempted mirror chain, for example
241
+ `nerinyan:HttpError,catboy:NotFound,osudirect:Timeout`.
242
+
243
+ ### Concurrent `osu_fetcher download` processes
244
+ Bad scenario: process B starts up while process A is still running. B's
245
+ `requeue_in_progress` would flip A's live in-flight claims back to
246
+ `pending`, then both processes might claim the same set, racing on the
247
+ final `rename` and one of them spuriously marking the row `failed`.
248
+
249
+ Defense: an OS-level **exclusive file lock** on `<state_db>.run.lock`,
250
+ acquired via `std::fs::File::try_lock` (Rust 1.89+). Held for the lifetime
251
+ of a download run. The kernel releases it on process exit — graceful,
252
+ panic, SIGKILL, or power-off — so there are no stale OS locks to clean
253
+ up. A second concurrent process bails immediately with a clear error
254
+ pointing at the lockfile.
255
+
256
+ The zero-byte lockfile path can remain on disk after a clean exit. That file
257
+ is not the lock; the OS-held lock is. You should not need to delete it
258
+ manually.
259
+
260
+ The lock is per-`--state-db` so running two distinct fetcher invocations
261
+ against two distinct DBs on the same machine doesn't deadlock.
262
+
263
+ ### `finish_success` DB write fails
264
+ After atomic_write puts the `.osz` on disk, we commit the success row.
265
+ If that DB write fails (disk full, locked DB), the worker now returns
266
+ **`Failed`** rather than `Success`. The on-disk file is harmless: the next
267
+ run sees the row as `in_progress`, requeues to `pending`, re-fetches, and
268
+ the new `atomic_write` overwrites the existing file with identical (or
269
+ newer) bytes. The state DB is never out of sync with the run statistics.
270
+
271
+ ### Cursor checkpoint corruption
272
+ `enumerate` saves the API's `cursor_string` into `meta` after every
273
+ *successful* page. If the API ever returned a malformed cursor, the next
274
+ run's `/search` call would error and we'd surface that — no silent data
275
+ corruption, no infinite loop. (Hasn't happened yet against the real API.)
276
+
277
+ ### Body size during stream
278
+ Whole-body buffering via `resp.bytes().await`. For typical maps (~5–50 MB)
279
+ this is cheap. For unusual large videos (~100+ MB) it's still fine on a
280
+ modern host. We never write incomplete bytes — we either get the full body
281
+ or an error. The trade-off: peak memory roughly equals
282
+ `concurrency * largest_concurrent_body`. With `--concurrency 8` and 100 MB
283
+ maps that's ~800 MB at peak — well within ordinary headroom.
284
+
285
+ ## State DB schema (v1)
286
+
287
+ ```sql
288
+ sets
289
+ set_id INTEGER PRIMARY KEY
290
+ wanted INTEGER NOT NULL DEFAULT 0 -- 0 or 1
291
+ ranked_status TEXT -- ranked|approved|loved|qualified
292
+ artist, title, creator, api_last_updated TEXT
293
+ discovered_at INTEGER -- unix epoch
294
+ download_status TEXT NOT NULL DEFAULT 'pending'
295
+ -- pending|in_progress|success|failed|missing
296
+ attempts INTEGER NOT NULL DEFAULT 0
297
+ last_error TEXT
298
+ last_mirror, flavor, saved_path, sha256 TEXT
299
+ bytes, last_attempt_at, completed_at INTEGER
300
+
301
+ mirror_attempts -- append-only audit log
302
+ id, set_id, mirror, attempted_at, duration_ms,
303
+ http_status, bytes, outcome, error
304
+ -- outcome ∈ {success, not_found, http_error,
305
+ -- rate_limited, network, invalid_archive}
306
+
307
+ meta -- key/value bag
308
+ schema_version
309
+ enumerate.cursor.<status>
310
+ enumerate.high_water.<status>
311
+
312
+ mirror_discoveries -- v2 discovery table
313
+ set_id, mirror, claimed_status, has_osu_std,
314
+ title, artist, creator, last_updated,
315
+ first_seen_at, last_seen_at
316
+ ```
317
+
318
+ WAL mode + `synchronous=NORMAL`. `foreign_keys=ON` so deleting a `sets` row
319
+ cascades to its `mirror_attempts`.
320
+
321
+ ## Mirror-by-mirror notes
322
+
323
+ The dataset wants the **complete** archive only (video + storyboard +
324
+ skin + hitsounds), so the CLI no longer exposes a `--flavor` flag —
325
+ every download requests the unmodified `.osz` from each mirror. The
326
+ `Flavor` enum stays in the library so per-mirror URL builders keep their
327
+ flavor-aware paths for future use.
328
+
329
+ | Mirror | Auth | Notes |
330
+ |---|---|---|
331
+ | nerinyan.moe | none | Fastest in our smoke tests. |
332
+ | catboy.best | none | Operated by osu.direct. Solid backup. |
333
+ | osu.direct | none | Documented 120 rpm rate limit. Returns 302 to a signed S3 URL (reqwest follows transparently). |
334
+ | nekoha.moe | none | Newer mirror; reasonable fallback. |
335
+ | direct.nzbasic.com | none | Same endpoint nzbasic's batch-beatmap-downloader uses (`{set_id}.osz`). Full-archive only, no novideo path. |
336
+ | osudl.org | none | Short-link mirror (`/s/{set_id}`). |
337
+ | osu! API download | osu! API credentials | Official `/api/v2/beatmapsets/{id}/download` endpoint. Can be disabled with `--disable osuapi`; requires an auth mode that can access downloads. |
338
+ | sayobot.cn | none | China-based; slower from Western users but occasionally has rare maps. |
339
+ | beatconnect.io | API key (token query param) | Slower; auto-skipped if no key configured. |
340
+
341
+ Pool selection is **health-aware**, not priority-ordered: each request's
342
+ starting mirror is chosen via smooth weighted round-robin where
343
+ `weight = score² × MiB/s` (success rate squared × measured bandwidth).
344
+ Mirrors that consistently fail drop to "dormant" status — they get ~2%
345
+ probe traffic so we can detect recovery, but otherwise stay out of
346
+ rotation. Fallback after a transient failure walks the chain in
347
+ descending health order and exhausts every supported mirror before the set
348
+ is marked failed or missing.
349
+
350
+ To add a mirror: implement the `Mirror` trait in
351
+ `src/mirrors/<name>.rs`, add a per-mirror `RateLimited` field on
352
+ `MirrorLimiters`, register in `main::build_pool`. The per-mirror unit
353
+ tests live next to each impl and just exercise URL generation; HTTP
354
+ behavior is exercised via `tests/classify_response.rs`.
355
+
356
+ ## Tests
357
+
358
+ ```bash
359
+ cargo test -p osu_fetcher
360
+ ```
361
+
362
+ Coverage:
363
+ - Unit tests — state DB migrations + transitions, rate limiter
364
+ pacing, config file resolution, mirror URL generators, ZIP validation,
365
+ file lock acquire/release.
366
+ - Integration tests (`tests/integration.rs`) — full `download::run`
367
+ orchestration: success, all-mirrors-404 → missing, 5xx fallback,
368
+ in-flight cancellation, requeue across restart, `--limit` cap, deep
369
+ verify advancing past invalid archives.
370
+ - **7 wiremock tests** (`tests/classify_response.rs`) — `classify_response`
371
+ against real HTTP responses: HTML 200, truncated zip, no-osu-files zip,
372
+ minimal-real osz, 404, 429.
373
+
374
+ ## Operational tips
375
+
376
+ - **Dataset updates**: prefer `scripts/update_maps_v1.sh` from the repo root.
377
+ It seeds success rows from compact Parquet metadata, so update workers do
378
+ not need the historical archive tree.
379
+ - **Standalone first run**: `enumerate`, optionally `discover`, then `scan`
380
+ your existing archive folder to populate the success side, then `download`.
381
+ After that, run incremental `enumerate` to pick up new ranks.
382
+ - **Long runs**: tail the lockfile path printed by `download begin` to see
383
+ the active PID. Ctrl-C is responsive even mid-flight.
384
+ - **Disk full**: workers fail individual sets, the run continues. Free
385
+ space and run `retry` to drain the failed bucket.
386
+ - **Permanently missing maps** (DMCA / mapper deletions on every mirror):
387
+ they accumulate in `missing`. Tolerated; not retried by `download` until
388
+ you `retry` them explicitly.
389
+ - **Rate-limit tuning**: if a mirror op asks you to slow down, lower
390
+ `--<name>-rpm`. The update wrapper passes `480` rpm by default for every
391
+ fetcher target.
crates/osu_fetcher/src/api.rs ADDED
@@ -0,0 +1,241 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //! High-level osu! API v2 client.
2
+ //!
3
+ //! `api.rs` used to own auth state directly; that lives in [`crate::auth`]
4
+ //! now (it grew enough complexity — refresh tokens, 2FA, persistence,
5
+ //! lazer-impersonation password grant — to deserve its own module). What
6
+ //! remains here is the thin part: a typed [`OsuApi`] that bundles the
7
+ //! shared [`OsuAuth`] handle with a per-process [`RateLimited`] and exposes
8
+ //! the search-paginate helper used by `enumerate`.
9
+ //!
10
+ //! Other modules wanting authenticated /api/v2 access (notably the
11
+ //! [`crate::mirrors::osuapi::OsuApiMirror`]) build their own requests
12
+ //! against [`OsuApi::client`] / [`OsuApi::current_token`] — sharing one
13
+ //! token + one rate limiter across everything keeps the upstream's view
14
+ //! consistent regardless of which subcommand or mirror initiated the call.
15
+
16
+ use std::sync::Arc;
17
+
18
+ use anyhow::{anyhow, bail, Context, Result};
19
+ use reqwest::{header::AUTHORIZATION, StatusCode};
20
+ use serde::Deserialize;
21
+
22
+ use crate::auth::OsuAuth;
23
+ use crate::ratelimit::RateLimited;
24
+ use crate::RankedStatus;
25
+
26
+ /// One page of beatmapsets returned by `search`.
27
+ ///
28
+ /// `cursor_string` is `None` once the server has nothing left to send; that
29
+ /// is also our enumeration's stop condition.
30
+ #[derive(Clone, Debug, Deserialize)]
31
+ pub struct SearchResponse {
32
+ #[serde(default)]
33
+ pub beatmapsets: Vec<BeatmapsetEntry>,
34
+ #[serde(default)]
35
+ pub cursor_string: Option<String>,
36
+ #[serde(default)]
37
+ pub total: Option<u64>,
38
+ }
39
+
40
+ /// Slim subset of the API beatmapset shape — just the fields we persist into
41
+ /// `sets`. Everything else is left unparsed; we don't want a schema evolution
42
+ /// upstream to break enumeration.
43
+ #[derive(Clone, Debug, Deserialize)]
44
+ pub struct BeatmapsetEntry {
45
+ pub id: u64,
46
+ #[serde(default)]
47
+ pub artist: Option<String>,
48
+ #[serde(default)]
49
+ pub title: Option<String>,
50
+ #[serde(default)]
51
+ pub creator: Option<String>,
52
+ #[serde(default)]
53
+ pub status: Option<String>,
54
+ #[serde(default)]
55
+ pub last_updated: Option<String>,
56
+ /// Per-difficulty list — used downstream to filter sets that lack any
57
+ /// osu! standard difficulty. Optional; older API responses may omit it.
58
+ #[serde(default)]
59
+ pub beatmaps: Option<Vec<BeatmapEntry>>,
60
+ }
61
+
62
+ #[derive(Clone, Debug, Deserialize)]
63
+ pub struct BeatmapEntry {
64
+ #[serde(default)]
65
+ pub mode_int: Option<u8>,
66
+ #[serde(default)]
67
+ pub mode: Option<String>,
68
+ }
69
+
70
+ const OSU_BASE: &str = "https://osu.ppy.sh";
71
+
72
+ pub struct OsuApi {
73
+ auth: Arc<OsuAuth>,
74
+ rl: RateLimited,
75
+ }
76
+
77
+ impl OsuApi {
78
+ pub fn new(auth: Arc<OsuAuth>, rl: RateLimited) -> Arc<Self> {
79
+ Arc::new(Self { auth, rl })
80
+ }
81
+
82
+ /// Reqwest client used for all osu! API requests. Exposed so other
83
+ /// callers (the `osuapi` download mirror) can issue authenticated
84
+ /// requests without spinning up a second client; the auth-mode-specific
85
+ /// User-Agent (`osu!` for lazer mode, `osu_fetcher/...` otherwise) is
86
+ /// already baked in.
87
+ pub fn client(&self) -> &reqwest::Client {
88
+ self.auth.client()
89
+ }
90
+
91
+ /// Yield a usable bearer token, minting / refreshing / verifying as
92
+ /// needed. Delegated to [`OsuAuth`] — see that module for the full
93
+ /// state machine.
94
+ pub async fn current_token(&self) -> Result<String> {
95
+ self.auth.current_token().await
96
+ }
97
+
98
+ /// Force the next `current_token` call to mint a fresh token. Use this
99
+ /// after a 401 so the retry doesn't hand back the same dead token from
100
+ /// cache.
101
+ pub async fn invalidate_token(&self) {
102
+ self.auth.invalidate().await
103
+ }
104
+
105
+ /// Pinned `x-api-version` header value. Lazer-equivalent: this is what
106
+ /// the lazer client sends on every authenticated /api/v2 request.
107
+ pub fn api_version_header(&self) -> &'static str {
108
+ self.auth.api_version()
109
+ }
110
+
111
+ /// Underlying auth handle — exposed for callers that want auth-mode
112
+ /// metadata (e.g., logging) without going through the high-level
113
+ /// `OsuApi` accessors.
114
+ pub fn auth(&self) -> &Arc<OsuAuth> {
115
+ &self.auth
116
+ }
117
+
118
+ /// One page of `/api/v2/beatmapsets/search`. The caller drives the loop
119
+ /// with the returned `cursor_string`.
120
+ ///
121
+ /// `sort` is an osu! API sort token (e.g. `"updated_desc"`,
122
+ /// `"ranked_desc"`). Passing `None` defers to the API default. Pagination
123
+ /// is sort-aware — within a single paginated session, every call must use
124
+ /// the same sort, otherwise the cursor returns inconsistent rows.
125
+ pub async fn search_beatmapsets(
126
+ &self,
127
+ status: RankedStatus,
128
+ mode: u8,
129
+ cursor: Option<&str>,
130
+ sort: Option<&str>,
131
+ ) -> Result<SearchResponse> {
132
+ // Per-call rate limit. A retry on 401 reuses the same slot — the
133
+ // upstream's actual concern is request volume, not whether the token
134
+ // happened to be stale.
135
+ self.rl.acquire().await;
136
+
137
+ let token = self.current_token().await?;
138
+ let resp = self
139
+ .build_search_request(&token, status, mode, cursor, sort)
140
+ .send()
141
+ .await
142
+ .context("GET /api/v2/beatmapsets/search")?;
143
+ if resp.status() == StatusCode::UNAUTHORIZED {
144
+ // Token may have been invalidated server-side; force-refresh once.
145
+ tracing::debug!("/search returned 401, forcing token refresh");
146
+ self.invalidate_token().await;
147
+ let token = self.current_token().await?;
148
+ let resp = self
149
+ .build_search_request(&token, status, mode, cursor, sort)
150
+ .send()
151
+ .await
152
+ .context("GET /api/v2/beatmapsets/search (after token refresh)")?;
153
+ if !resp.status().is_success() {
154
+ let status = resp.status();
155
+ let body = resp.text().await.unwrap_or_default();
156
+ bail!("search failed after token refresh: {status} {body}");
157
+ }
158
+ return resp
159
+ .json()
160
+ .await
161
+ .map_err(|e| anyhow!("decoding search JSON: {e}"));
162
+ }
163
+ if !resp.status().is_success() {
164
+ let status = resp.status();
165
+ let body = resp.text().await.unwrap_or_default();
166
+ bail!("search returned {status}: {body}");
167
+ }
168
+ resp.json::<SearchResponse>()
169
+ .await
170
+ .map_err(|e| anyhow!("decoding search JSON: {e}"))
171
+ }
172
+
173
+ fn build_search_request(
174
+ &self,
175
+ token: &str,
176
+ status: RankedStatus,
177
+ mode: u8,
178
+ cursor: Option<&str>,
179
+ sort: Option<&str>,
180
+ ) -> reqwest::RequestBuilder {
181
+ let mut req = self
182
+ .client()
183
+ .get(format!("{OSU_BASE}/api/v2/beatmapsets/search"))
184
+ .header(AUTHORIZATION, format!("Bearer {token}"))
185
+ .header("x-api-version", self.api_version_header())
186
+ .query(&[
187
+ ("m", mode.to_string()),
188
+ ("s", status.as_api_str().to_string()),
189
+ ]);
190
+ if let Some(s) = sort {
191
+ req = req.query(&[("sort", s)]);
192
+ }
193
+ if let Some(c) = cursor {
194
+ req = req.query(&[("cursor_string", c)]);
195
+ }
196
+ req
197
+ }
198
+ }
199
+
200
+ #[cfg(test)]
201
+ mod tests {
202
+ use super::*;
203
+
204
+ #[test]
205
+ fn search_response_deserializes_minimal() {
206
+ let body = r#"{
207
+ "beatmapsets": [
208
+ {"id": 123, "artist": "a", "title": "t", "creator": "c",
209
+ "status": "ranked", "last_updated": "2026-01-01T00:00:00Z"}
210
+ ],
211
+ "cursor_string": "abc",
212
+ "total": 9999
213
+ }"#;
214
+ let r: SearchResponse = serde_json::from_str(body).unwrap();
215
+ assert_eq!(r.beatmapsets.len(), 1);
216
+ assert_eq!(r.beatmapsets[0].id, 123);
217
+ assert_eq!(r.cursor_string.as_deref(), Some("abc"));
218
+ }
219
+
220
+ #[test]
221
+ fn search_response_handles_terminal_page() {
222
+ // Last page: server returns null cursor and may omit beatmapsets.
223
+ let body = r#"{"beatmapsets": [], "cursor_string": null}"#;
224
+ let r: SearchResponse = serde_json::from_str(body).unwrap();
225
+ assert!(r.beatmapsets.is_empty());
226
+ assert!(r.cursor_string.is_none());
227
+ }
228
+
229
+ #[test]
230
+ fn search_response_tolerates_extra_fields() {
231
+ // Schema evolution: the API may add fields. We must not break.
232
+ let body = r#"{
233
+ "beatmapsets": [],
234
+ "cursor_string": null,
235
+ "future_field": {"nested": [1,2,3]},
236
+ "search": {"sort": "ranked_desc"}
237
+ }"#;
238
+ let r: SearchResponse = serde_json::from_str(body).unwrap();
239
+ assert!(r.cursor_string.is_none());
240
+ }
241
+ }
crates/osu_fetcher/src/auth.rs ADDED
@@ -0,0 +1,894 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //! OAuth handshake + token cache for the official osu! API.
2
+ //!
3
+ //! Two auth modes coexist behind a single [`OsuAuth`] handle:
4
+ //!
5
+ //! 1. [`OsuAuthMode::ClientCredentials`] — the standard OAuth app flow you
6
+ //! register at <https://osu.ppy.sh/home/account/edit#oauth>. Tokens have
7
+ //! `public` scope: enough for `/api/v2/beatmapsets/search` (used by
8
+ //! `enumerate`), but **not** enough for `/api/v2/beatmapsets/{id}/download`
9
+ //! — that endpoint returns 403 for any client_credentials token.
10
+ //!
11
+ //! 2. [`OsuAuthMode::LazerPassword`] — replicates the public osu!lazer
12
+ //! desktop client byte-for-byte. We POST to `/oauth/token` with the
13
+ //! well-known hardcoded `client_id=5` and matching secret straight out
14
+ //! of `osu/osu.Game/Online/ProductionEndpointConfiguration.cs`, plus
15
+ //! `grant_type=password`, `scope=*`, and the user's own osu! login.
16
+ //! The response is a *user-scoped* bearer that's authorised to download
17
+ //! sets — same token type the real lazer client uses.
18
+ //!
19
+ //! After a fresh password grant, lazer probes `/api/v2/me` to see whether
20
+ //! the account requires session verification (TOTP or email). When it does,
21
+ //! lazer pops a UI dialog asking for the 6-digit code; we read the code
22
+ //! from stderr/stdin instead. The successful POST to `/api/v2/session/verify`
23
+ //! "unlocks" the existing token — no new token is issued.
24
+ //!
25
+ //! Tokens are persisted as JSON to a sidecar file (default:
26
+ //! `<state_db>.osu_token.json`) so login + 2FA happen once per machine, not
27
+ //! once per CLI invocation. On Unix the file is created with mode 0600;
28
+ //! Windows uses default ACLs (treat the file as sensitive — it grants full
29
+ //! access to the linked osu! account until the refresh chain breaks).
30
+ //!
31
+ //! Refresh-on-expiry uses lazer's same 30-second pre-expiry margin
32
+ //! (`OAuthToken.IsValid` in the lazer source). On a 401 from a sensitive
33
+ //! endpoint, callers should `invalidate()` so the next request re-mints.
34
+
35
+ use std::path::{Path, PathBuf};
36
+ use std::sync::Arc;
37
+ use std::time::Duration;
38
+
39
+ use anyhow::{bail, Context, Result};
40
+ use reqwest::{header::AUTHORIZATION, Client};
41
+ use serde::{Deserialize, Serialize};
42
+ use tokio::sync::Mutex;
43
+ use tracing::{debug, info, warn};
44
+
45
+ /// Lazer's hardcoded production `client_id`. MIT-licensed and embedded in
46
+ /// every released lazer binary, so quoting it here is fine; treating it as
47
+ /// secret would be theatre. Source:
48
+ /// `osu.Game/Online/ProductionEndpointConfiguration.cs:12`.
49
+ pub const LAZER_CLIENT_ID: &str = "5";
50
+ /// Matching `client_secret`. Same source, line 11.
51
+ pub const LAZER_CLIENT_SECRET: &str = "FGc9GAtyHzeQDshWP5Ah7dega8hJACAJpQtw6OXk";
52
+ /// Scope lazer always requests on `/oauth/token` (`OAuth.cs:210`).
53
+ pub const LAZER_SCOPE: &str = "*";
54
+ /// Exact User-Agent lazer sends on every HTTP call (`OsuJsonWebRequest.cs:19`,
55
+ /// `OsuWebRequest.cs:19`). Literally the four bytes "osu!".
56
+ pub const LAZER_USER_AGENT: &str = "osu!";
57
+ /// `x-api-version` header value. Lazer release builds compute this from
58
+ /// the assembly version (`AssemblyVersion.Major*10000 + Minor`,
59
+ /// `APIAccess.cs:81`). The exact integer isn't load-bearing — the server
60
+ /// supports a wide compat window — so we pin to a stable date so a future
61
+ /// schema rev doesn't change response shapes underneath us.
62
+ pub const LAZER_API_VERSION: &str = "20240130";
63
+
64
+ const OSU_BASE: &str = "https://osu.ppy.sh";
65
+
66
+ /// Strategy for authenticating against the osu! API.
67
+ #[derive(Clone, Debug)]
68
+ pub enum OsuAuthMode {
69
+ /// Standard OAuth app credentials. `public` scope. Cannot download.
70
+ ClientCredentials {
71
+ client_id: String,
72
+ client_secret: String,
73
+ },
74
+ /// Lazer impersonation. Uses the well-known lazer client_id/secret with
75
+ /// `grant_type=password` to obtain a user-scoped token that's allowed to
76
+ /// hit `/api/v2/beatmapsets/{id}/download`.
77
+ LazerPassword { username: String, password: String },
78
+ }
79
+
80
+ impl OsuAuthMode {
81
+ pub fn label(&self) -> &'static str {
82
+ match self {
83
+ OsuAuthMode::ClientCredentials { .. } => "client_credentials",
84
+ OsuAuthMode::LazerPassword { .. } => "lazer_password",
85
+ }
86
+ }
87
+
88
+ fn is_lazer(&self) -> bool {
89
+ matches!(self, OsuAuthMode::LazerPassword { .. })
90
+ }
91
+ }
92
+
93
+ /// Persisted token state. Same shape lazer caches in
94
+ /// `osu.Game/Online/API/OAuthToken.cs` minus the unused `token_type`.
95
+ #[derive(Clone, Debug, Serialize, Deserialize)]
96
+ struct StoredToken {
97
+ access_token: String,
98
+ #[serde(default)]
99
+ refresh_token: Option<String>,
100
+ /// Unix seconds since epoch — the absolute moment the access token
101
+ /// expires. Computed at issuance from `expires_in`.
102
+ expires_at: i64,
103
+ /// Tracks which auth mode minted this token, so we don't accidentally
104
+ /// reuse a client_credentials token under lazer mode (it'd 403 on
105
+ /// downloads despite looking valid by expiry).
106
+ #[serde(default)]
107
+ mode_label: Option<String>,
108
+ /// True after `/api/v2/session/verify` succeeded (or wasn't needed).
109
+ /// A token whose session isn't verified can pass `/me` checks but
110
+ /// will still be denied at sensitive endpoints — track this so we
111
+ /// don't skip the verify step on a restored-from-disk token.
112
+ #[serde(default = "default_true")]
113
+ session_verified: bool,
114
+ }
115
+
116
+ fn default_true() -> bool {
117
+ true
118
+ }
119
+
120
+ impl StoredToken {
121
+ /// Same 30-second margin lazer uses (`OAuthToken.cs:28`).
122
+ fn is_valid(&self) -> bool {
123
+ let now = unix_now();
124
+ !self.access_token.is_empty() && self.expires_at - now > 30
125
+ }
126
+ }
127
+
128
+ #[derive(Debug, Deserialize)]
129
+ struct TokenResponse {
130
+ access_token: String,
131
+ expires_in: u64,
132
+ /// Only present on password / refresh grants. client_credentials
133
+ /// tokens never carry one — the `Default` lets us deserialize either.
134
+ #[serde(default)]
135
+ refresh_token: Option<String>,
136
+ }
137
+
138
+ #[derive(Debug, Deserialize)]
139
+ struct ApiMeMinimal {
140
+ /// `null` (or absent) when the session is fully verified. Otherwise
141
+ /// `"totp"` or `"mail"` per `APIMe.cs:12`.
142
+ #[serde(default)]
143
+ session_verification_method: Option<String>,
144
+ }
145
+
146
+ /// Pluggable adapter for reading the 2FA code. Default behaviour (and what
147
+ /// `OsuAuth::new` installs) is an interactive stdin prompt; tests inject a
148
+ /// canned reader so they don't block on real I/O.
149
+ pub trait VerificationReader: Send + Sync {
150
+ fn read_code(&self, method_label: &str) -> Result<String>;
151
+ }
152
+
153
+ /// Stdin-based reader. Prints to stderr (so the dashboard's stdout stays
154
+ /// clean for piping) and reads one line.
155
+ pub struct StdinVerificationReader;
156
+
157
+ impl VerificationReader for StdinVerificationReader {
158
+ fn read_code(&self, method_label: &str) -> Result<String> {
159
+ use std::io::{BufRead, Write};
160
+ eprintln!();
161
+ eprintln!("osu! session verification required.");
162
+ eprintln!("Check your {method_label} for a 6-digit code from osu! and enter it below.");
163
+ eprint!("Code: ");
164
+ std::io::stderr().flush().ok();
165
+ let mut buf = String::new();
166
+ std::io::stdin()
167
+ .lock()
168
+ .read_line(&mut buf)
169
+ .context("reading verification code from stdin")?;
170
+ let trimmed = buf.trim();
171
+ if trimmed.is_empty() {
172
+ bail!("no verification code entered");
173
+ }
174
+ Ok(trimmed.to_string())
175
+ }
176
+ }
177
+
178
+ pub struct OsuAuth {
179
+ client: Client,
180
+ mode: OsuAuthMode,
181
+ token_file: Option<PathBuf>,
182
+ /// Serializes token mutations so two concurrent `current_token` callers
183
+ /// don't both hit `/oauth/token` (matches lazer's
184
+ /// `access_token_retrieval_lock` in `OAuth.cs:121`).
185
+ token: Mutex<Option<StoredToken>>,
186
+ verification: Box<dyn VerificationReader>,
187
+ /// Override base URL so tests can point at a wiremock server.
188
+ base_url: String,
189
+ api_v2_url: String,
190
+ }
191
+
192
+ impl OsuAuth {
193
+ /// Build an auth handle. `token_file` (if `Some`) is used both to
194
+ /// restore a previous login on startup and to persist new tokens as
195
+ /// they're minted. Pass `None` for a memory-only client (tests, or
196
+ /// short-lived runs where you don't want a sidecar file on disk).
197
+ pub fn new(mode: OsuAuthMode, token_file: Option<PathBuf>) -> Result<Arc<Self>> {
198
+ Self::new_with(
199
+ mode,
200
+ token_file,
201
+ Box::new(StdinVerificationReader),
202
+ OSU_BASE.to_string(),
203
+ )
204
+ }
205
+
206
+ /// Test-friendly constructor: lets the caller swap the verification
207
+ /// reader and point the base URL at a mock server.
208
+ pub fn new_with(
209
+ mode: OsuAuthMode,
210
+ token_file: Option<PathBuf>,
211
+ verification: Box<dyn VerificationReader>,
212
+ base_url: String,
213
+ ) -> Result<Arc<Self>> {
214
+ let user_agent = if mode.is_lazer() {
215
+ LAZER_USER_AGENT.to_string()
216
+ } else {
217
+ format!(
218
+ "osu_fetcher/{} (+https://github.com/lekdan/osu-everything)",
219
+ env!("CARGO_PKG_VERSION")
220
+ )
221
+ };
222
+ let client = Client::builder()
223
+ .user_agent(user_agent)
224
+ .timeout(Duration::from_secs(60))
225
+ .gzip(true)
226
+ .brotli(true)
227
+ .build()
228
+ .context("building reqwest client")?;
229
+ let restored = match &token_file {
230
+ Some(p) => Self::read_token_file(p, &mode),
231
+ None => None,
232
+ };
233
+ let api_v2_url = format!("{}/api/v2", base_url.trim_end_matches('/'));
234
+ Ok(Arc::new(Self {
235
+ client,
236
+ mode,
237
+ token_file,
238
+ token: Mutex::new(restored),
239
+ verification,
240
+ base_url,
241
+ api_v2_url,
242
+ }))
243
+ }
244
+
245
+ pub fn client(&self) -> &Client {
246
+ &self.client
247
+ }
248
+
249
+ pub fn user_agent(&self) -> &'static str {
250
+ if self.mode.is_lazer() {
251
+ LAZER_USER_AGENT
252
+ } else {
253
+ "osu_fetcher"
254
+ }
255
+ }
256
+
257
+ pub fn api_version(&self) -> &'static str {
258
+ LAZER_API_VERSION
259
+ }
260
+
261
+ pub fn mode_label(&self) -> &'static str {
262
+ self.mode.label()
263
+ }
264
+
265
+ /// Yield a usable bearer token. Steps:
266
+ ///
267
+ /// 1. If the cached token is non-expired (≥30s headroom), return it.
268
+ /// 2. Else if it has a refresh token, swap it in (one round-trip).
269
+ /// 3. Else (or on refresh failure), do a full re-authentication —
270
+ /// which for lazer mode includes the `/api/v2/me` probe and an
271
+ /// interactive 2FA prompt if the account requires it.
272
+ ///
273
+ /// Mutex-serialised so concurrent callers don't trigger redundant
274
+ /// `/oauth/token` POSTs.
275
+ pub async fn current_token(&self) -> Result<String> {
276
+ let mut guard = self.token.lock().await;
277
+ if let Some(t) = guard.as_ref() {
278
+ if t.is_valid() && t.session_verified {
279
+ return Ok(t.access_token.clone());
280
+ }
281
+ if t.is_valid() && !t.session_verified {
282
+ // Token works for /me probes but downloads will 401/403
283
+ // until verify is completed. Run verification now.
284
+ let token = t.clone();
285
+ drop(guard);
286
+ let verified = self.run_session_verification(token).await?;
287
+ let mut guard = self.token.lock().await;
288
+ *guard = Some(verified.clone());
289
+ self.persist(&verified).await;
290
+ return Ok(verified.access_token);
291
+ }
292
+ if let Some(rt) = t.refresh_token.clone() {
293
+ match self.refresh(&rt).await {
294
+ Ok(mut refreshed) => {
295
+ // Carry verification state forward — refreshing
296
+ // doesn't reset the session (lazer treats refresh
297
+ // and password grants identically post-verify).
298
+ refreshed.session_verified = t.session_verified;
299
+ *guard = Some(refreshed.clone());
300
+ self.persist(&refreshed).await;
301
+ return Ok(refreshed.access_token);
302
+ }
303
+ Err(e) => {
304
+ warn!(error = %e, "token refresh failed; re-authenticating");
305
+ }
306
+ }
307
+ }
308
+ }
309
+ let fresh = self.full_authenticate().await?;
310
+ *guard = Some(fresh.clone());
311
+ self.persist(&fresh).await;
312
+ Ok(fresh.access_token)
313
+ }
314
+
315
+ /// Drop the cached token. Use after a 401: the next `current_token`
316
+ /// call will re-mint. The on-disk file is left alone — its
317
+ /// refresh_token may still be salvageable on the next attempt.
318
+ pub async fn invalidate(&self) {
319
+ *self.token.lock().await = None;
320
+ }
321
+
322
+ async fn full_authenticate(&self) -> Result<StoredToken> {
323
+ match &self.mode {
324
+ OsuAuthMode::ClientCredentials {
325
+ client_id,
326
+ client_secret,
327
+ } => {
328
+ let token = self
329
+ .token_request(&[
330
+ ("grant_type", "client_credentials"),
331
+ ("client_id", client_id),
332
+ ("client_secret", client_secret),
333
+ ("scope", "public"),
334
+ ])
335
+ .await?;
336
+ // No verification needed for app-scoped tokens.
337
+ Ok(StoredToken {
338
+ session_verified: true,
339
+ mode_label: Some("client_credentials".into()),
340
+ ..token
341
+ })
342
+ }
343
+ OsuAuthMode::LazerPassword { username, password } => {
344
+ info!(
345
+ user_agent = LAZER_USER_AGENT,
346
+ "performing lazer-impersonation password grant"
347
+ );
348
+ let raw = self
349
+ .token_request(&[
350
+ ("grant_type", "password"),
351
+ ("client_id", LAZER_CLIENT_ID),
352
+ ("client_secret", LAZER_CLIENT_SECRET),
353
+ ("scope", LAZER_SCOPE),
354
+ ("username", username),
355
+ ("password", password),
356
+ ])
357
+ .await
358
+ .context("lazer password grant")?;
359
+ let raw = StoredToken {
360
+ mode_label: Some("lazer_password".into()),
361
+ session_verified: false,
362
+ ..raw
363
+ };
364
+ self.run_session_verification(raw).await
365
+ }
366
+ }
367
+ }
368
+
369
+ async fn refresh(&self, refresh_token: &str) -> Result<StoredToken> {
370
+ let (id, secret, scope, label) = match &self.mode {
371
+ OsuAuthMode::LazerPassword { .. } => (
372
+ LAZER_CLIENT_ID,
373
+ LAZER_CLIENT_SECRET,
374
+ LAZER_SCOPE,
375
+ "lazer_password",
376
+ ),
377
+ OsuAuthMode::ClientCredentials {
378
+ client_id,
379
+ client_secret,
380
+ } => (
381
+ client_id.as_str(),
382
+ client_secret.as_str(),
383
+ "public",
384
+ "client_credentials",
385
+ ),
386
+ };
387
+ debug!(mode = label, "refreshing access token");
388
+ let token = self
389
+ .token_request(&[
390
+ ("grant_type", "refresh_token"),
391
+ ("client_id", id),
392
+ ("client_secret", secret),
393
+ ("scope", scope),
394
+ ("refresh_token", refresh_token),
395
+ ])
396
+ .await?;
397
+ Ok(StoredToken {
398
+ mode_label: Some(label.into()),
399
+ session_verified: true,
400
+ ..token
401
+ })
402
+ }
403
+
404
+ async fn token_request(&self, form: &[(&str, &str)]) -> Result<StoredToken> {
405
+ let issued_at_unix = unix_now();
406
+ let resp = self
407
+ .client
408
+ .post(format!(
409
+ "{}/oauth/token",
410
+ self.base_url.trim_end_matches('/')
411
+ ))
412
+ .form(form)
413
+ .send()
414
+ .await
415
+ .context("POST /oauth/token")?;
416
+ let status = resp.status();
417
+ if !status.is_success() {
418
+ let body = resp.text().await.unwrap_or_default();
419
+ let snippet: String = body.chars().take(400).collect();
420
+ bail!("/oauth/token returned {status}: {snippet}");
421
+ }
422
+ let tr: TokenResponse = resp.json().await.context("decoding /oauth/token JSON")?;
423
+ Ok(StoredToken {
424
+ access_token: tr.access_token,
425
+ refresh_token: tr.refresh_token,
426
+ expires_at: issued_at_unix + tr.expires_in as i64,
427
+ mode_label: None,
428
+ session_verified: false,
429
+ })
430
+ }
431
+
432
+ /// Probe `/api/v2/me`. If the response carries
433
+ /// `session_verification_method`, prompt the user and POST
434
+ /// `/api/v2/session/verify` with the code. On success the *same*
435
+ /// access token becomes usable at sensitive endpoints — no new token
436
+ /// is issued by the server.
437
+ async fn run_session_verification(&self, mut token: StoredToken) -> Result<StoredToken> {
438
+ let me = self.fetch_me(&token.access_token).await?;
439
+ let Some(method) = me.session_verification_method.as_deref() else {
440
+ token.session_verified = true;
441
+ return Ok(token);
442
+ };
443
+ let label = match method {
444
+ "totp" => "TOTP authenticator app",
445
+ "mail" => "email inbox",
446
+ other => other,
447
+ };
448
+ info!(method = method, "osu! session verification required");
449
+ let code = self.verification.read_code(label)?;
450
+ let resp = self
451
+ .client
452
+ .post(format!("{}/session/verify", self.api_v2_url))
453
+ .header(AUTHORIZATION, format!("Bearer {}", token.access_token))
454
+ .header("x-api-version", LAZER_API_VERSION)
455
+ .form(&[("verification_key", code.as_str())])
456
+ .send()
457
+ .await
458
+ .context("POST /api/v2/session/verify")?;
459
+ if resp.status().is_success() {
460
+ info!("osu! session verified");
461
+ token.session_verified = true;
462
+ return Ok(token);
463
+ }
464
+ let status = resp.status();
465
+ let body = resp.text().await.unwrap_or_default();
466
+ let snippet: String = body.chars().take(300).collect();
467
+ bail!("session verification failed: {status} {snippet}");
468
+ }
469
+
470
+ async fn fetch_me(&self, token: &str) -> Result<ApiMeMinimal> {
471
+ let resp = self
472
+ .client
473
+ .get(format!("{}/me", self.api_v2_url))
474
+ .header(AUTHORIZATION, format!("Bearer {token}"))
475
+ .header("x-api-version", LAZER_API_VERSION)
476
+ .send()
477
+ .await
478
+ .context("GET /api/v2/me")?;
479
+ if !resp.status().is_success() {
480
+ let status = resp.status();
481
+ let body = resp.text().await.unwrap_or_default();
482
+ let snippet: String = body.chars().take(300).collect();
483
+ bail!("/api/v2/me returned {status}: {snippet}");
484
+ }
485
+ resp.json().await.context("decoding /api/v2/me JSON")
486
+ }
487
+
488
+ async fn persist(&self, token: &StoredToken) {
489
+ let Some(path) = self.token_file.as_ref() else {
490
+ return;
491
+ };
492
+ let payload = match serde_json::to_vec_pretty(token) {
493
+ Ok(b) => b,
494
+ Err(e) => {
495
+ warn!(error = %e, "could not serialize token; skipping persistence");
496
+ return;
497
+ }
498
+ };
499
+ if let Err(e) = write_secure(path, &payload).await {
500
+ warn!(
501
+ error = %e,
502
+ path = %path.display(),
503
+ "could not persist osu! token to disk; in-memory token still works for this run"
504
+ );
505
+ }
506
+ }
507
+
508
+ fn read_token_file(path: &Path, mode: &OsuAuthMode) -> Option<StoredToken> {
509
+ if !path.exists() {
510
+ return None;
511
+ }
512
+ let raw = match std::fs::read(path) {
513
+ Ok(b) => b,
514
+ Err(e) => {
515
+ warn!(error = %e, path = %path.display(), "could not read token file");
516
+ return None;
517
+ }
518
+ };
519
+ let token: StoredToken = match serde_json::from_slice(&raw) {
520
+ Ok(t) => t,
521
+ Err(e) => {
522
+ warn!(error = %e, "token file unparseable; ignoring and re-authenticating");
523
+ return None;
524
+ }
525
+ };
526
+ // Refuse to reuse a token minted under a different auth mode —
527
+ // a client_credentials token will fail downloads regardless of
528
+ // its expiry, and a lazer token may carry scopes we don't want
529
+ // to use under client_credentials mode.
530
+ let expected = mode.label();
531
+ let actual = token.mode_label.as_deref().unwrap_or("client_credentials");
532
+ if actual != expected {
533
+ info!(
534
+ actual,
535
+ expected, "ignoring cached token from different auth mode"
536
+ );
537
+ return None;
538
+ }
539
+ Some(token)
540
+ }
541
+ }
542
+
543
+ #[cfg(unix)]
544
+ async fn write_secure(path: &Path, data: &[u8]) -> Result<()> {
545
+ use std::io::Write;
546
+ use std::os::unix::fs::OpenOptionsExt;
547
+ if let Some(parent) = path.parent() {
548
+ if !parent.as_os_str().is_empty() {
549
+ tokio::fs::create_dir_all(parent).await.ok();
550
+ }
551
+ }
552
+ let mut opts = std::fs::OpenOptions::new();
553
+ opts.write(true).create(true).truncate(true).mode(0o600);
554
+ let mut f = opts
555
+ .open(path)
556
+ .with_context(|| format!("opening token file {} for writing", path.display()))?;
557
+ f.write_all(data)?;
558
+ Ok(())
559
+ }
560
+
561
+ #[cfg(not(unix))]
562
+ async fn write_secure(path: &Path, data: &[u8]) -> Result<()> {
563
+ if let Some(parent) = path.parent() {
564
+ if !parent.as_os_str().is_empty() {
565
+ tokio::fs::create_dir_all(parent).await.ok();
566
+ }
567
+ }
568
+ tokio::fs::write(path, data).await?;
569
+ Ok(())
570
+ }
571
+
572
+ fn unix_now() -> i64 {
573
+ std::time::SystemTime::now()
574
+ .duration_since(std::time::UNIX_EPOCH)
575
+ .map(|d| d.as_secs() as i64)
576
+ .unwrap_or(0)
577
+ }
578
+
579
+ #[cfg(test)]
580
+ mod tests {
581
+ use super::*;
582
+ use std::sync::atomic::{AtomicUsize, Ordering};
583
+ use std::sync::Arc;
584
+ use wiremock::matchers::{body_string_contains, header, method, path};
585
+ use wiremock::{Mock, MockServer, ResponseTemplate};
586
+
587
+ struct CannedReader(String);
588
+ impl VerificationReader for CannedReader {
589
+ fn read_code(&self, _: &str) -> Result<String> {
590
+ Ok(self.0.clone())
591
+ }
592
+ }
593
+
594
+ struct CountingReader {
595
+ code: String,
596
+ calls: Arc<AtomicUsize>,
597
+ }
598
+ impl VerificationReader for CountingReader {
599
+ fn read_code(&self, _: &str) -> Result<String> {
600
+ self.calls.fetch_add(1, Ordering::Relaxed);
601
+ Ok(self.code.clone())
602
+ }
603
+ }
604
+
605
+ fn lazer_mode() -> OsuAuthMode {
606
+ OsuAuthMode::LazerPassword {
607
+ username: "lekdan".into(),
608
+ password: "hunter2".into(),
609
+ }
610
+ }
611
+
612
+ #[tokio::test]
613
+ async fn lazer_password_grant_sends_lazer_creds_and_user_login() {
614
+ // Verify the form body contains the literal hardcoded creds + user
615
+ // login + scope=*. We check by `body_string_contains` because the
616
+ // form encoding order isn't guaranteed; presence is what matters.
617
+ let server = MockServer::start().await;
618
+ Mock::given(method("POST"))
619
+ .and(path("/oauth/token"))
620
+ .and(body_string_contains("grant_type=password"))
621
+ .and(body_string_contains("client_id=5"))
622
+ .and(body_string_contains(
623
+ "client_secret=FGc9GAtyHzeQDshWP5Ah7dega8hJACAJpQtw6OXk",
624
+ ))
625
+ .and(body_string_contains("scope=*")) // WHATWG form-urlencoded leaves `*` literal
626
+ .and(body_string_contains("username=lekdan"))
627
+ .and(body_string_contains("password=hunter2"))
628
+ .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
629
+ "access_token": "tok-abc",
630
+ "refresh_token": "ref-abc",
631
+ "expires_in": 86400,
632
+ })))
633
+ .expect(1)
634
+ .mount(&server)
635
+ .await;
636
+ // /api/v2/me with no verification required.
637
+ Mock::given(method("GET"))
638
+ .and(path("/api/v2/me"))
639
+ .and(header(AUTHORIZATION, "Bearer tok-abc"))
640
+ .and(header("x-api-version", LAZER_API_VERSION))
641
+ .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
642
+ "session_verification_method": null,
643
+ })))
644
+ .expect(1)
645
+ .mount(&server)
646
+ .await;
647
+
648
+ let auth = OsuAuth::new_with(
649
+ lazer_mode(),
650
+ None,
651
+ Box::new(CannedReader("000000".into())),
652
+ server.uri(),
653
+ )
654
+ .unwrap();
655
+ let token = auth.current_token().await.unwrap();
656
+ assert_eq!(token, "tok-abc");
657
+ assert_eq!(auth.user_agent(), LAZER_USER_AGENT);
658
+ }
659
+
660
+ #[tokio::test]
661
+ async fn lazer_password_grant_runs_session_verify_when_required() {
662
+ let server = MockServer::start().await;
663
+ Mock::given(method("POST"))
664
+ .and(path("/oauth/token"))
665
+ .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
666
+ "access_token": "tok-needs-verify",
667
+ "refresh_token": "ref-x",
668
+ "expires_in": 3600,
669
+ })))
670
+ .expect(1)
671
+ .mount(&server)
672
+ .await;
673
+ Mock::given(method("GET"))
674
+ .and(path("/api/v2/me"))
675
+ .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
676
+ "session_verification_method": "mail",
677
+ })))
678
+ .expect(1)
679
+ .mount(&server)
680
+ .await;
681
+ // The verify endpoint must receive the exact form param
682
+ // verification_key=<code>.
683
+ Mock::given(method("POST"))
684
+ .and(path("/api/v2/session/verify"))
685
+ .and(body_string_contains("verification_key=123456"))
686
+ .and(header(AUTHORIZATION, "Bearer tok-needs-verify"))
687
+ .respond_with(ResponseTemplate::new(200))
688
+ .expect(1)
689
+ .mount(&server)
690
+ .await;
691
+
692
+ let calls = Arc::new(AtomicUsize::new(0));
693
+ let reader = CountingReader {
694
+ code: "123456".into(),
695
+ calls: calls.clone(),
696
+ };
697
+ let auth = OsuAuth::new_with(lazer_mode(), None, Box::new(reader), server.uri()).unwrap();
698
+ let token = auth.current_token().await.unwrap();
699
+ assert_eq!(token, "tok-needs-verify");
700
+ assert_eq!(calls.load(Ordering::Relaxed), 1);
701
+ }
702
+
703
+ #[tokio::test]
704
+ async fn current_token_short_circuits_when_cached_valid() {
705
+ // Mount only ONE expected /oauth/token hit; calling current_token
706
+ // a second time must reuse the cached value, not refetch.
707
+ let server = MockServer::start().await;
708
+ Mock::given(method("POST"))
709
+ .and(path("/oauth/token"))
710
+ .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
711
+ "access_token": "tok-once",
712
+ "refresh_token": "ref-once",
713
+ "expires_in": 86400,
714
+ })))
715
+ .expect(1)
716
+ .mount(&server)
717
+ .await;
718
+ Mock::given(method("GET"))
719
+ .and(path("/api/v2/me"))
720
+ .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
721
+ "session_verification_method": null,
722
+ })))
723
+ .expect(1)
724
+ .mount(&server)
725
+ .await;
726
+
727
+ let auth = OsuAuth::new_with(
728
+ lazer_mode(),
729
+ None,
730
+ Box::new(CannedReader("0".into())),
731
+ server.uri(),
732
+ )
733
+ .unwrap();
734
+ assert_eq!(auth.current_token().await.unwrap(), "tok-once");
735
+ assert_eq!(auth.current_token().await.unwrap(), "tok-once");
736
+ }
737
+
738
+ #[tokio::test]
739
+ async fn invalidate_forces_refetch_on_next_call() {
740
+ let server = MockServer::start().await;
741
+ Mock::given(method("POST"))
742
+ .and(path("/oauth/token"))
743
+ .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
744
+ "access_token": "tok-A",
745
+ "refresh_token": "ref-A",
746
+ "expires_in": 86400,
747
+ })))
748
+ .up_to_n_times(1)
749
+ .mount(&server)
750
+ .await;
751
+ Mock::given(method("POST"))
752
+ .and(path("/oauth/token"))
753
+ .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
754
+ "access_token": "tok-B",
755
+ "refresh_token": "ref-B",
756
+ "expires_in": 86400,
757
+ })))
758
+ .mount(&server)
759
+ .await;
760
+ Mock::given(method("GET"))
761
+ .and(path("/api/v2/me"))
762
+ .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
763
+ "session_verification_method": null,
764
+ })))
765
+ .mount(&server)
766
+ .await;
767
+ let auth = OsuAuth::new_with(
768
+ lazer_mode(),
769
+ None,
770
+ Box::new(CannedReader("0".into())),
771
+ server.uri(),
772
+ )
773
+ .unwrap();
774
+ assert_eq!(auth.current_token().await.unwrap(), "tok-A");
775
+ auth.invalidate().await;
776
+ assert_eq!(auth.current_token().await.unwrap(), "tok-B");
777
+ }
778
+
779
+ #[tokio::test]
780
+ async fn client_credentials_mode_uses_app_scope_and_no_user_creds() {
781
+ let server = MockServer::start().await;
782
+ Mock::given(method("POST"))
783
+ .and(path("/oauth/token"))
784
+ .and(body_string_contains("grant_type=client_credentials"))
785
+ .and(body_string_contains("client_id=12345"))
786
+ .and(body_string_contains("scope=public"))
787
+ .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
788
+ "access_token": "tok-cc",
789
+ "expires_in": 86400,
790
+ })))
791
+ .expect(1)
792
+ .mount(&server)
793
+ .await;
794
+ let auth = OsuAuth::new_with(
795
+ OsuAuthMode::ClientCredentials {
796
+ client_id: "12345".into(),
797
+ client_secret: "ccsecret".into(),
798
+ },
799
+ None,
800
+ Box::new(CannedReader("0".into())),
801
+ server.uri(),
802
+ )
803
+ .unwrap();
804
+ assert_eq!(auth.current_token().await.unwrap(), "tok-cc");
805
+ // client_credentials never triggers /api/v2/me.
806
+ assert!(auth.user_agent().starts_with("osu_fetcher"));
807
+ }
808
+
809
+ #[tokio::test]
810
+ async fn token_persists_to_disk_and_reloads() {
811
+ let dir = tempfile::tempdir().unwrap();
812
+ let token_path = dir.path().join("osu_token.json");
813
+ let server = MockServer::start().await;
814
+ Mock::given(method("POST"))
815
+ .and(path("/oauth/token"))
816
+ .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
817
+ "access_token": "tok-persist",
818
+ "refresh_token": "ref-persist",
819
+ "expires_in": 86400,
820
+ })))
821
+ .expect(1)
822
+ .mount(&server)
823
+ .await;
824
+ Mock::given(method("GET"))
825
+ .and(path("/api/v2/me"))
826
+ .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
827
+ "session_verification_method": null,
828
+ })))
829
+ .expect(1)
830
+ .mount(&server)
831
+ .await;
832
+
833
+ {
834
+ let auth = OsuAuth::new_with(
835
+ lazer_mode(),
836
+ Some(token_path.clone()),
837
+ Box::new(CannedReader("0".into())),
838
+ server.uri(),
839
+ )
840
+ .unwrap();
841
+ assert_eq!(auth.current_token().await.unwrap(), "tok-persist");
842
+ }
843
+ // Second instance must read the file and not hit the wire.
844
+ let auth = OsuAuth::new_with(
845
+ lazer_mode(),
846
+ Some(token_path.clone()),
847
+ Box::new(CannedReader("0".into())),
848
+ server.uri(),
849
+ )
850
+ .unwrap();
851
+ assert_eq!(auth.current_token().await.unwrap(), "tok-persist");
852
+ }
853
+
854
+ #[tokio::test]
855
+ async fn refresh_grant_carries_session_verified_forward() {
856
+ let server = MockServer::start().await;
857
+ // Seed an expired-but-refreshable token on disk so the cached path
858
+ // fires the refresh branch instead of the full re-auth branch.
859
+ let dir = tempfile::tempdir().unwrap();
860
+ let token_path = dir.path().join("osu_token.json");
861
+ let stale = StoredToken {
862
+ access_token: "stale".into(),
863
+ refresh_token: Some("ref-keep".into()),
864
+ expires_at: 0,
865
+ mode_label: Some("lazer_password".into()),
866
+ session_verified: true,
867
+ };
868
+ std::fs::write(&token_path, serde_json::to_vec(&stale).unwrap()).unwrap();
869
+
870
+ Mock::given(method("POST"))
871
+ .and(path("/oauth/token"))
872
+ .and(body_string_contains("grant_type=refresh_token"))
873
+ .and(body_string_contains("refresh_token=ref-keep"))
874
+ .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
875
+ "access_token": "tok-refreshed",
876
+ "refresh_token": "ref-new",
877
+ "expires_in": 86400,
878
+ })))
879
+ .expect(1)
880
+ .mount(&server)
881
+ .await;
882
+ // No /api/v2/me on a refresh flow — verification carries forward
883
+ // from the seeded token.
884
+
885
+ let auth = OsuAuth::new_with(
886
+ lazer_mode(),
887
+ Some(token_path.clone()),
888
+ Box::new(CannedReader("0".into())),
889
+ server.uri(),
890
+ )
891
+ .unwrap();
892
+ assert_eq!(auth.current_token().await.unwrap(), "tok-refreshed");
893
+ }
894
+ }
crates/osu_fetcher/src/config.rs ADDED
@@ -0,0 +1,231 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //! Config-file loading.
2
+ //!
3
+ //! Defaults to `<repo_root>/osu_fetcher.toml`. The file is **not** committed
4
+ //! (`.gitignore` excludes it); a `osu_fetcher.toml.example` template is
5
+ //! committed so a fresh clone can be configured by `cp` + edit.
6
+ //!
7
+ //! Resolution order for each credential:
8
+ //!
9
+ //! 1. Environment variable, if set and non-empty (lets CI/CD override
10
+ //! without touching the file).
11
+ //! 2. Value from the loaded config file.
12
+ //! 3. `None` — the caller decides whether the missing value is fatal
13
+ //! (osu! API requires both id+secret; beatconnect can be skipped).
14
+ //!
15
+ //! The TOML schema is conservative: every section is optional, every key is
16
+ //! optional, and unknown keys are accepted (we set
17
+ //! `serde(default)` everywhere so adding fields later doesn't break older
18
+ //! configs).
19
+
20
+ use std::path::{Path, PathBuf};
21
+
22
+ use anyhow::{Context, Result};
23
+ use serde::Deserialize;
24
+
25
+ /// Filename relative to the working directory (or `--config <path>`).
26
+ pub const DEFAULT_CONFIG_FILENAME: &str = "osu_fetcher.toml";
27
+
28
+ #[derive(Clone, Debug, Default, Deserialize)]
29
+ #[serde(deny_unknown_fields)]
30
+ pub struct Config {
31
+ #[serde(default)]
32
+ pub osu_api: OsuApiConfig,
33
+ #[serde(default)]
34
+ pub mirrors: MirrorsConfig,
35
+ }
36
+
37
+ #[derive(Clone, Debug, Default, Deserialize)]
38
+ #[serde(deny_unknown_fields)]
39
+ pub struct OsuApiConfig {
40
+ /// Numeric client_id from <https://osu.ppy.sh/home/account/edit#oauth>.
41
+ /// Stored as a string in the file (TOML doesn't care; the API accepts
42
+ /// either form). Used only by the legacy client_credentials path —
43
+ /// when `username` + `password` are also set the lazer-impersonation
44
+ /// flow takes precedence and these are ignored.
45
+ #[serde(default)]
46
+ pub client_id: Option<String>,
47
+
48
+ #[serde(default)]
49
+ pub client_secret: Option<String>,
50
+
51
+ /// osu! account username for the lazer-impersonation password grant.
52
+ /// Pair with `password` to upgrade to user-scoped tokens that work for
53
+ /// the `/api/v2/beatmapsets/{id}/download` endpoint. Storing your
54
+ /// password in TOML is sensitive — prefer the `OSU_USERNAME` /
55
+ /// `OSU_PASSWORD` env vars.
56
+ #[serde(default)]
57
+ pub username: Option<String>,
58
+
59
+ #[serde(default)]
60
+ pub password: Option<String>,
61
+ }
62
+
63
+ #[derive(Clone, Debug, Default, Deserialize)]
64
+ #[serde(deny_unknown_fields)]
65
+ pub struct MirrorsConfig {
66
+ #[serde(default)]
67
+ pub beatconnect: BeatconnectConfig,
68
+ }
69
+
70
+ #[derive(Clone, Debug, Default, Deserialize)]
71
+ #[serde(deny_unknown_fields)]
72
+ pub struct BeatconnectConfig {
73
+ /// API token from <https://beatconnect.io/api/docs/>. Optional — without
74
+ /// it, beatconnect is skipped from the mirror pool.
75
+ #[serde(default)]
76
+ pub api_key: Option<String>,
77
+ }
78
+
79
+ impl Config {
80
+ /// Load from `path` if it exists; otherwise return an empty config.
81
+ /// Missing-file is **not** an error so the binary still works in CI/CD
82
+ /// where credentials live in env vars only.
83
+ pub fn load_or_empty(path: &Path) -> Result<Self> {
84
+ if !path.exists() {
85
+ return Ok(Self::default());
86
+ }
87
+ let raw = std::fs::read_to_string(path)
88
+ .with_context(|| format!("reading config file {}", path.display()))?;
89
+ let cfg: Self = toml::from_str(&raw)
90
+ .with_context(|| format!("parsing config file {}", path.display()))?;
91
+ Ok(cfg)
92
+ }
93
+
94
+ /// Resolve the OAuth credentials by combining env vars (winning) with
95
+ /// values from this config file (fallback). Callers decide which auth
96
+ /// mode applies (lazer password grant vs client_credentials) based on
97
+ /// which fields came back populated.
98
+ pub fn osu_credentials(&self) -> ResolvedOsuCreds {
99
+ ResolvedOsuCreds {
100
+ client_id: env_then_cfg("OSU_CLIENT_ID", self.osu_api.client_id.as_deref()),
101
+ client_secret: env_then_cfg("OSU_CLIENT_SECRET", self.osu_api.client_secret.as_deref()),
102
+ username: env_then_cfg("OSU_USERNAME", self.osu_api.username.as_deref()),
103
+ password: env_then_cfg("OSU_PASSWORD", self.osu_api.password.as_deref()),
104
+ }
105
+ }
106
+
107
+ pub fn beatconnect_api_key(&self) -> Option<String> {
108
+ env_then_cfg(
109
+ "BEATCONNECT_API_KEY",
110
+ self.mirrors.beatconnect.api_key.as_deref(),
111
+ )
112
+ }
113
+ }
114
+
115
+ /// Resolved credentials. Each field is `Some` if either the env var or the
116
+ /// config file supplied a non-empty value; `None` otherwise. The caller
117
+ /// inspects this struct to pick an auth mode:
118
+ /// * `username` + `password` set → lazer password grant
119
+ /// * else `client_id` + `client_secret` set → client_credentials
120
+ /// * else → no osu! API access (osuapi mirror skipped, enumerate fails)
121
+ #[derive(Clone, Debug, Default)]
122
+ pub struct ResolvedOsuCreds {
123
+ pub client_id: Option<String>,
124
+ pub client_secret: Option<String>,
125
+ pub username: Option<String>,
126
+ pub password: Option<String>,
127
+ }
128
+
129
+ fn env_then_cfg(env_key: &str, cfg_value: Option<&str>) -> Option<String> {
130
+ match std::env::var(env_key) {
131
+ Ok(v) if !v.trim().is_empty() => Some(v),
132
+ _ => cfg_value
133
+ .map(|s| s.trim().to_string())
134
+ .filter(|s| !s.is_empty()),
135
+ }
136
+ }
137
+
138
+ /// Resolve the config-file location with these precedence rules:
139
+ /// * `--config <path>` if the user passed one (returns the path verbatim).
140
+ /// * Otherwise, the default name relative to `cwd_or_archive_dir` —
141
+ /// in practice the directory the user is running from.
142
+ pub fn resolve_config_path(explicit: Option<&Path>) -> PathBuf {
143
+ if let Some(p) = explicit {
144
+ return p.to_path_buf();
145
+ }
146
+ PathBuf::from(DEFAULT_CONFIG_FILENAME)
147
+ }
148
+
149
+ #[cfg(test)]
150
+ mod tests {
151
+ use super::*;
152
+ use std::io::Write;
153
+ use tempfile::NamedTempFile;
154
+
155
+ #[test]
156
+ fn load_or_empty_returns_default_when_file_missing() {
157
+ let p = std::path::Path::new("/definitely/not/here.toml");
158
+ let cfg = Config::load_or_empty(p).unwrap();
159
+ assert!(cfg.osu_api.client_id.is_none());
160
+ assert!(cfg.mirrors.beatconnect.api_key.is_none());
161
+ }
162
+
163
+ #[test]
164
+ fn full_config_round_trips() {
165
+ let mut tmp = NamedTempFile::new().unwrap();
166
+ writeln!(
167
+ tmp,
168
+ r#"
169
+ [osu_api]
170
+ client_id = "47060"
171
+ client_secret = "secret_value"
172
+
173
+ [mirrors.beatconnect]
174
+ api_key = "abcdef"
175
+ "#
176
+ )
177
+ .unwrap();
178
+ let cfg = Config::load_or_empty(tmp.path()).unwrap();
179
+ assert_eq!(cfg.osu_api.client_id.as_deref(), Some("47060"));
180
+ assert_eq!(cfg.osu_api.client_secret.as_deref(), Some("secret_value"));
181
+ assert_eq!(cfg.mirrors.beatconnect.api_key.as_deref(), Some("abcdef"));
182
+ }
183
+
184
+ #[test]
185
+ fn missing_section_does_not_fail() {
186
+ let mut tmp = NamedTempFile::new().unwrap();
187
+ writeln!(tmp, "[osu_api]\nclient_id = \"x\"").unwrap();
188
+ let cfg = Config::load_or_empty(tmp.path()).unwrap();
189
+ assert_eq!(cfg.osu_api.client_id.as_deref(), Some("x"));
190
+ assert!(cfg.mirrors.beatconnect.api_key.is_none());
191
+ }
192
+
193
+ #[test]
194
+ fn unknown_keys_are_rejected() {
195
+ let mut tmp = NamedTempFile::new().unwrap();
196
+ writeln!(tmp, "[osu_api]\nclient_id = \"x\"\nbogus = 1").unwrap();
197
+ let err = Config::load_or_empty(tmp.path()).expect_err("expected schema error");
198
+ // toml's "unknown field" message wording varies; just assert it
199
+ // surfaced as an error rather than silently dropping the field.
200
+ let msg = err.to_string();
201
+ assert!(
202
+ msg.contains("config file") || msg.contains("unknown") || msg.contains("bogus"),
203
+ "unexpected error: {msg}"
204
+ );
205
+ }
206
+
207
+ #[test]
208
+ fn env_var_wins_over_config() {
209
+ // Setting env vars in tests is per-process. Use a unique name so we
210
+ // don't trample the real OSU_CLIENT_ID. We test the helper directly
211
+ // because that's what `osu_credentials` calls underneath.
212
+ std::env::set_var("OSU_FETCHER_TEST_KEY_A", "from_env");
213
+ let resolved = env_then_cfg("OSU_FETCHER_TEST_KEY_A", Some("from_cfg"));
214
+ assert_eq!(resolved.as_deref(), Some("from_env"));
215
+ std::env::remove_var("OSU_FETCHER_TEST_KEY_A");
216
+ }
217
+
218
+ #[test]
219
+ fn empty_env_falls_back_to_config() {
220
+ std::env::set_var("OSU_FETCHER_TEST_KEY_B", " ");
221
+ let resolved = env_then_cfg("OSU_FETCHER_TEST_KEY_B", Some("from_cfg"));
222
+ assert_eq!(resolved.as_deref(), Some("from_cfg"));
223
+ std::env::remove_var("OSU_FETCHER_TEST_KEY_B");
224
+ }
225
+
226
+ #[test]
227
+ fn no_env_no_cfg_returns_none() {
228
+ std::env::remove_var("OSU_FETCHER_TEST_KEY_C");
229
+ assert!(env_then_cfg("OSU_FETCHER_TEST_KEY_C", None).is_none());
230
+ }
231
+ }
crates/osu_fetcher/src/discover/mod.rs ADDED
@@ -0,0 +1,813 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //! Cross-mirror discovery: find ranked / approved / loved / qualified
2
+ //! beatmapsets the official osu! API may have dropped but mirrors still know
3
+ //! about, then cross-verify by counting independent mirrors that agree.
4
+ //!
5
+ //! ## Why this exists
6
+ //!
7
+ //! `enumerate.rs` only walks `osu.ppy.sh/api/v2/beatmapsets/search`. A set that
8
+ //! was once ranked but later removed from the API (DMCA, deleted creator, etc.)
9
+ //! never appears, even though several mirrors still cache it. Mirrors are
10
+ //! *complementary forensic sources*: they remember sets that have rotated off
11
+ //! the upstream catalog.
12
+ //!
13
+ //! Our policy is "trust by quorum": a set absent from the official API is
14
+ //! promoted to `wanted` only when *N independent mirrors agree* on its
15
+ //! identity (status in our target set + at least one osu! standard
16
+ //! difficulty). The default N is 2 — enough that a single mirror's stale
17
+ //! cache or buggy parse doesn't pollute the catalog, low enough to actually
18
+ //! recover sets the public mirrors keep alive.
19
+ //!
20
+ //! ## Mirrors used
21
+ //!
22
+ //! Per the project's mirror docs (April 2026), the *discovery* surface is:
23
+ //!
24
+ //! | Mirror | Status filter | Paging | Notes |
25
+ //! |-------------|---------------|----------------------------|----------------------|
26
+ //! | nerinyan | text + numeric| cursor_string + page+limit | rich response |
27
+ //! | osu.direct | numeric | offset + amount | `last_checked` field |
28
+ //! | sayobot | unreliable | offset + limit | client-side filter |
29
+ //! | nekoha | none on list | per-set lookup only | verifier, not lister |
30
+ //! | osudl | n/a | HTML only | download-only here |
31
+ //! | nzbasic | n/a | none | download-only here |
32
+ //! | catboy | down | - | skipped |
33
+ //!
34
+ //! `download-only` mirrors stay in `crates::mirrors`; they're not part of the
35
+ //! discovery loop.
36
+
37
+ use std::collections::HashMap;
38
+ use std::sync::Arc;
39
+ use std::time::Duration;
40
+
41
+ use anyhow::{Context, Result};
42
+ use async_trait::async_trait;
43
+ use bytes::Bytes;
44
+ use reqwest::Client;
45
+ use serde::Deserialize;
46
+ use thiserror::Error;
47
+ use tokio::time::sleep;
48
+ use tracing::{debug, info, warn};
49
+
50
+ use crate::progress::CounterSpinner;
51
+ use crate::ratelimit::RateLimited;
52
+ use crate::state::StateDb;
53
+ use crate::RankedStatus;
54
+
55
+ pub mod nekoha;
56
+ pub mod nerinyan;
57
+ pub mod osudirect;
58
+ pub mod sayobot;
59
+
60
+ /// One beatmapset entry as a mirror reports it. Field names use the *mirror's*
61
+ /// claim — the aggregator does its own truth-by-quorum reconciliation.
62
+ #[derive(Clone, Debug, PartialEq, Eq)]
63
+ pub struct DiscoveryEntry {
64
+ pub set_id: u64,
65
+ pub claimed_status: RankedStatus,
66
+ /// True iff the entry has at least one beatmap with `mode_int == 0`.
67
+ /// Mirrors with no per-difficulty info should set this to `true` only when
68
+ /// the catalog-level mode field includes osu! standard.
69
+ pub has_osu_std: bool,
70
+ /// The mirror's stored `last_updated` (ISO 8601 or unix sec converted).
71
+ pub mirror_last_updated: Option<String>,
72
+ }
73
+
74
+ /// Opaque pagination token. Each mirror variant carries the bytes it needs
75
+ /// for its own pagination scheme; callers don't read it.
76
+ #[derive(Clone, Debug)]
77
+ pub enum PageCursor {
78
+ /// Cursor-based: opaque server token (Nerinyan).
79
+ Opaque(String),
80
+ /// Offset-based: skip-N integer (osu.direct, Sayobot).
81
+ Offset(u64),
82
+ }
83
+
84
+ /// One page of search results from a mirror.
85
+ #[derive(Clone, Debug, Default)]
86
+ pub struct SearchPage {
87
+ pub entries: Vec<DiscoveryEntry>,
88
+ pub next_cursor: Option<PageCursor>,
89
+ }
90
+
91
+ #[derive(Debug, Error)]
92
+ pub enum MirrorSearchError {
93
+ #[error("{mirror} returned HTTP {status}: {body_snippet}")]
94
+ HttpError {
95
+ mirror: String,
96
+ status: u16,
97
+ body_snippet: String,
98
+ },
99
+
100
+ #[error("{mirror} rate limited")]
101
+ RateLimited { mirror: String },
102
+
103
+ #[error("{mirror} network error: {source}")]
104
+ Network {
105
+ mirror: String,
106
+ #[source]
107
+ source: reqwest::Error,
108
+ },
109
+
110
+ #[error("{mirror} response decode failed: {reason}")]
111
+ DecodeError { mirror: String, reason: String },
112
+ }
113
+
114
+ impl MirrorSearchError {
115
+ pub fn mirror(&self) -> &str {
116
+ match self {
117
+ MirrorSearchError::HttpError { mirror, .. }
118
+ | MirrorSearchError::RateLimited { mirror }
119
+ | MirrorSearchError::Network { mirror, .. }
120
+ | MirrorSearchError::DecodeError { mirror, .. } => mirror,
121
+ }
122
+ }
123
+ }
124
+
125
+ /// Async iterator-shaped trait for "list me one page at a time".
126
+ ///
127
+ /// Mirrors that *can* filter status server-side accept a `Some(status)` and
128
+ /// only return matching sets. Mirrors that can't (Sayobot's `R` param is
129
+ /// inconsistent) ignore it and rely on the aggregator filtering by
130
+ /// `claimed_status`.
131
+ #[async_trait]
132
+ pub trait MirrorSearch: Send + Sync {
133
+ fn name(&self) -> &str;
134
+
135
+ /// True if this mirror filters by ranked status server-side. False means
136
+ /// the caller will receive all statuses and must drop unwanted ones.
137
+ fn supports_status_filter(&self) -> bool;
138
+
139
+ /// Fetch one page. `status` is the desired filter (only honored when
140
+ /// `supports_status_filter()`); `mode` is the standard mode_int (0 for
141
+ /// osu! standard).
142
+ async fn search_page(
143
+ &self,
144
+ status: Option<RankedStatus>,
145
+ mode: u8,
146
+ cursor: Option<&PageCursor>,
147
+ ) -> Result<SearchPage, MirrorSearchError>;
148
+ }
149
+
150
+ /// Per-set verifier: given a set ID, ask the mirror what it knows. Used to
151
+ /// double-check a candidate before promoting it to `wanted`.
152
+ #[async_trait]
153
+ pub trait MirrorVerify: Send + Sync {
154
+ fn name(&self) -> &str;
155
+
156
+ /// `Ok(Some(...))` when the mirror has the set, `Ok(None)` when the
157
+ /// mirror reports 404 (definitive absence), `Err(...)` for any other
158
+ /// failure (transient — retry later).
159
+ async fn verify_set(&self, set_id: u64) -> Result<Option<DiscoveryEntry>, MirrorSearchError>;
160
+ }
161
+
162
+ /// Knobs for `discover_all`.
163
+ #[derive(Clone, Copy, Debug)]
164
+ pub struct DiscoverOptions {
165
+ pub mode: u8,
166
+ /// Hard cap on pages per (mirror, status). `None` = exhaust pagination.
167
+ pub max_pages_per_mirror_status: Option<u32>,
168
+ /// Whether to walk every status on every mirror. Useful to limit reads
169
+ /// on first run; default = walk Ranked + Approved + Loved + Qualified.
170
+ pub statuses: &'static [RankedStatus],
171
+ /// Promote sets to `wanted` once at least this many distinct mirrors have
172
+ /// reported them with `has_osu_std = true`. The official API counts as
173
+ /// one mirror; if the set is already on the API, it's already wanted.
174
+ pub min_quorum: u32,
175
+ /// How many consecutive zero-record pages to tolerate before we stop a
176
+ /// walk. Sayobot's `T=4` newest-first list eventually grinds into
177
+ /// pending/graveyard rows that all filter out — without a fuse we
178
+ /// paginate forever. Tuned to 10: at 100 raw rows/page that's 1000
179
+ /// rows in a row with no qualifying matches, well past statistical
180
+ /// noise. Set to 0 to disable.
181
+ pub consecutive_empty_break_pages: u32,
182
+ /// Per-page retry budget for transient errors (RateLimited / Network /
183
+ /// 5xx). Each retry waits exponentially: 2s, 4s, 8s. Set to 0 to
184
+ /// disable retries entirely (every transient blip becomes a hard
185
+ /// failure for the walk).
186
+ pub retry_attempts: u32,
187
+ }
188
+
189
+ impl Default for DiscoverOptions {
190
+ fn default() -> Self {
191
+ Self {
192
+ mode: 0,
193
+ max_pages_per_mirror_status: None,
194
+ statuses: RankedStatus::all_with_leaderboard(),
195
+ min_quorum: 2,
196
+ consecutive_empty_break_pages: 10,
197
+ retry_attempts: 3,
198
+ }
199
+ }
200
+ }
201
+
202
+ #[derive(Clone, Debug, Default)]
203
+ pub struct DiscoverStats {
204
+ /// Pages fetched, summed across mirrors and statuses.
205
+ pub pages: u64,
206
+ /// Distinct (mirror, set_id) reports recorded.
207
+ pub reports_recorded: u64,
208
+ /// Distinct sets reported by at least one mirror.
209
+ pub sets_seen: u64,
210
+ /// Sets newly promoted from "mirror-only sighting" to `wanted` because
211
+ /// the quorum threshold was met. Excludes sets already wanted from the
212
+ /// official API run.
213
+ pub promoted_to_wanted: u64,
214
+ /// Sets the mirror catalog claims exist but the official API doesn't —
215
+ /// not yet meeting quorum. Useful to surface to a human reviewer.
216
+ pub sub_quorum_candidates: u64,
217
+ }
218
+
219
+ /// Walk every mirror's discovery surface for every requested status, write
220
+ /// each report to `mirror_discoveries`, then aggregate to find sets that
221
+ /// meet `opts.min_quorum` independent-mirror agreement.
222
+ ///
223
+ /// The aggregator does NOT re-check the official API; if the caller wants
224
+ /// "sets the API doesn't know about", run `enumerate` first and let
225
+ /// `record_discovery` upsert against the existing `sets` table.
226
+ ///
227
+ /// `progress_enabled` controls the live one-line spinners. It must be `false`
228
+ /// in CI / log-redirect / tests; the caller usually computes
229
+ /// `!cli.no_progress && progress::stderr_is_terminal()`. When `false`, every
230
+ /// status update becomes a no-op and there's no terminal painting at all.
231
+ pub async fn discover_all(
232
+ state: Arc<StateDb>,
233
+ mirrors: &[Arc<dyn MirrorSearch>],
234
+ verifiers: &[Arc<dyn MirrorVerify>],
235
+ opts: DiscoverOptions,
236
+ progress_enabled: bool,
237
+ ) -> Result<DiscoverStats> {
238
+ let mut stats = DiscoverStats::default();
239
+
240
+ for mirror in mirrors {
241
+ if mirror.supports_status_filter() {
242
+ // Once a mirror's first status walk fails after retries, the
243
+ // mirror is in some sticky bad state (rate-banned for the day,
244
+ // upstream cache outage, etc.). Skip its remaining statuses
245
+ // rather than burn the retry budget on each — the next
246
+ // discover run will retry from scratch.
247
+ let mut mirror_unhealthy = false;
248
+ for &status in opts.statuses {
249
+ let label = format!("{} {}", mirror.name(), status.as_api_str());
250
+ let spinner = CounterSpinner::new(&label, progress_enabled);
251
+ if mirror_unhealthy {
252
+ spinner.finish(String::from("skipped (earlier walk failed)"));
253
+ continue;
254
+ }
255
+ let walk = walk_mirror(
256
+ state.clone(),
257
+ mirror.as_ref(),
258
+ Some(status),
259
+ opts,
260
+ Some(&spinner),
261
+ )
262
+ .await;
263
+ if walk.is_err() {
264
+ mirror_unhealthy = true;
265
+ }
266
+ accumulate_walk(&mut stats, &spinner, &label, walk);
267
+ }
268
+ } else {
269
+ // No server-side status filter → one walk covers every status
270
+ // the catalog can yield. The aggregator filters by claimed
271
+ // status against `opts.statuses` so unwanted ones are dropped
272
+ // before they hit `mirror_discoveries`.
273
+ let label = format!("{} (all-status)", mirror.name());
274
+ let spinner = CounterSpinner::new(&label, progress_enabled);
275
+ let walk =
276
+ walk_mirror(state.clone(), mirror.as_ref(), None, opts, Some(&spinner)).await;
277
+ accumulate_walk(&mut stats, &spinner, &label, walk);
278
+ }
279
+ }
280
+
281
+ // Verifier pass: for sets seen on exactly `min_quorum - 1` mirrors,
282
+ // ping the verifiers. This trades an extra HTTP call for a second
283
+ // independent confirmation, often enough to push a 1-mirror sighting
284
+ // over the quorum line. Walked here rather than inside the per-mirror
285
+ // loop so the verifier set is built from *every* mirror's contribution,
286
+ // not just the first.
287
+ if !verifiers.is_empty() {
288
+ let singleton_ids = state.list_singleton_discoveries(opts.min_quorum)?;
289
+ let total = singleton_ids.len();
290
+ debug!(count = total, "running verifier pass on singletons");
291
+ let label = format!("verify ({} candidates)", total);
292
+ let spinner = CounterSpinner::new(&label, progress_enabled);
293
+ let mut confirmed: u64 = 0;
294
+ let mut absent: u64 = 0;
295
+ let mut errors: u64 = 0;
296
+ for (i, id) in singleton_ids.iter().enumerate() {
297
+ for v in verifiers {
298
+ match v.verify_set(*id).await {
299
+ Ok(Some(entry)) => {
300
+ state.record_discovery(v.name(), &entry)?;
301
+ stats.reports_recorded += 1;
302
+ confirmed += 1;
303
+ }
304
+ Ok(None) => {
305
+ absent += 1;
306
+ }
307
+ Err(e) => {
308
+ errors += 1;
309
+ warn!(verifier = v.name(), set_id = id, error = %e,
310
+ "verifier transient failure; will retry next run");
311
+ }
312
+ }
313
+ }
314
+ // Repaint every 5 candidates (or on the last one). Per-set
315
+ // updates would flicker badly when verifiers reply quickly.
316
+ if (i + 1) % 5 == 0 || i + 1 == total {
317
+ spinner.set_message(format!(
318
+ "{}/{} · confirmed {} · absent {} · errors {}",
319
+ i + 1,
320
+ total,
321
+ confirmed,
322
+ absent,
323
+ errors
324
+ ));
325
+ }
326
+ }
327
+ spinner.finish(format!(
328
+ "done · confirmed {} · absent {} · errors {}",
329
+ confirmed, absent, errors
330
+ ));
331
+ }
332
+
333
+ // Aggregate + promote — fast (single SQL pass), but worth its own
334
+ // spinner so the operator sees the whole pipeline reach completion
335
+ // even when the walks dominate wallclock.
336
+ let agg_spinner = CounterSpinner::new("aggregate", progress_enabled);
337
+ agg_spinner.set_message("computing quorum across discoveries…");
338
+ let agg = state.aggregate_discoveries(opts.min_quorum)?;
339
+ stats.sets_seen = agg.distinct_sets;
340
+ stats.promoted_to_wanted = state.promote_quorum_to_wanted(opts.min_quorum)?;
341
+ stats.sub_quorum_candidates = agg.sub_quorum;
342
+ agg_spinner.finish(format!(
343
+ "done · sets_seen {} · promoted {} · sub_quorum {}",
344
+ stats.sets_seen, stats.promoted_to_wanted, stats.sub_quorum_candidates
345
+ ));
346
+
347
+ info!(
348
+ pages = stats.pages,
349
+ reports = stats.reports_recorded,
350
+ sets_seen = stats.sets_seen,
351
+ promoted = stats.promoted_to_wanted,
352
+ sub_quorum = stats.sub_quorum_candidates,
353
+ "discover complete"
354
+ );
355
+ Ok(stats)
356
+ }
357
+
358
+ /// Roll one mirror walk's outcome into the aggregate `DiscoverStats` and
359
+ /// finish its spinner with a status-aware summary line. A failed walk
360
+ /// updates the spinner with the error so a transient mirror outage is
361
+ /// visually obvious without burying it in the trace log.
362
+ fn accumulate_walk(
363
+ stats: &mut DiscoverStats,
364
+ spinner: &CounterSpinner,
365
+ label: &str,
366
+ walk: Result<MirrorWalkStats>,
367
+ ) {
368
+ match walk {
369
+ Ok(p) => {
370
+ stats.pages += p.pages;
371
+ stats.reports_recorded += p.reports;
372
+ spinner.finish(format!(
373
+ "done · pages {} · entries {} · recorded {}",
374
+ p.pages, p.entries_seen, p.reports
375
+ ));
376
+ }
377
+ Err(e) => {
378
+ // Don't `?`-bubble: one mirror's outage shouldn't kill a
379
+ // multi-mirror discover run. Surface it on the spinner line
380
+ // and continue with the rest. `{e:#}` includes the full
381
+ // anyhow chain so the underlying HTTP status / decode
382
+ // error is visible (the outermost context alone is just
383
+ // `search_page mirror=osudirect status=Some(Ranked)`,
384
+ // which is useless for diagnosing a 429 vs 500 vs decode bug).
385
+ warn!(mirror_label = label, error = %format!("{e:#}"),
386
+ "mirror walk failed; continuing with the rest");
387
+ spinner.finish(format!("FAILED · {e:#}"));
388
+ }
389
+ }
390
+ }
391
+
392
+ /// Walk one (mirror, status) pair across pages, persisting each entry as a
393
+ /// `mirror_discoveries` row. Returns counters for stats aggregation.
394
+ ///
395
+ /// `status` is `Some(s)` when the mirror filters server-side (one walk per
396
+ /// requested status), `None` for mirrors that can't filter (one walk total,
397
+ /// client-side filter against `opts.statuses`).
398
+ ///
399
+ /// `progress`, when supplied, is updated after every page so the operator
400
+ /// sees the walk advance in real time. Updates use raw entry counts (what
401
+ /// the mirror returned) and recorded counts (what survived our filters)
402
+ /// to make a stuck-but-paginating page chain distinguishable from one
403
+ /// that's just turning over inapplicable entries.
404
+ async fn walk_mirror(
405
+ state: Arc<StateDb>,
406
+ mirror: &dyn MirrorSearch,
407
+ status: Option<RankedStatus>,
408
+ opts: DiscoverOptions,
409
+ progress: Option<&CounterSpinner>,
410
+ ) -> Result<MirrorWalkStats> {
411
+ let mut walk = MirrorWalkStats::default();
412
+ let mut cursor: Option<PageCursor> = None;
413
+ let mut consecutive_empty: u32 = 0;
414
+
415
+ loop {
416
+ let page = fetch_page_with_retry(mirror, status, opts, cursor.as_ref(), progress)
417
+ .await
418
+ .with_context(|| format!("search_page mirror={} status={:?}", mirror.name(), status))?;
419
+ walk.pages += 1;
420
+ walk.entries_seen += page.entries.len() as u64;
421
+
422
+ let mut recorded_this_page: u64 = 0;
423
+ for entry in &page.entries {
424
+ // Mirrors with server-side filter return only matches; we
425
+ // record what they say. Mirrors without filter (sayobot) hand
426
+ // back every status — drop entries outside our target set
427
+ // before they pollute `mirror_discoveries`.
428
+ let want = status.is_some() || opts.statuses.contains(&entry.claimed_status);
429
+ if !want {
430
+ continue;
431
+ }
432
+ if !entry.has_osu_std {
433
+ continue;
434
+ }
435
+ state
436
+ .record_discovery(mirror.name(), entry)
437
+ .with_context(|| {
438
+ format!(
439
+ "recording discovery set_id={} mirror={}",
440
+ entry.set_id,
441
+ mirror.name()
442
+ )
443
+ })?;
444
+ walk.reports += 1;
445
+ recorded_this_page += 1;
446
+ }
447
+ if recorded_this_page == 0 {
448
+ consecutive_empty += 1;
449
+ } else {
450
+ consecutive_empty = 0;
451
+ }
452
+
453
+ if let Some(p) = progress {
454
+ p.set_message(format!(
455
+ "pages {} · entries {} · recorded {} · {}",
456
+ walk.pages,
457
+ walk.entries_seen,
458
+ walk.reports,
459
+ cursor_hint(&page.next_cursor),
460
+ ));
461
+ }
462
+
463
+ let cap = opts.max_pages_per_mirror_status.unwrap_or(u32::MAX) as u64;
464
+ if walk.pages >= cap {
465
+ debug!(
466
+ mirror = mirror.name(),
467
+ status = ?status,
468
+ "stopping at max_pages cap"
469
+ );
470
+ break;
471
+ }
472
+ // Consecutive-empty fuse: a long run of pages where every entry
473
+ // got filtered out (status outside our target set, or no osu!std
474
+ // difficulty) means we've walked past the useful section of the
475
+ // mirror's catalog. Sayobot is the canonical case — `T=4` newest-
476
+ // first eventually grinds into pending/graveyard rows that all
477
+ // drop. Without this, the walk runs until offset overflow.
478
+ if opts.consecutive_empty_break_pages > 0
479
+ && consecutive_empty >= opts.consecutive_empty_break_pages
480
+ {
481
+ debug!(
482
+ mirror = mirror.name(),
483
+ status = ?status,
484
+ consecutive_empty,
485
+ "stopping at consecutive-empty fuse"
486
+ );
487
+ if let Some(p) = progress {
488
+ p.set_message(format!(
489
+ "pages {} · entries {} · recorded {} · fuse: {} empty pages",
490
+ walk.pages, walk.entries_seen, walk.reports, consecutive_empty
491
+ ));
492
+ }
493
+ break;
494
+ }
495
+ cursor = match page.next_cursor {
496
+ Some(c) => Some(c),
497
+ None => break,
498
+ };
499
+ }
500
+ Ok(walk)
501
+ }
502
+
503
+ /// Wrap one `mirror.search_page` call in a retry loop with exponential
504
+ /// backoff. Only retries *transient* errors (RateLimited, Network, 5xx
505
+ /// HttpError). Permanent-looking errors (4xx other than 429, decode
506
+ /// failures) bail immediately so a malformed schema doesn't waste 14
507
+ /// seconds of backoff before erroring out.
508
+ ///
509
+ /// Backoff schedule for `retry_attempts = 3`: wait 2s → try → wait 4s →
510
+ /// try → wait 8s → try → fail. Total worst-case latency: ~14s. Picked to
511
+ /// be long enough that a 429 from a strict mirror can settle, but short
512
+ /// enough that a hung mirror doesn't drag the whole run.
513
+ async fn fetch_page_with_retry(
514
+ mirror: &dyn MirrorSearch,
515
+ status: Option<RankedStatus>,
516
+ opts: DiscoverOptions,
517
+ cursor: Option<&PageCursor>,
518
+ progress: Option<&CounterSpinner>,
519
+ ) -> Result<SearchPage, MirrorSearchError> {
520
+ let mut attempt: u32 = 0;
521
+ loop {
522
+ match mirror.search_page(status, opts.mode, cursor).await {
523
+ Ok(page) => return Ok(page),
524
+ Err(e) => {
525
+ if attempt >= opts.retry_attempts || !is_transient(&e) {
526
+ return Err(e);
527
+ }
528
+ let backoff_secs = 1u64 << (attempt + 1); // 2, 4, 8, 16…
529
+ if let Some(p) = progress {
530
+ p.set_message(format!(
531
+ "retry {}/{} in {}s · {e}",
532
+ attempt + 1,
533
+ opts.retry_attempts,
534
+ backoff_secs
535
+ ));
536
+ }
537
+ debug!(
538
+ mirror = mirror.name(),
539
+ attempt = attempt + 1,
540
+ backoff_secs,
541
+ error = %e,
542
+ "transient mirror error; backing off"
543
+ );
544
+ sleep(Duration::from_secs(backoff_secs)).await;
545
+ attempt += 1;
546
+ }
547
+ }
548
+ }
549
+ }
550
+
551
+ /// Classify a `MirrorSearchError` as worth retrying or not.
552
+ ///
553
+ /// * RateLimited (429): worth retrying — the limiter expects pacing,
554
+ /// but a peer-side burst can still spike past it.
555
+ /// * Network: transient by definition — DNS hiccup, TCP RST, peer
556
+ /// timeout. Retrying is the entire point.
557
+ /// * HttpError 5xx: server side; usually clears in a few seconds.
558
+ /// * HttpError 4xx (other than 429): malformed request or auth issue;
559
+ /// retrying just sends the same broken thing again.
560
+ /// * DecodeError: schema drift; retrying won't make the JSON parse.
561
+ fn is_transient(e: &MirrorSearchError) -> bool {
562
+ match e {
563
+ MirrorSearchError::RateLimited { .. } => true,
564
+ MirrorSearchError::Network { .. } => true,
565
+ MirrorSearchError::HttpError { status, .. } => *status >= 500,
566
+ MirrorSearchError::DecodeError { .. } => false,
567
+ }
568
+ }
569
+
570
+ #[derive(Default, Debug)]
571
+ struct MirrorWalkStats {
572
+ pages: u64,
573
+ /// Raw entries returned by the mirror across all pages — useful as a
574
+ /// sanity check against `reports` when most of a page is filtered out
575
+ /// (e.g., sayobot returning many graveyard sets we don't care about).
576
+ entries_seen: u64,
577
+ /// Entries we actually recorded into `mirror_discoveries`.
578
+ reports: u64,
579
+ }
580
+
581
+ /// One-line cursor summary for the spinner: `cursor done` once pagination
582
+ /// is exhausted, or a short token preview otherwise. Mirrors the
583
+ /// human-readable shape `enumerate.rs` uses.
584
+ fn cursor_hint(c: &Option<PageCursor>) -> String {
585
+ match c {
586
+ None => "cursor done".into(),
587
+ Some(PageCursor::Opaque(s)) => {
588
+ if s.len() <= 12 {
589
+ format!("cursor {s}")
590
+ } else {
591
+ format!("cursor …{}", &s[s.len().saturating_sub(8)..])
592
+ }
593
+ }
594
+ Some(PageCursor::Offset(n)) => format!("offset {n}"),
595
+ }
596
+ }
597
+
598
+ /// Result of aggregating `mirror_discoveries` rows for a given quorum.
599
+ #[derive(Clone, Debug, Default)]
600
+ pub struct DiscoveryAggregate {
601
+ /// Distinct set_ids that appear in `mirror_discoveries`.
602
+ pub distinct_sets: u64,
603
+ /// Sets short of `min_quorum` mirrors. These are surfaced to the human
604
+ /// for manual review but not auto-promoted.
605
+ pub sub_quorum: u64,
606
+ }
607
+
608
+ /// Build a `reqwest::Client` configured for discovery I/O. Identical knobs
609
+ /// to `mirrors::build_client` so the same User-Agent surfaces upstream. We
610
+ /// keep a separate factory so future tweaks (different timeout, different
611
+ /// UA) don't bleed across modules.
612
+ pub fn build_client() -> Result<Client, reqwest::Error> {
613
+ Client::builder()
614
+ .user_agent(crate::mirrors::user_agent())
615
+ .timeout(Duration::from_secs(45))
616
+ .pool_idle_timeout(Duration::from_secs(60))
617
+ .gzip(true)
618
+ .brotli(true)
619
+ .build()
620
+ }
621
+
622
+ /// Common helper: take a finished `reqwest::Response` and return its body as
623
+ /// JSON-decodable bytes. Centralizes status → MirrorSearchError mapping so
624
+ /// every mirror impl handles 404/429/5xx/decode-error consistently.
625
+ pub(crate) async fn response_bytes(
626
+ mirror: &str,
627
+ resp: reqwest::Response,
628
+ ) -> Result<Bytes, MirrorSearchError> {
629
+ let status = resp.status();
630
+ if status.is_success() {
631
+ return resp.bytes().await.map_err(|e| MirrorSearchError::Network {
632
+ mirror: mirror.into(),
633
+ source: e,
634
+ });
635
+ }
636
+ if status == reqwest::StatusCode::TOO_MANY_REQUESTS {
637
+ return Err(MirrorSearchError::RateLimited {
638
+ mirror: mirror.into(),
639
+ });
640
+ }
641
+ let body = resp.text().await.unwrap_or_default();
642
+ Err(MirrorSearchError::HttpError {
643
+ mirror: mirror.into(),
644
+ status: status.as_u16(),
645
+ body_snippet: body.chars().take(200).collect(),
646
+ })
647
+ }
648
+
649
+ /// Decode JSON into `T`. Wraps `serde_json` errors as
650
+ /// `MirrorSearchError::DecodeError` so a schema drift on one mirror doesn't
651
+ /// take down the whole `discover_all` run.
652
+ pub(crate) fn decode_json<T: for<'de> Deserialize<'de>>(
653
+ mirror: &str,
654
+ bytes: &[u8],
655
+ ) -> Result<T, MirrorSearchError> {
656
+ serde_json::from_slice::<T>(bytes).map_err(|e| MirrorSearchError::DecodeError {
657
+ mirror: mirror.into(),
658
+ reason: e.to_string(),
659
+ })
660
+ }
661
+
662
+ /// Construction inputs every search impl takes. Avoids the same
663
+ /// `(client, rate_limiter)` pair leaking through every constructor signature.
664
+ #[derive(Clone)]
665
+ pub struct DiscoverContext {
666
+ pub client: Client,
667
+ pub limiters: DiscoverLimiters,
668
+ }
669
+
670
+ /// Per-mirror rate-limit handles for the *discovery* path. Kept separate
671
+ /// from `MirrorLimiters` because download and search hit different upstream
672
+ /// endpoints — a single shared limiter would force search to compete with
673
+ /// download for the budget, which we don't want.
674
+ #[derive(Clone)]
675
+ pub struct DiscoverLimiters {
676
+ pub nerinyan: RateLimited,
677
+ pub osudirect: RateLimited,
678
+ pub sayobot: RateLimited,
679
+ pub nekoha: RateLimited,
680
+ }
681
+
682
+ /// Map status counts back to the fmt-friendly form for logging.
683
+ pub fn quorum_summary(rows: &[(u64, u32, RankedStatus)]) -> String {
684
+ let mut by_status: HashMap<&'static str, u32> = HashMap::new();
685
+ for (_id, _count, st) in rows {
686
+ *by_status.entry(st.as_api_str()).or_default() += 1;
687
+ }
688
+ let mut parts: Vec<_> = by_status.into_iter().collect();
689
+ parts.sort_by_key(|(k, _)| *k);
690
+ parts
691
+ .into_iter()
692
+ .map(|(k, v)| format!("{k}={v}"))
693
+ .collect::<Vec<_>>()
694
+ .join(" ")
695
+ }
696
+
697
+ #[cfg(test)]
698
+ mod tests {
699
+ use super::*;
700
+
701
+ #[test]
702
+ fn discover_options_default_walks_all_leaderboard_statuses() {
703
+ let opts = DiscoverOptions::default();
704
+ assert_eq!(opts.statuses.len(), 4);
705
+ assert!(opts.statuses.contains(&RankedStatus::Ranked));
706
+ assert!(opts.statuses.contains(&RankedStatus::Loved));
707
+ assert!(opts.statuses.contains(&RankedStatus::Qualified));
708
+ assert!(opts.statuses.contains(&RankedStatus::Approved));
709
+ assert_eq!(opts.min_quorum, 2);
710
+ }
711
+
712
+ #[test]
713
+ fn discovery_entry_round_trips_for_known_status() {
714
+ // Construction smoke test: the struct should hold values the
715
+ // sayobot/osu.direct/nerinyan parsers all hand back.
716
+ let e = DiscoveryEntry {
717
+ set_id: 12345,
718
+ claimed_status: RankedStatus::Loved,
719
+ has_osu_std: true,
720
+ mirror_last_updated: Some("2026-01-01T00:00:00Z".into()),
721
+ };
722
+ assert_eq!(e.set_id, 12345);
723
+ assert_eq!(e.claimed_status, RankedStatus::Loved);
724
+ assert!(e.has_osu_std);
725
+ }
726
+
727
+ #[test]
728
+ fn cursor_hint_displays_done_when_no_next_cursor() {
729
+ assert_eq!(cursor_hint(&None), "cursor done");
730
+ }
731
+
732
+ #[test]
733
+ fn cursor_hint_truncates_long_opaque_tokens() {
734
+ // Nerinyan tokens can be 40+ chars (e.g. `[1776262922000]`-style
735
+ // arrays or alphanumeric blobs). The spinner line has a fixed
736
+ // width budget; the hint must collapse long tokens to a tail.
737
+ let short = cursor_hint(&Some(PageCursor::Opaque("abc".into())));
738
+ assert_eq!(short, "cursor abc");
739
+ let long = cursor_hint(&Some(PageCursor::Opaque(
740
+ "abcdefghijklmnopqrstuvwxyz".into(),
741
+ )));
742
+ assert!(long.starts_with("cursor …"));
743
+ assert!(long.len() < 20);
744
+ }
745
+
746
+ #[test]
747
+ fn is_transient_classifies_known_cases() {
748
+ // 429: rate limit — definitely retry-worthy.
749
+ assert!(is_transient(&MirrorSearchError::RateLimited {
750
+ mirror: "x".into()
751
+ }));
752
+ // 503: upstream gateway hiccup — retry.
753
+ assert!(is_transient(&MirrorSearchError::HttpError {
754
+ mirror: "x".into(),
755
+ status: 503,
756
+ body_snippet: "".into()
757
+ }));
758
+ // 500: same — retry.
759
+ assert!(is_transient(&MirrorSearchError::HttpError {
760
+ mirror: "x".into(),
761
+ status: 500,
762
+ body_snippet: "".into()
763
+ }));
764
+ // 403: client-side rejection (osu.direct returns this for type
765
+ // errors). Don't retry — the request is malformed.
766
+ assert!(!is_transient(&MirrorSearchError::HttpError {
767
+ mirror: "x".into(),
768
+ status: 403,
769
+ body_snippet: "".into()
770
+ }));
771
+ // 404: not found. Don't retry.
772
+ assert!(!is_transient(&MirrorSearchError::HttpError {
773
+ mirror: "x".into(),
774
+ status: 404,
775
+ body_snippet: "".into()
776
+ }));
777
+ // Decode failure: schema drift, retry won't fix the JSON.
778
+ assert!(!is_transient(&MirrorSearchError::DecodeError {
779
+ mirror: "x".into(),
780
+ reason: "bad".into()
781
+ }));
782
+ }
783
+
784
+ #[test]
785
+ fn discover_options_default_has_retry_and_fuse() {
786
+ let opts = DiscoverOptions::default();
787
+ assert!(
788
+ opts.retry_attempts >= 1,
789
+ "retries must be enabled by default"
790
+ );
791
+ assert!(
792
+ opts.consecutive_empty_break_pages >= 1,
793
+ "fuse must be enabled by default"
794
+ );
795
+ }
796
+
797
+ #[test]
798
+ fn cursor_hint_renders_offset_as_plain_int() {
799
+ assert_eq!(cursor_hint(&Some(PageCursor::Offset(42))), "offset 42");
800
+ }
801
+
802
+ #[test]
803
+ fn quorum_summary_formats_grouped_counts() {
804
+ let rows = vec![
805
+ (1, 2, RankedStatus::Ranked),
806
+ (2, 3, RankedStatus::Ranked),
807
+ (3, 2, RankedStatus::Loved),
808
+ ];
809
+ let s = quorum_summary(&rows);
810
+ assert!(s.contains("ranked=2"));
811
+ assert!(s.contains("loved=1"));
812
+ }
813
+ }
crates/osu_fetcher/src/discover/nekoha.rs ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //! nekoha.moe — per-set verifier.
2
+ //!
3
+ //! nekoha's `/api4/search` only supports text search (`q`, `page`,
4
+ //! `sort`, `order`) — no status filter, no listing-by-status. That makes
5
+ //! it useless as a *discovery* source for our use case (we'd have to walk
6
+ //! the entire catalog blindly and post-filter, burning a million requests
7
+ //! for a small recovery).
8
+ //!
9
+ //! What it *is* useful for: per-set verification. `GET /api4/beatmapsetFull/:id`
10
+ //! returns a beatmapset with a `beatmaps[]` array including `mode_int` and
11
+ //! `status`. If we have a candidate set ID with a 1-mirror sighting, asking
12
+ //! nekoha is a cheap second opinion that often pushes the candidate over the
13
+ //! quorum line.
14
+
15
+ use async_trait::async_trait;
16
+ use reqwest::Client;
17
+ use serde::Deserialize;
18
+
19
+ use super::{
20
+ decode_json, response_bytes, DiscoverContext, DiscoveryEntry, MirrorSearchError, MirrorVerify,
21
+ };
22
+ use crate::ratelimit::RateLimited;
23
+ use crate::RankedStatus;
24
+
25
+ pub const NAME: &str = "nekoha";
26
+ const BASE: &str = "https://mirror.nekoha.moe/api4/beatmapsetFull";
27
+
28
+ /// Nekoha encodes integers as JSON strings ("12345" not 12345). The
29
+ /// `serde-aux` style fix is to deserialize to a string and parse it; we
30
+ /// use a small helper instead so we don't pull a dep in for one field.
31
+ #[derive(Clone, Debug, Deserialize)]
32
+ struct NekohaSet {
33
+ #[serde(default)]
34
+ id: serde_json::Value,
35
+ #[serde(default)]
36
+ status: Option<String>,
37
+ #[serde(default)]
38
+ last_updated: Option<String>,
39
+ #[serde(default)]
40
+ beatmaps: Vec<NekohaBeatmap>,
41
+ }
42
+
43
+ #[derive(Clone, Debug, Deserialize)]
44
+ struct NekohaBeatmap {
45
+ #[serde(default)]
46
+ mode_int: serde_json::Value,
47
+ #[serde(default)]
48
+ mode: Option<String>,
49
+ }
50
+
51
+ pub struct NekohaVerify {
52
+ client: Client,
53
+ limiter: RateLimited,
54
+ }
55
+
56
+ impl NekohaVerify {
57
+ pub fn new(ctx: &DiscoverContext) -> Self {
58
+ Self {
59
+ client: ctx.client.clone(),
60
+ limiter: ctx.limiters.nekoha.clone(),
61
+ }
62
+ }
63
+ }
64
+
65
+ #[async_trait]
66
+ impl MirrorVerify for NekohaVerify {
67
+ fn name(&self) -> &str {
68
+ NAME
69
+ }
70
+
71
+ async fn verify_set(&self, set_id: u64) -> Result<Option<DiscoveryEntry>, MirrorSearchError> {
72
+ self.limiter.acquire().await;
73
+ let url = format!("{BASE}/{set_id}");
74
+ let resp = self
75
+ .client
76
+ .get(&url)
77
+ .send()
78
+ .await
79
+ .map_err(|e| MirrorSearchError::Network {
80
+ mirror: NAME.into(),
81
+ source: e,
82
+ })?;
83
+ if resp.status() == reqwest::StatusCode::NOT_FOUND {
84
+ return Ok(None);
85
+ }
86
+ let bytes = response_bytes(NAME, resp).await?;
87
+ let parsed: NekohaSet = decode_json(NAME, &bytes)?;
88
+ Ok(parse_entry(set_id, &parsed))
89
+ }
90
+ }
91
+
92
+ fn parse_entry(set_id: u64, raw: &NekohaSet) -> Option<DiscoveryEntry> {
93
+ let status = match raw.status.as_deref()? {
94
+ "ranked" => RankedStatus::Ranked,
95
+ "approved" => RankedStatus::Approved,
96
+ "loved" => RankedStatus::Loved,
97
+ "qualified" => RankedStatus::Qualified,
98
+ _ => return None,
99
+ };
100
+ // Confirm the response actually corresponds to the requested ID. If
101
+ // nekoha ever returns a different set (cache miss, redirect), we want
102
+ // to drop the row rather than crosslink unrelated set IDs.
103
+ if !id_matches(&raw.id, set_id) {
104
+ return None;
105
+ }
106
+ let has_osu_std = raw.beatmaps.iter().any(|b| {
107
+ if let Some(m) = b.mode.as_deref() {
108
+ if m == "osu" {
109
+ return true;
110
+ }
111
+ }
112
+ json_to_u8(&b.mode_int).map(|m| m == 0).unwrap_or(false)
113
+ });
114
+ if !has_osu_std {
115
+ return None;
116
+ }
117
+ Some(DiscoveryEntry {
118
+ set_id,
119
+ claimed_status: status,
120
+ has_osu_std,
121
+ mirror_last_updated: raw.last_updated.clone(),
122
+ })
123
+ }
124
+
125
+ /// Compare the response's `id` (which nekoha may serialize as a JSON string
126
+ /// or number) to the requested `set_id`.
127
+ fn id_matches(value: &serde_json::Value, expected: u64) -> bool {
128
+ match value {
129
+ serde_json::Value::Number(n) => n.as_u64().map(|v| v == expected).unwrap_or(false),
130
+ serde_json::Value::String(s) => s.parse::<u64>().map(|v| v == expected).unwrap_or(false),
131
+ _ => false,
132
+ }
133
+ }
134
+
135
+ fn json_to_u8(value: &serde_json::Value) -> Option<u8> {
136
+ match value {
137
+ serde_json::Value::Number(n) => n.as_u64().and_then(|v| u8::try_from(v).ok()),
138
+ serde_json::Value::String(s) => s.parse::<u8>().ok(),
139
+ _ => None,
140
+ }
141
+ }
142
+
143
+ #[cfg(test)]
144
+ mod tests {
145
+ use super::*;
146
+
147
+ #[test]
148
+ fn parses_response_with_string_ids() {
149
+ // nekoha serializes IDs as strings (`"id":"218851"`). The parser
150
+ // must still recognize them.
151
+ let body = r#"{
152
+ "id":"218851","status":"loved","last_updated":"2026-04-15T16:51:26Z",
153
+ "beatmaps":[{"mode_int":"0","mode":"osu"}]
154
+ }"#;
155
+ let parsed: NekohaSet = serde_json::from_str(body).unwrap();
156
+ let e = parse_entry(218851, &parsed).unwrap();
157
+ assert_eq!(e.set_id, 218851);
158
+ assert_eq!(e.claimed_status, RankedStatus::Loved);
159
+ assert!(e.has_osu_std);
160
+ }
161
+
162
+ #[test]
163
+ fn parses_response_with_numeric_ids() {
164
+ let body = r#"{
165
+ "id":42,"status":"ranked","last_updated":"2026-01-01T00:00:00Z",
166
+ "beatmaps":[{"mode_int":0,"mode":"osu"}]
167
+ }"#;
168
+ let parsed: NekohaSet = serde_json::from_str(body).unwrap();
169
+ let e = parse_entry(42, &parsed).unwrap();
170
+ assert_eq!(e.claimed_status, RankedStatus::Ranked);
171
+ }
172
+
173
+ #[test]
174
+ fn drops_when_response_id_disagrees_with_requested() {
175
+ let body = r#"{
176
+ "id":"999","status":"ranked",
177
+ "beatmaps":[{"mode_int":"0","mode":"osu"}]
178
+ }"#;
179
+ let parsed: NekohaSet = serde_json::from_str(body).unwrap();
180
+ // Asked for 42, mirror handed back 999 — must not record.
181
+ assert!(parse_entry(42, &parsed).is_none());
182
+ }
183
+
184
+ #[test]
185
+ fn drops_when_no_osu_difficulty_present() {
186
+ let body = r#"{
187
+ "id":"1","status":"ranked",
188
+ "beatmaps":[{"mode_int":"1","mode":"taiko"}]
189
+ }"#;
190
+ let parsed: NekohaSet = serde_json::from_str(body).unwrap();
191
+ assert!(parse_entry(1, &parsed).is_none());
192
+ }
193
+
194
+ #[test]
195
+ fn drops_unwanted_status_text() {
196
+ let body = r#"{
197
+ "id":"1","status":"graveyard",
198
+ "beatmaps":[{"mode_int":"0","mode":"osu"}]
199
+ }"#;
200
+ let parsed: NekohaSet = serde_json::from_str(body).unwrap();
201
+ assert!(parse_entry(1, &parsed).is_none());
202
+ }
203
+ }
crates/osu_fetcher/src/discover/nerinyan.rs ADDED
@@ -0,0 +1,316 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //! Nerinyan v2 search — discovery surface.
2
+ //!
3
+ //! Endpoint: `GET https://api.nerinyan.moe/v2/search`
4
+ //!
5
+ //! Why v2 and not v1? v2 is the modern path, advertises a `cursor` object
6
+ //! for pagination, and returns the rich `beatmaps[]` array with `mode_int`
7
+ //! per difficulty so we can verify osu! standard presence without a follow-up
8
+ //! request. v1's flat shape would force us to call `/v1/get_beatmapsets/{id}`
9
+ //! once per row to find the mode set — wasteful at our scale.
10
+ //!
11
+ //! Pagination: the response carries `cursor.cursor_string`. Pass it back as
12
+ //! `cursor_string=<value>` on the next request. When the server omits the
13
+ //! cursor (or returns an empty `beatmapsets`), pagination is exhausted.
14
+ //!
15
+ //! Rate limit: response headers expose `RateLimit-Limit: 120` and
16
+ //! `RateLimit-Remaining` / `RateLimit-Reset` (seconds). The CLI default is
17
+ //! currently 480 rpm for update speed; lower it if this endpoint starts
18
+ //! returning 429s.
19
+
20
+ use async_trait::async_trait;
21
+ use reqwest::Client;
22
+ use serde::Deserialize;
23
+ use tracing::debug;
24
+
25
+ use super::{
26
+ decode_json, response_bytes, DiscoverContext, DiscoveryEntry, MirrorSearch, MirrorSearchError,
27
+ PageCursor, SearchPage,
28
+ };
29
+ use crate::ratelimit::RateLimited;
30
+ use crate::RankedStatus;
31
+
32
+ pub const NAME: &str = "nerinyan";
33
+ const BASE: &str = "https://api.nerinyan.moe/v2/search";
34
+ /// Page cap for one HTTP call. The endpoint allows up to 100; we use the
35
+ /// full ceiling so we shave round-trips on a multi-thousand-page walk.
36
+ const PAGE_LIMIT: u32 = 100;
37
+
38
+ #[derive(Clone, Debug, Deserialize)]
39
+ struct NerinyanSearchResp {
40
+ #[serde(default)]
41
+ beatmapsets: Vec<NerinyanSet>,
42
+ #[serde(default)]
43
+ cursor: Option<NerinyanCursor>,
44
+ }
45
+
46
+ #[derive(Clone, Debug, Deserialize)]
47
+ struct NerinyanCursor {
48
+ /// Opaque token. Pass back verbatim as the `cursor_string` query param.
49
+ /// Some Nerinyan responses use a stringified array (e.g. `"[1776262922000]"`),
50
+ /// some use an alphanumeric token; we treat the field as opaque either way.
51
+ #[serde(default)]
52
+ cursor_string: Option<String>,
53
+ }
54
+
55
+ #[derive(Clone, Debug, Deserialize)]
56
+ struct NerinyanSet {
57
+ id: u64,
58
+ /// Status as text: `"ranked" | "approved" | "loved" | "qualified" | "graveyard" | ...`.
59
+ #[serde(default)]
60
+ status: Option<String>,
61
+ /// Numeric status: `-2 .. 4`. Used as a fallback if `status` is missing.
62
+ #[serde(default)]
63
+ ranked: Option<i32>,
64
+ #[serde(default)]
65
+ last_updated: Option<String>,
66
+ #[serde(default)]
67
+ beatmaps: Option<Vec<NerinyanBeatmap>>,
68
+ }
69
+
70
+ #[derive(Clone, Debug, Deserialize)]
71
+ struct NerinyanBeatmap {
72
+ #[serde(default)]
73
+ mode_int: Option<u8>,
74
+ #[serde(default)]
75
+ mode: Option<String>,
76
+ }
77
+
78
+ pub struct NerinyanSearch {
79
+ client: Client,
80
+ limiter: RateLimited,
81
+ }
82
+
83
+ impl NerinyanSearch {
84
+ pub fn new(ctx: &DiscoverContext) -> Self {
85
+ Self {
86
+ client: ctx.client.clone(),
87
+ limiter: ctx.limiters.nerinyan.clone(),
88
+ }
89
+ }
90
+ }
91
+
92
+ #[async_trait]
93
+ impl MirrorSearch for NerinyanSearch {
94
+ fn name(&self) -> &str {
95
+ NAME
96
+ }
97
+
98
+ fn supports_status_filter(&self) -> bool {
99
+ true
100
+ }
101
+
102
+ async fn search_page(
103
+ &self,
104
+ status: Option<RankedStatus>,
105
+ mode: u8,
106
+ cursor: Option<&PageCursor>,
107
+ ) -> Result<SearchPage, MirrorSearchError> {
108
+ self.limiter.acquire().await;
109
+
110
+ let mut req = self.client.get(BASE).query(&[
111
+ ("mode", mode.to_string()),
112
+ ("limit", PAGE_LIMIT.to_string()),
113
+ ("sort", "ranked_date".to_string()),
114
+ ("order", "desc".to_string()),
115
+ ]);
116
+ if let Some(s) = status {
117
+ req = req.query(&[("status", s.as_api_str())]);
118
+ }
119
+ if let Some(PageCursor::Opaque(c)) = cursor {
120
+ req = req.query(&[("cursor_string", c.as_str())]);
121
+ }
122
+
123
+ let resp = req.send().await.map_err(|e| MirrorSearchError::Network {
124
+ mirror: NAME.into(),
125
+ source: e,
126
+ })?;
127
+ let bytes = response_bytes(NAME, resp).await?;
128
+ let parsed: NerinyanSearchResp = decode_json(NAME, &bytes)?;
129
+
130
+ let mut entries = Vec::with_capacity(parsed.beatmapsets.len());
131
+ for raw in &parsed.beatmapsets {
132
+ if let Some(e) = parse_entry(raw, status) {
133
+ entries.push(e);
134
+ }
135
+ }
136
+ let next = parsed
137
+ .cursor
138
+ .and_then(|c| c.cursor_string)
139
+ .filter(|s| !s.is_empty())
140
+ .map(PageCursor::Opaque);
141
+ debug!(
142
+ mirror = NAME,
143
+ entries = entries.len(),
144
+ cursor_present = next.is_some(),
145
+ "nerinyan page parsed"
146
+ );
147
+ Ok(SearchPage {
148
+ entries,
149
+ next_cursor: next,
150
+ })
151
+ }
152
+ }
153
+
154
+ /// Project a raw Nerinyan record into our `DiscoveryEntry`. Drops entries we
155
+ /// can't classify (no status, status not in our wanted set) — the aggregator
156
+ /// only deals with sets that *could* be promoted.
157
+ fn parse_entry(raw: &NerinyanSet, expected: Option<RankedStatus>) -> Option<DiscoveryEntry> {
158
+ let status = derive_status(raw)?;
159
+ // Defense in depth: the request asked for `expected`, but the server
160
+ // sometimes returns a slightly different status due to a recent rerank.
161
+ // We accept whatever the mirror reports; the aggregator filters again.
162
+ let _ = expected;
163
+ let has_osu_std = match &raw.beatmaps {
164
+ Some(diffs) => diffs.iter().any(|d| {
165
+ d.mode_int.map(|m| m == 0).unwrap_or(false)
166
+ || d.mode.as_deref().map(|s| s == "osu").unwrap_or(false)
167
+ }),
168
+ // No per-difficulty info: we can't prove osu! standard, so skip.
169
+ // The shape will almost always include `beatmaps`; a missing value
170
+ // means an old or partial cache row we don't trust.
171
+ None => return None,
172
+ };
173
+ if !has_osu_std {
174
+ // Taiko / catch / mania-only sets are real beatmapsets but not part
175
+ // of the osu! standard dataset. Returning None here keeps the
176
+ // `mirror_discoveries` table free of rows that would never meet
177
+ // quorum on `has_osu_std = 1`.
178
+ return None;
179
+ }
180
+ Some(DiscoveryEntry {
181
+ set_id: raw.id,
182
+ claimed_status: status,
183
+ has_osu_std,
184
+ mirror_last_updated: raw.last_updated.clone(),
185
+ })
186
+ }
187
+
188
+ /// Convert Nerinyan's status fields to our internal `RankedStatus`. Prefers
189
+ /// the text field, falls back to the numeric `ranked`. Returns `None` for
190
+ /// statuses we don't track (graveyard / wip / pending — those don't have
191
+ /// leaderboards and aren't part of the dataset).
192
+ fn derive_status(raw: &NerinyanSet) -> Option<RankedStatus> {
193
+ if let Some(text) = raw.status.as_deref() {
194
+ return match text {
195
+ "ranked" => Some(RankedStatus::Ranked),
196
+ "approved" => Some(RankedStatus::Approved),
197
+ "loved" => Some(RankedStatus::Loved),
198
+ "qualified" => Some(RankedStatus::Qualified),
199
+ _ => None,
200
+ };
201
+ }
202
+ match raw.ranked {
203
+ Some(1) => Some(RankedStatus::Ranked),
204
+ Some(2) => Some(RankedStatus::Approved),
205
+ Some(3) => Some(RankedStatus::Qualified),
206
+ Some(4) => Some(RankedStatus::Loved),
207
+ _ => None,
208
+ }
209
+ }
210
+
211
+ #[cfg(test)]
212
+ mod tests {
213
+ use super::*;
214
+
215
+ #[test]
216
+ fn parses_typical_v2_response() {
217
+ let body = r#"{
218
+ "beatmapsets":[
219
+ {"id":2504431,"status":"ranked","ranked":1,
220
+ "last_updated":"2026-04-24T08:38:16Z",
221
+ "beatmaps":[{"id":1,"mode":"osu","mode_int":0}]},
222
+ {"id":1366006,"status":"loved","ranked":4,
223
+ "last_updated":"2026-04-15T16:51:26Z",
224
+ "beatmaps":[{"id":2,"mode":"osu","mode_int":0}]}
225
+ ],
226
+ "cursor":{"approved_date":"...","id":1366006,"cursor_string":"[1776262922000]"},
227
+ "total":1183
228
+ }"#;
229
+ let parsed: NerinyanSearchResp = serde_json::from_str(body).unwrap();
230
+ assert_eq!(parsed.beatmapsets.len(), 2);
231
+ let e0 = parse_entry(&parsed.beatmapsets[0], None).unwrap();
232
+ assert_eq!(e0.set_id, 2504431);
233
+ assert_eq!(e0.claimed_status, RankedStatus::Ranked);
234
+ assert!(e0.has_osu_std);
235
+ let e1 = parse_entry(&parsed.beatmapsets[1], None).unwrap();
236
+ assert_eq!(e1.claimed_status, RankedStatus::Loved);
237
+ assert_eq!(
238
+ parsed.cursor.unwrap().cursor_string.unwrap(),
239
+ "[1776262922000]"
240
+ );
241
+ }
242
+
243
+ #[test]
244
+ fn drops_sets_without_osu_standard_difficulty() {
245
+ let body = r#"{
246
+ "beatmapsets":[
247
+ {"id":1,"status":"ranked","ranked":1,
248
+ "beatmaps":[{"mode":"taiko","mode_int":1}]}
249
+ ],
250
+ "cursor":null
251
+ }"#;
252
+ let parsed: NerinyanSearchResp = serde_json::from_str(body).unwrap();
253
+ assert!(
254
+ parse_entry(&parsed.beatmapsets[0], None).is_none(),
255
+ "set with only taiko diffs must be filtered out"
256
+ );
257
+ }
258
+
259
+ #[test]
260
+ fn drops_sets_with_unwanted_status() {
261
+ // graveyard and pending are not tracked; we don't want to record
262
+ // discoveries for them, otherwise the aggregator would see ghost
263
+ // sets every time a mirror returns recent submissions.
264
+ let body = r#"{
265
+ "beatmapsets":[
266
+ {"id":1,"status":"graveyard","ranked":-2,
267
+ "beatmaps":[{"mode":"osu","mode_int":0}]},
268
+ {"id":2,"status":"pending","ranked":0,
269
+ "beatmaps":[{"mode":"osu","mode_int":0}]}
270
+ ],
271
+ "cursor":null
272
+ }"#;
273
+ let parsed: NerinyanSearchResp = serde_json::from_str(body).unwrap();
274
+ assert!(parse_entry(&parsed.beatmapsets[0], None).is_none());
275
+ assert!(parse_entry(&parsed.beatmapsets[1], None).is_none());
276
+ }
277
+
278
+ #[test]
279
+ fn falls_back_to_numeric_status_when_text_missing() {
280
+ let body = r#"{
281
+ "beatmapsets":[
282
+ {"id":42,"ranked":4,
283
+ "beatmaps":[{"mode_int":0}]}
284
+ ],
285
+ "cursor":null
286
+ }"#;
287
+ let parsed: NerinyanSearchResp = serde_json::from_str(body).unwrap();
288
+ let e = parse_entry(&parsed.beatmapsets[0], None).unwrap();
289
+ assert_eq!(e.claimed_status, RankedStatus::Loved);
290
+ }
291
+
292
+ #[test]
293
+ fn no_cursor_in_response_means_pagination_done() {
294
+ let body = r#"{"beatmapsets":[],"cursor":null}"#;
295
+ let parsed: NerinyanSearchResp = serde_json::from_str(body).unwrap();
296
+ let cur = parsed
297
+ .cursor
298
+ .and_then(|c| c.cursor_string)
299
+ .filter(|s| !s.is_empty());
300
+ assert!(cur.is_none());
301
+ }
302
+
303
+ #[test]
304
+ fn empty_cursor_string_is_treated_as_done() {
305
+ // Some Nerinyan responses include `"cursor":{"cursor_string":""}`
306
+ // at the end of pagination. Our walker must treat that as exhausted,
307
+ // not loop forever on the empty string.
308
+ let body = r#"{"beatmapsets":[],"cursor":{"cursor_string":""}}"#;
309
+ let parsed: NerinyanSearchResp = serde_json::from_str(body).unwrap();
310
+ let cur = parsed
311
+ .cursor
312
+ .and_then(|c| c.cursor_string)
313
+ .filter(|s| !s.is_empty());
314
+ assert!(cur.is_none());
315
+ }
316
+ }
crates/osu_fetcher/src/discover/osudirect.rs ADDED
@@ -0,0 +1,303 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //! osu.direct v2 search — discovery surface.
2
+ //!
3
+ //! Endpoint: `GET https://osu.direct/api/v2/search`
4
+ //!
5
+ //! Live spec (April 2026, confirmed against the running service):
6
+ //! * `status` — **numeric**: 1=ranked, 2=approved, 3=qualified, 4=loved
7
+ //! (matches osu! API integer mapping). Text values are rejected with
8
+ //! `403 status is not a valid number`.
9
+ //! * `mode` — **numeric**: 0=osu, 1=taiko, 2=catch, 3=mania.
10
+ //! * `amount` — page size (max 100 in practice).
11
+ //! * `offset` — skip-N pagination.
12
+ //!
13
+ //! Response is a bare JSON array (not wrapped in an envelope), each entry a
14
+ //! beatmapset with `id`, `status`, `ranked`, `last_updated`, `last_checked`
15
+ //! (when osu.direct last verified the set against the official API), and a
16
+ //! `beatmaps[]` with `mode_int`. The `last_checked` field is unique among
17
+ //! mirrors and lets us reason about staleness — old `last_checked` values
18
+ //! mean the mirror's view may be out of date.
19
+ //!
20
+ //! Rate limit: response carries `RateLimit-Limit: 120` (Cloudflare). The CLI
21
+ //! default is currently 480 rpm for update speed; lower it if this endpoint
22
+ //! starts returning 429s.
23
+
24
+ use async_trait::async_trait;
25
+ use reqwest::Client;
26
+ use serde::Deserialize;
27
+ use tracing::debug;
28
+
29
+ use super::{
30
+ decode_json, response_bytes, DiscoverContext, DiscoveryEntry, MirrorSearch, MirrorSearchError,
31
+ MirrorVerify, PageCursor, SearchPage,
32
+ };
33
+ use crate::ratelimit::RateLimited;
34
+ use crate::RankedStatus;
35
+
36
+ pub const NAME: &str = "osudirect";
37
+ const SEARCH_BASE: &str = "https://osu.direct/api/v2/search";
38
+ const SET_BASE: &str = "https://osu.direct/api/v2/s";
39
+ const PAGE_AMOUNT: u32 = 100;
40
+
41
+ #[derive(Clone, Debug, Deserialize)]
42
+ struct OsuDirectSet {
43
+ id: u64,
44
+ #[serde(default)]
45
+ status: Option<String>,
46
+ #[serde(default)]
47
+ ranked: Option<i32>,
48
+ #[serde(default)]
49
+ last_updated: Option<String>,
50
+ #[serde(default)]
51
+ beatmaps: Option<Vec<OsuDirectBeatmap>>,
52
+ }
53
+
54
+ #[derive(Clone, Debug, Deserialize)]
55
+ struct OsuDirectBeatmap {
56
+ #[serde(default)]
57
+ mode_int: Option<u8>,
58
+ #[serde(default)]
59
+ mode: Option<String>,
60
+ }
61
+
62
+ pub struct OsuDirectSearch {
63
+ client: Client,
64
+ limiter: RateLimited,
65
+ }
66
+
67
+ impl OsuDirectSearch {
68
+ pub fn new(ctx: &DiscoverContext) -> Self {
69
+ Self {
70
+ client: ctx.client.clone(),
71
+ limiter: ctx.limiters.osudirect.clone(),
72
+ }
73
+ }
74
+
75
+ /// Numeric status param expected by `/api/v2/search`. The mirror returns
76
+ /// 403 for any non-integer, so we map our enum directly to its osu! API
77
+ /// integer.
78
+ fn status_int(s: RankedStatus) -> u8 {
79
+ match s {
80
+ RankedStatus::Ranked => 1,
81
+ RankedStatus::Approved => 2,
82
+ RankedStatus::Qualified => 3,
83
+ RankedStatus::Loved => 4,
84
+ }
85
+ }
86
+ }
87
+
88
+ #[async_trait]
89
+ impl MirrorSearch for OsuDirectSearch {
90
+ fn name(&self) -> &str {
91
+ NAME
92
+ }
93
+
94
+ fn supports_status_filter(&self) -> bool {
95
+ true
96
+ }
97
+
98
+ async fn search_page(
99
+ &self,
100
+ status: Option<RankedStatus>,
101
+ mode: u8,
102
+ cursor: Option<&PageCursor>,
103
+ ) -> Result<SearchPage, MirrorSearchError> {
104
+ self.limiter.acquire().await;
105
+
106
+ let offset = match cursor {
107
+ Some(PageCursor::Offset(n)) => *n,
108
+ Some(PageCursor::Opaque(_)) => 0, // wrong cursor variant; restart
109
+ None => 0,
110
+ };
111
+
112
+ // osu.direct rejects text statuses with HTTP 403 — always send the
113
+ // integer. When `status` is None the mirror returns "all", which is
114
+ // fine for callers that don't care.
115
+ let status_int = status.map(Self::status_int);
116
+ let mut req = self.client.get(SEARCH_BASE).query(&[
117
+ ("mode", mode.to_string()),
118
+ ("amount", PAGE_AMOUNT.to_string()),
119
+ ("offset", offset.to_string()),
120
+ ]);
121
+ if let Some(s) = status_int {
122
+ req = req.query(&[("status", s.to_string())]);
123
+ }
124
+
125
+ let resp = req.send().await.map_err(|e| MirrorSearchError::Network {
126
+ mirror: NAME.into(),
127
+ source: e,
128
+ })?;
129
+ let bytes = response_bytes(NAME, resp).await?;
130
+ let parsed: Vec<OsuDirectSet> = decode_json(NAME, &bytes)?;
131
+
132
+ let count = parsed.len() as u32;
133
+ let entries: Vec<_> = parsed.iter().filter_map(parse_entry).collect();
134
+
135
+ // Offset-based pagination is exhausted when a page returns fewer
136
+ // rows than the page size we asked for. Adding one more would just
137
+ // return [] and waste a round-trip.
138
+ let next_cursor = if count >= PAGE_AMOUNT {
139
+ Some(PageCursor::Offset(offset + PAGE_AMOUNT as u64))
140
+ } else {
141
+ None
142
+ };
143
+ debug!(
144
+ mirror = NAME,
145
+ offset,
146
+ entries = entries.len(),
147
+ raw = count,
148
+ "osudirect page parsed"
149
+ );
150
+ Ok(SearchPage {
151
+ entries,
152
+ next_cursor,
153
+ })
154
+ }
155
+ }
156
+
157
+ pub struct OsuDirectVerify {
158
+ client: Client,
159
+ limiter: RateLimited,
160
+ }
161
+
162
+ impl OsuDirectVerify {
163
+ pub fn new(ctx: &DiscoverContext) -> Self {
164
+ Self {
165
+ client: ctx.client.clone(),
166
+ limiter: ctx.limiters.osudirect.clone(),
167
+ }
168
+ }
169
+ }
170
+
171
+ #[async_trait]
172
+ impl MirrorVerify for OsuDirectVerify {
173
+ fn name(&self) -> &str {
174
+ NAME
175
+ }
176
+
177
+ async fn verify_set(&self, set_id: u64) -> Result<Option<DiscoveryEntry>, MirrorSearchError> {
178
+ self.limiter.acquire().await;
179
+ let url = format!("{SET_BASE}/{set_id}");
180
+ let resp = self
181
+ .client
182
+ .get(&url)
183
+ .send()
184
+ .await
185
+ .map_err(|e| MirrorSearchError::Network {
186
+ mirror: NAME.into(),
187
+ source: e,
188
+ })?;
189
+ if resp.status() == reqwest::StatusCode::NOT_FOUND {
190
+ // Definitive absence — caller treats this as a vote *against*.
191
+ return Ok(None);
192
+ }
193
+ let bytes = response_bytes(NAME, resp).await?;
194
+ let parsed: OsuDirectSet = decode_json(NAME, &bytes)?;
195
+ Ok(parse_entry(&parsed))
196
+ }
197
+ }
198
+
199
+ fn parse_entry(raw: &OsuDirectSet) -> Option<DiscoveryEntry> {
200
+ let status = derive_status(raw)?;
201
+ let has_osu_std = match &raw.beatmaps {
202
+ Some(diffs) => diffs.iter().any(|d| {
203
+ d.mode_int.map(|m| m == 0).unwrap_or(false)
204
+ || d.mode.as_deref().map(|s| s == "osu").unwrap_or(false)
205
+ }),
206
+ None => return None,
207
+ };
208
+ if !has_osu_std {
209
+ return None;
210
+ }
211
+ Some(DiscoveryEntry {
212
+ set_id: raw.id,
213
+ claimed_status: status,
214
+ has_osu_std,
215
+ mirror_last_updated: raw.last_updated.clone(),
216
+ })
217
+ }
218
+
219
+ fn derive_status(raw: &OsuDirectSet) -> Option<RankedStatus> {
220
+ if let Some(text) = raw.status.as_deref() {
221
+ return match text {
222
+ "ranked" => Some(RankedStatus::Ranked),
223
+ "approved" => Some(RankedStatus::Approved),
224
+ "loved" => Some(RankedStatus::Loved),
225
+ "qualified" => Some(RankedStatus::Qualified),
226
+ _ => None,
227
+ };
228
+ }
229
+ match raw.ranked {
230
+ Some(1) => Some(RankedStatus::Ranked),
231
+ Some(2) => Some(RankedStatus::Approved),
232
+ Some(3) => Some(RankedStatus::Qualified),
233
+ Some(4) => Some(RankedStatus::Loved),
234
+ _ => None,
235
+ }
236
+ }
237
+
238
+ #[cfg(test)]
239
+ mod tests {
240
+ use super::*;
241
+
242
+ #[test]
243
+ fn status_int_matches_osu_api_integers() {
244
+ assert_eq!(OsuDirectSearch::status_int(RankedStatus::Ranked), 1);
245
+ assert_eq!(OsuDirectSearch::status_int(RankedStatus::Approved), 2);
246
+ assert_eq!(OsuDirectSearch::status_int(RankedStatus::Qualified), 3);
247
+ assert_eq!(OsuDirectSearch::status_int(RankedStatus::Loved), 4);
248
+ }
249
+
250
+ #[test]
251
+ fn parses_array_response() {
252
+ // The endpoint returns a bare array (no envelope).
253
+ let body = r#"[
254
+ {"id":2303912,"status":"ranked","ranked":1,
255
+ "last_updated":"2026-04-20T08:16:27Z",
256
+ "beatmaps":[{"mode":"osu","mode_int":0}]}
257
+ ]"#;
258
+ let parsed: Vec<OsuDirectSet> = serde_json::from_str(body).unwrap();
259
+ let e = parse_entry(&parsed[0]).unwrap();
260
+ assert_eq!(e.set_id, 2303912);
261
+ assert_eq!(e.claimed_status, RankedStatus::Ranked);
262
+ assert!(e.has_osu_std);
263
+ }
264
+
265
+ #[test]
266
+ fn drops_taiko_only_set() {
267
+ let body = r#"[
268
+ {"id":1,"status":"ranked","ranked":1,
269
+ "beatmaps":[{"mode":"taiko","mode_int":1}]}
270
+ ]"#;
271
+ let parsed: Vec<OsuDirectSet> = serde_json::from_str(body).unwrap();
272
+ assert!(parse_entry(&parsed[0]).is_none());
273
+ }
274
+
275
+ #[test]
276
+ fn cursor_advances_by_page_size_until_short_page() {
277
+ // Simulate the boundary the search loop would hit. A page of
278
+ // PAGE_AMOUNT entries means "ask for the next slice"; a page below
279
+ // that means "we've reached the end".
280
+ let full = (0..PAGE_AMOUNT).count() as u32;
281
+ assert!(full >= PAGE_AMOUNT);
282
+ let partial = (0..50).count() as u32;
283
+ assert!(partial < PAGE_AMOUNT);
284
+ }
285
+
286
+ #[test]
287
+ fn unknown_status_text_does_not_panic() {
288
+ let raw = OsuDirectSet {
289
+ id: 1,
290
+ status: Some("some-future-status".into()),
291
+ ranked: None,
292
+ last_updated: None,
293
+ beatmaps: Some(vec![OsuDirectBeatmap {
294
+ mode_int: Some(0),
295
+ mode: None,
296
+ }]),
297
+ };
298
+ assert!(
299
+ parse_entry(&raw).is_none(),
300
+ "unknown status text should drop the entry gracefully"
301
+ );
302
+ }
303
+ }
crates/osu_fetcher/src/discover/sayobot.rs ADDED
@@ -0,0 +1,448 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //! Sayobot beatmaplist — discovery surface.
2
+ //!
3
+ //! Endpoint: `GET https://api.sayobot.cn/beatmaplist`
4
+ //!
5
+ //! Live behaviour (April 2026):
6
+ //! * `T` — list type. `T=4` is "newest by ranked_date desc" — the most
7
+ //! useful for catching recently added ranked/loved sets.
8
+ //! * `L` — page limit (max ~100 in practice).
9
+ //! * `O` — offset.
10
+ //! * `M` — mode bitmask: `1=osu`, `2=taiko`, `4=catch`, `8=mania`,
11
+ //! bitwise-OR for combinations. `M=1` returns sets that include osu!
12
+ //! standard.
13
+ //! * `R` — *advertised* status mask, but probing shows the server returns
14
+ //! identical results for `R=1..32`. We treat status filtering as
15
+ //! **client-side** and rely on each row's `approved` field.
16
+ //!
17
+ //! Response:
18
+ //! ```json
19
+ //! {"data":[{"sid":<set_id>,"approved":<-2..4>,"modes":<bitmask>,
20
+ //! "lastupdate":<unix_sec>, ...}], "endid":<int>, "status":0}
21
+ //! ```
22
+ //! `endid` is a server-side cursor that we don't fully understand (a small
23
+ //! integer like 26, not a row id). We use plain `O=offset` pagination
24
+ //! instead — predictable and cursor-format independent.
25
+ //!
26
+ //! Per-set verifier endpoint: `/v2/beatmapinfo?K=<set_id>&T=1` returns full
27
+ //! difficulty info (incl. mode per beatmap).
28
+
29
+ use async_trait::async_trait;
30
+ use reqwest::Client;
31
+ use serde::Deserialize;
32
+ use tracing::debug;
33
+
34
+ use super::{
35
+ decode_json, response_bytes, DiscoverContext, DiscoveryEntry, MirrorSearch, MirrorSearchError,
36
+ MirrorVerify, PageCursor, SearchPage,
37
+ };
38
+ use crate::ratelimit::RateLimited;
39
+ use crate::RankedStatus;
40
+
41
+ pub const NAME: &str = "sayobot";
42
+ const LIST_BASE: &str = "https://api.sayobot.cn/beatmaplist";
43
+ const INFO_BASE: &str = "https://api.sayobot.cn/v2/beatmapinfo";
44
+ const PAGE_LIMIT: u32 = 100;
45
+ /// Mode bit for osu! standard — bit 0.
46
+ const MODE_BIT_STD: u32 = 1;
47
+
48
+ #[derive(Clone, Debug, Deserialize)]
49
+ struct SayobotListResp {
50
+ #[serde(default)]
51
+ data: Vec<SayobotListEntry>,
52
+ /// Server-reported error code: `0` is OK, `-1` (and others) indicate
53
+ /// the server rejected something (e.g. wrong mode bitmask). We log it
54
+ /// and return an empty page rather than raise — Sayobot does this for
55
+ /// arguably-valid queries and we don't want a single mirror's quirk to
56
+ /// poison `discover_all`.
57
+ #[serde(default)]
58
+ status: i32,
59
+ }
60
+
61
+ #[derive(Clone, Debug, Deserialize)]
62
+ struct SayobotListEntry {
63
+ sid: u64,
64
+ /// osu!-API-style approved code: -2=graveyard, -1=wip, 0=pending,
65
+ /// 1=ranked, 2=approved, 3=qualified, 4=loved.
66
+ approved: i32,
67
+ /// Bitmask of modes the set contains. Bit 0 = osu!std.
68
+ #[serde(default)]
69
+ modes: u32,
70
+ /// Unix seconds. Converted to ISO 8601 for storage.
71
+ #[serde(default)]
72
+ lastupdate: Option<i64>,
73
+ }
74
+
75
+ #[derive(Clone, Debug, Deserialize)]
76
+ struct SayobotInfoResp {
77
+ #[serde(default)]
78
+ data: Option<SayobotInfo>,
79
+ #[serde(default)]
80
+ status: i32,
81
+ }
82
+
83
+ #[derive(Clone, Debug, Deserialize)]
84
+ struct SayobotInfo {
85
+ #[serde(default)]
86
+ approved: i32,
87
+ #[serde(default)]
88
+ last_update: Option<i64>,
89
+ /// Per-difficulty array; each entry has a `mode` (0..3) integer.
90
+ #[serde(default)]
91
+ bid_data: Vec<SayobotInfoBid>,
92
+ }
93
+
94
+ #[derive(Clone, Debug, Deserialize)]
95
+ struct SayobotInfoBid {
96
+ #[serde(default)]
97
+ mode: u8,
98
+ }
99
+
100
+ pub struct SayobotSearch {
101
+ client: Client,
102
+ limiter: RateLimited,
103
+ }
104
+
105
+ impl SayobotSearch {
106
+ pub fn new(ctx: &DiscoverContext) -> Self {
107
+ Self {
108
+ client: ctx.client.clone(),
109
+ limiter: ctx.limiters.sayobot.clone(),
110
+ }
111
+ }
112
+ }
113
+
114
+ #[async_trait]
115
+ impl MirrorSearch for SayobotSearch {
116
+ fn name(&self) -> &str {
117
+ NAME
118
+ }
119
+
120
+ fn supports_status_filter(&self) -> bool {
121
+ // Server-side `R` mask is unreliable on the public endpoint —
122
+ // every value we tested returned the same result. We filter by
123
+ // `approved` client-side instead.
124
+ false
125
+ }
126
+
127
+ async fn search_page(
128
+ &self,
129
+ _status: Option<RankedStatus>,
130
+ mode: u8,
131
+ cursor: Option<&PageCursor>,
132
+ ) -> Result<SearchPage, MirrorSearchError> {
133
+ self.limiter.acquire().await;
134
+
135
+ let offset = match cursor {
136
+ Some(PageCursor::Offset(n)) => *n,
137
+ Some(PageCursor::Opaque(_)) => 0,
138
+ None => 0,
139
+ };
140
+ // Build mode bitmask from the integer mode_int. Out-of-range modes
141
+ // fall back to "osu! standard included" so we still get a page.
142
+ let mode_mask = mode_int_to_bitmask(mode);
143
+
144
+ let req = self.client.get(LIST_BASE).query(&[
145
+ ("T", 4u32.to_string()), // newest by ranked_date desc
146
+ ("L", PAGE_LIMIT.to_string()),
147
+ ("O", offset.to_string()),
148
+ ("M", mode_mask.to_string()),
149
+ ]);
150
+ let resp = req.send().await.map_err(|e| MirrorSearchError::Network {
151
+ mirror: NAME.into(),
152
+ source: e,
153
+ })?;
154
+ let bytes = response_bytes(NAME, resp).await?;
155
+ let parsed: SayobotListResp = decode_json(NAME, &bytes)?;
156
+
157
+ if parsed.status != 0 {
158
+ // Server rejected the query. Don't panic: log and return empty
159
+ // so the higher-level walk treats it as exhausted for this
160
+ // status. The aggregator will rely on the other mirrors.
161
+ debug!(
162
+ mirror = NAME,
163
+ server_status = parsed.status,
164
+ "sayobot returned non-zero status; treating as empty page"
165
+ );
166
+ return Ok(SearchPage::default());
167
+ }
168
+
169
+ let raw_count = parsed.data.len() as u32;
170
+ let entries: Vec<_> = parsed.data.iter().filter_map(parse_entry).collect();
171
+
172
+ let next_cursor = if raw_count >= PAGE_LIMIT {
173
+ Some(PageCursor::Offset(offset + PAGE_LIMIT as u64))
174
+ } else {
175
+ None
176
+ };
177
+ debug!(
178
+ mirror = NAME,
179
+ offset,
180
+ raw = raw_count,
181
+ entries = entries.len(),
182
+ "sayobot page parsed"
183
+ );
184
+ Ok(SearchPage {
185
+ entries,
186
+ next_cursor,
187
+ })
188
+ }
189
+ }
190
+
191
+ pub struct SayobotVerify {
192
+ client: Client,
193
+ limiter: RateLimited,
194
+ }
195
+
196
+ impl SayobotVerify {
197
+ pub fn new(ctx: &DiscoverContext) -> Self {
198
+ Self {
199
+ client: ctx.client.clone(),
200
+ limiter: ctx.limiters.sayobot.clone(),
201
+ }
202
+ }
203
+ }
204
+
205
+ #[async_trait]
206
+ impl MirrorVerify for SayobotVerify {
207
+ fn name(&self) -> &str {
208
+ NAME
209
+ }
210
+
211
+ async fn verify_set(&self, set_id: u64) -> Result<Option<DiscoveryEntry>, MirrorSearchError> {
212
+ self.limiter.acquire().await;
213
+ let req = self
214
+ .client
215
+ .get(INFO_BASE)
216
+ .query(&[("K", set_id.to_string()), ("T", 1u32.to_string())]);
217
+ let resp = req.send().await.map_err(|e| MirrorSearchError::Network {
218
+ mirror: NAME.into(),
219
+ source: e,
220
+ })?;
221
+ let bytes = response_bytes(NAME, resp).await?;
222
+ let parsed: SayobotInfoResp = decode_json(NAME, &bytes)?;
223
+
224
+ if parsed.status != 0 {
225
+ // Sayobot reports `-1` for non-existent sets (no separate 404).
226
+ return Ok(None);
227
+ }
228
+ let info = match parsed.data {
229
+ Some(d) => d,
230
+ None => return Ok(None),
231
+ };
232
+ let status = match info.approved {
233
+ 1 => RankedStatus::Ranked,
234
+ 2 => RankedStatus::Approved,
235
+ 3 => RankedStatus::Qualified,
236
+ 4 => RankedStatus::Loved,
237
+ _ => return Ok(None),
238
+ };
239
+ let has_osu_std = info.bid_data.iter().any(|b| b.mode == 0);
240
+ if !has_osu_std {
241
+ return Ok(None);
242
+ }
243
+ Ok(Some(DiscoveryEntry {
244
+ set_id,
245
+ claimed_status: status,
246
+ has_osu_std,
247
+ mirror_last_updated: info.last_update.map(unix_sec_to_iso),
248
+ }))
249
+ }
250
+ }
251
+
252
+ fn parse_entry(raw: &SayobotListEntry) -> Option<DiscoveryEntry> {
253
+ let status = match raw.approved {
254
+ 1 => RankedStatus::Ranked,
255
+ 2 => RankedStatus::Approved,
256
+ 3 => RankedStatus::Qualified,
257
+ 4 => RankedStatus::Loved,
258
+ _ => return None,
259
+ };
260
+ if raw.modes & MODE_BIT_STD == 0 {
261
+ return None;
262
+ }
263
+ Some(DiscoveryEntry {
264
+ set_id: raw.sid,
265
+ claimed_status: status,
266
+ has_osu_std: true,
267
+ mirror_last_updated: raw.lastupdate.map(unix_sec_to_iso),
268
+ })
269
+ }
270
+
271
+ /// Map an osu! API-style mode integer to Sayobot's mode bitmask. Sayobot
272
+ /// expects exactly one of the bits set when filtering by a specific mode;
273
+ /// out-of-range inputs fall back to "include osu! std" so we still return
274
+ /// rows the aggregator can use.
275
+ fn mode_int_to_bitmask(mode_int: u8) -> u32 {
276
+ match mode_int {
277
+ 0 => 1, // osu!
278
+ 1 => 2, // taiko
279
+ 2 => 4, // catch
280
+ 3 => 8, // mania
281
+ _ => MODE_BIT_STD,
282
+ }
283
+ }
284
+
285
+ /// Convert unix seconds to RFC3339 / ISO 8601 (`YYYY-MM-DDThh:mm:ssZ`).
286
+ /// Sayobot stores epoch seconds; every other source stores ISO. We
287
+ /// normalize on write so the `mirror_discoveries` table holds one format
288
+ /// for human inspection and lex-comparable ordering.
289
+ ///
290
+ /// Date arithmetic uses Hinnant's "days since civil epoch" algorithm
291
+ /// (public domain) — handles negative inputs and any year up to ~9999
292
+ /// correctly without pulling chrono / time as a dependency.
293
+ fn unix_sec_to_iso(secs: i64) -> String {
294
+ let day_seconds: i64 = 86400;
295
+ let mut days = secs.div_euclid(day_seconds);
296
+ let mut rem = secs.rem_euclid(day_seconds);
297
+ if rem < 0 {
298
+ rem += day_seconds;
299
+ days -= 1;
300
+ }
301
+ let h = rem / 3600;
302
+ let m = (rem % 3600) / 60;
303
+ let s = rem % 60;
304
+ let (y, mo, d) = days_to_ymd(days);
305
+ format!("{y:04}-{mo:02}-{d:02}T{h:02}:{m:02}:{s:02}Z")
306
+ }
307
+
308
+ /// Days since Unix epoch (1970-01-01) → (year, month, day). Howard
309
+ /// Hinnant's `civil_from_days` algorithm; valid for the entire signed
310
+ /// 64-bit range we'd ever see.
311
+ fn days_to_ymd(days: i64) -> (i64, u32, u32) {
312
+ let z = days + 719468;
313
+ let era = z.div_euclid(146097);
314
+ let doe = z.rem_euclid(146097) as u64;
315
+ let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
316
+ let y = yoe as i64 + era * 400;
317
+ let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
318
+ let mp = (5 * doy + 2) / 153;
319
+ let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
320
+ let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
321
+ let y = if m <= 2 { y + 1 } else { y };
322
+ (y, m, d)
323
+ }
324
+
325
+ #[cfg(test)]
326
+ mod tests {
327
+ use super::*;
328
+
329
+ #[test]
330
+ fn parses_typical_list_response() {
331
+ let body = r#"{
332
+ "data":[
333
+ {"sid":2540534,"approved":1,"modes":1,"lastupdate":1776440408,
334
+ "title":"x","artist":"y","creator":"z","favourite_count":15,"play_count":1,"order":0,"titleU":"","artistU":""},
335
+ {"sid":2542796,"approved":3,"modes":1,"lastupdate":1777195153,
336
+ "title":"x","artist":"y","creator":"z","favourite_count":1,"play_count":1,"order":0,"titleU":"","artistU":""}
337
+ ],
338
+ "endid":4,
339
+ "status":0
340
+ }"#;
341
+ let parsed: SayobotListResp = serde_json::from_str(body).unwrap();
342
+ assert_eq!(parsed.status, 0);
343
+ let e0 = parse_entry(&parsed.data[0]).unwrap();
344
+ assert_eq!(e0.set_id, 2540534);
345
+ assert_eq!(e0.claimed_status, RankedStatus::Ranked);
346
+ assert!(e0.has_osu_std);
347
+ let e1 = parse_entry(&parsed.data[1]).unwrap();
348
+ assert_eq!(e1.claimed_status, RankedStatus::Qualified);
349
+ }
350
+
351
+ #[test]
352
+ fn drops_taiko_only_set_via_modes_bitmask() {
353
+ let raw = SayobotListEntry {
354
+ sid: 1,
355
+ approved: 1,
356
+ modes: 2, // taiko bit, no osu!
357
+ lastupdate: None,
358
+ };
359
+ assert!(parse_entry(&raw).is_none());
360
+ }
361
+
362
+ #[test]
363
+ fn keeps_set_with_multiple_modes_when_osu_bit_is_set() {
364
+ let raw = SayobotListEntry {
365
+ sid: 99,
366
+ approved: 4,
367
+ modes: 1 | 2 | 8, // osu+taiko+mania
368
+ lastupdate: Some(1700000000),
369
+ };
370
+ let e = parse_entry(&raw).unwrap();
371
+ assert_eq!(e.claimed_status, RankedStatus::Loved);
372
+ assert!(e.has_osu_std);
373
+ }
374
+
375
+ #[test]
376
+ fn drops_graveyard_pending_wip() {
377
+ for code in [-2, -1, 0] {
378
+ let raw = SayobotListEntry {
379
+ sid: 1,
380
+ approved: code,
381
+ modes: 1,
382
+ lastupdate: None,
383
+ };
384
+ assert!(parse_entry(&raw).is_none(), "code {code} should be dropped");
385
+ }
386
+ }
387
+
388
+ #[test]
389
+ fn server_status_nonzero_returns_empty_page_in_decode() {
390
+ // The walker calls search_page; if the JSON shape parsed but the
391
+ // server returned status=-1, we expect the parser to expose that.
392
+ let body = r#"{"data":[],"endid":0,"status":-1}"#;
393
+ let parsed: SayobotListResp = serde_json::from_str(body).unwrap();
394
+ assert_eq!(parsed.status, -1);
395
+ assert!(parsed.data.is_empty());
396
+ }
397
+
398
+ #[test]
399
+ fn mode_int_to_bitmask_covers_known_modes() {
400
+ assert_eq!(mode_int_to_bitmask(0), 1);
401
+ assert_eq!(mode_int_to_bitmask(1), 2);
402
+ assert_eq!(mode_int_to_bitmask(2), 4);
403
+ assert_eq!(mode_int_to_bitmask(3), 8);
404
+ // Out-of-range falls back to osu!std so we still get rows.
405
+ assert_eq!(mode_int_to_bitmask(99), 1);
406
+ }
407
+
408
+ #[test]
409
+ fn unix_sec_to_iso_known_values() {
410
+ // Cross-checked with `date -u -d @<sec>`. Pinned here so future
411
+ // edits to `days_to_ymd` can't silently drift.
412
+ assert_eq!(unix_sec_to_iso(0), "1970-01-01T00:00:00Z");
413
+ assert_eq!(unix_sec_to_iso(86400), "1970-01-02T00:00:00Z");
414
+ assert_eq!(unix_sec_to_iso(1700000000), "2023-11-14T22:13:20Z");
415
+ // 2026-04-15T14:51:26Z = epoch 1776264686 (sayobot's `lastupdate`
416
+ // for one of the loved sets we sampled during the integration probe).
417
+ assert_eq!(unix_sec_to_iso(1776264686), "2026-04-15T14:51:26Z");
418
+ // Cross-month boundary: 2024-12-31T23:59:59Z → 1735689599.
419
+ assert_eq!(unix_sec_to_iso(1735689599), "2024-12-31T23:59:59Z");
420
+ // Leap-year day: 2024-02-29T00:00:00Z → 1709164800.
421
+ assert_eq!(unix_sec_to_iso(1709164800), "2024-02-29T00:00:00Z");
422
+ }
423
+
424
+ #[test]
425
+ fn unix_sec_to_iso_handles_negative_input_without_panic() {
426
+ // Very early unix timestamps shouldn't crash the formatter — Sayobot
427
+ // returns -1 for "no value", which is what triggers this path.
428
+ let s = unix_sec_to_iso(-1);
429
+ assert!(s.starts_with("1969-12-31T23:59:59"));
430
+ }
431
+
432
+ #[test]
433
+ fn beatmapinfo_response_decodes_for_existing_set() {
434
+ // Excerpt from the live response for set 2303912 (graveyard, but
435
+ // with osu! difficulties present). The verifier should mark it None
436
+ // because graveyard isn't a tracked status.
437
+ let body = r#"{
438
+ "data":{"approved":-2,"approved_date":-1,
439
+ "bid_data":[{"mode":0,"bid":1,"length":1,"AR":9.4,"CS":4,"HP":4,"OD":9,"audio":"","bg":"","circles":1,"hit300window":0,"img":"0","maxcombo":1,"passcount":1,"playcount":1,"pp":0,"pp_acc":0,"pp_aim":0,"pp_speed":0,"sliders":1,"speed":0,"spinners":0,"star":1,"strain_aim":"","strain_speed":"","version":"x","aim":0}],
440
+ "last_update":1700000000,
441
+ "title":"","artist":"","artistU":"","titleU":"","creator":"","source":"","tags":""},
442
+ "status":0
443
+ }"#;
444
+ let parsed: SayobotInfoResp = serde_json::from_str(body).unwrap();
445
+ assert_eq!(parsed.status, 0);
446
+ assert_eq!(parsed.data.unwrap().approved, -2);
447
+ }
448
+ }
crates/osu_fetcher/src/download.rs ADDED
@@ -0,0 +1,530 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //! `download` subcommand — bounded-concurrency worker pool.
2
+ //!
3
+ //! The orchestration is deliberately small: we spin up a fixed number of
4
+ //! workers (`concurrency` argument), each in a `select!` loop of "claim →
5
+ //! fetch → verify → write → update state". The state DB is the only
6
+ //! synchronization primitive; workers never talk to each other directly.
7
+ //!
8
+ //! Why per-worker `select!` against a shutdown signal: if Ctrl-C arrives
9
+ //! while a worker is mid-HTTP, we let the in-flight request finish (its
10
+ //! result still gets recorded), then bail out before claiming the next set.
11
+ //! That keeps the state DB tidy — no abandoned `in_progress` rows on graceful
12
+ //! shutdown.
13
+ //!
14
+ //! Atomicity on writes: each `.osz` is written to `<id>.osz.partial`, fsynced,
15
+ //! and renamed in place. A crash mid-write leaves a `.partial` file that
16
+ //! `scan` will ignore (it filters on the `.osz` extension). The `.partial`
17
+ //! cleanup is best-effort on the next `download` run via the
18
+ //! [`cleanup_orphan_partials`] helper.
19
+
20
+ use std::path::{Path, PathBuf};
21
+ use std::sync::atomic::{AtomicU64, Ordering};
22
+ use std::sync::Arc;
23
+
24
+ use anyhow::{Context, Result};
25
+ use sha2::{Digest, Sha256};
26
+ use tokio::fs;
27
+ use tokio::io::AsyncWriteExt;
28
+ use tokio::task::JoinSet;
29
+ use tokio_util::sync::CancellationToken;
30
+ use tracing::{debug, error, info, warn};
31
+
32
+ use crate::mirrors::{AttemptObserver, MirrorError, MirrorPool, NoOpObserver};
33
+ use crate::progress::DownloadDashboard;
34
+ use crate::state::{AttemptOutcome as StateOutcome, DownloadFailure, DownloadSuccess, StateDb};
35
+ use crate::Flavor;
36
+
37
+ #[derive(Clone, Copy, Debug, Default)]
38
+ pub struct DownloadStats {
39
+ pub attempted: u64,
40
+ pub success: u64,
41
+ pub failed: u64,
42
+ pub missing: u64,
43
+ pub aborted: u64,
44
+ }
45
+
46
+ #[derive(Clone, Debug)]
47
+ pub struct DownloadOptions {
48
+ pub archives_dir: PathBuf,
49
+ pub flavor: Flavor,
50
+ pub concurrency: usize,
51
+ /// Cap total *attempted* downloads in this run (None = drain queue).
52
+ pub limit: Option<u64>,
53
+ }
54
+
55
+ impl Default for DownloadOptions {
56
+ fn default() -> Self {
57
+ Self {
58
+ archives_dir: PathBuf::from("osu_archives"),
59
+ flavor: Flavor::Full,
60
+ concurrency: 8,
61
+ limit: None,
62
+ }
63
+ }
64
+ }
65
+
66
+ pub async fn run(
67
+ state: Arc<StateDb>,
68
+ pool: Arc<MirrorPool>,
69
+ opts: DownloadOptions,
70
+ shutdown: CancellationToken,
71
+ dashboard: Option<Arc<DownloadDashboard>>,
72
+ ) -> Result<DownloadStats> {
73
+ if pool.is_empty() {
74
+ anyhow::bail!("mirror pool is empty — nothing can be downloaded");
75
+ }
76
+ fs::create_dir_all(&opts.archives_dir)
77
+ .await
78
+ .with_context(|| format!("creating {}", opts.archives_dir.display()))?;
79
+
80
+ // Re-queue any rows from a prior crashed run.
81
+ let requeued = state.requeue_in_progress()?;
82
+ if requeued > 0 {
83
+ info!(rows = requeued, "requeued in_progress rows from prior run");
84
+ }
85
+ cleanup_orphan_partials(&opts.archives_dir).await;
86
+
87
+ let worker_count = opts.concurrency.max(1);
88
+ let budget = Arc::new(AttemptBudget::new(opts.limit));
89
+ let mut tasks: JoinSet<DownloadStats> = JoinSet::new();
90
+ let mut stats = DownloadStats::default();
91
+
92
+ for worker_id in 0..worker_count {
93
+ tasks.spawn(download_worker(
94
+ worker_id,
95
+ opts.flavor,
96
+ opts.archives_dir.clone(),
97
+ pool.clone(),
98
+ state.clone(),
99
+ shutdown.clone(),
100
+ dashboard.clone(),
101
+ budget.clone(),
102
+ ));
103
+ }
104
+
105
+ while let Some(joined) = tasks.join_next().await {
106
+ match joined {
107
+ Ok(worker_stats) => stats.add(worker_stats),
108
+ Err(e) => {
109
+ error!(err = %e, "download worker task panicked");
110
+ stats.failed += 1;
111
+ if let Some(d) = dashboard.as_deref() {
112
+ d.record_failed();
113
+ }
114
+ }
115
+ }
116
+ }
117
+
118
+ Ok(stats)
119
+ }
120
+
121
+ impl DownloadStats {
122
+ fn add(&mut self, other: DownloadStats) {
123
+ self.attempted += other.attempted;
124
+ self.success += other.success;
125
+ self.failed += other.failed;
126
+ self.missing += other.missing;
127
+ self.aborted += other.aborted;
128
+ }
129
+ }
130
+
131
+ #[derive(Debug)]
132
+ struct AttemptBudget {
133
+ limit: Option<u64>,
134
+ claimed: AtomicU64,
135
+ }
136
+
137
+ impl AttemptBudget {
138
+ fn new(limit: Option<u64>) -> Self {
139
+ Self {
140
+ limit,
141
+ claimed: AtomicU64::new(0),
142
+ }
143
+ }
144
+
145
+ fn try_reserve(&self) -> bool {
146
+ let Some(limit) = self.limit else {
147
+ return true;
148
+ };
149
+ loop {
150
+ let current = self.claimed.load(Ordering::Relaxed);
151
+ if current >= limit {
152
+ return false;
153
+ }
154
+ if self
155
+ .claimed
156
+ .compare_exchange_weak(current, current + 1, Ordering::AcqRel, Ordering::Relaxed)
157
+ .is_ok()
158
+ {
159
+ return true;
160
+ }
161
+ }
162
+ }
163
+
164
+ fn release_unused(&self) {
165
+ if self.limit.is_some() {
166
+ self.claimed.fetch_sub(1, Ordering::AcqRel);
167
+ }
168
+ }
169
+ }
170
+
171
+ async fn download_worker(
172
+ worker_id: usize,
173
+ flavor: Flavor,
174
+ archives_dir: PathBuf,
175
+ pool: Arc<MirrorPool>,
176
+ state: Arc<StateDb>,
177
+ shutdown: CancellationToken,
178
+ dashboard: Option<Arc<DownloadDashboard>>,
179
+ budget: Arc<AttemptBudget>,
180
+ ) -> DownloadStats {
181
+ let mut stats = DownloadStats::default();
182
+
183
+ loop {
184
+ if shutdown.is_cancelled() {
185
+ debug!(worker_id, "download worker stopping after shutdown");
186
+ break;
187
+ }
188
+ if !budget.try_reserve() {
189
+ debug!(worker_id, "download worker reached attempt limit");
190
+ break;
191
+ }
192
+
193
+ let set_id = match state.claim_next_pending() {
194
+ Ok(Some(set_id)) => set_id,
195
+ Ok(None) => {
196
+ budget.release_unused();
197
+ debug!(worker_id, "download worker found empty queue");
198
+ break;
199
+ }
200
+ Err(e) => {
201
+ budget.release_unused();
202
+ error!(worker_id, err = %e, "claim_next_pending failed; worker exiting");
203
+ break;
204
+ }
205
+ };
206
+
207
+ stats.attempted += 1;
208
+ if let Some(d) = &dashboard {
209
+ d.worker_inflight_inc();
210
+ }
211
+ let outcome = run_one(
212
+ set_id,
213
+ flavor,
214
+ &archives_dir,
215
+ pool.clone(),
216
+ state.clone(),
217
+ shutdown.clone(),
218
+ dashboard.clone(),
219
+ )
220
+ .await;
221
+ if let Some(d) = &dashboard {
222
+ d.worker_inflight_dec();
223
+ }
224
+ match outcome {
225
+ WorkerOutcome::Success => stats.success += 1,
226
+ WorkerOutcome::Failed => stats.failed += 1,
227
+ WorkerOutcome::Missing => stats.missing += 1,
228
+ WorkerOutcome::Aborted => stats.aborted += 1,
229
+ }
230
+ }
231
+
232
+ stats
233
+ }
234
+
235
+ #[derive(Debug)]
236
+ enum WorkerOutcome {
237
+ Success,
238
+ Failed,
239
+ Missing,
240
+ Aborted,
241
+ }
242
+
243
+ async fn run_one(
244
+ set_id: u64,
245
+ flavor: Flavor,
246
+ archives_dir: &Path,
247
+ pool: Arc<MirrorPool>,
248
+ state: Arc<StateDb>,
249
+ shutdown: CancellationToken,
250
+ dashboard: Option<Arc<DownloadDashboard>>,
251
+ ) -> WorkerOutcome {
252
+ if shutdown.is_cancelled() {
253
+ if let Err(e) = state.release_claim(set_id) {
254
+ warn!(set_id, err = %e, "release_claim after shutdown");
255
+ }
256
+ if let Some(d) = &dashboard {
257
+ d.record_aborted();
258
+ }
259
+ return WorkerOutcome::Aborted;
260
+ }
261
+
262
+ // Race the in-flight HTTP against the shutdown token so a Ctrl-C while
263
+ // a worker is mid-download (especially big videos: 100+ MB / 30+ s)
264
+ // aborts the request rather than waiting for it to finish.
265
+ let noop = NoOpObserver;
266
+ let observer: &dyn AttemptObserver = match dashboard.as_deref() {
267
+ Some(d) => d,
268
+ None => &noop,
269
+ };
270
+ let download_fut = pool.download_with_observer(set_id, flavor, observer);
271
+ let (result, attempts) = tokio::select! {
272
+ biased;
273
+ _ = shutdown.cancelled() => {
274
+ if let Err(e) = state.release_claim(set_id) {
275
+ warn!(set_id, err = %e, "release_claim after mid-flight shutdown");
276
+ }
277
+ if let Some(d) = &dashboard {
278
+ d.record_aborted();
279
+ }
280
+ return WorkerOutcome::Aborted;
281
+ }
282
+ out = download_fut => out,
283
+ };
284
+ // Persist every attempt regardless of overall outcome.
285
+ for a in &attempts {
286
+ let outcome = match a.outcome {
287
+ crate::mirrors::AttemptOutcome::Success => StateOutcome::Success,
288
+ crate::mirrors::AttemptOutcome::NotFound => StateOutcome::NotFound,
289
+ crate::mirrors::AttemptOutcome::HttpError => StateOutcome::HttpError,
290
+ crate::mirrors::AttemptOutcome::RateLimited => StateOutcome::RateLimited,
291
+ crate::mirrors::AttemptOutcome::Network => StateOutcome::Network,
292
+ crate::mirrors::AttemptOutcome::InvalidArchive => StateOutcome::InvalidArchive,
293
+ crate::mirrors::AttemptOutcome::Timeout => StateOutcome::Timeout,
294
+ crate::mirrors::AttemptOutcome::UnsupportedFlavor => continue,
295
+ };
296
+ if let Err(e) = state.record_attempt(
297
+ set_id,
298
+ &a.mirror,
299
+ outcome,
300
+ a.http_status,
301
+ a.bytes,
302
+ Some(a.duration.as_millis() as u64),
303
+ a.error.as_deref(),
304
+ ) {
305
+ warn!(set_id, mirror = %a.mirror, err = %e, "record_attempt failed");
306
+ }
307
+ if let Some(d) = &dashboard {
308
+ d.record_attempt(&a.mirror, a.outcome, a.duration, a.bytes);
309
+ }
310
+ }
311
+
312
+ match result {
313
+ Ok((mirror, bytes)) => {
314
+ // Pool's classify_response already deep-verified (zip + at least
315
+ // one .osu) before returning, so we trust the bytes here.
316
+ let sha = sha256_hex(&bytes);
317
+ let final_path = archives_dir.join(format!("{set_id}.osz"));
318
+ if let Err(e) = atomic_write(&final_path, archives_dir, &bytes).await {
319
+ let msg = format!("atomic_write: {e}");
320
+ error!(set_id, mirror = %mirror, err = %msg);
321
+ let _ = state.finish_failed(&DownloadFailure {
322
+ set_id,
323
+ mirror: &mirror,
324
+ error: &msg,
325
+ });
326
+ if let Some(d) = &dashboard {
327
+ d.record_failed();
328
+ }
329
+ return WorkerOutcome::Failed;
330
+ }
331
+ let saved_path = final_path.to_string_lossy();
332
+ // If the DB write fails, we have an orphan .osz on disk. Surface
333
+ // this as a Failed outcome so the run stats reflect reality —
334
+ // the next run will requeue (in_progress -> pending), re-fetch,
335
+ // and atomic_write will overwrite the existing file with the
336
+ // same (or newer) bytes. No data corruption, no lost work.
337
+ if let Err(e) = state.finish_success(&DownloadSuccess {
338
+ set_id,
339
+ mirror: &mirror,
340
+ bytes: bytes.len() as u64,
341
+ sha256: &sha,
342
+ flavor: flavor.as_str(),
343
+ saved_path: &saved_path,
344
+ }) {
345
+ let msg = format!("finish_success DB write: {e}");
346
+ error!(set_id, mirror = %mirror, err = %msg);
347
+ let _ = state.finish_failed(&DownloadFailure {
348
+ set_id,
349
+ mirror: &mirror,
350
+ error: &msg,
351
+ });
352
+ if let Some(d) = &dashboard {
353
+ d.record_failed();
354
+ }
355
+ return WorkerOutcome::Failed;
356
+ }
357
+ // Per-set INFO is at debug! so the dashboard isn't clobbered;
358
+ // promote with --verbose / RUST_LOG when investigating.
359
+ debug!(
360
+ set_id,
361
+ mirror = %mirror,
362
+ bytes = bytes.len(),
363
+ "download ok"
364
+ );
365
+ if let Some(d) = &dashboard {
366
+ d.record_success(bytes.len() as u64);
367
+ }
368
+ WorkerOutcome::Success
369
+ }
370
+ Err(MirrorError::NotFound { mirror }) => {
371
+ // Promoted by the pool: every mirror returned 404.
372
+ let tried = attempt_summary(&attempts);
373
+ let msg = format!("not found on any mirror (last={mirror}; tried={tried})");
374
+ warn!(set_id, attempts = attempts.len(), mirrors = %tried, %msg);
375
+ let _ = state.finish_missing(&DownloadFailure {
376
+ set_id,
377
+ mirror: &mirror,
378
+ error: &msg,
379
+ });
380
+ if let Some(d) = &dashboard {
381
+ d.record_missing();
382
+ }
383
+ WorkerOutcome::Missing
384
+ }
385
+ Err(MirrorError::Aborted) => {
386
+ if let Err(e) = state.release_claim(set_id) {
387
+ warn!(set_id, err = %e, "release_claim after Aborted");
388
+ }
389
+ if let Some(d) = &dashboard {
390
+ d.record_aborted();
391
+ }
392
+ WorkerOutcome::Aborted
393
+ }
394
+ Err(other) => {
395
+ let mirror = other.mirror_name().to_string();
396
+ let msg = other.to_string();
397
+ let tried = attempt_summary(&attempts);
398
+ warn!(
399
+ set_id,
400
+ %mirror,
401
+ attempts = attempts.len(),
402
+ mirrors = %tried,
403
+ err = %msg,
404
+ "download failed after trying mirror chain"
405
+ );
406
+ let _ = state.finish_failed(&DownloadFailure {
407
+ set_id,
408
+ mirror: &mirror,
409
+ error: &msg,
410
+ });
411
+ if let Some(d) = &dashboard {
412
+ d.record_failed();
413
+ }
414
+ WorkerOutcome::Failed
415
+ }
416
+ }
417
+ }
418
+
419
+ fn attempt_summary(attempts: &[crate::mirrors::AttemptRecord]) -> String {
420
+ attempts
421
+ .iter()
422
+ .map(|a| format!("{}:{:?}", a.mirror, a.outcome))
423
+ .collect::<Vec<_>>()
424
+ .join(",")
425
+ }
426
+
427
+ /// Crash-safe write: bytes hit a `.partial` file, are fsynced, then renamed
428
+ /// in place. After the rename we also fsync the parent directory so the
429
+ /// rename's metadata is durable on power-off — without that step, some
430
+ /// filesystems can lose the directory entry while the file's contents are
431
+ /// safe, leaving us with bytes on disk that nothing references and a state
432
+ /// row that thinks the file is there.
433
+ ///
434
+ /// On Windows the directory-fsync call is a noop at the FS level (NTFS
435
+ /// orders metadata more strictly than ext4) but we issue it unconditionally
436
+ /// because fs4-style portable code is cheaper than another platform branch.
437
+ async fn atomic_write(final_path: &Path, parent_dir: &Path, bytes: &[u8]) -> std::io::Result<()> {
438
+ let tmp = final_path.with_extension("osz.partial");
439
+ let mut f = fs::File::create(&tmp).await?;
440
+ f.write_all(bytes).await?;
441
+ f.flush().await?;
442
+ f.sync_all().await?;
443
+ drop(f);
444
+ fs::rename(&tmp, final_path).await?;
445
+ // Fsync the directory so the rename is durable. Errors here are not
446
+ // fatal — the file is already on disk — but they're worth logging.
447
+ let dir = parent_dir.to_path_buf();
448
+ if let Err(e) =
449
+ tokio::task::spawn_blocking(move || std::fs::File::open(&dir).and_then(|f| f.sync_all()))
450
+ .await
451
+ .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))?
452
+ {
453
+ tracing::debug!(
454
+ path = %parent_dir.display(),
455
+ err = %e,
456
+ "dir fsync after rename failed (non-fatal)"
457
+ );
458
+ }
459
+ Ok(())
460
+ }
461
+
462
+ fn sha256_hex(bytes: &[u8]) -> String {
463
+ let mut h = Sha256::new();
464
+ h.update(bytes);
465
+ hex::encode(h.finalize())
466
+ }
467
+
468
+ /// Best-effort cleanup of `.partial` files left behind by a crashed worker.
469
+ /// Failures here are logged at debug level — they don't block downloads.
470
+ pub async fn cleanup_orphan_partials(archives_dir: &Path) {
471
+ let Ok(mut entries) = fs::read_dir(archives_dir).await else {
472
+ return;
473
+ };
474
+ while let Ok(Some(entry)) = entries.next_entry().await {
475
+ let path = entry.path();
476
+ if path
477
+ .extension()
478
+ .and_then(|e| e.to_str())
479
+ .map(|e| e.eq_ignore_ascii_case("partial"))
480
+ .unwrap_or(false)
481
+ {
482
+ if let Err(e) = fs::remove_file(&path).await {
483
+ debug!(path = %path.display(), err = %e, "couldn't remove orphan partial");
484
+ } else {
485
+ debug!(path = %path.display(), "cleaned orphan partial");
486
+ }
487
+ }
488
+ }
489
+ }
490
+
491
+ #[cfg(test)]
492
+ mod tests {
493
+ use super::*;
494
+ use tempfile::TempDir;
495
+
496
+ #[tokio::test]
497
+ async fn atomic_write_creates_final_file_and_removes_tmp() {
498
+ let dir = TempDir::new().unwrap();
499
+ let final_path = dir.path().join("123.osz");
500
+ atomic_write(&final_path, dir.path(), b"PK\x03\x04hello")
501
+ .await
502
+ .unwrap();
503
+ assert!(final_path.exists());
504
+ assert!(!dir.path().join("123.osz.partial").exists());
505
+ let read = fs::read(&final_path).await.unwrap();
506
+ assert_eq!(read, b"PK\x03\x04hello");
507
+ }
508
+
509
+ #[tokio::test]
510
+ async fn cleanup_removes_only_partials() {
511
+ let dir = TempDir::new().unwrap();
512
+ fs::write(dir.path().join("123.osz.partial"), b"x")
513
+ .await
514
+ .unwrap();
515
+ fs::write(dir.path().join("456.osz"), b"y").await.unwrap();
516
+ cleanup_orphan_partials(dir.path()).await;
517
+ assert!(!dir.path().join("123.osz.partial").exists());
518
+ assert!(dir.path().join("456.osz").exists());
519
+ }
520
+
521
+ #[test]
522
+ fn sha256_hex_matches_known_vector() {
523
+ // Known SHA-256 of "hello" (lowercase hex) is
524
+ // 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824.
525
+ assert_eq!(
526
+ sha256_hex(b"hello"),
527
+ "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"
528
+ );
529
+ }
530
+ }
crates/osu_fetcher/src/enumerate.rs ADDED
@@ -0,0 +1,356 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //! `enumerate` subcommand — populate the wanted side of the `sets` table by
2
+ //! paginating the official osu! API search endpoint.
3
+ //!
4
+ //! Pagination is cursor-based: each successful response carries a
5
+ //! `cursor_string` to feed back into the next request, or `None` when the
6
+ //! server has nothing left. We persist the cursor into `meta` after every
7
+ //! successful page so a crash mid-enumerate resumes from the next unscanned
8
+ //! page.
9
+ //!
10
+ //! ## Incremental mode
11
+ //!
12
+ //! Each successful enumerate stores a per-status `last_updated` "high-water
13
+ //! mark" — the most recent `last_updated` value across every set seen in
14
+ //! that run. Subsequent runs query the API with `sort=updated_desc`, walking
15
+ //! pages newest-first, and stop pagination once they hit a set whose
16
+ //! `last_updated <= watermark` (i.e., already known and unchanged). This
17
+ //! cuts a steady-state daily enumerate from ~700 pages down to the number
18
+ //! of *new or updated* pages — usually 1–5.
19
+ //!
20
+ //! Set `EnumerateOptions::full_rescan = true` (or `--full-rescan` on the
21
+ //! CLI) to ignore the watermark and re-paginate everything; useful when
22
+ //! you're worried the watermark drifted or when bootstrapping a fresh DB.
23
+
24
+ use std::sync::Arc;
25
+
26
+ use anyhow::{Context, Result};
27
+ use tracing::{debug, info};
28
+
29
+ use crate::api::OsuApi;
30
+ use crate::progress::CounterSpinner;
31
+ use crate::state::{StateDb, WantedRow};
32
+ use crate::RankedStatus;
33
+
34
+ #[derive(Clone, Copy, Debug, Default)]
35
+ pub struct EnumerateStats {
36
+ pub pages: u64,
37
+ pub seen: u64,
38
+ pub upserted: u64,
39
+ pub skipped_no_osu_mode: u64,
40
+ /// True when pagination stopped because we hit the saved watermark
41
+ /// (the incremental fast-path), rather than exhausting the cursor.
42
+ pub stopped_at_watermark: bool,
43
+ }
44
+
45
+ #[derive(Clone, Copy, Debug, Eq, PartialEq)]
46
+ pub enum SearchSort {
47
+ UpdatedDesc,
48
+ RankedDesc,
49
+ }
50
+
51
+ impl SearchSort {
52
+ pub fn as_api_str(self) -> &'static str {
53
+ match self {
54
+ SearchSort::UpdatedDesc => "updated_desc",
55
+ SearchSort::RankedDesc => "ranked_desc",
56
+ }
57
+ }
58
+ }
59
+
60
+ #[derive(Clone, Copy, Debug)]
61
+ pub struct EnumerateOptions {
62
+ /// Mode integer (0 = osu! standard).
63
+ pub mode: u8,
64
+ /// Hard cap on pages per status (None = exhaust the cursor).
65
+ pub max_pages: Option<u64>,
66
+ /// If true, only persist sets that have at least one beatmap whose
67
+ /// `mode_int` matches `mode`. The API search filter already returns sets
68
+ /// that *contain* such a difficulty, but the field lets us be paranoid.
69
+ pub require_matching_mode_difficulty: bool,
70
+ /// Ignore the saved high-water mark and walk every page. Use this for
71
+ /// bootstrap runs or when you suspect the watermark is stale.
72
+ pub full_rescan: bool,
73
+ /// Search ordering to request from osu! API.
74
+ pub sort: SearchSort,
75
+ /// Do not read or persist cursor/high-water metadata. Use this for
76
+ /// bounded front scans such as `ranked_desc` recent-rank checks.
77
+ pub stateless: bool,
78
+ }
79
+
80
+ impl Default for EnumerateOptions {
81
+ fn default() -> Self {
82
+ Self {
83
+ mode: 0,
84
+ max_pages: None,
85
+ require_matching_mode_difficulty: true,
86
+ full_rescan: false,
87
+ sort: SearchSort::UpdatedDesc,
88
+ stateless: false,
89
+ }
90
+ }
91
+ }
92
+
93
+ /// Enumerate one (status, mode) combination through cursor pagination.
94
+ ///
95
+ /// `progress`, when supplied, has its message updated after every page so
96
+ /// the spinner reflects live page/seen/upserted counts.
97
+ pub async fn enumerate_status(
98
+ api: Arc<OsuApi>,
99
+ state: Arc<StateDb>,
100
+ status: RankedStatus,
101
+ opts: EnumerateOptions,
102
+ progress: Option<&CounterSpinner>,
103
+ ) -> Result<EnumerateStats> {
104
+ let mut stats = EnumerateStats::default();
105
+
106
+ // Resume any in-flight cursor from a crashed prior run. If a cursor is
107
+ // present it dominates the watermark — we have to drain the page chain
108
+ // we were on before we can trust a fresh `updated_desc` walk.
109
+ let mut cursor = if opts.stateless {
110
+ None
111
+ } else {
112
+ state
113
+ .get_enumerate_cursor(status)
114
+ .with_context(|| format!("loading saved cursor for {}", status.as_api_str()))?
115
+ };
116
+
117
+ let watermark = if opts.full_rescan || opts.stateless || opts.sort != SearchSort::UpdatedDesc {
118
+ None
119
+ } else {
120
+ state
121
+ .get_enumerate_high_water(status)
122
+ .with_context(|| format!("loading high-water mark for {}", status.as_api_str()))?
123
+ };
124
+ let mid_run_resume = cursor.is_some();
125
+
126
+ if let Some(c) = cursor.as_deref() {
127
+ info!(
128
+ status = status.as_api_str(),
129
+ cursor = c,
130
+ "resuming enumerate from saved cursor"
131
+ );
132
+ } else if let Some(w) = watermark.as_deref() {
133
+ info!(
134
+ status = status.as_api_str(),
135
+ watermark = w,
136
+ "incremental enumerate; will stop at watermark"
137
+ );
138
+ } else if opts.stateless {
139
+ info!(
140
+ status = status.as_api_str(),
141
+ sort = opts.sort.as_api_str(),
142
+ "stateless front-scan enumerate"
143
+ );
144
+ } else {
145
+ info!(
146
+ status = status.as_api_str(),
147
+ "full enumerate (no watermark)"
148
+ );
149
+ }
150
+
151
+ let mut max_seen: Option<String> = None;
152
+ loop {
153
+ // Fresh runs (and resumed runs without a cursor) sort by
154
+ // updated_desc so the watermark check terminates fast. If we're
155
+ // resuming a saved cursor, we must NOT change the sort — the
156
+ // server-issued cursor is sort-aware.
157
+ let sort = if mid_run_resume {
158
+ None
159
+ } else {
160
+ Some(opts.sort.as_api_str())
161
+ };
162
+
163
+ let resp = api
164
+ .search_beatmapsets(status, opts.mode, cursor.as_deref(), sort)
165
+ .await
166
+ .with_context(|| {
167
+ format!(
168
+ "search beatmapsets m={} s={} cursor={:?}",
169
+ opts.mode,
170
+ status.as_api_str(),
171
+ cursor.as_deref()
172
+ )
173
+ })?;
174
+ stats.pages += 1;
175
+ let page_size = resp.beatmapsets.len() as u64;
176
+ stats.seen += page_size;
177
+ debug!(
178
+ status = status.as_api_str(),
179
+ page = stats.pages,
180
+ count = page_size,
181
+ total = ?resp.total,
182
+ cursor = ?resp.cursor_string,
183
+ "/search page"
184
+ );
185
+
186
+ let mut hit_watermark = false;
187
+ for entry in &resp.beatmapsets {
188
+ // Track the freshest `last_updated` we've seen so we can save
189
+ // it as the next watermark.
190
+ if let Some(lu) = entry.last_updated.as_deref() {
191
+ if max_seen.as_deref().map(|m| lu > m).unwrap_or(true) {
192
+ max_seen = Some(lu.to_string());
193
+ }
194
+ // Watermark check: in updated_desc order, hitting
195
+ // `last_updated <= watermark` means the rest of the catalog
196
+ // is already known. Finish the page (cheap) then break.
197
+ if opts.sort == SearchSort::UpdatedDesc && !mid_run_resume {
198
+ if let Some(w) = watermark.as_deref() {
199
+ if lu <= w {
200
+ hit_watermark = true;
201
+ }
202
+ }
203
+ }
204
+ }
205
+
206
+ if opts.require_matching_mode_difficulty {
207
+ let any_match = match &entry.beatmaps {
208
+ Some(diffs) => diffs.iter().any(|d| {
209
+ d.mode_int.map(|m| m == opts.mode).unwrap_or(false)
210
+ || d.mode
211
+ .as_deref()
212
+ .map(|s| api_mode_int(s) == Some(opts.mode))
213
+ .unwrap_or(false)
214
+ }),
215
+ // Older API responses without `beatmaps` — trust the
216
+ // upstream `s=` filter and accept the row.
217
+ None => true,
218
+ };
219
+ if !any_match {
220
+ stats.skipped_no_osu_mode += 1;
221
+ continue;
222
+ }
223
+ }
224
+
225
+ state.upsert_wanted(&WantedRow {
226
+ set_id: entry.id,
227
+ ranked_status: status,
228
+ artist: entry.artist.as_deref(),
229
+ title: entry.title.as_deref(),
230
+ creator: entry.creator.as_deref(),
231
+ api_last_updated: entry.last_updated.as_deref(),
232
+ })?;
233
+ stats.upserted += 1;
234
+ }
235
+
236
+ // Save cursor *after* persisting the page so a crash never loses rows
237
+ // (we'd just re-upsert idempotently on resume).
238
+ cursor = resp.cursor_string.clone();
239
+ if !opts.stateless {
240
+ state
241
+ .set_enumerate_cursor(status, cursor.as_deref())
242
+ .context("persisting cursor")?;
243
+ }
244
+
245
+ if let Some(p) = progress {
246
+ let cursor_hint = cursor
247
+ .as_deref()
248
+ .map(short_cursor)
249
+ .unwrap_or_else(|| "done".into());
250
+ p.set_message(format!(
251
+ "pages {} · seen {} · upserted {} · skipped {} · cursor {}",
252
+ stats.pages, stats.seen, stats.upserted, stats.skipped_no_osu_mode, cursor_hint,
253
+ ));
254
+ }
255
+
256
+ if hit_watermark {
257
+ stats.stopped_at_watermark = true;
258
+ info!(
259
+ status = status.as_api_str(),
260
+ pages = stats.pages,
261
+ "stopped at watermark; remaining catalog already known"
262
+ );
263
+ break;
264
+ }
265
+ if cursor.is_none() {
266
+ break;
267
+ }
268
+ if let Some(max) = opts.max_pages {
269
+ if stats.pages >= max {
270
+ info!(
271
+ status = status.as_api_str(),
272
+ pages = stats.pages,
273
+ "stopping early at --max-pages"
274
+ );
275
+ break;
276
+ }
277
+ }
278
+ }
279
+
280
+ // Clean exit means either we hit the watermark or the cursor was
281
+ // exhausted. In both cases, the cursor is no longer useful — wipe it
282
+ // and bump the watermark.
283
+ let cursor_exhausted = cursor.is_none();
284
+ if !opts.stateless
285
+ && (stats.stopped_at_watermark || cursor_exhausted)
286
+ && !mid_run_resume
287
+ && opts.sort == SearchSort::UpdatedDesc
288
+ {
289
+ // Wipe the cursor (we're done; next run starts fresh).
290
+ state
291
+ .set_enumerate_cursor(status, None)
292
+ .context("clearing cursor at clean exit")?;
293
+ // New watermark = max(prev, this run's max_seen). If this run saw
294
+ // nothing newer than the watermark (an empty incremental), don't
295
+ // regress.
296
+ let new_watermark = match (watermark.as_deref(), max_seen.as_deref()) {
297
+ (Some(prev), Some(now)) if now > prev => Some(now),
298
+ (Some(prev), _) => Some(prev),
299
+ (None, Some(now)) => Some(now),
300
+ (None, None) => None,
301
+ };
302
+ if new_watermark.is_some() {
303
+ state
304
+ .set_enumerate_high_water(status, new_watermark)
305
+ .context("persisting new high-water mark")?;
306
+ }
307
+ }
308
+ // If `mid_run_resume` was true, leave the watermark alone — we just
309
+ // walked an old cursor under whatever sort the previous run started
310
+ // with, and the result isn't comparable to an `updated_desc` watermark.
311
+
312
+ Ok(stats)
313
+ }
314
+
315
+ /// Last 8 chars of an opaque cursor string — enough for the user to see
316
+ /// it advance, short enough to fit in the spinner template.
317
+ fn short_cursor(c: &str) -> String {
318
+ if c.len() <= 10 {
319
+ c.to_string()
320
+ } else {
321
+ format!("…{}", &c[c.len() - 8..])
322
+ }
323
+ }
324
+
325
+ /// Convert an API mode string (`"osu" | "taiko" | "catch" | "mania"`) to its
326
+ /// integer.
327
+ fn api_mode_int(s: &str) -> Option<u8> {
328
+ match s {
329
+ "osu" => Some(0),
330
+ "taiko" => Some(1),
331
+ "fruits" | "catch" => Some(2),
332
+ "mania" => Some(3),
333
+ _ => None,
334
+ }
335
+ }
336
+
337
+ #[cfg(test)]
338
+ mod tests {
339
+ use super::*;
340
+
341
+ #[test]
342
+ fn api_mode_int_recognizes_known_modes() {
343
+ assert_eq!(api_mode_int("osu"), Some(0));
344
+ assert_eq!(api_mode_int("taiko"), Some(1));
345
+ assert_eq!(api_mode_int("fruits"), Some(2));
346
+ assert_eq!(api_mode_int("catch"), Some(2));
347
+ assert_eq!(api_mode_int("mania"), Some(3));
348
+ assert_eq!(api_mode_int("???"), None);
349
+ }
350
+
351
+ #[test]
352
+ fn search_sort_tokens_match_osu_api() {
353
+ assert_eq!(SearchSort::UpdatedDesc.as_api_str(), "updated_desc");
354
+ assert_eq!(SearchSort::RankedDesc.as_api_str(), "ranked_desc");
355
+ }
356
+ }
crates/osu_fetcher/src/lib.rs ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //! osu_fetcher library — discover and download missing osu! beatmapsets.
2
+ //!
3
+ //! The CLI in `main.rs` is a thin shim over these modules so that integration
4
+ //! tests can drive each phase directly without forking a process.
5
+ //!
6
+ //! Five stateful tables in SQLite (see `state` module) carry the work:
7
+ //!
8
+ //! * `sets` — the merged "wanted + acquired" record per beatmapset. A row is
9
+ //! created either by `enumerate` (API said this set exists with a
10
+ //! leaderboard) or by `scan` (we found a `<id>.osz` on disk). Both sides
11
+ //! can later be filled in.
12
+ //! * `mirror_attempts` — append-only log of every download attempt across
13
+ //! mirrors. Used to weight mirror health and for forensics.
14
+ //! * `meta` — small key/value store for cursor checkpoints and schema
15
+ //! version.
16
+ //!
17
+ //! State transitions are deliberately narrow:
18
+ //!
19
+ //! `pending -> in_progress -> { success | failed | missing }`
20
+ //!
21
+ //! `in_progress` is reset to `pending` on startup so a crashed worker doesn't
22
+ //! block forever.
23
+
24
+ pub mod api;
25
+ pub mod auth;
26
+ pub mod config;
27
+ pub mod discover;
28
+ pub mod download;
29
+ pub mod enumerate;
30
+ pub mod mirrors;
31
+ pub mod progress;
32
+ pub mod ratelimit;
33
+ pub mod runlock;
34
+ pub mod scan;
35
+ pub mod state;
36
+ pub mod verify;
37
+
38
+ /// Archive flavor preference passed through the mirror pool.
39
+ #[derive(Clone, Copy, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
40
+ #[serde(rename_all = "snake_case")]
41
+ pub enum Flavor {
42
+ /// Original archive with all assets (audio + video + storyboard + skin).
43
+ Full,
44
+ /// Hitsound archive without video. Smaller; some mirrors only serve this.
45
+ NoVideo,
46
+ }
47
+
48
+ impl Flavor {
49
+ pub fn as_str(self) -> &'static str {
50
+ match self {
51
+ Flavor::Full => "full",
52
+ Flavor::NoVideo => "novideo",
53
+ }
54
+ }
55
+ }
56
+
57
+ impl std::str::FromStr for Flavor {
58
+ type Err = String;
59
+ fn from_str(s: &str) -> Result<Self, Self::Err> {
60
+ match s {
61
+ "full" => Ok(Flavor::Full),
62
+ "novideo" | "no-video" | "no_video" => Ok(Flavor::NoVideo),
63
+ other => Err(format!(
64
+ "unknown flavor `{other}` (expected: full | novideo)"
65
+ )),
66
+ }
67
+ }
68
+ }
69
+
70
+ /// Beatmapset ranked statuses we care about (osu! standard with leaderboards).
71
+ #[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, serde::Serialize, serde::Deserialize)]
72
+ #[serde(rename_all = "snake_case")]
73
+ pub enum RankedStatus {
74
+ Ranked,
75
+ Approved,
76
+ Loved,
77
+ Qualified,
78
+ }
79
+
80
+ impl RankedStatus {
81
+ pub fn as_api_str(self) -> &'static str {
82
+ match self {
83
+ RankedStatus::Ranked => "ranked",
84
+ RankedStatus::Approved => "approved",
85
+ RankedStatus::Loved => "loved",
86
+ RankedStatus::Qualified => "qualified",
87
+ }
88
+ }
89
+
90
+ pub fn all_with_leaderboard() -> &'static [RankedStatus] {
91
+ &[
92
+ RankedStatus::Ranked,
93
+ RankedStatus::Approved,
94
+ RankedStatus::Loved,
95
+ RankedStatus::Qualified,
96
+ ]
97
+ }
98
+ }
99
+
100
+ impl std::str::FromStr for RankedStatus {
101
+ type Err = String;
102
+ fn from_str(s: &str) -> Result<Self, Self::Err> {
103
+ match s.to_ascii_lowercase().as_str() {
104
+ "ranked" => Ok(RankedStatus::Ranked),
105
+ "approved" => Ok(RankedStatus::Approved),
106
+ "loved" => Ok(RankedStatus::Loved),
107
+ "qualified" => Ok(RankedStatus::Qualified),
108
+ other => Err(format!(
109
+ "unknown ranked status `{other}` (expected: ranked | approved | loved | qualified)"
110
+ )),
111
+ }
112
+ }
113
+ }
crates/osu_fetcher/src/main.rs ADDED
@@ -0,0 +1,887 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //! `osu_fetcher` CLI.
2
+ //!
3
+ //! Subcommands map 1:1 to library modules so each phase is independently
4
+ //! testable. Global flags configure the state DB path, archive directory, and
5
+ //! per-target rate limits; everything else is subcommand-specific.
6
+
7
+ use std::path::PathBuf;
8
+ use std::sync::Arc;
9
+
10
+ use anyhow::{anyhow, Context, Result};
11
+ use clap::{Parser, Subcommand, ValueEnum};
12
+ use tokio_util::sync::CancellationToken;
13
+ use tracing::{info, warn};
14
+
15
+ use osu_fetcher::api::OsuApi;
16
+ use osu_fetcher::auth::{OsuAuth, OsuAuthMode};
17
+ use osu_fetcher::config::{self, Config, ResolvedOsuCreds};
18
+ use osu_fetcher::discover::{
19
+ self,
20
+ nekoha::NekohaVerify,
21
+ nerinyan::NerinyanSearch,
22
+ osudirect::{OsuDirectSearch, OsuDirectVerify},
23
+ sayobot::{SayobotSearch, SayobotVerify},
24
+ DiscoverContext, DiscoverLimiters, DiscoverOptions, MirrorSearch, MirrorVerify,
25
+ };
26
+ use osu_fetcher::download::{self, DownloadOptions};
27
+ use osu_fetcher::enumerate::{self, EnumerateOptions, EnumerateStats, SearchSort};
28
+ use osu_fetcher::mirrors::{
29
+ beatconnect::BeatconnectMirror, build_client, catboy::CatboyMirror, nekoha::NekohaMirror,
30
+ nerinyan::NerinyanMirror, nzbasic::NzbasicMirror, osuapi::OsuApiMirror,
31
+ osudirect::OsuDirectMirror, osudl::OsudlMirror, sayobot::SayobotMirror, Mirror, MirrorContext,
32
+ MirrorLimiters, MirrorPool,
33
+ };
34
+ use osu_fetcher::progress::{self, CounterSpinner, DownloadDashboard, ProgressTarget};
35
+ use osu_fetcher::ratelimit::RateLimited;
36
+ use osu_fetcher::runlock::DownloadLock;
37
+ use osu_fetcher::scan;
38
+ use osu_fetcher::state::StateDb;
39
+ use osu_fetcher::verify::{self, AdaptiveVerifyOptions};
40
+ use osu_fetcher::{Flavor, RankedStatus};
41
+
42
+ const DEFAULT_RATE_LIMIT_RPM: u32 = 480;
43
+
44
+ #[derive(Parser, Debug)]
45
+ #[command(
46
+ name = "osu_fetcher",
47
+ version,
48
+ about = "Discover and download missing osu! beatmapsets via the official API + multiple mirrors."
49
+ )]
50
+ struct Cli {
51
+ /// Path to the TOML config file holding API credentials. Optional: if
52
+ /// missing, env vars (OSU_CLIENT_ID / OSU_CLIENT_SECRET / BEATCONNECT_API_KEY)
53
+ /// are used. Env vars override file values when both are set.
54
+ #[arg(long, global = true)]
55
+ config: Option<PathBuf>,
56
+
57
+ /// SQLite state DB path. Created on first use.
58
+ #[arg(long, global = true, default_value = ".fetcher.state.db")]
59
+ state_db: PathBuf,
60
+
61
+ /// Directory where finished `.osz` archives live. Same dir is read by the
62
+ /// rest of the dataset pipeline (`python/ingest_osz.py`).
63
+ #[arg(long, global = true, default_value = "osu_archives")]
64
+ archives_dir: PathBuf,
65
+
66
+ /// Official osu! API rate limit (requests per minute).
67
+ #[arg(long, global = true, default_value_t = DEFAULT_RATE_LIMIT_RPM)]
68
+ osu_rpm: u32,
69
+
70
+ /// Where to persist the osu! OAuth token between runs. The file holds
71
+ /// access_token + refresh_token + expiry; treat it like a credential.
72
+ /// On Unix it's created with mode 0600. Default: `<state_db>.osu_token.json`.
73
+ #[arg(long, global = true)]
74
+ osu_token_file: Option<PathBuf>,
75
+
76
+ /// Per-mirror rate limits (requests per minute). Defaults are
77
+ /// tuned for the update worker and can be lowered if a mirror asks us
78
+ /// to back off.
79
+ #[arg(long, global = true, default_value_t = DEFAULT_RATE_LIMIT_RPM)]
80
+ nerinyan_rpm: u32,
81
+ #[arg(long, global = true, default_value_t = DEFAULT_RATE_LIMIT_RPM)]
82
+ catboy_rpm: u32,
83
+ #[arg(long, global = true, default_value_t = DEFAULT_RATE_LIMIT_RPM)]
84
+ sayobot_rpm: u32,
85
+ #[arg(long, global = true, default_value_t = DEFAULT_RATE_LIMIT_RPM)]
86
+ nekoha_rpm: u32,
87
+ #[arg(long, global = true, default_value_t = DEFAULT_RATE_LIMIT_RPM)]
88
+ beatconnect_rpm: u32,
89
+ /// osu.direct's documented rate limit is lower than this default in
90
+ /// some older notes; lower this flag if the mirror asks us to back off.
91
+ #[arg(long, global = true, default_value_t = DEFAULT_RATE_LIMIT_RPM)]
92
+ osudirect_rpm: u32,
93
+ /// direct.nzbasic.com — same endpoint nzbasic's batch-beatmap-downloader
94
+ /// uses. No documented rate limit; can be overridden if needed.
95
+ #[arg(long, global = true, default_value_t = DEFAULT_RATE_LIMIT_RPM)]
96
+ nzbasic_rpm: u32,
97
+ /// osudl.org — short-link mirror (`/s/{set_id}`). No documented rate
98
+ /// limit; can be overridden if needed.
99
+ #[arg(long, global = true, default_value_t = DEFAULT_RATE_LIMIT_RPM)]
100
+ osudl_rpm: u32,
101
+ /// Official osu! API download endpoint (`/api/v2/beatmapsets/{id}/download`).
102
+ /// Shares the same upstream as `--osu-rpm` (which paces enumeration);
103
+ /// `download` and `enumerate` aren't run concurrently in normal use,
104
+ /// so a separate bucket here is fine. Default matches the other
105
+ /// mirrors.
106
+ #[arg(long, global = true, default_value_t = DEFAULT_RATE_LIMIT_RPM)]
107
+ osuapi_rpm: u32,
108
+
109
+ /// Disable a mirror by name. Repeatable: `--disable nerinyan --disable catboy`.
110
+ #[arg(long, global = true)]
111
+ disable: Vec<String>,
112
+
113
+ /// Per-attempt wallclock deadline, in seconds. If a single mirror call
114
+ /// (DNS → TLS → headers → body) doesn't complete in this many seconds,
115
+ /// the pool aborts it, scores the mirror as a hard failure, and tries
116
+ /// the next mirror. Belt-and-suspenders against hung connections that
117
+ /// would otherwise hold a worker for the reqwest client's 120s ceiling.
118
+ /// Set to 0 to disable (rely only on the reqwest timeout).
119
+ #[arg(long, global = true, default_value_t = 60)]
120
+ mirror_timeout_secs: u64,
121
+
122
+ /// Disable the live terminal dashboard. Use this for CI or when
123
+ /// redirecting stderr to a file. Default is to enable when stderr is
124
+ /// a TTY.
125
+ #[arg(long, global = true)]
126
+ no_progress: bool,
127
+
128
+ /// Force live download progress through /dev/tty even when stderr is not
129
+ /// detected as a terminal. Useful for wrapper scripts that tee logs while
130
+ /// still running interactively in tmux.
131
+ #[arg(long, global = true)]
132
+ force_progress: bool,
133
+
134
+ /// Lower the tracing level threshold so per-set INFO lines (e.g.
135
+ /// "download ok") appear. Useful for debugging; will visually
136
+ /// interrupt the dashboard while events fly by.
137
+ #[arg(long, global = true)]
138
+ verbose: bool,
139
+
140
+ #[command(subcommand)]
141
+ cmd: Cmd,
142
+ }
143
+
144
+ #[derive(Subcommand, Debug)]
145
+ enum Cmd {
146
+ /// Query the official osu! API and populate the wanted side of the state DB.
147
+ Enumerate(EnumerateArgs),
148
+
149
+ /// Walk archives_dir and record every `<set_id>.osz` as already acquired.
150
+ Scan(ScanArgs),
151
+
152
+ /// Download every pending wanted set in parallel, cycling mirrors.
153
+ Download(DownloadArgs),
154
+
155
+ /// Print summary counts from the state DB.
156
+ Status,
157
+
158
+ /// Validate every `.osz` in archives_dir; report corrupt files.
159
+ Verify(VerifyArgs),
160
+
161
+ /// Reset failed/missing rows back to pending so the next download retries them.
162
+ Retry(RetryArgs),
163
+
164
+ /// Walk every mirror's search surface and cross-verify candidates.
165
+ /// Useful for discovering ranked/loved/approved/qualified sets the
166
+ /// official API stopped serving but mirrors still cache.
167
+ Discover(DiscoverArgs),
168
+ }
169
+
170
+ #[derive(clap::Args, Debug)]
171
+ struct EnumerateArgs {
172
+ /// Statuses to enumerate. Repeatable, comma-separated.
173
+ /// Defaults to ranked + approved + loved.
174
+ #[arg(long, value_delimiter = ',', default_values = ["ranked", "approved", "loved"])]
175
+ statuses: Vec<String>,
176
+
177
+ /// Game mode integer. 0 = osu! standard.
178
+ #[arg(long, default_value_t = 0)]
179
+ mode: u8,
180
+
181
+ /// Stop after N pages per status. Useful for smoke testing.
182
+ #[arg(long)]
183
+ max_pages: Option<u64>,
184
+
185
+ /// If set, accept beatmapsets even if their listed difficulties don't
186
+ /// match `mode`. By default we double-check via the per-difficulty
187
+ /// `mode_int` field.
188
+ #[arg(long)]
189
+ no_mode_filter: bool,
190
+
191
+ /// Ignore the saved `last_updated` watermark and re-paginate every
192
+ /// page from the API. Use this on first run, after long pauses, or
193
+ /// when you suspect the watermark is stale. Default is incremental.
194
+ #[arg(long)]
195
+ full_rescan: bool,
196
+
197
+ /// API sort order for fresh pages.
198
+ #[arg(long, value_enum, default_value_t = EnumerateSortArg::UpdatedDesc)]
199
+ sort: EnumerateSortArg,
200
+
201
+ /// Do not read or persist enumerate cursor/high-water state. Intended
202
+ /// for bounded front scans, e.g. `--sort ranked-desc --max-pages 3`.
203
+ #[arg(long)]
204
+ stateless: bool,
205
+ }
206
+
207
+ #[derive(Clone, Copy, Debug, ValueEnum)]
208
+ enum EnumerateSortArg {
209
+ UpdatedDesc,
210
+ RankedDesc,
211
+ }
212
+
213
+ impl From<EnumerateSortArg> for SearchSort {
214
+ fn from(value: EnumerateSortArg) -> Self {
215
+ match value {
216
+ EnumerateSortArg::UpdatedDesc => SearchSort::UpdatedDesc,
217
+ EnumerateSortArg::RankedDesc => SearchSort::RankedDesc,
218
+ }
219
+ }
220
+ }
221
+
222
+ #[derive(clap::Args, Debug)]
223
+ struct ScanArgs {
224
+ /// Open every archive and walk its ZIP entries; corrupt archives are left
225
+ /// pending for re-download. Slower but catches bit-rot.
226
+ #[arg(long)]
227
+ verify: bool,
228
+ }
229
+
230
+ #[derive(clap::Args, Debug)]
231
+ struct DownloadArgs {
232
+ /// Concurrent in-flight downloads. Total across all mirrors.
233
+ #[arg(long, default_value_t = 8)]
234
+ concurrency: usize,
235
+
236
+ /// Cap total downloads attempted in this run.
237
+ #[arg(long)]
238
+ limit: Option<u64>,
239
+ }
240
+
241
+ #[derive(clap::Args, Debug)]
242
+ struct VerifyArgs {
243
+ /// On corruption, mark the row in the state DB as needing re-download.
244
+ /// The next `download` run will overwrite the bad `.osz` on disk.
245
+ #[arg(long)]
246
+ fix: bool,
247
+
248
+ /// Pin the worker pool to this many threads, disabling auto-tuning.
249
+ /// Use this when you know the right number for your disk; otherwise
250
+ /// the controller hill-climbs between `--min-workers` and `--max-workers`
251
+ /// to find the I/O sweet spot (best for HDDs, where 1–3 is typical).
252
+ #[arg(long, conflicts_with_all = ["min_workers", "max_workers"])]
253
+ workers: Option<usize>,
254
+
255
+ /// Lower bound for the adaptive worker pool.
256
+ #[arg(long, default_value_t = 1)]
257
+ min_workers: usize,
258
+
259
+ /// Upper bound for the adaptive worker pool.
260
+ #[arg(long, default_value_t = 8)]
261
+ max_workers: usize,
262
+ }
263
+
264
+ #[derive(clap::Args, Debug)]
265
+ struct RetryArgs {}
266
+
267
+ #[derive(clap::Args, Debug)]
268
+ struct DiscoverArgs {
269
+ /// Statuses to walk on each mirror. Repeatable, comma-separated.
270
+ /// Defaults to ranked + approved + loved + qualified (the dataset's
271
+ /// full leaderboard target). Mirrors that don't filter server-side
272
+ /// only walk once and the aggregator filters by status post-hoc.
273
+ #[arg(long, value_delimiter = ',',
274
+ default_values = ["ranked", "approved", "loved", "qualified"])]
275
+ statuses: Vec<String>,
276
+
277
+ /// Game mode integer. 0 = osu! standard.
278
+ #[arg(long, default_value_t = 0)]
279
+ mode: u8,
280
+
281
+ /// Cap pages-per-(mirror,status). Useful for smoke runs.
282
+ #[arg(long)]
283
+ max_pages: Option<u32>,
284
+
285
+ /// Minimum number of *independent* mirrors that must agree on a set
286
+ /// before it's auto-promoted to `wanted`. The default of 2 protects
287
+ /// against a single mirror's stale cache promoting ghost set IDs.
288
+ /// Set to 1 to accept any single-mirror sighting (use with caution).
289
+ #[arg(long, default_value_t = 2)]
290
+ min_quorum: u32,
291
+
292
+ /// Per-mirror discovery rate limit. Search endpoints are typically
293
+ /// faster than download endpoints, so we keep these separate.
294
+ #[arg(long, default_value_t = DEFAULT_RATE_LIMIT_RPM)]
295
+ nerinyan_search_rpm: u32,
296
+ #[arg(long, default_value_t = DEFAULT_RATE_LIMIT_RPM)]
297
+ osudirect_search_rpm: u32,
298
+ #[arg(long, default_value_t = DEFAULT_RATE_LIMIT_RPM)]
299
+ sayobot_search_rpm: u32,
300
+ #[arg(long, default_value_t = DEFAULT_RATE_LIMIT_RPM)]
301
+ nekoha_search_rpm: u32,
302
+
303
+ /// Disable a discovery source by name. Repeatable. Recognized values:
304
+ /// `nerinyan`, `osudirect`, `sayobot`, `nekoha`.
305
+ #[arg(long)]
306
+ disable: Vec<String>,
307
+
308
+ /// Skip the verifier pass. By default, after every list walk we run
309
+ /// per-set verifiers on candidates one mirror short of quorum to try
310
+ /// to push them over the line. Disabling saves HTTP calls at the
311
+ /// cost of leaving more sub-quorum candidates unresolved.
312
+ #[arg(long)]
313
+ no_verify: bool,
314
+
315
+ /// Stop a per-mirror walk after this many consecutive pages where
316
+ /// every entry got filtered out (status outside our target set, no
317
+ /// osu! standard difficulty). Without the fuse, sayobot's `T=4`
318
+ /// list eventually grinds into pending/graveyard rows that never
319
+ /// match. 0 disables the fuse (walk to true exhaustion).
320
+ #[arg(long, default_value_t = 10)]
321
+ consecutive_empty_break_pages: u32,
322
+
323
+ /// Per-page retry budget for transient errors (rate-limited,
324
+ /// network, 5xx). Backoff doubles each attempt: 2s, 4s, 8s, …
325
+ /// 0 disables retries.
326
+ #[arg(long, default_value_t = 3)]
327
+ retry_attempts: u32,
328
+ }
329
+
330
+ #[tokio::main]
331
+ async fn main() -> Result<()> {
332
+ let cli = Cli::parse();
333
+ init_tracing(cli.verbose);
334
+
335
+ let state = Arc::new(StateDb::open(&cli.state_db).context("opening state DB")?);
336
+ let config_path = config::resolve_config_path(cli.config.as_deref());
337
+ let cfg = Config::load_or_empty(&config_path)
338
+ .with_context(|| format!("loading config from {}", config_path.display()))?;
339
+ if config_path.exists() {
340
+ info!(path = %config_path.display(), "loaded config file");
341
+ }
342
+
343
+ match &cli.cmd {
344
+ Cmd::Status => cmd_status(state),
345
+ Cmd::Retry(_) => cmd_retry(state),
346
+ Cmd::Verify(args) => {
347
+ cmd_verify(state, &cli.archives_dir, args, progress_enabled(&cli)).await
348
+ }
349
+ Cmd::Scan(args) => {
350
+ cmd_scan(
351
+ state,
352
+ &cli.archives_dir,
353
+ args.verify,
354
+ progress_enabled(&cli),
355
+ )
356
+ .await
357
+ }
358
+ Cmd::Enumerate(args) => cmd_enumerate(state, &cli, args, &cfg).await,
359
+ Cmd::Download(args) => cmd_download(state, &cli, args, &cfg).await,
360
+ Cmd::Discover(args) => cmd_discover(state, &cli, args).await,
361
+ }
362
+ }
363
+
364
+ fn progress_enabled(cli: &Cli) -> bool {
365
+ !cli.no_progress && (cli.force_progress || progress::stderr_is_terminal())
366
+ }
367
+
368
+ fn download_progress_target(cli: &Cli) -> ProgressTarget {
369
+ if cli.no_progress {
370
+ ProgressTarget::Hidden
371
+ } else if cli.force_progress {
372
+ ProgressTarget::Tty
373
+ } else if progress::stderr_is_terminal() {
374
+ ProgressTarget::Stderr
375
+ } else {
376
+ ProgressTarget::Hidden
377
+ }
378
+ }
379
+
380
+ fn init_tracing(verbose: bool) {
381
+ use tracing_subscriber::{fmt, EnvFilter};
382
+ // Default keeps INFO globally but suppresses per-set INFO from
383
+ // `download` so the live dashboard isn't repainted by every "download
384
+ // ok" line. RUST_LOG overrides everything; --verbose flips download
385
+ // back to INFO.
386
+ let default = if verbose {
387
+ "info,osu_fetcher=info"
388
+ } else {
389
+ "info,osu_fetcher=info,osu_fetcher::download=warn"
390
+ };
391
+ let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new(default));
392
+ fmt()
393
+ .with_env_filter(filter)
394
+ .with_writer(std::io::stderr)
395
+ .init();
396
+ }
397
+
398
+ fn cmd_status(state: Arc<StateDb>) -> Result<()> {
399
+ let s = state.status_counts()?;
400
+ println!("wanted: {}", s.wanted);
401
+ println!("pending: {}", s.pending);
402
+ println!("in_progress: {}", s.in_progress);
403
+ println!("success: {}", s.success);
404
+ println!("failed: {}", s.failed);
405
+ println!("missing: {}", s.missing);
406
+ let queue = s.pending + s.in_progress;
407
+ println!("--");
408
+ println!(
409
+ "queue (pending + in_progress): {queue} ({:.1}% of wanted)",
410
+ if s.wanted == 0 {
411
+ 0.0
412
+ } else {
413
+ 100.0 * queue as f64 / s.wanted as f64
414
+ }
415
+ );
416
+ Ok(())
417
+ }
418
+
419
+ fn cmd_retry(state: Arc<StateDb>) -> Result<()> {
420
+ let n = state.reset_failed_to_pending()?;
421
+ println!("reset {n} failed/missing rows back to pending");
422
+ Ok(())
423
+ }
424
+
425
+ async fn cmd_verify(
426
+ state: Arc<StateDb>,
427
+ archives_dir: &std::path::Path,
428
+ args: &VerifyArgs,
429
+ progress_enabled: bool,
430
+ ) -> Result<()> {
431
+ let opts = AdaptiveVerifyOptions {
432
+ min_workers: args.min_workers.max(1),
433
+ max_workers: args.max_workers.max(args.min_workers.max(1)),
434
+ fixed_workers: args.workers,
435
+ fix: args.fix,
436
+ progress: progress_enabled,
437
+ };
438
+ let stats = verify::run_adaptive(state, archives_dir, opts).await?;
439
+ if stats.aborted_remaining > 0 {
440
+ // Non-zero exit so scripts can detect a partial verify run.
441
+ std::process::exit(130);
442
+ }
443
+ Ok(())
444
+ }
445
+
446
+ async fn cmd_scan(
447
+ state: Arc<StateDb>,
448
+ archives_dir: &std::path::Path,
449
+ verify: bool,
450
+ progress_enabled: bool,
451
+ ) -> Result<()> {
452
+ let spinner = CounterSpinner::new("scan", progress_enabled);
453
+ let stats = scan::scan_archives(state, archives_dir, verify, Some(&spinner)).await?;
454
+ spinner.finish(format!(
455
+ "done · seen {} · recorded {} · bad name {} · bad archive {}",
456
+ stats.seen, stats.recorded, stats.bad_name, stats.bad_archive
457
+ ));
458
+ println!(
459
+ "scan: seen={} recorded={} bad_name={} bad_archive={}",
460
+ stats.seen, stats.recorded, stats.bad_name, stats.bad_archive
461
+ );
462
+ Ok(())
463
+ }
464
+
465
+ async fn cmd_enumerate(
466
+ state: Arc<StateDb>,
467
+ cli: &Cli,
468
+ args: &EnumerateArgs,
469
+ cfg: &Config,
470
+ ) -> Result<()> {
471
+ let auth = build_osu_auth(cli, cfg)?;
472
+ info!(mode = auth.mode_label(), "osu! API auth configured");
473
+ // Eager auth: do the password grant + any 2FA prompt up front so the
474
+ // dashboard doesn't render mid-prompt (and so missing creds fail fast).
475
+ let _ = auth
476
+ .current_token()
477
+ .await
478
+ .context("authenticating to osu! API")?;
479
+ let api = OsuApi::new(auth, RateLimited::per_minute("osu_api", cli.osu_rpm));
480
+
481
+ let progress_enabled = progress_enabled(cli);
482
+ let mut grand = EnumerateStats::default();
483
+ for raw in &args.statuses {
484
+ let status: RankedStatus = raw
485
+ .parse()
486
+ .map_err(|e| anyhow!("--statuses {raw:?}: {e}"))?;
487
+ info!(status = status.as_api_str(), "enumerate begin");
488
+ let spinner = CounterSpinner::new(status.as_api_str(), progress_enabled);
489
+ let stats = enumerate::enumerate_status(
490
+ api.clone(),
491
+ state.clone(),
492
+ status,
493
+ EnumerateOptions {
494
+ mode: args.mode,
495
+ max_pages: args.max_pages,
496
+ require_matching_mode_difficulty: !args.no_mode_filter,
497
+ full_rescan: args.full_rescan,
498
+ sort: args.sort.into(),
499
+ stateless: args.stateless,
500
+ },
501
+ Some(&spinner),
502
+ )
503
+ .await?;
504
+ spinner.finish(format!(
505
+ "done · pages {} · seen {} · upserted {} · skipped {}",
506
+ stats.pages, stats.seen, stats.upserted, stats.skipped_no_osu_mode,
507
+ ));
508
+ info!(
509
+ status = status.as_api_str(),
510
+ pages = stats.pages,
511
+ seen = stats.seen,
512
+ upserted = stats.upserted,
513
+ skipped = stats.skipped_no_osu_mode,
514
+ "enumerate done"
515
+ );
516
+ grand.pages += stats.pages;
517
+ grand.seen += stats.seen;
518
+ grand.upserted += stats.upserted;
519
+ grand.skipped_no_osu_mode += stats.skipped_no_osu_mode;
520
+ }
521
+ println!(
522
+ "enumerate: pages={} seen={} upserted={} skipped_mode={}",
523
+ grand.pages, grand.seen, grand.upserted, grand.skipped_no_osu_mode
524
+ );
525
+ Ok(())
526
+ }
527
+
528
+ async fn cmd_download(
529
+ state: Arc<StateDb>,
530
+ cli: &Cli,
531
+ args: &DownloadArgs,
532
+ cfg: &Config,
533
+ ) -> Result<()> {
534
+ // Hold the run-lock for the lifetime of this download. OS releases it
535
+ // automatically on process exit (graceful, panic, SIGKILL, power-off)
536
+ // so a second `osu_fetcher download` started concurrently bails out
537
+ // cleanly instead of stomping on this run's claims.
538
+ let lock_path = lock_path_for(&cli.state_db);
539
+ let _lock = DownloadLock::acquire(&lock_path).context("acquiring download run lock")?;
540
+ info!(path = %lock_path.display(), "acquired download run lock");
541
+
542
+ // The dataset only ever wants the complete archive (video + storyboard
543
+ // + skin + hitsounds). The CLI used to expose a `--flavor` flag but
544
+ // it's gone now so a mid-run footgun can't pollute archives_dir with
545
+ // novideo variants. The `Flavor` enum stays in the library so mirror
546
+ // impls retain their flavor-aware URL builders for future use.
547
+ let flavor: Flavor = Flavor::Full;
548
+ // Build the osu! API client best-effort — the public mirrors don't
549
+ // need it, so missing credentials shouldn't fail `download`. If it
550
+ // builds, the `osuapi` mirror joins the pool; if not, it's skipped.
551
+ // We also eagerly mint a token here so any 2FA prompt happens *before*
552
+ // the dashboard takes over the screen — much friendlier than having
553
+ // a stdin prompt fight the live progress bar.
554
+ let osu_api = match build_osu_auth(cli, cfg) {
555
+ Ok(auth) => {
556
+ info!(mode = auth.mode_label(), "osu! API auth configured");
557
+ match auth.current_token().await {
558
+ Ok(_) => Some(OsuApi::new(
559
+ auth,
560
+ RateLimited::per_minute("osu_api", cli.osu_rpm),
561
+ )),
562
+ Err(e) => {
563
+ warn!(
564
+ error = %e,
565
+ "osu! API authentication failed; osuapi mirror disabled for this run"
566
+ );
567
+ None
568
+ }
569
+ }
570
+ }
571
+ Err(e) => {
572
+ warn!(error = %e, "osu! API credentials not configured; osuapi mirror disabled");
573
+ None
574
+ }
575
+ };
576
+ let pool = build_pool(cli, cfg, osu_api)?;
577
+ info!(
578
+ mirrors = ?pool.names(),
579
+ concurrency = args.concurrency,
580
+ flavor = flavor.as_str(),
581
+ "download begin"
582
+ );
583
+
584
+ let token = CancellationToken::new();
585
+ let token_clone = token.clone();
586
+ tokio::spawn(async move {
587
+ if tokio::signal::ctrl_c().await.is_ok() {
588
+ warn!("Ctrl-C received; signalling shutdown");
589
+ token_clone.cancel();
590
+ }
591
+ });
592
+
593
+ // Compute total *up front* so the bar has a real ceiling. We read the
594
+ // queue size after lock acquisition so it reflects what this run will
595
+ // actually attempt (including in_progress rows that requeue_in_progress
596
+ // will recover at the start of run()).
597
+ let total_pending = state
598
+ .count_pending_wanted()
599
+ .context("counting pending sets")?;
600
+ let total = match args.limit {
601
+ Some(lim) => lim.min(total_pending),
602
+ None => total_pending,
603
+ };
604
+ let mirror_names = pool.names();
605
+ let dashboard = DownloadDashboard::new(
606
+ total,
607
+ args.concurrency,
608
+ &mirror_names,
609
+ download_progress_target(cli),
610
+ );
611
+ let tick_shutdown = CancellationToken::new();
612
+ let tick_handle = progress::spawn_tick_task(dashboard.clone(), tick_shutdown.clone());
613
+
614
+ let stats = download::run(
615
+ state,
616
+ Arc::new(pool),
617
+ DownloadOptions {
618
+ archives_dir: cli.archives_dir.clone(),
619
+ flavor,
620
+ concurrency: args.concurrency,
621
+ limit: args.limit,
622
+ },
623
+ token,
624
+ Some(dashboard.clone()),
625
+ )
626
+ .await?;
627
+
628
+ tick_shutdown.cancel();
629
+ let _ = tick_handle.await;
630
+ dashboard.finalize();
631
+
632
+ println!(
633
+ "download: attempted={} success={} failed={} missing={} aborted={}",
634
+ stats.attempted, stats.success, stats.failed, stats.missing, stats.aborted
635
+ );
636
+ Ok(())
637
+ }
638
+
639
+ async fn cmd_discover(state: Arc<StateDb>, cli: &Cli, args: &DiscoverArgs) -> Result<()> {
640
+ // Parse statuses up front so a typo in --statuses fails before we
641
+ // build the mirror pool and warm any HTTP connections.
642
+ let mut want_statuses: Vec<RankedStatus> = Vec::new();
643
+ for raw in &args.statuses {
644
+ let s: RankedStatus = raw
645
+ .parse()
646
+ .map_err(|e| anyhow!("--statuses {raw:?}: {e}"))?;
647
+ if !want_statuses.contains(&s) {
648
+ want_statuses.push(s);
649
+ }
650
+ }
651
+
652
+ let client = discover::build_client().context("build discover http client")?;
653
+ let limiters = DiscoverLimiters {
654
+ nerinyan: RateLimited::per_minute("nerinyan_search", args.nerinyan_search_rpm),
655
+ osudirect: RateLimited::per_minute("osudirect_search", args.osudirect_search_rpm),
656
+ sayobot: RateLimited::per_minute("sayobot_search", args.sayobot_search_rpm),
657
+ nekoha: RateLimited::per_minute("nekoha_search", args.nekoha_search_rpm),
658
+ };
659
+ let ctx = DiscoverContext { client, limiters };
660
+
661
+ let disabled: Vec<String> = args
662
+ .disable
663
+ .iter()
664
+ .map(|s| s.to_ascii_lowercase())
665
+ .collect();
666
+ let is_enabled = |name: &str| !disabled.iter().any(|d| d == &name.to_ascii_lowercase());
667
+
668
+ let mut search_sources: Vec<Arc<dyn MirrorSearch>> = Vec::new();
669
+ if is_enabled("nerinyan") {
670
+ search_sources.push(Arc::new(NerinyanSearch::new(&ctx)));
671
+ }
672
+ if is_enabled("osudirect") {
673
+ search_sources.push(Arc::new(OsuDirectSearch::new(&ctx)));
674
+ }
675
+ if is_enabled("sayobot") {
676
+ search_sources.push(Arc::new(SayobotSearch::new(&ctx)));
677
+ }
678
+
679
+ let mut verifiers: Vec<Arc<dyn MirrorVerify>> = Vec::new();
680
+ if !args.no_verify {
681
+ if is_enabled("nekoha") {
682
+ verifiers.push(Arc::new(NekohaVerify::new(&ctx)));
683
+ }
684
+ if is_enabled("osudirect") {
685
+ verifiers.push(Arc::new(OsuDirectVerify::new(&ctx)));
686
+ }
687
+ if is_enabled("sayobot") {
688
+ verifiers.push(Arc::new(SayobotVerify::new(&ctx)));
689
+ }
690
+ }
691
+
692
+ if search_sources.is_empty() {
693
+ anyhow::bail!("every discovery source is disabled; nothing to do");
694
+ }
695
+
696
+ let names: Vec<&str> = search_sources.iter().map(|m| m.name()).collect();
697
+ info!(sources = ?names, statuses = ?args.statuses, quorum = args.min_quorum,
698
+ verifiers = verifiers.len(), "discover begin");
699
+
700
+ // We leak `want_statuses` only when we can't borrow it as a `&'static [RankedStatus]`.
701
+ // Since `DiscoverOptions::statuses` is `&'static`, build the slice from the
702
+ // default helper when the user passed exactly that set; otherwise box-and-leak.
703
+ let statuses_slice: &'static [RankedStatus] = leak_statuses(want_statuses);
704
+
705
+ let opts = DiscoverOptions {
706
+ mode: args.mode,
707
+ max_pages_per_mirror_status: args.max_pages,
708
+ statuses: statuses_slice,
709
+ min_quorum: args.min_quorum,
710
+ consecutive_empty_break_pages: args.consecutive_empty_break_pages,
711
+ retry_attempts: args.retry_attempts,
712
+ };
713
+
714
+ // Same gating policy as the other long-running subcommands. When off,
715
+ // the spinners short-circuit to no-ops.
716
+ let progress_enabled = progress_enabled(cli);
717
+
718
+ let stats =
719
+ discover::discover_all(state, &search_sources, &verifiers, opts, progress_enabled).await?;
720
+ println!(
721
+ "discover: pages={} reports={} sets_seen={} promoted={} sub_quorum={}",
722
+ stats.pages,
723
+ stats.reports_recorded,
724
+ stats.sets_seen,
725
+ stats.promoted_to_wanted,
726
+ stats.sub_quorum_candidates,
727
+ );
728
+ Ok(())
729
+ }
730
+
731
+ /// Convert a runtime `Vec<RankedStatus>` into the `&'static [RankedStatus]`
732
+ /// `DiscoverOptions` expects. We deliberately leak — discover runs once
733
+ /// per process, and copying the small slice is cheaper than threading a
734
+ /// lifetime through the entire pipeline.
735
+ fn leak_statuses(s: Vec<RankedStatus>) -> &'static [RankedStatus] {
736
+ Box::leak(s.into_boxed_slice())
737
+ }
738
+
739
+ /// Lockfile lives next to the state DB so per-DB isolation is preserved
740
+ /// (a user running two distinct DBs on the same machine doesn't deadlock).
741
+ fn lock_path_for(state_db: &std::path::Path) -> PathBuf {
742
+ let mut p = state_db.to_path_buf();
743
+ let new_name = match p.file_name().and_then(|s| s.to_str()) {
744
+ Some(n) => format!("{n}.run.lock"),
745
+ None => String::from(".fetcher.run.lock"),
746
+ };
747
+ p.set_file_name(new_name);
748
+ p
749
+ }
750
+
751
+ /// Pick an auth mode based on what credentials the user provided.
752
+ ///
753
+ /// Lazer mode (`username` + `password`) wins when both are present —
754
+ /// downloads only work with the user-scoped token it produces, and nothing
755
+ /// in the read-only enumeration path needs anything stricter than what
756
+ /// lazer-mode provides. We only fall back to client_credentials when the
757
+ /// user explicitly registered an OAuth app and *didn't* supply a login.
758
+ fn select_auth_mode(resolved: &ResolvedOsuCreds) -> Result<OsuAuthMode> {
759
+ if let (Some(u), Some(p)) = (resolved.username.as_deref(), resolved.password.as_deref()) {
760
+ return Ok(OsuAuthMode::LazerPassword {
761
+ username: u.to_string(),
762
+ password: p.to_string(),
763
+ });
764
+ }
765
+ if let (Some(id), Some(secret)) = (
766
+ resolved.client_id.as_deref(),
767
+ resolved.client_secret.as_deref(),
768
+ ) {
769
+ return Ok(OsuAuthMode::ClientCredentials {
770
+ client_id: id.to_string(),
771
+ client_secret: secret.to_string(),
772
+ });
773
+ }
774
+ Err(anyhow!(
775
+ "no osu! API credentials configured. Provide either:\n \
776
+ (a) [osu_api] username + password (or OSU_USERNAME / OSU_PASSWORD env vars) \
777
+ — preferred; uses the lazer-impersonation flow and unlocks the \
778
+ /api/v2/beatmapsets/{{id}}/download endpoint, or\n \
779
+ (b) [osu_api] client_id + client_secret (or OSU_CLIENT_ID / OSU_CLIENT_SECRET) \
780
+ — registered at https://osu.ppy.sh/home/account/edit#oauth; sufficient for \
781
+ enumerate but not for the osuapi download mirror.\n\
782
+ Config file expected at {}.",
783
+ config::DEFAULT_CONFIG_FILENAME
784
+ ))
785
+ }
786
+
787
+ /// Default token-cache path: `<state_db>.osu_token.json` next to the DB.
788
+ /// Kept beside the state DB so swapping `--state-db` between projects also
789
+ /// swaps the token file (different state DB = different "session").
790
+ fn default_token_path(state_db: &std::path::Path) -> PathBuf {
791
+ let mut p = state_db.to_path_buf();
792
+ let new_name = match p.file_name().and_then(|s| s.to_str()) {
793
+ Some(n) => format!("{n}.osu_token.json"),
794
+ None => String::from(".fetcher.osu_token.json"),
795
+ };
796
+ p.set_file_name(new_name);
797
+ p
798
+ }
799
+
800
+ fn build_osu_auth(cli: &Cli, cfg: &Config) -> Result<Arc<OsuAuth>> {
801
+ let resolved = cfg.osu_credentials();
802
+ let mode = select_auth_mode(&resolved)?;
803
+ let token_file = Some(
804
+ cli.osu_token_file
805
+ .clone()
806
+ .unwrap_or_else(|| default_token_path(&cli.state_db)),
807
+ );
808
+ OsuAuth::new(mode, token_file)
809
+ }
810
+
811
+ fn build_pool(cli: &Cli, cfg: &Config, osu_api: Option<Arc<OsuApi>>) -> Result<MirrorPool> {
812
+ let client = build_client().context("build reqwest client")?;
813
+ let limiters = MirrorLimiters {
814
+ nerinyan: RateLimited::per_minute("nerinyan", cli.nerinyan_rpm),
815
+ catboy: RateLimited::per_minute("catboy", cli.catboy_rpm),
816
+ sayobot: RateLimited::per_minute("sayobot", cli.sayobot_rpm),
817
+ nekoha: RateLimited::per_minute("nekoha", cli.nekoha_rpm),
818
+ beatconnect: RateLimited::per_minute("beatconnect", cli.beatconnect_rpm),
819
+ osudirect: RateLimited::per_minute("osudirect", cli.osudirect_rpm),
820
+ nzbasic: RateLimited::per_minute("nzbasic", cli.nzbasic_rpm),
821
+ osudl: RateLimited::per_minute("osudl", cli.osudl_rpm),
822
+ osuapi: RateLimited::per_minute("osuapi", cli.osuapi_rpm),
823
+ };
824
+ let ctx = MirrorContext {
825
+ client,
826
+ limiters,
827
+ osu_api,
828
+ };
829
+
830
+ let disabled = cli
831
+ .disable
832
+ .iter()
833
+ .map(|s| s.to_ascii_lowercase())
834
+ .collect::<Vec<_>>();
835
+ let is_enabled = |name: &str| !disabled.iter().any(|d| d == &name.to_ascii_lowercase());
836
+
837
+ let mut mirrors: Vec<Arc<dyn Mirror>> = Vec::new();
838
+ if is_enabled("nerinyan") {
839
+ mirrors.push(Arc::new(NerinyanMirror::new(&ctx)));
840
+ }
841
+ if is_enabled("catboy") {
842
+ mirrors.push(Arc::new(CatboyMirror::new(&ctx)));
843
+ }
844
+ if is_enabled("osudirect") {
845
+ mirrors.push(Arc::new(OsuDirectMirror::new(&ctx)));
846
+ }
847
+ if is_enabled("nekoha") {
848
+ mirrors.push(Arc::new(NekohaMirror::new(&ctx)));
849
+ }
850
+ if is_enabled("nzbasic") {
851
+ mirrors.push(Arc::new(NzbasicMirror::new(&ctx)));
852
+ }
853
+ if is_enabled("osudl") {
854
+ mirrors.push(Arc::new(OsudlMirror::new(&ctx)));
855
+ }
856
+ if is_enabled("sayobot") {
857
+ mirrors.push(Arc::new(SayobotMirror::new(&ctx)));
858
+ }
859
+ if is_enabled("beatconnect") {
860
+ match cfg.beatconnect_api_key() {
861
+ Some(key) => mirrors.push(Arc::new(BeatconnectMirror::new(&ctx, key))),
862
+ None => warn!(
863
+ "beatconnect skipped: no [mirrors.beatconnect].api_key in config and \
864
+ BEATCONNECT_API_KEY env var is unset"
865
+ ),
866
+ }
867
+ }
868
+ if is_enabled("osuapi") {
869
+ match OsuApiMirror::new(&ctx) {
870
+ Some(m) => mirrors.push(Arc::new(m)),
871
+ None => warn!(
872
+ "osuapi skipped: no osu! API credentials available — set [osu_api] in \
873
+ config or OSU_CLIENT_ID / OSU_CLIENT_SECRET to enable the official \
874
+ download endpoint"
875
+ ),
876
+ }
877
+ }
878
+
879
+ if mirrors.is_empty() {
880
+ anyhow::bail!("every mirror is disabled; nothing to do");
881
+ }
882
+ let attempt_timeout = match cli.mirror_timeout_secs {
883
+ 0 => None,
884
+ s => Some(std::time::Duration::from_secs(s)),
885
+ };
886
+ Ok(MirrorPool::with_attempt_timeout(mirrors, attempt_timeout))
887
+ }
crates/osu_fetcher/src/mirrors/beatconnect.rs ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //! beatconnect.io — requires an API key passed via `token` query parameter.
2
+ //!
3
+ //! Endpoints (per <https://beatconnect.io/api/docs/>):
4
+ //! * `GET https://beatconnect.io/b/{set_id}?token=<key>` — full archive
5
+ //! * No documented "novideo" variant; we only register `Full` support.
6
+ //!
7
+ //! beatconnect tends to be slower than the other mirrors and carries a
8
+ //! historical archive that occasionally has maps the others don't. It earns a
9
+ //! place in the fallback chain but should be ranked last by default so we
10
+ //! don't burn its rate budget when faster mirrors would have served the file.
11
+
12
+ use async_trait::async_trait;
13
+ use bytes::Bytes;
14
+ use reqwest::Client;
15
+
16
+ use super::{classify_response, Mirror, MirrorContext, MirrorError};
17
+ use crate::ratelimit::RateLimited;
18
+ use crate::Flavor;
19
+
20
+ pub const NAME: &str = "beatconnect";
21
+ const BASE: &str = "https://beatconnect.io/b";
22
+
23
+ pub struct BeatconnectMirror {
24
+ client: Client,
25
+ limiter: RateLimited,
26
+ api_key: String,
27
+ }
28
+
29
+ impl BeatconnectMirror {
30
+ pub fn new(ctx: &MirrorContext, api_key: String) -> Self {
31
+ Self {
32
+ client: ctx.client.clone(),
33
+ limiter: ctx.limiters.beatconnect.clone(),
34
+ api_key,
35
+ }
36
+ }
37
+
38
+ pub fn url(set_id: u64, api_key: &str) -> String {
39
+ // The API key goes via a query parameter so it survives 30x redirect
40
+ // bounces (some headers don't). Tokens are scoped to the user's
41
+ // account and are not bearer-grade — exposing them in a URL is the
42
+ // documented usage.
43
+ format!("{BASE}/{set_id}?token={api_key}")
44
+ }
45
+ }
46
+
47
+ #[async_trait]
48
+ impl Mirror for BeatconnectMirror {
49
+ fn name(&self) -> &str {
50
+ NAME
51
+ }
52
+
53
+ fn supports(&self, flavor: Flavor) -> bool {
54
+ matches!(flavor, Flavor::Full)
55
+ }
56
+
57
+ async fn download(&self, set_id: u64, flavor: Flavor) -> Result<Bytes, MirrorError> {
58
+ if !self.supports(flavor) {
59
+ return Err(MirrorError::UnsupportedFlavor {
60
+ mirror: NAME.into(),
61
+ flavor,
62
+ });
63
+ }
64
+ self.limiter.acquire().await;
65
+ let url = Self::url(set_id, &self.api_key);
66
+ let resp = self
67
+ .client
68
+ .get(&url)
69
+ .send()
70
+ .await
71
+ .map_err(|e| MirrorError::Network {
72
+ mirror: NAME.into(),
73
+ source: e,
74
+ })?;
75
+ classify_response(NAME, resp).await
76
+ }
77
+ }
78
+
79
+ #[cfg(test)]
80
+ mod tests {
81
+ use super::*;
82
+
83
+ #[test]
84
+ fn url_includes_token_in_query_string() {
85
+ let url = BeatconnectMirror::url(789, "deadbeef");
86
+ assert_eq!(url, "https://beatconnect.io/b/789?token=deadbeef");
87
+ }
88
+
89
+ #[test]
90
+ fn novideo_is_not_supported() {
91
+ // The mirror impl needs a `MirrorContext` to construct, which means a
92
+ // live `RateLimited`; we exercise the static `supports` predicate
93
+ // through a thin wrapper that doesn't hit the network.
94
+ let supports_full = matches!(Flavor::Full, Flavor::Full);
95
+ let supports_novideo = matches!(Flavor::NoVideo, Flavor::Full);
96
+ assert!(supports_full);
97
+ assert!(!supports_novideo);
98
+ }
99
+ }
crates/osu_fetcher/src/mirrors/catboy.rs ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //! catboy.best — public mirror (operated by osu.direct), no auth required.
2
+ //!
3
+ //! Endpoint:
4
+ //! * `GET https://catboy.best/d/{set_id}` — full archive
5
+ //! * `GET https://catboy.best/d/{set_id}n` — novideo (suffix `n` selects)
6
+ //!
7
+ //! catboy serves both flavors via the same path style; the URL form is the
8
+ //! only difference.
9
+
10
+ use async_trait::async_trait;
11
+ use bytes::Bytes;
12
+ use reqwest::Client;
13
+
14
+ use super::{classify_response, Mirror, MirrorContext, MirrorError};
15
+ use crate::ratelimit::RateLimited;
16
+ use crate::Flavor;
17
+
18
+ pub const NAME: &str = "catboy";
19
+ const BASE: &str = "https://catboy.best/d";
20
+
21
+ pub struct CatboyMirror {
22
+ client: Client,
23
+ limiter: RateLimited,
24
+ }
25
+
26
+ impl CatboyMirror {
27
+ pub fn new(ctx: &MirrorContext) -> Self {
28
+ Self {
29
+ client: ctx.client.clone(),
30
+ limiter: ctx.limiters.catboy.clone(),
31
+ }
32
+ }
33
+
34
+ pub fn url(set_id: u64, flavor: Flavor) -> String {
35
+ match flavor {
36
+ Flavor::Full => format!("{BASE}/{set_id}"),
37
+ Flavor::NoVideo => format!("{BASE}/{set_id}n"),
38
+ }
39
+ }
40
+ }
41
+
42
+ #[async_trait]
43
+ impl Mirror for CatboyMirror {
44
+ fn name(&self) -> &str {
45
+ NAME
46
+ }
47
+
48
+ fn supports(&self, _flavor: Flavor) -> bool {
49
+ true
50
+ }
51
+
52
+ async fn download(&self, set_id: u64, flavor: Flavor) -> Result<Bytes, MirrorError> {
53
+ self.limiter.acquire().await;
54
+ let url = Self::url(set_id, flavor);
55
+ let resp = self
56
+ .client
57
+ .get(&url)
58
+ .send()
59
+ .await
60
+ .map_err(|e| MirrorError::Network {
61
+ mirror: NAME.into(),
62
+ source: e,
63
+ })?;
64
+ classify_response(NAME, resp).await
65
+ }
66
+ }
67
+
68
+ #[cfg(test)]
69
+ mod tests {
70
+ use super::*;
71
+
72
+ #[test]
73
+ fn url_full_uses_plain_id() {
74
+ assert_eq!(
75
+ CatboyMirror::url(123, Flavor::Full),
76
+ "https://catboy.best/d/123"
77
+ );
78
+ }
79
+
80
+ #[test]
81
+ fn url_novideo_appends_n_suffix() {
82
+ assert_eq!(
83
+ CatboyMirror::url(123, Flavor::NoVideo),
84
+ "https://catboy.best/d/123n"
85
+ );
86
+ }
87
+ }
crates/osu_fetcher/src/mirrors/mod.rs ADDED
@@ -0,0 +1,1138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //! Mirror abstraction + pool.
2
+ //!
3
+ //! Every concrete download mirror implements [`Mirror`] and is pushed into a
4
+ //! [`MirrorPool`]. The pool tries mirrors in priority order; on a recoverable
5
+ //! failure (any error other than [`MirrorError::Aborted`]) it advances to the
6
+ //! next mirror. Each individual attempt — success or failure — is reported
7
+ //! via [`AttemptRecord`] so the caller can log it to the state DB without the
8
+ //! pool having to know about persistence.
9
+ //!
10
+ //! Mirrors are *I/O-only*: they own a [`reqwest::Client`] and a
11
+ //! [`crate::ratelimit::RateLimited`] keyed on the mirror's name. They never
12
+ //! touch the filesystem or the state DB. This keeps each mirror impl small
13
+ //! enough to test by stubbing the URL through a wiremock server.
14
+
15
+ use std::sync::Arc;
16
+ use std::sync::Mutex;
17
+ use std::time::Duration;
18
+
19
+ use async_trait::async_trait;
20
+ use bytes::Bytes;
21
+ use reqwest::{Client, StatusCode};
22
+ use thiserror::Error;
23
+ use tokio::time::Instant;
24
+
25
+ use crate::api::OsuApi;
26
+ use crate::ratelimit::RateLimited;
27
+ use crate::verify::verify_bytes;
28
+ use crate::Flavor;
29
+
30
+ pub mod beatconnect;
31
+ pub mod catboy;
32
+ pub mod nekoha;
33
+ pub mod nerinyan;
34
+ pub mod nzbasic;
35
+ pub mod osuapi;
36
+ pub mod osudirect;
37
+ pub mod osudl;
38
+ pub mod sayobot;
39
+
40
+ #[derive(Debug, Error)]
41
+ pub enum MirrorError {
42
+ /// Server-confirmed: this set isn't here. Try next mirror.
43
+ #[error("not found on {mirror}")]
44
+ NotFound { mirror: String },
45
+
46
+ /// Server told us to slow down. The wrapper records this and tries the
47
+ /// next mirror; the limiter on this mirror will catch up via natural
48
+ /// pacing on the next iteration.
49
+ #[error("{mirror} rate limited")]
50
+ RateLimited { mirror: String },
51
+
52
+ /// Anything other than 2xx/404/429.
53
+ #[error("{mirror} returned HTTP {status}")]
54
+ HttpError {
55
+ mirror: String,
56
+ status: u16,
57
+ body_snippet: String,
58
+ },
59
+
60
+ /// Connection errors, timeouts, DNS, TLS — any pre-response failure.
61
+ #[error("{mirror} network error: {source}")]
62
+ Network {
63
+ mirror: String,
64
+ #[source]
65
+ source: reqwest::Error,
66
+ },
67
+
68
+ /// We got bytes back but they don't look like a `.osz` (no ZIP magic, or
69
+ /// truncated, or HTML error page slipped through). Treated as a recoverable
70
+ /// failure; try next mirror.
71
+ #[error("{mirror} returned invalid archive: {reason}")]
72
+ InvalidArchive { mirror: String, reason: String },
73
+
74
+ /// The mirror declines this flavor (e.g., novideo-only mirror with a
75
+ /// `Full` request). Try the next mirror without recording an attempt as
76
+ /// a failure.
77
+ #[error("{mirror} does not serve {flavor:?}")]
78
+ UnsupportedFlavor { mirror: String, flavor: Flavor },
79
+
80
+ /// Per-attempt wallclock deadline expired before the mirror returned a
81
+ /// response. Treated as a hard failure (try next mirror; penalize this
82
+ /// mirror's health like a Network error). The pool, not the individual
83
+ /// mirror, enforces this — mirrors all share the same per-call deadline.
84
+ #[error("{mirror} timed out after {after_secs}s")]
85
+ Timeout { mirror: String, after_secs: u64 },
86
+
87
+ /// Caller-side cancel. Stop the pool entirely.
88
+ #[error("download aborted")]
89
+ Aborted,
90
+ }
91
+
92
+ impl MirrorError {
93
+ pub fn mirror_name(&self) -> &str {
94
+ match self {
95
+ MirrorError::NotFound { mirror }
96
+ | MirrorError::RateLimited { mirror }
97
+ | MirrorError::HttpError { mirror, .. }
98
+ | MirrorError::Network { mirror, .. }
99
+ | MirrorError::InvalidArchive { mirror, .. }
100
+ | MirrorError::Timeout { mirror, .. }
101
+ | MirrorError::UnsupportedFlavor { mirror, .. } => mirror,
102
+ MirrorError::Aborted => "(none)",
103
+ }
104
+ }
105
+ }
106
+
107
+ /// Result of one HTTP attempt against a single mirror.
108
+ #[derive(Debug)]
109
+ pub struct AttemptRecord {
110
+ pub mirror: String,
111
+ pub duration: Duration,
112
+ pub http_status: Option<u16>,
113
+ pub bytes: Option<u64>,
114
+ pub error: Option<String>,
115
+ pub outcome: AttemptOutcome,
116
+ }
117
+
118
+ #[derive(Clone, Copy, Debug, Eq, PartialEq)]
119
+ pub enum AttemptOutcome {
120
+ Success,
121
+ NotFound,
122
+ HttpError,
123
+ RateLimited,
124
+ Network,
125
+ InvalidArchive,
126
+ /// Mirror call exceeded the pool's per-attempt deadline.
127
+ Timeout,
128
+ UnsupportedFlavor,
129
+ }
130
+
131
+ #[async_trait]
132
+ pub trait Mirror: Send + Sync {
133
+ fn name(&self) -> &str;
134
+
135
+ /// True if this mirror can serve the requested flavor. If false, the pool
136
+ /// short-circuits to `MirrorError::UnsupportedFlavor` before any HTTP.
137
+ fn supports(&self, flavor: Flavor) -> bool;
138
+
139
+ /// Fetch one beatmapset's `.osz` bytes.
140
+ async fn download(&self, set_id: u64, flavor: Flavor) -> Result<Bytes, MirrorError>;
141
+ }
142
+
143
+ /// Lightweight observer plugged into the pool's per-attempt loop so an
144
+ /// outside watcher (the live dashboard) can track which mirrors are
145
+ /// currently in-flight without the pool having to know about progress UI.
146
+ /// Both methods default to no-op so non-observing callers can ignore it.
147
+ pub trait AttemptObserver: Send + Sync {
148
+ fn before_attempt(&self, _mirror: &str) {}
149
+ fn after_attempt(&self, _mirror: &str) {}
150
+ }
151
+
152
+ /// Used by `MirrorPool::download` when no observer is provided.
153
+ pub struct NoOpObserver;
154
+ impl AttemptObserver for NoOpObserver {}
155
+
156
+ /// Per-mirror health snapshot used by the selector. Held under a single
157
+ /// pool-wide `Mutex` — selection is fast (≤5 floats per call) and
158
+ /// updates are once-per-attempt, so contention is irrelevant compared to
159
+ /// the network round-trip.
160
+ #[derive(Clone, Debug)]
161
+ struct MirrorHealth {
162
+ /// EWMA of "did this attempt succeed". Range [0, 1]. Starts at 1.0 so
163
+ /// untested mirrors get the benefit of the doubt.
164
+ score: f64,
165
+ /// EWMA of successful-attempt latency in milliseconds. 0 = unknown.
166
+ /// Kept for diagnostics; not used in the selection weight (latency is
167
+ /// confounded with archive size; we use bandwidth instead).
168
+ avg_latency_ms: f64,
169
+ /// EWMA of throughput across successful attempts, in bytes/sec.
170
+ /// 0.0 = unknown — fresh mirrors get a neutral default in `weight()`
171
+ /// so they get fair attempts before being judged. This is the *real*
172
+ /// "is this mirror fast" metric: a mirror downloading 50 MB sets in
173
+ /// 5s has the same bandwidth as one downloading 5 MB sets in 0.5s,
174
+ /// even though their per-request latencies differ 10×.
175
+ avg_bandwidth_bps: f64,
176
+ /// Total attempts we've recorded — used to gate the "dormant"
177
+ /// classification so a single failure on a fresh mirror doesn't kill it.
178
+ attempts: u32,
179
+ /// Consecutive non-success non-NotFound outcomes. Resets to 0 on any
180
+ /// success or NotFound (NotFound = mirror is alive, just doesn't have
181
+ /// this set; not a health signal).
182
+ consecutive_hard_failures: u32,
183
+ /// Smooth weighted round-robin: accumulator for selection.
184
+ swrr_current: f64,
185
+ }
186
+
187
+ impl MirrorHealth {
188
+ fn fresh() -> Self {
189
+ Self {
190
+ score: 1.0,
191
+ avg_latency_ms: 0.0,
192
+ avg_bandwidth_bps: 0.0,
193
+ attempts: 0,
194
+ consecutive_hard_failures: 0,
195
+ swrr_current: 0.0,
196
+ }
197
+ }
198
+
199
+ /// Composite weight used for selection. Higher = more attractive.
200
+ /// `score²` (sharply punishes flaky mirrors) × `bandwidth_mbps`
201
+ /// (rewards fast throughput). Untested mirrors get a neutral
202
+ /// bandwidth default of 2 MiB/s so they aren't starved before
203
+ /// they've had a chance to demonstrate themselves.
204
+ fn weight(&self) -> f64 {
205
+ let bw_mibps = if self.avg_bandwidth_bps > 0.0 {
206
+ // Floor at 0.1 MiB/s so a single very-slow request doesn't
207
+ // make the weight collapse to ~0; we still want to rotate
208
+ // through and re-measure occasionally.
209
+ (self.avg_bandwidth_bps / 1_048_576.0).max(0.1)
210
+ } else {
211
+ 2.0
212
+ };
213
+ let raw = self.score * self.score * bw_mibps;
214
+ if self.is_dormant() {
215
+ // Dormant mirrors still get a small probe weight so we can
216
+ // detect recovery. Tuned so a single dormant mirror in a
217
+ // 5-mirror pool gets ~1–2% of starts.
218
+ 0.05_f64.min(raw)
219
+ } else {
220
+ raw
221
+ }
222
+ }
223
+
224
+ /// Treat as dormant after enough probes confirm consistent failure.
225
+ /// Note: `attempts >= 5` gates this so a single transient burst on a
226
+ /// new mirror can't sideline it permanently.
227
+ fn is_dormant(&self) -> bool {
228
+ self.attempts >= 5 && self.score < 0.10
229
+ }
230
+ }
231
+
232
+ pub struct MirrorPool {
233
+ mirrors: Vec<Arc<dyn Mirror>>,
234
+ /// All selection state lives behind a single mutex. Selection is fast
235
+ /// (≤5 mirrors × a few floats); contention here is dwarfed by the
236
+ /// network round-trip that follows.
237
+ state: Mutex<PoolState>,
238
+ /// Per-attempt wallclock budget. `None` falls back to whatever timeout
239
+ /// the underlying reqwest client uses; `Some(d)` aborts the mirror call
240
+ /// after `d` regardless of where it stalled (DNS, TLS, headers, body).
241
+ /// This is what stops a single hung mirror from holding a worker for
242
+ /// the full 120s reqwest ceiling while six healthy mirrors sit idle.
243
+ attempt_timeout: Option<Duration>,
244
+ }
245
+
246
+ struct PoolState {
247
+ health: Vec<MirrorHealth>,
248
+ }
249
+
250
+ /// Public snapshot returned by [`MirrorPool::health_snapshot`].
251
+ #[derive(Clone, Debug)]
252
+ pub struct MirrorHealthSnapshot {
253
+ pub name: String,
254
+ pub score: f64,
255
+ pub avg_latency_ms: f64,
256
+ pub avg_bandwidth_bps: f64,
257
+ pub dormant: bool,
258
+ }
259
+
260
+ impl MirrorPool {
261
+ pub fn new(mirrors: Vec<Arc<dyn Mirror>>) -> Self {
262
+ Self::with_attempt_timeout(mirrors, None)
263
+ }
264
+
265
+ /// Build a pool that aborts any single mirror call exceeding
266
+ /// `attempt_timeout`. Pass `None` to disable (rely only on the reqwest
267
+ /// client's own timeout). When a deadline fires the chain advances to
268
+ /// the next mirror just like any other recoverable failure.
269
+ pub fn with_attempt_timeout(
270
+ mirrors: Vec<Arc<dyn Mirror>>,
271
+ attempt_timeout: Option<Duration>,
272
+ ) -> Self {
273
+ let n = mirrors.len();
274
+ Self {
275
+ mirrors,
276
+ state: Mutex::new(PoolState {
277
+ health: (0..n).map(|_| MirrorHealth::fresh()).collect(),
278
+ }),
279
+ attempt_timeout,
280
+ }
281
+ }
282
+
283
+ pub fn names(&self) -> Vec<&str> {
284
+ self.mirrors.iter().map(|m| m.name()).collect()
285
+ }
286
+
287
+ pub fn is_empty(&self) -> bool {
288
+ self.mirrors.is_empty()
289
+ }
290
+
291
+ /// Snapshot of per-mirror health: `(name, score, avg_latency_ms,
292
+ /// avg_bandwidth_bps, dormant)`. Useful for the live dashboard or
293
+ /// "why is X being skipped" diagnostics.
294
+ pub fn health_snapshot(&self) -> Vec<MirrorHealthSnapshot> {
295
+ let state = self.state.lock().unwrap_or_else(|e| e.into_inner());
296
+ self.mirrors
297
+ .iter()
298
+ .zip(&state.health)
299
+ .map(|(m, h)| MirrorHealthSnapshot {
300
+ name: m.name().to_string(),
301
+ score: h.score,
302
+ avg_latency_ms: h.avg_latency_ms,
303
+ avg_bandwidth_bps: h.avg_bandwidth_bps,
304
+ dormant: h.is_dormant(),
305
+ })
306
+ .collect()
307
+ }
308
+
309
+ /// Pick the order in which to try mirrors for the next request.
310
+ ///
311
+ /// 1. The first slot is chosen via *smooth weighted round-robin* —
312
+ /// each call increments per-mirror SWRR accumulators by their
313
+ /// health weight, picks the max, decrements by the total weight.
314
+ /// Over many calls this gives each mirror a share of starts
315
+ /// proportional to its weight, but interleaved smoothly rather
316
+ /// than in bursty runs.
317
+ /// 2. The remaining slots are filled in *descending weight* order so
318
+ /// that fall-through after a transient failure still goes to the
319
+ /// healthiest available mirror, not whatever happens to be next
320
+ /// in the Vec.
321
+ /// 3. Dormant mirrors are placed last in the chain (so a healthy
322
+ /// chain doesn't usually reach them) but still included — if
323
+ /// every healthy mirror returns NotFound, we want to ask the
324
+ /// dormant ones too before declaring the set missing.
325
+ fn build_chain(&self) -> Vec<usize> {
326
+ let n = self.mirrors.len();
327
+ let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner());
328
+
329
+ // Compute current weights.
330
+ let weights: Vec<f64> = state.health.iter().map(|h| h.weight()).collect();
331
+ let total: f64 = weights.iter().sum();
332
+ if total <= 0.0 {
333
+ // Pathological: every mirror is dormant with weight 0. Just
334
+ // serve them in declared order so the chain isn't empty.
335
+ return (0..n).collect();
336
+ }
337
+
338
+ // SWRR: bump every accumulator by its weight, then pick max.
339
+ for (i, w) in weights.iter().enumerate() {
340
+ state.health[i].swrr_current += w;
341
+ }
342
+ // Tie-break by *lower* index so ordering matches the Vec when
343
+ // every mirror has equal weight (e.g., a fresh pool's first
344
+ // request). `Iterator::max_by` returns the last element on ties,
345
+ // which would invert that — so we walk manually with strict `>`.
346
+ let mut start = 0;
347
+ let mut max_swrr = state.health[0].swrr_current;
348
+ for i in 1..state.health.len() {
349
+ if state.health[i].swrr_current > max_swrr {
350
+ max_swrr = state.health[i].swrr_current;
351
+ start = i;
352
+ }
353
+ }
354
+ state.health[start].swrr_current -= total;
355
+
356
+ // Build remaining order: healthy by weight desc, then dormant.
357
+ let mut others: Vec<usize> = (0..n).filter(|i| *i != start).collect();
358
+ others.sort_by(|a, b| {
359
+ let ad = state.health[*a].is_dormant();
360
+ let bd = state.health[*b].is_dormant();
361
+ // dormant after non-dormant
362
+ if ad != bd {
363
+ return ad.cmp(&bd);
364
+ }
365
+ // within group, higher weight first
366
+ weights[*b]
367
+ .partial_cmp(&weights[*a])
368
+ .unwrap_or(std::cmp::Ordering::Equal)
369
+ });
370
+ let mut chain = Vec::with_capacity(n);
371
+ chain.push(start);
372
+ chain.extend(others);
373
+ chain
374
+ }
375
+
376
+ fn record_outcome(
377
+ &self,
378
+ idx: usize,
379
+ outcome: AttemptOutcome,
380
+ latency: Duration,
381
+ bytes: Option<u64>,
382
+ ) {
383
+ let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner());
384
+ let h = &mut state.health[idx];
385
+ h.attempts = h.attempts.saturating_add(1);
386
+ match outcome {
387
+ AttemptOutcome::Success => {
388
+ // Mirror healthy → score climbs back toward 1.0 quickly
389
+ // so a previously-dormant mirror that recovers via probe
390
+ // rejoins the rotation within a few requests.
391
+ h.score = 0.7 * h.score + 0.3 * 1.0;
392
+ let now = latency.as_millis() as f64;
393
+ h.avg_latency_ms = if h.avg_latency_ms == 0.0 {
394
+ now
395
+ } else {
396
+ 0.7 * h.avg_latency_ms + 0.3 * now
397
+ };
398
+ // Record observed throughput from this attempt — only
399
+ // signal we can compare across mirrors that's invariant
400
+ // to the size of the set being fetched. Skip degenerate
401
+ // cases (empty body or sub-millisecond timing) so a
402
+ // single weird request doesn't poison the EWMA.
403
+ if let Some(b) = bytes {
404
+ let secs = latency.as_secs_f64();
405
+ if b > 0 && secs > 0.001 {
406
+ let bps = b as f64 / secs;
407
+ h.avg_bandwidth_bps = if h.avg_bandwidth_bps == 0.0 {
408
+ bps
409
+ } else {
410
+ 0.7 * h.avg_bandwidth_bps + 0.3 * bps
411
+ };
412
+ }
413
+ }
414
+ h.consecutive_hard_failures = 0;
415
+ }
416
+ AttemptOutcome::NotFound => {
417
+ // Mirror is alive and answered correctly — they just
418
+ // don't host this set. No score change. We still reset
419
+ // the consecutive-hard-failure counter (the mirror is
420
+ // demonstrably responsive).
421
+ h.consecutive_hard_failures = 0;
422
+ }
423
+ AttemptOutcome::InvalidArchive => {
424
+ // Light penalty: invalid bytes can be a transient
425
+ // mid-update glitch on the mirror, not necessarily a
426
+ // dead host. (Per design note: "invalid doesn't mean
427
+ // dead.") Multiplier 0.92 means a mirror needs roughly
428
+ // 25 consecutive invalids to fall to score 0.10 — so a
429
+ // few flaky responses don't sideline a working mirror.
430
+ h.score = 0.92 * h.score;
431
+ h.consecutive_hard_failures = h.consecutive_hard_failures.saturating_add(1);
432
+ }
433
+ AttemptOutcome::RateLimited
434
+ | AttemptOutcome::HttpError
435
+ | AttemptOutcome::Network
436
+ | AttemptOutcome::Timeout => {
437
+ // Hard failures: 0.7 multiplier means ~7 consecutive
438
+ // hard failures drops score below the dormant threshold
439
+ // (0.10). RateLimited is in here intentionally — 429
440
+ // means our pacing is wrong for this mirror, so we want
441
+ // fewer fresh starts there until headroom recovers.
442
+ // Timeout is grouped with Network because they're the
443
+ // same signal: this mirror is unresponsive *right now*.
444
+ h.score = 0.7 * h.score;
445
+ h.consecutive_hard_failures = h.consecutive_hard_failures.saturating_add(1);
446
+ }
447
+ AttemptOutcome::UnsupportedFlavor => {
448
+ // Carries no health information — no update.
449
+ }
450
+ }
451
+ }
452
+
453
+ /// Backward-compatible entry point — equivalent to
454
+ /// [`download_with_observer`] using a no-op observer.
455
+ pub async fn download(
456
+ &self,
457
+ set_id: u64,
458
+ flavor: Flavor,
459
+ ) -> (Result<(String, Bytes), MirrorError>, Vec<AttemptRecord>) {
460
+ self.download_with_observer(set_id, flavor, &NoOpObserver)
461
+ .await
462
+ }
463
+
464
+ /// Try mirrors in health-aware order. Returns:
465
+ /// * `Ok((mirror_name, bytes, attempts))` — first success.
466
+ /// * `Err((last_error, attempts))` — every mirror was tried and none
467
+ /// produced bytes. `attempts` is in the order tried.
468
+ ///
469
+ /// `NotFound` from every mirror is reported as `MirrorError::NotFound`
470
+ /// so the caller can mark the set as `missing` rather than `failed`.
471
+ pub async fn download_with_observer<O: AttemptObserver + ?Sized>(
472
+ &self,
473
+ set_id: u64,
474
+ flavor: Flavor,
475
+ observer: &O,
476
+ ) -> (Result<(String, Bytes), MirrorError>, Vec<AttemptRecord>) {
477
+ let n = self.mirrors.len();
478
+ let mut attempts = Vec::with_capacity(n);
479
+ let mut last_err = MirrorError::Aborted;
480
+ let mut all_not_found = true;
481
+ if n == 0 {
482
+ return (Err(MirrorError::Aborted), attempts);
483
+ }
484
+
485
+ for idx in self.build_chain() {
486
+ let mirror = &self.mirrors[idx];
487
+ let name = mirror.name().to_string();
488
+ if !mirror.supports(flavor) {
489
+ attempts.push(AttemptRecord {
490
+ mirror: name.clone(),
491
+ duration: Duration::ZERO,
492
+ http_status: None,
493
+ bytes: None,
494
+ error: Some(format!("does not serve {flavor:?}")),
495
+ outcome: AttemptOutcome::UnsupportedFlavor,
496
+ });
497
+ last_err = MirrorError::UnsupportedFlavor {
498
+ mirror: name,
499
+ flavor,
500
+ };
501
+ all_not_found = false;
502
+ continue;
503
+ }
504
+
505
+ observer.before_attempt(&name);
506
+ let started = Instant::now();
507
+ let result = match self.attempt_timeout {
508
+ Some(d) => match tokio::time::timeout(d, mirror.download(set_id, flavor)).await {
509
+ Ok(r) => r,
510
+ Err(_elapsed) => Err(MirrorError::Timeout {
511
+ mirror: name.clone(),
512
+ after_secs: d.as_secs(),
513
+ }),
514
+ },
515
+ None => mirror.download(set_id, flavor).await,
516
+ };
517
+ let elapsed = started.elapsed();
518
+ observer.after_attempt(&name);
519
+
520
+ match result {
521
+ Ok(bytes) => {
522
+ self.record_outcome(
523
+ idx,
524
+ AttemptOutcome::Success,
525
+ elapsed,
526
+ Some(bytes.len() as u64),
527
+ );
528
+ attempts.push(AttemptRecord {
529
+ mirror: name.clone(),
530
+ duration: elapsed,
531
+ http_status: Some(200),
532
+ bytes: Some(bytes.len() as u64),
533
+ error: None,
534
+ outcome: AttemptOutcome::Success,
535
+ });
536
+ return (Ok((name, bytes)), attempts);
537
+ }
538
+ Err(err) => {
539
+ let outcome = match &err {
540
+ MirrorError::NotFound { .. } => AttemptOutcome::NotFound,
541
+ MirrorError::RateLimited { .. } => AttemptOutcome::RateLimited,
542
+ MirrorError::HttpError { .. } => AttemptOutcome::HttpError,
543
+ MirrorError::Network { .. } => AttemptOutcome::Network,
544
+ MirrorError::InvalidArchive { .. } => AttemptOutcome::InvalidArchive,
545
+ MirrorError::Timeout { .. } => AttemptOutcome::Timeout,
546
+ MirrorError::UnsupportedFlavor { .. } => AttemptOutcome::UnsupportedFlavor,
547
+ MirrorError::Aborted => {
548
+ attempts.push(AttemptRecord {
549
+ mirror: name,
550
+ duration: elapsed,
551
+ http_status: None,
552
+ bytes: None,
553
+ error: Some("aborted".into()),
554
+ outcome: AttemptOutcome::Network,
555
+ });
556
+ return (Err(MirrorError::Aborted), attempts);
557
+ }
558
+ };
559
+ self.record_outcome(idx, outcome, elapsed, None);
560
+ let http_status = match &err {
561
+ MirrorError::HttpError { status, .. } => Some(*status),
562
+ MirrorError::RateLimited { .. } => Some(429),
563
+ MirrorError::NotFound { .. } => Some(404),
564
+ _ => None,
565
+ };
566
+ attempts.push(AttemptRecord {
567
+ mirror: name,
568
+ duration: elapsed,
569
+ http_status,
570
+ bytes: None,
571
+ error: Some(err.to_string()),
572
+ outcome,
573
+ });
574
+ if !matches!(err, MirrorError::NotFound { .. }) {
575
+ all_not_found = false;
576
+ }
577
+ last_err = err;
578
+ }
579
+ }
580
+ }
581
+
582
+ // Every mirror was tried. If literally every result was 404,
583
+ // promote to a "missing" signal so the caller can move the set
584
+ // to the `missing` terminal state instead of retrying as
585
+ // `failed`.
586
+ if all_not_found && !attempts.is_empty() {
587
+ (
588
+ Err(MirrorError::NotFound {
589
+ mirror: "(all)".into(),
590
+ }),
591
+ attempts,
592
+ )
593
+ } else {
594
+ (Err(last_err), attempts)
595
+ }
596
+ }
597
+ }
598
+
599
+ /// Construct the User-Agent we send to every mirror. Includes a contact hint
600
+ /// so a mirror op who notices us can ask us to back off rather than silently
601
+ /// blocking.
602
+ pub fn user_agent() -> String {
603
+ format!(
604
+ "osu_fetcher/{} (osu-everything dataset; lekdan/osu-everything)",
605
+ env!("CARGO_PKG_VERSION")
606
+ )
607
+ }
608
+
609
+ /// Build a reqwest client preconfigured with timeouts + decompression.
610
+ ///
611
+ /// We share these knobs across every mirror; per-mirror tuning is handled by
612
+ /// the rate limiter, not by the client config.
613
+ pub fn build_client() -> Result<Client, reqwest::Error> {
614
+ Client::builder()
615
+ .user_agent(user_agent())
616
+ .timeout(Duration::from_secs(120))
617
+ .pool_idle_timeout(Duration::from_secs(60))
618
+ .gzip(true)
619
+ .brotli(true)
620
+ .build()
621
+ }
622
+
623
+ /// Common helper used by every mirror: convert a finished `reqwest::Response`
624
+ /// into the right `MirrorError` variant. Caller has already done the GET.
625
+ ///
626
+ /// On 2xx, the body is buffered into memory and *deep-verified* — the bytes
627
+ /// must parse as a ZIP and contain at least one `.osu` file. This catches
628
+ /// mirrors that respond 200 with a status page, a truncated zip, or any
629
+ /// shape that wouldn't survive ingestion. The `MirrorPool` treats
630
+ /// `InvalidArchive` as a recoverable failure and tries the next mirror, so
631
+ /// shoving the deep check up here is what makes mirror failover actually
632
+ /// reliable.
633
+ pub async fn classify_response(
634
+ mirror: &str,
635
+ resp: reqwest::Response,
636
+ ) -> Result<Bytes, MirrorError> {
637
+ let status = resp.status();
638
+ if status.is_success() {
639
+ let bytes = resp.bytes().await.map_err(|e| MirrorError::Network {
640
+ mirror: mirror.into(),
641
+ source: e,
642
+ })?;
643
+ if let Err(e) = verify_bytes(&bytes) {
644
+ return Err(MirrorError::InvalidArchive {
645
+ mirror: mirror.into(),
646
+ reason: e.to_string(),
647
+ });
648
+ }
649
+ return Ok(bytes);
650
+ }
651
+ if status == StatusCode::NOT_FOUND {
652
+ return Err(MirrorError::NotFound {
653
+ mirror: mirror.into(),
654
+ });
655
+ }
656
+ if status == StatusCode::TOO_MANY_REQUESTS {
657
+ return Err(MirrorError::RateLimited {
658
+ mirror: mirror.into(),
659
+ });
660
+ }
661
+ let body = resp.text().await.unwrap_or_default();
662
+ let snippet: String = body.chars().take(200).collect();
663
+ Err(MirrorError::HttpError {
664
+ mirror: mirror.into(),
665
+ status: status.as_u16(),
666
+ body_snippet: snippet,
667
+ })
668
+ }
669
+
670
+ /// Bundle of construction inputs every mirror takes. Avoids 5x the same
671
+ /// `(client, rate_limiter)` argument list at every call site.
672
+ ///
673
+ /// `osu_api` is optional because not every subcommand has credentials —
674
+ /// the public mirrors don't need it; only [`osuapi::OsuApiMirror`] does.
675
+ /// When it's `None` the caller skips constructing that mirror.
676
+ #[derive(Clone)]
677
+ pub struct MirrorContext {
678
+ pub client: Client,
679
+ pub limiters: MirrorLimiters,
680
+ pub osu_api: Option<Arc<OsuApi>>,
681
+ }
682
+
683
+ /// Per-mirror rate limit configuration, all in requests/minute.
684
+ #[derive(Clone)]
685
+ pub struct MirrorLimiters {
686
+ pub nerinyan: RateLimited,
687
+ pub catboy: RateLimited,
688
+ pub sayobot: RateLimited,
689
+ pub nekoha: RateLimited,
690
+ pub beatconnect: RateLimited,
691
+ pub osudirect: RateLimited,
692
+ pub nzbasic: RateLimited,
693
+ pub osudl: RateLimited,
694
+ pub osuapi: RateLimited,
695
+ }
696
+
697
+ #[cfg(test)]
698
+ mod tests {
699
+ use super::*;
700
+
701
+ struct StubMirror {
702
+ name: &'static str,
703
+ outcome: StubOutcome,
704
+ flavors: Vec<Flavor>,
705
+ }
706
+
707
+ enum StubOutcome {
708
+ Bytes(Bytes),
709
+ NotFound,
710
+ Error(String),
711
+ }
712
+
713
+ #[async_trait]
714
+ impl Mirror for StubMirror {
715
+ fn name(&self) -> &str {
716
+ self.name
717
+ }
718
+ fn supports(&self, f: Flavor) -> bool {
719
+ self.flavors.contains(&f)
720
+ }
721
+ async fn download(&self, _set_id: u64, _flavor: Flavor) -> Result<Bytes, MirrorError> {
722
+ match &self.outcome {
723
+ StubOutcome::Bytes(b) => Ok(b.clone()),
724
+ StubOutcome::NotFound => Err(MirrorError::NotFound {
725
+ mirror: self.name.into(),
726
+ }),
727
+ StubOutcome::Error(msg) => Err(MirrorError::HttpError {
728
+ mirror: self.name.into(),
729
+ status: 500,
730
+ body_snippet: msg.clone(),
731
+ }),
732
+ }
733
+ }
734
+ }
735
+
736
+ #[tokio::test]
737
+ async fn pool_returns_first_success() {
738
+ let pool = MirrorPool::new(vec![
739
+ Arc::new(StubMirror {
740
+ name: "first",
741
+ outcome: StubOutcome::NotFound,
742
+ flavors: vec![Flavor::Full],
743
+ }),
744
+ Arc::new(StubMirror {
745
+ name: "second",
746
+ outcome: StubOutcome::Bytes(Bytes::from_static(b"PK\x03\x04ok")),
747
+ flavors: vec![Flavor::Full],
748
+ }),
749
+ Arc::new(StubMirror {
750
+ name: "third",
751
+ outcome: StubOutcome::Bytes(Bytes::from_static(b"PK\x03\x04unused")),
752
+ flavors: vec![Flavor::Full],
753
+ }),
754
+ ]);
755
+ let (result, attempts) = pool.download(123, Flavor::Full).await;
756
+ let (mirror, bytes) = result.expect("expected success");
757
+ assert_eq!(mirror, "second");
758
+ assert_eq!(&bytes[..4], b"PK\x03\x04");
759
+ assert_eq!(attempts.len(), 2);
760
+ assert_eq!(attempts[0].outcome, AttemptOutcome::NotFound);
761
+ assert_eq!(attempts[1].outcome, AttemptOutcome::Success);
762
+ }
763
+
764
+ #[tokio::test]
765
+ async fn pool_advances_past_5xx_to_a_working_mirror() {
766
+ let pool = MirrorPool::new(vec![
767
+ Arc::new(StubMirror {
768
+ name: "broken",
769
+ outcome: StubOutcome::Error("upstream meltdown".into()),
770
+ flavors: vec![Flavor::Full],
771
+ }),
772
+ Arc::new(StubMirror {
773
+ name: "good",
774
+ outcome: StubOutcome::Bytes(Bytes::from_static(b"PK\x03\x04ok")),
775
+ flavors: vec![Flavor::Full],
776
+ }),
777
+ ]);
778
+ let (result, attempts) = pool.download(7, Flavor::Full).await;
779
+ let (mirror, _) = result.expect("expected eventual success");
780
+ assert_eq!(mirror, "good");
781
+ assert_eq!(attempts[0].outcome, AttemptOutcome::HttpError);
782
+ assert_eq!(attempts[0].http_status, Some(500));
783
+ assert_eq!(attempts[1].outcome, AttemptOutcome::Success);
784
+ }
785
+
786
+ #[tokio::test]
787
+ async fn pool_exhausts_all_supported_mirrors_before_failing() {
788
+ let pool = MirrorPool::new(vec![
789
+ Arc::new(StubMirror {
790
+ name: "first-broken",
791
+ outcome: StubOutcome::Error("first".into()),
792
+ flavors: vec![Flavor::Full],
793
+ }),
794
+ Arc::new(StubMirror {
795
+ name: "missing",
796
+ outcome: StubOutcome::NotFound,
797
+ flavors: vec![Flavor::Full],
798
+ }),
799
+ Arc::new(StubMirror {
800
+ name: "last-broken",
801
+ outcome: StubOutcome::Error("last".into()),
802
+ flavors: vec![Flavor::Full],
803
+ }),
804
+ ]);
805
+ let (result, attempts) = pool.download(7, Flavor::Full).await;
806
+ assert!(matches!(result, Err(MirrorError::HttpError { .. })));
807
+ assert_eq!(attempts.len(), 3);
808
+ let names: Vec<&str> = attempts.iter().map(|a| a.mirror.as_str()).collect();
809
+ assert!(names.contains(&"first-broken"));
810
+ assert!(names.contains(&"missing"));
811
+ assert!(names.contains(&"last-broken"));
812
+ }
813
+
814
+ #[tokio::test]
815
+ async fn pool_promotes_all_404_to_not_found() {
816
+ let pool = MirrorPool::new(vec![
817
+ Arc::new(StubMirror {
818
+ name: "a",
819
+ outcome: StubOutcome::NotFound,
820
+ flavors: vec![Flavor::Full],
821
+ }),
822
+ Arc::new(StubMirror {
823
+ name: "b",
824
+ outcome: StubOutcome::NotFound,
825
+ flavors: vec![Flavor::Full],
826
+ }),
827
+ ]);
828
+ let (result, attempts) = pool.download(123, Flavor::Full).await;
829
+ let err = result.unwrap_err();
830
+ assert!(matches!(err, MirrorError::NotFound { .. }));
831
+ assert_eq!(attempts.len(), 2);
832
+ }
833
+
834
+ #[tokio::test]
835
+ async fn pool_rotates_starting_mirror_when_health_is_equal() {
836
+ // All three mirrors return NotFound — that's a *neutral* signal,
837
+ // so health stays equal across all three. With equal weights,
838
+ // smooth weighted round-robin degenerates to plain round-robin.
839
+ let pool = MirrorPool::new(vec![
840
+ Arc::new(StubMirror {
841
+ name: "a",
842
+ outcome: StubOutcome::NotFound,
843
+ flavors: vec![Flavor::Full],
844
+ }),
845
+ Arc::new(StubMirror {
846
+ name: "b",
847
+ outcome: StubOutcome::NotFound,
848
+ flavors: vec![Flavor::Full],
849
+ }),
850
+ Arc::new(StubMirror {
851
+ name: "c",
852
+ outcome: StubOutcome::NotFound,
853
+ flavors: vec![Flavor::Full],
854
+ }),
855
+ ]);
856
+
857
+ let mut starts = Vec::new();
858
+ for _ in 0..6 {
859
+ let (_, attempts) = pool.download(1, Flavor::Full).await;
860
+ starts.push(attempts[0].mirror.clone());
861
+ // Sanity: every call should still try all 3 mirrors.
862
+ assert_eq!(attempts.len(), 3);
863
+ }
864
+ // Six calls × three mirrors with equal weights → each gets two starts.
865
+ let mut counts = std::collections::HashMap::new();
866
+ for s in &starts {
867
+ *counts.entry(s.clone()).or_insert(0) += 1;
868
+ }
869
+ for name in ["a", "b", "c"] {
870
+ assert_eq!(
871
+ counts.get(name).copied().unwrap_or(0),
872
+ 2,
873
+ "mirror {name} should start twice; got {counts:?}"
874
+ );
875
+ }
876
+ }
877
+
878
+ #[tokio::test]
879
+ async fn pool_dormant_mirror_stops_being_picked_as_start() {
880
+ // Five attempts of consecutive HTTP errors crosses the dormant
881
+ // threshold. Once dormant, the bad mirror should rarely be the
882
+ // *starting* choice; the healthy mirror should dominate starts.
883
+ let pool = MirrorPool::new(vec![
884
+ Arc::new(StubMirror {
885
+ name: "broken",
886
+ outcome: StubOutcome::Error("upstream meltdown".into()),
887
+ flavors: vec![Flavor::Full],
888
+ }),
889
+ Arc::new(StubMirror {
890
+ name: "good",
891
+ outcome: StubOutcome::Bytes(Bytes::from_static(b"PK\x03\x04ok")),
892
+ flavors: vec![Flavor::Full],
893
+ }),
894
+ ]);
895
+
896
+ // Warm up: do 30 calls so health stats stabilize. After this,
897
+ // `broken` should be dormant and `good` should be the routine
898
+ // starter.
899
+ for _ in 0..30 {
900
+ let _ = pool.download(1, Flavor::Full).await;
901
+ }
902
+
903
+ // Now check the next 20 starts: at most a handful (the probe
904
+ // budget) should hit `broken` first.
905
+ let mut broken_starts = 0;
906
+ for _ in 0..20 {
907
+ let (_, attempts) = pool.download(1, Flavor::Full).await;
908
+ if attempts[0].mirror == "broken" {
909
+ broken_starts += 1;
910
+ }
911
+ }
912
+ assert!(
913
+ broken_starts <= 3,
914
+ "expected dormant 'broken' to rarely be picked as start; got {broken_starts}/20"
915
+ );
916
+ }
917
+
918
+ #[tokio::test]
919
+ async fn pool_invalid_archive_does_not_immediately_dormant() {
920
+ // The user explicitly requested: invalid_archive should be a
921
+ // *light* penalty, not a death sentence. Two invalids in a row
922
+ // shouldn't sideline the mirror.
923
+ struct InvalidThenOk {
924
+ count: std::sync::atomic::AtomicU32,
925
+ }
926
+ #[async_trait]
927
+ impl Mirror for InvalidThenOk {
928
+ fn name(&self) -> &str {
929
+ "flaky"
930
+ }
931
+ fn supports(&self, _: Flavor) -> bool {
932
+ true
933
+ }
934
+ async fn download(&self, _: u64, _: Flavor) -> Result<Bytes, MirrorError> {
935
+ let c = self
936
+ .count
937
+ .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
938
+ if c < 2 {
939
+ Err(MirrorError::InvalidArchive {
940
+ mirror: "flaky".into(),
941
+ reason: "test".into(),
942
+ })
943
+ } else {
944
+ Ok(Bytes::from_static(b"PK\x03\x04ok"))
945
+ }
946
+ }
947
+ }
948
+
949
+ let pool = MirrorPool::new(vec![Arc::new(InvalidThenOk {
950
+ count: std::sync::atomic::AtomicU32::new(0),
951
+ })]);
952
+
953
+ // Two invalids — should not be dormant after.
954
+ let _ = pool.download(1, Flavor::Full).await;
955
+ let _ = pool.download(1, Flavor::Full).await;
956
+ let snap = pool.health_snapshot();
957
+ assert!(
958
+ !snap[0].dormant,
959
+ "two invalids alone should not dormant a mirror"
960
+ );
961
+ assert!(
962
+ snap[0].score > 0.5,
963
+ "score after 2 invalids should still be >0.5; got {}",
964
+ snap[0].score
965
+ );
966
+
967
+ // Subsequent attempt succeeds; score recovers.
968
+ let (result, _) = pool.download(1, Flavor::Full).await;
969
+ assert!(result.is_ok());
970
+ }
971
+
972
+ #[tokio::test]
973
+ async fn pool_records_bandwidth_from_successful_attempts() {
974
+ // A mirror that returns 1 MB after a synthetic 100 ms delay → 10 MiB/s.
975
+ struct FixedSizeMirror {
976
+ bytes: usize,
977
+ delay: Duration,
978
+ }
979
+ #[async_trait]
980
+ impl Mirror for FixedSizeMirror {
981
+ fn name(&self) -> &str {
982
+ "fixed"
983
+ }
984
+ fn supports(&self, _: Flavor) -> bool {
985
+ true
986
+ }
987
+ async fn download(&self, _: u64, _: Flavor) -> Result<Bytes, MirrorError> {
988
+ tokio::time::sleep(self.delay).await;
989
+ Ok(Bytes::from(vec![0u8; self.bytes]))
990
+ }
991
+ }
992
+
993
+ let pool = MirrorPool::new(vec![Arc::new(FixedSizeMirror {
994
+ bytes: 1024 * 1024,
995
+ delay: Duration::from_millis(100),
996
+ })]);
997
+ // Run a few times so the EWMA stabilizes.
998
+ for _ in 0..3 {
999
+ let _ = pool.download(1, Flavor::Full).await;
1000
+ }
1001
+ let snap = pool.health_snapshot();
1002
+ let bw_mibps = snap[0].avg_bandwidth_bps / 1_048_576.0;
1003
+ // 1 MiB / 0.1s = 10 MiB/s. Allow generous tolerance for runtime jitter.
1004
+ assert!(
1005
+ bw_mibps > 4.0 && bw_mibps < 30.0,
1006
+ "expected ~10 MiB/s; got {bw_mibps}"
1007
+ );
1008
+ }
1009
+
1010
+ #[tokio::test]
1011
+ async fn pool_observer_sees_before_and_after_each_attempt() {
1012
+ use std::sync::atomic::{AtomicUsize, Ordering};
1013
+ struct CountingObserver {
1014
+ befores: AtomicUsize,
1015
+ afters: AtomicUsize,
1016
+ }
1017
+ impl AttemptObserver for CountingObserver {
1018
+ fn before_attempt(&self, _: &str) {
1019
+ self.befores.fetch_add(1, Ordering::Relaxed);
1020
+ }
1021
+ fn after_attempt(&self, _: &str) {
1022
+ self.afters.fetch_add(1, Ordering::Relaxed);
1023
+ }
1024
+ }
1025
+ let pool = MirrorPool::new(vec![
1026
+ Arc::new(StubMirror {
1027
+ name: "a",
1028
+ outcome: StubOutcome::NotFound,
1029
+ flavors: vec![Flavor::Full],
1030
+ }),
1031
+ Arc::new(StubMirror {
1032
+ name: "b",
1033
+ outcome: StubOutcome::Bytes(Bytes::from_static(b"PK\x03\x04ok")),
1034
+ flavors: vec![Flavor::Full],
1035
+ }),
1036
+ ]);
1037
+ let obs = CountingObserver {
1038
+ befores: AtomicUsize::new(0),
1039
+ afters: AtomicUsize::new(0),
1040
+ };
1041
+ let _ = pool.download_with_observer(1, Flavor::Full, &obs).await;
1042
+ // Two mirrors tried (a NotFound, b Success).
1043
+ assert_eq!(obs.befores.load(Ordering::Relaxed), 2);
1044
+ assert_eq!(obs.afters.load(Ordering::Relaxed), 2);
1045
+ }
1046
+
1047
+ #[tokio::test]
1048
+ async fn pool_aborts_slow_mirror_when_per_attempt_timeout_set() {
1049
+ // Mirror that would never complete inside the deadline. The pool
1050
+ // must bail with Timeout, advance to the next mirror, and succeed
1051
+ // there — this is the exact scenario the deadline was added for
1052
+ // (sayobot hanging on a single in-flight request for 60+s).
1053
+ struct SleepyMirror {
1054
+ name: &'static str,
1055
+ delay: Duration,
1056
+ }
1057
+ #[async_trait]
1058
+ impl Mirror for SleepyMirror {
1059
+ fn name(&self) -> &str {
1060
+ self.name
1061
+ }
1062
+ fn supports(&self, _: Flavor) -> bool {
1063
+ true
1064
+ }
1065
+ async fn download(&self, _: u64, _: Flavor) -> Result<Bytes, MirrorError> {
1066
+ tokio::time::sleep(self.delay).await;
1067
+ Ok(Bytes::from_static(b"PK\x03\x04ok"))
1068
+ }
1069
+ }
1070
+ let pool = MirrorPool::with_attempt_timeout(
1071
+ vec![
1072
+ Arc::new(SleepyMirror {
1073
+ name: "slow",
1074
+ delay: Duration::from_secs(60),
1075
+ }),
1076
+ Arc::new(SleepyMirror {
1077
+ name: "fast",
1078
+ delay: Duration::from_millis(1),
1079
+ }),
1080
+ ],
1081
+ Some(Duration::from_millis(100)),
1082
+ );
1083
+ let (result, attempts) = pool.download(1, Flavor::Full).await;
1084
+ let (mirror, _) = result.expect("expected fast mirror to succeed");
1085
+ assert_eq!(mirror, "fast");
1086
+ assert_eq!(attempts.len(), 2);
1087
+ assert_eq!(attempts[0].outcome, AttemptOutcome::Timeout);
1088
+ assert_eq!(attempts[0].mirror, "slow");
1089
+ assert_eq!(attempts[1].outcome, AttemptOutcome::Success);
1090
+ }
1091
+
1092
+ #[tokio::test]
1093
+ async fn pool_without_attempt_timeout_lets_mirror_finish() {
1094
+ // Default constructor (no per-attempt timeout) must not abort a
1095
+ // mirror that takes a moment to respond — only the reqwest
1096
+ // client's own timeout applies in that mode.
1097
+ struct SleepyMirror;
1098
+ #[async_trait]
1099
+ impl Mirror for SleepyMirror {
1100
+ fn name(&self) -> &str {
1101
+ "slow"
1102
+ }
1103
+ fn supports(&self, _: Flavor) -> bool {
1104
+ true
1105
+ }
1106
+ async fn download(&self, _: u64, _: Flavor) -> Result<Bytes, MirrorError> {
1107
+ tokio::time::sleep(Duration::from_millis(50)).await;
1108
+ Ok(Bytes::from_static(b"PK\x03\x04ok"))
1109
+ }
1110
+ }
1111
+ let pool = MirrorPool::new(vec![Arc::new(SleepyMirror)]);
1112
+ let (result, attempts) = pool.download(1, Flavor::Full).await;
1113
+ assert!(result.is_ok(), "mirror should be allowed to finish");
1114
+ assert_eq!(attempts[0].outcome, AttemptOutcome::Success);
1115
+ }
1116
+
1117
+ #[tokio::test]
1118
+ async fn pool_skips_unsupported_flavor_without_http() {
1119
+ let pool = MirrorPool::new(vec![
1120
+ Arc::new(StubMirror {
1121
+ name: "novideo-only",
1122
+ outcome: StubOutcome::Bytes(Bytes::from_static(b"PK\x03\x04unused")),
1123
+ flavors: vec![Flavor::NoVideo],
1124
+ }),
1125
+ Arc::new(StubMirror {
1126
+ name: "full-capable",
1127
+ outcome: StubOutcome::Bytes(Bytes::from_static(b"PK\x03\x04good")),
1128
+ flavors: vec![Flavor::Full, Flavor::NoVideo],
1129
+ }),
1130
+ ]);
1131
+ let (result, attempts) = pool.download(123, Flavor::Full).await;
1132
+ let (mirror, _) = result.unwrap();
1133
+ assert_eq!(mirror, "full-capable");
1134
+ assert_eq!(attempts[0].outcome, AttemptOutcome::UnsupportedFlavor);
1135
+ assert_eq!(attempts[0].http_status, None);
1136
+ assert_eq!(attempts[1].outcome, AttemptOutcome::Success);
1137
+ }
1138
+ }
crates/osu_fetcher/src/mirrors/nekoha.rs ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //! nekoha.moe — public mirror, no auth required.
2
+ //!
3
+ //! Endpoint: `GET https://mirror.nekoha.moe/api4/download/{set_id}`. The
4
+ //! legacy `/d/{set_id}` path was retired when the site was rewritten as a
5
+ //! React SPA; it now serves the HTML shell unconditionally and we'd reject
6
+ //! the bytes as `InvalidArchive`. Flavor selection on the v4 API is
7
+ //! unconfirmed, so we always request the default (Full) — the only
8
+ //! flavor the dataset pipeline ever asks for anyway.
9
+
10
+ use async_trait::async_trait;
11
+ use bytes::Bytes;
12
+ use reqwest::Client;
13
+
14
+ use super::{classify_response, Mirror, MirrorContext, MirrorError};
15
+ use crate::ratelimit::RateLimited;
16
+ use crate::Flavor;
17
+
18
+ pub const NAME: &str = "nekoha";
19
+ const BASE: &str = "https://mirror.nekoha.moe/api4/download";
20
+
21
+ pub struct NekohaMirror {
22
+ client: Client,
23
+ limiter: RateLimited,
24
+ }
25
+
26
+ impl NekohaMirror {
27
+ pub fn new(ctx: &MirrorContext) -> Self {
28
+ Self {
29
+ client: ctx.client.clone(),
30
+ limiter: ctx.limiters.nekoha.clone(),
31
+ }
32
+ }
33
+
34
+ pub fn url(set_id: u64, _flavor: Flavor) -> String {
35
+ // v4 API: single endpoint per set; flavor selection isn't documented
36
+ // and isn't needed by the pipeline.
37
+ format!("{BASE}/{set_id}")
38
+ }
39
+ }
40
+
41
+ #[async_trait]
42
+ impl Mirror for NekohaMirror {
43
+ fn name(&self) -> &str {
44
+ NAME
45
+ }
46
+
47
+ fn supports(&self, _flavor: Flavor) -> bool {
48
+ true
49
+ }
50
+
51
+ async fn download(&self, set_id: u64, flavor: Flavor) -> Result<Bytes, MirrorError> {
52
+ self.limiter.acquire().await;
53
+ let url = Self::url(set_id, flavor);
54
+ let resp = self
55
+ .client
56
+ .get(&url)
57
+ .send()
58
+ .await
59
+ .map_err(|e| MirrorError::Network {
60
+ mirror: NAME.into(),
61
+ source: e,
62
+ })?;
63
+ classify_response(NAME, resp).await
64
+ }
65
+ }
66
+
67
+ #[cfg(test)]
68
+ mod tests {
69
+ use super::*;
70
+
71
+ #[test]
72
+ fn url_full_uses_v4_api_path() {
73
+ assert_eq!(
74
+ NekohaMirror::url(456, Flavor::Full),
75
+ "https://mirror.nekoha.moe/api4/download/456"
76
+ );
77
+ }
78
+
79
+ #[test]
80
+ fn url_novideo_falls_back_to_full_endpoint() {
81
+ // NoVideo isn't differentiated on the v4 API; we still hand back
82
+ // a valid URL so the chain doesn't UnsupportedFlavor-skip nekoha.
83
+ assert_eq!(
84
+ NekohaMirror::url(456, Flavor::NoVideo),
85
+ "https://mirror.nekoha.moe/api4/download/456"
86
+ );
87
+ }
88
+ }
crates/osu_fetcher/src/mirrors/nerinyan.rs ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //! nerinyan.moe — public mirror, no auth required.
2
+ //!
3
+ //! Endpoint: `GET https://api.nerinyan.moe/d/{set_id}` (full archive).
4
+ //! Toggle assets via the `nv`/`nb`/`nh` query params; we leave them all
5
+ //! unset to request the full original `.osz`.
6
+
7
+ use async_trait::async_trait;
8
+ use bytes::Bytes;
9
+ use reqwest::Client;
10
+
11
+ use super::{classify_response, Mirror, MirrorContext, MirrorError};
12
+ use crate::ratelimit::RateLimited;
13
+ use crate::Flavor;
14
+
15
+ pub const NAME: &str = "nerinyan";
16
+ const BASE: &str = "https://api.nerinyan.moe/d";
17
+
18
+ pub struct NerinyanMirror {
19
+ client: Client,
20
+ limiter: RateLimited,
21
+ }
22
+
23
+ impl NerinyanMirror {
24
+ pub fn new(ctx: &MirrorContext) -> Self {
25
+ Self {
26
+ client: ctx.client.clone(),
27
+ limiter: ctx.limiters.nerinyan.clone(),
28
+ }
29
+ }
30
+
31
+ pub fn url(set_id: u64, flavor: Flavor) -> String {
32
+ match flavor {
33
+ Flavor::Full => format!("{BASE}/{set_id}"),
34
+ Flavor::NoVideo => format!("{BASE}/{set_id}?nv=true"),
35
+ }
36
+ }
37
+ }
38
+
39
+ #[async_trait]
40
+ impl Mirror for NerinyanMirror {
41
+ fn name(&self) -> &str {
42
+ NAME
43
+ }
44
+
45
+ fn supports(&self, _flavor: Flavor) -> bool {
46
+ // Both flavors are supported via query params.
47
+ true
48
+ }
49
+
50
+ async fn download(&self, set_id: u64, flavor: Flavor) -> Result<Bytes, MirrorError> {
51
+ self.limiter.acquire().await;
52
+ let url = Self::url(set_id, flavor);
53
+ let resp = self
54
+ .client
55
+ .get(&url)
56
+ .send()
57
+ .await
58
+ .map_err(|e| MirrorError::Network {
59
+ mirror: NAME.into(),
60
+ source: e,
61
+ })?;
62
+ classify_response(NAME, resp).await
63
+ }
64
+ }
65
+
66
+ #[cfg(test)]
67
+ mod tests {
68
+ use super::*;
69
+
70
+ #[test]
71
+ fn url_full_has_no_params() {
72
+ assert_eq!(
73
+ NerinyanMirror::url(123, Flavor::Full),
74
+ "https://api.nerinyan.moe/d/123"
75
+ );
76
+ }
77
+
78
+ #[test]
79
+ fn url_novideo_uses_nv_param() {
80
+ assert_eq!(
81
+ NerinyanMirror::url(123, Flavor::NoVideo),
82
+ "https://api.nerinyan.moe/d/123?nv=true"
83
+ );
84
+ }
85
+ }
crates/osu_fetcher/src/mirrors/nzbasic.rs ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //! direct.nzbasic.com — public mirror, no auth required.
2
+ //!
3
+ //! Endpoint: `GET https://direct.nzbasic.com/{set_id}.osz` — full archive.
4
+ //! This is the same endpoint used by nzbasic's own
5
+ //! [batch-beatmap-downloader](https://github.com/nzbasic/batch-beatmap-downloader),
6
+ //! which just hardcodes a `direct + "{setId}.osz"` GET. There is no documented
7
+ //! novideo variant, so we only register `Full` support; a `NoVideo` request
8
+ //! short-circuits to `UnsupportedFlavor` before any HTTP.
9
+ //!
10
+ //! Note on missing sets: the upstream Go downloader observes that this mirror
11
+ //! sometimes returns a tiny (~36 byte) JSON-ish "doesn't exist" body with a
12
+ //! 200 status instead of a real 404. We don't special-case that here — the
13
+ //! shared `classify_response` helper deep-verifies every successful body via
14
+ //! [`crate::verify::verify_bytes`] and rejects anything without a valid ZIP +
15
+ //! at least one `.osu` file. The pool treats `InvalidArchive` as a recoverable
16
+ //! error and advances to the next mirror, which gives us the same behavior
17
+ //! a proper 404 would. The only cost is a small health-score penalty against
18
+ //! this mirror per missing set; tolerable in practice.
19
+
20
+ use async_trait::async_trait;
21
+ use bytes::Bytes;
22
+ use reqwest::Client;
23
+
24
+ use super::{classify_response, Mirror, MirrorContext, MirrorError};
25
+ use crate::ratelimit::RateLimited;
26
+ use crate::Flavor;
27
+
28
+ pub const NAME: &str = "nzbasic";
29
+ const BASE: &str = "https://direct.nzbasic.com";
30
+
31
+ pub struct NzbasicMirror {
32
+ client: Client,
33
+ limiter: RateLimited,
34
+ }
35
+
36
+ impl NzbasicMirror {
37
+ pub fn new(ctx: &MirrorContext) -> Self {
38
+ Self {
39
+ client: ctx.client.clone(),
40
+ limiter: ctx.limiters.nzbasic.clone(),
41
+ }
42
+ }
43
+
44
+ pub fn url(set_id: u64) -> String {
45
+ format!("{BASE}/{set_id}.osz")
46
+ }
47
+ }
48
+
49
+ #[async_trait]
50
+ impl Mirror for NzbasicMirror {
51
+ fn name(&self) -> &str {
52
+ NAME
53
+ }
54
+
55
+ fn supports(&self, flavor: Flavor) -> bool {
56
+ matches!(flavor, Flavor::Full)
57
+ }
58
+
59
+ async fn download(&self, set_id: u64, flavor: Flavor) -> Result<Bytes, MirrorError> {
60
+ if !self.supports(flavor) {
61
+ return Err(MirrorError::UnsupportedFlavor {
62
+ mirror: NAME.into(),
63
+ flavor,
64
+ });
65
+ }
66
+ self.limiter.acquire().await;
67
+ let url = Self::url(set_id);
68
+ let resp = self
69
+ .client
70
+ .get(&url)
71
+ .send()
72
+ .await
73
+ .map_err(|e| MirrorError::Network {
74
+ mirror: NAME.into(),
75
+ source: e,
76
+ })?;
77
+ classify_response(NAME, resp).await
78
+ }
79
+ }
80
+
81
+ #[cfg(test)]
82
+ mod tests {
83
+ use super::*;
84
+
85
+ #[test]
86
+ fn url_full_uses_osz_suffix() {
87
+ assert_eq!(
88
+ NzbasicMirror::url(1234),
89
+ "https://direct.nzbasic.com/1234.osz"
90
+ );
91
+ }
92
+
93
+ #[test]
94
+ fn novideo_is_not_supported() {
95
+ // Mirror has no documented novideo path; a NoVideo request must
96
+ // surface as UnsupportedFlavor before we burn a rate-limit token.
97
+ let supports_full = matches!(Flavor::Full, Flavor::Full);
98
+ let supports_novideo = matches!(Flavor::NoVideo, Flavor::Full);
99
+ assert!(supports_full);
100
+ assert!(!supports_novideo);
101
+ }
102
+ }
crates/osu_fetcher/src/mirrors/osuapi.rs ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //! Official osu! API — bearer-token authenticated download endpoint.
2
+ //!
3
+ //! Endpoint: `GET https://osu.ppy.sh/api/v2/beatmapsets/{set_id}/download`,
4
+ //! optionally with `?noVideo=1` for the no-video flavor. Authentication
5
+ //! reuses the same [`OsuApi`] instance the `enumerate` phase uses, so a
6
+ //! single token is shared across the whole process — no second OAuth
7
+ //! handshake just for downloads.
8
+ //!
9
+ //! On 401 we invalidate the cached token and retry once. Repeated auth
10
+ //! failures (e.g., a `client_credentials` token without the right scope
11
+ //! to hit this endpoint) become consecutive hard failures in the pool's
12
+ //! health view, so the mirror is sidelined cleanly without poisoning the
13
+ //! whole run.
14
+ //!
15
+ //! The mirror is opt-out via `--disable osuapi` and skipped entirely
16
+ //! when no credentials are configured (handled by the caller in
17
+ //! `main.rs` — see [`OsuApiMirror::new`] returning `Option`).
18
+
19
+ use std::sync::Arc;
20
+
21
+ use async_trait::async_trait;
22
+ use bytes::Bytes;
23
+ use reqwest::{header::AUTHORIZATION, StatusCode};
24
+
25
+ use super::{classify_response, Mirror, MirrorContext, MirrorError};
26
+ use crate::api::OsuApi;
27
+ use crate::ratelimit::RateLimited;
28
+ use crate::Flavor;
29
+
30
+ pub const NAME: &str = "osuapi";
31
+ const BASE: &str = "https://osu.ppy.sh/api/v2/beatmapsets";
32
+
33
+ pub struct OsuApiMirror {
34
+ api: Arc<OsuApi>,
35
+ limiter: RateLimited,
36
+ }
37
+
38
+ impl OsuApiMirror {
39
+ /// Build the mirror. Returns `None` when no credentials were supplied
40
+ /// (`MirrorContext::osu_api` is `None`); the caller treats that as
41
+ /// "skip osuapi" instead of a hard configuration error so users
42
+ /// running the public mirrors alone don't need to register an OAuth
43
+ /// app.
44
+ pub fn new(ctx: &MirrorContext) -> Option<Self> {
45
+ let api = ctx.osu_api.clone()?;
46
+ Some(Self {
47
+ api,
48
+ limiter: ctx.limiters.osuapi.clone(),
49
+ })
50
+ }
51
+
52
+ pub fn url(set_id: u64, flavor: Flavor) -> String {
53
+ match flavor {
54
+ Flavor::Full => format!("{BASE}/{set_id}/download"),
55
+ Flavor::NoVideo => format!("{BASE}/{set_id}/download?noVideo=1"),
56
+ }
57
+ }
58
+
59
+ /// Convert an auth-flow failure (token mint or refresh error) into a
60
+ /// `MirrorError`. We can't construct a `reqwest::Error` from outside
61
+ /// the reqwest crate, and dragging anyhow into `MirrorError` would
62
+ /// pollute every other mirror, so we surface it as a synthetic 401
63
+ /// `HttpError` — the closest existing variant. The pool's health
64
+ /// scoring treats 401 as a hard failure, which is exactly right here.
65
+ fn token_error(reason: impl ToString) -> MirrorError {
66
+ let snippet: String = reason.to_string().chars().take(200).collect();
67
+ MirrorError::HttpError {
68
+ mirror: NAME.into(),
69
+ status: 401,
70
+ body_snippet: format!("auth: {snippet}"),
71
+ }
72
+ }
73
+
74
+ async fn send(&self, url: &str, token: &str) -> Result<reqwest::Response, MirrorError> {
75
+ // Headers match the lazer client byte-for-byte: bearer + pinned
76
+ // x-api-version. The User-Agent is set on the shared OsuApi client
77
+ // (which runs in lazer mode when the user provides username +
78
+ // password), so /api/v2/beatmapsets/{id}/download requests look
79
+ // indistinguishable from a real lazer client on the wire.
80
+ self.api
81
+ .client()
82
+ .get(url)
83
+ .header(AUTHORIZATION, format!("Bearer {token}"))
84
+ .header("x-api-version", self.api.api_version_header())
85
+ .send()
86
+ .await
87
+ .map_err(|e| MirrorError::Network {
88
+ mirror: NAME.into(),
89
+ source: e,
90
+ })
91
+ }
92
+ }
93
+
94
+ #[async_trait]
95
+ impl Mirror for OsuApiMirror {
96
+ fn name(&self) -> &str {
97
+ NAME
98
+ }
99
+
100
+ fn supports(&self, _flavor: Flavor) -> bool {
101
+ // The endpoint accepts both flavors via `?noVideo=1`.
102
+ true
103
+ }
104
+
105
+ async fn download(&self, set_id: u64, flavor: Flavor) -> Result<Bytes, MirrorError> {
106
+ self.limiter.acquire().await;
107
+ let url = Self::url(set_id, flavor);
108
+ let token = self.api.current_token().await.map_err(Self::token_error)?;
109
+ let resp = self.send(&url, &token).await?;
110
+ if resp.status() == StatusCode::UNAUTHORIZED {
111
+ // Cached token may have been invalidated server-side. Force a
112
+ // mint and try once more before falling through to the next
113
+ // mirror. The pool will sideline us via health scoring if 401
114
+ // becomes the steady state.
115
+ self.api.invalidate_token().await;
116
+ let token = self.api.current_token().await.map_err(Self::token_error)?;
117
+ let resp = self.send(&url, &token).await?;
118
+ return classify_response(NAME, resp).await;
119
+ }
120
+ classify_response(NAME, resp).await
121
+ }
122
+ }
123
+
124
+ #[cfg(test)]
125
+ mod tests {
126
+ use super::*;
127
+
128
+ #[test]
129
+ fn url_full_uses_documented_endpoint() {
130
+ assert_eq!(
131
+ OsuApiMirror::url(218851, Flavor::Full),
132
+ "https://osu.ppy.sh/api/v2/beatmapsets/218851/download"
133
+ );
134
+ }
135
+
136
+ #[test]
137
+ fn url_novideo_appends_no_video_query() {
138
+ assert_eq!(
139
+ OsuApiMirror::url(218851, Flavor::NoVideo),
140
+ "https://osu.ppy.sh/api/v2/beatmapsets/218851/download?noVideo=1"
141
+ );
142
+ }
143
+ }
crates/osu_fetcher/src/mirrors/osudirect.rs ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //! osu.direct — public mirror, no auth required.
2
+ //!
3
+ //! Endpoint: `GET https://osu.direct/api/d/{set_id}` (full archive) or
4
+ //! `?noVideo=true` for the no-video flavor. Returns a 302 redirect to a
5
+ //! signed iDrive E2 (S3-compatible) URL; reqwest's default redirect
6
+ //! policy follows it transparently, so the call site sees the eventual
7
+ //! `.osz` body the same as any other mirror.
8
+ //!
9
+ //! Native rate limit (observed via `RateLimit-Limit` header): 120
10
+ //! requests / 60s — generous compared to other mirrors. Our default
11
+ //! `--osudirect-rpm` is 60 for headroom; override with the flag if
12
+ //! you've coordinated higher.
13
+ //!
14
+ //! Docs: <https://osu.direct/api/docs>
15
+
16
+ use async_trait::async_trait;
17
+ use bytes::Bytes;
18
+ use reqwest::Client;
19
+
20
+ use super::{classify_response, Mirror, MirrorContext, MirrorError};
21
+ use crate::ratelimit::RateLimited;
22
+ use crate::Flavor;
23
+
24
+ pub const NAME: &str = "osudirect";
25
+ const BASE: &str = "https://osu.direct/api/d";
26
+
27
+ pub struct OsuDirectMirror {
28
+ client: Client,
29
+ limiter: RateLimited,
30
+ }
31
+
32
+ impl OsuDirectMirror {
33
+ pub fn new(ctx: &MirrorContext) -> Self {
34
+ Self {
35
+ client: ctx.client.clone(),
36
+ limiter: ctx.limiters.osudirect.clone(),
37
+ }
38
+ }
39
+
40
+ pub fn url(set_id: u64, flavor: Flavor) -> String {
41
+ match flavor {
42
+ Flavor::Full => format!("{BASE}/{set_id}"),
43
+ Flavor::NoVideo => format!("{BASE}/{set_id}?noVideo=true"),
44
+ }
45
+ }
46
+ }
47
+
48
+ #[async_trait]
49
+ impl Mirror for OsuDirectMirror {
50
+ fn name(&self) -> &str {
51
+ NAME
52
+ }
53
+
54
+ fn supports(&self, _flavor: Flavor) -> bool {
55
+ // Both flavors via the noVideo query param.
56
+ true
57
+ }
58
+
59
+ async fn download(&self, set_id: u64, flavor: Flavor) -> Result<Bytes, MirrorError> {
60
+ self.limiter.acquire().await;
61
+ let url = Self::url(set_id, flavor);
62
+ let resp = self
63
+ .client
64
+ .get(&url)
65
+ .send()
66
+ .await
67
+ .map_err(|e| MirrorError::Network {
68
+ mirror: NAME.into(),
69
+ source: e,
70
+ })?;
71
+ classify_response(NAME, resp).await
72
+ }
73
+ }
74
+
75
+ #[cfg(test)]
76
+ mod tests {
77
+ use super::*;
78
+
79
+ #[test]
80
+ fn url_full_uses_plain_id() {
81
+ assert_eq!(
82
+ OsuDirectMirror::url(1234, Flavor::Full),
83
+ "https://osu.direct/api/d/1234"
84
+ );
85
+ }
86
+
87
+ #[test]
88
+ fn url_novideo_appends_query_param() {
89
+ assert_eq!(
90
+ OsuDirectMirror::url(1234, Flavor::NoVideo),
91
+ "https://osu.direct/api/d/1234?noVideo=true"
92
+ );
93
+ }
94
+ }
crates/osu_fetcher/src/mirrors/osudl.rs ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //! osudl.org — public mirror, no auth required.
2
+ //!
3
+ //! Endpoint: `GET https://osudl.org/s/{set_id}`. The mirror exposes a single
4
+ //! short-link path regardless of flavor; reqwest follows whatever redirect
5
+ //! it issues to the underlying archive. We treat the response as Full (the
6
+ //! dataset's only target) and let `classify_response` deep-verify the bytes
7
+ //! as a real `.osz` before accepting them.
8
+
9
+ use async_trait::async_trait;
10
+ use bytes::Bytes;
11
+ use reqwest::Client;
12
+
13
+ use super::{classify_response, Mirror, MirrorContext, MirrorError};
14
+ use crate::ratelimit::RateLimited;
15
+ use crate::Flavor;
16
+
17
+ pub const NAME: &str = "osudl";
18
+ const BASE: &str = "https://osudl.org/s";
19
+
20
+ pub struct OsudlMirror {
21
+ client: Client,
22
+ limiter: RateLimited,
23
+ }
24
+
25
+ impl OsudlMirror {
26
+ pub fn new(ctx: &MirrorContext) -> Self {
27
+ Self {
28
+ client: ctx.client.clone(),
29
+ limiter: ctx.limiters.osudl.clone(),
30
+ }
31
+ }
32
+
33
+ pub fn url(set_id: u64) -> String {
34
+ format!("{BASE}/{set_id}")
35
+ }
36
+ }
37
+
38
+ #[async_trait]
39
+ impl Mirror for OsudlMirror {
40
+ fn name(&self) -> &str {
41
+ NAME
42
+ }
43
+
44
+ fn supports(&self, _flavor: Flavor) -> bool {
45
+ true
46
+ }
47
+
48
+ async fn download(&self, set_id: u64, _flavor: Flavor) -> Result<Bytes, MirrorError> {
49
+ self.limiter.acquire().await;
50
+ let url = Self::url(set_id);
51
+ let resp = self
52
+ .client
53
+ .get(&url)
54
+ .send()
55
+ .await
56
+ .map_err(|e| MirrorError::Network {
57
+ mirror: NAME.into(),
58
+ source: e,
59
+ })?;
60
+ classify_response(NAME, resp).await
61
+ }
62
+ }
63
+
64
+ #[cfg(test)]
65
+ mod tests {
66
+ use super::*;
67
+
68
+ #[test]
69
+ fn url_uses_short_link_path() {
70
+ assert_eq!(OsudlMirror::url(2513011), "https://osudl.org/s/2513011");
71
+ }
72
+
73
+ #[test]
74
+ fn url_works_for_low_id() {
75
+ assert_eq!(OsudlMirror::url(1), "https://osudl.org/s/1");
76
+ }
77
+ }
crates/osu_fetcher/src/mirrors/sayobot.rs ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //! sayobot.cn — public Chinese mirror, no auth required.
2
+ //!
3
+ //! Endpoint: `GET https://txy1.sayobot.cn/beatmaps/download/{type}/{set_id}`
4
+ //! where `{type}` is `full`, `novideo`, or `mini`. For our lossless dataset
5
+ //! we only use `full` and `novideo`; `mini` strips hitsounds and is therefore
6
+ //! not useful as a primary source.
7
+ //!
8
+ //! sayobot is geographically far from the typical English-speaking user but
9
+ //! retains some maps that have rotated off Western mirrors, so it earns a
10
+ //! place in the fallback chain.
11
+
12
+ use async_trait::async_trait;
13
+ use bytes::Bytes;
14
+ use reqwest::Client;
15
+
16
+ use super::{classify_response, Mirror, MirrorContext, MirrorError};
17
+ use crate::ratelimit::RateLimited;
18
+ use crate::Flavor;
19
+
20
+ pub const NAME: &str = "sayobot";
21
+ const BASE: &str = "https://txy1.sayobot.cn/beatmaps/download";
22
+
23
+ pub struct SayobotMirror {
24
+ client: Client,
25
+ limiter: RateLimited,
26
+ }
27
+
28
+ impl SayobotMirror {
29
+ pub fn new(ctx: &MirrorContext) -> Self {
30
+ Self {
31
+ client: ctx.client.clone(),
32
+ limiter: ctx.limiters.sayobot.clone(),
33
+ }
34
+ }
35
+
36
+ pub fn url(set_id: u64, flavor: Flavor) -> String {
37
+ let kind = match flavor {
38
+ Flavor::Full => "full",
39
+ Flavor::NoVideo => "novideo",
40
+ };
41
+ format!("{BASE}/{kind}/{set_id}")
42
+ }
43
+ }
44
+
45
+ #[async_trait]
46
+ impl Mirror for SayobotMirror {
47
+ fn name(&self) -> &str {
48
+ NAME
49
+ }
50
+
51
+ fn supports(&self, _flavor: Flavor) -> bool {
52
+ true
53
+ }
54
+
55
+ async fn download(&self, set_id: u64, flavor: Flavor) -> Result<Bytes, MirrorError> {
56
+ self.limiter.acquire().await;
57
+ let url = Self::url(set_id, flavor);
58
+ let resp = self
59
+ .client
60
+ .get(&url)
61
+ .send()
62
+ .await
63
+ .map_err(|e| MirrorError::Network {
64
+ mirror: NAME.into(),
65
+ source: e,
66
+ })?;
67
+ classify_response(NAME, resp).await
68
+ }
69
+ }
70
+
71
+ #[cfg(test)]
72
+ mod tests {
73
+ use super::*;
74
+
75
+ #[test]
76
+ fn url_full_uses_full_path_segment() {
77
+ assert_eq!(
78
+ SayobotMirror::url(123, Flavor::Full),
79
+ "https://txy1.sayobot.cn/beatmaps/download/full/123"
80
+ );
81
+ }
82
+
83
+ #[test]
84
+ fn url_novideo_uses_novideo_path_segment() {
85
+ assert_eq!(
86
+ SayobotMirror::url(123, Flavor::NoVideo),
87
+ "https://txy1.sayobot.cn/beatmaps/download/novideo/123"
88
+ );
89
+ }
90
+ }
crates/osu_fetcher/src/progress.rs ADDED
@@ -0,0 +1,612 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //! Live terminal dashboards for the long-running subcommands.
2
+ //!
3
+ //! For `download`, this is a multi-pane view built on `indicatif`'s
4
+ //! [`MultiProgress`]: a header line, the main progress bar, an aggregate
5
+ //! totals line, and a per-mirror table. The dashboard is purely a *view* —
6
+ //! callers update it via lock-free atomic counters, and a background tick
7
+ //! task re-renders the messages every 250 ms. Counters and bars live
8
+ //! together inside [`DownloadDashboard`] so a single `Arc` is everything a
9
+ //! worker needs.
10
+ //!
11
+ //! When stderr is not a TTY (CI, log redirect, `--no-progress`), the
12
+ //! [`MultiProgress`] is built with a hidden draw target so the same code
13
+ //! paths are used either way; calls become silent rather than missing.
14
+ //!
15
+ //! Design notes:
16
+ //! * The mirror table is a column-aligned text format rendered into the
17
+ //! `set_message` of one spinner per mirror. The header row uses the same
18
+ //! format string with the column titles, so the columns can never drift
19
+ //! out of alignment.
20
+ //! * The main bar's `pos` is incremented exactly once per terminal worker
21
+ //! outcome (success / failed / missing). `aborted` does *not* advance the
22
+ //! bar — the row will be retried on the next run, so counting it as
23
+ //! progress would lie about ETA.
24
+ //! * `enable_steady_tick` is intentionally not used; the tick task drives
25
+ //! redraw via `set_message`.
26
+
27
+ use std::sync::atomic::{AtomicU64, Ordering};
28
+ use std::sync::Arc;
29
+ use std::time::{Duration, Instant};
30
+
31
+ #[cfg(unix)]
32
+ use console::Term;
33
+ use indicatif::{
34
+ HumanBytes, HumanDuration, MultiProgress, ProgressBar, ProgressDrawTarget, ProgressStyle,
35
+ };
36
+ use tokio::task::JoinHandle;
37
+ use tokio_util::sync::CancellationToken;
38
+
39
+ use crate::mirrors::{AttemptObserver, AttemptOutcome as MirrorAttemptOutcome};
40
+
41
+ #[derive(Clone, Copy, Debug, Eq, PartialEq)]
42
+ pub enum ProgressTarget {
43
+ Hidden,
44
+ Stderr,
45
+ Tty,
46
+ }
47
+
48
+ impl ProgressTarget {
49
+ pub fn enabled(self) -> bool {
50
+ !matches!(self, Self::Hidden)
51
+ }
52
+ }
53
+
54
+ fn draw_target(target: ProgressTarget) -> ProgressDrawTarget {
55
+ match target {
56
+ ProgressTarget::Hidden => ProgressDrawTarget::hidden(),
57
+ ProgressTarget::Stderr => ProgressDrawTarget::stderr(),
58
+ ProgressTarget::Tty => tty_draw_target().unwrap_or_else(ProgressDrawTarget::stderr),
59
+ }
60
+ }
61
+
62
+ #[cfg(unix)]
63
+ fn tty_draw_target() -> Option<ProgressDrawTarget> {
64
+ let read = std::fs::OpenOptions::new()
65
+ .read(true)
66
+ .open("/dev/tty")
67
+ .ok()?;
68
+ let write = std::fs::OpenOptions::new()
69
+ .write(true)
70
+ .open("/dev/tty")
71
+ .ok()?;
72
+ Some(ProgressDrawTarget::term(
73
+ Term::read_write_pair(read, write),
74
+ 20,
75
+ ))
76
+ }
77
+
78
+ #[cfg(not(unix))]
79
+ fn tty_draw_target() -> Option<ProgressDrawTarget> {
80
+ None
81
+ }
82
+
83
+ /// Per-mirror counters. All fields use `Relaxed` ordering — accuracy across
84
+ /// threads doesn't need a memory barrier; we just want monotonically
85
+ /// non-decreasing values that the renderer reads as a snapshot.
86
+ #[derive(Default)]
87
+ struct MirrorCounters {
88
+ reqs: AtomicU64,
89
+ ok: AtomicU64,
90
+ not_found: AtomicU64,
91
+ rate_limited: AtomicU64,
92
+ network: AtomicU64,
93
+ invalid: AtomicU64,
94
+ http_error: AtomicU64,
95
+ /// Counts attempts that hit the pool's per-attempt deadline. Surfaced
96
+ /// in its own dashboard column so a hung mirror is visually obvious
97
+ /// (vs being lumped into a generic "err" bucket).
98
+ timeout: AtomicU64,
99
+ total_duration_ms: AtomicU64,
100
+ /// Sum of successful-attempt durations only — pairs with `bytes`
101
+ /// (success-only) to give a clean MiB/s for the dashboard.
102
+ total_success_duration_ms: AtomicU64,
103
+ inflight: AtomicU64,
104
+ bytes: AtomicU64,
105
+ }
106
+
107
+ /// Top-level dashboard for the `download` subcommand.
108
+ pub struct DownloadDashboard {
109
+ multi: MultiProgress,
110
+ header: ProgressBar,
111
+ main: ProgressBar,
112
+ totals: ProgressBar,
113
+ mirror_header: ProgressBar,
114
+ mirror_bars: Vec<ProgressBar>,
115
+
116
+ mirrors: Vec<(String, MirrorCounters)>,
117
+
118
+ success: AtomicU64,
119
+ failed: AtomicU64,
120
+ missing: AtomicU64,
121
+ aborted: AtomicU64,
122
+ bytes: AtomicU64,
123
+ inflight: AtomicU64,
124
+ started: Instant,
125
+
126
+ enabled: bool,
127
+ concurrency: usize,
128
+ }
129
+
130
+ impl DownloadDashboard {
131
+ pub fn new(
132
+ total: u64,
133
+ concurrency: usize,
134
+ mirrors: &[&str],
135
+ target: ProgressTarget,
136
+ ) -> Arc<Self> {
137
+ let multi = MultiProgress::with_draw_target(draw_target(target));
138
+
139
+ let header = multi.add(ProgressBar::new_spinner());
140
+ header.set_style(ProgressStyle::with_template("{msg}").unwrap());
141
+
142
+ let main = multi.add(ProgressBar::new(total));
143
+ main.set_style(
144
+ ProgressStyle::with_template(
145
+ " [{bar:40.cyan/blue}] {pos:>7}/{len:<7} {percent:>3}% · {msg}",
146
+ )
147
+ .unwrap()
148
+ .progress_chars("█▉▊▋▌▍▎▏ "),
149
+ );
150
+ main.set_message("starting…");
151
+
152
+ let totals = multi.add(ProgressBar::new_spinner());
153
+ totals.set_style(ProgressStyle::with_template(" {msg}").unwrap());
154
+ totals.set_message("ok 0 · failed 0 · missing 0 · aborted 0".to_string());
155
+
156
+ let mirror_header = multi.add(ProgressBar::new_spinner());
157
+ mirror_header.set_style(ProgressStyle::with_template("{msg}").unwrap());
158
+ mirror_header.set_message(mirror_header_line());
159
+
160
+ let mut mirror_bars = Vec::with_capacity(mirrors.len());
161
+ let mut mirrors_vec = Vec::with_capacity(mirrors.len());
162
+ for name in mirrors {
163
+ let pb = multi.add(ProgressBar::new_spinner());
164
+ pb.set_style(ProgressStyle::with_template("{msg}").unwrap());
165
+ let counters = MirrorCounters::default();
166
+ pb.set_message(format_mirror_line(name, &counters));
167
+ mirror_bars.push(pb);
168
+ mirrors_vec.push((name.to_string(), counters));
169
+ }
170
+
171
+ let dash = Arc::new(Self {
172
+ multi,
173
+ header,
174
+ main,
175
+ totals,
176
+ mirror_header,
177
+ mirror_bars,
178
+ mirrors: mirrors_vec,
179
+ success: AtomicU64::new(0),
180
+ failed: AtomicU64::new(0),
181
+ missing: AtomicU64::new(0),
182
+ aborted: AtomicU64::new(0),
183
+ bytes: AtomicU64::new(0),
184
+ inflight: AtomicU64::new(0),
185
+ started: Instant::now(),
186
+ enabled: target.enabled(),
187
+ concurrency,
188
+ });
189
+ dash.render();
190
+ dash
191
+ }
192
+
193
+ /// Print a line above the dashboard. Visible in both enabled and hidden
194
+ /// mode (in hidden mode it falls back to plain stderr).
195
+ pub fn println(&self, msg: impl AsRef<str>) {
196
+ if self.enabled {
197
+ let _ = self.multi.println(msg.as_ref());
198
+ } else {
199
+ eprintln!("{}", msg.as_ref());
200
+ }
201
+ }
202
+
203
+ pub fn record_attempt(
204
+ &self,
205
+ mirror: &str,
206
+ outcome: MirrorAttemptOutcome,
207
+ duration: Duration,
208
+ bytes: Option<u64>,
209
+ ) {
210
+ let Some((_, c)) = self.mirrors.iter().find(|(n, _)| n == mirror) else {
211
+ return;
212
+ };
213
+ c.reqs.fetch_add(1, Ordering::Relaxed);
214
+ c.total_duration_ms
215
+ .fetch_add(duration.as_millis() as u64, Ordering::Relaxed);
216
+ if let Some(b) = bytes {
217
+ c.bytes.fetch_add(b, Ordering::Relaxed);
218
+ }
219
+ match outcome {
220
+ MirrorAttemptOutcome::Success => {
221
+ c.ok.fetch_add(1, Ordering::Relaxed);
222
+ c.total_success_duration_ms
223
+ .fetch_add(duration.as_millis() as u64, Ordering::Relaxed);
224
+ }
225
+ MirrorAttemptOutcome::NotFound => {
226
+ c.not_found.fetch_add(1, Ordering::Relaxed);
227
+ }
228
+ MirrorAttemptOutcome::RateLimited => {
229
+ c.rate_limited.fetch_add(1, Ordering::Relaxed);
230
+ }
231
+ MirrorAttemptOutcome::Network => {
232
+ c.network.fetch_add(1, Ordering::Relaxed);
233
+ }
234
+ MirrorAttemptOutcome::InvalidArchive => {
235
+ c.invalid.fetch_add(1, Ordering::Relaxed);
236
+ }
237
+ MirrorAttemptOutcome::HttpError => {
238
+ c.http_error.fetch_add(1, Ordering::Relaxed);
239
+ }
240
+ MirrorAttemptOutcome::Timeout => {
241
+ c.timeout.fetch_add(1, Ordering::Relaxed);
242
+ }
243
+ MirrorAttemptOutcome::UnsupportedFlavor => {}
244
+ }
245
+ }
246
+
247
+ pub fn mirror_inflight_inc(&self, mirror: &str) {
248
+ if let Some((_, c)) = self.mirrors.iter().find(|(n, _)| n == mirror) {
249
+ c.inflight.fetch_add(1, Ordering::Relaxed);
250
+ }
251
+ }
252
+ pub fn mirror_inflight_dec(&self, mirror: &str) {
253
+ if let Some((_, c)) = self.mirrors.iter().find(|(n, _)| n == mirror) {
254
+ c.inflight.fetch_sub(1, Ordering::Relaxed);
255
+ }
256
+ }
257
+ pub fn worker_inflight_inc(&self) {
258
+ self.inflight.fetch_add(1, Ordering::Relaxed);
259
+ }
260
+ pub fn worker_inflight_dec(&self) {
261
+ self.inflight.fetch_sub(1, Ordering::Relaxed);
262
+ }
263
+
264
+ pub fn record_success(&self, bytes: u64) {
265
+ self.success.fetch_add(1, Ordering::Relaxed);
266
+ self.bytes.fetch_add(bytes, Ordering::Relaxed);
267
+ self.main.inc(1);
268
+ }
269
+ pub fn record_failed(&self) {
270
+ self.failed.fetch_add(1, Ordering::Relaxed);
271
+ self.main.inc(1);
272
+ }
273
+ pub fn record_missing(&self) {
274
+ self.missing.fetch_add(1, Ordering::Relaxed);
275
+ self.main.inc(1);
276
+ }
277
+ pub fn record_aborted(&self) {
278
+ // Aborted rows go back to pending, so they shouldn't advance the bar
279
+ // (otherwise ETA lies on resume).
280
+ self.aborted.fetch_add(1, Ordering::Relaxed);
281
+ }
282
+
283
+ /// Recompute messages for all bars from current atomic state.
284
+ pub fn render(&self) {
285
+ let elapsed = self.started.elapsed();
286
+ let elapsed_secs = elapsed.as_secs_f64().max(0.001);
287
+ let success = self.success.load(Ordering::Relaxed);
288
+ let failed = self.failed.load(Ordering::Relaxed);
289
+ let missing = self.missing.load(Ordering::Relaxed);
290
+ let aborted = self.aborted.load(Ordering::Relaxed);
291
+ let bytes = self.bytes.load(Ordering::Relaxed);
292
+ let inflight = self.inflight.load(Ordering::Relaxed);
293
+
294
+ // Header — keep it short; the running clock makes it feel alive.
295
+ self.header.set_message(format!(
296
+ "osu_fetcher download · {} workers · running {}",
297
+ self.concurrency,
298
+ HumanDuration(elapsed),
299
+ ));
300
+
301
+ // Main bar message: ETA + sets/sec.
302
+ let pos = self.main.position();
303
+ let len = self.main.length().unwrap_or(0);
304
+ let sps = pos as f64 / elapsed_secs;
305
+ let eta_str = if sps > 0.05 && len > pos {
306
+ let secs = ((len - pos) as f64 / sps) as u64;
307
+ format!("{}", HumanDuration(Duration::from_secs(secs)))
308
+ } else {
309
+ "—".to_string()
310
+ };
311
+ self.main
312
+ .set_message(format!("ETA {:>10} · {:>5.1} sets/s", eta_str, sps));
313
+
314
+ // Totals.
315
+ let avg_size = if success > 0 { bytes / success } else { 0 };
316
+ let bps = (bytes as f64 / elapsed_secs) as u64;
317
+ self.totals.set_message(format!(
318
+ "ok {success} failed {failed} missing {missing} aborted {aborted} · {} at {}/s · avg {} · {inflight} in flight",
319
+ HumanBytes(bytes),
320
+ HumanBytes(bps),
321
+ HumanBytes(avg_size),
322
+ ));
323
+
324
+ // Per-mirror lines.
325
+ for (i, (name, c)) in self.mirrors.iter().enumerate() {
326
+ self.mirror_bars[i].set_message(format_mirror_line(name, c));
327
+ }
328
+ }
329
+
330
+ /// Stop drawing and print one final summary line. Call once at the end
331
+ /// of `download::run`.
332
+ pub fn finalize(&self) {
333
+ self.render();
334
+ // Set the main bar's prefix-ish message to a finished state, then
335
+ // freeze everything. `finish` leaves the bars at their current
336
+ // rendered values so the user can see the final dashboard.
337
+ self.header.finish();
338
+ self.main.finish();
339
+ self.totals.finish();
340
+ self.mirror_header.finish();
341
+ for pb in &self.mirror_bars {
342
+ pb.finish();
343
+ }
344
+ }
345
+ }
346
+
347
+ /// Wire the dashboard up as the pool's per-attempt observer so the
348
+ /// per-mirror `in` column reflects real-time concurrency. Uses the
349
+ /// existing `mirror_inflight_inc/dec` atomics.
350
+ impl AttemptObserver for DownloadDashboard {
351
+ fn before_attempt(&self, mirror: &str) {
352
+ self.mirror_inflight_inc(mirror);
353
+ }
354
+ fn after_attempt(&self, mirror: &str) {
355
+ self.mirror_inflight_dec(mirror);
356
+ }
357
+ }
358
+
359
+ const COL_NAME: usize = 14;
360
+ const COL_REQS: usize = 7;
361
+ const COL_OK: usize = 7;
362
+ const COL_MISS: usize = 7;
363
+ const COL_RL: usize = 5;
364
+ const COL_ERR: usize = 5;
365
+ const COL_TMO: usize = 5;
366
+ const COL_INV: usize = 5;
367
+ const COL_MS: usize = 6;
368
+ const COL_MBPS: usize = 7;
369
+ const COL_PCT: usize = 6;
370
+ const COL_IN: usize = 5;
371
+
372
+ fn mirror_header_line() -> String {
373
+ format!(
374
+ " {:<w_name$} {:>w_reqs$} {:>w_ok$} {:>w_miss$} {:>w_rl$} {:>w_err$} {:>w_tmo$} {:>w_inv$} {:>w_ms$} {:>w_mbps$} {:>w_pct$} {:>w_in$}",
375
+ "mirror", "reqs", "ok", "miss", "429", "err", "tmo", "inv", "ms", "MiB/s", "ok%", "in",
376
+ w_name = COL_NAME,
377
+ w_reqs = COL_REQS,
378
+ w_ok = COL_OK,
379
+ w_miss = COL_MISS,
380
+ w_rl = COL_RL,
381
+ w_err = COL_ERR,
382
+ w_tmo = COL_TMO,
383
+ w_inv = COL_INV,
384
+ w_ms = COL_MS,
385
+ w_mbps = COL_MBPS,
386
+ w_pct = COL_PCT,
387
+ w_in = COL_IN,
388
+ )
389
+ }
390
+
391
+ fn format_mirror_line(name: &str, c: &MirrorCounters) -> String {
392
+ let reqs = c.reqs.load(Ordering::Relaxed);
393
+ let ok = c.ok.load(Ordering::Relaxed);
394
+ let miss = c.not_found.load(Ordering::Relaxed);
395
+ let rate = c.rate_limited.load(Ordering::Relaxed);
396
+ let net = c.network.load(Ordering::Relaxed);
397
+ let http = c.http_error.load(Ordering::Relaxed);
398
+ let inv = c.invalid.load(Ordering::Relaxed);
399
+ let tmo = c.timeout.load(Ordering::Relaxed);
400
+ let dur = c.total_duration_ms.load(Ordering::Relaxed);
401
+ let success_dur = c.total_success_duration_ms.load(Ordering::Relaxed);
402
+ let bytes = c.bytes.load(Ordering::Relaxed);
403
+ let inflight = c.inflight.load(Ordering::Relaxed);
404
+ // `err` keeps its original meaning (network + http_error) so users
405
+ // who scan it for "things going wrong" still see the same number;
406
+ // timeouts get their own column because they're the specific signal
407
+ // the user added a deadline to detect.
408
+ let err = net + http;
409
+ let avg_ms = if reqs > 0 { dur / reqs } else { 0 };
410
+ let mibps = if success_dur > 0 {
411
+ // bytes / (success_dur ms) → bytes / (success_dur / 1000 sec).
412
+ // Convert to MiB/s.
413
+ let bps = bytes as f64 * 1000.0 / success_dur as f64;
414
+ format!("{:.2}", bps / 1_048_576.0)
415
+ } else {
416
+ "—".to_string()
417
+ };
418
+ let ok_pct = if reqs > 0 {
419
+ format!("{:.1}%", 100.0 * ok as f64 / reqs as f64)
420
+ } else {
421
+ "—".to_string()
422
+ };
423
+ format!(
424
+ " {:<w_name$} {:>w_reqs$} {:>w_ok$} {:>w_miss$} {:>w_rl$} {:>w_err$} {:>w_tmo$} {:>w_inv$} {:>w_ms$} {:>w_mbps$} {:>w_pct$} {:>w_in$}",
425
+ truncate(name, COL_NAME),
426
+ reqs,
427
+ ok,
428
+ miss,
429
+ rate,
430
+ err,
431
+ tmo,
432
+ inv,
433
+ avg_ms,
434
+ mibps,
435
+ ok_pct,
436
+ inflight,
437
+ w_name = COL_NAME,
438
+ w_reqs = COL_REQS,
439
+ w_ok = COL_OK,
440
+ w_miss = COL_MISS,
441
+ w_rl = COL_RL,
442
+ w_err = COL_ERR,
443
+ w_tmo = COL_TMO,
444
+ w_inv = COL_INV,
445
+ w_ms = COL_MS,
446
+ w_mbps = COL_MBPS,
447
+ w_pct = COL_PCT,
448
+ w_in = COL_IN,
449
+ )
450
+ }
451
+
452
+ fn truncate(s: &str, n: usize) -> String {
453
+ if s.chars().count() <= n {
454
+ s.to_string()
455
+ } else {
456
+ s.chars()
457
+ .take(n.saturating_sub(1))
458
+ .chain(std::iter::once('…'))
459
+ .collect()
460
+ }
461
+ }
462
+
463
+ /// Spawn a background task that re-renders the dashboard every 250 ms until
464
+ /// `shutdown` fires. The handle should be awaited (or aborted) by
465
+ /// `download::run` before the dashboard is finalized.
466
+ pub fn spawn_tick_task(
467
+ dash: Arc<DownloadDashboard>,
468
+ shutdown: CancellationToken,
469
+ ) -> JoinHandle<()> {
470
+ tokio::spawn(async move {
471
+ let mut interval = tokio::time::interval(Duration::from_millis(250));
472
+ interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
473
+ loop {
474
+ tokio::select! {
475
+ _ = shutdown.cancelled() => {
476
+ dash.render();
477
+ break;
478
+ }
479
+ _ = interval.tick() => dash.render(),
480
+ }
481
+ }
482
+ })
483
+ }
484
+
485
+ /// Whether stderr is connected to a terminal. Use this to decide whether
486
+ /// to enable the dashboard by default.
487
+ pub fn stderr_is_terminal() -> bool {
488
+ use std::io::IsTerminal;
489
+ std::io::stderr().is_terminal()
490
+ }
491
+
492
+ /// Lightweight one-line spinner used by `enumerate` and `scan`. The total
493
+ /// is unknown (cursor-driven pagination / fs walk), so a counter spinner
494
+ /// is the right shape — no length, just an updating message.
495
+ pub struct CounterSpinner {
496
+ multi: MultiProgress,
497
+ pb: ProgressBar,
498
+ enabled: bool,
499
+ }
500
+
501
+ impl CounterSpinner {
502
+ pub fn new(prefix: &str, enable: bool) -> Self {
503
+ let multi = if enable {
504
+ MultiProgress::with_draw_target(ProgressDrawTarget::stderr())
505
+ } else {
506
+ MultiProgress::with_draw_target(ProgressDrawTarget::hidden())
507
+ };
508
+ let pb = multi.add(ProgressBar::new_spinner());
509
+ pb.set_style(
510
+ ProgressStyle::with_template(" {spinner:.cyan} {prefix} · {msg}")
511
+ .unwrap()
512
+ .tick_chars("⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏ "),
513
+ );
514
+ pb.set_prefix(prefix.to_string());
515
+ pb.set_message("starting…");
516
+ pb.enable_steady_tick(Duration::from_millis(120));
517
+ Self {
518
+ multi,
519
+ pb,
520
+ enabled: enable,
521
+ }
522
+ }
523
+
524
+ pub fn set_message(&self, msg: impl Into<String>) {
525
+ self.pb.set_message(msg.into());
526
+ }
527
+
528
+ pub fn println(&self, msg: impl AsRef<str>) {
529
+ if self.enabled {
530
+ let _ = self.multi.println(msg.as_ref());
531
+ } else {
532
+ eprintln!("{}", msg.as_ref());
533
+ }
534
+ }
535
+
536
+ pub fn finish(&self, final_msg: impl Into<String>) {
537
+ self.pb.set_message(final_msg.into());
538
+ self.pb.finish();
539
+ }
540
+ }
541
+
542
+ #[cfg(test)]
543
+ mod tests {
544
+ use super::*;
545
+
546
+ #[test]
547
+ fn header_and_row_have_matching_widths() {
548
+ let header = mirror_header_line();
549
+ let row = format_mirror_line("nerinyan", &MirrorCounters::default());
550
+ assert_eq!(
551
+ header.chars().count(),
552
+ row.chars().count(),
553
+ "header `{}` and row `{}` should be equal width",
554
+ header,
555
+ row
556
+ );
557
+ }
558
+
559
+ #[test]
560
+ fn mirror_name_truncates_when_too_long() {
561
+ let row = format_mirror_line("a-very-long-mirror-name", &MirrorCounters::default());
562
+ // Should still match header width.
563
+ assert_eq!(row.chars().count(), mirror_header_line().chars().count());
564
+ }
565
+
566
+ #[test]
567
+ fn record_attempt_increments_appropriate_counters() {
568
+ let dash = DownloadDashboard::new(10, 1, &["nerinyan"], ProgressTarget::Hidden);
569
+ dash.record_attempt(
570
+ "nerinyan",
571
+ MirrorAttemptOutcome::Success,
572
+ Duration::from_millis(100),
573
+ Some(1024),
574
+ );
575
+ dash.record_attempt(
576
+ "nerinyan",
577
+ MirrorAttemptOutcome::RateLimited,
578
+ Duration::from_millis(50),
579
+ None,
580
+ );
581
+ let (_, c) = &dash.mirrors[0];
582
+ assert_eq!(c.reqs.load(Ordering::Relaxed), 2);
583
+ assert_eq!(c.ok.load(Ordering::Relaxed), 1);
584
+ assert_eq!(c.rate_limited.load(Ordering::Relaxed), 1);
585
+ assert_eq!(c.total_duration_ms.load(Ordering::Relaxed), 150);
586
+ assert_eq!(c.bytes.load(Ordering::Relaxed), 1024);
587
+ }
588
+
589
+ #[test]
590
+ fn record_success_advances_main_bar_record_aborted_does_not() {
591
+ let dash = DownloadDashboard::new(10, 1, &[], ProgressTarget::Hidden);
592
+ dash.record_success(2048);
593
+ dash.record_aborted();
594
+ assert_eq!(dash.main.position(), 1, "abort should not advance bar");
595
+ assert_eq!(dash.success.load(Ordering::Relaxed), 1);
596
+ assert_eq!(dash.aborted.load(Ordering::Relaxed), 1);
597
+ assert_eq!(dash.bytes.load(Ordering::Relaxed), 2048);
598
+ }
599
+
600
+ #[test]
601
+ fn record_attempt_for_unknown_mirror_is_noop() {
602
+ let dash = DownloadDashboard::new(10, 1, &["nerinyan"], ProgressTarget::Hidden);
603
+ dash.record_attempt(
604
+ "ghostmirror",
605
+ MirrorAttemptOutcome::Success,
606
+ Duration::from_millis(10),
607
+ None,
608
+ );
609
+ let (_, c) = &dash.mirrors[0];
610
+ assert_eq!(c.reqs.load(Ordering::Relaxed), 0);
611
+ }
612
+ }
crates/osu_fetcher/src/ratelimit.rs ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //! Per-target rate limiting on top of `governor`.
2
+ //!
3
+ //! The osu! API and every mirror gets its own `RateLimited` instance so that
4
+ //! the global concurrency cap (`Semaphore` in `download::run`) bounds in-flight
5
+ //! requests, while these per-target governors enforce *throughput* against
6
+ //! each upstream independently.
7
+ //!
8
+ //! Limits are configured per minute and **evenly paced** — at most one
9
+ //! token outstanding at any moment, refilled at `rpm / 60` per second.
10
+ //! `governor`'s `Quota::per_minute(rpm)` defaults to a burst size equal to
11
+ //! `rpm`, which would let a `--concurrency 1024` worker pool drain a whole
12
+ //! minute's quota in a single instant the moment a fresh limiter wakes up.
13
+ //! That respects the rate over a 1-minute window but feels like a TCP
14
+ //! swarm to the mirror operator and is exactly what high-concurrency
15
+ //! callers complain about. We override the burst to 1 so concurrency does
16
+ //! not change the rate the upstream sees.
17
+ //!
18
+ //! The `acquire` helper just waits until the limiter says ready. Callers that
19
+ //! want to time out the wait should `tokio::select!` against their own
20
+ //! deadline.
21
+
22
+ use std::num::NonZeroU32;
23
+ use std::sync::Arc;
24
+
25
+ use governor::{
26
+ clock::DefaultClock,
27
+ state::{InMemoryState, NotKeyed},
28
+ Quota, RateLimiter,
29
+ };
30
+
31
+ type DirectRateLimiter = RateLimiter<NotKeyed, InMemoryState, DefaultClock>;
32
+
33
+ /// Named, cloneable, per-target rate limiter.
34
+ ///
35
+ /// `name` is purely cosmetic — it shows up in `tracing` events when the
36
+ /// limiter blocks a request. Cloning is cheap (Arc bump).
37
+ #[derive(Clone)]
38
+ pub struct RateLimited {
39
+ name: Arc<str>,
40
+ limiter: Arc<DirectRateLimiter>,
41
+ rpm: u32,
42
+ }
43
+
44
+ impl RateLimited {
45
+ /// Build a limiter that allows `rpm` requests per minute, paced
46
+ /// evenly: tokens refill every `60s / rpm`, and at most one is
47
+ /// available at any instant (burst = 1). Concurrency above the rate
48
+ /// just queues — the upstream still sees the documented throughput.
49
+ /// `rpm` is clamped to at least 1 so callers can pass user-supplied
50
+ /// values without an unwrap.
51
+ pub fn per_minute(name: impl Into<Arc<str>>, rpm: u32) -> Self {
52
+ let rpm_nz = NonZeroU32::new(rpm.max(1)).expect("clamped above 0");
53
+ let burst = NonZeroU32::new(1).expect("1 is non-zero");
54
+ let quota = Quota::per_minute(rpm_nz).allow_burst(burst);
55
+ Self {
56
+ name: name.into(),
57
+ limiter: Arc::new(RateLimiter::direct(quota)),
58
+ rpm: rpm_nz.get(),
59
+ }
60
+ }
61
+
62
+ pub fn name(&self) -> &str {
63
+ &self.name
64
+ }
65
+
66
+ pub fn rpm(&self) -> u32 {
67
+ self.rpm
68
+ }
69
+
70
+ /// Block until the limiter has a token available, then return.
71
+ pub async fn acquire(&self) {
72
+ // governor returns immediately when capacity exists; otherwise it
73
+ // sleeps until the next refill. Either way, no early-return needed.
74
+ self.limiter.until_ready().await;
75
+ }
76
+ }
77
+
78
+ #[cfg(test)]
79
+ mod tests {
80
+ use super::*;
81
+ use std::time::Instant;
82
+
83
+ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
84
+ async fn rate_limited_paces_back_to_back_requests() {
85
+ // 60 rpm = period 1s, burst = 1. First acquire passes instantly,
86
+ // the second must wait roughly the period.
87
+ let rl = RateLimited::per_minute("test", 60);
88
+ rl.acquire().await;
89
+ let t0 = Instant::now();
90
+ rl.acquire().await;
91
+ let waited = t0.elapsed();
92
+ assert!(
93
+ waited >= std::time::Duration::from_millis(700),
94
+ "expected to wait ~1s between back-to-back acquires; only waited {:?}",
95
+ waited
96
+ );
97
+ }
98
+
99
+ #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
100
+ async fn rate_limited_does_not_let_concurrency_swamp_upstream() {
101
+ // The bug we're guarding against: with burst=rpm, 25 concurrent
102
+ // acquires would all complete in milliseconds. With burst=1 the
103
+ // upstream sees them at the configured pace regardless of how
104
+ // many futures are queued.
105
+ //
106
+ // 1200 rpm = period 50ms. 25 acquires → first immediate, remaining
107
+ // 24 paced 50ms apart → expect ~24 * 50ms = ~1.2s of wallclock,
108
+ // well above what an unconstrained burst would produce.
109
+ let rl = RateLimited::per_minute("swamp", 1200);
110
+ let t0 = Instant::now();
111
+ let mut handles = Vec::with_capacity(25);
112
+ for _ in 0..25 {
113
+ let rl = rl.clone();
114
+ handles.push(tokio::spawn(async move { rl.acquire().await }));
115
+ }
116
+ for h in handles {
117
+ h.await.unwrap();
118
+ }
119
+ let elapsed = t0.elapsed();
120
+ assert!(
121
+ elapsed >= std::time::Duration::from_millis(1000),
122
+ "25 acquires at 1200 rpm with burst=1 should take ~1.2s; took {:?}",
123
+ elapsed
124
+ );
125
+ }
126
+
127
+ #[test]
128
+ fn rpm_zero_clamps_to_one() {
129
+ let rl = RateLimited::per_minute("zero", 0);
130
+ assert_eq!(rl.rpm(), 1);
131
+ }
132
+ }
crates/osu_fetcher/src/runlock.rs ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //! Single-writer file lock for the `download` command.
2
+ //!
3
+ //! Two concurrent `osu_fetcher download` processes are catastrophic for our
4
+ //! state machine: process B's startup-time `requeue_in_progress()` would
5
+ //! flip process A's live in-flight claims back to `pending`, then B would
6
+ //! re-claim them. Two workers trying to download the same set hit a
7
+ //! `MoveFileExW`-replace collision on Windows and one of them spuriously
8
+ //! marks the row failed.
9
+ //!
10
+ //! The defense: take an OS-level exclusive file lock at the start of a
11
+ //! download run and hold it for the duration. The lock is released
12
+ //! automatically by the kernel when the process exits — graceful exit, panic,
13
+ //! SIGKILL, or power-off — so there's no PID-aliveness logic to maintain
14
+ //! and no stale lockfiles to clean up. We use `std::fs::File::try_lock`
15
+ //! (stable since Rust 1.89), which is `LockFileEx(LOCKFILE_EXCLUSIVE_LOCK
16
+ //! | LOCKFILE_FAIL_IMMEDIATELY)` on Windows and `flock(LOCK_EX|LOCK_NB)` on
17
+ //! Unix.
18
+
19
+ use std::fs::{File, OpenOptions};
20
+ use std::path::{Path, PathBuf};
21
+
22
+ use anyhow::{anyhow, Context, Result};
23
+
24
+ /// RAII guard for the lock. Drop releases the lock; `path()` exposes the
25
+ /// path the lock file was created at for diagnostic logging.
26
+ #[derive(Debug)]
27
+ pub struct DownloadLock {
28
+ file: File,
29
+ path: PathBuf,
30
+ }
31
+
32
+ impl DownloadLock {
33
+ /// Acquire the lock or return an error explaining why it's already held.
34
+ /// `path` is the lockfile location — typically next to the state DB.
35
+ pub fn acquire(path: &Path) -> Result<Self> {
36
+ let file = OpenOptions::new()
37
+ .create(true)
38
+ .read(true)
39
+ .write(true)
40
+ .truncate(false)
41
+ .open(path)
42
+ .with_context(|| format!("opening lockfile {}", path.display()))?;
43
+ if let Err(e) = file.try_lock() {
44
+ return Err(anyhow!(
45
+ "another osu_fetcher download appears to be running ({}); \
46
+ lockfile path is {}. The file may remain after clean or \
47
+ killed exits; that is harmless because the OS lock is what \
48
+ matters. Check for a live osu_fetcher process before retrying.",
49
+ e,
50
+ path.display()
51
+ ));
52
+ }
53
+ // We deliberately don't stamp PID/timestamp into the file body —
54
+ // on Windows `LockFileEx` locks the byte range, so a third-party
55
+ // reader can't actually read the contents anyway. To find the
56
+ // holder, use `lsof <path>` (Unix) or Process Explorer (Windows).
57
+ Ok(Self {
58
+ file,
59
+ path: path.to_path_buf(),
60
+ })
61
+ }
62
+
63
+ pub fn path(&self) -> &Path {
64
+ &self.path
65
+ }
66
+ }
67
+
68
+ impl Drop for DownloadLock {
69
+ fn drop(&mut self) {
70
+ // OS releases the lock on file close (which Drop on `File` does)
71
+ // anyway. Calling unlock() explicitly here just makes the release
72
+ // happen before the process keeps running — useful if a long-lived
73
+ // process wants to release between phases.
74
+ let _ = self.file.unlock();
75
+ // Don't delete the lockfile: a different concurrent acquire may
76
+ // have raced in between our unlock and the would-be delete.
77
+ // Leaving the file is harmless — std re-locks on next acquire.
78
+ }
79
+ }
80
+
81
+ #[cfg(test)]
82
+ mod tests {
83
+ use super::*;
84
+ use tempfile::TempDir;
85
+
86
+ #[test]
87
+ fn acquire_then_drop_releases() {
88
+ let dir = TempDir::new().unwrap();
89
+ let path = dir.path().join(".lock");
90
+ {
91
+ let _g = DownloadLock::acquire(&path).expect("first lock");
92
+ }
93
+ // Should be re-acquirable after drop.
94
+ let _g2 = DownloadLock::acquire(&path).expect("second lock after drop");
95
+ }
96
+
97
+ #[test]
98
+ fn concurrent_acquire_fails() {
99
+ let dir = TempDir::new().unwrap();
100
+ let path = dir.path().join(".lock");
101
+ let g1 = DownloadLock::acquire(&path).expect("first lock");
102
+ let err = DownloadLock::acquire(&path).expect_err("second concurrent should fail");
103
+ assert!(
104
+ err.to_string().contains("running"),
105
+ "unexpected error: {err}"
106
+ );
107
+ drop(g1);
108
+ // Now re-acquirable.
109
+ let _g3 = DownloadLock::acquire(&path).expect("third lock after first dropped");
110
+ }
111
+
112
+ #[test]
113
+ fn lockfile_persists_on_disk_until_drop() {
114
+ let dir = TempDir::new().unwrap();
115
+ let path = dir.path().join(".lock");
116
+ let g = DownloadLock::acquire(&path).unwrap();
117
+ assert!(path.exists());
118
+ // After drop, the file remains (we don't delete to avoid a
119
+ // race with a concurrent acquire); verify only that the lock
120
+ // is released, not the path.
121
+ drop(g);
122
+ let _g2 = DownloadLock::acquire(&path).expect("re-acquire after drop");
123
+ assert!(path.exists());
124
+ }
125
+ }
crates/osu_fetcher/src/scan.rs ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //! `scan` subcommand — record `.osz` files already on disk.
2
+ //!
3
+ //! Walks the `archives-dir` once and records every `<u64>.osz` whose filename
4
+ //! parses as a beatmapset id. Sets in the directory but with non-numeric
5
+ //! filenames are skipped (they could exist for ad-hoc reasons; we don't
6
+ //! presume to interpret them).
7
+ //!
8
+ //! Pass `verify = true` to additionally open each archive and reject corrupt
9
+ //! ones — corrupt archives are left in `pending` so a `download` run will
10
+ //! re-fetch them. Without `verify`, scan is fast: a single `read_dir` pass.
11
+
12
+ use std::path::{Path, PathBuf};
13
+ use std::sync::Arc;
14
+
15
+ use anyhow::{Context, Result};
16
+ use tokio::fs;
17
+ use tracing::{debug, info, warn};
18
+
19
+ use crate::progress::CounterSpinner;
20
+ use crate::state::StateDb;
21
+ use crate::verify::verify_path;
22
+
23
+ #[derive(Clone, Copy, Debug, Default)]
24
+ pub struct ScanStats {
25
+ pub seen: u64,
26
+ pub recorded: u64,
27
+ pub bad_name: u64,
28
+ pub bad_archive: u64,
29
+ }
30
+
31
+ /// Walk `archives_dir`, recording every `<set_id>.osz` into the state DB.
32
+ ///
33
+ /// `progress`, when supplied, gets a fresh `set_message` after every file so
34
+ /// the user has a live counter; pass `None` from tests to keep the call
35
+ /// silent.
36
+ pub async fn scan_archives(
37
+ state: Arc<StateDb>,
38
+ archives_dir: &Path,
39
+ verify: bool,
40
+ progress: Option<&CounterSpinner>,
41
+ ) -> Result<ScanStats> {
42
+ if !archives_dir.exists() {
43
+ anyhow::bail!(
44
+ "archives directory does not exist: {}",
45
+ archives_dir.display()
46
+ );
47
+ }
48
+ let mut stats = ScanStats::default();
49
+ let mut entries = fs::read_dir(archives_dir)
50
+ .await
51
+ .with_context(|| format!("reading {}", archives_dir.display()))?;
52
+ while let Some(entry) = entries.next_entry().await.context("walking archives dir")? {
53
+ let path = entry.path();
54
+ if !path.is_file() {
55
+ continue;
56
+ }
57
+ let Some(set_id) = parse_set_id_from_filename(&path) else {
58
+ stats.bad_name += 1;
59
+ continue;
60
+ };
61
+ stats.seen += 1;
62
+
63
+ let meta = fs::metadata(&path)
64
+ .await
65
+ .with_context(|| format!("stat {}", path.display()))?;
66
+ let bytes = meta.len();
67
+
68
+ if verify {
69
+ // Run sync zip open inside spawn_blocking — the verify path is
70
+ // CPU-bound and small (we only walk entries, not decompress).
71
+ let p = path.clone();
72
+ match tokio::task::spawn_blocking(move || verify_path(&p))
73
+ .await
74
+ .context("verify worker join")?
75
+ {
76
+ Ok(_) => (),
77
+ Err(e) => {
78
+ warn!(set_id, err = %e, "scan: invalid archive, leaving pending");
79
+ stats.bad_archive += 1;
80
+ continue;
81
+ }
82
+ }
83
+ }
84
+
85
+ state.record_present(set_id, &path.to_string_lossy(), bytes)?;
86
+ stats.recorded += 1;
87
+ if let Some(p) = progress {
88
+ p.set_message(format!(
89
+ "seen {} · recorded {} · bad name {} · bad archive {}",
90
+ stats.seen, stats.recorded, stats.bad_name, stats.bad_archive
91
+ ));
92
+ }
93
+ if stats.recorded % 1000 == 0 {
94
+ debug!(recorded = stats.recorded, "scan progress");
95
+ }
96
+ }
97
+ info!(
98
+ seen = stats.seen,
99
+ recorded = stats.recorded,
100
+ bad_name = stats.bad_name,
101
+ bad_archive = stats.bad_archive,
102
+ "scan complete"
103
+ );
104
+ Ok(stats)
105
+ }
106
+
107
+ /// Pull a `set_id` out of `<id>.osz` (case-insensitive on extension).
108
+ ///
109
+ /// Returns `None` for any filename whose stem isn't a positive integer that
110
+ /// fits in `u64`. We intentionally accept *only* numeric filenames so the
111
+ /// scan is conservative: ad-hoc renamed archives stay invisible to the state
112
+ /// DB rather than being misattributed to the wrong set.
113
+ pub fn parse_set_id_from_filename(path: &Path) -> Option<u64> {
114
+ let stem = path.file_stem()?.to_str()?;
115
+ let ext = path
116
+ .extension()
117
+ .and_then(|e| e.to_str())
118
+ .unwrap_or("")
119
+ .to_ascii_lowercase();
120
+ if ext != "osz" {
121
+ return None;
122
+ }
123
+ stem.parse::<u64>().ok().filter(|n| *n > 0)
124
+ }
125
+
126
+ /// Convenience wrapper used by the scan smoke test: scan the directory, not
127
+ /// touching the DB. Returns the parsed set_ids.
128
+ #[allow(dead_code)]
129
+ pub async fn list_set_ids(archives_dir: &Path) -> Result<Vec<u64>> {
130
+ if !archives_dir.exists() {
131
+ return Ok(Vec::new());
132
+ }
133
+ let mut ids = Vec::new();
134
+ let mut entries = fs::read_dir(archives_dir).await?;
135
+ while let Some(entry) = entries.next_entry().await? {
136
+ let path: PathBuf = entry.path();
137
+ if let Some(id) = parse_set_id_from_filename(&path) {
138
+ ids.push(id);
139
+ }
140
+ }
141
+ ids.sort_unstable();
142
+ Ok(ids)
143
+ }
144
+
145
+ #[cfg(test)]
146
+ mod tests {
147
+ use super::*;
148
+ use std::path::PathBuf;
149
+
150
+ #[test]
151
+ fn parse_set_id_accepts_numeric_osz() {
152
+ assert_eq!(
153
+ parse_set_id_from_filename(&PathBuf::from("/p/123456.osz")),
154
+ Some(123456)
155
+ );
156
+ }
157
+
158
+ #[test]
159
+ fn parse_set_id_handles_uppercase_extension() {
160
+ assert_eq!(
161
+ parse_set_id_from_filename(&PathBuf::from("/p/789.OSZ")),
162
+ Some(789)
163
+ );
164
+ }
165
+
166
+ #[test]
167
+ fn parse_set_id_rejects_non_osz_extension() {
168
+ assert_eq!(
169
+ parse_set_id_from_filename(&PathBuf::from("/p/123.zip")),
170
+ None
171
+ );
172
+ }
173
+
174
+ #[test]
175
+ fn parse_set_id_rejects_non_numeric_stem() {
176
+ assert_eq!(
177
+ parse_set_id_from_filename(&PathBuf::from("/p/songname.osz")),
178
+ None
179
+ );
180
+ assert_eq!(
181
+ parse_set_id_from_filename(&PathBuf::from("/p/123-edit.osz")),
182
+ None
183
+ );
184
+ }
185
+
186
+ #[test]
187
+ fn parse_set_id_rejects_zero() {
188
+ assert_eq!(parse_set_id_from_filename(&PathBuf::from("/p/0.osz")), None);
189
+ }
190
+ }
crates/osu_fetcher/src/state.rs ADDED
@@ -0,0 +1,1223 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //! SQLite-backed persistent state for `osu_fetcher`.
2
+ //!
3
+ //! Schema is created on first open via [`StateDb::open`] and version-stamped
4
+ //! into the `meta` table so future migrations have a hook. WAL mode is enabled
5
+ //! for crash safety and concurrent reads while a worker writes. Foreign keys
6
+ //! are enabled so deleting a `sets` row also drops its `mirror_attempts`.
7
+ //!
8
+ //! Tables:
9
+ //!
10
+ //! * `sets` — one row per beatmapset of interest. The "wanted" half is filled
11
+ //! by `enumerate` (from the official API); the "acquisition" half is filled
12
+ //! by `scan` (we found `<id>.osz` on disk) and `download` (we just fetched
13
+ //! it). The columns are deliberately nullable so partial info from either
14
+ //! side is preserved.
15
+ //!
16
+ //! * `mirror_attempts` — append-only audit log. One row per HTTP attempt
17
+ //! regardless of outcome. Used to compute mirror success rates and as raw
18
+ //! forensics for stuck downloads.
19
+ //!
20
+ //! * `meta` — small key/value bag for the schema version and per-status
21
+ //! enumerate cursor checkpoints.
22
+ //!
23
+ //! All public methods take `&self` and serialize through the inner mutex, so
24
+ //! the same `StateDb` can be shared across worker tasks (`Arc<StateDb>`).
25
+ //! Calls are short and serialized blocking operations on the connection — for
26
+ //! our scale (~37k rows + ~tens of thousands of attempts), this is well
27
+ //! within rusqlite's comfort zone.
28
+
29
+ use std::path::Path;
30
+ use std::sync::Mutex;
31
+ use std::time::{SystemTime, UNIX_EPOCH};
32
+
33
+ use anyhow::{Context, Result};
34
+ use rusqlite::{params, Connection, OptionalExtension, Transaction};
35
+
36
+ use crate::discover::{DiscoveryAggregate, DiscoveryEntry};
37
+ use crate::RankedStatus;
38
+
39
+ pub const SCHEMA_VERSION: i64 = 2;
40
+
41
+ /// Lifecycle states for a beatmapset row.
42
+ ///
43
+ /// `pending` rows are eligible for download workers. `in_progress` is held
44
+ /// only while a worker is actively fetching; on startup, any leftover
45
+ /// `in_progress` is reset to `pending` so a crashed worker doesn't strand its
46
+ /// claim. Terminal states (`success`, `failed`, `missing`) require explicit
47
+ /// user action (e.g. `retry`) to re-enter the queue.
48
+ #[derive(Clone, Copy, Debug, Eq, PartialEq)]
49
+ pub enum DownloadStatus {
50
+ Pending,
51
+ InProgress,
52
+ Success,
53
+ Failed,
54
+ Missing,
55
+ }
56
+
57
+ impl DownloadStatus {
58
+ pub fn as_str(self) -> &'static str {
59
+ match self {
60
+ DownloadStatus::Pending => "pending",
61
+ DownloadStatus::InProgress => "in_progress",
62
+ DownloadStatus::Success => "success",
63
+ DownloadStatus::Failed => "failed",
64
+ DownloadStatus::Missing => "missing",
65
+ }
66
+ }
67
+
68
+ pub fn parse(s: &str) -> Option<Self> {
69
+ Some(match s {
70
+ "pending" => DownloadStatus::Pending,
71
+ "in_progress" => DownloadStatus::InProgress,
72
+ "success" => DownloadStatus::Success,
73
+ "failed" => DownloadStatus::Failed,
74
+ "missing" => DownloadStatus::Missing,
75
+ _ => return None,
76
+ })
77
+ }
78
+ }
79
+
80
+ /// Snapshot of the queue used by `status`.
81
+ #[derive(Clone, Debug, Default)]
82
+ pub struct StatusCounts {
83
+ pub wanted: u64,
84
+ pub pending: u64,
85
+ pub in_progress: u64,
86
+ pub success: u64,
87
+ pub failed: u64,
88
+ pub missing: u64,
89
+ }
90
+
91
+ /// One outcome of a single HTTP attempt against a mirror.
92
+ #[derive(Clone, Copy, Debug, Eq, PartialEq)]
93
+ pub enum AttemptOutcome {
94
+ Success,
95
+ NotFound,
96
+ HttpError,
97
+ RateLimited,
98
+ Network,
99
+ InvalidArchive,
100
+ /// Per-attempt deadline elapsed before the mirror returned a response.
101
+ Timeout,
102
+ }
103
+
104
+ impl AttemptOutcome {
105
+ pub fn as_str(self) -> &'static str {
106
+ match self {
107
+ AttemptOutcome::Success => "success",
108
+ AttemptOutcome::NotFound => "not_found",
109
+ AttemptOutcome::HttpError => "http_error",
110
+ AttemptOutcome::RateLimited => "rate_limited",
111
+ AttemptOutcome::Network => "network",
112
+ AttemptOutcome::InvalidArchive => "invalid_archive",
113
+ AttemptOutcome::Timeout => "timeout",
114
+ }
115
+ }
116
+ }
117
+
118
+ /// Wanted-set facts harvested from the osu! API's beatmapset search.
119
+ pub struct WantedRow<'a> {
120
+ pub set_id: u64,
121
+ pub ranked_status: RankedStatus,
122
+ pub artist: Option<&'a str>,
123
+ pub title: Option<&'a str>,
124
+ pub creator: Option<&'a str>,
125
+ pub api_last_updated: Option<&'a str>,
126
+ }
127
+
128
+ /// Acquisition-side update written when a download succeeds.
129
+ pub struct DownloadSuccess<'a> {
130
+ pub set_id: u64,
131
+ pub mirror: &'a str,
132
+ pub bytes: u64,
133
+ pub sha256: &'a str,
134
+ pub flavor: &'a str,
135
+ pub saved_path: &'a str,
136
+ }
137
+
138
+ /// Acquisition-side update written when a download fails (transient).
139
+ pub struct DownloadFailure<'a> {
140
+ pub set_id: u64,
141
+ pub mirror: &'a str,
142
+ pub error: &'a str,
143
+ }
144
+
145
+ pub struct StateDb {
146
+ inner: Mutex<Connection>,
147
+ }
148
+
149
+ impl StateDb {
150
+ /// Open or create the state database at `path`. The schema is applied
151
+ /// idempotently — opening an existing DB is a no-op once `schema_version`
152
+ /// matches `SCHEMA_VERSION`.
153
+ pub fn open(path: impl AsRef<Path>) -> Result<Self> {
154
+ let conn = Connection::open(path.as_ref())
155
+ .with_context(|| format!("opening state DB at {:?}", path.as_ref()))?;
156
+ Self::configure_and_migrate(&conn)?;
157
+ Ok(Self {
158
+ inner: Mutex::new(conn),
159
+ })
160
+ }
161
+
162
+ /// Build an in-memory state DB. Useful for tests.
163
+ pub fn open_memory() -> Result<Self> {
164
+ let conn = Connection::open_in_memory()?;
165
+ Self::configure_and_migrate(&conn)?;
166
+ Ok(Self {
167
+ inner: Mutex::new(conn),
168
+ })
169
+ }
170
+
171
+ fn configure_and_migrate(conn: &Connection) -> Result<()> {
172
+ // WAL gives us the resilience profile we want for crash recovery.
173
+ conn.pragma_update(None, "journal_mode", "WAL")?;
174
+ conn.pragma_update(None, "synchronous", "NORMAL")?;
175
+ conn.pragma_update(None, "foreign_keys", "ON")?;
176
+
177
+ conn.execute_batch(SCHEMA_SQL)?;
178
+
179
+ // Stamp + future-proof the schema version.
180
+ let now = unix_now();
181
+ conn.execute(
182
+ "INSERT INTO meta(key, value, updated_at) VALUES('schema_version', ?, ?)
183
+ ON CONFLICT(key) DO UPDATE SET value=excluded.value, updated_at=excluded.updated_at",
184
+ params![SCHEMA_VERSION.to_string(), now],
185
+ )?;
186
+ Ok(())
187
+ }
188
+
189
+ /// Reset stale `in_progress` rows from a prior run back to `pending`.
190
+ /// Run at startup before dispatching workers.
191
+ pub fn requeue_in_progress(&self) -> Result<u64> {
192
+ let conn = self.lock();
193
+ let n = conn.execute(
194
+ "UPDATE sets SET download_status = 'pending'
195
+ WHERE download_status = 'in_progress'",
196
+ [],
197
+ )?;
198
+ Ok(n as u64)
199
+ }
200
+
201
+ /// Insert or refresh a `wanted` row.
202
+ ///
203
+ /// Existing acquisition columns are preserved unless the API reports a
204
+ /// strictly newer `last_updated` than the row currently records. In that
205
+ /// case a terminal acquisition row is moved back to `pending` so the
206
+ /// updater downloads the new `.osz` revision instead of treating the old
207
+ /// compact dataset entry as current.
208
+ pub fn upsert_wanted(&self, row: &WantedRow<'_>) -> Result<()> {
209
+ let conn = self.lock();
210
+ let now = unix_now();
211
+ conn.execute(
212
+ "INSERT INTO sets(set_id, wanted, ranked_status, artist, title, creator,
213
+ api_last_updated, discovered_at, download_status)
214
+ VALUES(?, 1, ?, ?, ?, ?, ?, ?, 'pending')
215
+ ON CONFLICT(set_id) DO UPDATE SET
216
+ wanted = 1,
217
+ ranked_status = excluded.ranked_status,
218
+ artist = COALESCE(excluded.artist, sets.artist),
219
+ title = COALESCE(excluded.title, sets.title),
220
+ creator = COALESCE(excluded.creator, sets.creator),
221
+ api_last_updated = CASE
222
+ WHEN excluded.api_last_updated IS NOT NULL
223
+ AND (
224
+ sets.api_last_updated IS NULL
225
+ OR excluded.api_last_updated > sets.api_last_updated
226
+ )
227
+ THEN excluded.api_last_updated
228
+ ELSE sets.api_last_updated
229
+ END,
230
+ discovered_at = COALESCE(sets.discovered_at, excluded.discovered_at),
231
+ download_status = CASE
232
+ WHEN excluded.api_last_updated IS NOT NULL
233
+ AND sets.api_last_updated IS NOT NULL
234
+ AND excluded.api_last_updated > sets.api_last_updated
235
+ AND sets.download_status IN ('success', 'failed', 'missing')
236
+ THEN 'pending'
237
+ ELSE sets.download_status
238
+ END,
239
+ last_error = CASE
240
+ WHEN excluded.api_last_updated IS NOT NULL
241
+ AND sets.api_last_updated IS NOT NULL
242
+ AND excluded.api_last_updated > sets.api_last_updated
243
+ AND sets.download_status IN ('success', 'failed', 'missing')
244
+ THEN NULL
245
+ ELSE sets.last_error
246
+ END,
247
+ bytes = CASE
248
+ WHEN excluded.api_last_updated IS NOT NULL
249
+ AND sets.api_last_updated IS NOT NULL
250
+ AND excluded.api_last_updated > sets.api_last_updated
251
+ AND sets.download_status IN ('success', 'failed', 'missing')
252
+ THEN NULL
253
+ ELSE sets.bytes
254
+ END,
255
+ sha256 = CASE
256
+ WHEN excluded.api_last_updated IS NOT NULL
257
+ AND sets.api_last_updated IS NOT NULL
258
+ AND excluded.api_last_updated > sets.api_last_updated
259
+ AND sets.download_status IN ('success', 'failed', 'missing')
260
+ THEN NULL
261
+ ELSE sets.sha256
262
+ END,
263
+ flavor = CASE
264
+ WHEN excluded.api_last_updated IS NOT NULL
265
+ AND sets.api_last_updated IS NOT NULL
266
+ AND excluded.api_last_updated > sets.api_last_updated
267
+ AND sets.download_status IN ('success', 'failed', 'missing')
268
+ THEN NULL
269
+ ELSE sets.flavor
270
+ END,
271
+ saved_path = CASE
272
+ WHEN excluded.api_last_updated IS NOT NULL
273
+ AND sets.api_last_updated IS NOT NULL
274
+ AND excluded.api_last_updated > sets.api_last_updated
275
+ AND sets.download_status IN ('success', 'failed', 'missing')
276
+ THEN NULL
277
+ ELSE sets.saved_path
278
+ END,
279
+ completed_at = CASE
280
+ WHEN excluded.api_last_updated IS NOT NULL
281
+ AND sets.api_last_updated IS NOT NULL
282
+ AND excluded.api_last_updated > sets.api_last_updated
283
+ AND sets.download_status IN ('success', 'failed', 'missing')
284
+ THEN NULL
285
+ ELSE sets.completed_at
286
+ END",
287
+ params![
288
+ row.set_id as i64,
289
+ row.ranked_status.as_api_str(),
290
+ row.artist,
291
+ row.title,
292
+ row.creator,
293
+ row.api_last_updated,
294
+ now,
295
+ ],
296
+ )?;
297
+ Ok(())
298
+ }
299
+
300
+ /// Mark `set_id` as already on disk (e.g. from a `scan` pass). Sets the
301
+ /// download_status to `success` and records the path. Does not require
302
+ /// the row to already exist — scan can find archives the API didn't list.
303
+ pub fn record_present(&self, set_id: u64, saved_path: &str, bytes: u64) -> Result<()> {
304
+ let conn = self.lock();
305
+ let now = unix_now();
306
+ conn.execute(
307
+ "INSERT INTO sets(set_id, wanted, download_status, saved_path, bytes,
308
+ completed_at, discovered_at)
309
+ VALUES(?, 0, 'success', ?, ?, ?, ?)
310
+ ON CONFLICT(set_id) DO UPDATE SET
311
+ download_status = 'success',
312
+ saved_path = excluded.saved_path,
313
+ bytes = excluded.bytes,
314
+ completed_at = excluded.completed_at,
315
+ discovered_at = COALESCE(sets.discovered_at, excluded.discovered_at)",
316
+ params![set_id as i64, saved_path, bytes as i64, now, now],
317
+ )?;
318
+ Ok(())
319
+ }
320
+
321
+ /// Atomically claim the next pending set for a worker. Returns `None` if
322
+ /// the queue is empty.
323
+ ///
324
+ /// We pick the lowest set_id first so workers progress through the
325
+ /// catalog in a predictable order. The `RETURNING` clause keeps the claim
326
+ /// in one round-trip.
327
+ pub fn claim_next_pending(&self) -> Result<Option<u64>> {
328
+ let conn = self.lock();
329
+ let now = unix_now();
330
+ let id: Option<i64> = conn
331
+ .query_row(
332
+ "UPDATE sets
333
+ SET download_status = 'in_progress',
334
+ last_attempt_at = ?
335
+ WHERE set_id = (
336
+ SELECT set_id FROM sets
337
+ WHERE download_status = 'pending' AND wanted = 1
338
+ ORDER BY set_id
339
+ LIMIT 1
340
+ )
341
+ RETURNING set_id",
342
+ params![now],
343
+ |r| r.get::<_, i64>(0),
344
+ )
345
+ .optional()?;
346
+ Ok(id.map(|n| n as u64))
347
+ }
348
+
349
+ /// Mark a previously-claimed `set_id` back as pending. Used on graceful
350
+ /// shutdown to release the worker's claim.
351
+ pub fn release_claim(&self, set_id: u64) -> Result<()> {
352
+ let conn = self.lock();
353
+ conn.execute(
354
+ "UPDATE sets SET download_status = 'pending'
355
+ WHERE set_id = ? AND download_status = 'in_progress'",
356
+ params![set_id as i64],
357
+ )?;
358
+ Ok(())
359
+ }
360
+
361
+ pub fn record_attempt(
362
+ &self,
363
+ set_id: u64,
364
+ mirror: &str,
365
+ outcome: AttemptOutcome,
366
+ http_status: Option<u16>,
367
+ bytes: Option<u64>,
368
+ duration_ms: Option<u64>,
369
+ error: Option<&str>,
370
+ ) -> Result<()> {
371
+ let conn = self.lock();
372
+ let now = unix_now();
373
+ conn.execute(
374
+ "INSERT INTO mirror_attempts(set_id, mirror, attempted_at, duration_ms,
375
+ http_status, bytes, outcome, error)
376
+ VALUES(?, ?, ?, ?, ?, ?, ?, ?)",
377
+ params![
378
+ set_id as i64,
379
+ mirror,
380
+ now,
381
+ duration_ms.map(|n| n as i64),
382
+ http_status.map(|n| n as i64),
383
+ bytes.map(|n| n as i64),
384
+ outcome.as_str(),
385
+ error,
386
+ ],
387
+ )?;
388
+ Ok(())
389
+ }
390
+
391
+ pub fn finish_success(&self, s: &DownloadSuccess<'_>) -> Result<()> {
392
+ let conn = self.lock();
393
+ let now = unix_now();
394
+ let mut tx_conn = conn;
395
+ let tx = tx_conn.transaction()?;
396
+ tx.execute(
397
+ "UPDATE sets SET
398
+ download_status = 'success',
399
+ last_mirror = ?,
400
+ last_attempt_at = ?,
401
+ attempts = attempts + 1,
402
+ bytes = ?,
403
+ sha256 = ?,
404
+ flavor = ?,
405
+ saved_path = ?,
406
+ completed_at = ?,
407
+ last_error = NULL
408
+ WHERE set_id = ?",
409
+ params![
410
+ s.mirror,
411
+ now,
412
+ s.bytes as i64,
413
+ s.sha256,
414
+ s.flavor,
415
+ s.saved_path,
416
+ now,
417
+ s.set_id as i64,
418
+ ],
419
+ )?;
420
+ tx.commit()?;
421
+ Ok(())
422
+ }
423
+
424
+ pub fn finish_failed(&self, f: &DownloadFailure<'_>) -> Result<()> {
425
+ self.finish_terminal(f, DownloadStatus::Failed)
426
+ }
427
+
428
+ pub fn finish_missing(&self, f: &DownloadFailure<'_>) -> Result<()> {
429
+ self.finish_terminal(f, DownloadStatus::Missing)
430
+ }
431
+
432
+ fn finish_terminal(&self, f: &DownloadFailure<'_>, st: DownloadStatus) -> Result<()> {
433
+ let conn = self.lock();
434
+ let now = unix_now();
435
+ let mut tx_conn = conn;
436
+ let tx = tx_conn.transaction()?;
437
+ tx.execute(
438
+ "UPDATE sets SET
439
+ download_status = ?,
440
+ last_mirror = ?,
441
+ last_attempt_at = ?,
442
+ attempts = attempts + 1,
443
+ last_error = ?
444
+ WHERE set_id = ?",
445
+ params![st.as_str(), f.mirror, now, f.error, f.set_id as i64],
446
+ )?;
447
+ tx.commit()?;
448
+ Ok(())
449
+ }
450
+
451
+ /// Reset terminal failed/missing rows back to pending so the next
452
+ /// `download` run will retry them. Returns the count moved.
453
+ pub fn reset_failed_to_pending(&self) -> Result<u64> {
454
+ let conn = self.lock();
455
+ let n = conn.execute(
456
+ "UPDATE sets SET download_status = 'pending', last_error = NULL
457
+ WHERE download_status IN ('failed', 'missing')",
458
+ [],
459
+ )?;
460
+ Ok(n as u64)
461
+ }
462
+
463
+ /// Mark a specific set's on-disk archive as corrupt: status → pending,
464
+ /// blob metadata cleared so the next `download` overwrites cleanly.
465
+ /// Used by `verify --fix`; idempotent.
466
+ pub fn mark_archive_corrupt(&self, set_id: u64) -> Result<()> {
467
+ let conn = self.lock();
468
+ conn.execute(
469
+ "UPDATE sets SET
470
+ download_status = 'pending',
471
+ bytes = NULL,
472
+ sha256 = NULL,
473
+ flavor = NULL,
474
+ saved_path = NULL,
475
+ last_error = 'verify: corrupt archive'
476
+ WHERE set_id = ?",
477
+ params![set_id as i64],
478
+ )?;
479
+ Ok(())
480
+ }
481
+
482
+ /// Count rows that a `download` worker can or will touch this run:
483
+ /// `pending` (eligible) + `in_progress` (currently claimed; will be
484
+ /// requeued on startup). Used to give the progress bar a real ceiling.
485
+ pub fn count_pending_wanted(&self) -> Result<u64> {
486
+ let conn = self.lock();
487
+ let n: i64 = conn.query_row(
488
+ "SELECT COUNT(*) FROM sets
489
+ WHERE wanted = 1 AND download_status IN ('pending', 'in_progress')",
490
+ [],
491
+ |r| r.get(0),
492
+ )?;
493
+ Ok(n as u64)
494
+ }
495
+
496
+ pub fn status_counts(&self) -> Result<StatusCounts> {
497
+ let conn = self.lock();
498
+ let mut counts = StatusCounts::default();
499
+
500
+ counts.wanted = conn.query_row("SELECT COUNT(*) FROM sets WHERE wanted = 1", [], |r| {
501
+ r.get::<_, i64>(0)
502
+ })? as u64;
503
+
504
+ let mut stmt =
505
+ conn.prepare("SELECT download_status, COUNT(*) FROM sets GROUP BY download_status")?;
506
+ let rows = stmt.query_map([], |r| {
507
+ let st: String = r.get(0)?;
508
+ let c: i64 = r.get(1)?;
509
+ Ok((st, c as u64))
510
+ })?;
511
+ for row in rows {
512
+ let (st, c) = row?;
513
+ match st.as_str() {
514
+ "pending" => counts.pending = c,
515
+ "in_progress" => counts.in_progress = c,
516
+ "success" => counts.success = c,
517
+ "failed" => counts.failed = c,
518
+ "missing" => counts.missing = c,
519
+ _ => (),
520
+ }
521
+ }
522
+ Ok(counts)
523
+ }
524
+
525
+ /// Persist a per-status enumerate cursor so a crashed enumerate can resume
526
+ /// from where it left off.
527
+ pub fn set_enumerate_cursor(&self, status: RankedStatus, cursor: Option<&str>) -> Result<()> {
528
+ let conn = self.lock();
529
+ let key = format!("enumerate.cursor.{}", status.as_api_str());
530
+ let now = unix_now();
531
+ match cursor {
532
+ Some(c) => {
533
+ conn.execute(
534
+ "INSERT INTO meta(key, value, updated_at) VALUES(?, ?, ?)
535
+ ON CONFLICT(key) DO UPDATE SET value=excluded.value, updated_at=excluded.updated_at",
536
+ params![key, c, now],
537
+ )?;
538
+ }
539
+ None => {
540
+ conn.execute("DELETE FROM meta WHERE key = ?", params![key])?;
541
+ }
542
+ }
543
+ Ok(())
544
+ }
545
+
546
+ pub fn get_enumerate_cursor(&self, status: RankedStatus) -> Result<Option<String>> {
547
+ let conn = self.lock();
548
+ let key = format!("enumerate.cursor.{}", status.as_api_str());
549
+ let v: Option<String> = conn
550
+ .query_row("SELECT value FROM meta WHERE key = ?", params![key], |r| {
551
+ r.get(0)
552
+ })
553
+ .optional()?;
554
+ Ok(v)
555
+ }
556
+
557
+ /// Persist the high-water mark of `last_updated` from the most recent
558
+ /// *successful* enumerate of `status`. Used by incremental enumerate to
559
+ /// stop pagination once it hits already-known entries.
560
+ pub fn set_enumerate_high_water(
561
+ &self,
562
+ status: RankedStatus,
563
+ value: Option<&str>,
564
+ ) -> Result<()> {
565
+ let conn = self.lock();
566
+ let key = format!("enumerate.high_water.{}", status.as_api_str());
567
+ let now = unix_now();
568
+ match value {
569
+ Some(v) => {
570
+ conn.execute(
571
+ "INSERT INTO meta(key, value, updated_at) VALUES(?, ?, ?)
572
+ ON CONFLICT(key) DO UPDATE SET value=excluded.value, updated_at=excluded.updated_at",
573
+ params![key, v, now],
574
+ )?;
575
+ }
576
+ None => {
577
+ conn.execute("DELETE FROM meta WHERE key = ?", params![key])?;
578
+ }
579
+ }
580
+ Ok(())
581
+ }
582
+
583
+ pub fn get_enumerate_high_water(&self, status: RankedStatus) -> Result<Option<String>> {
584
+ let conn = self.lock();
585
+ let key = format!("enumerate.high_water.{}", status.as_api_str());
586
+ let v: Option<String> = conn
587
+ .query_row("SELECT value FROM meta WHERE key = ?", params![key], |r| {
588
+ r.get(0)
589
+ })
590
+ .optional()?;
591
+ Ok(v)
592
+ }
593
+
594
+ /// Upsert one (mirror, set) report from `discover_all`. Updating the row
595
+ /// if it already exists is the right semantics — a mirror's view can
596
+ /// shift between runs (a set re-ranks, a creator gets restored), and we
597
+ /// want the freshest claim per mirror to drive the aggregator.
598
+ pub fn record_discovery(&self, mirror: &str, entry: &DiscoveryEntry) -> Result<()> {
599
+ let conn = self.lock();
600
+ let now = unix_now();
601
+ conn.execute(
602
+ "INSERT INTO mirror_discoveries(set_id, mirror, claimed_status, has_osu_std,
603
+ mirror_last_updated, last_seen_at)
604
+ VALUES(?, ?, ?, ?, ?, ?)
605
+ ON CONFLICT(set_id, mirror) DO UPDATE SET
606
+ claimed_status = excluded.claimed_status,
607
+ has_osu_std = excluded.has_osu_std,
608
+ mirror_last_updated = excluded.mirror_last_updated,
609
+ last_seen_at = excluded.last_seen_at",
610
+ params![
611
+ entry.set_id as i64,
612
+ mirror,
613
+ entry.claimed_status.as_api_str(),
614
+ if entry.has_osu_std { 1i64 } else { 0i64 },
615
+ entry.mirror_last_updated.as_deref(),
616
+ now,
617
+ ],
618
+ )?;
619
+ Ok(())
620
+ }
621
+
622
+ /// One stat line: distinct sets in `mirror_discoveries`, and how many of
623
+ /// them fall short of `min_quorum` mirrors. Used by the `discover` CLI
624
+ /// summary so the operator sees the recovery shape at a glance.
625
+ pub fn aggregate_discoveries(&self, min_quorum: u32) -> Result<DiscoveryAggregate> {
626
+ let conn = self.lock();
627
+ let distinct_sets: i64 = conn.query_row(
628
+ "SELECT COUNT(DISTINCT set_id) FROM mirror_discoveries WHERE has_osu_std = 1",
629
+ [],
630
+ |r| r.get(0),
631
+ )?;
632
+ let sub_quorum: i64 = conn.query_row(
633
+ "SELECT COUNT(*) FROM (
634
+ SELECT set_id, COUNT(DISTINCT mirror) AS m
635
+ FROM mirror_discoveries
636
+ WHERE has_osu_std = 1
637
+ GROUP BY set_id
638
+ HAVING m < ?
639
+ )",
640
+ params![min_quorum as i64],
641
+ |r| r.get(0),
642
+ )?;
643
+ Ok(DiscoveryAggregate {
644
+ distinct_sets: distinct_sets as u64,
645
+ sub_quorum: sub_quorum as u64,
646
+ })
647
+ }
648
+
649
+ /// Sets that hit the quorum threshold but aren't `wanted = 1`. These are
650
+ /// the maps the official osu! API never told us about; promote them so
651
+ /// the existing download path picks them up. The chosen `ranked_status`
652
+ /// is the one most mirrors agree on (modal); ties resolve to the
653
+ /// strictest (Ranked > Approved > Qualified > Loved is *not* a real
654
+ /// ordering — we use the first encountered claim from `MIN(...)` as a
655
+ /// stable tiebreaker).
656
+ ///
657
+ /// Returns the number of rows newly upserted with `wanted = 1`.
658
+ pub fn promote_quorum_to_wanted(&self, min_quorum: u32) -> Result<u64> {
659
+ let conn = self.lock();
660
+ let now = unix_now();
661
+ // We use a single SQL pass for atomicity. The subquery picks the
662
+ // status with the most votes per set; if multiple statuses tie,
663
+ // SQLite returns one deterministically (lowest text).
664
+ let rows = conn.execute(
665
+ "INSERT INTO sets(set_id, wanted, ranked_status, discovered_at, download_status)
666
+ SELECT
667
+ d.set_id,
668
+ 1,
669
+ (SELECT claimed_status FROM mirror_discoveries d2
670
+ WHERE d2.set_id = d.set_id AND d2.has_osu_std = 1
671
+ GROUP BY claimed_status
672
+ ORDER BY COUNT(*) DESC, claimed_status ASC
673
+ LIMIT 1),
674
+ ?,
675
+ 'pending'
676
+ FROM mirror_discoveries d
677
+ WHERE d.has_osu_std = 1
678
+ GROUP BY d.set_id
679
+ HAVING COUNT(DISTINCT d.mirror) >= ?
680
+ AND d.set_id NOT IN (SELECT set_id FROM sets WHERE wanted = 1)
681
+ ON CONFLICT(set_id) DO UPDATE SET
682
+ wanted = 1,
683
+ ranked_status = COALESCE(sets.ranked_status, excluded.ranked_status),
684
+ discovered_at = COALESCE(sets.discovered_at, excluded.discovered_at)",
685
+ params![now, min_quorum as i64],
686
+ )?;
687
+ Ok(rows as u64)
688
+ }
689
+
690
+ /// Set IDs that have been reported by exactly `min_quorum - 1` mirrors —
691
+ /// one shy of meeting the quorum. The verifier pass uses this list to
692
+ /// concentrate its budget where it can actually flip an outcome.
693
+ pub fn list_singleton_discoveries(&self, min_quorum: u32) -> Result<Vec<u64>> {
694
+ let conn = self.lock();
695
+ let target = min_quorum.saturating_sub(1).max(1) as i64;
696
+ let mut stmt = conn.prepare(
697
+ "SELECT set_id FROM mirror_discoveries
698
+ WHERE has_osu_std = 1
699
+ GROUP BY set_id
700
+ HAVING COUNT(DISTINCT mirror) = ?
701
+ ORDER BY set_id",
702
+ )?;
703
+ let rows = stmt.query_map(params![target], |r| r.get::<_, i64>(0))?;
704
+ let mut ids = Vec::new();
705
+ for row in rows {
706
+ ids.push(row? as u64);
707
+ }
708
+ Ok(ids)
709
+ }
710
+
711
+ /// All mirror reports for a single set. Used by `status --set <id>`
712
+ /// (and tests) to inspect the per-set provenance.
713
+ pub fn list_discoveries_for_set(
714
+ &self,
715
+ set_id: u64,
716
+ ) -> Result<Vec<(String, String, bool, Option<String>, i64)>> {
717
+ let conn = self.lock();
718
+ let mut stmt = conn.prepare(
719
+ "SELECT mirror, claimed_status, has_osu_std, mirror_last_updated, last_seen_at
720
+ FROM mirror_discoveries
721
+ WHERE set_id = ?
722
+ ORDER BY mirror",
723
+ )?;
724
+ let rows = stmt.query_map(params![set_id as i64], |r| {
725
+ Ok((
726
+ r.get::<_, String>(0)?,
727
+ r.get::<_, String>(1)?,
728
+ r.get::<_, i64>(2)? != 0,
729
+ r.get::<_, Option<String>>(3)?,
730
+ r.get::<_, i64>(4)?,
731
+ ))
732
+ })?;
733
+ let mut out = Vec::new();
734
+ for row in rows {
735
+ out.push(row?);
736
+ }
737
+ Ok(out)
738
+ }
739
+
740
+ fn lock(&self) -> std::sync::MutexGuard<'_, Connection> {
741
+ self.inner
742
+ .lock()
743
+ .unwrap_or_else(|poison| poison.into_inner())
744
+ }
745
+ }
746
+
747
+ const SCHEMA_SQL: &str = r#"
748
+ CREATE TABLE IF NOT EXISTS meta (
749
+ key TEXT PRIMARY KEY,
750
+ value TEXT NOT NULL,
751
+ updated_at INTEGER NOT NULL
752
+ );
753
+
754
+ CREATE TABLE IF NOT EXISTS sets (
755
+ set_id INTEGER PRIMARY KEY,
756
+ wanted INTEGER NOT NULL DEFAULT 0, -- 0 or 1
757
+ ranked_status TEXT, -- ranked|approved|loved|qualified
758
+ artist TEXT,
759
+ title TEXT,
760
+ creator TEXT,
761
+ api_last_updated TEXT,
762
+ discovered_at INTEGER,
763
+
764
+ download_status TEXT NOT NULL DEFAULT 'pending',
765
+ attempts INTEGER NOT NULL DEFAULT 0,
766
+ last_error TEXT,
767
+ last_mirror TEXT,
768
+ last_attempt_at INTEGER,
769
+ bytes INTEGER,
770
+ sha256 TEXT,
771
+ flavor TEXT,
772
+ saved_path TEXT,
773
+ completed_at INTEGER
774
+ );
775
+
776
+ CREATE INDEX IF NOT EXISTS idx_sets_status ON sets(download_status);
777
+ CREATE INDEX IF NOT EXISTS idx_sets_wanted_st ON sets(wanted, download_status);
778
+
779
+ CREATE TABLE IF NOT EXISTS mirror_attempts (
780
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
781
+ set_id INTEGER NOT NULL,
782
+ mirror TEXT NOT NULL,
783
+ attempted_at INTEGER NOT NULL,
784
+ duration_ms INTEGER,
785
+ http_status INTEGER,
786
+ bytes INTEGER,
787
+ outcome TEXT NOT NULL,
788
+ error TEXT,
789
+ FOREIGN KEY(set_id) REFERENCES sets(set_id) ON DELETE CASCADE
790
+ );
791
+
792
+ CREATE INDEX IF NOT EXISTS idx_attempts_set ON mirror_attempts(set_id);
793
+ CREATE INDEX IF NOT EXISTS idx_attempts_mirror ON mirror_attempts(mirror, outcome);
794
+
795
+ -- Schema v2: cross-mirror discovery surface. One row per (set_id, mirror)
796
+ -- claim. Aggregating by `set_id` and counting distinct `mirror` is what
797
+ -- the quorum-promotion logic in `state::promote_quorum_to_wanted` runs.
798
+ -- We deliberately don't FK to `sets`: a discovery may exist for a set the
799
+ -- official API has never seen, and we want to insert the discovery row
800
+ -- before any matching `sets` row exists.
801
+ CREATE TABLE IF NOT EXISTS mirror_discoveries (
802
+ set_id INTEGER NOT NULL,
803
+ mirror TEXT NOT NULL,
804
+ claimed_status TEXT NOT NULL, -- ranked|approved|loved|qualified
805
+ has_osu_std INTEGER NOT NULL, -- 0 or 1
806
+ mirror_last_updated TEXT, -- ISO 8601, mirror's claim
807
+ last_seen_at INTEGER NOT NULL, -- unix sec, when we recorded it
808
+ PRIMARY KEY(set_id, mirror)
809
+ );
810
+
811
+ CREATE INDEX IF NOT EXISTS idx_disc_set ON mirror_discoveries(set_id);
812
+ CREATE INDEX IF NOT EXISTS idx_disc_mirror ON mirror_discoveries(mirror);
813
+ CREATE INDEX IF NOT EXISTS idx_disc_status ON mirror_discoveries(claimed_status, has_osu_std);
814
+ "#;
815
+
816
+ fn unix_now() -> i64 {
817
+ SystemTime::now()
818
+ .duration_since(UNIX_EPOCH)
819
+ .unwrap_or_default()
820
+ .as_secs() as i64
821
+ }
822
+
823
+ // Suppress unused warning until further phases call into Transaction directly.
824
+ #[allow(dead_code)]
825
+ fn _unused_marker(_t: &Transaction<'_>) {}
826
+
827
+ #[cfg(test)]
828
+ mod tests {
829
+ use super::*;
830
+
831
+ #[test]
832
+ fn schema_applies_idempotently() {
833
+ let _ = StateDb::open_memory().expect("first open");
834
+ // The same in-memory DB can't be reopened (it's lost on drop), so
835
+ // re-apply the schema via a fresh handle and confirm no errors.
836
+ let _ = StateDb::open_memory().expect("second open");
837
+ }
838
+
839
+ #[test]
840
+ fn upsert_wanted_then_record_present_round_trips() {
841
+ let db = StateDb::open_memory().unwrap();
842
+ db.upsert_wanted(&WantedRow {
843
+ set_id: 1,
844
+ ranked_status: RankedStatus::Ranked,
845
+ artist: Some("a"),
846
+ title: Some("t"),
847
+ creator: Some("c"),
848
+ api_last_updated: Some("2026-01-01"),
849
+ })
850
+ .unwrap();
851
+ db.record_present(1, "/p/1.osz", 1234).unwrap();
852
+ let counts = db.status_counts().unwrap();
853
+ assert_eq!(counts.wanted, 1);
854
+ assert_eq!(counts.success, 1);
855
+ }
856
+
857
+ #[test]
858
+ fn newer_api_revision_requeues_terminal_acquisition() {
859
+ let db = StateDb::open_memory().unwrap();
860
+ db.upsert_wanted(&WantedRow {
861
+ set_id: 1,
862
+ ranked_status: RankedStatus::Ranked,
863
+ artist: None,
864
+ title: None,
865
+ creator: None,
866
+ api_last_updated: Some("2026-01-01T00:00:00Z"),
867
+ })
868
+ .unwrap();
869
+ db.record_present(1, "/p/1.osz", 1234).unwrap();
870
+
871
+ db.upsert_wanted(&WantedRow {
872
+ set_id: 1,
873
+ ranked_status: RankedStatus::Ranked,
874
+ artist: None,
875
+ title: None,
876
+ creator: None,
877
+ api_last_updated: Some("2026-01-02T00:00:00Z"),
878
+ })
879
+ .unwrap();
880
+
881
+ let counts = db.status_counts().unwrap();
882
+ assert_eq!(counts.pending, 1);
883
+ assert_eq!(counts.success, 0);
884
+
885
+ let conn = db.lock();
886
+ let (status, path, api_last_updated): (String, Option<String>, String) = conn
887
+ .query_row(
888
+ "SELECT download_status, saved_path, api_last_updated FROM sets WHERE set_id = 1",
889
+ [],
890
+ |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
891
+ )
892
+ .unwrap();
893
+ assert_eq!(status, "pending");
894
+ assert_eq!(path, None);
895
+ assert_eq!(api_last_updated, "2026-01-02T00:00:00Z");
896
+ }
897
+
898
+ #[test]
899
+ fn first_api_timestamp_for_seeded_success_does_not_requeue() {
900
+ let db = StateDb::open_memory().unwrap();
901
+ db.record_present(1, "compact://seed/1", 0).unwrap();
902
+
903
+ db.upsert_wanted(&WantedRow {
904
+ set_id: 1,
905
+ ranked_status: RankedStatus::Ranked,
906
+ artist: None,
907
+ title: None,
908
+ creator: None,
909
+ api_last_updated: Some("2026-01-02T00:00:00Z"),
910
+ })
911
+ .unwrap();
912
+
913
+ let counts = db.status_counts().unwrap();
914
+ assert_eq!(counts.success, 1);
915
+ assert_eq!(counts.pending, 0);
916
+ }
917
+
918
+ #[test]
919
+ fn claim_next_pending_returns_lowest_id() {
920
+ let db = StateDb::open_memory().unwrap();
921
+ for id in [3, 1, 2] {
922
+ db.upsert_wanted(&WantedRow {
923
+ set_id: id,
924
+ ranked_status: RankedStatus::Ranked,
925
+ artist: None,
926
+ title: None,
927
+ creator: None,
928
+ api_last_updated: None,
929
+ })
930
+ .unwrap();
931
+ }
932
+ assert_eq!(db.claim_next_pending().unwrap(), Some(1));
933
+ assert_eq!(db.claim_next_pending().unwrap(), Some(2));
934
+ assert_eq!(db.claim_next_pending().unwrap(), Some(3));
935
+ assert_eq!(db.claim_next_pending().unwrap(), None);
936
+ }
937
+
938
+ #[test]
939
+ fn requeue_in_progress_resets_stalled_claims() {
940
+ let db = StateDb::open_memory().unwrap();
941
+ db.upsert_wanted(&WantedRow {
942
+ set_id: 1,
943
+ ranked_status: RankedStatus::Ranked,
944
+ artist: None,
945
+ title: None,
946
+ creator: None,
947
+ api_last_updated: None,
948
+ })
949
+ .unwrap();
950
+ let _ = db.claim_next_pending().unwrap();
951
+ let n = db.requeue_in_progress().unwrap();
952
+ assert_eq!(n, 1);
953
+ assert_eq!(db.claim_next_pending().unwrap(), Some(1));
954
+ }
955
+
956
+ #[test]
957
+ fn finish_success_marks_completed_and_records_blob_meta() {
958
+ let db = StateDb::open_memory().unwrap();
959
+ db.upsert_wanted(&WantedRow {
960
+ set_id: 42,
961
+ ranked_status: RankedStatus::Loved,
962
+ artist: None,
963
+ title: None,
964
+ creator: None,
965
+ api_last_updated: None,
966
+ })
967
+ .unwrap();
968
+ let _ = db.claim_next_pending().unwrap();
969
+ db.finish_success(&DownloadSuccess {
970
+ set_id: 42,
971
+ mirror: "test",
972
+ bytes: 1024,
973
+ sha256: "abc",
974
+ flavor: "full",
975
+ saved_path: "/p/42.osz",
976
+ })
977
+ .unwrap();
978
+ let counts = db.status_counts().unwrap();
979
+ assert_eq!(counts.success, 1);
980
+ assert_eq!(counts.pending, 0);
981
+ }
982
+
983
+ #[test]
984
+ fn enumerate_high_water_persists_and_clears() {
985
+ let db = StateDb::open_memory().unwrap();
986
+ assert_eq!(
987
+ db.get_enumerate_high_water(RankedStatus::Ranked).unwrap(),
988
+ None
989
+ );
990
+ db.set_enumerate_high_water(RankedStatus::Ranked, Some("2026-04-26T12:34:56Z"))
991
+ .unwrap();
992
+ assert_eq!(
993
+ db.get_enumerate_high_water(RankedStatus::Ranked).unwrap(),
994
+ Some("2026-04-26T12:34:56Z".into())
995
+ );
996
+ // Independent across statuses.
997
+ assert_eq!(
998
+ db.get_enumerate_high_water(RankedStatus::Loved).unwrap(),
999
+ None
1000
+ );
1001
+ // Clearing.
1002
+ db.set_enumerate_high_water(RankedStatus::Ranked, None)
1003
+ .unwrap();
1004
+ assert_eq!(
1005
+ db.get_enumerate_high_water(RankedStatus::Ranked).unwrap(),
1006
+ None
1007
+ );
1008
+ }
1009
+
1010
+ #[test]
1011
+ fn record_discovery_is_idempotent_per_mirror() {
1012
+ // Recording the same (set, mirror) twice updates the row instead of
1013
+ // double-counting it. This matters: an operator running `discover`
1014
+ // back-to-back must not inflate the quorum count.
1015
+ let db = StateDb::open_memory().unwrap();
1016
+ let entry = DiscoveryEntry {
1017
+ set_id: 100,
1018
+ claimed_status: RankedStatus::Loved,
1019
+ has_osu_std: true,
1020
+ mirror_last_updated: Some("2026-01-01T00:00:00Z".into()),
1021
+ };
1022
+ db.record_discovery("nerinyan", &entry).unwrap();
1023
+ db.record_discovery("nerinyan", &entry).unwrap();
1024
+ let rows = db.list_discoveries_for_set(100).unwrap();
1025
+ assert_eq!(rows.len(), 1);
1026
+ }
1027
+
1028
+ #[test]
1029
+ fn aggregate_counts_distinct_sets_and_sub_quorum() {
1030
+ let db = StateDb::open_memory().unwrap();
1031
+ // set 1: 2 mirrors → meets quorum (>= 2)
1032
+ // set 2: 1 mirror only → sub-quorum
1033
+ // set 3: 3 mirrors → meets quorum
1034
+ for (set_id, mirror) in [
1035
+ (1, "nerinyan"),
1036
+ (1, "osudirect"),
1037
+ (2, "nerinyan"),
1038
+ (3, "nerinyan"),
1039
+ (3, "osudirect"),
1040
+ (3, "sayobot"),
1041
+ ] {
1042
+ db.record_discovery(
1043
+ mirror,
1044
+ &DiscoveryEntry {
1045
+ set_id,
1046
+ claimed_status: RankedStatus::Ranked,
1047
+ has_osu_std: true,
1048
+ mirror_last_updated: None,
1049
+ },
1050
+ )
1051
+ .unwrap();
1052
+ }
1053
+ let agg = db.aggregate_discoveries(2).unwrap();
1054
+ assert_eq!(agg.distinct_sets, 3);
1055
+ assert_eq!(agg.sub_quorum, 1);
1056
+ }
1057
+
1058
+ #[test]
1059
+ fn promote_quorum_to_wanted_only_promotes_above_threshold() {
1060
+ let db = StateDb::open_memory().unwrap();
1061
+ // set 100 has 2 mirrors agreeing → should promote
1062
+ // set 200 has 1 mirror only → should NOT promote
1063
+ for (set_id, mirror) in [(100, "nerinyan"), (100, "osudirect"), (200, "nerinyan")] {
1064
+ db.record_discovery(
1065
+ mirror,
1066
+ &DiscoveryEntry {
1067
+ set_id,
1068
+ claimed_status: RankedStatus::Loved,
1069
+ has_osu_std: true,
1070
+ mirror_last_updated: None,
1071
+ },
1072
+ )
1073
+ .unwrap();
1074
+ }
1075
+ let promoted = db.promote_quorum_to_wanted(2).unwrap();
1076
+ assert_eq!(promoted, 1);
1077
+ let counts = db.status_counts().unwrap();
1078
+ assert_eq!(counts.wanted, 1);
1079
+ assert_eq!(counts.pending, 1);
1080
+ }
1081
+
1082
+ #[test]
1083
+ fn promote_picks_modal_status_when_mirrors_disagree() {
1084
+ // Two mirrors say "loved", one says "ranked". The promoted row
1085
+ // should carry the modal claim (loved). This is the only place
1086
+ // we synthesize a status from disagreement, so a regression here
1087
+ // would silently misclassify recovered sets.
1088
+ let db = StateDb::open_memory().unwrap();
1089
+ for (mirror, status) in [
1090
+ ("nerinyan", RankedStatus::Loved),
1091
+ ("osudirect", RankedStatus::Loved),
1092
+ ("sayobot", RankedStatus::Ranked),
1093
+ ] {
1094
+ db.record_discovery(
1095
+ mirror,
1096
+ &DiscoveryEntry {
1097
+ set_id: 7,
1098
+ claimed_status: status,
1099
+ has_osu_std: true,
1100
+ mirror_last_updated: None,
1101
+ },
1102
+ )
1103
+ .unwrap();
1104
+ }
1105
+ db.promote_quorum_to_wanted(2).unwrap();
1106
+
1107
+ // Read back the upserted row.
1108
+ let conn = db.lock();
1109
+ let st: String = conn
1110
+ .query_row("SELECT ranked_status FROM sets WHERE set_id = 7", [], |r| {
1111
+ r.get(0)
1112
+ })
1113
+ .unwrap();
1114
+ assert_eq!(st, "loved");
1115
+ }
1116
+
1117
+ #[test]
1118
+ fn promote_does_not_overwrite_existing_wanted_row() {
1119
+ // If the official enumerate already classified set X as ranked,
1120
+ // the discovery aggregator must NOT downgrade the row to whatever
1121
+ // a few mirrors happen to claim. Quorum promotion is for *new*
1122
+ // sets; existing ones are managed by enumerate.
1123
+ let db = StateDb::open_memory().unwrap();
1124
+ db.upsert_wanted(&WantedRow {
1125
+ set_id: 42,
1126
+ ranked_status: RankedStatus::Ranked,
1127
+ artist: None,
1128
+ title: None,
1129
+ creator: None,
1130
+ api_last_updated: None,
1131
+ })
1132
+ .unwrap();
1133
+ for mirror in ["nerinyan", "osudirect"] {
1134
+ db.record_discovery(
1135
+ mirror,
1136
+ &DiscoveryEntry {
1137
+ set_id: 42,
1138
+ claimed_status: RankedStatus::Loved,
1139
+ has_osu_std: true,
1140
+ mirror_last_updated: None,
1141
+ },
1142
+ )
1143
+ .unwrap();
1144
+ }
1145
+ let promoted = db.promote_quorum_to_wanted(2).unwrap();
1146
+ assert_eq!(promoted, 0, "existing wanted row must not be re-promoted");
1147
+
1148
+ let conn = db.lock();
1149
+ let st: String = conn
1150
+ .query_row(
1151
+ "SELECT ranked_status FROM sets WHERE set_id = 42",
1152
+ [],
1153
+ |r| r.get(0),
1154
+ )
1155
+ .unwrap();
1156
+ assert_eq!(st, "ranked", "existing status must not be overwritten");
1157
+ }
1158
+
1159
+ #[test]
1160
+ fn singleton_list_returns_sets_one_short_of_quorum() {
1161
+ // For min_quorum=2, sets seen on exactly 1 mirror are the candidates
1162
+ // a verifier pass should target — the verifier's confirmation can
1163
+ // push them to quorum.
1164
+ let db = StateDb::open_memory().unwrap();
1165
+ for (set_id, mirror) in [
1166
+ (1, "nerinyan"), // singleton
1167
+ (2, "nerinyan"),
1168
+ (2, "osudirect"), // already at quorum
1169
+ (3, "sayobot"), // singleton
1170
+ ] {
1171
+ db.record_discovery(
1172
+ mirror,
1173
+ &DiscoveryEntry {
1174
+ set_id,
1175
+ claimed_status: RankedStatus::Ranked,
1176
+ has_osu_std: true,
1177
+ mirror_last_updated: None,
1178
+ },
1179
+ )
1180
+ .unwrap();
1181
+ }
1182
+ let singletons = db.list_singleton_discoveries(2).unwrap();
1183
+ assert_eq!(singletons, vec![1, 3]);
1184
+ }
1185
+
1186
+ #[test]
1187
+ fn discoveries_with_taiko_only_are_excluded_from_aggregation() {
1188
+ // The aggregator gates on `has_osu_std = 1`; a taiko-only set
1189
+ // recorded with has_osu_std=0 must not contribute to quorum even
1190
+ // if multiple mirrors claim it.
1191
+ let db = StateDb::open_memory().unwrap();
1192
+ for mirror in ["nerinyan", "osudirect", "sayobot"] {
1193
+ db.record_discovery(
1194
+ mirror,
1195
+ &DiscoveryEntry {
1196
+ set_id: 99,
1197
+ claimed_status: RankedStatus::Ranked,
1198
+ has_osu_std: false,
1199
+ mirror_last_updated: None,
1200
+ },
1201
+ )
1202
+ .unwrap();
1203
+ }
1204
+ let agg = db.aggregate_discoveries(2).unwrap();
1205
+ assert_eq!(agg.distinct_sets, 0);
1206
+ let promoted = db.promote_quorum_to_wanted(2).unwrap();
1207
+ assert_eq!(promoted, 0);
1208
+ }
1209
+
1210
+ #[test]
1211
+ fn enumerate_cursor_persists() {
1212
+ let db = StateDb::open_memory().unwrap();
1213
+ assert_eq!(db.get_enumerate_cursor(RankedStatus::Ranked).unwrap(), None);
1214
+ db.set_enumerate_cursor(RankedStatus::Ranked, Some("abc123"))
1215
+ .unwrap();
1216
+ assert_eq!(
1217
+ db.get_enumerate_cursor(RankedStatus::Ranked).unwrap(),
1218
+ Some("abc123".into())
1219
+ );
1220
+ db.set_enumerate_cursor(RankedStatus::Ranked, None).unwrap();
1221
+ assert_eq!(db.get_enumerate_cursor(RankedStatus::Ranked).unwrap(), None);
1222
+ }
1223
+ }
crates/osu_fetcher/src/verify.rs ADDED
@@ -0,0 +1,706 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //! `.osz` archive validation.
2
+ //!
3
+ //! Two levels:
4
+ //!
5
+ //! * [`verify_bytes`] — cheap, in-memory check that the buffer is a real ZIP
6
+ //! and contains at least one `.osu` file. Used right after a download to
7
+ //! reject HTML error pages and truncated downloads before we write to disk.
8
+ //!
9
+ //! * [`verify_path`] — opens an on-disk archive and runs the same check.
10
+ //! Used by the `verify` subcommand to audit existing `archives/` content.
11
+ //!
12
+ //! * [`run_adaptive`] — bulk verification of every `.osz` in a directory with
13
+ //! an adaptive worker pool that hill-climbs concurrency to find the I/O
14
+ //! sweet spot for the underlying disk (especially HDDs, where too many
15
+ //! concurrent reads cause seek thrash and one-or-two workers may already be
16
+ //! saturating).
17
+
18
+ use std::collections::VecDeque;
19
+ use std::fs::File;
20
+ use std::io::{Cursor, Read, Seek};
21
+ use std::path::{Path, PathBuf};
22
+ use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
23
+ use std::sync::{Arc, Mutex as StdMutex};
24
+ use std::time::{Duration, Instant};
25
+
26
+ use anyhow::{Context, Result};
27
+ use indicatif::{HumanBytes, HumanDuration, ProgressBar, ProgressDrawTarget, ProgressStyle};
28
+ use thiserror::Error;
29
+ use tokio::sync::Semaphore;
30
+ use tokio_util::sync::CancellationToken;
31
+ use zip::ZipArchive;
32
+
33
+ use crate::scan::parse_set_id_from_filename;
34
+ use crate::state::StateDb;
35
+
36
+ #[derive(Debug, Error)]
37
+ pub enum VerifyError {
38
+ #[error("archive bytes are empty")]
39
+ Empty,
40
+
41
+ #[error("archive does not start with a ZIP magic")]
42
+ NotZip,
43
+
44
+ #[error("ZIP open failed: {0}")]
45
+ OpenFailed(String),
46
+
47
+ #[error("ZIP contains no `.osu` files (likely a wrong-payload mirror response)")]
48
+ NoOsuFiles,
49
+
50
+ #[error("ZIP read I/O error: {0}")]
51
+ Io(#[from] std::io::Error),
52
+ }
53
+
54
+ /// Quick magic-byte check + archive open + entry walk for at least one `.osu`.
55
+ ///
56
+ /// Doesn't try to fully decode every entry; we just need confidence that the
57
+ /// payload is a real beatmapset archive before committing it to disk.
58
+ pub fn verify_bytes(bytes: &[u8]) -> Result<ArchiveInfo, VerifyError> {
59
+ if bytes.is_empty() {
60
+ return Err(VerifyError::Empty);
61
+ }
62
+ if !is_zip_magic(bytes) {
63
+ return Err(VerifyError::NotZip);
64
+ }
65
+ let mut archive =
66
+ ZipArchive::new(Cursor::new(bytes)).map_err(|e| VerifyError::OpenFailed(e.to_string()))?;
67
+ walk(&mut archive)
68
+ }
69
+
70
+ pub fn verify_path(path: &Path) -> Result<ArchiveInfo, VerifyError> {
71
+ let f = File::open(path)
72
+ .context("opening archive")
73
+ .map_err(|e| VerifyError::OpenFailed(format!("{}: {e}", path.display())))?;
74
+ let mut archive = ZipArchive::new(f).map_err(|e| VerifyError::OpenFailed(e.to_string()))?;
75
+ walk(&mut archive)
76
+ }
77
+
78
+ #[derive(Clone, Debug, Default)]
79
+ pub struct ArchiveInfo {
80
+ pub osu_count: u32,
81
+ pub osb_count: u32,
82
+ pub other_count: u32,
83
+ }
84
+
85
+ fn walk<R: Read + Seek>(archive: &mut ZipArchive<R>) -> Result<ArchiveInfo, VerifyError> {
86
+ let mut info = ArchiveInfo::default();
87
+ for i in 0..archive.len() {
88
+ // We deliberately swallow individual-entry decode errors so a single
89
+ // malformed filename doesn't fail the whole archive. The test for
90
+ // "is this a valid beatmapset" is "does it have `.osu` files".
91
+ let entry = match archive.by_index(i) {
92
+ Ok(e) => e,
93
+ Err(_) => continue,
94
+ };
95
+ let name = entry.name().to_ascii_lowercase();
96
+ if name.ends_with(".osu") {
97
+ info.osu_count += 1;
98
+ } else if name.ends_with(".osb") {
99
+ info.osb_count += 1;
100
+ } else {
101
+ info.other_count += 1;
102
+ }
103
+ }
104
+ if info.osu_count == 0 {
105
+ return Err(VerifyError::NoOsuFiles);
106
+ }
107
+ Ok(info)
108
+ }
109
+
110
+ fn is_zip_magic(bytes: &[u8]) -> bool {
111
+ if bytes.len() < 4 {
112
+ return false;
113
+ }
114
+ let head = &bytes[..4];
115
+ head == b"PK\x03\x04" || head == b"PK\x05\x06" || head == b"PK\x07\x08"
116
+ }
117
+
118
+ // =====================================================================
119
+ // Adaptive bulk verification
120
+ // =====================================================================
121
+
122
+ /// CLI-facing knobs for [`run_adaptive`].
123
+ #[derive(Clone, Debug)]
124
+ pub struct AdaptiveVerifyOptions {
125
+ /// Lower bound on concurrent workers. The controller will not shrink
126
+ /// below this. Must be ≥ 1.
127
+ pub min_workers: usize,
128
+ /// Upper bound on concurrent workers. The controller will not grow
129
+ /// above this. Must be ≥ `min_workers`.
130
+ pub max_workers: usize,
131
+ /// If `Some(N)`, disables auto-tuning and pins the pool at `N`.
132
+ pub fixed_workers: Option<usize>,
133
+ /// Reset bad rows back to `pending` so the next `download` overwrites them.
134
+ pub fix: bool,
135
+ /// Render the live progress bar. Disable for CI / log redirection.
136
+ pub progress: bool,
137
+ }
138
+
139
+ impl Default for AdaptiveVerifyOptions {
140
+ fn default() -> Self {
141
+ Self {
142
+ min_workers: 1,
143
+ max_workers: 8,
144
+ fixed_workers: None,
145
+ fix: false,
146
+ progress: true,
147
+ }
148
+ }
149
+ }
150
+
151
+ #[derive(Clone, Debug, Default)]
152
+ pub struct VerifyStats {
153
+ pub total: u64,
154
+ pub bad: u64,
155
+ /// Files left unverified because the user hit Ctrl-C.
156
+ pub aborted_remaining: u64,
157
+ }
158
+
159
+ #[derive(Default)]
160
+ struct VerifyCounters {
161
+ verified: AtomicU64,
162
+ bad: AtomicU64,
163
+ bytes: AtomicU64,
164
+ }
165
+
166
+ /// Walk `archives_dir`, verify every `<id>.osz`, and report bad ones.
167
+ ///
168
+ /// Spawns `max_workers` worker tasks; the live concurrency is gated by a
169
+ /// shared [`Semaphore`] whose available permits represent the current target
170
+ /// level. A controller task hill-climbs that level once every 5 s, raising
171
+ /// concurrency while throughput improves and reverting otherwise. After a
172
+ /// rejected grow the controller alternates to a shrink probe so the pool can
173
+ /// also discover lower local optima — useful on cold HDDs where 1–2 workers
174
+ /// often beats 4+.
175
+ ///
176
+ /// On Ctrl-C the [`CancellationToken`] fires; workers finish their current
177
+ /// file and exit, the partial summary is printed, and the function returns
178
+ /// normally with `aborted_remaining > 0`.
179
+ pub async fn run_adaptive(
180
+ state: Arc<StateDb>,
181
+ archives_dir: &Path,
182
+ opts: AdaptiveVerifyOptions,
183
+ ) -> Result<VerifyStats> {
184
+ if opts.min_workers == 0 {
185
+ anyhow::bail!("min_workers must be ≥ 1");
186
+ }
187
+ if opts.max_workers < opts.min_workers {
188
+ anyhow::bail!(
189
+ "max_workers ({}) must be ≥ min_workers ({})",
190
+ opts.max_workers,
191
+ opts.min_workers
192
+ );
193
+ }
194
+
195
+ if !archives_dir.exists() {
196
+ anyhow::bail!(
197
+ "archives directory does not exist: {}",
198
+ archives_dir.display()
199
+ );
200
+ }
201
+
202
+ // 1. Collect work.
203
+ let files = collect_archives(archives_dir).await?;
204
+ let total_files = files.len() as u64;
205
+ let queue = Arc::new(StdMutex::new(VecDeque::from(files)));
206
+ let counters = Arc::new(VerifyCounters::default());
207
+
208
+ // 2. Concurrency gate. We start by holding (max - start_level) permits in
209
+ // a "throttle pool" so only `start_level` workers can run at once;
210
+ // grow == add a permit, shrink == acquire-and-forget a permit.
211
+ let start_level = opts
212
+ .fixed_workers
213
+ .unwrap_or(2)
214
+ .clamp(opts.min_workers, opts.max_workers);
215
+ let sem = Arc::new(Semaphore::new(opts.max_workers));
216
+ for _ in 0..(opts.max_workers - start_level) {
217
+ // We hold these permits forever (forget) until the controller
218
+ // chooses to release them by adding equivalent permits back.
219
+ sem.clone()
220
+ .acquire_owned()
221
+ .await
222
+ .expect("semaphore not closed")
223
+ .forget();
224
+ }
225
+ let level = Arc::new(AtomicUsize::new(start_level));
226
+
227
+ // 3. Progress.
228
+ let pb = build_progress_bar(total_files, opts.progress);
229
+
230
+ let cancel = CancellationToken::new();
231
+
232
+ // 4. Workers.
233
+ let mut handles = Vec::with_capacity(opts.max_workers);
234
+ for _ in 0..opts.max_workers {
235
+ let s = sem.clone();
236
+ let q = queue.clone();
237
+ let c = counters.clone();
238
+ let st = state.clone();
239
+ let cx = cancel.clone();
240
+ let pbx = pb.clone();
241
+ let fix = opts.fix;
242
+ handles.push(tokio::spawn(async move {
243
+ worker_loop(s, q, c, st, cx, pbx, fix).await;
244
+ }));
245
+ }
246
+
247
+ // 5. Controller (only when adaptive).
248
+ let controller_handle = if opts.fixed_workers.is_none() && opts.min_workers != opts.max_workers
249
+ {
250
+ let s = sem.clone();
251
+ let l = level.clone();
252
+ let c = counters.clone();
253
+ let cx = cancel.clone();
254
+ Some(tokio::spawn(controller_loop(
255
+ s,
256
+ l,
257
+ c,
258
+ cx,
259
+ opts.min_workers,
260
+ opts.max_workers,
261
+ )))
262
+ } else {
263
+ None
264
+ };
265
+
266
+ // 6. Ctrl-C → cancel.
267
+ let cancel_for_signal = cancel.clone();
268
+ let signal_handle = tokio::spawn(async move {
269
+ let _ = tokio::signal::ctrl_c().await;
270
+ cancel_for_signal.cancel();
271
+ });
272
+
273
+ // 7. Progress refresh.
274
+ let refresh_handle = {
275
+ let pbx = pb.clone();
276
+ let lvl = level.clone();
277
+ let cnt = counters.clone();
278
+ let cx = cancel.clone();
279
+ let started = Instant::now();
280
+ tokio::spawn(async move {
281
+ let mut interval = tokio::time::interval(Duration::from_millis(250));
282
+ interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
283
+ let active = Arc::new(AtomicBool::new(true));
284
+ while active.load(Ordering::Relaxed) {
285
+ tokio::select! {
286
+ _ = cx.cancelled() => { active.store(false, Ordering::Relaxed); }
287
+ _ = interval.tick() => {}
288
+ }
289
+ if let Some(pb) = &pbx {
290
+ refresh_progress(pb, &cnt, lvl.load(Ordering::Relaxed), started, total_files);
291
+ }
292
+ }
293
+ })
294
+ };
295
+
296
+ // 8. Wait for workers (they exit when queue empties or cancel fires).
297
+ for h in handles {
298
+ let _ = h.await;
299
+ }
300
+
301
+ // Workers done; tear down the helpers.
302
+ cancel.cancel();
303
+ if let Some(h) = controller_handle {
304
+ let _ = h.await;
305
+ }
306
+ let _ = refresh_handle.await;
307
+ signal_handle.abort();
308
+ let _ = signal_handle.await;
309
+
310
+ let verified = counters.verified.load(Ordering::Relaxed);
311
+ let bad = counters.bad.load(Ordering::Relaxed);
312
+ let remaining = total_files.saturating_sub(verified);
313
+
314
+ if let Some(pb) = &pb {
315
+ pb.finish_and_clear();
316
+ }
317
+
318
+ if remaining > 0 {
319
+ println!("verified {verified} archives ({bad} bad); {remaining} skipped due to abort");
320
+ } else {
321
+ println!("verified {verified} archives ({bad} bad)");
322
+ }
323
+
324
+ Ok(VerifyStats {
325
+ total: verified,
326
+ bad,
327
+ aborted_remaining: remaining,
328
+ })
329
+ }
330
+
331
+ async fn collect_archives(archives_dir: &Path) -> Result<Vec<(u64, PathBuf)>> {
332
+ let mut out = Vec::new();
333
+ let mut entries = tokio::fs::read_dir(archives_dir)
334
+ .await
335
+ .context("read archives_dir")?;
336
+ while let Some(entry) = entries.next_entry().await? {
337
+ let path = entry.path();
338
+ if let Some(set_id) = parse_set_id_from_filename(&path) {
339
+ out.push((set_id, path));
340
+ }
341
+ }
342
+ Ok(out)
343
+ }
344
+
345
+ async fn worker_loop(
346
+ sem: Arc<Semaphore>,
347
+ queue: Arc<StdMutex<VecDeque<(u64, PathBuf)>>>,
348
+ counters: Arc<VerifyCounters>,
349
+ state: Arc<StateDb>,
350
+ cancel: CancellationToken,
351
+ pb: Option<ProgressBar>,
352
+ fix: bool,
353
+ ) {
354
+ loop {
355
+ let permit = tokio::select! {
356
+ _ = cancel.cancelled() => return,
357
+ p = sem.clone().acquire_owned() => match p {
358
+ Ok(p) => p,
359
+ Err(_) => return,
360
+ },
361
+ };
362
+
363
+ let next = {
364
+ let mut q = queue.lock().unwrap_or_else(|e| e.into_inner());
365
+ q.pop_front()
366
+ };
367
+ let Some((set_id, path)) = next else {
368
+ // Queue drained; dropping the permit lets siblings exit too.
369
+ return;
370
+ };
371
+
372
+ if cancel.is_cancelled() {
373
+ return;
374
+ }
375
+
376
+ let p_for_thread = path.clone();
377
+ let result = tokio::task::spawn_blocking(move || verify_path(&p_for_thread)).await;
378
+
379
+ let bytes = std::fs::metadata(&path).map(|m| m.len()).unwrap_or(0);
380
+ match result {
381
+ Ok(Ok(_info)) => {
382
+ counters.verified.fetch_add(1, Ordering::Relaxed);
383
+ counters.bytes.fetch_add(bytes, Ordering::Relaxed);
384
+ }
385
+ Ok(Err(e)) => {
386
+ counters.verified.fetch_add(1, Ordering::Relaxed);
387
+ counters.bad.fetch_add(1, Ordering::Relaxed);
388
+ let line = format!("BAD {set_id} {}: {e}", path.display());
389
+ if let Some(pb) = &pb {
390
+ pb.println(line);
391
+ } else {
392
+ println!("{line}");
393
+ }
394
+ if fix {
395
+ if let Err(e) = state.mark_archive_corrupt(set_id) {
396
+ let warn = format!("warn: mark_archive_corrupt({set_id}) failed: {e}");
397
+ if let Some(pb) = &pb {
398
+ pb.println(warn);
399
+ } else {
400
+ eprintln!("{warn}");
401
+ }
402
+ }
403
+ }
404
+ }
405
+ Err(join_err) => {
406
+ let line = format!(
407
+ "WARN verify task panicked for {set_id} at {}: {join_err}",
408
+ path.display()
409
+ );
410
+ if let Some(pb) = &pb {
411
+ pb.println(line);
412
+ } else {
413
+ eprintln!("{line}");
414
+ }
415
+ }
416
+ }
417
+
418
+ if let Some(pb) = &pb {
419
+ pb.inc(1);
420
+ }
421
+
422
+ drop(permit);
423
+ }
424
+ }
425
+
426
+ // ----- adaptive controller -----
427
+
428
+ /// What happened in the last completed probe. Drives the *next* probe
429
+ /// direction so we don't endlessly retry an already-rejected change.
430
+ #[derive(Clone, Copy, Debug, Eq, PartialEq)]
431
+ enum LastOutcome {
432
+ /// First probe of the run.
433
+ Initial,
434
+ GrowKept,
435
+ GrowReverted,
436
+ ShrinkKept,
437
+ ShrinkReverted,
438
+ }
439
+
440
+ #[derive(Clone, Copy, Debug)]
441
+ enum ControllerState {
442
+ /// Sit idle until `until`; build a baseline rate measurement, then probe.
443
+ Cooldown { until: Instant, last: LastOutcome },
444
+ /// Just applied +1 worker; decide on next tick whether it helped.
445
+ ProbingGrow { baseline_rate: f64 },
446
+ /// Just applied -1 worker; decide on next tick whether it cost throughput.
447
+ ProbingShrink { baseline_rate: f64 },
448
+ }
449
+
450
+ const TICK: Duration = Duration::from_secs(5);
451
+ const COOLDOWN: Duration = Duration::from_secs(60);
452
+ const GROW_THRESHOLD: f64 = 1.05; // need ≥ +5% rate to keep an extra worker
453
+ const SHRINK_THRESHOLD: f64 = 0.98; // accept shrink that loses ≤ 2% throughput
454
+
455
+ async fn controller_loop(
456
+ sem: Arc<Semaphore>,
457
+ level: Arc<AtomicUsize>,
458
+ counters: Arc<VerifyCounters>,
459
+ cancel: CancellationToken,
460
+ min: usize,
461
+ max: usize,
462
+ ) {
463
+ let mut interval = tokio::time::interval(TICK);
464
+ interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
465
+ // Skip the immediate first tick so we have a real measurement window.
466
+ interval.tick().await;
467
+
468
+ let mut last_count = counters.verified.load(Ordering::Relaxed);
469
+ let mut last_at = Instant::now();
470
+ let mut state = ControllerState::Cooldown {
471
+ until: Instant::now() + Duration::from_secs(15),
472
+ last: LastOutcome::Initial,
473
+ };
474
+
475
+ loop {
476
+ tokio::select! {
477
+ _ = cancel.cancelled() => return,
478
+ _ = interval.tick() => {}
479
+ }
480
+
481
+ let now = Instant::now();
482
+ let count = counters.verified.load(Ordering::Relaxed);
483
+ let elapsed = now.saturating_duration_since(last_at).as_secs_f64();
484
+ let rate = if elapsed > 0.0 {
485
+ (count - last_count) as f64 / elapsed
486
+ } else {
487
+ 0.0
488
+ };
489
+ last_count = count;
490
+ last_at = now;
491
+
492
+ match state {
493
+ ControllerState::Cooldown { until, last } if now < until => {
494
+ // Building rate baseline; nothing to do.
495
+ let _ = (until, last);
496
+ }
497
+ ControllerState::Cooldown { last, .. } => {
498
+ // Cooldown elapsed → choose the next probe direction.
499
+ let cur = level.load(Ordering::Relaxed);
500
+ let prefer_shrink =
501
+ matches!(last, LastOutcome::GrowReverted | LastOutcome::ShrinkKept);
502
+ if prefer_shrink && cur > min {
503
+ apply_shrink(&sem);
504
+ level.store(cur - 1, Ordering::Relaxed);
505
+ state = ControllerState::ProbingShrink {
506
+ baseline_rate: rate,
507
+ };
508
+ } else if cur < max {
509
+ sem.add_permits(1);
510
+ level.store(cur + 1, Ordering::Relaxed);
511
+ state = ControllerState::ProbingGrow {
512
+ baseline_rate: rate,
513
+ };
514
+ } else if cur > min {
515
+ apply_shrink(&sem);
516
+ level.store(cur - 1, Ordering::Relaxed);
517
+ state = ControllerState::ProbingShrink {
518
+ baseline_rate: rate,
519
+ };
520
+ } else {
521
+ // Pinned (min == max); just keep cooling down.
522
+ state = ControllerState::Cooldown {
523
+ until: now + COOLDOWN,
524
+ last,
525
+ };
526
+ }
527
+ }
528
+ ControllerState::ProbingGrow { baseline_rate } => {
529
+ if rate > baseline_rate * GROW_THRESHOLD {
530
+ // Win: try to keep climbing on the next tick.
531
+ let cur = level.load(Ordering::Relaxed);
532
+ if cur < max {
533
+ sem.add_permits(1);
534
+ level.store(cur + 1, Ordering::Relaxed);
535
+ state = ControllerState::ProbingGrow {
536
+ baseline_rate: rate,
537
+ };
538
+ } else {
539
+ state = ControllerState::Cooldown {
540
+ until: now + COOLDOWN,
541
+ last: LastOutcome::GrowKept,
542
+ };
543
+ }
544
+ } else {
545
+ // No improvement → revert.
546
+ apply_shrink(&sem);
547
+ let cur = level.load(Ordering::Relaxed);
548
+ level.store(cur.saturating_sub(1).max(min), Ordering::Relaxed);
549
+ state = ControllerState::Cooldown {
550
+ until: now + COOLDOWN,
551
+ last: LastOutcome::GrowReverted,
552
+ };
553
+ }
554
+ }
555
+ ControllerState::ProbingShrink { baseline_rate } => {
556
+ if rate >= baseline_rate * SHRINK_THRESHOLD {
557
+ // Throughput held → keep the lower level.
558
+ let cur = level.load(Ordering::Relaxed);
559
+ if cur > min {
560
+ apply_shrink(&sem);
561
+ level.store(cur - 1, Ordering::Relaxed);
562
+ state = ControllerState::ProbingShrink {
563
+ baseline_rate: rate,
564
+ };
565
+ } else {
566
+ state = ControllerState::Cooldown {
567
+ until: now + COOLDOWN,
568
+ last: LastOutcome::ShrinkKept,
569
+ };
570
+ }
571
+ } else {
572
+ // Lost too much throughput → revert.
573
+ sem.add_permits(1);
574
+ let cur = level.load(Ordering::Relaxed);
575
+ level.store((cur + 1).min(max), Ordering::Relaxed);
576
+ state = ControllerState::Cooldown {
577
+ until: now + COOLDOWN,
578
+ last: LastOutcome::ShrinkReverted,
579
+ };
580
+ }
581
+ }
582
+ }
583
+ }
584
+ }
585
+
586
+ fn apply_shrink(sem: &Arc<Semaphore>) {
587
+ // Acquire-and-forget pulls one permit out of circulation. Spawned so the
588
+ // controller never blocks waiting for an in-use permit.
589
+ let s = sem.clone();
590
+ tokio::spawn(async move {
591
+ if let Ok(p) = s.acquire_owned().await {
592
+ p.forget();
593
+ }
594
+ });
595
+ }
596
+
597
+ // ----- progress -----
598
+
599
+ fn build_progress_bar(total: u64, enabled: bool) -> Option<ProgressBar> {
600
+ if !enabled {
601
+ return None;
602
+ }
603
+ let pb = ProgressBar::with_draw_target(Some(total), ProgressDrawTarget::stderr());
604
+ pb.set_style(
605
+ ProgressStyle::with_template(
606
+ " [{bar:40.cyan/blue}] {pos:>6}/{len:<6} {percent:>3}% · {msg}",
607
+ )
608
+ .unwrap()
609
+ .progress_chars("█▉▊▋▌▍▎▏ "),
610
+ );
611
+ pb.set_message("starting…");
612
+ Some(pb)
613
+ }
614
+
615
+ fn refresh_progress(
616
+ pb: &ProgressBar,
617
+ counters: &VerifyCounters,
618
+ workers: usize,
619
+ started: Instant,
620
+ total: u64,
621
+ ) {
622
+ let verified = counters.verified.load(Ordering::Relaxed);
623
+ let bad = counters.bad.load(Ordering::Relaxed);
624
+ let bytes = counters.bytes.load(Ordering::Relaxed);
625
+ let elapsed = started.elapsed();
626
+ let secs = elapsed.as_secs_f64().max(0.001);
627
+ let fps = verified as f64 / secs;
628
+ let bps = (bytes as f64 / secs) as u64;
629
+ let eta = if fps > 0.05 && total > verified {
630
+ let remaining_secs = ((total - verified) as f64 / fps) as u64;
631
+ format!("{}", HumanDuration(Duration::from_secs(remaining_secs)))
632
+ } else {
633
+ "—".to_string()
634
+ };
635
+ pb.set_position(verified);
636
+ pb.set_message(format!(
637
+ "{:>5.1} files/s · {}/s · workers {workers} · ETA {eta} · bad {bad}",
638
+ fps,
639
+ HumanBytes(bps),
640
+ ));
641
+ }
642
+
643
+ #[cfg(test)]
644
+ mod tests {
645
+ use super::*;
646
+ use std::io::Write;
647
+
648
+ fn make_minimal_osz() -> Vec<u8> {
649
+ let mut buf = Vec::new();
650
+ {
651
+ let mut zw = zip::ZipWriter::new(Cursor::new(&mut buf));
652
+ zw.start_file::<&str, ()>(
653
+ "Artist - Title (Mapper) [Easy].osu",
654
+ zip::write::SimpleFileOptions::default(),
655
+ )
656
+ .unwrap();
657
+ zw.write_all(b"osu file format v14\n").unwrap();
658
+ zw.finish().unwrap();
659
+ }
660
+ buf
661
+ }
662
+
663
+ #[test]
664
+ fn verify_bytes_accepts_minimal_osz() {
665
+ let bytes = make_minimal_osz();
666
+ let info = verify_bytes(&bytes).unwrap();
667
+ assert_eq!(info.osu_count, 1);
668
+ assert_eq!(info.osb_count, 0);
669
+ }
670
+
671
+ #[test]
672
+ fn verify_bytes_rejects_empty() {
673
+ assert!(matches!(verify_bytes(&[]), Err(VerifyError::Empty)));
674
+ }
675
+
676
+ #[test]
677
+ fn verify_bytes_rejects_html_error_page() {
678
+ let html = b"<!DOCTYPE html><html><body>error</body></html>";
679
+ assert!(matches!(verify_bytes(html), Err(VerifyError::NotZip)));
680
+ }
681
+
682
+ #[test]
683
+ fn verify_bytes_rejects_zip_without_osu_files() {
684
+ // Minimal ZIP containing a single non-.osu entry.
685
+ let mut buf = Vec::new();
686
+ {
687
+ let mut zw = zip::ZipWriter::new(Cursor::new(&mut buf));
688
+ zw.start_file::<&str, ()>("background.jpg", zip::write::SimpleFileOptions::default())
689
+ .unwrap();
690
+ zw.write_all(b"\xff\xd8\xff").unwrap();
691
+ zw.finish().unwrap();
692
+ }
693
+ assert!(matches!(verify_bytes(&buf), Err(VerifyError::NoOsuFiles)));
694
+ }
695
+
696
+ #[test]
697
+ fn verify_bytes_rejects_truncated_zip() {
698
+ // First 4 bytes are valid magic but the rest is garbage.
699
+ let truncated = b"PK\x03\x04garbage_truncated_archive";
700
+ let err = verify_bytes(truncated).expect_err("expected error on truncated zip");
701
+ assert!(matches!(
702
+ err,
703
+ VerifyError::OpenFailed(_) | VerifyError::NoOsuFiles
704
+ ));
705
+ }
706
+ }
crates/osu_fetcher/tests/classify_response.rs ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //! Failure-mode test: a mirror that returns 200 with garbage must NOT be
2
+ //! treated as success — `classify_response` must reject the body via deep
3
+ //! `verify_bytes` and surface `MirrorError::InvalidArchive`.
4
+ //!
5
+ //! Without this guard, the very first mirror in the pool's order can poison
6
+ //! the run: 200-OK + non-osz bytes would be written to disk and committed
7
+ //! to the state DB as `success`. Re-running download would skip the row,
8
+ //! so the bad file would persist until manually purged. This test exercises
9
+ //! the production path end-to-end via wiremock.
10
+
11
+ use std::io::Write;
12
+
13
+ use osu_fetcher::mirrors::{build_client, MirrorError};
14
+ use wiremock::matchers::{method, path};
15
+ use wiremock::{Mock, MockServer, ResponseTemplate};
16
+
17
+ fn make_minimal_osz() -> Vec<u8> {
18
+ let mut buf = Vec::new();
19
+ {
20
+ let mut zw = zip::ZipWriter::new(std::io::Cursor::new(&mut buf));
21
+ zw.start_file::<&str, ()>(
22
+ "Stub - X (Y) [N].osu",
23
+ zip::write::SimpleFileOptions::default(),
24
+ )
25
+ .unwrap();
26
+ zw.write_all(b"osu file format v14\n").unwrap();
27
+ zw.finish().unwrap();
28
+ }
29
+ buf
30
+ }
31
+
32
+ fn make_zip_without_osu_files() -> Vec<u8> {
33
+ let mut buf = Vec::new();
34
+ {
35
+ let mut zw = zip::ZipWriter::new(std::io::Cursor::new(&mut buf));
36
+ zw.start_file::<&str, ()>("bg.jpg", zip::write::SimpleFileOptions::default())
37
+ .unwrap();
38
+ zw.write_all(b"\xff\xd8\xff\xe0").unwrap();
39
+ zw.finish().unwrap();
40
+ }
41
+ buf
42
+ }
43
+
44
+ #[tokio::test]
45
+ async fn pool_rejects_200_with_html_error_page() {
46
+ // We can't fully redirect the mirror's hardcoded base URL, so instead
47
+ // we exercise the `classify_response` helper through a custom Mirror
48
+ // impl that constructs a full reqwest::Response from the wiremock URL.
49
+ let server = MockServer::start().await;
50
+ Mock::given(method("GET"))
51
+ .and(path("/d/123"))
52
+ .respond_with(
53
+ ResponseTemplate::new(200).set_body_bytes(b"<!DOCTYPE html><html>oops</html>"),
54
+ )
55
+ .mount(&server)
56
+ .await;
57
+
58
+ let client = build_client().unwrap();
59
+ let resp = client
60
+ .get(format!("{}/d/123", server.uri()))
61
+ .send()
62
+ .await
63
+ .unwrap();
64
+ let result = osu_fetcher::mirrors::classify_response("test-mirror", resp).await;
65
+ let err = result.expect_err("expected InvalidArchive");
66
+ assert!(
67
+ matches!(err, MirrorError::InvalidArchive { .. }),
68
+ "expected InvalidArchive, got {err:?}"
69
+ );
70
+ }
71
+
72
+ #[tokio::test]
73
+ async fn pool_rejects_200_with_truncated_zip() {
74
+ let server = MockServer::start().await;
75
+ // Valid PK\x03\x04 magic but truncated body — opens fail or no .osu inside.
76
+ Mock::given(method("GET"))
77
+ .and(path("/d/456"))
78
+ .respond_with(ResponseTemplate::new(200).set_body_bytes(b"PK\x03\x04truncated_bytes"))
79
+ .mount(&server)
80
+ .await;
81
+
82
+ let client = build_client().unwrap();
83
+ let resp = client
84
+ .get(format!("{}/d/456", server.uri()))
85
+ .send()
86
+ .await
87
+ .unwrap();
88
+ let err = osu_fetcher::mirrors::classify_response("test-mirror", resp)
89
+ .await
90
+ .expect_err("expected InvalidArchive");
91
+ assert!(matches!(err, MirrorError::InvalidArchive { .. }));
92
+ }
93
+
94
+ #[tokio::test]
95
+ async fn pool_rejects_200_with_zip_lacking_osu_files() {
96
+ let server = MockServer::start().await;
97
+ Mock::given(method("GET"))
98
+ .and(path("/d/789"))
99
+ .respond_with(ResponseTemplate::new(200).set_body_bytes(make_zip_without_osu_files()))
100
+ .mount(&server)
101
+ .await;
102
+
103
+ let client = build_client().unwrap();
104
+ let resp = client
105
+ .get(format!("{}/d/789", server.uri()))
106
+ .send()
107
+ .await
108
+ .unwrap();
109
+ let err = osu_fetcher::mirrors::classify_response("test-mirror", resp)
110
+ .await
111
+ .expect_err("expected InvalidArchive");
112
+ assert!(matches!(err, MirrorError::InvalidArchive { .. }));
113
+ }
114
+
115
+ #[tokio::test]
116
+ async fn pool_accepts_minimal_real_osz() {
117
+ let server = MockServer::start().await;
118
+ Mock::given(method("GET"))
119
+ .and(path("/d/100"))
120
+ .respond_with(ResponseTemplate::new(200).set_body_bytes(make_minimal_osz()))
121
+ .mount(&server)
122
+ .await;
123
+
124
+ let client = build_client().unwrap();
125
+ let resp = client
126
+ .get(format!("{}/d/100", server.uri()))
127
+ .send()
128
+ .await
129
+ .unwrap();
130
+ let bytes = osu_fetcher::mirrors::classify_response("test-mirror", resp)
131
+ .await
132
+ .expect("minimal real osz should pass");
133
+ assert!(bytes.starts_with(b"PK\x03\x04"));
134
+ }
135
+
136
+ #[tokio::test]
137
+ async fn pool_propagates_404_as_not_found() {
138
+ let server = MockServer::start().await;
139
+ Mock::given(method("GET"))
140
+ .and(path("/d/999"))
141
+ .respond_with(ResponseTemplate::new(404))
142
+ .mount(&server)
143
+ .await;
144
+
145
+ let client = build_client().unwrap();
146
+ let resp = client
147
+ .get(format!("{}/d/999", server.uri()))
148
+ .send()
149
+ .await
150
+ .unwrap();
151
+ let err = osu_fetcher::mirrors::classify_response("test-mirror", resp)
152
+ .await
153
+ .expect_err("expected NotFound");
154
+ assert!(matches!(err, MirrorError::NotFound { .. }));
155
+ }
156
+
157
+ #[tokio::test]
158
+ async fn pool_propagates_429_as_rate_limited() {
159
+ let server = MockServer::start().await;
160
+ Mock::given(method("GET"))
161
+ .and(path("/d/888"))
162
+ .respond_with(ResponseTemplate::new(429))
163
+ .mount(&server)
164
+ .await;
165
+
166
+ let client = build_client().unwrap();
167
+ let resp = client
168
+ .get(format!("{}/d/888", server.uri()))
169
+ .send()
170
+ .await
171
+ .unwrap();
172
+ let err = osu_fetcher::mirrors::classify_response("test-mirror", resp)
173
+ .await
174
+ .expect_err("expected RateLimited");
175
+ assert!(matches!(err, MirrorError::RateLimited { .. }));
176
+ }
crates/osu_fetcher/tests/discover_live.rs ADDED
@@ -0,0 +1,218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //! Live discovery integration test.
2
+ //!
3
+ //! Hits the real Nerinyan / osu.direct / Sayobot / nekoha endpoints in
4
+ //! constrained, low-volume queries to confirm that:
5
+ //!
6
+ //! 1. each mirror's parser handles the wire shape returned today,
7
+ //! 2. cross-mirror cross-verification produces a quorum on a set we know
8
+ //! is currently ranked, and
9
+ //! 3. the aggregator promotes that set to `wanted`.
10
+ //!
11
+ //! Network-dependent and lower-determinism than the in-process unit tests,
12
+ //! so every test is `#[ignore]` by default. Run explicitly with:
13
+ //!
14
+ //! `cargo test -p osu_fetcher --test discover_live -- --ignored --nocapture`
15
+ //!
16
+ //! Each test fetches at most a few pages and one or two per-set verifies —
17
+ //! tens of HTTP calls total. Within every public mirror's documented rate
18
+ //! budget; running this in a tight loop is still rude, so don't.
19
+
20
+ use std::sync::Arc;
21
+ use std::time::Duration;
22
+
23
+ use osu_fetcher::discover::{
24
+ self,
25
+ nekoha::NekohaVerify,
26
+ nerinyan::NerinyanSearch,
27
+ osudirect::{OsuDirectSearch, OsuDirectVerify},
28
+ sayobot::{SayobotSearch, SayobotVerify},
29
+ DiscoverContext, DiscoverLimiters, DiscoverOptions, MirrorSearch, MirrorVerify,
30
+ };
31
+ use osu_fetcher::ratelimit::RateLimited;
32
+ use osu_fetcher::state::StateDb;
33
+ use osu_fetcher::RankedStatus;
34
+
35
+ /// We probe set 2303912 — it was ranked at the time of the discovery
36
+ /// design (April 2026) and shows up across every mirror we cross-checked.
37
+ /// Pinning a known-ranked set keeps the assertion stable regardless of
38
+ /// which page the live API happens to return today; if upstream re-ranks
39
+ /// or removes the set, this number can be swapped without touching logic.
40
+ const PROBE_SET_ID: u64 = 2303912;
41
+
42
+ fn build_context() -> DiscoverContext {
43
+ let client = discover::build_client().expect("build http client");
44
+ DiscoverContext {
45
+ client,
46
+ // Slow rates for the test so a CI re-run can't accidentally
47
+ // hammer a mirror — 30 rpm gives us one request every 2s. The
48
+ // tests only issue a handful, so this is invisible to wallclock.
49
+ limiters: DiscoverLimiters {
50
+ nerinyan: RateLimited::per_minute("nerinyan_test", 30),
51
+ osudirect: RateLimited::per_minute("osudirect_test", 30),
52
+ sayobot: RateLimited::per_minute("sayobot_test", 30),
53
+ nekoha: RateLimited::per_minute("nekoha_test", 30),
54
+ },
55
+ }
56
+ }
57
+
58
+ #[tokio::test]
59
+ #[ignore = "live HTTP — opt in with --ignored"]
60
+ async fn nerinyan_search_returns_ranked_osu_std_sets() {
61
+ let ctx = build_context();
62
+ let m = NerinyanSearch::new(&ctx);
63
+ let page = tokio::time::timeout(
64
+ Duration::from_secs(30),
65
+ m.search_page(Some(RankedStatus::Ranked), 0, None),
66
+ )
67
+ .await
68
+ .expect("timeout")
69
+ .expect("nerinyan returned an error");
70
+ assert!(!page.entries.is_empty(), "nerinyan returned no entries");
71
+ for e in &page.entries {
72
+ assert!(e.has_osu_std);
73
+ assert_eq!(e.claimed_status, RankedStatus::Ranked);
74
+ }
75
+ // Cursor should be present on the first page (catalog is huge).
76
+ assert!(
77
+ page.next_cursor.is_some(),
78
+ "nerinyan first page should advertise more pages"
79
+ );
80
+ }
81
+
82
+ #[tokio::test]
83
+ #[ignore = "live HTTP — opt in with --ignored"]
84
+ async fn osudirect_search_returns_loved_osu_std_sets() {
85
+ let ctx = build_context();
86
+ let m = OsuDirectSearch::new(&ctx);
87
+ let page = tokio::time::timeout(
88
+ Duration::from_secs(30),
89
+ m.search_page(Some(RankedStatus::Loved), 0, None),
90
+ )
91
+ .await
92
+ .expect("timeout")
93
+ .expect("osu.direct returned an error");
94
+ assert!(!page.entries.is_empty(), "osu.direct returned no entries");
95
+ for e in &page.entries {
96
+ assert!(e.has_osu_std);
97
+ assert_eq!(e.claimed_status, RankedStatus::Loved);
98
+ }
99
+ }
100
+
101
+ #[tokio::test]
102
+ #[ignore = "live HTTP — opt in with --ignored"]
103
+ async fn sayobot_search_returns_some_recent_sets() {
104
+ // Sayobot doesn't filter by status server-side; we just confirm it
105
+ // returns *something* and that every entry has `has_osu_std == true`
106
+ // (parser invariant).
107
+ let ctx = build_context();
108
+ let m = SayobotSearch::new(&ctx);
109
+ let page = tokio::time::timeout(Duration::from_secs(30), m.search_page(None, 0, None))
110
+ .await
111
+ .expect("timeout")
112
+ .expect("sayobot returned an error");
113
+ assert!(!page.entries.is_empty(), "sayobot returned no entries");
114
+ for e in &page.entries {
115
+ assert!(e.has_osu_std);
116
+ // Sayobot's `approved` int is one of {1,2,3,4} after our parse;
117
+ // the `claimed_status` enum guarantees that.
118
+ let _ = e.claimed_status;
119
+ }
120
+ }
121
+
122
+ #[tokio::test]
123
+ #[ignore = "live HTTP — opt in with --ignored"]
124
+ async fn osudirect_verifier_confirms_known_ranked_set() {
125
+ let ctx = build_context();
126
+ let v = OsuDirectVerify::new(&ctx);
127
+ let entry = tokio::time::timeout(Duration::from_secs(30), v.verify_set(PROBE_SET_ID))
128
+ .await
129
+ .expect("timeout")
130
+ .expect("osu.direct verifier failed")
131
+ .expect("osu.direct should know set 2303912");
132
+ assert_eq!(entry.set_id, PROBE_SET_ID);
133
+ assert!(entry.has_osu_std);
134
+ }
135
+
136
+ #[tokio::test]
137
+ #[ignore = "live HTTP — opt in with --ignored"]
138
+ async fn nekoha_verifier_confirms_known_ranked_set() {
139
+ let ctx = build_context();
140
+ let v = NekohaVerify::new(&ctx);
141
+ let entry = tokio::time::timeout(Duration::from_secs(30), v.verify_set(PROBE_SET_ID))
142
+ .await
143
+ .expect("timeout")
144
+ .expect("nekoha verifier failed");
145
+ // nekoha may legitimately return None if the set is graveyarded /
146
+ // not in their target statuses; the parser drops those. We only
147
+ // assert "no panic, no transient error". If the mirror is healthy
148
+ // and the set exists with a tracked status, we get Some(...).
149
+ if let Some(e) = entry {
150
+ assert_eq!(e.set_id, PROBE_SET_ID);
151
+ assert!(e.has_osu_std);
152
+ }
153
+ }
154
+
155
+ /// End-to-end smoke: drive `discover_all` against the real mirrors with a
156
+ /// 1-page cap, confirm at least one quorum-passing set comes through, and
157
+ /// confirm the aggregator promotes it. This is the test that proves the
158
+ /// "smart system" actually does what its name claims.
159
+ #[tokio::test]
160
+ #[ignore = "live HTTP — opt in with --ignored"]
161
+ async fn discover_all_promotes_at_least_one_quorum_set() {
162
+ let ctx = build_context();
163
+ let state = Arc::new(StateDb::open_memory().expect("memory state db"));
164
+ let searches: Vec<Arc<dyn MirrorSearch>> = vec![
165
+ Arc::new(NerinyanSearch::new(&ctx)),
166
+ Arc::new(OsuDirectSearch::new(&ctx)),
167
+ Arc::new(SayobotSearch::new(&ctx)),
168
+ ];
169
+ let verifiers: Vec<Arc<dyn MirrorVerify>> = vec![
170
+ Arc::new(NekohaVerify::new(&ctx)),
171
+ Arc::new(OsuDirectVerify::new(&ctx)),
172
+ Arc::new(SayobotVerify::new(&ctx)),
173
+ ];
174
+ let opts = DiscoverOptions {
175
+ mode: 0,
176
+ // 1 page per (mirror, status) keeps the test under ~30 calls
177
+ // even with all four statuses enabled.
178
+ max_pages_per_mirror_status: Some(1),
179
+ statuses: &[RankedStatus::Ranked],
180
+ min_quorum: 2,
181
+ // Default fuse + retries so the live test exercises the full
182
+ // production path (a transient blip during the test should be
183
+ // recovered by the same retry logic the user sees).
184
+ ..DiscoverOptions::default()
185
+ };
186
+ let stats = tokio::time::timeout(
187
+ Duration::from_secs(120),
188
+ // Progress disabled: the test runner pipes stderr, and a live
189
+ // spinner mid-test would just be visual noise.
190
+ discover::discover_all(state.clone(), &searches, &verifiers, opts, false),
191
+ )
192
+ .await
193
+ .expect("discover_all timed out")
194
+ .expect("discover_all errored");
195
+
196
+ eprintln!(
197
+ "live stats: pages={} reports={} sets_seen={} promoted={} sub_quorum={}",
198
+ stats.pages,
199
+ stats.reports_recorded,
200
+ stats.sets_seen,
201
+ stats.promoted_to_wanted,
202
+ stats.sub_quorum_candidates
203
+ );
204
+ assert!(
205
+ stats.reports_recorded > 0,
206
+ "no mirror reported any sets — every search source is broken or unreachable"
207
+ );
208
+ // Quorum from 1 page each across 3 mirrors should easily exceed 0
209
+ // sets — top-of-list ranked sets are always present on multiple
210
+ // mirrors. If this fails, either a mirror is down (which the
211
+ // separate per-mirror tests would also flag) or the parser is
212
+ // dropping rows it should accept.
213
+ assert!(
214
+ stats.sets_seen >= 1,
215
+ "expected at least one cross-mirror reported set; got {}",
216
+ stats.sets_seen
217
+ );
218
+ }
crates/osu_fetcher/tests/integration.rs ADDED
@@ -0,0 +1,471 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //! End-to-end test: state DB + a stub Mirror impl + the download orchestrator.
2
+ //!
3
+ //! We exercise the real `download::run` worker pool against a custom in-memory
4
+ //! mirror (avoids a wiremock setup; the `Mirror` trait is what the pool sees,
5
+ //! and the network layer is already exercised by per-mirror unit tests).
6
+ //!
7
+ //! The goal is to cover the *orchestration* logic: requeue on startup,
8
+ //! atomic write, claim → terminal-status transitions, partial cleanup,
9
+ //! and that records make it into the state DB.
10
+
11
+ use std::io::{Cursor, Write};
12
+ use std::sync::Arc;
13
+
14
+ use async_trait::async_trait;
15
+ use bytes::Bytes;
16
+ use osu_fetcher::download::{self, DownloadOptions};
17
+ use osu_fetcher::mirrors::{Mirror, MirrorError, MirrorPool};
18
+ use osu_fetcher::state::{StateDb, WantedRow};
19
+ use osu_fetcher::{Flavor, RankedStatus};
20
+ use tempfile::TempDir;
21
+ use tokio_util::sync::CancellationToken;
22
+
23
+ fn make_minimal_osz(set_id: u64) -> Vec<u8> {
24
+ let mut buf = Vec::new();
25
+ {
26
+ let mut zw = zip::ZipWriter::new(Cursor::new(&mut buf));
27
+ zw.start_file::<&str, ()>(
28
+ &format!("Mock - Stub (Tester) [Set{set_id}].osu"),
29
+ zip::write::SimpleFileOptions::default(),
30
+ )
31
+ .unwrap();
32
+ zw.write_all(b"osu file format v14\n").unwrap();
33
+ zw.finish().unwrap();
34
+ }
35
+ buf
36
+ }
37
+
38
+ struct OkMirror {
39
+ name: &'static str,
40
+ }
41
+
42
+ #[async_trait]
43
+ impl Mirror for OkMirror {
44
+ fn name(&self) -> &str {
45
+ self.name
46
+ }
47
+ fn supports(&self, _flavor: Flavor) -> bool {
48
+ true
49
+ }
50
+ async fn download(&self, set_id: u64, _flavor: Flavor) -> Result<Bytes, MirrorError> {
51
+ Ok(Bytes::from(make_minimal_osz(set_id)))
52
+ }
53
+ }
54
+
55
+ struct AlwaysMissingMirror {
56
+ name: &'static str,
57
+ }
58
+
59
+ #[async_trait]
60
+ impl Mirror for AlwaysMissingMirror {
61
+ fn name(&self) -> &str {
62
+ self.name
63
+ }
64
+ fn supports(&self, _flavor: Flavor) -> bool {
65
+ true
66
+ }
67
+ async fn download(&self, _set_id: u64, _flavor: Flavor) -> Result<Bytes, MirrorError> {
68
+ Err(MirrorError::NotFound {
69
+ mirror: self.name.into(),
70
+ })
71
+ }
72
+ }
73
+
74
+ struct TransientHttpErrorMirror {
75
+ name: &'static str,
76
+ }
77
+
78
+ #[async_trait]
79
+ impl Mirror for TransientHttpErrorMirror {
80
+ fn name(&self) -> &str {
81
+ self.name
82
+ }
83
+ fn supports(&self, _flavor: Flavor) -> bool {
84
+ true
85
+ }
86
+ async fn download(&self, _set_id: u64, _flavor: Flavor) -> Result<Bytes, MirrorError> {
87
+ Err(MirrorError::HttpError {
88
+ mirror: self.name.into(),
89
+ status: 500,
90
+ body_snippet: "internal".into(),
91
+ })
92
+ }
93
+ }
94
+
95
+ /// Mimics a misbehaving mirror that responds 200 with bytes that are not a
96
+ /// valid `.osz` (no `.osu` files). The pool's deep verify must catch this
97
+ /// and try the next mirror — a regression here means real bad-bytes mirror
98
+ /// responses would corrupt our archive directory.
99
+ struct InvalidArchiveMirror {
100
+ name: &'static str,
101
+ }
102
+
103
+ #[async_trait]
104
+ impl Mirror for InvalidArchiveMirror {
105
+ fn name(&self) -> &str {
106
+ self.name
107
+ }
108
+ fn supports(&self, _flavor: Flavor) -> bool {
109
+ true
110
+ }
111
+ async fn download(&self, _set_id: u64, _flavor: Flavor) -> Result<Bytes, MirrorError> {
112
+ // A ZIP that opens cleanly but contains no `.osu` (just a bg image).
113
+ let mut buf = Vec::new();
114
+ {
115
+ let mut zw = zip::ZipWriter::new(std::io::Cursor::new(&mut buf));
116
+ zw.start_file::<&str, ()>("bg.jpg", zip::write::SimpleFileOptions::default())
117
+ .unwrap();
118
+ std::io::Write::write_all(&mut zw, b"\xff\xd8\xff").unwrap();
119
+ zw.finish().unwrap();
120
+ }
121
+ Err(MirrorError::InvalidArchive {
122
+ mirror: self.name.into(),
123
+ reason: "no .osu files".into(),
124
+ })
125
+ }
126
+ }
127
+
128
+ /// Mirror that "succeeds" (returns Ok) with bytes that wouldn't pass the
129
+ /// deeper `verify_bytes` check. Used to confirm that when bytes come back
130
+ /// already invalid, the pool's classify_response path catches them.
131
+ struct BadBytesMirror;
132
+
133
+ #[async_trait]
134
+ impl Mirror for BadBytesMirror {
135
+ fn name(&self) -> &str {
136
+ "bad-bytes"
137
+ }
138
+ fn supports(&self, _flavor: Flavor) -> bool {
139
+ true
140
+ }
141
+ async fn download(&self, _set_id: u64, _flavor: Flavor) -> Result<Bytes, MirrorError> {
142
+ // Emulating "mirror returned 200 with garbage". The integration
143
+ // test exercises the pool-level fallback path indirectly — the
144
+ // unit test in mirrors/mod.rs covers classify_response directly.
145
+ Err(MirrorError::InvalidArchive {
146
+ mirror: "bad-bytes".into(),
147
+ reason: "test stub".into(),
148
+ })
149
+ }
150
+ }
151
+
152
+ #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
153
+ async fn download_persists_files_and_marks_success() {
154
+ let dir = TempDir::new().unwrap();
155
+ let archives_dir = dir.path().join("archives");
156
+ let state_path = dir.path().join("state.db");
157
+
158
+ let state = Arc::new(StateDb::open(&state_path).unwrap());
159
+ for id in [10u64, 20, 30] {
160
+ state
161
+ .upsert_wanted(&WantedRow {
162
+ set_id: id,
163
+ ranked_status: RankedStatus::Ranked,
164
+ artist: None,
165
+ title: None,
166
+ creator: None,
167
+ api_last_updated: None,
168
+ })
169
+ .unwrap();
170
+ }
171
+
172
+ let pool = Arc::new(MirrorPool::new(vec![Arc::new(OkMirror { name: "ok" })]));
173
+ let token = CancellationToken::new();
174
+ let stats = download::run(
175
+ state.clone(),
176
+ pool,
177
+ DownloadOptions {
178
+ archives_dir: archives_dir.clone(),
179
+ flavor: Flavor::Full,
180
+ concurrency: 2,
181
+ limit: None,
182
+ },
183
+ token,
184
+ None,
185
+ )
186
+ .await
187
+ .unwrap();
188
+
189
+ assert_eq!(stats.attempted, 3);
190
+ assert_eq!(stats.success, 3);
191
+ assert_eq!(stats.failed, 0);
192
+ assert_eq!(stats.missing, 0);
193
+
194
+ for id in [10u64, 20, 30] {
195
+ let path = archives_dir.join(format!("{id}.osz"));
196
+ assert!(path.exists(), "expected {id}.osz on disk");
197
+ }
198
+
199
+ let counts = state.status_counts().unwrap();
200
+ assert_eq!(counts.success, 3);
201
+ assert_eq!(counts.pending, 0);
202
+ }
203
+
204
+ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
205
+ async fn download_marks_set_missing_when_every_mirror_is_404() {
206
+ let dir = TempDir::new().unwrap();
207
+ let archives_dir = dir.path().join("archives");
208
+ let state = Arc::new(StateDb::open(dir.path().join("state.db")).unwrap());
209
+ state
210
+ .upsert_wanted(&WantedRow {
211
+ set_id: 1,
212
+ ranked_status: RankedStatus::Loved,
213
+ artist: None,
214
+ title: None,
215
+ creator: None,
216
+ api_last_updated: None,
217
+ })
218
+ .unwrap();
219
+
220
+ let pool = Arc::new(MirrorPool::new(vec![
221
+ Arc::new(AlwaysMissingMirror { name: "a" }),
222
+ Arc::new(AlwaysMissingMirror { name: "b" }),
223
+ ]));
224
+ let stats = download::run(
225
+ state.clone(),
226
+ pool,
227
+ DownloadOptions {
228
+ archives_dir,
229
+ flavor: Flavor::Full,
230
+ concurrency: 1,
231
+ limit: None,
232
+ },
233
+ CancellationToken::new(),
234
+ None,
235
+ )
236
+ .await
237
+ .unwrap();
238
+
239
+ assert_eq!(stats.missing, 1);
240
+ assert_eq!(stats.success, 0);
241
+
242
+ let counts = state.status_counts().unwrap();
243
+ assert_eq!(counts.missing, 1);
244
+ }
245
+
246
+ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
247
+ async fn download_falls_back_through_mirrors_on_5xx() {
248
+ let dir = TempDir::new().unwrap();
249
+ let archives_dir = dir.path().join("archives");
250
+ let state = Arc::new(StateDb::open(dir.path().join("state.db")).unwrap());
251
+ state
252
+ .upsert_wanted(&WantedRow {
253
+ set_id: 7,
254
+ ranked_status: RankedStatus::Ranked,
255
+ artist: None,
256
+ title: None,
257
+ creator: None,
258
+ api_last_updated: None,
259
+ })
260
+ .unwrap();
261
+
262
+ let pool = Arc::new(MirrorPool::new(vec![
263
+ Arc::new(TransientHttpErrorMirror { name: "broken" }),
264
+ Arc::new(OkMirror { name: "good" }),
265
+ ]));
266
+ let stats = download::run(
267
+ state.clone(),
268
+ pool,
269
+ DownloadOptions {
270
+ archives_dir: archives_dir.clone(),
271
+ flavor: Flavor::Full,
272
+ concurrency: 1,
273
+ limit: None,
274
+ },
275
+ CancellationToken::new(),
276
+ None,
277
+ )
278
+ .await
279
+ .unwrap();
280
+
281
+ assert_eq!(stats.success, 1);
282
+ assert!(archives_dir.join("7.osz").exists());
283
+ }
284
+
285
+ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
286
+ async fn requeue_in_progress_resets_stuck_workers_on_restart() {
287
+ let dir = TempDir::new().unwrap();
288
+ let state_path = dir.path().join("state.db");
289
+ let state = Arc::new(StateDb::open(&state_path).unwrap());
290
+ state
291
+ .upsert_wanted(&WantedRow {
292
+ set_id: 99,
293
+ ranked_status: RankedStatus::Ranked,
294
+ artist: None,
295
+ title: None,
296
+ creator: None,
297
+ api_last_updated: None,
298
+ })
299
+ .unwrap();
300
+ let _ = state.claim_next_pending().unwrap();
301
+ drop(state);
302
+
303
+ // Reopen — simulate restart.
304
+ let state2 = Arc::new(StateDb::open(&state_path).unwrap());
305
+ let pool = Arc::new(MirrorPool::new(vec![Arc::new(OkMirror { name: "ok" })]));
306
+ let stats = download::run(
307
+ state2.clone(),
308
+ pool,
309
+ DownloadOptions {
310
+ archives_dir: dir.path().join("archives"),
311
+ flavor: Flavor::Full,
312
+ concurrency: 1,
313
+ limit: None,
314
+ },
315
+ CancellationToken::new(),
316
+ None,
317
+ )
318
+ .await
319
+ .unwrap();
320
+ assert_eq!(stats.success, 1);
321
+ }
322
+
323
+ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
324
+ async fn invalid_archive_advances_to_next_mirror_and_succeeds() {
325
+ let dir = TempDir::new().unwrap();
326
+ let archives_dir = dir.path().join("archives");
327
+ let state = Arc::new(StateDb::open(dir.path().join("state.db")).unwrap());
328
+ state
329
+ .upsert_wanted(&WantedRow {
330
+ set_id: 42,
331
+ ranked_status: RankedStatus::Ranked,
332
+ artist: None,
333
+ title: None,
334
+ creator: None,
335
+ api_last_updated: None,
336
+ })
337
+ .unwrap();
338
+
339
+ let pool = Arc::new(MirrorPool::new(vec![
340
+ Arc::new(InvalidArchiveMirror { name: "garbage" }),
341
+ Arc::new(BadBytesMirror),
342
+ Arc::new(OkMirror { name: "good" }),
343
+ ]));
344
+ let stats = download::run(
345
+ state.clone(),
346
+ pool,
347
+ DownloadOptions {
348
+ archives_dir: archives_dir.clone(),
349
+ flavor: Flavor::Full,
350
+ concurrency: 1,
351
+ limit: None,
352
+ },
353
+ CancellationToken::new(),
354
+ None,
355
+ )
356
+ .await
357
+ .unwrap();
358
+ assert_eq!(stats.success, 1);
359
+ assert!(archives_dir.join("42.osz").exists());
360
+ let counts = state.status_counts().unwrap();
361
+ assert_eq!(counts.success, 1);
362
+ }
363
+
364
+ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
365
+ async fn shutdown_token_aborts_in_flight_workers() {
366
+ use std::time::Duration;
367
+
368
+ let dir = TempDir::new().unwrap();
369
+ let state = Arc::new(StateDb::open(dir.path().join("state.db")).unwrap());
370
+ for id in 1u64..=20 {
371
+ state
372
+ .upsert_wanted(&WantedRow {
373
+ set_id: id,
374
+ ranked_status: RankedStatus::Ranked,
375
+ artist: None,
376
+ title: None,
377
+ creator: None,
378
+ api_last_updated: None,
379
+ })
380
+ .unwrap();
381
+ }
382
+
383
+ /// Mirror that sleeps so the shutdown token races the in-flight HTTP.
384
+ struct SlowMirror;
385
+ #[async_trait]
386
+ impl Mirror for SlowMirror {
387
+ fn name(&self) -> &str {
388
+ "slow"
389
+ }
390
+ fn supports(&self, _: Flavor) -> bool {
391
+ true
392
+ }
393
+ async fn download(&self, set_id: u64, _: Flavor) -> Result<Bytes, MirrorError> {
394
+ tokio::time::sleep(Duration::from_secs(60)).await;
395
+ Ok(Bytes::from(make_minimal_osz(set_id)))
396
+ }
397
+ }
398
+
399
+ let pool = Arc::new(MirrorPool::new(vec![Arc::new(SlowMirror)]));
400
+ let token = CancellationToken::new();
401
+ let token_to_fire = token.clone();
402
+ tokio::spawn(async move {
403
+ tokio::time::sleep(Duration::from_millis(200)).await;
404
+ token_to_fire.cancel();
405
+ });
406
+
407
+ let started = std::time::Instant::now();
408
+ let stats = download::run(
409
+ state.clone(),
410
+ pool,
411
+ DownloadOptions {
412
+ archives_dir: dir.path().join("archives"),
413
+ flavor: Flavor::Full,
414
+ concurrency: 4,
415
+ limit: None,
416
+ },
417
+ token,
418
+ None,
419
+ )
420
+ .await
421
+ .unwrap();
422
+ let elapsed = started.elapsed();
423
+ assert!(
424
+ elapsed < Duration::from_secs(10),
425
+ "shutdown should abort in-flight HTTP within seconds; took {elapsed:?}"
426
+ );
427
+ assert_eq!(stats.aborted, stats.attempted);
428
+ let counts = state.status_counts().unwrap();
429
+ // Every claimed set should have been released back to pending.
430
+ assert_eq!(counts.in_progress, 0);
431
+ assert!(counts.pending >= stats.attempted);
432
+ }
433
+
434
+ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
435
+ async fn limit_caps_attempts() {
436
+ let dir = TempDir::new().unwrap();
437
+ let archives_dir = dir.path().join("archives");
438
+ let state = Arc::new(StateDb::open(dir.path().join("state.db")).unwrap());
439
+ for id in 1u64..=5 {
440
+ state
441
+ .upsert_wanted(&WantedRow {
442
+ set_id: id,
443
+ ranked_status: RankedStatus::Ranked,
444
+ artist: None,
445
+ title: None,
446
+ creator: None,
447
+ api_last_updated: None,
448
+ })
449
+ .unwrap();
450
+ }
451
+ let pool = Arc::new(MirrorPool::new(vec![Arc::new(OkMirror { name: "ok" })]));
452
+ let stats = download::run(
453
+ state.clone(),
454
+ pool,
455
+ DownloadOptions {
456
+ archives_dir,
457
+ flavor: Flavor::Full,
458
+ concurrency: 2,
459
+ limit: Some(3),
460
+ },
461
+ CancellationToken::new(),
462
+ None,
463
+ )
464
+ .await
465
+ .unwrap();
466
+ assert_eq!(stats.attempted, 3);
467
+ assert_eq!(stats.success, 3);
468
+ let counts = state.status_counts().unwrap();
469
+ assert_eq!(counts.success, 3);
470
+ assert_eq!(counts.pending, 2);
471
+ }
crates/osu_indexer/.gitignore ADDED
@@ -0,0 +1 @@
 
 
1
+ target/
crates/osu_indexer/Cargo.toml ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [package]
2
+ name = "osu_indexer"
3
+ version = "0.1.0"
4
+ edition.workspace = true
5
+ license.workspace = true
6
+ publish.workspace = true
7
+ description = "Indexer for osu! beatmapset archives. Emits NDJSON tables consumed by python/ingest_osz.py."
8
+
9
+ [dependencies]
10
+ # rosu stack (verified 2026-04-25 via cargo search).
11
+ rosu-map = "0.2" # current 0.2.1
12
+ rosu-storyboard = "0.1" # current 0.1.1
13
+ rosu-pp = "4" # current 4.0.1 — major API rev vs 1.x/2.x
14
+
15
+ # Archive + hashing
16
+ zip.workspace = true
17
+ sha2.workspace = true
18
+ crc32fast = "1" # current 1.5.0
19
+ hex.workspace = true
20
+
21
+ # Path / encoding
22
+ unicode-normalization = "0.1" # current 0.1.25
23
+ base64 = "0.22" # current 0.22.1
24
+
25
+ # Serialization
26
+ serde.workspace = true
27
+ serde_json.workspace = true
28
+
29
+ # CLI
30
+ clap.workspace = true
31
+
32
+ # Errors / logging
33
+ anyhow.workspace = true
34
+ thiserror.workspace = true
35
+ tracing.workspace = true
36
+ tracing-subscriber.workspace = true
37
+
38
+ # Concurrency: process archives in parallel per chunk so the input-drive
39
+ # read and the CAS-drive write overlap (per-archive: hash → archive copy →
40
+ # ZIP walk + blob write; with N workers, different archives are at
41
+ # different stages so both drives stay busy continuously) and rosu-pp
42
+ # scales across CPU cores.
43
+ rayon.workspace = true
44
+
45
+ # Cross-platform Ctrl+C handling. We catch SIGINT/SIGTERM, flip a shared
46
+ # atomic flag, and let in-flight workers drain so the NDJSON we hand back
47
+ # is internally consistent — partial archives never get half-emitted.
48
+ ctrlc.workspace = true
49
+
50
+ [dev-dependencies]
51
+ tempfile = "3" # tempdirs for integration tests
crates/osu_indexer/build.rs ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //! Build script: extract the `rosu-pp` crate version from `Cargo.lock` and
2
+ //! expose it as the `ROSU_PP_VERSION` env var so `difficulty.rs` can record
3
+ //! it on every `difficulty_attributes` row.
4
+ //!
5
+ //! Per `schemas/v1/difficulty_attributes.schema.json`:
6
+ //! `calculator_version` — "Crate version pulled from Cargo.lock."
7
+ //! Hardcoding the version in source would drift the moment the dep is
8
+ //! bumped. This build script reads the lockfile that cargo itself writes,
9
+ //! so the recorded version always matches what was actually linked.
10
+ //!
11
+ //! In a workspace the `Cargo.lock` lives at the workspace root, not in the
12
+ //! per-crate manifest dir. We walk parent dirs from `CARGO_MANIFEST_DIR` to
13
+ //! the first ancestor that contains one. This also keeps the script working
14
+ //! if the crate is built standalone (its own `Cargo.lock` would be in the
15
+ //! manifest dir).
16
+
17
+ use std::env;
18
+ use std::fs;
19
+ use std::path::{Path, PathBuf};
20
+
21
+ const PACKAGE: &str = "rosu-pp";
22
+
23
+ fn main() {
24
+ let manifest_dir =
25
+ PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR set by cargo"));
26
+
27
+ let lockfile = match locate_lockfile(&manifest_dir) {
28
+ Some(p) => p,
29
+ None => {
30
+ // No lockfile anywhere up the tree (shouldn't happen under cargo).
31
+ // Emit "unknown" rather than failing the build — `difficulty.rs`
32
+ // already tolerates that case in its tests.
33
+ println!("cargo:rustc-env=ROSU_PP_VERSION=unknown");
34
+ return;
35
+ }
36
+ };
37
+
38
+ // Re-run if any candidate location's lockfile changes — this includes
39
+ // the located one and the per-crate fallback so a switch back to a
40
+ // standalone build is picked up automatically.
41
+ println!("cargo:rerun-if-changed={}", lockfile.display());
42
+ println!("cargo:rerun-if-changed=build.rs");
43
+ let local_lockfile = manifest_dir.join("Cargo.lock");
44
+ if local_lockfile != lockfile {
45
+ println!("cargo:rerun-if-changed={}", local_lockfile.display());
46
+ }
47
+
48
+ let version = match fs::read_to_string(&lockfile) {
49
+ Ok(text) => find_pkg_version(&text, PACKAGE).unwrap_or_else(|| "unknown".to_string()),
50
+ Err(_) => "unknown".to_string(),
51
+ };
52
+
53
+ println!("cargo:rustc-env=ROSU_PP_VERSION={version}");
54
+ }
55
+
56
+ /// Walk from `start` up to the filesystem root, returning the first
57
+ /// directory that contains a `Cargo.lock`.
58
+ fn locate_lockfile(start: &Path) -> Option<PathBuf> {
59
+ let mut cur = Some(start);
60
+ while let Some(dir) = cur {
61
+ let candidate = dir.join("Cargo.lock");
62
+ if candidate.is_file() {
63
+ return Some(candidate);
64
+ }
65
+ cur = dir.parent();
66
+ }
67
+ None
68
+ }
69
+
70
+ fn find_pkg_version(lockfile: &str, name: &str) -> Option<String> {
71
+ let mut in_target = false;
72
+ let want = format!("name = \"{name}\"");
73
+ for line in lockfile.lines() {
74
+ let trimmed = line.trim();
75
+ if trimmed == "[[package]]" {
76
+ in_target = false;
77
+ } else if trimmed == want {
78
+ in_target = true;
79
+ } else if in_target && trimmed.starts_with("version = \"") {
80
+ return trimmed
81
+ .strip_prefix("version = \"")
82
+ .and_then(|s| s.strip_suffix('"'))
83
+ .map(String::from);
84
+ }
85
+ }
86
+ None
87
+ }
crates/osu_indexer/src/archive.rs ADDED
@@ -0,0 +1,451 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //! ZIP / .osz archive reading.
2
+ //!
3
+ //! Two entry points:
4
+ //! * [`hash_file`] — stream a file through SHA-256, returning the hex digest
5
+ //! and total size. Used to compute `archive_revision_id` before the ZIP
6
+ //! parse runs (so we can store the bytes content-addressed even when the
7
+ //! ZIP turns out to be corrupt).
8
+ //! * [`process`] — open the archive and walk every member once, handing the
9
+ //! decompressed bytes to a caller-supplied callback. The caller is
10
+ //! responsible for hashing and optionally writing extracted blob files.
11
+ //!
12
+ //! These steps are split so a ZIP-open failure can quarantine an archive after
13
+ //! its bytes are preserved, while callback/storage errors still abort the
14
+ //! ingest chunk.
15
+
16
+ use anyhow::Result;
17
+ use sha2::{Digest, Sha256};
18
+ use std::fs::File;
19
+ use std::io::{self, BufReader, Read, Seek};
20
+ use std::path::Path;
21
+ use thiserror::Error;
22
+ use zip::ZipArchive;
23
+
24
+ /// Hard cap on per-member decompressed size (1 GiB). Any single file inside an
25
+ /// .osz that decompresses to more than this is treated as broken/malicious;
26
+ /// the member is skipped and recorded as a warning. Real osu! beatmap members
27
+ /// are well under 100 MB (videos, the largest legitimate members, cap there).
28
+ /// This is purely defensive — the trusted-corpus run has never seen one near
29
+ /// the limit, but a bombed input is one of the few things that could OOM the
30
+ /// indexer mid-chunk.
31
+ pub const MAX_MEMBER_BYTES: u64 = 1_073_741_824;
32
+
33
+ /// Per-member header (no decompressed contents).
34
+ #[derive(Debug, Clone)]
35
+ pub struct MemberHeader {
36
+ /// Filename bytes as stored in the ZIP central directory. Encoding is
37
+ /// undefined per the ZIP spec; the caller decodes (UTF-8 first).
38
+ pub raw_name_bytes: Vec<u8>,
39
+ pub crc32: u32,
40
+ pub compressed_size: u64,
41
+ pub uncompressed_size: u64,
42
+ /// Best-effort unix epoch milliseconds. ZIP DOS time is timezone-less; we
43
+ /// treat it as UTC. None when the timestamp is missing or invalid.
44
+ pub mtime_unix_ms: Option<i64>,
45
+ pub is_dir: bool,
46
+ }
47
+
48
+ /// Archive-level metadata produced after a full member walk.
49
+ #[derive(Debug, Clone, Default)]
50
+ pub struct ArchiveScan {
51
+ pub member_count: u32,
52
+ pub zip_comment: Option<String>,
53
+ pub warnings: Vec<String>,
54
+ }
55
+
56
+ #[derive(Debug, Error)]
57
+ pub enum ArchiveProcessError {
58
+ #[error("opening input archive failed: {0}")]
59
+ InputOpen(#[source] io::Error),
60
+ #[error("opening zip archive failed: {0}")]
61
+ ZipOpen(#[source] zip::result::ZipError),
62
+ #[error("member callback failed: {0:#}")]
63
+ Callback(#[source] anyhow::Error),
64
+ }
65
+
66
+ impl ArchiveProcessError {
67
+ pub fn is_quarantinable_zip_open_failure(&self) -> bool {
68
+ matches!(self, Self::ZipOpen(_))
69
+ }
70
+ }
71
+
72
+ /// Stream a file through SHA-256. Returns hex digest + total bytes read.
73
+ pub fn hash_file(path: &Path) -> io::Result<(String, u64)> {
74
+ let file = File::open(path)?;
75
+ hash_reader(BufReader::new(file))
76
+ }
77
+
78
+ /// Stream-hash an arbitrary reader.
79
+ pub fn hash_reader<R: Read>(mut reader: R) -> io::Result<(String, u64)> {
80
+ let mut hasher = Sha256::new();
81
+ let mut buf = [0u8; 65_536];
82
+ let mut total = 0u64;
83
+ loop {
84
+ let n = reader.read(&mut buf)?;
85
+ if n == 0 {
86
+ break;
87
+ }
88
+ hasher.update(&buf[..n]);
89
+ total += n as u64;
90
+ }
91
+ Ok((hex::encode(hasher.finalize()), total))
92
+ }
93
+
94
+ /// Open `path` as a ZIP archive and visit every member.
95
+ ///
96
+ /// `on_member` is called once per entry with the header + fully-decompressed
97
+ /// bytes (empty Vec for directory entries). If the callback returns `Err`, the
98
+ /// walk aborts with [`ArchiveProcessError::Callback`]. Per-entry decode/read
99
+ /// failures are recorded in
100
+ /// `ArchiveScan::warnings` and the bad entry is skipped.
101
+ pub fn process_path<F>(
102
+ path: &Path,
103
+ on_member: F,
104
+ ) -> std::result::Result<ArchiveScan, ArchiveProcessError>
105
+ where
106
+ F: FnMut(MemberHeader, Vec<u8>) -> Result<()>,
107
+ {
108
+ let file = File::open(path).map_err(ArchiveProcessError::InputOpen)?;
109
+ process(BufReader::new(file), on_member)
110
+ }
111
+
112
+ /// Generic version of [`process_path`] for in-memory ZIPs (used in tests).
113
+ pub fn process<R, F>(
114
+ reader: R,
115
+ on_member: F,
116
+ ) -> std::result::Result<ArchiveScan, ArchiveProcessError>
117
+ where
118
+ R: Read + Seek,
119
+ F: FnMut(MemberHeader, Vec<u8>) -> Result<()>,
120
+ {
121
+ process_with_cap(reader, MAX_MEMBER_BYTES, on_member)
122
+ }
123
+
124
+ /// `process` parameterized on the per-member size cap. Production calls
125
+ /// [`process`] which wires `MAX_MEMBER_BYTES`; tests inject a tiny cap to
126
+ /// exercise the size-exceeded skip path without allocating gigabytes.
127
+ pub(crate) fn process_with_cap<R, F>(
128
+ reader: R,
129
+ max_member_bytes: u64,
130
+ mut on_member: F,
131
+ ) -> std::result::Result<ArchiveScan, ArchiveProcessError>
132
+ where
133
+ R: Read + Seek,
134
+ F: FnMut(MemberHeader, Vec<u8>) -> Result<()>,
135
+ {
136
+ let mut archive = ZipArchive::new(reader).map_err(ArchiveProcessError::ZipOpen)?;
137
+
138
+ let comment_bytes = archive.comment().to_vec();
139
+ let zip_comment = if comment_bytes.is_empty() {
140
+ None
141
+ } else {
142
+ Some(String::from_utf8_lossy(&comment_bytes).into_owned())
143
+ };
144
+
145
+ let len = archive.len();
146
+ let mut warnings = Vec::new();
147
+
148
+ for i in 0..len {
149
+ let mut entry = match archive.by_index(i) {
150
+ Ok(e) => e,
151
+ Err(err) => {
152
+ warnings.push(format!("member[{i}]: header read failed: {err}"));
153
+ continue;
154
+ }
155
+ };
156
+
157
+ let raw_name = entry.name_raw().to_vec();
158
+ let crc32 = entry.crc32();
159
+ let compressed_size = entry.compressed_size();
160
+ let uncompressed_size = entry.size();
161
+ let mtime_unix_ms = entry.last_modified().and_then(zip_dt_to_unix_ms);
162
+ let is_dir = entry.is_dir();
163
+
164
+ let mut buf = Vec::new();
165
+ if !is_dir {
166
+ // Cap per-member decompression at `max_member_bytes`. We read one
167
+ // extra byte so we can detect oversized payloads: any read that
168
+ // returns more than the cap is treated as broken/malicious and
169
+ // the member is skipped with a warning. This protects against ZIP
170
+ // bombs and malformed central directories that misreport
171
+ // `uncompressed_size`.
172
+ let mut limited = (&mut entry).take(max_member_bytes + 1);
173
+ if let Err(err) = limited.read_to_end(&mut buf) {
174
+ warnings.push(format!(
175
+ "member[{i}] ({}): decompress failed: {err}",
176
+ String::from_utf8_lossy(&raw_name)
177
+ ));
178
+ continue;
179
+ }
180
+ if buf.len() as u64 > max_member_bytes {
181
+ warnings.push(format!(
182
+ "member[{i}] ({}): decompressed size exceeds {max_member_bytes} byte cap; skipping",
183
+ String::from_utf8_lossy(&raw_name)
184
+ ));
185
+ continue;
186
+ }
187
+ }
188
+
189
+ let header = MemberHeader {
190
+ raw_name_bytes: raw_name,
191
+ crc32,
192
+ compressed_size,
193
+ uncompressed_size,
194
+ mtime_unix_ms,
195
+ is_dir,
196
+ };
197
+
198
+ on_member(header, buf).map_err(ArchiveProcessError::Callback)?;
199
+ }
200
+
201
+ Ok(ArchiveScan {
202
+ member_count: len as u32,
203
+ zip_comment,
204
+ warnings,
205
+ })
206
+ }
207
+
208
+ /// Convert zip 8.x's `DateTime` (DOS-time-derived) to unix epoch milliseconds.
209
+ ///
210
+ /// DOS time has no timezone; we treat it as UTC. Returns `None` for clearly
211
+ /// invalid timestamps (year < 1980 from the DOS epoch, or out-of-range fields).
212
+ fn zip_dt_to_unix_ms(dt: zip::DateTime) -> Option<i64> {
213
+ let y = dt.year() as i64;
214
+ let m = dt.month() as i64;
215
+ let d = dt.day() as i64;
216
+ let h = dt.hour() as i64;
217
+ let mi = dt.minute() as i64;
218
+ let s = dt.second() as i64;
219
+
220
+ if !(1970..=2099).contains(&y)
221
+ || !(1..=12).contains(&m)
222
+ || !(1..=31).contains(&d)
223
+ || !(0..=23).contains(&h)
224
+ || !(0..=59).contains(&mi)
225
+ || !(0..=60).contains(&s)
226
+ {
227
+ return None;
228
+ }
229
+
230
+ // Days from civil date (Howard Hinnant). Treats input as UTC.
231
+ let yy = if m <= 2 { y - 1 } else { y };
232
+ let era = if yy >= 0 { yy } else { yy - 399 } / 400;
233
+ let yoe = yy - era * 400;
234
+ let mp = if m > 2 { m - 3 } else { m + 9 };
235
+ let doy = (153 * mp + 2) / 5 + d - 1;
236
+ let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
237
+ let days = era * 146_097 + doe - 719_468;
238
+
239
+ let secs = days * 86_400 + h * 3600 + mi * 60 + s;
240
+ secs.checked_mul(1000)
241
+ }
242
+
243
+ #[cfg(test)]
244
+ mod tests {
245
+ use super::*;
246
+ use std::io::{Cursor, Write};
247
+ use zip::write::SimpleFileOptions;
248
+
249
+ fn build_test_zip() -> Vec<u8> {
250
+ let mut buf = Vec::new();
251
+ {
252
+ let mut w = zip::ZipWriter::new(Cursor::new(&mut buf));
253
+ let opts =
254
+ SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated);
255
+ w.start_file("hello.txt", opts).unwrap();
256
+ w.write_all(b"hello, world").unwrap();
257
+ w.start_file("subdir/empty.txt", opts).unwrap();
258
+ // intentionally empty
259
+ w.start_file("subdir/data.bin", opts).unwrap();
260
+ w.write_all(&[0u8, 1, 2, 3, 4, 5]).unwrap();
261
+ w.set_raw_comment(b"test-comment".to_vec().into()).unwrap();
262
+ w.finish().unwrap();
263
+ }
264
+ buf
265
+ }
266
+
267
+ #[test]
268
+ fn hash_reader_known_vector() {
269
+ // Empty input → SHA-256 of empty string.
270
+ let (h, n) = hash_reader(&b""[..]).unwrap();
271
+ assert_eq!(n, 0);
272
+ assert_eq!(
273
+ h,
274
+ "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
275
+ );
276
+
277
+ // "abc" → known SHA-256.
278
+ let (h, n) = hash_reader(&b"abc"[..]).unwrap();
279
+ assert_eq!(n, 3);
280
+ assert_eq!(
281
+ h,
282
+ "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
283
+ );
284
+ }
285
+
286
+ #[test]
287
+ fn process_walks_every_member_with_correct_metadata() {
288
+ let bytes = build_test_zip();
289
+ let mut seen: Vec<(String, u64, bool, u32)> = Vec::new();
290
+ let scan = process(Cursor::new(bytes), |hdr, content| {
291
+ seen.push((
292
+ String::from_utf8(hdr.raw_name_bytes).unwrap(),
293
+ content.len() as u64,
294
+ hdr.is_dir,
295
+ hdr.crc32,
296
+ ));
297
+ Ok(())
298
+ })
299
+ .unwrap();
300
+
301
+ assert_eq!(scan.member_count, 3);
302
+ assert_eq!(scan.zip_comment.as_deref(), Some("test-comment"));
303
+ assert_eq!(scan.warnings.len(), 0);
304
+
305
+ // Names and content sizes round-trip.
306
+ let names: Vec<&str> = seen.iter().map(|(n, _, _, _)| n.as_str()).collect();
307
+ assert!(names.contains(&"hello.txt"));
308
+ assert!(names.contains(&"subdir/empty.txt"));
309
+ assert!(names.contains(&"subdir/data.bin"));
310
+
311
+ for (name, size, is_dir, _crc) in &seen {
312
+ assert!(!is_dir, "no directory entries expected in this fixture");
313
+ match name.as_str() {
314
+ "hello.txt" => assert_eq!(*size, 12),
315
+ "subdir/empty.txt" => assert_eq!(*size, 0),
316
+ "subdir/data.bin" => assert_eq!(*size, 6),
317
+ other => panic!("unexpected member {other}"),
318
+ }
319
+ }
320
+ }
321
+
322
+ #[test]
323
+ fn process_propagates_callback_errors() {
324
+ let bytes = build_test_zip();
325
+ let result = process(Cursor::new(bytes), |_hdr, _content| {
326
+ anyhow::bail!("synthetic")
327
+ });
328
+ assert!(result.is_err());
329
+ assert!(matches!(
330
+ result.unwrap_err(),
331
+ ArchiveProcessError::Callback(_)
332
+ ));
333
+ }
334
+
335
+ #[test]
336
+ fn process_corrupt_zip_returns_err() {
337
+ let result = process(Cursor::new(b"not a zip".to_vec()), |_, _| Ok(()));
338
+ assert!(matches!(result, Err(ArchiveProcessError::ZipOpen(_))));
339
+ }
340
+
341
+ #[test]
342
+ fn max_member_bytes_has_video_headroom() {
343
+ // Real osu! members top out around 100 MB (videos). The cap must give
344
+ // legitimate inputs comfortable headroom while still bounding the
345
+ // damage from a bombed member.
346
+ assert!(
347
+ MAX_MEMBER_BYTES > 100 * 1024 * 1024,
348
+ "MAX_MEMBER_BYTES must give legitimate video members headroom",
349
+ );
350
+ }
351
+
352
+ #[test]
353
+ fn process_with_cap_skips_oversized_member() {
354
+ // Build a 3-member ZIP where one member is larger than a tiny test
355
+ // cap. Stored compression is fine — we just need the decompressed
356
+ // size to exceed the cap so the post-read length check fires.
357
+ let mut buf = Vec::new();
358
+ {
359
+ let mut w = zip::ZipWriter::new(Cursor::new(&mut buf));
360
+ let opts =
361
+ SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored);
362
+ w.start_file("small.txt", opts).unwrap();
363
+ w.write_all(&[b'a'; 8]).unwrap();
364
+ w.start_file("huge.bin", opts).unwrap();
365
+ w.write_all(&[0u8; 4096]).unwrap(); // 4 KiB, well over the 1 KiB cap
366
+ w.start_file("also_small.txt", opts).unwrap();
367
+ w.write_all(&[b'b'; 16]).unwrap();
368
+ w.finish().unwrap();
369
+ }
370
+
371
+ let mut delivered: Vec<(String, usize)> = Vec::new();
372
+ let scan = process_with_cap(Cursor::new(buf), 1024, |hdr, content| {
373
+ delivered.push((
374
+ String::from_utf8_lossy(&hdr.raw_name_bytes).into_owned(),
375
+ content.len(),
376
+ ));
377
+ Ok(())
378
+ })
379
+ .unwrap();
380
+
381
+ assert_eq!(scan.member_count, 3);
382
+ // huge.bin must NOT have been delivered to the callback.
383
+ let names: Vec<&str> = delivered.iter().map(|(n, _)| n.as_str()).collect();
384
+ assert!(names.contains(&"small.txt"));
385
+ assert!(names.contains(&"also_small.txt"));
386
+ assert!(
387
+ !names.contains(&"huge.bin"),
388
+ "oversized member should be skipped, got {names:?}",
389
+ );
390
+ // Exactly one warning citing the size cap.
391
+ let cap_warnings: Vec<&String> = scan
392
+ .warnings
393
+ .iter()
394
+ .filter(|w| w.contains("decompressed size exceeds"))
395
+ .collect();
396
+ assert_eq!(cap_warnings.len(), 1, "warnings: {:?}", scan.warnings);
397
+ assert!(cap_warnings[0].contains("huge.bin"));
398
+ }
399
+
400
+ #[test]
401
+ fn process_with_cap_accepts_member_at_exact_cap() {
402
+ // Off-by-one defense: a member whose decompressed size equals the cap
403
+ // exactly should pass through, not be skipped.
404
+ let mut buf = Vec::new();
405
+ {
406
+ let mut w = zip::ZipWriter::new(Cursor::new(&mut buf));
407
+ let opts =
408
+ SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored);
409
+ w.start_file("at_cap.bin", opts).unwrap();
410
+ w.write_all(&[0u8; 1024]).unwrap();
411
+ w.finish().unwrap();
412
+ }
413
+ let mut delivered_size = 0usize;
414
+ let scan = process_with_cap(Cursor::new(buf), 1024, |_hdr, content| {
415
+ delivered_size = content.len();
416
+ Ok(())
417
+ })
418
+ .unwrap();
419
+ assert_eq!(delivered_size, 1024);
420
+ assert!(scan
421
+ .warnings
422
+ .iter()
423
+ .all(|w| !w.contains("decompressed size exceeds")));
424
+ }
425
+
426
+ #[test]
427
+ fn zip_dt_dos_epoch_is_315532800000() {
428
+ // ZIP DOS time epoch is 1980-01-01T00:00:00. zip's DateTime cannot
429
+ // represent any earlier date — `from_date_and_time(1970, ...)` returns
430
+ // DateTimeRangeError. So the lowest representable value is 1980-01-01,
431
+ // which is 315_532_800 unix seconds = 315_532_800_000 unix ms.
432
+ let dt = zip::DateTime::from_date_and_time(1980, 1, 1, 0, 0, 0).unwrap();
433
+ assert_eq!(zip_dt_to_unix_ms(dt), Some(315_532_800_000));
434
+ }
435
+
436
+ #[test]
437
+ fn zip_dt_2024_round_trip() {
438
+ // 2024-01-01T00:00:00 UTC → 1_704_067_200_000 ms.
439
+ let dt = zip::DateTime::from_date_and_time(2024, 1, 1, 0, 0, 0).unwrap();
440
+ assert_eq!(zip_dt_to_unix_ms(dt), Some(1_704_067_200_000));
441
+ }
442
+
443
+ #[test]
444
+ fn zip_dt_2026_april_25_round_trip() {
445
+ // 2026-04-25T00:00:00 UTC → 1_777_075_200_000 ms.
446
+ // 56y * 365d + 14 leap-day = 20454d to 2026-01-01;
447
+ // +114d = 20568d to 2026-04-25; *86400s = 1777075200s.
448
+ let dt = zip::DateTime::from_date_and_time(2026, 4, 25, 0, 0, 0).unwrap();
449
+ assert_eq!(zip_dt_to_unix_ms(dt), Some(1_777_075_200_000));
450
+ }
451
+ }
crates/osu_indexer/src/difficulty.rs ADDED
@@ -0,0 +1,441 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //! Difficulty & performance attributes via [`rosu-pp`].
2
+ //!
3
+ //! Phase 13 emits one `difficulty_attributes` row per (beatmap, mod) pair
4
+ //! from a fixed per-ruleset default mod set. Star rating + pp logic drift as
5
+ //! upstream osu!lazer changes, so every row records `calculator_version`
6
+ //! (read from `Cargo.lock` via `build.rs`); `lazer_commit` / `tools_commit`
7
+ //! are nullable in the schema and left None until a future enrichment phase.
8
+ //!
9
+ //! Mod selection uses a standard set per ruleset, not a full combinatorial
10
+ //! sweep. Mods are passed to rosu-pp as legacy bitmask `u32`s
11
+ //! (rosu-pp auto-applies clock rate from DT/HT — we still record the
12
+ //! expected `clock_rate` on the row for downstream filtering convenience).
13
+ //!
14
+ //! Failure modes are captured in `calculation_status`: rosu-pp's
15
+ //! `Beatmap::from_bytes` failures, panics inside `Difficulty::calculate`
16
+ //! (caught via `catch_unwind`), and unsupported modes all yield a row with
17
+ //! `calculation_status="failed"` so the join with `beatmaps` stays clean.
18
+
19
+ use rosu_pp::any::DifficultyAttributes;
20
+ use rosu_pp::{Beatmap, Difficulty};
21
+ use serde_json::{json, Value};
22
+ use std::panic::{self, AssertUnwindSafe};
23
+
24
+ pub const CALCULATOR_NAME: &str = "rosu-pp";
25
+ /// Pulled from `Cargo.lock` at build time by `build.rs`. Falls back to
26
+ /// `"unknown"` if the lockfile is absent/unreadable.
27
+ pub const CALCULATOR_VERSION: &str = env!("ROSU_PP_VERSION");
28
+
29
+ /// (acronym, legacy_bitmask, expected_clock_rate)
30
+ type ModSpec = (&'static str, u32, f32);
31
+
32
+ const DEFAULT_MODS_OSU: &[ModSpec] = &[
33
+ ("NM", 0, 1.0),
34
+ ("HD", 8, 1.0),
35
+ ("HR", 16, 1.0),
36
+ ("DT", 64, 1.5),
37
+ ("HT", 256, 0.75),
38
+ ("EZ", 2, 1.0),
39
+ ("FL", 1024, 1.0),
40
+ ("HDHR", 24, 1.0),
41
+ ("HDDT", 72, 1.5),
42
+ ];
43
+
44
+ const DEFAULT_MODS_TAIKO: &[ModSpec] = &[
45
+ ("NM", 0, 1.0),
46
+ ("HD", 8, 1.0),
47
+ ("HR", 16, 1.0),
48
+ ("DT", 64, 1.5),
49
+ ("HT", 256, 0.75),
50
+ ("EZ", 2, 1.0),
51
+ ];
52
+
53
+ const DEFAULT_MODS_CATCH: &[ModSpec] = &[
54
+ ("NM", 0, 1.0),
55
+ ("HD", 8, 1.0),
56
+ ("HR", 16, 1.0),
57
+ ("DT", 64, 1.5),
58
+ ("HT", 256, 0.75),
59
+ ("EZ", 2, 1.0),
60
+ ];
61
+
62
+ const DEFAULT_MODS_MANIA: &[ModSpec] = &[
63
+ ("NM", 0, 1.0),
64
+ ("HR", 16, 1.0),
65
+ ("DT", 64, 1.5),
66
+ ("HT", 256, 0.75),
67
+ ("EZ", 2, 1.0),
68
+ ];
69
+
70
+ #[derive(Debug, Clone)]
71
+ pub struct DifficultyRow {
72
+ pub ruleset: String,
73
+ pub mods_acronym: String,
74
+ pub mods_bitmask: Option<i64>,
75
+ pub clock_rate: Option<f32>,
76
+ pub stars: f64,
77
+ pub max_combo: Option<i32>,
78
+ pub attributes_json: String,
79
+ pub calculator: String,
80
+ pub calculator_version: String,
81
+ pub status: String,
82
+ pub error: Option<String>,
83
+ }
84
+
85
+ /// Compute one `DifficultyRow` per default mod for the given ruleset.
86
+ ///
87
+ /// Returns an empty `Vec` when `ruleset` is not one of the four standard
88
+ /// modes (e.g. "unknown" from a totally-failed parse).
89
+ ///
90
+ /// Beatmap-decode failures and rosu-pp internal panics produce
91
+ /// `status="failed"` rows rather than aborting the call; one row per default
92
+ /// mod is always emitted so the join with `beatmaps` stays uniform.
93
+ pub fn compute(osu_bytes: &[u8], ruleset: &str) -> Vec<DifficultyRow> {
94
+ let mods = default_mods(ruleset);
95
+ if mods.is_empty() {
96
+ return Vec::new();
97
+ }
98
+
99
+ let map = match Beatmap::from_bytes(osu_bytes) {
100
+ Ok(m) => m,
101
+ Err(e) => {
102
+ let err = format!("Beatmap::from_bytes failed: {e}");
103
+ return mods
104
+ .iter()
105
+ .map(|spec| failed_row(ruleset, spec, err.clone()))
106
+ .collect();
107
+ }
108
+ };
109
+
110
+ mods.iter()
111
+ .map(|spec| compute_one(&map, ruleset, spec))
112
+ .collect()
113
+ }
114
+
115
+ pub fn default_mods(ruleset: &str) -> &'static [ModSpec] {
116
+ match ruleset {
117
+ "osu" => DEFAULT_MODS_OSU,
118
+ "taiko" => DEFAULT_MODS_TAIKO,
119
+ "catch" => DEFAULT_MODS_CATCH,
120
+ "mania" => DEFAULT_MODS_MANIA,
121
+ _ => &[],
122
+ }
123
+ }
124
+
125
+ fn compute_one(map: &Beatmap, ruleset: &str, spec: &ModSpec) -> DifficultyRow {
126
+ let (acronym, bitmask, clock_rate) = *spec;
127
+
128
+ // rosu-pp can panic on some malformed maps. Catch + report rather than
129
+ // taking down the indexer; a calculation failure is a queryable problem,
130
+ // not a fatal ingest error.
131
+ let result = panic::catch_unwind(AssertUnwindSafe(|| {
132
+ Difficulty::new().mods(bitmask).calculate(map)
133
+ }));
134
+
135
+ match result {
136
+ Ok(attrs) => DifficultyRow {
137
+ ruleset: ruleset.to_string(),
138
+ mods_acronym: acronym.to_string(),
139
+ mods_bitmask: Some(bitmask as i64),
140
+ clock_rate: Some(clock_rate),
141
+ stars: attrs.stars(),
142
+ max_combo: Some(attrs.max_combo() as i32),
143
+ attributes_json: serialize_attributes(&attrs),
144
+ calculator: CALCULATOR_NAME.to_string(),
145
+ calculator_version: CALCULATOR_VERSION.to_string(),
146
+ status: "ok".to_string(),
147
+ error: None,
148
+ },
149
+ Err(payload) => failed_row(ruleset, spec, panic_message(payload)),
150
+ }
151
+ }
152
+
153
+ fn failed_row(ruleset: &str, spec: &ModSpec, err: String) -> DifficultyRow {
154
+ let (acronym, bitmask, clock_rate) = *spec;
155
+ DifficultyRow {
156
+ ruleset: ruleset.to_string(),
157
+ mods_acronym: acronym.to_string(),
158
+ mods_bitmask: Some(bitmask as i64),
159
+ clock_rate: Some(clock_rate),
160
+ stars: 0.0,
161
+ max_combo: None,
162
+ attributes_json: "{}".to_string(),
163
+ calculator: CALCULATOR_NAME.to_string(),
164
+ calculator_version: CALCULATOR_VERSION.to_string(),
165
+ status: "failed".to_string(),
166
+ error: Some(err),
167
+ }
168
+ }
169
+
170
+ fn panic_message(payload: Box<dyn std::any::Any + Send>) -> String {
171
+ if let Some(s) = payload.downcast_ref::<String>() {
172
+ format!("rosu-pp panic: {s}")
173
+ } else if let Some(s) = payload.downcast_ref::<&'static str>() {
174
+ format!("rosu-pp panic: {s}")
175
+ } else {
176
+ "rosu-pp panic: <non-string payload>".to_string()
177
+ }
178
+ }
179
+
180
+ /// Serialize per-ruleset attribute fields into a JSON object. Each variant
181
+ /// emits its own keys verbatim (no renaming) so a downstream consumer can
182
+ /// match the field names to rosu-pp's docs without translation.
183
+ fn serialize_attributes(attrs: &DifficultyAttributes) -> String {
184
+ let v: Value = match attrs {
185
+ DifficultyAttributes::Osu(o) => json!({
186
+ "ruleset": "osu",
187
+ "stars": o.stars,
188
+ "max_combo": o.max_combo,
189
+ "aim": o.aim,
190
+ "speed": o.speed,
191
+ "flashlight": o.flashlight,
192
+ "slider_factor": o.slider_factor,
193
+ "speed_note_count": o.speed_note_count,
194
+ "aim_difficult_slider_count": o.aim_difficult_slider_count,
195
+ "aim_difficult_strain_count": o.aim_difficult_strain_count,
196
+ "speed_difficult_strain_count": o.speed_difficult_strain_count,
197
+ "aim_top_weighted_slider_factor": o.aim_top_weighted_slider_factor,
198
+ "speed_top_weighted_slider_factor": o.speed_top_weighted_slider_factor,
199
+ "ar": o.ar,
200
+ "hp": o.hp,
201
+ "great_hit_window": o.great_hit_window,
202
+ "ok_hit_window": o.ok_hit_window,
203
+ "meh_hit_window": o.meh_hit_window,
204
+ "n_circles": o.n_circles,
205
+ "n_sliders": o.n_sliders,
206
+ "n_spinners": o.n_spinners,
207
+ "n_large_ticks": o.n_large_ticks,
208
+ "nested_score_per_object": o.nested_score_per_object,
209
+ "maximum_legacy_combo_score": o.maximum_legacy_combo_score,
210
+ "legacy_score_base_multiplier": o.legacy_score_base_multiplier,
211
+ }),
212
+ DifficultyAttributes::Taiko(t) => json!({
213
+ "ruleset": "taiko",
214
+ "stars": t.stars,
215
+ "max_combo": t.max_combo,
216
+ "stamina": t.stamina,
217
+ "rhythm": t.rhythm,
218
+ "color": t.color,
219
+ "reading": t.reading,
220
+ "great_hit_window": t.great_hit_window,
221
+ "ok_hit_window": t.ok_hit_window,
222
+ "mono_stamina_factor": t.mono_stamina_factor,
223
+ "mechanical_difficulty": t.mechanical_difficulty,
224
+ "consistency_factor": t.consistency_factor,
225
+ "is_convert": t.is_convert,
226
+ }),
227
+ DifficultyAttributes::Catch(c) => json!({
228
+ "ruleset": "catch",
229
+ "stars": c.stars,
230
+ "max_combo": c.max_combo(),
231
+ "preempt": c.preempt,
232
+ "n_fruits": c.n_fruits,
233
+ "n_droplets": c.n_droplets,
234
+ "n_tiny_droplets": c.n_tiny_droplets,
235
+ "is_convert": c.is_convert,
236
+ }),
237
+ DifficultyAttributes::Mania(m) => json!({
238
+ "ruleset": "mania",
239
+ "stars": m.stars,
240
+ "max_combo": m.max_combo,
241
+ "n_objects": m.n_objects,
242
+ "n_hold_notes": m.n_hold_notes,
243
+ "is_convert": m.is_convert,
244
+ }),
245
+ };
246
+ // serde_json on a json!() Value never fails — we built it from owned data.
247
+ serde_json::to_string(&v).expect("serialize Value to String")
248
+ }
249
+
250
+ #[cfg(test)]
251
+ mod tests {
252
+ use super::*;
253
+
254
+ /// Minimal but well-formed osu!standard map. rosu-pp accepts it cleanly
255
+ /// and produces non-zero stars on NM.
256
+ const OSU_FIXTURE: &str = "osu file format v14\r\n\r\n\
257
+ [General]\r\nAudioFilename: song.mp3\r\nMode: 0\r\n\r\n\
258
+ [Metadata]\r\nTitle:T\r\nTitleUnicode:T\r\nArtist:A\r\nArtistUnicode:A\r\n\
259
+ Creator:c\r\nVersion:V\r\nSource:\r\nTags:\r\nBeatmapID:1\r\nBeatmapSetID:1\r\n\r\n\
260
+ [Difficulty]\r\nHPDrainRate:5\r\nCircleSize:4\r\nOverallDifficulty:5\r\n\
261
+ ApproachRate:9\r\nSliderMultiplier:1.4\r\nSliderTickRate:1\r\n\r\n\
262
+ [Events]\r\n[TimingPoints]\r\n0,500.0,4,1,1,60,1,0\r\n\r\n\
263
+ [HitObjects]\r\n256,192,1000,1,0,0:0:0:0:\r\n\
264
+ 128,192,1500,1,0,0:0:0:0:\r\n\
265
+ 384,192,2000,1,0,0:0:0:0:\r\n\
266
+ 256,128,2500,1,0,0:0:0:0:\r\n\
267
+ 256,256,3000,1,0,0:0:0:0:\r\n";
268
+
269
+ const MANIA_FIXTURE: &str = "osu file format v14\r\n\r\n\
270
+ [General]\r\nAudioFilename: song.mp3\r\nMode: 3\r\n\r\n\
271
+ [Metadata]\r\nTitle:M\r\nTitleUnicode:M\r\nArtist:A\r\nArtistUnicode:A\r\n\
272
+ Creator:c\r\nVersion:M\r\nSource:\r\nTags:\r\nBeatmapID:1\r\nBeatmapSetID:1\r\n\r\n\
273
+ [Difficulty]\r\nHPDrainRate:5\r\nCircleSize:4\r\nOverallDifficulty:5\r\n\
274
+ ApproachRate:5\r\nSliderMultiplier:1.4\r\nSliderTickRate:1\r\n\r\n\
275
+ [Events]\r\n[TimingPoints]\r\n0,500.0,4,1,1,60,1,0\r\n\r\n\
276
+ [HitObjects]\r\n64,192,1000,1,0,0:0:0:0:\r\n\
277
+ 192,192,1100,1,0,0:0:0:0:\r\n\
278
+ 320,192,1200,1,0,0:0:0:0:\r\n\
279
+ 448,192,1300,1,0,0:0:0:0:\r\n";
280
+
281
+ #[test]
282
+ fn calculator_version_is_real() {
283
+ // The build.rs reads Cargo.lock; if it found rosu-pp, the version
284
+ // string should look like a semver. "unknown" means the lockfile
285
+ // wasn't readable at build time — flag that as a regression.
286
+ assert_ne!(CALCULATOR_VERSION, "unknown");
287
+ assert!(
288
+ CALCULATOR_VERSION
289
+ .chars()
290
+ .next()
291
+ .map(|c| c.is_ascii_digit())
292
+ .unwrap_or(false),
293
+ "CALCULATOR_VERSION should start with a digit, got {CALCULATOR_VERSION}"
294
+ );
295
+ }
296
+
297
+ #[test]
298
+ fn default_mods_listed_per_ruleset() {
299
+ assert_eq!(default_mods("osu").len(), 9);
300
+ assert_eq!(default_mods("taiko").len(), 6);
301
+ assert_eq!(default_mods("catch").len(), 6);
302
+ assert_eq!(default_mods("mania").len(), 5);
303
+ assert_eq!(default_mods("unknown").len(), 0);
304
+ // First mod is always NM with bitmask 0.
305
+ for ruleset in ["osu", "taiko", "catch", "mania"] {
306
+ let first = default_mods(ruleset)[0];
307
+ assert_eq!(first.0, "NM");
308
+ assert_eq!(first.1, 0);
309
+ assert_eq!(first.2, 1.0);
310
+ }
311
+ }
312
+
313
+ #[test]
314
+ fn legacy_bitmask_combos_are_correct() {
315
+ let osu = default_mods("osu");
316
+ let lookup: std::collections::HashMap<&str, u32> =
317
+ osu.iter().map(|(a, b, _)| (*a, *b)).collect();
318
+ assert_eq!(lookup["NM"], 0);
319
+ assert_eq!(lookup["HD"], 8);
320
+ assert_eq!(lookup["HR"], 16);
321
+ assert_eq!(lookup["DT"], 64);
322
+ assert_eq!(lookup["HT"], 256);
323
+ assert_eq!(lookup["EZ"], 2);
324
+ assert_eq!(lookup["FL"], 1024);
325
+ assert_eq!(lookup["HDHR"], 24); // 8 + 16
326
+ assert_eq!(lookup["HDDT"], 72); // 8 + 64
327
+ }
328
+
329
+ #[test]
330
+ fn compute_emits_one_row_per_default_mod_for_osu() {
331
+ let rows = compute(OSU_FIXTURE.as_bytes(), "osu");
332
+ assert_eq!(rows.len(), 9, "9 default osu mods");
333
+ let acronyms: Vec<&str> = rows.iter().map(|r| r.mods_acronym.as_str()).collect();
334
+ assert_eq!(
335
+ acronyms,
336
+ vec!["NM", "HD", "HR", "DT", "HT", "EZ", "FL", "HDHR", "HDDT"]
337
+ );
338
+ for row in &rows {
339
+ assert_eq!(row.calculator, "rosu-pp");
340
+ assert_eq!(row.calculator_version, CALCULATOR_VERSION);
341
+ assert_eq!(row.ruleset, "osu");
342
+ assert_eq!(row.status, "ok");
343
+ assert!(row.error.is_none());
344
+ assert!(row.stars > 0.0, "stars should be non-zero on a valid map");
345
+ assert!(row.max_combo.is_some());
346
+ }
347
+ }
348
+
349
+ #[test]
350
+ fn compute_returns_empty_for_unknown_ruleset() {
351
+ let rows = compute(OSU_FIXTURE.as_bytes(), "unknown");
352
+ assert!(rows.is_empty());
353
+ }
354
+
355
+ #[test]
356
+ fn nm_clock_rate_is_one_dt_is_one_point_five_ht_is_three_quarters() {
357
+ let rows = compute(OSU_FIXTURE.as_bytes(), "osu");
358
+ let nm = rows.iter().find(|r| r.mods_acronym == "NM").unwrap();
359
+ let dt = rows.iter().find(|r| r.mods_acronym == "DT").unwrap();
360
+ let ht = rows.iter().find(|r| r.mods_acronym == "HT").unwrap();
361
+ let hddt = rows.iter().find(|r| r.mods_acronym == "HDDT").unwrap();
362
+ assert_eq!(nm.clock_rate, Some(1.0));
363
+ assert_eq!(dt.clock_rate, Some(1.5));
364
+ assert_eq!(ht.clock_rate, Some(0.75));
365
+ assert_eq!(hddt.clock_rate, Some(1.5));
366
+ }
367
+
368
+ #[test]
369
+ fn dt_stars_strictly_above_nm_for_osu() {
370
+ let rows = compute(OSU_FIXTURE.as_bytes(), "osu");
371
+ let nm = rows.iter().find(|r| r.mods_acronym == "NM").unwrap();
372
+ let dt = rows.iter().find(|r| r.mods_acronym == "DT").unwrap();
373
+ assert!(
374
+ dt.stars > nm.stars,
375
+ "DT ({}) should yield higher stars than NM ({})",
376
+ dt.stars,
377
+ nm.stars
378
+ );
379
+ }
380
+
381
+ #[test]
382
+ fn attributes_json_is_valid_with_mode_specific_keys() {
383
+ let rows = compute(OSU_FIXTURE.as_bytes(), "osu");
384
+ let nm = rows.iter().find(|r| r.mods_acronym == "NM").unwrap();
385
+ let v: Value = serde_json::from_str(&nm.attributes_json).unwrap();
386
+ assert_eq!(v["ruleset"], "osu");
387
+ // Mode-specific keys present.
388
+ assert!(v.get("aim").is_some());
389
+ assert!(v.get("speed").is_some());
390
+ assert!(v.get("n_circles").is_some());
391
+ assert!(v.get("great_hit_window").is_some());
392
+ // Stars on the JSON matches stars on the row.
393
+ assert_eq!(v["stars"].as_f64().unwrap(), nm.stars);
394
+ }
395
+
396
+ #[test]
397
+ fn mania_emits_five_rows_with_mania_specific_keys() {
398
+ let rows = compute(MANIA_FIXTURE.as_bytes(), "mania");
399
+ assert_eq!(rows.len(), 5);
400
+ let acronyms: Vec<&str> = rows.iter().map(|r| r.mods_acronym.as_str()).collect();
401
+ assert_eq!(acronyms, vec!["NM", "HR", "DT", "HT", "EZ"]);
402
+ for row in &rows {
403
+ assert_eq!(row.ruleset, "mania");
404
+ assert_eq!(row.status, "ok");
405
+ }
406
+ let v: Value = serde_json::from_str(&rows[0].attributes_json).unwrap();
407
+ assert_eq!(v["ruleset"], "mania");
408
+ assert!(v.get("n_hold_notes").is_some());
409
+ assert!(v.get("n_objects").is_some());
410
+ }
411
+
412
+ #[test]
413
+ fn mania_hr_clock_rate_is_one() {
414
+ let rows = compute(MANIA_FIXTURE.as_bytes(), "mania");
415
+ let hr = rows.iter().find(|r| r.mods_acronym == "HR").unwrap();
416
+ assert_eq!(hr.clock_rate, Some(1.0));
417
+ assert_eq!(hr.mods_bitmask, Some(16));
418
+ assert_eq!(hr.status, "ok");
419
+ }
420
+
421
+ #[test]
422
+ fn failed_row_helper_carries_full_metadata_for_clean_join() {
423
+ // The Beatmap::from_bytes / catch_unwind error paths can't be reliably
424
+ // forced with synthetic input — rosu-pp is lenient on most garbage.
425
+ // Instead we exercise the row-builder directly so the schema invariant
426
+ // ("a failed row still carries calculator + mod identity") is
427
+ // independently verified.
428
+ let row = failed_row("osu", &("HDDT", 72, 1.5), "synthetic".into());
429
+ assert_eq!(row.status, "failed");
430
+ assert_eq!(row.ruleset, "osu");
431
+ assert_eq!(row.mods_acronym, "HDDT");
432
+ assert_eq!(row.mods_bitmask, Some(72));
433
+ assert_eq!(row.clock_rate, Some(1.5));
434
+ assert_eq!(row.stars, 0.0);
435
+ assert!(row.max_combo.is_none());
436
+ assert_eq!(row.attributes_json, "{}");
437
+ assert_eq!(row.calculator, "rosu-pp");
438
+ assert_eq!(row.calculator_version, CALCULATOR_VERSION);
439
+ assert_eq!(row.error.as_deref(), Some("synthetic"));
440
+ }
441
+ }
crates/osu_indexer/src/hitsounds.rs ADDED
@@ -0,0 +1,384 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //! Explicit + derived hitsound reference generation.
2
+ //!
3
+ //! Two kinds of hitsound references:
4
+ //! * Explicit — the trailing `filename` field of a hit object's
5
+ //! `hit_sample` overrides the conventional name.
6
+ //! * Derived — generated from `(sample_set, addition_set, sample_index,
7
+ //! hit_sound_flags)` per hit object × active timing point. Produces
8
+ //! conventional filenames like `normal-hitnormal.wav`,
9
+ //! `soft-hitclap2.wav`. Conventional names that are NOT in the
10
+ //! beatmapset are `external_or_default_resource`, NOT `missing` —
11
+ //! osu falls back to the default skin.
12
+ //!
13
+ //! Per the .osu file format wiki:
14
+ //! * Sample-set codes: 0 = auto, 1 = normal, 2 = soft, 3 = drum.
15
+ //! * Hit-sound bit field: 1 = HITNORMAL, 2 = HITWHISTLE,
16
+ //! 4 = HITFINISH, 8 = HITCLAP.
17
+ //! * Filename pattern: `<sampleSet>-<sound><index?>.wav`. Index 0/1 is
18
+ //! omitted; ≥ 2 is appended without a separator.
19
+ //! * Every hit object always plays the *hitnormal* sample regardless of
20
+ //! bits, using `normalSet`. Whistle/finish/clap use `additionSet`,
21
+ //! which falls back to `normalSet` when not specified.
22
+ //!
23
+ //! Filename extension defaults to `.wav` here. Resolution can also match
24
+ //! the same stem with `.mp3` / `.ogg` (handled in `references.rs`).
25
+
26
+ use std::collections::BTreeSet;
27
+
28
+ use crate::osu_parse::{RawHitObject, RawTimingPoint};
29
+
30
+ #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
31
+ pub enum SampleSet {
32
+ Auto,
33
+ Normal,
34
+ Soft,
35
+ Drum,
36
+ }
37
+
38
+ impl SampleSet {
39
+ pub fn from_int(i: i32) -> Self {
40
+ match i {
41
+ 1 => Self::Normal,
42
+ 2 => Self::Soft,
43
+ 3 => Self::Drum,
44
+ _ => Self::Auto,
45
+ }
46
+ }
47
+
48
+ /// Map a free-form sample-bank string (`"normal"`, `"soft"`, `"drum"`,
49
+ /// or anything else) to a SampleSet. Used to seed the per-beatmap default
50
+ /// from the `[General].SampleSet` field.
51
+ pub fn from_str(s: &str) -> Self {
52
+ match s.to_ascii_lowercase().as_str() {
53
+ "normal" => Self::Normal,
54
+ "soft" => Self::Soft,
55
+ "drum" => Self::Drum,
56
+ _ => Self::Auto,
57
+ }
58
+ }
59
+
60
+ /// Return the conventional filename prefix. `Auto` is resolved via the
61
+ /// supplied fallback; if both are `Auto`, "normal" wins (osu's default).
62
+ pub fn prefix(self, fallback: SampleSet) -> &'static str {
63
+ let resolved = match self {
64
+ Self::Auto => match fallback {
65
+ Self::Auto => Self::Normal,
66
+ other => other,
67
+ },
68
+ other => other,
69
+ };
70
+ match resolved {
71
+ Self::Normal | Self::Auto => "normal",
72
+ Self::Soft => "soft",
73
+ Self::Drum => "drum",
74
+ }
75
+ }
76
+ }
77
+
78
+ /// Generate conventional candidate filenames for derived hitsounds in a
79
+ /// beatmap. Returns deduplicated `(filename, source_context_label)` pairs.
80
+ ///
81
+ /// Always emits a `<set>-hitnormal<idx?>.wav` candidate per hit object — even
82
+ /// when no hit-sound bits are set, osu still plays hitnormal. Whistle / finish
83
+ /// / clap candidates are emitted only when their respective bits are set on
84
+ /// the hit object.
85
+ pub fn derived_candidates_for_beatmap(
86
+ hit_objects: &[RawHitObject],
87
+ timing_points: &[RawTimingPoint],
88
+ default_sample_set: SampleSet,
89
+ ) -> Vec<(String, String)> {
90
+ let mut out: BTreeSet<(String, String)> = BTreeSet::new();
91
+
92
+ for ho in hit_objects {
93
+ let active = active_timing_point_at(ho.time_ms, timing_points);
94
+ let tp_sample_set = active
95
+ .and_then(|tp| tp.sample_set)
96
+ .map(SampleSet::from_int)
97
+ .unwrap_or(SampleSet::Auto);
98
+ let tp_index = active
99
+ .and_then(|tp| tp.sample_index)
100
+ .filter(|&i| i > 0)
101
+ .unwrap_or(1);
102
+
103
+ // Per-object overrides from the trailing hit_sample CSV.
104
+ let (obj_normal, obj_addition, obj_index) =
105
+ parse_hit_sample_overrides(ho.hit_sample_raw.as_deref());
106
+
107
+ let normal_set = if obj_normal != SampleSet::Auto {
108
+ obj_normal
109
+ } else {
110
+ tp_sample_set
111
+ };
112
+ let addition_set = if obj_addition != SampleSet::Auto {
113
+ obj_addition
114
+ } else {
115
+ normal_set
116
+ };
117
+ let index = obj_index.unwrap_or(tp_index);
118
+
119
+ // hitnormal — always plays.
120
+ push_candidate(&mut out, normal_set, "hitnormal", index, default_sample_set);
121
+
122
+ // Additions — only when the bit is set.
123
+ for (bit, sound) in &[(2, "hitwhistle"), (4, "hitfinish"), (8, "hitclap")] {
124
+ if ho.hit_sound_flags & bit != 0 {
125
+ push_candidate(&mut out, addition_set, sound, index, default_sample_set);
126
+ }
127
+ }
128
+ }
129
+
130
+ out.into_iter().collect()
131
+ }
132
+
133
+ fn push_candidate(
134
+ out: &mut BTreeSet<(String, String)>,
135
+ set: SampleSet,
136
+ sound: &str,
137
+ index: i32,
138
+ default: SampleSet,
139
+ ) {
140
+ let prefix = set.prefix(default);
141
+ let filename = format_candidate(prefix, sound, index);
142
+ let context = format!("derived_hitsound:{prefix}-{sound}:index={index}");
143
+ out.insert((filename, context));
144
+ }
145
+
146
+ fn format_candidate(prefix: &str, sound: &str, index: i32) -> String {
147
+ if index <= 1 {
148
+ format!("{prefix}-{sound}.wav")
149
+ } else {
150
+ format!("{prefix}-{sound}{index}.wav")
151
+ }
152
+ }
153
+
154
+ fn active_timing_point_at(time_ms: i32, tps: &[RawTimingPoint]) -> Option<&RawTimingPoint> {
155
+ let t = time_ms as f64;
156
+ tps.iter().rev().find(|tp| tp.time_ms <= t)
157
+ }
158
+
159
+ /// Decode the per-object overrides from a hit-sample CSV
160
+ /// (`normalSet:additionSet:index:volume:filename`). Returns
161
+ /// `(normal_set, addition_set, index_override)`.
162
+ fn parse_hit_sample_overrides(field: Option<&str>) -> (SampleSet, SampleSet, Option<i32>) {
163
+ let Some(s) = field else {
164
+ return (SampleSet::Auto, SampleSet::Auto, None);
165
+ };
166
+ let parts: Vec<&str> = s.split(':').collect();
167
+ let normal = parts
168
+ .first()
169
+ .and_then(|x| x.trim().parse::<i32>().ok())
170
+ .map(SampleSet::from_int)
171
+ .unwrap_or(SampleSet::Auto);
172
+ let addition = parts
173
+ .get(1)
174
+ .and_then(|x| x.trim().parse::<i32>().ok())
175
+ .map(SampleSet::from_int)
176
+ .unwrap_or(SampleSet::Auto);
177
+ let index = parts
178
+ .get(2)
179
+ .and_then(|x| x.trim().parse::<i32>().ok())
180
+ .filter(|&i| i > 0);
181
+ (normal, addition, index)
182
+ }
183
+
184
+ /// Return the trailing custom filename from a hit-sample CSV
185
+ /// (`normalSet:additionSet:index:volume:filename`). `None` when the field
186
+ /// is missing, has fewer than 5 segments, or the filename is empty.
187
+ pub fn explicit_from_hit_sample_field(field: &str) -> Option<String> {
188
+ let parts: Vec<&str> = field.split(':').collect();
189
+ if parts.len() < 5 {
190
+ return None;
191
+ }
192
+ // Filenames with a literal ':' in them are vanishingly rare; if one ever
193
+ // shows up, the trailing segments rejoin without ambiguity.
194
+ let filename = parts[4..].join(":").trim().to_string();
195
+ if filename.is_empty() {
196
+ None
197
+ } else {
198
+ Some(filename)
199
+ }
200
+ }
201
+
202
+ #[cfg(test)]
203
+ mod tests {
204
+ use super::*;
205
+
206
+ fn ho(time_ms: i32, hs: i32, sample: Option<&str>) -> RawHitObject {
207
+ RawHitObject {
208
+ object_index: 0,
209
+ x: 0,
210
+ y: 0,
211
+ time_ms,
212
+ type_flags: 1,
213
+ hit_sound_flags: hs,
214
+ common_kind: crate::osu_parse::HitObjectCommonKind::Circle,
215
+ is_new_combo: false,
216
+ combo_skip: None,
217
+ raw_params: Vec::new(),
218
+ raw_line: String::new(),
219
+ parse_status: "ok",
220
+ end_time_ms: None,
221
+ slider: None,
222
+ hit_sample_raw: sample.map(String::from),
223
+ hit_sample: None,
224
+ }
225
+ }
226
+
227
+ fn tp(time_ms: f64, sample_set: i32, sample_index: i32) -> RawTimingPoint {
228
+ RawTimingPoint {
229
+ row_index: 0,
230
+ time_ms,
231
+ beat_length: 500.0,
232
+ meter: Some(4),
233
+ sample_set: Some(sample_set),
234
+ sample_index: Some(sample_index),
235
+ volume: Some(60),
236
+ uninherited: true,
237
+ effects: Some(0),
238
+ raw_line: String::new(),
239
+ }
240
+ }
241
+
242
+ #[test]
243
+ fn sample_set_from_int_basic() {
244
+ assert_eq!(SampleSet::from_int(0), SampleSet::Auto);
245
+ assert_eq!(SampleSet::from_int(1), SampleSet::Normal);
246
+ assert_eq!(SampleSet::from_int(2), SampleSet::Soft);
247
+ assert_eq!(SampleSet::from_int(3), SampleSet::Drum);
248
+ assert_eq!(SampleSet::from_int(99), SampleSet::Auto);
249
+ }
250
+
251
+ #[test]
252
+ fn prefix_resolves_auto_via_fallback() {
253
+ assert_eq!(SampleSet::Auto.prefix(SampleSet::Soft), "soft");
254
+ assert_eq!(SampleSet::Auto.prefix(SampleSet::Auto), "normal");
255
+ assert_eq!(SampleSet::Drum.prefix(SampleSet::Soft), "drum");
256
+ }
257
+
258
+ #[test]
259
+ fn explicit_field_extracts_filename() {
260
+ assert_eq!(
261
+ explicit_from_hit_sample_field("0:0:0:0:custom.wav"),
262
+ Some("custom.wav".to_string())
263
+ );
264
+ assert_eq!(explicit_from_hit_sample_field("0:0:0:0:"), None);
265
+ assert_eq!(explicit_from_hit_sample_field("0:0:0:0"), None);
266
+ assert_eq!(explicit_from_hit_sample_field(""), None);
267
+ }
268
+
269
+ #[test]
270
+ fn derived_basic_circle_no_addition() {
271
+ // hit_sound = 0 → just hitnormal, normal-hitnormal.wav.
272
+ let candidates = derived_candidates_for_beatmap(
273
+ &[ho(1000, 0, Some("0:0:0:0:"))],
274
+ &[tp(0.0, 1, 1)],
275
+ SampleSet::Normal,
276
+ );
277
+ let names: Vec<&str> = candidates.iter().map(|(n, _)| n.as_str()).collect();
278
+ assert!(names.contains(&"normal-hitnormal.wav"));
279
+ assert_eq!(candidates.len(), 1);
280
+ }
281
+
282
+ #[test]
283
+ fn derived_with_clap_uses_addition() {
284
+ // hit_sound = 8 (CLAP). normal-hitnormal + normal-hitclap (addition
285
+ // defaults to normalSet when not overridden).
286
+ let candidates = derived_candidates_for_beatmap(
287
+ &[ho(1000, 8, Some("0:0:0:0:"))],
288
+ &[tp(0.0, 1, 1)],
289
+ SampleSet::Normal,
290
+ );
291
+ let names: Vec<String> = candidates.iter().map(|(n, _)| n.clone()).collect();
292
+ assert!(names.contains(&"normal-hitnormal.wav".to_string()));
293
+ assert!(names.contains(&"normal-hitclap.wav".to_string()));
294
+ assert_eq!(candidates.len(), 2);
295
+ }
296
+
297
+ #[test]
298
+ fn derived_addition_set_overrides_via_hit_sample() {
299
+ // normalSet=1 (normal), additionSet=3 (drum). With CLAP bit:
300
+ // normal-hitnormal.wav (from normalSet)
301
+ // drum-hitclap.wav (from additionSet)
302
+ let candidates = derived_candidates_for_beatmap(
303
+ &[ho(1000, 8, Some("1:3:1:0:"))],
304
+ &[tp(0.0, 1, 1)],
305
+ SampleSet::Normal,
306
+ );
307
+ let names: Vec<String> = candidates.iter().map(|(n, _)| n.clone()).collect();
308
+ assert!(names.contains(&"normal-hitnormal.wav".to_string()));
309
+ assert!(names.contains(&"drum-hitclap.wav".to_string()));
310
+ }
311
+
312
+ #[test]
313
+ fn derived_index_appended_when_above_one() {
314
+ let candidates = derived_candidates_for_beatmap(
315
+ &[ho(1000, 0, Some("0:0:5:0:"))],
316
+ &[tp(0.0, 1, 1)],
317
+ SampleSet::Normal,
318
+ );
319
+ let names: Vec<String> = candidates.iter().map(|(n, _)| n.clone()).collect();
320
+ assert!(names.contains(&"normal-hitnormal5.wav".to_string()));
321
+ }
322
+
323
+ #[test]
324
+ fn derived_uses_timing_point_index_when_no_override() {
325
+ let candidates = derived_candidates_for_beatmap(
326
+ &[ho(1000, 2, Some("0:0:0:0:"))],
327
+ &[tp(0.0, 2, 3)],
328
+ SampleSet::Normal,
329
+ );
330
+ let names: Vec<String> = candidates.iter().map(|(n, _)| n.clone()).collect();
331
+ assert!(names.contains(&"soft-hitnormal3.wav".to_string()));
332
+ assert!(names.contains(&"soft-hitwhistle3.wav".to_string()));
333
+ }
334
+
335
+ #[test]
336
+ fn derived_default_sample_set_resolves_when_tp_auto() {
337
+ // Timing point sample_set=0 (auto) → fall back to per-beatmap default.
338
+ let candidates = derived_candidates_for_beatmap(
339
+ &[ho(1000, 0, Some("0:0:0:0:"))],
340
+ &[tp(0.0, 0, 1)],
341
+ SampleSet::Drum,
342
+ );
343
+ let names: Vec<String> = candidates.iter().map(|(n, _)| n.clone()).collect();
344
+ assert!(names.contains(&"drum-hitnormal.wav".to_string()));
345
+ }
346
+
347
+ #[test]
348
+ fn derived_dedups_across_many_objects() {
349
+ // 100 hit objects all with hit_sound=0 → still just one candidate.
350
+ let objs: Vec<RawHitObject> = (0..100)
351
+ .map(|i| ho(1000 + i, 0, Some("0:0:0:0:")))
352
+ .collect();
353
+ let candidates = derived_candidates_for_beatmap(&objs, &[tp(0.0, 1, 1)], SampleSet::Normal);
354
+ assert_eq!(candidates.len(), 1);
355
+ assert_eq!(candidates[0].0, "normal-hitnormal.wav");
356
+ }
357
+
358
+ #[test]
359
+ fn derived_active_tp_changes_at_object_time() {
360
+ // Two timing points: first at 0 with sample_set=1, second at 1500
361
+ // with sample_set=3. An object at t=1000 picks up sample_set=1; at
362
+ // t=2000 picks up sample_set=3.
363
+ let candidates = derived_candidates_for_beatmap(
364
+ &[ho(1000, 0, Some("0:0:0:0:")), ho(2000, 0, Some("0:0:0:0:"))],
365
+ &[tp(0.0, 1, 1), tp(1500.0, 3, 1)],
366
+ SampleSet::Normal,
367
+ );
368
+ let names: Vec<String> = candidates.iter().map(|(n, _)| n.clone()).collect();
369
+ assert!(names.contains(&"normal-hitnormal.wav".to_string()));
370
+ assert!(names.contains(&"drum-hitnormal.wav".to_string()));
371
+ }
372
+
373
+ #[test]
374
+ fn derived_finish_bit_emits_addition_finish() {
375
+ // hit_sound = 4 (FINISH).
376
+ let candidates = derived_candidates_for_beatmap(
377
+ &[ho(1000, 4, Some("0:0:0:0:"))],
378
+ &[tp(0.0, 1, 1)],
379
+ SampleSet::Normal,
380
+ );
381
+ let names: Vec<String> = candidates.iter().map(|(n, _)| n.clone()).collect();
382
+ assert!(names.contains(&"normal-hitfinish.wav".to_string()));
383
+ }
384
+ }
crates/osu_indexer/src/main.rs ADDED
The diff for this file is too large to render. See raw diff
 
crates/osu_indexer/src/osu_parse.rs ADDED
@@ -0,0 +1,1778 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //! `.osu` parsing via rosu-map, with raw section preservation and a
2
+ //! standalone `[TimingPoints]` parser.
3
+ //!
4
+ //! rosu-map decomposes `[TimingPoints]` into four separate vecs (timing /
5
+ //! difficulty / effect / sample). The schema's `timing_points` table mirrors
6
+ //! the original .osu CSV format, so we reparse that section from raw text
7
+ //! rather than reconstructing from rosu's split structures.
8
+
9
+ use rosu_map::section::general::{CountdownType, GameMode};
10
+ use rosu_map::section::hit_objects::hit_samples::SampleBank;
11
+ use rosu_map::Beatmap;
12
+
13
+ pub const PARSER_NAME: &str = "rosu-map";
14
+ pub const PARSER_VERSION: &str = "0.2";
15
+
16
+ /// Outcome of parsing one `.osu` file.
17
+ #[derive(Debug, Clone)]
18
+ pub struct ParsedBeatmap {
19
+ /// File-level identity (known regardless of whether parsing succeeded).
20
+ pub osu_blob_sha256: String,
21
+ pub osu_path_raw: Option<String>,
22
+ pub osu_path_posix: Option<String>,
23
+ /// Lookup-only path key. Duplicate archive members may share this value.
24
+ pub osu_path_key: String,
25
+ /// Unique logical-file suffix used to construct `logical_file_id` once the
26
+ /// `set_revision_id` is resolved. Equal to `osu_path_key` for ordinary
27
+ /// members, with a `::memberNNNN` suffix for duplicate path keys.
28
+ pub osu_logical_file_id_suffix: String,
29
+
30
+ pub parse_status: ParseStatus,
31
+ pub parse_error: Option<String>,
32
+
33
+ /// Always populated. Empty list on total scan failure (BOM/encoding).
34
+ pub sections: Vec<RawSection>,
35
+
36
+ /// None when rosu-map fails outright.
37
+ pub fields: Option<ParsedFields>,
38
+
39
+ /// Reparsed from the raw `[TimingPoints]` section (in source order).
40
+ /// Empty when the section is missing or rosu-map failed and no section
41
+ /// scan succeeded.
42
+ pub timing_points: Vec<RawTimingPoint>,
43
+
44
+ /// Reparsed from the raw `[HitObjects]` section (in source order). Empty
45
+ /// when the section is missing.
46
+ pub hit_objects: Vec<RawHitObject>,
47
+
48
+ /// Reparsed from the raw `[Colours]` section. None when the section is
49
+ /// absent. Always Some when at least one combo/slider line was scanned.
50
+ pub colours: Option<RawColours>,
51
+
52
+ /// Break events from `[Events]` (entries 2,start,end / Break,start,end).
53
+ /// Empty when none are declared.
54
+ pub breaks: Vec<RawBreak>,
55
+
56
+ /// Original `.osu` bytes, retained so downstream consumers (e.g.
57
+ /// `difficulty::compute` via rosu-pp) can re-parse without re-reading the
58
+ /// blob. Memory cost is bounded: typical `.osu` is 5–30 KB; even
59
+ /// storyboard-heavy maps cap at a few hundred KB.
60
+ pub raw_bytes: Vec<u8>,
61
+ }
62
+
63
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
64
+ pub enum ParseStatus {
65
+ Ok,
66
+ Partial,
67
+ Failed,
68
+ }
69
+
70
+ impl ParseStatus {
71
+ pub fn as_str(self) -> &'static str {
72
+ match self {
73
+ ParseStatus::Ok => "ok",
74
+ ParseStatus::Partial => "partial",
75
+ ParseStatus::Failed => "failed",
76
+ }
77
+ }
78
+ }
79
+
80
+ #[allow(dead_code)]
81
+ #[derive(Debug, Clone)]
82
+ pub struct ParsedFields {
83
+ pub format_version: i32,
84
+ pub mode: u8,
85
+ pub ruleset: String,
86
+
87
+ pub title: String,
88
+ pub title_unicode: String,
89
+ pub artist: String,
90
+ pub artist_unicode: String,
91
+ pub creator: String,
92
+ pub version: String,
93
+ pub source: String,
94
+ pub tags: Vec<String>,
95
+
96
+ pub audio_filename_raw: String,
97
+ pub audio_lead_in_ms: i32,
98
+ pub background_filename: Option<String>,
99
+
100
+ pub hp_drain_rate: f32,
101
+ pub circle_size: f32,
102
+ pub overall_difficulty: f32,
103
+ pub approach_rate: f32,
104
+ pub slider_multiplier: f64,
105
+ pub slider_tick_rate: f64,
106
+
107
+ pub preview_time_ms: i32,
108
+ pub countdown: i32,
109
+ pub sample_set: String,
110
+ pub stack_leniency: f32,
111
+ pub special_style: bool,
112
+ pub widescreen_storyboard: bool,
113
+ pub letterbox_in_breaks: bool,
114
+ pub epilepsy_warning: bool,
115
+ pub samples_match_playback_rate: bool,
116
+
117
+ pub hit_object_count: i32,
118
+ pub timing_point_count: i32,
119
+ pub break_count: i32,
120
+ pub event_count: i32,
121
+
122
+ pub has_local_storyboard: bool,
123
+ pub has_video: bool,
124
+
125
+ pub beatmap_id: i32,
126
+ pub beatmapset_id: i32,
127
+
128
+ /// Optional pixel offset on the background line in `[Events]`.
129
+ pub background_x: Option<i32>,
130
+ pub background_y: Option<i32>,
131
+ /// Optional offset (ms) on the video line in `[Events]`.
132
+ pub video_start_time_ms: Option<i32>,
133
+ }
134
+
135
+ #[derive(Debug, Clone)]
136
+ pub struct RawSection {
137
+ /// Header as written in the file, including brackets (`[General]`), or
138
+ /// the literal `_header` for the leading `osu file format vN` declaration
139
+ /// and any pre-section content.
140
+ pub section_name: String,
141
+ pub line_index_start: i32,
142
+ pub line_index_end: i32,
143
+ pub byte_start: i64,
144
+ pub byte_end: i64,
145
+ pub raw_text: String,
146
+ pub parse_status: String,
147
+ }
148
+
149
+ #[derive(Debug, Clone)]
150
+ pub struct RawTimingPoint {
151
+ pub row_index: i32,
152
+ pub time_ms: f64,
153
+ pub beat_length: f64,
154
+ pub meter: Option<i32>,
155
+ pub sample_set: Option<i32>,
156
+ pub sample_index: Option<i32>,
157
+ pub volume: Option<i32>,
158
+ pub uninherited: bool,
159
+ pub effects: Option<i32>,
160
+ pub raw_line: String,
161
+ }
162
+
163
+ /// Per-line hit object. Built by reparsing `[HitObjects]` directly: rosu-map
164
+ /// strips the raw curve string and edge-sound list, but the schema preserves
165
+ /// them column-for-column.
166
+ #[derive(Debug, Clone)]
167
+ pub struct RawHitObject {
168
+ pub object_index: i32,
169
+ pub x: i32,
170
+ pub y: i32,
171
+ pub time_ms: i32,
172
+ pub type_flags: i32,
173
+ pub hit_sound_flags: i32,
174
+ pub common_kind: HitObjectCommonKind,
175
+ pub is_new_combo: bool,
176
+ pub combo_skip: Option<i32>,
177
+ /// CSV tail after the first 5 mandatory fields (x, y, time, type, hitsound).
178
+ pub raw_params: Vec<String>,
179
+ pub raw_line: String,
180
+ pub parse_status: &'static str,
181
+ /// Spinner / hold end time, if present.
182
+ pub end_time_ms: Option<i32>,
183
+ /// Decoded slider geometry, when `common_kind == Slider`.
184
+ pub slider: Option<RawSlider>,
185
+ /// Trailing colon-delimited "normalSet:additionSet:index:volume:filename".
186
+ pub hit_sample_raw: Option<String>,
187
+ /// Parsed view of `hit_sample_raw`. None when `hit_sample_raw` is None or
188
+ /// empty; partially-populated when only some fields parse.
189
+ pub hit_sample: Option<HitSample>,
190
+ }
191
+
192
+ /// Decoded `normalSet:additionSet:index:volume:filename` field. Each component
193
+ /// is independently optional — old maps may carry just a few fields.
194
+ #[derive(Debug, Clone, Default)]
195
+ pub struct HitSample {
196
+ pub normal_set: Option<i32>,
197
+ pub addition_set: Option<i32>,
198
+ pub index: Option<i32>,
199
+ pub volume: Option<i32>,
200
+ pub filename: Option<String>,
201
+ }
202
+
203
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
204
+ pub enum HitObjectCommonKind {
205
+ Circle,
206
+ Slider,
207
+ Spinner,
208
+ Hold,
209
+ Unknown,
210
+ }
211
+
212
+ impl HitObjectCommonKind {
213
+ pub fn as_str(self) -> &'static str {
214
+ match self {
215
+ HitObjectCommonKind::Circle => "circle",
216
+ HitObjectCommonKind::Slider => "slider",
217
+ HitObjectCommonKind::Spinner => "spinner",
218
+ HitObjectCommonKind::Hold => "hold",
219
+ HitObjectCommonKind::Unknown => "unknown",
220
+ }
221
+ }
222
+
223
+ /// Decode the type byte. Mania `Hold` (bit 7) takes precedence, then
224
+ /// `Spinner` (bit 3), `Slider` (bit 1), `Circle` (bit 0). The flags are
225
+ /// mutually exclusive in practice but we still pick a winner deterministically.
226
+ fn from_type_flags(flags: i32) -> Self {
227
+ if flags & 128 != 0 {
228
+ Self::Hold
229
+ } else if flags & 8 != 0 {
230
+ Self::Spinner
231
+ } else if flags & 2 != 0 {
232
+ Self::Slider
233
+ } else if flags & 1 != 0 {
234
+ Self::Circle
235
+ } else {
236
+ Self::Unknown
237
+ }
238
+ }
239
+ }
240
+
241
+ /// Decoded slider geometry from the raw line. Stays as close to the file
242
+ /// format as possible: `curve_type` is the literal prefix (usually a single
243
+ /// letter, occasionally `B<degree>` for higher-order Béziers); control points
244
+ /// do NOT include the implicit head at `(x, y)`.
245
+ #[derive(Debug, Clone)]
246
+ pub struct RawSlider {
247
+ pub curve_type: String,
248
+ pub control_points: Vec<(i32, i32)>,
249
+ pub repeats: i32,
250
+ pub pixel_length: f64,
251
+ pub edge_sounds_raw: Option<String>,
252
+ pub edge_sets_raw: Option<String>,
253
+ /// Parsed `edge_sounds_raw` (pipe-split integers). None when the field
254
+ /// is absent; empty Vec is returned only when an explicitly-empty field
255
+ /// somehow survives parsing.
256
+ pub edge_sounds: Option<Vec<i32>>,
257
+ /// Parsed `edge_sets_raw` (pipe-split "normalSet:additionSet" strings).
258
+ pub edge_sets: Option<Vec<String>>,
259
+ }
260
+
261
+ /// Parsed `[Colours]` section.
262
+ #[derive(Debug, Clone)]
263
+ pub struct RawColours {
264
+ /// Combo color RGB triples in declared order (Combo1, Combo2, ...).
265
+ pub combo_colors: Vec<(i32, i32, i32)>,
266
+ pub slider_track_override: Option<(i32, i32, i32)>,
267
+ pub slider_border: Option<(i32, i32, i32)>,
268
+ /// Whether any line failed to parse. Lets us mark the row partial.
269
+ pub had_parse_failure: bool,
270
+ }
271
+
272
+ /// One break event from `[Events]` (`2,start,end` or `Break,start,end`).
273
+ /// `break_index` is stamped at row-build time to mirror the iter index.
274
+ #[derive(Debug, Clone)]
275
+ pub struct RawBreak {
276
+ pub start_time_ms: i32,
277
+ pub end_time_ms: i32,
278
+ pub raw_line: String,
279
+ }
280
+
281
+ /// Decoded background event line: `0,0,"bg.jpg",x,y`. The filename is already
282
+ /// captured on `bm.background_file`; this struct just carries the optional
283
+ /// pixel offset.
284
+ #[derive(Debug, Clone, Default)]
285
+ pub struct RawBackgroundEvent {
286
+ pub x: Option<i32>,
287
+ pub y: Option<i32>,
288
+ }
289
+
290
+ /// Decoded video event line: `1,start,"video.mp4"` or `Video,start,"..."`.
291
+ #[derive(Debug, Clone, Default)]
292
+ pub struct RawVideoEvent {
293
+ pub start_time_ms: Option<i32>,
294
+ }
295
+
296
+ /// Parse a `.osu` blob.
297
+ ///
298
+ /// `osu_blob_sha256` / `osu_path_*` come from the `logical_files` row already
299
+ /// being constructed for this member, so they're passed in by the caller. The
300
+ /// returned `ParsedBeatmap` is always populated even when rosu-map fails — the
301
+ /// raw section scan still runs, and `parse_status` distinguishes the cases.
302
+ pub fn parse(
303
+ bytes: &[u8],
304
+ osu_blob_sha256: String,
305
+ osu_path_raw: Option<String>,
306
+ osu_path_posix: Option<String>,
307
+ osu_path_key: String,
308
+ osu_logical_file_id_suffix: String,
309
+ ) -> ParsedBeatmap {
310
+ // Independently of rosu-map: scan sections so osu_sections / timing_points
311
+ // are queryable even on parse failure.
312
+ let text_for_scan = decode_for_scan(bytes);
313
+ let sections = scan_sections(&text_for_scan);
314
+ let timing_points = sections
315
+ .iter()
316
+ .find(|s| s.section_name.eq_ignore_ascii_case("[TimingPoints]"))
317
+ .map(|s| parse_timing_points_section(&s.raw_text))
318
+ .unwrap_or_default();
319
+ let mut hit_objects = sections
320
+ .iter()
321
+ .find(|s| s.section_name.eq_ignore_ascii_case("[HitObjects]"))
322
+ .map(|s| parse_hit_objects_section(&s.raw_text))
323
+ .unwrap_or_default();
324
+ let colours = sections
325
+ .iter()
326
+ .find(|s| s.section_name.eq_ignore_ascii_case("[Colours]"))
327
+ .map(|s| parse_colours_section(&s.raw_text));
328
+ let events_section = sections
329
+ .iter()
330
+ .find(|s| s.section_name.eq_ignore_ascii_case("[Events]"));
331
+ let breaks = events_section
332
+ .map(|s| parse_breaks_from_events(&s.raw_text))
333
+ .unwrap_or_default();
334
+ let background_event = events_section.and_then(|s| parse_background_event(&s.raw_text));
335
+ let video_event = events_section.and_then(|s| parse_video_event(&s.raw_text));
336
+ // background_event / video_event are consumed by build_fields below; we
337
+ // don't store them on ParsedBeatmap because every column we care about
338
+ // (background_x/y, video_start_time_ms) is already exposed via fields.
339
+
340
+ // Slider tail times need (pixel_length, repeats) plus the active timing
341
+ // point's beat_length and SV multiplier — none of which
342
+ // `parse_hit_objects_section` has access to. Fill them in here so
343
+ // downstream `hit_objects_*.end_time_ms` and `beatmaps.last_object_time_ms`
344
+ // include sliders. SliderMultiplier comes from rosu-map when the beatmap
345
+ // parses, else falls back to the .osu format default of 1.4.
346
+ let bm_result = Beatmap::from_bytes(bytes);
347
+ let slider_multiplier_for_ends = match bm_result.as_ref() {
348
+ Ok(bm) => bm.slider_multiplier,
349
+ Err(_) => 1.4,
350
+ };
351
+ compute_slider_end_times(&mut hit_objects, slider_multiplier_for_ends, &timing_points);
352
+
353
+ match bm_result {
354
+ Ok(bm) => {
355
+ let fields = build_fields(
356
+ &bm,
357
+ &sections,
358
+ background_event.as_ref(),
359
+ video_event.as_ref(),
360
+ );
361
+ ParsedBeatmap {
362
+ osu_blob_sha256,
363
+ osu_path_raw,
364
+ osu_path_posix,
365
+ osu_path_key,
366
+ osu_logical_file_id_suffix,
367
+ parse_status: ParseStatus::Ok,
368
+ parse_error: None,
369
+ sections,
370
+ fields: Some(fields),
371
+ timing_points,
372
+ hit_objects,
373
+ colours,
374
+ breaks,
375
+ raw_bytes: bytes.to_vec(),
376
+ }
377
+ }
378
+ Err(e) => {
379
+ // rosu failed but our raw scan may have succeeded — partial vs
380
+ // failed depends on whether we see at least one bracketed section.
381
+ let has_any_section = sections.iter().any(|s| s.section_name.starts_with('['));
382
+ let status = if has_any_section {
383
+ ParseStatus::Partial
384
+ } else {
385
+ ParseStatus::Failed
386
+ };
387
+ ParsedBeatmap {
388
+ osu_blob_sha256,
389
+ osu_path_raw,
390
+ osu_path_posix,
391
+ osu_path_key,
392
+ osu_logical_file_id_suffix,
393
+ parse_status: status,
394
+ parse_error: Some(e.to_string()),
395
+ sections,
396
+ fields: None,
397
+ timing_points,
398
+ hit_objects,
399
+ colours,
400
+ breaks,
401
+ raw_bytes: bytes.to_vec(),
402
+ }
403
+ }
404
+ }
405
+ }
406
+
407
+ fn decode_for_scan(bytes: &[u8]) -> String {
408
+ // .osu files are UTF-8 (with optional BOM). Lossy-decode lets the section
409
+ // scanner work on best-effort text even when the file has stray bytes.
410
+ let text = String::from_utf8_lossy(bytes);
411
+ let stripped = text.strip_prefix('\u{FEFF}').unwrap_or(&text);
412
+ stripped.to_string()
413
+ }
414
+
415
+ fn build_fields(
416
+ bm: &Beatmap,
417
+ sections: &[RawSection],
418
+ background_event: Option<&RawBackgroundEvent>,
419
+ video_event: Option<&RawVideoEvent>,
420
+ ) -> ParsedFields {
421
+ let mode_u8 = game_mode_to_u8(bm.mode);
422
+ let event_count = sections
423
+ .iter()
424
+ .find(|s| s.section_name.eq_ignore_ascii_case("[Events]"))
425
+ .map(|s| count_data_lines(&s.raw_text))
426
+ .unwrap_or(0);
427
+ let has_local_storyboard = sections
428
+ .iter()
429
+ .find(|s| s.section_name.eq_ignore_ascii_case("[Events]"))
430
+ .map(|s| events_has_storyboard(&s.raw_text))
431
+ .unwrap_or(false);
432
+ let has_video = sections
433
+ .iter()
434
+ .find(|s| s.section_name.eq_ignore_ascii_case("[Events]"))
435
+ .map(|s| events_has_video(&s.raw_text))
436
+ .unwrap_or(false);
437
+
438
+ let bg = if bm.background_file.is_empty() {
439
+ None
440
+ } else {
441
+ Some(bm.background_file.clone())
442
+ };
443
+
444
+ ParsedFields {
445
+ format_version: bm.format_version,
446
+ mode: mode_u8,
447
+ ruleset: ruleset_string(mode_u8).to_string(),
448
+
449
+ title: bm.title.clone(),
450
+ title_unicode: bm.title_unicode.clone(),
451
+ artist: bm.artist.clone(),
452
+ artist_unicode: bm.artist_unicode.clone(),
453
+ creator: bm.creator.clone(),
454
+ version: bm.version.clone(),
455
+ source: bm.source.clone(),
456
+ tags: bm.tags.split_whitespace().map(String::from).collect(),
457
+
458
+ audio_filename_raw: bm.audio_file.clone(),
459
+ // [General] AudioLeadIn — silence prepended before audio playback.
460
+ // Stored as i32 to match other ms columns; rosu-map decodes to f64
461
+ // but parses the source as i32, so the cast is lossless.
462
+ audio_lead_in_ms: bm.audio_lead_in as i32,
463
+ background_filename: bg,
464
+
465
+ hp_drain_rate: bm.hp_drain_rate,
466
+ circle_size: bm.circle_size,
467
+ overall_difficulty: bm.overall_difficulty,
468
+ approach_rate: bm.approach_rate,
469
+ slider_multiplier: bm.slider_multiplier,
470
+ slider_tick_rate: bm.slider_tick_rate,
471
+
472
+ preview_time_ms: bm.preview_time,
473
+ countdown: countdown_to_int(bm.countdown),
474
+ sample_set: sample_bank_string(bm.default_sample_bank).to_string(),
475
+ stack_leniency: bm.stack_leniency,
476
+ special_style: bm.special_style,
477
+ widescreen_storyboard: bm.widescreen_storyboard,
478
+ letterbox_in_breaks: bm.letterbox_in_breaks,
479
+ epilepsy_warning: bm.epilepsy_warning,
480
+ samples_match_playback_rate: bm.samples_match_playback_rate,
481
+
482
+ hit_object_count: bm.hit_objects.len() as i32,
483
+ timing_point_count: bm.control_points.timing_points.len() as i32,
484
+ break_count: bm.breaks.len() as i32,
485
+ event_count,
486
+
487
+ has_local_storyboard,
488
+ has_video,
489
+
490
+ beatmap_id: bm.beatmap_id,
491
+ beatmapset_id: bm.beatmap_set_id,
492
+
493
+ background_x: background_event.and_then(|e| e.x),
494
+ background_y: background_event.and_then(|e| e.y),
495
+ video_start_time_ms: video_event.and_then(|e| e.start_time_ms),
496
+ }
497
+ }
498
+
499
+ pub fn ruleset_string(mode: u8) -> &'static str {
500
+ match mode {
501
+ 0 => "osu",
502
+ 1 => "taiko",
503
+ 2 => "catch",
504
+ 3 => "mania",
505
+ _ => "unknown",
506
+ }
507
+ }
508
+
509
+ pub fn ruleset_aliases(mode: u8) -> Option<Vec<String>> {
510
+ match mode {
511
+ 2 => Some(vec!["ctb".to_string()]),
512
+ _ => None,
513
+ }
514
+ }
515
+
516
+ fn game_mode_to_u8(m: GameMode) -> u8 {
517
+ match m {
518
+ GameMode::Osu => 0,
519
+ GameMode::Taiko => 1,
520
+ GameMode::Catch => 2,
521
+ GameMode::Mania => 3,
522
+ }
523
+ }
524
+
525
+ fn countdown_to_int(c: CountdownType) -> i32 {
526
+ // Conventional .osu mapping per the file-format wiki:
527
+ // 0 = no countdown, 1 = normal, 2 = half, 3 = double.
528
+ match c {
529
+ CountdownType::None => 0,
530
+ CountdownType::Normal => 1,
531
+ CountdownType::HalfSpeed => 2,
532
+ CountdownType::DoubleSpeed => 3,
533
+ }
534
+ }
535
+
536
+ fn sample_bank_string(b: SampleBank) -> &'static str {
537
+ match b {
538
+ SampleBank::None => "none",
539
+ SampleBank::Normal => "normal",
540
+ SampleBank::Soft => "soft",
541
+ SampleBank::Drum => "drum",
542
+ }
543
+ }
544
+
545
+ /// Count non-empty, non-comment lines inside a raw section body, excluding
546
+ /// the bracketed header line.
547
+ fn count_data_lines(section_text: &str) -> i32 {
548
+ let mut n = 0i32;
549
+ for (i, line) in section_text.lines().enumerate() {
550
+ if i == 0 && line.trim_start().starts_with('[') {
551
+ continue;
552
+ }
553
+ let t = line.trim();
554
+ if t.is_empty() || t.starts_with("//") {
555
+ continue;
556
+ }
557
+ n += 1;
558
+ }
559
+ n
560
+ }
561
+
562
+ /// True when [Events] contains any storyboard command lines.
563
+ fn events_has_storyboard(section_text: &str) -> bool {
564
+ for (i, line) in section_text.lines().enumerate() {
565
+ if i == 0 && line.trim_start().starts_with('[') {
566
+ continue;
567
+ }
568
+ let t = line.trim_start();
569
+ if t.is_empty() || t.starts_with("//") {
570
+ continue;
571
+ }
572
+ let lc = t.to_ascii_lowercase();
573
+ if lc.starts_with("sprite,")
574
+ || lc.starts_with("animation,")
575
+ || lc.starts_with("sample,")
576
+ || lc.starts_with("4,")
577
+ || lc.starts_with("5,")
578
+ || lc.starts_with("6,")
579
+ {
580
+ return true;
581
+ }
582
+ // Indented child commands (F, M, S, R, etc.) appear under
583
+ // sprite/animation parents, so any indented line is also evidence.
584
+ if line.starts_with(' ') || line.starts_with('\t') || line.starts_with('_') {
585
+ return true;
586
+ }
587
+ }
588
+ false
589
+ }
590
+
591
+ /// True when [Events] has a video event (code 1 or "Video,...").
592
+ fn events_has_video(section_text: &str) -> bool {
593
+ for (i, line) in section_text.lines().enumerate() {
594
+ if i == 0 && line.trim_start().starts_with('[') {
595
+ continue;
596
+ }
597
+ let t = line.trim_start();
598
+ if t.is_empty() || t.starts_with("//") {
599
+ continue;
600
+ }
601
+ let lc = t.to_ascii_lowercase();
602
+ if lc.starts_with("video,") || lc.starts_with("1,") {
603
+ return true;
604
+ }
605
+ }
606
+ false
607
+ }
608
+
609
+ /// Slice a `.osu` text into `RawSection`s. Section headers are bracket-
610
+ /// delimited (`[General]`, `[Events]`, …). Anything before the first header
611
+ /// (typically just `osu file format vN`) is collected into a synthetic
612
+ /// `_header` section.
613
+ pub fn scan_sections(text: &str) -> Vec<RawSection> {
614
+ let mut sections: Vec<RawSection> = Vec::new();
615
+ let mut byte_offset: i64 = 0;
616
+ let mut header_started = false;
617
+
618
+ let mut cur_name: Option<String> = None;
619
+ let mut cur_start_line: i32 = 0;
620
+ let mut cur_start_byte: i64 = 0;
621
+ let mut cur_text = String::new();
622
+
623
+ let mut last_line_index: i32 = -1;
624
+
625
+ for (line_index, line_with_newline) in text.split_inclusive('\n').enumerate() {
626
+ let line_index = line_index as i32;
627
+ last_line_index = line_index;
628
+ let line_byte_start = byte_offset;
629
+ let line_len = line_with_newline.len() as i64;
630
+ let trimmed = line_with_newline
631
+ .trim_end_matches('\n')
632
+ .trim_end_matches('\r');
633
+
634
+ let is_section_header = trimmed.starts_with('[') && trimmed.ends_with(']');
635
+
636
+ if is_section_header {
637
+ // Close current section.
638
+ if let Some(name) = cur_name.take() {
639
+ sections.push(RawSection {
640
+ section_name: name,
641
+ line_index_start: cur_start_line,
642
+ line_index_end: line_index - 1,
643
+ byte_start: cur_start_byte,
644
+ byte_end: line_byte_start - 1,
645
+ raw_text: std::mem::take(&mut cur_text),
646
+ parse_status: "ok".to_string(),
647
+ });
648
+ } else if header_started {
649
+ // Pre-header bucket (anonymous "_header") existed; close it.
650
+ sections.push(RawSection {
651
+ section_name: "_header".to_string(),
652
+ line_index_start: 0,
653
+ line_index_end: line_index - 1,
654
+ byte_start: 0,
655
+ byte_end: line_byte_start - 1,
656
+ raw_text: std::mem::take(&mut cur_text),
657
+ parse_status: "ok".to_string(),
658
+ });
659
+ header_started = false;
660
+ }
661
+ // Start the new section.
662
+ cur_name = Some(trimmed.to_string());
663
+ cur_start_line = line_index;
664
+ cur_start_byte = line_byte_start;
665
+ cur_text = String::from(line_with_newline);
666
+ } else if cur_name.is_some() {
667
+ cur_text.push_str(line_with_newline);
668
+ } else {
669
+ // Pre-header content.
670
+ if !header_started {
671
+ header_started = true;
672
+ cur_start_line = 0;
673
+ cur_start_byte = 0;
674
+ }
675
+ cur_text.push_str(line_with_newline);
676
+ }
677
+
678
+ byte_offset += line_len;
679
+ }
680
+
681
+ // Close trailing section.
682
+ if let Some(name) = cur_name {
683
+ sections.push(RawSection {
684
+ section_name: name,
685
+ line_index_start: cur_start_line,
686
+ line_index_end: last_line_index,
687
+ byte_start: cur_start_byte,
688
+ byte_end: byte_offset.saturating_sub(1),
689
+ raw_text: cur_text,
690
+ parse_status: "ok".to_string(),
691
+ });
692
+ } else if header_started {
693
+ sections.push(RawSection {
694
+ section_name: "_header".to_string(),
695
+ line_index_start: 0,
696
+ line_index_end: last_line_index,
697
+ byte_start: 0,
698
+ byte_end: byte_offset.saturating_sub(1),
699
+ raw_text: cur_text,
700
+ parse_status: "ok".to_string(),
701
+ });
702
+ }
703
+
704
+ sections
705
+ }
706
+
707
+ /// Parse the raw text of a `[TimingPoints]` section. Skips comments, blank
708
+ /// lines, and the bracketed header itself.
709
+ pub fn parse_timing_points_section(section_text: &str) -> Vec<RawTimingPoint> {
710
+ let mut out = Vec::new();
711
+ let mut row_index = 0i32;
712
+ for line in section_text.lines() {
713
+ let trimmed = line.trim();
714
+ if trimmed.is_empty() || trimmed.starts_with("//") || trimmed.starts_with('[') {
715
+ continue;
716
+ }
717
+ let parts: Vec<&str> = trimmed.split(',').collect();
718
+ if parts.len() < 2 {
719
+ continue;
720
+ }
721
+ let time_ms = parts[0].trim().parse::<f64>().unwrap_or(f64::NAN);
722
+ let beat_length = parts[1].trim().parse::<f64>().unwrap_or(f64::NAN);
723
+ if !time_ms.is_finite() || !beat_length.is_finite() {
724
+ continue;
725
+ }
726
+ let meter = parts.get(2).and_then(|s| s.trim().parse::<i32>().ok());
727
+ let sample_set = parts.get(3).and_then(|s| s.trim().parse::<i32>().ok());
728
+ let sample_index = parts.get(4).and_then(|s| s.trim().parse::<i32>().ok());
729
+ let volume = parts.get(5).and_then(|s| s.trim().parse::<i32>().ok());
730
+ // The `uninherited` flag was introduced in v8 of the .osu format. Old
731
+ // maps lack it; default to (beat_length > 0) which matches the format
732
+ // convention (positive beat_length = uninherited).
733
+ let uninherited = parts
734
+ .get(6)
735
+ .and_then(|s| s.trim().parse::<i32>().ok())
736
+ .map(|n| n != 0)
737
+ .unwrap_or(beat_length > 0.0);
738
+ let effects = parts.get(7).and_then(|s| s.trim().parse::<i32>().ok());
739
+
740
+ out.push(RawTimingPoint {
741
+ row_index,
742
+ time_ms,
743
+ beat_length,
744
+ meter,
745
+ sample_set,
746
+ sample_index,
747
+ volume,
748
+ uninherited,
749
+ effects,
750
+ raw_line: trimmed.to_string(),
751
+ });
752
+ row_index += 1;
753
+ }
754
+ out
755
+ }
756
+
757
+ /// Parse the raw text of a `[HitObjects]` section. Skips comments, blank
758
+ /// lines, and the bracketed header. Each line must have at least 5
759
+ /// comma-separated fields (x, y, time, type, hitsound) to produce a row.
760
+ pub fn parse_hit_objects_section(section_text: &str) -> Vec<RawHitObject> {
761
+ let mut out = Vec::new();
762
+ let mut object_index = 0i32;
763
+ for line in section_text.lines() {
764
+ let trimmed = line.trim();
765
+ if trimmed.is_empty() || trimmed.starts_with("//") || trimmed.starts_with('[') {
766
+ continue;
767
+ }
768
+ let parts: Vec<&str> = trimmed.split(',').collect();
769
+ if parts.len() < 5 {
770
+ continue;
771
+ }
772
+
773
+ let x = parse_int_field(parts[0]);
774
+ let y = parse_int_field(parts[1]);
775
+ let time_ms = parse_int_field(parts[2]);
776
+ let type_flags = parts[3].trim().parse::<i32>().ok();
777
+ let hit_sound_flags = parts[4].trim().parse::<i32>().ok();
778
+ let (Some(x), Some(y), Some(time_ms), Some(tf), Some(hs)) =
779
+ (x, y, time_ms, type_flags, hit_sound_flags)
780
+ else {
781
+ continue;
782
+ };
783
+
784
+ let raw_params: Vec<String> = parts[5..].iter().map(|s| s.to_string()).collect();
785
+ let common_kind = HitObjectCommonKind::from_type_flags(tf);
786
+ let is_new_combo = (tf & 4) != 0;
787
+ let combo_skip = Some((tf >> 4) & 7);
788
+
789
+ let mut end_time_ms: Option<i32> = None;
790
+ let mut slider: Option<RawSlider> = None;
791
+ let mut hit_sample_raw: Option<String> = None;
792
+ let mut parse_status: &'static str = "ok";
793
+
794
+ match common_kind {
795
+ HitObjectCommonKind::Circle => {
796
+ hit_sample_raw = raw_params.first().cloned().filter(|s| !s.is_empty());
797
+ }
798
+ HitObjectCommonKind::Slider => {
799
+ let parsed_slider = parse_slider_params(&raw_params);
800
+ if parsed_slider.is_none() {
801
+ parse_status = "partial";
802
+ }
803
+ slider = parsed_slider;
804
+ // Slider tail layout (.osu spec):
805
+ // curve, slides, length, edgeSounds, edgeSets, hitSample
806
+ // Older format versions stop at `length`; that's why everything
807
+ // past index 2 is optional.
808
+ hit_sample_raw = raw_params.get(5).cloned().filter(|s| !s.is_empty());
809
+ }
810
+ HitObjectCommonKind::Spinner => {
811
+ end_time_ms = raw_params.first().and_then(|s| parse_int_field(s));
812
+ if end_time_ms.is_none() {
813
+ parse_status = "partial";
814
+ }
815
+ hit_sample_raw = raw_params.get(1).cloned().filter(|s| !s.is_empty());
816
+ }
817
+ HitObjectCommonKind::Hold => {
818
+ // Mania holds collapse `endTime:hitSample` into one comma-
819
+ // separated tail param.
820
+ if let Some(first) = raw_params.first() {
821
+ if let Some((end, sample)) = first.split_once(':') {
822
+ end_time_ms = parse_int_field(end);
823
+ if !sample.is_empty() {
824
+ hit_sample_raw = Some(sample.to_string());
825
+ }
826
+ } else {
827
+ end_time_ms = parse_int_field(first);
828
+ }
829
+ }
830
+ if end_time_ms.is_none() {
831
+ parse_status = "partial";
832
+ }
833
+ }
834
+ HitObjectCommonKind::Unknown => {
835
+ parse_status = "partial";
836
+ }
837
+ }
838
+
839
+ let hit_sample = hit_sample_raw.as_deref().and_then(parse_hit_sample_field);
840
+ out.push(RawHitObject {
841
+ object_index,
842
+ x,
843
+ y,
844
+ time_ms,
845
+ type_flags: tf,
846
+ hit_sound_flags: hs,
847
+ common_kind,
848
+ is_new_combo,
849
+ combo_skip,
850
+ raw_params,
851
+ raw_line: trimmed.to_string(),
852
+ parse_status,
853
+ end_time_ms,
854
+ slider,
855
+ hit_sample_raw,
856
+ hit_sample,
857
+ });
858
+ object_index += 1;
859
+ }
860
+ out
861
+ }
862
+
863
+ /// Fill in `end_time_ms` for every Slider in `hit_objects` whose value is
864
+ /// still `None`. Sliders need (`pixel_length`, `repeats`) plus the active
865
+ /// timing point's `beat_length` (uninherited) and SV multiplier (inherited if
866
+ /// active, else 1.0) — none of which `parse_hit_objects_section` has access
867
+ /// to. This pass fills the gap so `beatmaps.total_length_ms` and
868
+ /// `last_object_time_ms` cover slider/drumroll/juice-stream tails without
869
+ /// downstream consumers redoing the math.
870
+ ///
871
+ /// Formula (osu! file-format wiki, [HitObjects] → Slider):
872
+ ///
873
+ /// ```text
874
+ /// slide_duration_ms = (pixel_length / (slider_multiplier * 100 * sv)) * beat_length
875
+ /// total_duration_ms = slide_duration_ms * repeats
876
+ /// end_time_ms = start_time_ms + total_duration_ms
877
+ /// ```
878
+ ///
879
+ /// where `beat_length` is from the most recent UNINHERITED timing point and
880
+ /// `sv` is `-100 / beat_length` for the most recent timing point if it's
881
+ /// INHERITED with negative `beat_length`, else `1.0`.
882
+ ///
883
+ /// Idempotent: only sliders whose `end_time_ms` is currently `None` are
884
+ /// touched, so callers can run this twice safely.
885
+ pub fn compute_slider_end_times(
886
+ hit_objects: &mut [RawHitObject],
887
+ slider_multiplier: f64,
888
+ timing_points: &[RawTimingPoint],
889
+ ) {
890
+ if slider_multiplier <= 0.0 {
891
+ return;
892
+ }
893
+ for ho in hit_objects.iter_mut() {
894
+ if !matches!(ho.common_kind, HitObjectCommonKind::Slider) {
895
+ continue;
896
+ }
897
+ if ho.end_time_ms.is_some() {
898
+ continue;
899
+ }
900
+ let slider = match ho.slider.as_ref() {
901
+ Some(s) => s,
902
+ None => continue,
903
+ };
904
+ if slider.pixel_length <= 0.0 || slider.repeats < 1 {
905
+ continue;
906
+ }
907
+
908
+ // Most recent uninherited timing point at or before the slider start.
909
+ // Falls back to the first uninherited timing point if the slider
910
+ // precedes every point — rare on real maps but possible on broken
911
+ // 2008-era data; better an approximation than a null tail.
912
+ let beat_length = timing_points
913
+ .iter()
914
+ .rev()
915
+ .find(|tp| tp.uninherited && tp.time_ms <= ho.time_ms as f64)
916
+ .or_else(|| timing_points.iter().find(|tp| tp.uninherited))
917
+ .map(|tp| tp.beat_length);
918
+ let beat_length = match beat_length {
919
+ Some(b) if b > 0.0 => b,
920
+ _ => continue,
921
+ };
922
+
923
+ // Most recent timing point of any kind for the SV multiplier. Red
924
+ // (uninherited) lines reset SV to 1.0; green (inherited) lines carry
925
+ // SV via `-100 / beat_length`.
926
+ let sv = timing_points
927
+ .iter()
928
+ .rev()
929
+ .find(|tp| tp.time_ms <= ho.time_ms as f64)
930
+ .map(|tp| {
931
+ if !tp.uninherited && tp.beat_length < 0.0 {
932
+ -100.0 / tp.beat_length
933
+ } else {
934
+ 1.0
935
+ }
936
+ })
937
+ .unwrap_or(1.0);
938
+ if sv <= 0.0 {
939
+ continue;
940
+ }
941
+
942
+ let slide_duration = (slider.pixel_length / (slider_multiplier * 100.0 * sv)) * beat_length;
943
+ let total_duration = slide_duration * slider.repeats as f64;
944
+ ho.end_time_ms = Some((ho.time_ms as f64 + total_duration).round() as i32);
945
+ }
946
+ }
947
+
948
+ fn parse_int_field(s: &str) -> Option<i32> {
949
+ let t = s.trim();
950
+ // Some old maps store coordinates as floats ("256.5"). Accept both via f64.
951
+ t.parse::<f64>().ok().map(|v| v.round() as i32)
952
+ }
953
+
954
+ fn parse_slider_params(raw_params: &[String]) -> Option<RawSlider> {
955
+ let curve = raw_params.first()?;
956
+ let slides = raw_params.get(1)?.trim().parse::<i32>().ok()?;
957
+ let pixel_length = raw_params.get(2)?.trim().parse::<f64>().ok()?;
958
+ let (curve_type, control_points) = parse_curve_string(curve)?;
959
+ let edge_sounds_raw = raw_params.get(3).cloned().filter(|s| !s.is_empty());
960
+ let edge_sets_raw = raw_params.get(4).cloned().filter(|s| !s.is_empty());
961
+ let edge_sounds = edge_sounds_raw.as_deref().map(parse_edge_sounds);
962
+ let edge_sets = edge_sets_raw.as_deref().map(parse_edge_sets);
963
+ Some(RawSlider {
964
+ curve_type,
965
+ control_points,
966
+ repeats: slides,
967
+ pixel_length,
968
+ edge_sounds_raw,
969
+ edge_sets_raw,
970
+ edge_sounds,
971
+ edge_sets,
972
+ })
973
+ }
974
+
975
+ /// Parse `2|0|2` → `[2, 0, 2]`. Returns one entry per pipe-delimited field;
976
+ /// unparseable entries default to 0 (which is "no extra hit sound" in the
977
+ /// .osu spec, matching osu's tolerance for malformed lines).
978
+ pub fn parse_edge_sounds(raw: &str) -> Vec<i32> {
979
+ raw.split('|')
980
+ .map(|s| s.trim().parse::<i32>().unwrap_or(0))
981
+ .collect()
982
+ }
983
+
984
+ /// Parse `0:0|1:0|0:0` → `["0:0", "1:0", "0:0"]`. Each entry is a literal
985
+ /// `normalSet:additionSet` pair; we leave parsing of the inner colon to the
986
+ /// consumer because it's only meaningful when paired with the matching
987
+ /// edge_sounds bitfield.
988
+ pub fn parse_edge_sets(raw: &str) -> Vec<String> {
989
+ raw.split('|').map(|s| s.trim().to_string()).collect()
990
+ }
991
+
992
+ /// Parse `normalSet:additionSet:index:volume:filename` into a `HitSample`.
993
+ /// Empty/missing components map to None. Per the .osu spec, fields use 0 as
994
+ /// "use timing point default" — we preserve the raw 0 rather than synthesizing
995
+ /// nulls, since the consumer can distinguish "explicitly 0" from "not given"
996
+ /// by the field count.
997
+ pub fn parse_hit_sample_field(raw: &str) -> Option<HitSample> {
998
+ let trimmed = raw.trim();
999
+ if trimmed.is_empty() {
1000
+ return None;
1001
+ }
1002
+ let parts: Vec<&str> = trimmed.split(':').collect();
1003
+ let take_int = |idx: usize| -> Option<i32> {
1004
+ parts
1005
+ .get(idx)
1006
+ .map(|s| s.trim())
1007
+ .filter(|s| !s.is_empty())
1008
+ .and_then(|s| s.parse::<i32>().ok())
1009
+ };
1010
+ let filename = parts
1011
+ .get(4)
1012
+ .map(|s| s.trim().to_string())
1013
+ .filter(|s| !s.is_empty());
1014
+ Some(HitSample {
1015
+ normal_set: take_int(0),
1016
+ addition_set: take_int(1),
1017
+ index: take_int(2),
1018
+ volume: take_int(3),
1019
+ filename,
1020
+ })
1021
+ }
1022
+
1023
+ /// Parse `[Colours]` body. Per the .osu wiki: keys are `Combo<N>` (1..=8),
1024
+ /// `SliderTrackOverride`, `SliderBorder`. Values are `R,G,B` (each 0..=255).
1025
+ /// Unknown keys are tolerated (preserved in raw_section_text only).
1026
+ pub fn parse_colours_section(section_text: &str) -> RawColours {
1027
+ let mut combo_colors: Vec<(i32, i32, i32)> = Vec::new();
1028
+ let mut slider_track_override: Option<(i32, i32, i32)> = None;
1029
+ let mut slider_border: Option<(i32, i32, i32)> = None;
1030
+ let mut had_parse_failure = false;
1031
+ for line in section_text.lines() {
1032
+ let trimmed = line.trim();
1033
+ if trimmed.is_empty() || trimmed.starts_with("//") || trimmed.starts_with('[') {
1034
+ continue;
1035
+ }
1036
+ let Some((key_raw, value_raw)) = trimmed.split_once(':') else {
1037
+ continue;
1038
+ };
1039
+ let key = key_raw.trim();
1040
+ let value = value_raw.trim();
1041
+ let parsed_rgb = parse_rgb(value);
1042
+ let Some(rgb) = parsed_rgb else {
1043
+ had_parse_failure = true;
1044
+ continue;
1045
+ };
1046
+ if key.eq_ignore_ascii_case("SliderTrackOverride") {
1047
+ slider_track_override = Some(rgb);
1048
+ } else if key.eq_ignore_ascii_case("SliderBorder") {
1049
+ slider_border = Some(rgb);
1050
+ } else if let Some(rest) = key
1051
+ .strip_prefix("Combo")
1052
+ .or_else(|| key.strip_prefix("combo"))
1053
+ {
1054
+ // The numeric tail confirms it's actually a combo entry; we store
1055
+ // them in declared order rather than indexed by N because old maps
1056
+ // sometimes skip / re-order numbers.
1057
+ if rest.trim().parse::<i32>().is_ok() {
1058
+ combo_colors.push(rgb);
1059
+ }
1060
+ }
1061
+ }
1062
+ RawColours {
1063
+ combo_colors,
1064
+ slider_track_override,
1065
+ slider_border,
1066
+ had_parse_failure,
1067
+ }
1068
+ }
1069
+
1070
+ /// Parse "r,g,b" (with optional whitespace). Clamped to 0..=255 since some old
1071
+ /// maps store out-of-range values; consumers can recover the raw text from
1072
+ /// `colours.raw_section_text` if the clamp matters.
1073
+ fn parse_rgb(value: &str) -> Option<(i32, i32, i32)> {
1074
+ let parts: Vec<&str> = value.split(',').collect();
1075
+ if parts.len() < 3 {
1076
+ return None;
1077
+ }
1078
+ let r = parts[0].trim().parse::<f64>().ok()?.round() as i32;
1079
+ let g = parts[1].trim().parse::<f64>().ok()?.round() as i32;
1080
+ let b = parts[2].trim().parse::<f64>().ok()?.round() as i32;
1081
+ Some((r.clamp(0, 255), g.clamp(0, 255), b.clamp(0, 255)))
1082
+ }
1083
+
1084
+ /// Pull every `2,start,end` (or `Break,start,end`) line out of `[Events]`.
1085
+ /// Events are 0-indented; storyboard child commands at depth>=1 don't count.
1086
+ pub fn parse_breaks_from_events(section_text: &str) -> Vec<RawBreak> {
1087
+ let mut out = Vec::new();
1088
+ for (i, line) in section_text.lines().enumerate() {
1089
+ if i == 0 && line.trim_start().starts_with('[') {
1090
+ continue;
1091
+ }
1092
+ if line.starts_with(' ') || line.starts_with('\t') || line.starts_with('_') {
1093
+ continue;
1094
+ }
1095
+ let trimmed = line.trim();
1096
+ if trimmed.is_empty() || trimmed.starts_with("//") {
1097
+ continue;
1098
+ }
1099
+ let parts: Vec<&str> = trimmed.split(',').collect();
1100
+ if parts.len() < 3 {
1101
+ continue;
1102
+ }
1103
+ let kind = parts[0].trim();
1104
+ if !(kind == "2" || kind.eq_ignore_ascii_case("Break")) {
1105
+ continue;
1106
+ }
1107
+ let start = parse_int_field(parts[1]);
1108
+ let end = parse_int_field(parts[2]);
1109
+ let (Some(start), Some(end)) = (start, end) else {
1110
+ continue;
1111
+ };
1112
+ out.push(RawBreak {
1113
+ start_time_ms: start,
1114
+ end_time_ms: end,
1115
+ raw_line: trimmed.to_string(),
1116
+ });
1117
+ }
1118
+ out
1119
+ }
1120
+
1121
+ /// First background event line in `[Events]`. Format: `0,0,"bg.jpg",x,y` (the
1122
+ /// trailing x,y are optional).
1123
+ pub fn parse_background_event(section_text: &str) -> Option<RawBackgroundEvent> {
1124
+ for (i, line) in section_text.lines().enumerate() {
1125
+ if i == 0 && line.trim_start().starts_with('[') {
1126
+ continue;
1127
+ }
1128
+ if line.starts_with(' ') || line.starts_with('\t') || line.starts_with('_') {
1129
+ continue;
1130
+ }
1131
+ let trimmed = line.trim();
1132
+ if trimmed.is_empty() || trimmed.starts_with("//") {
1133
+ continue;
1134
+ }
1135
+ let parts: Vec<&str> = trimmed.split(',').collect();
1136
+ if parts.len() < 3 {
1137
+ continue;
1138
+ }
1139
+ let kind = parts[0].trim();
1140
+ if !(kind == "0" || kind.eq_ignore_ascii_case("Background")) {
1141
+ continue;
1142
+ }
1143
+ // parts[1] = startTime (always 0 for backgrounds), parts[2] = filename
1144
+ // (quoted), parts[3] = x, parts[4] = y.
1145
+ let x = parts.get(3).and_then(|s| parse_int_field(s));
1146
+ let y = parts.get(4).and_then(|s| parse_int_field(s));
1147
+ return Some(RawBackgroundEvent { x, y });
1148
+ }
1149
+ None
1150
+ }
1151
+
1152
+ /// First video event line in `[Events]`. Format: `1,startTime,"video.mp4"`
1153
+ /// or `Video,startTime,"video.mp4"`.
1154
+ pub fn parse_video_event(section_text: &str) -> Option<RawVideoEvent> {
1155
+ for (i, line) in section_text.lines().enumerate() {
1156
+ if i == 0 && line.trim_start().starts_with('[') {
1157
+ continue;
1158
+ }
1159
+ if line.starts_with(' ') || line.starts_with('\t') || line.starts_with('_') {
1160
+ continue;
1161
+ }
1162
+ let trimmed = line.trim();
1163
+ if trimmed.is_empty() || trimmed.starts_with("//") {
1164
+ continue;
1165
+ }
1166
+ let parts: Vec<&str> = trimmed.split(',').collect();
1167
+ if parts.len() < 3 {
1168
+ continue;
1169
+ }
1170
+ let kind = parts[0].trim();
1171
+ if !(kind == "1" || kind.eq_ignore_ascii_case("Video")) {
1172
+ continue;
1173
+ }
1174
+ let start = parts.get(1).and_then(|s| parse_int_field(s));
1175
+ return Some(RawVideoEvent {
1176
+ start_time_ms: start,
1177
+ });
1178
+ }
1179
+ None
1180
+ }
1181
+
1182
+ /// Decode the slider curve string `B|x:y|x:y|...`. Returns the literal prefix
1183
+ /// (typically a single letter, occasionally `B<degree>`) and the list of
1184
+ /// explicit control points (head implicit at the object's `(x, y)`).
1185
+ fn parse_curve_string(s: &str) -> Option<(String, Vec<(i32, i32)>)> {
1186
+ let mut iter = s.split('|');
1187
+ let head = iter.next()?;
1188
+ let mut points = Vec::new();
1189
+ for p in iter {
1190
+ let (xs, ys) = p.split_once(':')?;
1191
+ let x = parse_int_field(xs)?;
1192
+ let y = parse_int_field(ys)?;
1193
+ points.push((x, y));
1194
+ }
1195
+ Some((head.to_string(), points))
1196
+ }
1197
+
1198
+ #[cfg(test)]
1199
+ mod tests {
1200
+ use super::*;
1201
+
1202
+ const FIXTURE: &str = "osu file format v14\r\n\r\n\
1203
+ [General]\r\n\
1204
+ AudioFilename: audio.mp3\r\n\
1205
+ AudioLeadIn: 1500\r\n\
1206
+ PreviewTime: 12345\r\n\
1207
+ Mode: 0\r\n\
1208
+ \r\n\
1209
+ [Metadata]\r\n\
1210
+ Title:Test Title\r\n\
1211
+ TitleUnicode:テストタイトル\r\n\
1212
+ Artist:Test Artist\r\n\
1213
+ ArtistUnicode:テストアーティスト\r\n\
1214
+ Creator:peppy\r\n\
1215
+ Version:Easy\r\n\
1216
+ Source:\r\n\
1217
+ Tags:tag1 tag2 tag3\r\n\
1218
+ BeatmapID:42\r\n\
1219
+ BeatmapSetID:7\r\n\
1220
+ \r\n\
1221
+ [Difficulty]\r\n\
1222
+ HPDrainRate:5\r\n\
1223
+ CircleSize:4\r\n\
1224
+ OverallDifficulty:6\r\n\
1225
+ ApproachRate:7\r\n\
1226
+ SliderMultiplier:1.4\r\n\
1227
+ SliderTickRate:1\r\n\
1228
+ \r\n\
1229
+ [Events]\r\n\
1230
+ 0,0,\"bg.jpg\",0,0\r\n\
1231
+ Video,0,\"intro.mp4\"\r\n\
1232
+ 2,1000,2000\r\n\
1233
+ \r\n\
1234
+ [TimingPoints]\r\n\
1235
+ 0,500.0,4,2,1,60,1,0\r\n\
1236
+ 1000,-50,4,2,1,60,0,1\r\n\
1237
+ \r\n\
1238
+ [HitObjects]\r\n\
1239
+ 256,192,3000,1,0,0:0:0:0:\r\n\
1240
+ ";
1241
+
1242
+ #[test]
1243
+ fn rosu_parses_fixture() {
1244
+ let p = parse(
1245
+ FIXTURE.as_bytes(),
1246
+ "deadbeef".to_string(),
1247
+ Some("Test.osu".to_string()),
1248
+ Some("Test.osu".to_string()),
1249
+ "test.osu".to_string(),
1250
+ "test.osu".to_string(),
1251
+ );
1252
+ assert_eq!(p.parse_status, ParseStatus::Ok);
1253
+ let f = p.fields.expect("fields populated on Ok");
1254
+ assert_eq!(f.beatmap_id, 42);
1255
+ assert_eq!(f.beatmapset_id, 7);
1256
+ assert_eq!(f.format_version, 14);
1257
+ assert_eq!(f.mode, 0);
1258
+ assert_eq!(f.ruleset, "osu");
1259
+ assert_eq!(f.title, "Test Title");
1260
+ assert_eq!(f.title_unicode, "テストタイトル");
1261
+ assert_eq!(f.artist, "Test Artist");
1262
+ assert_eq!(f.creator, "peppy");
1263
+ assert_eq!(f.version, "Easy");
1264
+ assert_eq!(f.tags, vec!["tag1", "tag2", "tag3"]);
1265
+ assert_eq!(f.audio_filename_raw, "audio.mp3");
1266
+ assert_eq!(f.audio_lead_in_ms, 1500);
1267
+ assert_eq!(f.preview_time_ms, 12345);
1268
+ assert_eq!(f.hp_drain_rate, 5.0);
1269
+ assert_eq!(f.circle_size, 4.0);
1270
+ assert_eq!(f.overall_difficulty, 6.0);
1271
+ assert_eq!(f.approach_rate, 7.0);
1272
+ assert!(f.has_video, "Video,0 line should set has_video");
1273
+ assert!(f.event_count >= 2);
1274
+ }
1275
+
1276
+ #[test]
1277
+ fn scan_sections_finds_all_blocks() {
1278
+ let s = scan_sections(FIXTURE);
1279
+ let names: Vec<&str> = s.iter().map(|r| r.section_name.as_str()).collect();
1280
+ assert!(names.contains(&"_header"));
1281
+ assert!(names.contains(&"[General]"));
1282
+ assert!(names.contains(&"[Metadata]"));
1283
+ assert!(names.contains(&"[Difficulty]"));
1284
+ assert!(names.contains(&"[Events]"));
1285
+ assert!(names.contains(&"[TimingPoints]"));
1286
+ assert!(names.contains(&"[HitObjects]"));
1287
+ // Sections are ordered by appearance.
1288
+ let pos = |needle: &str| names.iter().position(|n| *n == needle).unwrap();
1289
+ assert!(pos("_header") < pos("[General]"));
1290
+ assert!(pos("[General]") < pos("[Metadata]"));
1291
+ assert!(pos("[TimingPoints]") < pos("[HitObjects]"));
1292
+ // Byte ranges are non-overlapping and increasing.
1293
+ for w in s.windows(2) {
1294
+ assert!(w[0].byte_end < w[1].byte_start);
1295
+ }
1296
+ }
1297
+
1298
+ #[test]
1299
+ fn timing_points_parsed() {
1300
+ let s = scan_sections(FIXTURE);
1301
+ let tp_section = s
1302
+ .iter()
1303
+ .find(|x| x.section_name == "[TimingPoints]")
1304
+ .expect("[TimingPoints] section must exist");
1305
+ let pts = parse_timing_points_section(&tp_section.raw_text);
1306
+ assert_eq!(pts.len(), 2);
1307
+ assert_eq!(pts[0].row_index, 0);
1308
+ assert_eq!(pts[0].time_ms, 0.0);
1309
+ assert_eq!(pts[0].beat_length, 500.0);
1310
+ assert!(pts[0].uninherited);
1311
+ assert_eq!(pts[1].time_ms, 1000.0);
1312
+ assert_eq!(pts[1].beat_length, -50.0);
1313
+ assert!(!pts[1].uninherited);
1314
+ }
1315
+
1316
+ #[test]
1317
+ fn parse_failure_keeps_section_scan() {
1318
+ // garbage that rosu can't parse but still has a [General] header.
1319
+ let bad = b"not a real osu file\n[General]\nbroken line without colon\n";
1320
+ let p = parse(
1321
+ bad,
1322
+ "x".to_string(),
1323
+ None,
1324
+ None,
1325
+ "bad.osu".to_string(),
1326
+ "bad.osu".to_string(),
1327
+ );
1328
+ // Either Ok (rosu is lenient) or Partial (rosu rejected, sections captured).
1329
+ assert_ne!(p.parse_status, ParseStatus::Failed);
1330
+ assert!(p.sections.iter().any(|s| s.section_name == "[General]"));
1331
+ }
1332
+
1333
+ #[test]
1334
+ fn ruleset_string_maps_modes() {
1335
+ assert_eq!(ruleset_string(0), "osu");
1336
+ assert_eq!(ruleset_string(1), "taiko");
1337
+ assert_eq!(ruleset_string(2), "catch");
1338
+ assert_eq!(ruleset_string(3), "mania");
1339
+ assert_eq!(ruleset_string(99), "unknown");
1340
+ }
1341
+
1342
+ #[test]
1343
+ fn ruleset_aliases_only_for_catch() {
1344
+ assert_eq!(ruleset_aliases(0), None);
1345
+ assert_eq!(ruleset_aliases(2), Some(vec!["ctb".to_string()]));
1346
+ assert_eq!(ruleset_aliases(3), None);
1347
+ }
1348
+
1349
+ #[test]
1350
+ fn hit_objects_circle_minimal() {
1351
+ let text = "[HitObjects]\r\n256,192,1000,1,0,0:0:0:0:\r\n";
1352
+ let v = parse_hit_objects_section(text);
1353
+ assert_eq!(v.len(), 1);
1354
+ let h = &v[0];
1355
+ assert_eq!(h.object_index, 0);
1356
+ assert_eq!(h.x, 256);
1357
+ assert_eq!(h.y, 192);
1358
+ assert_eq!(h.time_ms, 1000);
1359
+ assert_eq!(h.type_flags, 1);
1360
+ assert_eq!(h.hit_sound_flags, 0);
1361
+ assert_eq!(h.common_kind, HitObjectCommonKind::Circle);
1362
+ assert!(!h.is_new_combo);
1363
+ assert_eq!(h.hit_sample_raw.as_deref(), Some("0:0:0:0:"));
1364
+ assert_eq!(h.parse_status, "ok");
1365
+ assert_eq!(h.end_time_ms, None);
1366
+ assert!(h.slider.is_none());
1367
+ }
1368
+
1369
+ #[test]
1370
+ fn hit_objects_slider_full_tail() {
1371
+ // Linear slider, 1 slide, 100px, edges + sets + hit sample.
1372
+ let text = "[HitObjects]\r\n100,100,2000,2,0,L|200:200,1,100,2|0,0:0|0:0,0:0:0:0:\r\n";
1373
+ let v = parse_hit_objects_section(text);
1374
+ assert_eq!(v.len(), 1);
1375
+ let h = &v[0];
1376
+ assert_eq!(h.common_kind, HitObjectCommonKind::Slider);
1377
+ assert_eq!(h.parse_status, "ok");
1378
+ let s = h.slider.as_ref().expect("slider populated");
1379
+ assert_eq!(s.curve_type, "L");
1380
+ assert_eq!(s.control_points, vec![(200, 200)]);
1381
+ assert_eq!(s.repeats, 1);
1382
+ assert_eq!(s.pixel_length, 100.0);
1383
+ assert_eq!(s.edge_sounds_raw.as_deref(), Some("2|0"));
1384
+ assert_eq!(s.edge_sets_raw.as_deref(), Some("0:0|0:0"));
1385
+ assert_eq!(h.hit_sample_raw.as_deref(), Some("0:0:0:0:"));
1386
+ }
1387
+
1388
+ #[test]
1389
+ fn hit_objects_slider_bezier_multi_anchor() {
1390
+ // Bezier curve with 3 explicit control points (after head).
1391
+ let text = "[HitObjects]\r\n50,50,2500,2,0,B|100:100|150:50|150:50|200:100,2,150\r\n";
1392
+ let v = parse_hit_objects_section(text);
1393
+ let s = v[0].slider.as_ref().unwrap();
1394
+ assert_eq!(s.curve_type, "B");
1395
+ assert_eq!(
1396
+ s.control_points,
1397
+ vec![(100, 100), (150, 50), (150, 50), (200, 100)]
1398
+ );
1399
+ assert_eq!(s.repeats, 2);
1400
+ assert_eq!(s.pixel_length, 150.0);
1401
+ // No edge sounds / hitsample on this old-style line.
1402
+ assert!(s.edge_sounds_raw.is_none());
1403
+ assert!(s.edge_sets_raw.is_none());
1404
+ assert!(v[0].hit_sample_raw.is_none());
1405
+ }
1406
+
1407
+ #[test]
1408
+ fn hit_objects_spinner() {
1409
+ let text = "[HitObjects]\r\n256,192,3000,12,0,5000,1:0:0:0:\r\n";
1410
+ let v = parse_hit_objects_section(text);
1411
+ let h = &v[0];
1412
+ assert_eq!(h.common_kind, HitObjectCommonKind::Spinner);
1413
+ assert!(h.is_new_combo); // type=12 = SPINNER(8) | NEW_COMBO(4)
1414
+ assert_eq!(h.end_time_ms, Some(5000));
1415
+ assert_eq!(h.hit_sample_raw.as_deref(), Some("1:0:0:0:"));
1416
+ }
1417
+
1418
+ #[test]
1419
+ fn hit_objects_mania_hold() {
1420
+ // mania hold: type bit 7 = 128. Tail param "endTime:normalSet:..."
1421
+ let text = "[HitObjects]\r\n64,192,1000,128,0,1500:0:0:0:0:\r\n";
1422
+ let v = parse_hit_objects_section(text);
1423
+ let h = &v[0];
1424
+ assert_eq!(h.common_kind, HitObjectCommonKind::Hold);
1425
+ assert_eq!(h.end_time_ms, Some(1500));
1426
+ assert_eq!(h.hit_sample_raw.as_deref(), Some("0:0:0:0:"));
1427
+ }
1428
+
1429
+ #[test]
1430
+ fn hit_objects_combo_skip_extracted() {
1431
+ // type = 1 (circle) | 4 (new_combo) | (2 << 4) (combo_skip = 2)
1432
+ let tf = 1 | 4 | (2 << 4);
1433
+ let line = format!("256,192,1000,{tf},0,0:0:0:0:\r\n");
1434
+ let v = parse_hit_objects_section(&format!("[HitObjects]\r\n{line}"));
1435
+ assert_eq!(v[0].is_new_combo, true);
1436
+ assert_eq!(v[0].combo_skip, Some(2));
1437
+ }
1438
+
1439
+ #[test]
1440
+ fn hit_objects_indexes_increment_in_source_order() {
1441
+ let text =
1442
+ "[HitObjects]\r\n10,10,1000,1,0,0:0:0:0:\r\n20,20,1100,1,0,0:0:0:0:\r\n30,30,1200,1,0,0:0:0:0:\r\n";
1443
+ let v = parse_hit_objects_section(text);
1444
+ assert_eq!(v.len(), 3);
1445
+ assert_eq!(v[0].object_index, 0);
1446
+ assert_eq!(v[1].object_index, 1);
1447
+ assert_eq!(v[2].object_index, 2);
1448
+ assert_eq!(v[0].time_ms, 1000);
1449
+ assert_eq!(v[2].time_ms, 1200);
1450
+ }
1451
+
1452
+ #[test]
1453
+ fn hit_objects_short_line_skipped() {
1454
+ // Less than 5 fields = unparseable; row is dropped.
1455
+ let text = "[HitObjects]\r\n10,20,1000\r\n";
1456
+ let v = parse_hit_objects_section(text);
1457
+ assert!(v.is_empty());
1458
+ }
1459
+
1460
+ #[test]
1461
+ fn hit_objects_unknown_kind_marked_partial() {
1462
+ // Type byte = 0 (none of the known bits set) → Unknown.
1463
+ let text = "[HitObjects]\r\n100,100,500,0,0\r\n";
1464
+ let v = parse_hit_objects_section(text);
1465
+ assert_eq!(v.len(), 1);
1466
+ assert_eq!(v[0].common_kind, HitObjectCommonKind::Unknown);
1467
+ assert_eq!(v[0].parse_status, "partial");
1468
+ }
1469
+
1470
+ #[test]
1471
+ fn colours_section_parses_combo_and_overrides() {
1472
+ let s = "[Colours]\r\n\
1473
+ Combo1 : 255,128,32\r\n\
1474
+ Combo2 : 100,100,100\r\n\
1475
+ SliderTrackOverride : 200,0,0\r\n\
1476
+ SliderBorder : 0,255,0\r\n";
1477
+ let c = parse_colours_section(s);
1478
+ assert_eq!(c.combo_colors, vec![(255, 128, 32), (100, 100, 100)]);
1479
+ assert_eq!(c.slider_track_override, Some((200, 0, 0)));
1480
+ assert_eq!(c.slider_border, Some((0, 255, 0)));
1481
+ assert!(!c.had_parse_failure);
1482
+ }
1483
+
1484
+ #[test]
1485
+ fn colours_section_clamps_out_of_range_values() {
1486
+ // Some old maps store color values >255; we clamp rather than reject.
1487
+ let s = "[Colours]\r\nCombo1 : 300,-5,128\r\n";
1488
+ let c = parse_colours_section(s);
1489
+ assert_eq!(c.combo_colors, vec![(255, 0, 128)]);
1490
+ }
1491
+
1492
+ #[test]
1493
+ fn colours_section_skips_unknown_keys() {
1494
+ let s = "[Colours]\r\nCombo1:1,2,3\r\nWeirdKey:4,5,6\r\n";
1495
+ let c = parse_colours_section(s);
1496
+ assert_eq!(c.combo_colors, vec![(1, 2, 3)]);
1497
+ assert!(c.slider_track_override.is_none());
1498
+ assert!(c.slider_border.is_none());
1499
+ }
1500
+
1501
+ #[test]
1502
+ fn colours_section_marks_failure_on_malformed_rgb() {
1503
+ let s = "[Colours]\r\nCombo1:not,a,color\r\n";
1504
+ let c = parse_colours_section(s);
1505
+ assert!(c.combo_colors.is_empty());
1506
+ assert!(c.had_parse_failure);
1507
+ }
1508
+
1509
+ #[test]
1510
+ fn breaks_extracted_from_events() {
1511
+ let s = "[Events]\r\n\
1512
+ 0,0,\"bg.jpg\",0,0\r\n\
1513
+ 2,1000,2000\r\n\
1514
+ Break,5000,7500\r\n\
1515
+ Sprite,Foreground,Centre,\"sb.png\",320,240\r\n\
1516
+ F,0,0,1000,0,1\r\n";
1517
+ let breaks = parse_breaks_from_events(s);
1518
+ assert_eq!(breaks.len(), 2);
1519
+ assert_eq!(breaks[0].start_time_ms, 1000);
1520
+ assert_eq!(breaks[0].end_time_ms, 2000);
1521
+ assert_eq!(breaks[1].start_time_ms, 5000);
1522
+ assert_eq!(breaks[1].end_time_ms, 7500);
1523
+ // Indented child commands (`F,...`) must NOT be misread as a break
1524
+ // (they're under a sprite, not break events).
1525
+ }
1526
+
1527
+ #[test]
1528
+ fn background_event_offset_extracted() {
1529
+ let s = "[Events]\r\n0,0,\"bg.jpg\",16,-32\r\n";
1530
+ let bg = parse_background_event(s).expect("background event");
1531
+ assert_eq!(bg.x, Some(16));
1532
+ assert_eq!(bg.y, Some(-32));
1533
+ }
1534
+
1535
+ #[test]
1536
+ fn background_event_offset_optional_when_omitted() {
1537
+ let s = "[Events]\r\n0,0,\"bg.jpg\"\r\n";
1538
+ let bg = parse_background_event(s).expect("background event");
1539
+ assert!(bg.x.is_none());
1540
+ assert!(bg.y.is_none());
1541
+ }
1542
+
1543
+ #[test]
1544
+ fn video_event_start_time_extracted() {
1545
+ let s = "[Events]\r\nVideo,-1500,\"intro.mp4\"\r\n";
1546
+ let v = parse_video_event(s).expect("video event");
1547
+ assert_eq!(v.start_time_ms, Some(-1500));
1548
+ }
1549
+
1550
+ #[test]
1551
+ fn video_event_numeric_form() {
1552
+ let s = "[Events]\r\n1,2000,\"v.mp4\"\r\n";
1553
+ let v = parse_video_event(s).expect("video event");
1554
+ assert_eq!(v.start_time_ms, Some(2000));
1555
+ }
1556
+
1557
+ #[test]
1558
+ fn edge_sounds_parsed_from_pipe_delimited() {
1559
+ assert_eq!(parse_edge_sounds("2|0|8"), vec![2, 0, 8]);
1560
+ assert_eq!(parse_edge_sounds("0"), vec![0]);
1561
+ // Non-numeric tokens default to 0 (osu's lenient behavior).
1562
+ assert_eq!(parse_edge_sounds("2|x|8"), vec![2, 0, 8]);
1563
+ }
1564
+
1565
+ #[test]
1566
+ fn edge_sets_parsed_from_pipe_delimited() {
1567
+ assert_eq!(
1568
+ parse_edge_sets("0:0|1:0|0:0"),
1569
+ vec!["0:0".to_string(), "1:0".to_string(), "0:0".to_string()]
1570
+ );
1571
+ }
1572
+
1573
+ #[test]
1574
+ fn slider_emits_parsed_edge_lists_alongside_raw() {
1575
+ // 1 slide, edge_sounds 2|0, edge_sets 0:0|1:0
1576
+ let text = "[HitObjects]\r\n100,100,2000,2,0,L|200:200,1,100,2|0,0:0|1:0,0:0:0:0:\r\n";
1577
+ let v = parse_hit_objects_section(text);
1578
+ let s = v[0].slider.as_ref().unwrap();
1579
+ assert_eq!(s.edge_sounds.as_deref(), Some(&[2, 0][..]));
1580
+ assert_eq!(
1581
+ s.edge_sets.as_ref().map(Vec::as_slice),
1582
+ Some(&["0:0".to_string(), "1:0".to_string()][..])
1583
+ );
1584
+ // Raw forms preserved for round-trip.
1585
+ assert_eq!(s.edge_sounds_raw.as_deref(), Some("2|0"));
1586
+ assert_eq!(s.edge_sets_raw.as_deref(), Some("0:0|1:0"));
1587
+ }
1588
+
1589
+ #[test]
1590
+ fn slider_end_time_computed_from_pixel_length_and_active_timing() {
1591
+ // Red TP at t=0 with beat_length=500ms (= 120 BPM). Slider at t=1000
1592
+ // with pixel_length=100, slides=1, no inherited TP active so SV=1.0.
1593
+ // SliderMultiplier=1.4. Expected:
1594
+ // slide_duration = 100 / (1.4 * 100 * 1.0) * 500 ≈ 357.14 ms
1595
+ // end_time = 1000 + 357.14 ≈ 1357
1596
+ let tps_text = "[TimingPoints]\r\n0,500,4,2,1,60,1,0\r\n";
1597
+ let hos_text = "[HitObjects]\r\n100,100,1000,2,0,L|200:200,1,100,0|0,0:0|0:0,0:0:0:0:\r\n";
1598
+ let tps = parse_timing_points_section(tps_text);
1599
+ let mut hos = parse_hit_objects_section(hos_text);
1600
+ // Pre-condition: parser leaves slider end_time_ms unset.
1601
+ assert!(hos[0].end_time_ms.is_none());
1602
+ compute_slider_end_times(&mut hos, 1.4, &tps);
1603
+ let end = hos[0].end_time_ms.expect("slider end_time should be set");
1604
+ assert!(
1605
+ (1355..=1359).contains(&end),
1606
+ "expected slider end ~1357, got {end}"
1607
+ );
1608
+ }
1609
+
1610
+ #[test]
1611
+ fn slider_end_time_respects_inherited_sv_doubler() {
1612
+ // Red TP at 0 with beat_length=500ms, green TP at 1500 with
1613
+ // beat_length=-50 (= 2x SV). Slider at 2000 with pixel_length=100,
1614
+ // slides=1, SliderMultiplier=1.0:
1615
+ // slide_duration = 100 / (1.0 * 100 * 2.0) * 500 = 250 ms
1616
+ // end_time = 2000 + 250 = 2250
1617
+ let tps_text = "[TimingPoints]\r\n0,500,4,2,1,60,1,0\r\n1500,-50,4,2,1,60,0,0\r\n";
1618
+ let hos_text = "[HitObjects]\r\n100,100,2000,2,0,L|200:200,1,100,0|0,0:0|0:0,0:0:0:0:\r\n";
1619
+ let tps = parse_timing_points_section(tps_text);
1620
+ let mut hos = parse_hit_objects_section(hos_text);
1621
+ compute_slider_end_times(&mut hos, 1.0, &tps);
1622
+ assert_eq!(hos[0].end_time_ms, Some(2250));
1623
+ }
1624
+
1625
+ #[test]
1626
+ fn slider_end_time_handles_repeats() {
1627
+ // Same as the basic case but slides=3 (two repeats). Total duration
1628
+ // triples.
1629
+ let tps_text = "[TimingPoints]\r\n0,500,4,2,1,60,1,0\r\n";
1630
+ let hos_text =
1631
+ "[HitObjects]\r\n100,100,1000,2,0,L|200:200,3,100,0|0|0|0,0:0|0:0|0:0|0:0,0:0:0:0:\r\n";
1632
+ let tps = parse_timing_points_section(tps_text);
1633
+ let mut hos = parse_hit_objects_section(hos_text);
1634
+ compute_slider_end_times(&mut hos, 1.4, &tps);
1635
+ let end = hos[0].end_time_ms.expect("slider end_time should be set");
1636
+ // slide_duration ≈ 357.14 ms × 3 = 1071.43 ms; end ≈ 2071.
1637
+ assert!(
1638
+ (2069..=2073).contains(&end),
1639
+ "expected slider end ~2071, got {end}"
1640
+ );
1641
+ }
1642
+
1643
+ #[test]
1644
+ fn slider_end_time_skipped_when_already_set() {
1645
+ // Idempotency: an existing end_time_ms is left alone.
1646
+ let tps_text = "[TimingPoints]\r\n0,500,4,2,1,60,1,0\r\n";
1647
+ let hos_text = "[HitObjects]\r\n100,100,1000,2,0,L|200:200,1,100,0|0,0:0|0:0,0:0:0:0:\r\n";
1648
+ let tps = parse_timing_points_section(tps_text);
1649
+ let mut hos = parse_hit_objects_section(hos_text);
1650
+ hos[0].end_time_ms = Some(9999);
1651
+ compute_slider_end_times(&mut hos, 1.4, &tps);
1652
+ assert_eq!(hos[0].end_time_ms, Some(9999));
1653
+ }
1654
+
1655
+ #[test]
1656
+ fn slider_end_time_skipped_for_non_sliders() {
1657
+ // Spinner (type=12) has its own end_time path; circle has none. Both
1658
+ // should pass through compute_slider_end_times untouched.
1659
+ let tps_text = "[TimingPoints]\r\n0,500,4,2,1,60,1,0\r\n";
1660
+ let hos_text = "[HitObjects]\r\n256,192,1000,1,0,0:0:0:0:\r\n\
1661
+ 256,192,2000,12,0,3000,0:0:0:0:\r\n";
1662
+ let tps = parse_timing_points_section(tps_text);
1663
+ let mut hos = parse_hit_objects_section(hos_text);
1664
+ compute_slider_end_times(&mut hos, 1.4, &tps);
1665
+ // Circle: no end time.
1666
+ assert!(hos[0].end_time_ms.is_none());
1667
+ // Spinner: end time from its own raw param, untouched by this pass.
1668
+ assert_eq!(hos[1].end_time_ms, Some(3000));
1669
+ }
1670
+
1671
+ #[test]
1672
+ fn parse_populates_slider_end_times_end_to_end() {
1673
+ // Slider at time 3500 with pixel_length=100, slides=1. Red TP at 0
1674
+ // (beat_length=500) and green TP at 1000 (beat_length=-50, SV=2.0).
1675
+ // SliderMultiplier=1.4. Expected:
1676
+ // slide_duration = 100 / (1.4 * 100 * 2.0) * 500 ≈ 178.57 ms
1677
+ // end_time ≈ 3500 + 179 = 3679
1678
+ let osu = "osu file format v14\r\n\r\n\
1679
+ [General]\r\nAudioFilename: a.mp3\r\nMode: 0\r\n\r\n\
1680
+ [Metadata]\r\nTitle:T\r\nTitleUnicode:T\r\nArtist:A\r\nArtistUnicode:A\r\n\
1681
+ Creator:c\r\nVersion:Hard\r\nSource:\r\nTags:\r\nBeatmapID:1\r\nBeatmapSetID:1\r\n\r\n\
1682
+ [Difficulty]\r\nHPDrainRate:5\r\nCircleSize:4\r\nOverallDifficulty:6\r\n\
1683
+ ApproachRate:7\r\nSliderMultiplier:1.4\r\nSliderTickRate:1\r\n\r\n\
1684
+ [Events]\r\n[TimingPoints]\r\n0,500,4,2,1,60,1,0\r\n1000,-50,4,2,1,60,0,0\r\n\r\n\
1685
+ [HitObjects]\r\n100,100,3500,2,0,L|200:200,1,100,0|0,0:0|0:0,0:0:0:0:\r\n";
1686
+ let p = parse(
1687
+ osu.as_bytes(),
1688
+ "deadbeef".to_string(),
1689
+ None,
1690
+ None,
1691
+ "test.osu".to_string(),
1692
+ "test.osu".to_string(),
1693
+ );
1694
+ let slider = p
1695
+ .hit_objects
1696
+ .iter()
1697
+ .find(|h| matches!(h.common_kind, HitObjectCommonKind::Slider))
1698
+ .expect("fixture has a slider");
1699
+ let end = slider
1700
+ .end_time_ms
1701
+ .expect("slider end_time should be filled by parse()");
1702
+ assert!(
1703
+ (3675..=3683).contains(&end),
1704
+ "expected slider end ~3679, got {end}"
1705
+ );
1706
+ }
1707
+
1708
+ #[test]
1709
+ fn hit_sample_parsed_into_typed_components() {
1710
+ // normal=1, addition=2, index=3, volume=80, filename="custom.wav"
1711
+ let s = parse_hit_sample_field("1:2:3:80:custom.wav").expect("hit sample");
1712
+ assert_eq!(s.normal_set, Some(1));
1713
+ assert_eq!(s.addition_set, Some(2));
1714
+ assert_eq!(s.index, Some(3));
1715
+ assert_eq!(s.volume, Some(80));
1716
+ assert_eq!(s.filename.as_deref(), Some("custom.wav"));
1717
+ }
1718
+
1719
+ #[test]
1720
+ fn hit_sample_handles_short_fields() {
1721
+ // Partial: only first three fields populated.
1722
+ let s = parse_hit_sample_field("1:0:0").expect("hit sample");
1723
+ assert_eq!(s.normal_set, Some(1));
1724
+ assert_eq!(s.addition_set, Some(0));
1725
+ assert_eq!(s.index, Some(0));
1726
+ assert!(s.volume.is_none());
1727
+ assert!(s.filename.is_none());
1728
+ }
1729
+
1730
+ #[test]
1731
+ fn hit_sample_propagates_to_circle_via_parse_hit_objects_section() {
1732
+ let text = "[HitObjects]\r\n256,192,1000,1,0,2:1:5:60:custom.wav\r\n";
1733
+ let v = parse_hit_objects_section(text);
1734
+ let hs = v[0].hit_sample.as_ref().expect("hit sample populated");
1735
+ assert_eq!(hs.normal_set, Some(2));
1736
+ assert_eq!(hs.addition_set, Some(1));
1737
+ assert_eq!(hs.index, Some(5));
1738
+ assert_eq!(hs.volume, Some(60));
1739
+ assert_eq!(hs.filename.as_deref(), Some("custom.wav"));
1740
+ }
1741
+
1742
+ #[test]
1743
+ fn fixture_with_offset_background_and_video_populates_fields() {
1744
+ // Re-use FIXTURE which has `0,0,"bg.jpg",0,0` and `Video,0,...`.
1745
+ let p = parse(
1746
+ FIXTURE.as_bytes(),
1747
+ "deadbeef".to_string(),
1748
+ None,
1749
+ None,
1750
+ "test.osu".to_string(),
1751
+ "test.osu".to_string(),
1752
+ );
1753
+ let f = p.fields.expect("fields populated");
1754
+ assert_eq!(f.background_x, Some(0));
1755
+ assert_eq!(f.background_y, Some(0));
1756
+ assert_eq!(f.video_start_time_ms, Some(0));
1757
+ // FIXTURE has one break event (`2,1000,2000`).
1758
+ assert_eq!(p.breaks.len(), 1);
1759
+ assert_eq!(p.breaks[0].start_time_ms, 1000);
1760
+ assert_eq!(p.breaks[0].end_time_ms, 2000);
1761
+ }
1762
+
1763
+ #[test]
1764
+ fn bom_is_stripped_before_scan() {
1765
+ let mut bytes = vec![0xEF, 0xBB, 0xBF];
1766
+ bytes.extend_from_slice(FIXTURE.as_bytes());
1767
+ let p = parse(
1768
+ &bytes,
1769
+ "x".to_string(),
1770
+ None,
1771
+ None,
1772
+ "test.osu".to_string(),
1773
+ "test.osu".to_string(),
1774
+ );
1775
+ assert_ne!(p.parse_status, ParseStatus::Failed);
1776
+ assert!(p.sections.iter().any(|s| s.section_name == "[General]"));
1777
+ }
1778
+ }
crates/osu_indexer/src/output.rs ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //! NDJSON emission, junk-file filter, and media-kind classification.
2
+ //!
3
+ //! Tables emitted (matching `schemas/v1/*.schema.json`):
4
+ //! archive_revisions, set_revisions, logical_files,
5
+ //! beatmaps, osu_sections, timing_points,
6
+ //! hit_objects_common, hit_objects_{osu,taiko,catch,mania},
7
+ //! storyboard_sources, storyboard_elements, storyboard_commands, storyboard_variables,
8
+ //! asset_references, difficulty_attributes, problems.
9
+
10
+ use anyhow::Result;
11
+ use serde::Serialize;
12
+ use std::io::Write;
13
+
14
+ /// Serialize `row` as JSON, splice in a `_table` field, and write a newline.
15
+ pub fn emit<T: Serialize, W: Write>(table: &str, row: &T, w: &mut W) -> Result<()> {
16
+ let mut v = serde_json::to_value(row)?;
17
+ if let serde_json::Value::Object(ref mut m) = v {
18
+ m.insert(
19
+ "_table".to_string(),
20
+ serde_json::Value::String(table.to_string()),
21
+ );
22
+ }
23
+ serde_json::to_writer(&mut *w, &v)?;
24
+ w.write_all(b"\n")?;
25
+ Ok(())
26
+ }
27
+
28
+ /// Junk-file filter. Matches against the casefolded
29
+ /// `path_key` (which already has the slash-normalized, NFC-normalized,
30
+ /// lowercased form) plus the basename.
31
+ ///
32
+ /// Returns `Some(pattern_label)` to log alongside the skip, or `None` if the
33
+ /// path is not junk.
34
+ pub fn match_junk(path_key: &str) -> Option<&'static str> {
35
+ let basename = path_key.rsplit('/').next().unwrap_or(path_key);
36
+
37
+ if basename == "thumbs.db" {
38
+ return Some("Thumbs.db");
39
+ }
40
+ if basename == "desktop.ini" {
41
+ return Some("desktop.ini");
42
+ }
43
+ if basename == ".ds_store" {
44
+ return Some(".DS_Store");
45
+ }
46
+ if basename.starts_with("~$") {
47
+ return Some("~$* (Office lock)");
48
+ }
49
+ if basename.ends_with(".bak") {
50
+ return Some("*.bak");
51
+ }
52
+ if basename.ends_with(".swp") || basename.ends_with(".swo") {
53
+ return Some("*.swp/*.swo");
54
+ }
55
+ if basename.ends_with(".tmp") {
56
+ return Some("*.tmp");
57
+ }
58
+
59
+ for seg in path_key.split('/') {
60
+ match seg {
61
+ "__macosx" => return Some("__MACOSX/"),
62
+ ".git" => return Some(".git/"),
63
+ "node_modules" => return Some("node_modules/"),
64
+ _ => {}
65
+ }
66
+ }
67
+
68
+ None
69
+ }
70
+
71
+ /// Map an extension (lowercase, no dot) to a `media_kind` enum value.
72
+ /// Aligned with logical-file schema media kinds:
73
+ /// audio | image | video | osu | osb | text | archive | font | skin_asset | unknown.
74
+ ///
75
+ /// `skin_asset` is intentionally not assigned here — it requires reference
76
+ /// resolution to confirm a file is referenced as a skin element.
77
+ pub fn classify_media_kind(extension: Option<&str>) -> &'static str {
78
+ let Some(ext) = extension else {
79
+ return "unknown";
80
+ };
81
+ match ext {
82
+ "mp3" | "ogg" | "wav" | "flac" | "m4a" | "opus" | "aac" => "audio",
83
+ "jpg" | "jpeg" | "png" | "gif" | "webp" | "bmp" => "image",
84
+ "mp4" | "mkv" | "avi" | "mov" | "webm" | "flv" | "wmv" | "m4v" => "video",
85
+ "osu" => "osu",
86
+ "osb" => "osb",
87
+ "txt" | "log" | "md" | "ini" | "cfg" => "text",
88
+ "zip" | "rar" | "7z" | "tar" | "gz" => "archive",
89
+ "ttf" | "otf" | "woff" | "woff2" => "font",
90
+ _ => "unknown",
91
+ }
92
+ }
93
+
94
+ /// Default `roles` assignment before reference resolution refines asset roles.
95
+ pub fn classify_roles(extension: Option<&str>) -> Vec<String> {
96
+ match extension {
97
+ Some("osu") => vec!["beatmap_osu".to_string()],
98
+ Some("osb") => vec!["storyboard_osb".to_string()],
99
+ _ => vec!["unknown".to_string()],
100
+ }
101
+ }
102
+
103
+ #[cfg(test)]
104
+ mod tests {
105
+ use super::*;
106
+
107
+ #[test]
108
+ fn match_junk_basics() {
109
+ assert_eq!(match_junk("thumbs.db"), Some("Thumbs.db"));
110
+ assert_eq!(match_junk("song/thumbs.db"), Some("Thumbs.db"));
111
+ assert_eq!(match_junk("desktop.ini"), Some("desktop.ini"));
112
+ assert_eq!(match_junk(".ds_store"), Some(".DS_Store"));
113
+ assert_eq!(match_junk("a/b/.ds_store"), Some(".DS_Store"));
114
+ assert_eq!(match_junk("__macosx/foo"), Some("__MACOSX/"));
115
+ assert_eq!(match_junk("a/__macosx/b/c"), Some("__MACOSX/"));
116
+ assert_eq!(match_junk(".git/index"), Some(".git/"));
117
+ assert_eq!(
118
+ match_junk("project/node_modules/foo"),
119
+ Some("node_modules/")
120
+ );
121
+ assert_eq!(match_junk("foo.bak"), Some("*.bak"));
122
+ assert_eq!(match_junk("~$report.docx"), Some("~$* (Office lock)"));
123
+ assert_eq!(match_junk("foo.swp"), Some("*.swp/*.swo"));
124
+ assert_eq!(match_junk("foo.tmp"), Some("*.tmp"));
125
+ }
126
+
127
+ #[test]
128
+ fn match_junk_negatives() {
129
+ assert_eq!(match_junk("audio.mp3"), None);
130
+ assert_eq!(match_junk("song [Hard].osu"), None);
131
+ assert_eq!(match_junk("background.jpg"), None);
132
+ // ".git" as a substring of another segment is fine.
133
+ assert_eq!(match_junk("not-git/foo.txt"), None);
134
+ // backups inside a segment that doesn't end in .bak are fine.
135
+ assert_eq!(match_junk("backup-data/foo.txt"), None);
136
+ }
137
+
138
+ #[test]
139
+ fn classify_media_kind_known_extensions() {
140
+ assert_eq!(classify_media_kind(Some("mp3")), "audio");
141
+ assert_eq!(classify_media_kind(Some("ogg")), "audio");
142
+ assert_eq!(classify_media_kind(Some("jpg")), "image");
143
+ assert_eq!(classify_media_kind(Some("png")), "image");
144
+ assert_eq!(classify_media_kind(Some("mp4")), "video");
145
+ assert_eq!(classify_media_kind(Some("osu")), "osu");
146
+ assert_eq!(classify_media_kind(Some("osb")), "osb");
147
+ assert_eq!(classify_media_kind(Some("ttf")), "font");
148
+ assert_eq!(classify_media_kind(Some("xyz")), "unknown");
149
+ assert_eq!(classify_media_kind(None), "unknown");
150
+ }
151
+
152
+ #[test]
153
+ fn emit_writes_one_line_with_table_field() {
154
+ #[derive(Serialize)]
155
+ struct Row {
156
+ a: i32,
157
+ }
158
+ let mut buf = Vec::<u8>::new();
159
+ emit("test_table", &Row { a: 7 }, &mut buf).unwrap();
160
+ let s = String::from_utf8(buf).unwrap();
161
+ assert!(s.ends_with('\n'));
162
+ let v: serde_json::Value = serde_json::from_str(s.trim()).unwrap();
163
+ assert_eq!(v["_table"], "test_table");
164
+ assert_eq!(v["a"], 7);
165
+ }
166
+
167
+ #[test]
168
+ fn classify_roles_recognizes_osu_and_osb() {
169
+ assert_eq!(classify_roles(Some("osu")), vec!["beatmap_osu".to_string()]);
170
+ assert_eq!(
171
+ classify_roles(Some("osb")),
172
+ vec!["storyboard_osb".to_string()]
173
+ );
174
+ assert_eq!(classify_roles(Some("mp3")), vec!["unknown".to_string()]);
175
+ assert_eq!(classify_roles(None), vec!["unknown".to_string()]);
176
+ }
177
+ }
crates/osu_indexer/src/paths.rs ADDED
@@ -0,0 +1,315 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //! Path normalization, validation, and warning detection.
2
+ //!
3
+ //! Five path forms are tracked:
4
+ //! * `raw` decoded UTF-8, if decodable
5
+ //! * `raw_bytes_base64` always populated (source of truth for reconstruction)
6
+ //! * `posix` `raw` with backslashes → forward slashes
7
+ //! * `nfc` Unicode-NFC-normalized `posix`
8
+ //! * `key` casefolded `nfc` (lookup-only)
9
+ //!
10
+ //! Flags emitted (semicolon-joined into `logical_files.path_warning`):
11
+ //! path_traversal, absolute_path, invalid_unicode, unsafe_name.
12
+ //! `duplicate_path_key` and `case_collision` are detected at the archive
13
+ //! walk layer (need full member set), not here.
14
+ //! `zero_byte_file` is enforced by the junk filter; no logical_files row is
15
+ //! emitted for these so this flag is unused in practice.
16
+
17
+ use base64::engine::general_purpose::STANDARD as B64;
18
+ use base64::Engine;
19
+ use unicode_normalization::UnicodeNormalization;
20
+
21
+ pub const WARN_TRAVERSAL: &str = "path_traversal";
22
+ pub const WARN_ABSOLUTE: &str = "absolute_path";
23
+ pub const WARN_INVALID_UNICODE: &str = "invalid_unicode";
24
+ pub const WARN_UNSAFE_NAME: &str = "unsafe_name";
25
+
26
+ #[derive(Debug, Clone)]
27
+ pub struct NormalizedPath {
28
+ pub raw: Option<String>,
29
+ pub raw_bytes_base64: String,
30
+ pub posix: Option<String>,
31
+ pub nfc: Option<String>,
32
+ pub key: String,
33
+ pub warnings: Vec<&'static str>,
34
+ /// Set when the original ZIP entry name ends in '/' — by convention a
35
+ /// directory marker rather than a real file.
36
+ pub is_dir_marker: bool,
37
+ /// Lowercase extension (without the dot), recovered even when `posix` is
38
+ /// None — extensions are virtually always ASCII (.osu, .osb, .mp3, .jpg)
39
+ /// and survive any byte-level encoding. This is what classifies a 2008-era
40
+ /// Shift-JIS-named `Kenji Ninuma - DISCO★PRINCE [Normal].osu` as media_kind=osu.
41
+ pub extension: Option<String>,
42
+ }
43
+
44
+ /// Decode raw ZIP-name bytes into the five variants and run safety checks.
45
+ ///
46
+ /// Decoding is UTF-8-only: ZIP entries from osu! clients are virtually always
47
+ /// UTF-8 (post-2008 MapsetSerializer). Falling back to CP437/CP932 introduces
48
+ /// guesswork; we'd rather flag `invalid_unicode` and preserve raw bytes via
49
+ /// base64 so reconstruction is lossless.
50
+ pub fn normalize(raw_bytes: &[u8]) -> NormalizedPath {
51
+ let raw_bytes_base64 = B64.encode(raw_bytes);
52
+ let raw = std::str::from_utf8(raw_bytes).ok().map(String::from);
53
+
54
+ let mut warnings: Vec<&'static str> = Vec::new();
55
+ if raw.is_none() {
56
+ warnings.push(WARN_INVALID_UNICODE);
57
+ }
58
+
59
+ let posix = raw.as_ref().map(|s| s.replace('\\', "/"));
60
+ let is_dir_marker = posix.as_deref().is_some_and(|s| s.ends_with('/'));
61
+
62
+ if let Some(p) = posix.as_deref() {
63
+ if is_absolute(p) {
64
+ warnings.push(WARN_ABSOLUTE);
65
+ }
66
+ if has_traversal(p) {
67
+ warnings.push(WARN_TRAVERSAL);
68
+ }
69
+ if has_unsafe_chars(p) {
70
+ warnings.push(WARN_UNSAFE_NAME);
71
+ }
72
+ }
73
+
74
+ let nfc = posix.as_deref().map(|s| s.nfc().collect::<String>());
75
+
76
+ // path_key: casefolded NFC. Rust's str::to_lowercase is Unicode-aware and
77
+ // close enough for our purposes — true Unicode casefolding (which folds
78
+ // German ß → ss, etc.) requires the `caseless` crate. Osu paths are
79
+ // overwhelmingly ASCII; the few non-ASCII titles round-trip fine through
80
+ // to_lowercase(). Revisit if real collisions ever appear in problems.parquet.
81
+ //
82
+ // For undecodable bytes we fall back to a hex-prefixed key so it still
83
+ // uniquely identifies the entry (no NUL bytes, safe for joining).
84
+ let key = match nfc.as_deref() {
85
+ Some(n) => n.to_lowercase(),
86
+ None => format!("invalid:{}", hex::encode(raw_bytes)),
87
+ };
88
+
89
+ let extension = match posix.as_deref() {
90
+ Some(p) => extension(p),
91
+ None => extension_from_raw(raw_bytes),
92
+ };
93
+
94
+ NormalizedPath {
95
+ raw,
96
+ raw_bytes_base64,
97
+ posix,
98
+ nfc,
99
+ key,
100
+ warnings,
101
+ is_dir_marker,
102
+ extension,
103
+ }
104
+ }
105
+
106
+ /// Extract a lowercase ASCII extension directly from raw ZIP-name bytes,
107
+ /// without requiring UTF-8 decoding. The strategy is conservative: we only
108
+ /// accept an extension if every byte after the final dot in the basename is
109
+ /// ASCII alphanumeric. This is enough for `.osu`, `.osb`, `.mp3`, `.jpg`, etc.
110
+ fn extension_from_raw(raw_bytes: &[u8]) -> Option<String> {
111
+ let last_sep = raw_bytes
112
+ .iter()
113
+ .rposition(|&b| b == b'/' || b == b'\\')
114
+ .map(|i| i + 1)
115
+ .unwrap_or(0);
116
+ let basename = &raw_bytes[last_sep..];
117
+ let dot = basename.iter().rposition(|&b| b == b'.')?;
118
+ if dot == 0 {
119
+ return None;
120
+ }
121
+ let ext = &basename[dot + 1..];
122
+ if ext.is_empty() || !ext.iter().all(|b| b.is_ascii_alphanumeric()) {
123
+ return None;
124
+ }
125
+ // Safe: we just verified every byte is ASCII alphanumeric.
126
+ Some(std::str::from_utf8(ext).ok()?.to_ascii_lowercase())
127
+ }
128
+
129
+ /// True when `path_posix` looks absolute (POSIX root, Windows drive prefix, or
130
+ /// UNC/server share). Operates on the slash-normalized form.
131
+ fn is_absolute(p: &str) -> bool {
132
+ if p.starts_with('/') {
133
+ return true;
134
+ }
135
+ let bytes = p.as_bytes();
136
+ // Windows drive: "C:" / "C:/foo".
137
+ if bytes.len() >= 2 && bytes[1] == b':' && bytes[0].is_ascii_alphabetic() {
138
+ return true;
139
+ }
140
+ false
141
+ }
142
+
143
+ /// True when any path segment is exactly `..` (the dangerous one).
144
+ /// "..." or "..foo" are weird but not traversal.
145
+ fn has_traversal(p: &str) -> bool {
146
+ p.split('/').any(|seg| seg == "..")
147
+ }
148
+
149
+ /// True when the path contains NUL or any C0 control character. These can't
150
+ /// be safely materialized to disk and almost always indicate corruption.
151
+ fn has_unsafe_chars(p: &str) -> bool {
152
+ p.bytes().any(|b| b < 0x20)
153
+ }
154
+
155
+ /// Return `(aa, bb)` — the first two and next two hex chars of a SHA-256 —
156
+ /// used for sharded blob/archive paths under `sha256/aa/bb/<full>.bin`.
157
+ pub fn shard(sha256_hex: &str) -> (String, String) {
158
+ debug_assert!(sha256_hex.len() >= 4, "sha256 hex must be ≥ 4 chars");
159
+ (sha256_hex[0..2].to_string(), sha256_hex[2..4].to_string())
160
+ }
161
+
162
+ /// Lowercase extension of `path_posix` (without the dot). None if the basename
163
+ /// has no dot or only a leading dot ("dotfile").
164
+ pub fn extension(path_posix: &str) -> Option<String> {
165
+ let basename = path_posix.rsplit('/').next().unwrap_or(path_posix);
166
+ let dot = basename.rfind('.')?;
167
+ if dot == 0 {
168
+ return None;
169
+ }
170
+ Some(basename[dot + 1..].to_lowercase())
171
+ }
172
+
173
+ #[cfg(test)]
174
+ mod tests {
175
+ use super::*;
176
+
177
+ #[test]
178
+ fn ascii_plain_path() {
179
+ let n = normalize(b"audio.mp3");
180
+ assert_eq!(n.raw.as_deref(), Some("audio.mp3"));
181
+ assert_eq!(n.posix.as_deref(), Some("audio.mp3"));
182
+ assert_eq!(n.nfc.as_deref(), Some("audio.mp3"));
183
+ assert_eq!(n.key, "audio.mp3");
184
+ assert!(n.warnings.is_empty());
185
+ assert!(!n.is_dir_marker);
186
+ }
187
+
188
+ #[test]
189
+ fn backslash_to_posix() {
190
+ let n = normalize(b"sb\\Typography\\0030.png");
191
+ assert_eq!(n.posix.as_deref(), Some("sb/Typography/0030.png"));
192
+ assert_eq!(n.key, "sb/typography/0030.png");
193
+ assert!(n.warnings.is_empty());
194
+ }
195
+
196
+ #[test]
197
+ fn dir_marker_trailing_slash() {
198
+ let n = normalize(b"subdir/");
199
+ assert!(n.is_dir_marker);
200
+ }
201
+
202
+ #[test]
203
+ fn casefold_lookup_key() {
204
+ let a = normalize(b"Audio.MP3").key;
205
+ let b = normalize(b"audio.mp3").key;
206
+ assert_eq!(a, b);
207
+ }
208
+
209
+ #[test]
210
+ fn nfc_normalization() {
211
+ // U+00C5 (Å precomposed) vs. U+0041 U+030A (A + combining ring).
212
+ let composed = normalize("\u{00C5}.png".as_bytes());
213
+ let decomposed = normalize("A\u{030A}.png".as_bytes());
214
+ assert_eq!(composed.nfc, decomposed.nfc);
215
+ assert_eq!(composed.key, decomposed.key);
216
+ }
217
+
218
+ #[test]
219
+ fn absolute_path_posix_root() {
220
+ let n = normalize(b"/etc/passwd");
221
+ assert!(n.warnings.contains(&WARN_ABSOLUTE));
222
+ }
223
+
224
+ #[test]
225
+ fn absolute_path_windows_drive() {
226
+ let n = normalize(b"C:/Windows/system32/cmd.exe");
227
+ assert!(n.warnings.contains(&WARN_ABSOLUTE));
228
+ }
229
+
230
+ #[test]
231
+ fn traversal_segment() {
232
+ let n = normalize(b"foo/../etc/passwd");
233
+ assert!(n.warnings.contains(&WARN_TRAVERSAL));
234
+ }
235
+
236
+ #[test]
237
+ fn dot_dot_in_filename_is_not_traversal() {
238
+ let n = normalize(b"foo/..bar.txt");
239
+ assert!(!n.warnings.contains(&WARN_TRAVERSAL));
240
+ }
241
+
242
+ #[test]
243
+ fn nul_byte_unsafe() {
244
+ let n = normalize(b"foo\0bar.txt");
245
+ assert!(n.warnings.contains(&WARN_UNSAFE_NAME));
246
+ }
247
+
248
+ #[test]
249
+ fn invalid_utf8() {
250
+ let n = normalize(&[0xff, 0xfe, 0xfd]);
251
+ assert!(n.raw.is_none());
252
+ assert!(n.posix.is_none());
253
+ assert!(n.warnings.contains(&WARN_INVALID_UNICODE));
254
+ // Key stays unique via hex-encoded fallback.
255
+ assert!(n.key.starts_with("invalid:"));
256
+ // base64 of [0xff,0xfe,0xfd] = "//79".
257
+ assert_eq!(n.raw_bytes_base64, "//79");
258
+ }
259
+
260
+ #[test]
261
+ fn extension_recovered_from_undecodable_path() {
262
+ // The actual filename of beatmap 1's hardest difficulty:
263
+ // "Kenji Ninuma - DISCO\x81\x9aPRINCE (peppy) [Normal].osu"
264
+ // where \x81\x9a is Shift-JIS for ★. UTF-8 decoding fails, but the
265
+ // .osu suffix is plain ASCII so we still recover the extension.
266
+ let mut bytes = b"Kenji Ninuma - DISCO".to_vec();
267
+ bytes.extend_from_slice(&[0x81, 0x9a]);
268
+ bytes.extend_from_slice(b"PRINCE (peppy) [Normal].osu");
269
+
270
+ let n = normalize(&bytes);
271
+ assert!(
272
+ n.posix.is_none(),
273
+ "Shift-JIS path should not decode as UTF-8"
274
+ );
275
+ assert!(n.warnings.contains(&WARN_INVALID_UNICODE));
276
+ assert_eq!(n.extension.as_deref(), Some("osu"));
277
+ }
278
+
279
+ #[test]
280
+ fn extension_field_matches_extension_helper_for_ascii_paths() {
281
+ let n = normalize(b"Folder/song.MP3");
282
+ assert_eq!(n.extension.as_deref(), Some("mp3"));
283
+ let n = normalize(b"README");
284
+ assert_eq!(n.extension, None);
285
+ }
286
+
287
+ #[test]
288
+ fn extension_simple() {
289
+ assert_eq!(extension("song.MP3").as_deref(), Some("mp3"));
290
+ assert_eq!(extension("a/b/c.OGG").as_deref(), Some("ogg"));
291
+ }
292
+
293
+ #[test]
294
+ fn extension_no_extension() {
295
+ assert_eq!(extension("README"), None);
296
+ assert_eq!(extension("a/b/README"), None);
297
+ }
298
+
299
+ #[test]
300
+ fn extension_dotfile() {
301
+ assert_eq!(extension(".gitignore"), None);
302
+ }
303
+
304
+ #[test]
305
+ fn extension_double_extension_takes_last() {
306
+ assert_eq!(extension("archive.tar.gz").as_deref(), Some("gz"));
307
+ }
308
+
309
+ #[test]
310
+ fn shard_takes_first_two_pairs() {
311
+ let (a, b) = shard("abcdef0123456789");
312
+ assert_eq!(a, "ab");
313
+ assert_eq!(b, "cd");
314
+ }
315
+ }
crates/osu_indexer/src/references.rs ADDED
@@ -0,0 +1,1034 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //! Asset reference extraction + five-phase resolution.
2
+ //!
3
+ //! Reference resolution order:
4
+ //! 1. exact raw path
5
+ //! 2. slash-normalized
6
+ //! 3. unicode-NFC normalized
7
+ //! 4. casefolded
8
+ //! 5. convention-based (hitsounds — extension swap and external_or_default)
9
+ //! 6. mark `missing` / `ambiguous` / `invalid_path`
10
+ //!
11
+ //! Extraction sites:
12
+ //! * `.osu [General]` → AudioFilename
13
+ //! * `.osu [Events]` → Background (event 0), Video (event 1),
14
+ //! Sprite (4), Sample (5), Animation (6)
15
+ //! * `.osu [HitObjects]` → explicit + derived hitsound candidates
16
+ //! * `.osb [Events]` → Sprite, Sample, Animation, Video
17
+ //!
18
+ //! Hitsound conventional names that don't match the archive are
19
+ //! `external_or_default_resource`, NOT `missing` (osu falls back to skin).
20
+ //! All other unmatched references are `missing`.
21
+
22
+ use std::collections::{BTreeSet, HashMap};
23
+
24
+ use unicode_normalization::UnicodeNormalization;
25
+
26
+ use crate::hitsounds::{self, SampleSet};
27
+ use crate::osu_parse::{ParsedBeatmap, RawHitObject, RawTimingPoint};
28
+ use crate::storyboard_parse::{split_storyboard_fields, StoryboardParse};
29
+
30
+ /// A reference extracted from a source file (.osu or .osb), prior to
31
+ /// resolution against the logical_files of its set revision.
32
+ #[derive(Debug, Clone)]
33
+ pub struct ExtractedReference {
34
+ pub source_logical_file_id: String,
35
+ pub source_path: String,
36
+ pub source_section: Option<String>,
37
+ pub source_context: String,
38
+ pub beatmap_uid: Option<String>,
39
+ pub reference_kind: ReferenceKind,
40
+ pub raw_reference: String,
41
+ pub animation_frame_index: Option<i32>,
42
+ pub raw_line: Option<String>,
43
+ }
44
+
45
+ /// Reference categories matching the `reference_kind` enum in
46
+ /// `schemas/v1/references.schema.json`.
47
+ #[allow(dead_code)]
48
+ #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
49
+ pub enum ReferenceKind {
50
+ AudioFilename,
51
+ BackgroundImage,
52
+ Video,
53
+ StoryboardSprite,
54
+ StoryboardAnimation,
55
+ StoryboardAnimationFrame,
56
+ StoryboardAudioSample,
57
+ ExplicitHitsoundSample,
58
+ DerivedCustomHitsoundSample,
59
+ CustomSkinAssetConventional,
60
+ Font,
61
+ Unknown,
62
+ }
63
+
64
+ impl ReferenceKind {
65
+ pub fn as_str(self) -> &'static str {
66
+ match self {
67
+ Self::AudioFilename => "audio_filename",
68
+ Self::BackgroundImage => "background_image",
69
+ Self::Video => "video",
70
+ Self::StoryboardSprite => "storyboard_sprite",
71
+ Self::StoryboardAnimation => "storyboard_animation",
72
+ Self::StoryboardAnimationFrame => "storyboard_animation_frame",
73
+ Self::StoryboardAudioSample => "storyboard_audio_sample",
74
+ Self::ExplicitHitsoundSample => "explicit_hitsound_sample",
75
+ Self::DerivedCustomHitsoundSample => "derived_custom_hitsound_sample",
76
+ Self::CustomSkinAssetConventional => "custom_skin_asset_conventional",
77
+ Self::Font => "font",
78
+ Self::Unknown => "unknown",
79
+ }
80
+ }
81
+
82
+ /// True for kinds whose conventional candidates fall back to default
83
+ /// skin resources rather than failing as `missing`.
84
+ fn is_conventional(self) -> bool {
85
+ matches!(
86
+ self,
87
+ Self::DerivedCustomHitsoundSample | Self::CustomSkinAssetConventional
88
+ )
89
+ }
90
+ }
91
+
92
+ /// Resolution outcomes matching the `resolution_status` enum.
93
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
94
+ pub enum ResolutionStatus {
95
+ FoundExact,
96
+ FoundSlashNormalized,
97
+ FoundUnicodeNormalized,
98
+ FoundCasefolded,
99
+ FoundByConvention,
100
+ Missing,
101
+ Ambiguous,
102
+ ExternalOrDefaultResource,
103
+ InvalidPath,
104
+ }
105
+
106
+ impl ResolutionStatus {
107
+ pub fn as_str(self) -> &'static str {
108
+ match self {
109
+ Self::FoundExact => "found_exact",
110
+ Self::FoundSlashNormalized => "found_slash_normalized",
111
+ Self::FoundUnicodeNormalized => "found_unicode_normalized",
112
+ Self::FoundCasefolded => "found_casefolded",
113
+ Self::FoundByConvention => "found_by_convention",
114
+ Self::Missing => "missing",
115
+ Self::Ambiguous => "ambiguous",
116
+ Self::ExternalOrDefaultResource => "external_or_default_resource",
117
+ Self::InvalidPath => "invalid_path",
118
+ }
119
+ }
120
+ }
121
+
122
+ /// One row's worth of resolved data, ready to be turned into an
123
+ /// `asset_references` Parquet row.
124
+ #[derive(Debug, Clone)]
125
+ pub struct ResolvedReference {
126
+ pub source_logical_file_id: String,
127
+ pub source_path: String,
128
+ pub source_section: Option<String>,
129
+ pub source_context: String,
130
+ pub beatmap_uid: Option<String>,
131
+ pub reference_kind: ReferenceKind,
132
+ pub raw_reference: String,
133
+ pub normalized_reference: String,
134
+ pub lookup_key: String,
135
+ pub resolved_logical_file_id: Option<String>,
136
+ pub resolved_blob_sha256: Option<String>,
137
+ pub resolved_path_posix: Option<String>,
138
+ pub resolution_status: ResolutionStatus,
139
+ pub is_missing: bool,
140
+ pub is_ambiguous: bool,
141
+ pub raw_line: Option<String>,
142
+ }
143
+
144
+ /// One file entry in the resolver index.
145
+ #[derive(Debug, Clone)]
146
+ pub struct LogicalFileEntry {
147
+ pub logical_file_id: String,
148
+ pub blob_sha256: String,
149
+ pub path_raw: Option<String>,
150
+ pub path_posix: Option<String>,
151
+ pub path_nfc: Option<String>,
152
+ pub path_key: String,
153
+ }
154
+
155
+ /// Pre-built lookup index over the logical_files of one set revision.
156
+ ///
157
+ /// Each phase tier is a separate hash map so we never rebuild keys per
158
+ /// reference. The casefolded tier holds a `Vec` so we can detect
159
+ /// ambiguity when multiple distinct blobs share the same path_key.
160
+ pub struct ResolverIndex<'a> {
161
+ by_raw: HashMap<&'a str, &'a LogicalFileEntry>,
162
+ by_posix: HashMap<&'a str, &'a LogicalFileEntry>,
163
+ by_nfc: HashMap<&'a str, &'a LogicalFileEntry>,
164
+ by_key: HashMap<&'a str, Vec<&'a LogicalFileEntry>>,
165
+ }
166
+
167
+ impl<'a> ResolverIndex<'a> {
168
+ pub fn build(entries: &'a [LogicalFileEntry]) -> Self {
169
+ let mut by_raw: HashMap<&'a str, &'a LogicalFileEntry> = HashMap::new();
170
+ let mut by_posix: HashMap<&'a str, &'a LogicalFileEntry> = HashMap::new();
171
+ let mut by_nfc: HashMap<&'a str, &'a LogicalFileEntry> = HashMap::new();
172
+ let mut by_key: HashMap<&'a str, Vec<&'a LogicalFileEntry>> = HashMap::new();
173
+ for entry in entries {
174
+ if let Some(raw) = entry.path_raw.as_deref() {
175
+ by_raw.entry(raw).or_insert(entry);
176
+ }
177
+ if let Some(posix) = entry.path_posix.as_deref() {
178
+ by_posix.entry(posix).or_insert(entry);
179
+ }
180
+ if let Some(nfc) = entry.path_nfc.as_deref() {
181
+ by_nfc.entry(nfc).or_insert(entry);
182
+ }
183
+ by_key
184
+ .entry(entry.path_key.as_str())
185
+ .or_default()
186
+ .push(entry);
187
+ }
188
+ ResolverIndex {
189
+ by_raw,
190
+ by_posix,
191
+ by_nfc,
192
+ by_key,
193
+ }
194
+ }
195
+ }
196
+
197
+ /// Resolve every extracted reference. Order is preserved.
198
+ pub fn resolve(refs: Vec<ExtractedReference>, index: &ResolverIndex<'_>) -> Vec<ResolvedReference> {
199
+ refs.into_iter().map(|r| resolve_one(r, index)).collect()
200
+ }
201
+
202
+ fn resolve_one(ext: ExtractedReference, index: &ResolverIndex) -> ResolvedReference {
203
+ let raw = ext.raw_reference.clone();
204
+ let normalized = normalize_for_lookup(&raw);
205
+ let lookup_key = casefold_nfc(&normalized);
206
+
207
+ if raw.trim().is_empty() {
208
+ return finalize(
209
+ ext,
210
+ normalized,
211
+ lookup_key,
212
+ None,
213
+ ResolutionStatus::InvalidPath,
214
+ );
215
+ }
216
+
217
+ if matches!(ext.reference_kind, ReferenceKind::StoryboardAnimationFrame) {
218
+ let hit = ext
219
+ .animation_frame_index
220
+ .and_then(|idx| animation_frame_match_for_index(&lookup_key, idx, index));
221
+ let status = if hit.is_some() {
222
+ ResolutionStatus::FoundByConvention
223
+ } else {
224
+ ResolutionStatus::Missing
225
+ };
226
+ return finalize(ext, normalized, lookup_key, hit, status);
227
+ }
228
+
229
+ let conventional = ext.reference_kind.is_conventional();
230
+ let status_for = |default: ResolutionStatus| {
231
+ if conventional {
232
+ ResolutionStatus::FoundByConvention
233
+ } else {
234
+ default
235
+ }
236
+ };
237
+
238
+ // Phase 1: exact raw match.
239
+ if let Some(hit) = index.by_raw.get(raw.as_str()) {
240
+ return finalize(
241
+ ext,
242
+ normalized,
243
+ lookup_key,
244
+ Some((*hit).clone()),
245
+ status_for(ResolutionStatus::FoundExact),
246
+ );
247
+ }
248
+
249
+ // Phase 2: slash-normalized.
250
+ if let Some(hit) = index.by_posix.get(normalized.as_str()) {
251
+ return finalize(
252
+ ext,
253
+ normalized.clone(),
254
+ lookup_key,
255
+ Some((*hit).clone()),
256
+ status_for(ResolutionStatus::FoundSlashNormalized),
257
+ );
258
+ }
259
+
260
+ // Phase 3: NFC.
261
+ let nfc_form: String = normalized.nfc().collect();
262
+ if let Some(hit) = index.by_nfc.get(nfc_form.as_str()) {
263
+ return finalize(
264
+ ext,
265
+ normalized,
266
+ lookup_key,
267
+ Some((*hit).clone()),
268
+ status_for(ResolutionStatus::FoundUnicodeNormalized),
269
+ );
270
+ }
271
+
272
+ // Phase 4: casefolded. Detect ambiguity (multiple distinct blobs).
273
+ if let Some(candidates) = index.by_key.get(lookup_key.as_str()) {
274
+ if !candidates.is_empty() {
275
+ let distinct_blobs: std::collections::HashSet<&str> =
276
+ candidates.iter().map(|c| c.blob_sha256.as_str()).collect();
277
+ if distinct_blobs.len() > 1 {
278
+ let first = (*candidates[0]).clone();
279
+ return ambiguous(ext, normalized, lookup_key, first);
280
+ }
281
+ return finalize(
282
+ ext,
283
+ normalized,
284
+ lookup_key,
285
+ Some((*candidates[0]).clone()),
286
+ status_for(ResolutionStatus::FoundCasefolded),
287
+ );
288
+ }
289
+ }
290
+
291
+ // Phase 5: convention extension swap (hitsound stems sometimes ship as
292
+ // .mp3 or .ogg even though .wav is the canonical name).
293
+ if conventional {
294
+ for alt_ext in &["mp3", "ogg"] {
295
+ if let Some(swapped) = swap_extension(&lookup_key, alt_ext) {
296
+ if let Some(candidates) = index.by_key.get(swapped.as_str()) {
297
+ if let Some(first) = candidates.first() {
298
+ return finalize(
299
+ ext,
300
+ normalized,
301
+ lookup_key,
302
+ Some((**first).clone()),
303
+ ResolutionStatus::FoundByConvention,
304
+ );
305
+ }
306
+ }
307
+ }
308
+ }
309
+ // Conventional candidate without a match → external_or_default.
310
+ // Not a "missing" failure — osu falls back to the default skin.
311
+ return finalize(
312
+ ext,
313
+ normalized,
314
+ lookup_key,
315
+ None,
316
+ ResolutionStatus::ExternalOrDefaultResource,
317
+ );
318
+ }
319
+
320
+ // Phase 5b: storyboard animation references are patterns, not paths —
321
+ // the actual files are `<stem><frameIndex><.ext>`. We don't know the
322
+ // frame count (not threaded through `ExtractedReference`), so try a
323
+ // small set of canonical suffixes and accept the first match. This
324
+ // covers the bulk of real maps: `name0.png`, `name00.png`, …
325
+ if matches!(ext.reference_kind, ReferenceKind::StoryboardAnimation) {
326
+ if let Some(hit) = animation_frame_match(&lookup_key, index) {
327
+ return finalize(
328
+ ext,
329
+ normalized,
330
+ lookup_key,
331
+ Some(hit),
332
+ ResolutionStatus::FoundByConvention,
333
+ );
334
+ }
335
+ }
336
+
337
+ // Phase 6: nothing matched.
338
+ finalize(ext, normalized, lookup_key, None, ResolutionStatus::Missing)
339
+ }
340
+
341
+ /// Search for an animation-frame variant of `lookup_key`. Tries 1–4 leading
342
+ /// zero patterns (covers `0`, `00`, `000`, `0000`).
343
+ fn animation_frame_match(lookup_key: &str, index: &ResolverIndex) -> Option<LogicalFileEntry> {
344
+ animation_frame_match_for_index(lookup_key, 0, index)
345
+ }
346
+
347
+ fn animation_frame_match_for_index(
348
+ lookup_key: &str,
349
+ frame_index: i32,
350
+ index: &ResolverIndex,
351
+ ) -> Option<LogicalFileEntry> {
352
+ if frame_index < 0 {
353
+ return None;
354
+ }
355
+ let dot = lookup_key.rfind('.')?;
356
+ let stem = &lookup_key[..dot];
357
+ let ext = &lookup_key[dot..];
358
+ let mut suffixes = Vec::new();
359
+ suffixes.push(frame_index.to_string());
360
+ suffixes.push(format!("{frame_index:02}"));
361
+ suffixes.push(format!("{frame_index:03}"));
362
+ suffixes.push(format!("{frame_index:04}"));
363
+ suffixes.dedup();
364
+ for suffix in suffixes {
365
+ let candidate = format!("{stem}{suffix}{ext}");
366
+ if let Some(rows) = index.by_key.get(candidate.as_str()) {
367
+ if let Some(first) = rows.first() {
368
+ return Some((**first).clone());
369
+ }
370
+ }
371
+ }
372
+ None
373
+ }
374
+
375
+ fn finalize(
376
+ ext: ExtractedReference,
377
+ normalized: String,
378
+ lookup_key: String,
379
+ hit: Option<LogicalFileEntry>,
380
+ status: ResolutionStatus,
381
+ ) -> ResolvedReference {
382
+ let is_missing = matches!(
383
+ status,
384
+ ResolutionStatus::Missing | ResolutionStatus::Ambiguous | ResolutionStatus::InvalidPath
385
+ );
386
+ ResolvedReference {
387
+ source_logical_file_id: ext.source_logical_file_id,
388
+ source_path: ext.source_path,
389
+ source_section: ext.source_section,
390
+ source_context: ext.source_context,
391
+ beatmap_uid: ext.beatmap_uid,
392
+ reference_kind: ext.reference_kind,
393
+ raw_reference: ext.raw_reference,
394
+ normalized_reference: normalized,
395
+ lookup_key,
396
+ resolved_logical_file_id: hit.as_ref().map(|h| h.logical_file_id.clone()),
397
+ resolved_blob_sha256: hit.as_ref().map(|h| h.blob_sha256.clone()),
398
+ resolved_path_posix: hit.and_then(|h| h.path_posix),
399
+ resolution_status: status,
400
+ is_missing,
401
+ is_ambiguous: false,
402
+ raw_line: ext.raw_line,
403
+ }
404
+ }
405
+
406
+ fn ambiguous(
407
+ ext: ExtractedReference,
408
+ normalized: String,
409
+ lookup_key: String,
410
+ first: LogicalFileEntry,
411
+ ) -> ResolvedReference {
412
+ ResolvedReference {
413
+ source_logical_file_id: ext.source_logical_file_id,
414
+ source_path: ext.source_path,
415
+ source_section: ext.source_section,
416
+ source_context: ext.source_context,
417
+ beatmap_uid: ext.beatmap_uid,
418
+ reference_kind: ext.reference_kind,
419
+ raw_reference: ext.raw_reference,
420
+ normalized_reference: normalized,
421
+ lookup_key,
422
+ resolved_logical_file_id: Some(first.logical_file_id),
423
+ resolved_blob_sha256: Some(first.blob_sha256),
424
+ resolved_path_posix: first.path_posix,
425
+ resolution_status: ResolutionStatus::Ambiguous,
426
+ is_missing: true,
427
+ is_ambiguous: true,
428
+ raw_line: ext.raw_line,
429
+ }
430
+ }
431
+
432
+ fn normalize_for_lookup(raw: &str) -> String {
433
+ let trimmed = raw.trim();
434
+ let stripped = trimmed.strip_prefix('"').unwrap_or(trimmed);
435
+ let stripped = stripped.strip_suffix('"').unwrap_or(stripped);
436
+ stripped.replace('\\', "/")
437
+ }
438
+
439
+ fn casefold_nfc(normalized: &str) -> String {
440
+ normalized.nfc().collect::<String>().to_lowercase()
441
+ }
442
+
443
+ fn swap_extension(lookup_key: &str, new_ext: &str) -> Option<String> {
444
+ let dot = lookup_key.rfind('.')?;
445
+ let stem = &lookup_key[..dot];
446
+ Some(format!("{stem}.{new_ext}"))
447
+ }
448
+
449
+ // ---------------------------------------------------------------------------
450
+ // Extraction
451
+ // ---------------------------------------------------------------------------
452
+
453
+ /// Extract every reference originating from a parsed `.osu` file: AudioFilename
454
+ /// from [General], Background/Video/storyboard refs from [Events], explicit
455
+ /// hitsound filenames from [HitObjects], and conventional derived hitsound
456
+ /// candidates.
457
+ pub fn extract_from_beatmap(
458
+ parsed: &ParsedBeatmap,
459
+ set_revision_id: &str,
460
+ beatmap_uid: &str,
461
+ ) -> Vec<ExtractedReference> {
462
+ let mut out = Vec::new();
463
+ let source_logical_file_id =
464
+ format!("{set_revision_id}::{}", parsed.osu_logical_file_id_suffix);
465
+ let source_path = parsed
466
+ .osu_path_posix
467
+ .clone()
468
+ .unwrap_or_else(|| parsed.osu_path_key.clone());
469
+ let beatmap_uid_owned = beatmap_uid.to_string();
470
+
471
+ // [General] AudioFilename. fields is None on partial/failed parses; in
472
+ // those cases we don't have a clean AudioFilename anyway.
473
+ if let Some(fields) = parsed.fields.as_ref() {
474
+ let audio = fields.audio_filename_raw.trim();
475
+ if !audio.is_empty() {
476
+ out.push(ExtractedReference {
477
+ source_logical_file_id: source_logical_file_id.clone(),
478
+ source_path: source_path.clone(),
479
+ source_section: Some("[General]".to_string()),
480
+ source_context: "AudioFilename".to_string(),
481
+ beatmap_uid: Some(beatmap_uid_owned.clone()),
482
+ reference_kind: ReferenceKind::AudioFilename,
483
+ raw_reference: audio.to_string(),
484
+ animation_frame_index: None,
485
+ raw_line: None,
486
+ });
487
+ }
488
+ }
489
+
490
+ // [Events] — walk independently of rosu so refs survive partial parses.
491
+ if let Some(events) = parsed
492
+ .sections
493
+ .iter()
494
+ .find(|s| s.section_name.eq_ignore_ascii_case("[Events]"))
495
+ {
496
+ extract_from_events(
497
+ &events.raw_text,
498
+ &source_logical_file_id,
499
+ &source_path,
500
+ Some(beatmap_uid_owned.as_str()),
501
+ true, // include Background + Video
502
+ &mut out,
503
+ );
504
+ }
505
+
506
+ // [HitObjects]: explicit hitsounds + derived candidates.
507
+ let default_sample_set = parsed
508
+ .fields
509
+ .as_ref()
510
+ .map(|f| SampleSet::from_str(&f.sample_set))
511
+ .unwrap_or(SampleSet::Auto);
512
+ extract_from_hit_objects(
513
+ &parsed.hit_objects,
514
+ &parsed.timing_points,
515
+ default_sample_set,
516
+ &source_logical_file_id,
517
+ &source_path,
518
+ Some(beatmap_uid_owned.as_str()),
519
+ &mut out,
520
+ );
521
+
522
+ out
523
+ }
524
+
525
+ /// Extract references from a parsed `.osb` storyboard. `.osb`s carry no
526
+ /// AudioFilename / Background / hitsound refs — only sprite / animation /
527
+ /// sample / video event references.
528
+ pub fn extract_from_osb(
529
+ parsed: &StoryboardParse,
530
+ set_revision_id: &str,
531
+ source_logical_file_id_suffix: &str,
532
+ source_path: &str,
533
+ ) -> Vec<ExtractedReference> {
534
+ let mut out = Vec::new();
535
+ let source_logical_file_id = format!("{set_revision_id}::{source_logical_file_id_suffix}");
536
+ for elem in &parsed.elements {
537
+ let kind = match elem.element_kind.as_str() {
538
+ "sprite" => ReferenceKind::StoryboardSprite,
539
+ "animation" => ReferenceKind::StoryboardAnimation,
540
+ "sample" => ReferenceKind::StoryboardAudioSample,
541
+ "video" => ReferenceKind::Video,
542
+ _ => continue,
543
+ };
544
+ let raw = match &elem.file_reference_raw {
545
+ Some(s) if !s.trim().is_empty() => s.clone(),
546
+ _ => continue,
547
+ };
548
+ let context = match elem.element_kind.as_str() {
549
+ "sprite" => "storyboard_sprite",
550
+ "animation" => "storyboard_animation",
551
+ "sample" => "storyboard_audio_sample",
552
+ "video" => "video_event",
553
+ _ => "unknown",
554
+ };
555
+ out.push(ExtractedReference {
556
+ source_logical_file_id: source_logical_file_id.clone(),
557
+ source_path: source_path.to_string(),
558
+ // .osb has only one section ([Events]), so source_section stays
559
+ // None — the schema description says "null for .osb".
560
+ source_section: None,
561
+ source_context: context.to_string(),
562
+ beatmap_uid: None,
563
+ reference_kind: kind,
564
+ raw_reference: raw,
565
+ animation_frame_index: None,
566
+ raw_line: Some(elem.raw_line.clone()),
567
+ });
568
+ if elem.element_kind == "animation" {
569
+ push_animation_frame_references(
570
+ &mut out,
571
+ &source_logical_file_id,
572
+ source_path,
573
+ None,
574
+ None,
575
+ elem.file_reference_raw.as_deref(),
576
+ elem.frame_count,
577
+ Some(elem.raw_line.clone()),
578
+ );
579
+ }
580
+ }
581
+ out
582
+ }
583
+
584
+ /// Walk an `[Events]` section's raw text and extract Background / Video /
585
+ /// Sprite / Sample / Animation refs. Used by both .osu (with Background/Video
586
+ /// included) and .osb extraction paths.
587
+ fn extract_from_events(
588
+ events_text: &str,
589
+ source_logical_file_id: &str,
590
+ source_path: &str,
591
+ beatmap_uid: Option<&str>,
592
+ include_background_video: bool,
593
+ out: &mut Vec<ExtractedReference>,
594
+ ) {
595
+ for raw_line in events_text.lines() {
596
+ let trimmed = raw_line.trim_end_matches('\r');
597
+ let body = trimmed.trim_start_matches([' ', '_', '\t']);
598
+ if body.is_empty() || body.starts_with("//") || body.starts_with('[') {
599
+ continue;
600
+ }
601
+ // Only depth-0 lines declare elements (and thus carry file refs).
602
+ if trimmed.len() != body.len() {
603
+ continue;
604
+ }
605
+ let parts = split_storyboard_fields(body);
606
+ if parts.is_empty() {
607
+ continue;
608
+ }
609
+ let kw = parts[0].trim();
610
+
611
+ // (filename_index, kind, context).
612
+ let dispatch: Option<(usize, ReferenceKind, &str)> =
613
+ if kw == "0" || kw.eq_ignore_ascii_case("Background") {
614
+ if include_background_video {
615
+ Some((2, ReferenceKind::BackgroundImage, "background_event"))
616
+ } else {
617
+ None
618
+ }
619
+ } else if kw == "1" || kw.eq_ignore_ascii_case("Video") {
620
+ if include_background_video {
621
+ Some((2, ReferenceKind::Video, "video_event"))
622
+ } else {
623
+ None
624
+ }
625
+ } else if kw == "4" || kw.eq_ignore_ascii_case("Sprite") {
626
+ Some((3, ReferenceKind::StoryboardSprite, "storyboard_sprite"))
627
+ } else if kw == "6" || kw.eq_ignore_ascii_case("Animation") {
628
+ Some((
629
+ 3,
630
+ ReferenceKind::StoryboardAnimation,
631
+ "storyboard_animation",
632
+ ))
633
+ } else if kw == "5" || kw.eq_ignore_ascii_case("Sample") {
634
+ Some((
635
+ 3,
636
+ ReferenceKind::StoryboardAudioSample,
637
+ "storyboard_audio_sample",
638
+ ))
639
+ } else {
640
+ None
641
+ };
642
+
643
+ let Some((idx, kind, context)) = dispatch else {
644
+ continue;
645
+ };
646
+ let Some(raw_field) = parts.get(idx) else {
647
+ continue;
648
+ };
649
+ let cleaned = clean_filename(raw_field);
650
+ if cleaned.is_empty() {
651
+ continue;
652
+ }
653
+ out.push(ExtractedReference {
654
+ source_logical_file_id: source_logical_file_id.to_string(),
655
+ source_path: source_path.to_string(),
656
+ source_section: Some("[Events]".to_string()),
657
+ source_context: context.to_string(),
658
+ beatmap_uid: beatmap_uid.map(String::from),
659
+ reference_kind: kind,
660
+ raw_reference: cleaned,
661
+ animation_frame_index: None,
662
+ raw_line: Some(trimmed.to_string()),
663
+ });
664
+ if matches!(kind, ReferenceKind::StoryboardAnimation) {
665
+ let frame_count = parts.get(6).and_then(|s| s.trim().parse::<i32>().ok());
666
+ push_animation_frame_references(
667
+ out,
668
+ source_logical_file_id,
669
+ source_path,
670
+ beatmap_uid,
671
+ Some("[Events]"),
672
+ parts.get(idx).map(|s| clean_filename(s)).as_deref(),
673
+ frame_count,
674
+ Some(trimmed.to_string()),
675
+ );
676
+ }
677
+ }
678
+ }
679
+
680
+ fn push_animation_frame_references(
681
+ out: &mut Vec<ExtractedReference>,
682
+ source_logical_file_id: &str,
683
+ source_path: &str,
684
+ beatmap_uid: Option<&str>,
685
+ source_section: Option<&str>,
686
+ raw_reference: Option<&str>,
687
+ frame_count: Option<i32>,
688
+ raw_line: Option<String>,
689
+ ) {
690
+ let Some(raw) = raw_reference else {
691
+ return;
692
+ };
693
+ if raw.trim().is_empty() {
694
+ return;
695
+ }
696
+ let Some(frame_count) = frame_count else {
697
+ return;
698
+ };
699
+ if frame_count <= 0 {
700
+ return;
701
+ }
702
+ for frame_index in 0..frame_count {
703
+ out.push(ExtractedReference {
704
+ source_logical_file_id: source_logical_file_id.to_string(),
705
+ source_path: source_path.to_string(),
706
+ source_section: source_section.map(String::from),
707
+ source_context: format!("storyboard_animation_frame:index={frame_index}"),
708
+ beatmap_uid: beatmap_uid.map(String::from),
709
+ reference_kind: ReferenceKind::StoryboardAnimationFrame,
710
+ raw_reference: raw.to_string(),
711
+ animation_frame_index: Some(frame_index),
712
+ raw_line: raw_line.clone(),
713
+ });
714
+ }
715
+ }
716
+
717
+ fn extract_from_hit_objects(
718
+ hit_objects: &[RawHitObject],
719
+ timing_points: &[RawTimingPoint],
720
+ default_sample_set: SampleSet,
721
+ source_logical_file_id: &str,
722
+ source_path: &str,
723
+ beatmap_uid: Option<&str>,
724
+ out: &mut Vec<ExtractedReference>,
725
+ ) {
726
+ // Explicit overrides: dedup by filename per beatmap (one row per unique
727
+ // explicit filename, even if 100 hit objects use it).
728
+ let mut seen_explicit: BTreeSet<String> = BTreeSet::new();
729
+ for ho in hit_objects {
730
+ let Some(field) = ho.hit_sample_raw.as_deref() else {
731
+ continue;
732
+ };
733
+ if let Some(filename) = hitsounds::explicit_from_hit_sample_field(field) {
734
+ if seen_explicit.insert(filename.clone()) {
735
+ out.push(ExtractedReference {
736
+ source_logical_file_id: source_logical_file_id.to_string(),
737
+ source_path: source_path.to_string(),
738
+ source_section: Some("[HitObjects]".to_string()),
739
+ source_context: "hit_object_hit_sample".to_string(),
740
+ beatmap_uid: beatmap_uid.map(String::from),
741
+ reference_kind: ReferenceKind::ExplicitHitsoundSample,
742
+ raw_reference: filename,
743
+ animation_frame_index: None,
744
+ raw_line: Some(ho.raw_line.clone()),
745
+ });
746
+ }
747
+ }
748
+ }
749
+
750
+ // Derived candidates from (sample_set, addition_set, index, hit_sound_flags).
751
+ let candidates =
752
+ hitsounds::derived_candidates_for_beatmap(hit_objects, timing_points, default_sample_set);
753
+ let mut seen_derived: BTreeSet<String> = BTreeSet::new();
754
+ for (filename, context) in candidates {
755
+ if seen_derived.insert(filename.clone()) {
756
+ out.push(ExtractedReference {
757
+ source_logical_file_id: source_logical_file_id.to_string(),
758
+ source_path: source_path.to_string(),
759
+ source_section: Some("[HitObjects]".to_string()),
760
+ source_context: context,
761
+ beatmap_uid: beatmap_uid.map(String::from),
762
+ reference_kind: ReferenceKind::DerivedCustomHitsoundSample,
763
+ raw_reference: filename,
764
+ animation_frame_index: None,
765
+ raw_line: None,
766
+ });
767
+ }
768
+ }
769
+ }
770
+
771
+ fn clean_filename(s: &str) -> String {
772
+ let t = s.trim();
773
+ let stripped = t.strip_prefix('"').unwrap_or(t);
774
+ let stripped = stripped.strip_suffix('"').unwrap_or(stripped);
775
+ stripped.to_string()
776
+ }
777
+
778
+ #[cfg(test)]
779
+ mod tests {
780
+ use super::*;
781
+
782
+ fn entry(path: &str, blob: &str) -> LogicalFileEntry {
783
+ let posix = path.replace('\\', "/");
784
+ let nfc: String = posix.nfc().collect();
785
+ let key = nfc.to_lowercase();
786
+ LogicalFileEntry {
787
+ logical_file_id: format!("set::{key}"),
788
+ blob_sha256: blob.to_string(),
789
+ path_raw: Some(path.to_string()),
790
+ path_posix: Some(posix),
791
+ path_nfc: Some(nfc),
792
+ path_key: key,
793
+ }
794
+ }
795
+
796
+ fn audio_ref(raw: &str) -> ExtractedReference {
797
+ ExtractedReference {
798
+ source_logical_file_id: "set::a.osu".to_string(),
799
+ source_path: "a.osu".to_string(),
800
+ source_section: Some("[General]".to_string()),
801
+ source_context: "AudioFilename".to_string(),
802
+ beatmap_uid: Some("osu:1".to_string()),
803
+ reference_kind: ReferenceKind::AudioFilename,
804
+ raw_reference: raw.to_string(),
805
+ animation_frame_index: None,
806
+ raw_line: None,
807
+ }
808
+ }
809
+
810
+ fn derived_ref(raw: &str) -> ExtractedReference {
811
+ ExtractedReference {
812
+ source_logical_file_id: "set::a.osu".to_string(),
813
+ source_path: "a.osu".to_string(),
814
+ source_section: Some("[HitObjects]".to_string()),
815
+ source_context: "derived_hitsound:normal-hitnormal:index=1".to_string(),
816
+ beatmap_uid: Some("osu:1".to_string()),
817
+ reference_kind: ReferenceKind::DerivedCustomHitsoundSample,
818
+ raw_reference: raw.to_string(),
819
+ animation_frame_index: None,
820
+ raw_line: None,
821
+ }
822
+ }
823
+
824
+ #[test]
825
+ fn resolve_phase_1_exact() {
826
+ let entries = vec![entry("audio.mp3", "blob1")];
827
+ let idx = ResolverIndex::build(&entries);
828
+ let r = resolve(vec![audio_ref("audio.mp3")], &idx);
829
+ assert_eq!(r[0].resolution_status, ResolutionStatus::FoundExact);
830
+ assert_eq!(r[0].resolved_blob_sha256.as_deref(), Some("blob1"));
831
+ assert!(!r[0].is_missing);
832
+ }
833
+
834
+ #[test]
835
+ fn resolve_phase_2_slash_normalized() {
836
+ // Archive stores forward-slash; reference uses backslash.
837
+ let entries = vec![entry("sb/typography/0030.png", "blob2")];
838
+ let idx = ResolverIndex::build(&entries);
839
+ let mut e = audio_ref("sb\\Typography\\0030.png");
840
+ e.reference_kind = ReferenceKind::StoryboardSprite;
841
+ let r = resolve(vec![e], &idx);
842
+ // Slash-normalize matches via casefold tier (since "Typography" ≠
843
+ // "typography" in the slash-normalized form).
844
+ assert_eq!(r[0].resolution_status, ResolutionStatus::FoundCasefolded);
845
+ assert_eq!(r[0].resolved_blob_sha256.as_deref(), Some("blob2"));
846
+ }
847
+
848
+ #[test]
849
+ fn resolve_phase_4_casefold() {
850
+ let entries = vec![entry("AUDIO.MP3", "blob3")];
851
+ let idx = ResolverIndex::build(&entries);
852
+ let r = resolve(vec![audio_ref("audio.mp3")], &idx);
853
+ assert_eq!(r[0].resolution_status, ResolutionStatus::FoundCasefolded);
854
+ assert_eq!(r[0].resolved_blob_sha256.as_deref(), Some("blob3"));
855
+ }
856
+
857
+ #[test]
858
+ fn resolve_phase_3_unicode_normalization() {
859
+ // Archive holds NFC-precomposed, reference is NFD-decomposed.
860
+ // Composed "Å" = U+00C5; decomposed = "A" + U+030A.
861
+ let composed = format!("{}.png", "\u{00C5}");
862
+ let decomposed = format!("{}{}.png", "A", "\u{030A}");
863
+ let entries = vec![entry(&composed, "blob4")];
864
+ let idx = ResolverIndex::build(&entries);
865
+ let mut r_in = audio_ref(&decomposed);
866
+ r_in.reference_kind = ReferenceKind::BackgroundImage;
867
+ let r = resolve(vec![r_in], &idx);
868
+ // Both NFC normalization and casefolding agree, so we hit the NFC
869
+ // tier first.
870
+ assert!(matches!(
871
+ r[0].resolution_status,
872
+ ResolutionStatus::FoundUnicodeNormalized | ResolutionStatus::FoundCasefolded
873
+ ));
874
+ assert_eq!(r[0].resolved_blob_sha256.as_deref(), Some("blob4"));
875
+ }
876
+
877
+ #[test]
878
+ fn resolve_missing_when_no_match() {
879
+ let entries = vec![entry("other.mp3", "blob5")];
880
+ let idx = ResolverIndex::build(&entries);
881
+ let r = resolve(vec![audio_ref("audio.mp3")], &idx);
882
+ assert_eq!(r[0].resolution_status, ResolutionStatus::Missing);
883
+ assert!(r[0].is_missing);
884
+ assert!(r[0].resolved_blob_sha256.is_none());
885
+ }
886
+
887
+ #[test]
888
+ fn resolve_invalid_path_for_empty_raw() {
889
+ let entries: Vec<LogicalFileEntry> = vec![];
890
+ let idx = ResolverIndex::build(&entries);
891
+ let r = resolve(vec![audio_ref(" ")], &idx);
892
+ assert_eq!(r[0].resolution_status, ResolutionStatus::InvalidPath);
893
+ assert!(r[0].is_missing);
894
+ }
895
+
896
+ #[test]
897
+ fn resolve_derived_hitsound_external_when_not_found() {
898
+ let entries = vec![entry("audio.mp3", "blob6")];
899
+ let idx = ResolverIndex::build(&entries);
900
+ let r = resolve(vec![derived_ref("normal-hitnormal.wav")], &idx);
901
+ assert_eq!(
902
+ r[0].resolution_status,
903
+ ResolutionStatus::ExternalOrDefaultResource
904
+ );
905
+ // External-or-default is NOT a missing failure.
906
+ assert!(!r[0].is_missing);
907
+ }
908
+
909
+ #[test]
910
+ fn resolve_derived_hitsound_found_by_convention() {
911
+ let entries = vec![entry("normal-hitnormal.wav", "blob7")];
912
+ let idx = ResolverIndex::build(&entries);
913
+ let r = resolve(vec![derived_ref("normal-hitnormal.wav")], &idx);
914
+ assert_eq!(r[0].resolution_status, ResolutionStatus::FoundByConvention);
915
+ assert_eq!(r[0].resolved_blob_sha256.as_deref(), Some("blob7"));
916
+ }
917
+
918
+ #[test]
919
+ fn resolve_derived_hitsound_extension_swap() {
920
+ // Archive ships .ogg even though the convention names .wav.
921
+ let entries = vec![entry("normal-hitnormal.ogg", "blob8")];
922
+ let idx = ResolverIndex::build(&entries);
923
+ let r = resolve(vec![derived_ref("normal-hitnormal.wav")], &idx);
924
+ assert_eq!(r[0].resolution_status, ResolutionStatus::FoundByConvention);
925
+ assert_eq!(r[0].resolved_blob_sha256.as_deref(), Some("blob8"));
926
+ }
927
+
928
+ #[test]
929
+ fn resolve_animation_frame_via_convention() {
930
+ // Reference points at "name.png" but the archive only has the
931
+ // frame variants "name0.png" / "name1.png".
932
+ let entries = vec![
933
+ entry("anim/name0.png", "frame0"),
934
+ entry("anim/name1.png", "frame1"),
935
+ ];
936
+ let idx = ResolverIndex::build(&entries);
937
+ let mut e = audio_ref("anim/name.png");
938
+ e.reference_kind = ReferenceKind::StoryboardAnimation;
939
+ let r = resolve(vec![e], &idx);
940
+ assert_eq!(r[0].resolution_status, ResolutionStatus::FoundByConvention);
941
+ assert!(r[0].resolved_blob_sha256.is_some());
942
+ }
943
+
944
+ #[test]
945
+ fn resolve_animation_with_leading_zeros() {
946
+ let entries = vec![entry("sb/star_0000.png", "blobZ")];
947
+ let idx = ResolverIndex::build(&entries);
948
+ let mut e = audio_ref("sb/star_.png");
949
+ e.reference_kind = ReferenceKind::StoryboardAnimation;
950
+ let r = resolve(vec![e], &idx);
951
+ assert_eq!(r[0].resolution_status, ResolutionStatus::FoundByConvention);
952
+ assert_eq!(r[0].resolved_blob_sha256.as_deref(), Some("blobZ"));
953
+ }
954
+
955
+ #[test]
956
+ fn resolve_animation_frame_uses_requested_frame_index() {
957
+ let entries = vec![
958
+ entry("anim/name0.png", "frame0"),
959
+ entry("anim/name1.png", "frame1"),
960
+ ];
961
+ let idx = ResolverIndex::build(&entries);
962
+ let mut e = audio_ref("anim/name.png");
963
+ e.reference_kind = ReferenceKind::StoryboardAnimationFrame;
964
+ e.animation_frame_index = Some(1);
965
+ let r = resolve(vec![e], &idx);
966
+ assert_eq!(r[0].resolution_status, ResolutionStatus::FoundByConvention);
967
+ assert_eq!(r[0].resolved_blob_sha256.as_deref(), Some("frame1"));
968
+ }
969
+
970
+ #[test]
971
+ fn extract_events_keeps_comma_in_quoted_storyboard_path() {
972
+ let events = "[Events]\nSprite,Foreground,Centre,\"sb/title, part 1.png\",0,0\n";
973
+ let mut refs = Vec::new();
974
+ extract_from_events(
975
+ events,
976
+ "set::map.osu",
977
+ "map.osu",
978
+ Some("osu:1"),
979
+ true,
980
+ &mut refs,
981
+ );
982
+ assert_eq!(refs.len(), 1);
983
+ assert_eq!(refs[0].raw_reference, "sb/title, part 1.png");
984
+ }
985
+
986
+ #[test]
987
+ fn extract_animation_emits_frame_references() {
988
+ let events = "[Events]\nAnimation,Foreground,Centre,\"sb/a,b.png\",0,0,3,50\n";
989
+ let mut refs = Vec::new();
990
+ extract_from_events(
991
+ events,
992
+ "set::map.osu",
993
+ "map.osu",
994
+ Some("osu:1"),
995
+ true,
996
+ &mut refs,
997
+ );
998
+ let frame_refs: Vec<_> = refs
999
+ .iter()
1000
+ .filter(|r| r.reference_kind == ReferenceKind::StoryboardAnimationFrame)
1001
+ .collect();
1002
+ assert_eq!(frame_refs.len(), 3);
1003
+ assert_eq!(frame_refs[2].animation_frame_index, Some(2));
1004
+ assert_eq!(frame_refs[0].raw_reference, "sb/a,b.png");
1005
+ }
1006
+
1007
+ #[test]
1008
+ fn resolve_ambiguous_when_two_distinct_blobs_share_path_key() {
1009
+ // Two physical files differing only in case, with different blob shas.
1010
+ let entries = vec![
1011
+ LogicalFileEntry {
1012
+ logical_file_id: "set::audio.mp3".to_string(),
1013
+ blob_sha256: "blobA".to_string(),
1014
+ path_raw: Some("Audio.mp3".to_string()),
1015
+ path_posix: Some("Audio.mp3".to_string()),
1016
+ path_nfc: Some("Audio.mp3".to_string()),
1017
+ path_key: "audio.mp3".to_string(),
1018
+ },
1019
+ LogicalFileEntry {
1020
+ logical_file_id: "set::audio.mp3".to_string(),
1021
+ blob_sha256: "blobB".to_string(),
1022
+ path_raw: Some("AUDIO.mp3".to_string()),
1023
+ path_posix: Some("AUDIO.mp3".to_string()),
1024
+ path_nfc: Some("AUDIO.mp3".to_string()),
1025
+ path_key: "audio.mp3".to_string(),
1026
+ },
1027
+ ];
1028
+ let idx = ResolverIndex::build(&entries);
1029
+ let r = resolve(vec![audio_ref("audio.mp3")], &idx);
1030
+ assert_eq!(r[0].resolution_status, ResolutionStatus::Ambiguous);
1031
+ assert!(r[0].is_ambiguous);
1032
+ assert!(r[0].is_missing);
1033
+ }
1034
+ }