From ec0fdfd6b4bad13165afbdf798006c1b11c92d33 Mon Sep 17 00:00:00 2001 From: ddidderr Date: Sat, 29 Aug 2026 15:50:04 +0200 Subject: [PATCH] feat(highscores): add SQLite Axum service Add a small standalone Axum service for the shared anonymous top-ten table. SQLite keeps the deployment self-contained, while one transaction inserts a validated name and score and removes entries below the canonical top ten. Expose a health endpoint and same-origin API, with an nginx proxy block and run instructions beside the service. Keep the service outside the game crate so native gameplay persistence remains unchanged. Test Plan: - `cargo test --manifest-path highscore-server/Cargo.toml` -- passed (3 tests) - `cargo clippy --manifest-path highscore-server/Cargo.toml --all-targets --all-features -- -D warnings` -- passed - `cargo +nightly fmt --manifest-path highscore-server/Cargo.toml -- --check` -- passed - Live executable health, POST, and GET smoke test -- passed - `git diff --cached --check` -- passed --- tdkpin-rs/highscore-server/Cargo.lock | 675 ++++++++++++++++++ tdkpin-rs/highscore-server/Cargo.toml | 17 + tdkpin-rs/highscore-server/README.md | 28 + tdkpin-rs/highscore-server/nginx.conf.example | 15 + tdkpin-rs/highscore-server/src/lib.rs | 279 ++++++++ tdkpin-rs/highscore-server/src/main.rs | 18 + tdkpin-rs/justfile | 13 +- 7 files changed, 1043 insertions(+), 2 deletions(-) create mode 100644 tdkpin-rs/highscore-server/Cargo.lock create mode 100644 tdkpin-rs/highscore-server/Cargo.toml create mode 100644 tdkpin-rs/highscore-server/README.md create mode 100644 tdkpin-rs/highscore-server/nginx.conf.example create mode 100644 tdkpin-rs/highscore-server/src/lib.rs create mode 100644 tdkpin-rs/highscore-server/src/main.rs diff --git a/tdkpin-rs/highscore-server/Cargo.lock b/tdkpin-rs/highscore-server/Cargo.lock new file mode 100644 index 0000000..e38a20b --- /dev/null +++ b/tdkpin-rs/highscore-server/Cargo.lock @@ -0,0 +1,675 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "axum" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" +dependencies = [ + "axum-core", + "bytes", + "form_urlencoded", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "itoa", + "matchit", + "memchr", + "mime", + "percent-encoding", + "pin-project-lite", + "serde_core", + "serde_json", + "serde_path_to_error", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tower", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "axum-core" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "mime", + "pin-project-lite", + "sync_wrapper", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "bitflags" +version = "2.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "cc" +version = "1.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ad534f4357a5264cce5019c989cf66a4f0dc4e0d1b1d15f8aacec0ff7360273" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "fallible-iterator" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649" + +[[package]] +name = "fallible-streaming-iterator" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a" + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "find-msvc-tools" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d45db016d36b838f563236e9193d0ee6ce38f3f68b6c94e914b4929c96bbb890" + +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-task", + "pin-project-lite", + "slab", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", +] + +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "foldhash", +] + +[[package]] +name = "hashlink" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7382cf6263419f2d8df38c55d7da83da5c18aef87fc7a7fc1fb1e344edfe14c1" +dependencies = [ + "hashbrown", +] + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + +[[package]] +name = "hyper" +version = "1.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27b501faa50e7a26c3d3560ca625132f4078a17771f4810baf70475ae48cbe43" +dependencies = [ + "atomic-waker", + "bytes", + "futures-channel", + "futures-core", + "http", + "http-body", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", +] + +[[package]] +name = "hyper-util" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0" +dependencies = [ + "bytes", + "http", + "http-body", + "hyper", + "pin-project-lite", + "tokio", + "tower-service", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "libc" +version = "0.2.189" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" + +[[package]] +name = "libsqlite3-sys" +version = "0.35.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "133c182a6a2c87864fe97778797e46c7e999672690dc9fa3ee8e241aa4a9c13f" +dependencies = [ + "cc", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "log" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" + +[[package]] +name = "matchit" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "mime" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" + +[[package]] +name = "mio" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "30d65c71f1ce40ab09135ce117d742b9f8a19ff91a41a8b57ed50bc2de59c427" +dependencies = [ + "libc", + "wasi", + "windows-sys", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rusqlite" +version = "0.37.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "165ca6e57b20e1351573e3729b958bc62f0e48025386970b6e4d29e7a7e71f3f" +dependencies = [ + "bitflags", + "fallible-iterator", + "fallible-streaming-iterator", + "hashlink", + "libsqlite3-sys", + "smallvec", +] + +[[package]] +name = "rustix" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys", +] + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.151" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_path_to_error" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" +dependencies = [ + "itoa", + "serde", + "serde_core", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.15.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90" + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "syn" +version = "3.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6275cddf4610d1775e6d1fe9469b2e77d0f39fd98fb7450901b821e0c53649f" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" + +[[package]] +name = "tdkpin-highscore-server" +version = "0.1.0" +dependencies = [ + "axum", + "http-body-util", + "rusqlite", + "serde", + "serde_json", + "tempfile", + "tokio", + "tower", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom", + "once_cell", + "rustix", + "windows-sys", +] + +[[package]] +name = "tokio" +version = "1.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "202caea871b69668250d242070849eb495be178ed697a3e98aebce5bc81a0bed" +dependencies = [ + "libc", + "mio", + "pin-project-lite", + "socket2", + "tokio-macros", + "windows-sys", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "log", + "pin-project-lite", + "tracing-core", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "unicode-ident" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/tdkpin-rs/highscore-server/Cargo.toml b/tdkpin-rs/highscore-server/Cargo.toml new file mode 100644 index 0000000..de06490 --- /dev/null +++ b/tdkpin-rs/highscore-server/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "tdkpin-highscore-server" +version = "0.1.0" +edition = "2024" +publish = false + +[dependencies] +axum = "0.8" +rusqlite = { version = "0.37", features = ["bundled"] } +serde = { version = "1", features = ["derive"] } +serde_json = "1" +tokio = { version = "1", features = ["macros", "net", "rt-multi-thread"] } + +[dev-dependencies] +http-body-util = "0.1" +tempfile = "3" +tower = { version = "0.5", features = ["util"] } diff --git a/tdkpin-rs/highscore-server/README.md b/tdkpin-rs/highscore-server/README.md new file mode 100644 index 0000000..d1588fb --- /dev/null +++ b/tdkpin-rs/highscore-server/README.md @@ -0,0 +1,28 @@ +# TDK high-score service + +This small Axum service stores the shared top-ten table in SQLite. It exposes: + +```text +GET /healthz +GET /api/highscores +POST /api/highscores +``` + +The POST body is JSON with a 21-character maximum name and a `u32` score. The +response is the canonical top-ten JSON array. + +Submissions are anonymous and intentionally trust the browser's score. Add +rate limiting, moderation, or server-side run verification if the table needs +to resist forged scores. + +Run it from `tdkpin-rs` with: + +```sh +TDKPIN_HIGHSCORE_BIND=127.0.0.1:3000 \ +TDKPIN_HIGHSCORE_DB=/var/lib/tdkpin/highscores.sqlite3 \ +cargo run --manifest-path highscore-server/Cargo.toml +``` + +Place [nginx.conf.example](nginx.conf.example) inside the public site's +existing `server` block. The browser client expects the API at +`/api/highscores` on the same origin as the game. diff --git a/tdkpin-rs/highscore-server/nginx.conf.example b/tdkpin-rs/highscore-server/nginx.conf.example new file mode 100644 index 0000000..f243ddf --- /dev/null +++ b/tdkpin-rs/highscore-server/nginx.conf.example @@ -0,0 +1,15 @@ +# Add this block inside the nginx server block that serves the game. +location /api/highscores { + proxy_pass http://127.0.0.1:3000; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; +} + +# Optional health check for local monitoring. +location = /healthz { + proxy_pass http://127.0.0.1:3000; + proxy_http_version 1.1; + proxy_set_header Host $host; +} diff --git a/tdkpin-rs/highscore-server/src/lib.rs b/tdkpin-rs/highscore-server/src/lib.rs new file mode 100644 index 0000000..26e2709 --- /dev/null +++ b/tdkpin-rs/highscore-server/src/lib.rs @@ -0,0 +1,279 @@ +use std::{ + path::Path, + sync::{Arc, Mutex}, +}; + +use axum::{ + Json, + Router, + extract::State, + http::StatusCode, + response::{IntoResponse, Response}, + routing::get, +}; +use rusqlite::{Connection, params, types::Type}; +use serde::{Deserialize, Serialize}; + +const MAX_HIGH_SCORES: usize = 10; +const MAX_NAME_CHARS: usize = 21; + +#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)] +pub struct HighScore { + pub name: String, + pub score: u32, +} + +#[derive(Debug)] +pub enum StoreError { + Database(rusqlite::Error), + Poisoned, +} + +impl From for StoreError { + fn from(error: rusqlite::Error) -> Self { + Self::Database(error) + } +} + +#[derive(Clone)] +pub struct HighScoreStore(Arc>); + +impl HighScoreStore { + pub fn open(path: impl AsRef) -> Result { + Self::from_connection(Connection::open(path)?) + } + + pub fn open_in_memory() -> Result { + Self::from_connection(Connection::open_in_memory()?) + } + + fn from_connection(connection: Connection) -> Result { + connection.execute_batch( + "CREATE TABLE IF NOT EXISTS high_scores ( + id INTEGER PRIMARY KEY, + name TEXT NOT NULL, + score INTEGER NOT NULL CHECK (score >= 0 AND score <= 4294967295) + ); + CREATE INDEX IF NOT EXISTS high_scores_order + ON high_scores (score DESC, id ASC);", + )?; + Ok(Self(Arc::new(Mutex::new(connection)))) + } + + pub fn list(&self) -> Result, StoreError> { + let connection = self.0.lock().map_err(|_| StoreError::Poisoned)?; + let mut statement = connection.prepare( + "SELECT name, score + FROM high_scores + ORDER BY score DESC, id ASC + LIMIT ?1", + )?; + let scores = statement + .query_map([i64::try_from(MAX_HIGH_SCORES).unwrap_or(10)], |row| { + let score: i64 = row.get(1)?; + let score = u32::try_from(score).map_err(|error| { + rusqlite::Error::FromSqlConversionFailure(1, Type::Integer, Box::new(error)) + })?; + Ok(HighScore { + name: row.get(0)?, + score, + }) + })? + .collect::, _>>()?; + Ok(scores) + } + + pub fn submit(&self, entry: &HighScore) -> Result, StoreError> { + { + let mut connection = self.0.lock().map_err(|_| StoreError::Poisoned)?; + let transaction = connection.transaction()?; + transaction.execute( + "INSERT INTO high_scores (name, score) VALUES (?1, ?2)", + params![entry.name, i64::from(entry.score)], + )?; + transaction.execute( + "DELETE FROM high_scores + WHERE id NOT IN ( + SELECT id FROM high_scores + ORDER BY score DESC, id ASC + LIMIT ?1 + )", + [i64::try_from(MAX_HIGH_SCORES).unwrap_or(10)], + )?; + transaction.commit()?; + } + self.list() + } +} + +#[derive(Debug, Deserialize)] +struct SubmitRequest { + name: String, + score: u32, +} + +#[derive(Debug, Serialize)] +struct ErrorResponse { + error: &'static str, +} + +fn invalid_request(message: &'static str) -> Response { + ( + StatusCode::BAD_REQUEST, + Json(ErrorResponse { error: message }), + ) + .into_response() +} + +fn validate_request(request: SubmitRequest) -> Result { + let name = request.name.trim(); + if name.is_empty() { + return Err("name must not be empty"); + } + if name.chars().count() > MAX_NAME_CHARS { + return Err("name is too long"); + } + if name.chars().any(char::is_control) { + return Err("name contains a control character"); + } + Ok(HighScore { + name: name.to_owned(), + score: request.score, + }) +} + +async fn health() -> &'static str { + "ok" +} + +async fn list_high_scores(State(store): State) -> Response { + match store.list() { + Ok(scores) => Json(scores).into_response(), + Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(), + } +} + +async fn submit_high_score( + State(store): State, + Json(request): Json, +) -> Response { + let entry = match validate_request(request) { + Ok(entry) => entry, + Err(message) => return invalid_request(message), + }; + match store.submit(&entry) { + Ok(scores) => (StatusCode::CREATED, Json(scores)).into_response(), + Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(), + } +} + +pub fn router(store: HighScoreStore) -> Router { + Router::new() + .route("/healthz", get(health)) + .route( + "/api/highscores", + get(list_high_scores).post(submit_high_score), + ) + .with_state(store) +} + +#[cfg(test)] +mod tests { + use axum::{ + body::Body, + http::{Request, StatusCode}, + }; + use http_body_util::BodyExt; + use tempfile::tempdir; + use tower::ServiceExt; + + use super::*; + + async fn submit(app: &Router, name: &str, score: u32) -> StatusCode { + app.clone() + .oneshot( + Request::post("/api/highscores") + .header("content-type", "application/json") + .body(Body::from( + serde_json::to_vec(&serde_json::json!({ + "name": name, + "score": score, + })) + .expect("request JSON should encode"), + )) + .expect("request should build"), + ) + .await + .expect("router should respond") + .status() + } + + async fn list(app: &Router) -> Vec { + let response = app + .clone() + .oneshot( + Request::get("/api/highscores") + .body(Body::empty()) + .expect("request should build"), + ) + .await + .expect("router should respond"); + assert_eq!(response.status(), StatusCode::OK); + let body = response + .into_body() + .collect() + .await + .expect("response body should read") + .to_bytes(); + serde_json::from_slice(&body).expect("response should contain scores") + } + + #[tokio::test] + async fn api_persists_and_keeps_the_top_ten() { + let directory = tempdir().expect("temporary directory should exist"); + let database = directory.path().join("highscores.sqlite3"); + let store = HighScoreStore::open(&database).expect("database should open"); + let app = router(store); + + for score in 0..12 { + assert_eq!( + submit(&app, &format!("Player {score}"), score).await, + StatusCode::CREATED + ); + } + let scores = list(&app).await; + assert_eq!(scores.len(), MAX_HIGH_SCORES); + assert_eq!(scores[0].score, 11); + assert_eq!(scores[9].score, 2); + + drop(app); + let reopened = router(HighScoreStore::open(&database).expect("database should reopen")); + assert_eq!(list(&reopened).await, scores); + } + + #[tokio::test] + async fn api_rejects_invalid_names() { + let app = router(HighScoreStore::open_in_memory().expect("database should open")); + + assert_eq!(submit(&app, "", 10).await, StatusCode::BAD_REQUEST); + assert_eq!( + submit(&app, "abcdefghijklmnopqrstuv", 10).await, + StatusCode::BAD_REQUEST + ); + assert_eq!(submit(&app, "ok\nno", 10).await, StatusCode::BAD_REQUEST); + } + + #[tokio::test] + async fn health_endpoint_is_available_for_nginx() { + let app = router(HighScoreStore::open_in_memory().expect("database should open")); + let response = app + .oneshot( + Request::get("/healthz") + .body(Body::empty()) + .expect("request should build"), + ) + .await + .expect("router should respond"); + assert_eq!(response.status(), StatusCode::OK); + } +} diff --git a/tdkpin-rs/highscore-server/src/main.rs b/tdkpin-rs/highscore-server/src/main.rs new file mode 100644 index 0000000..f9d42fb --- /dev/null +++ b/tdkpin-rs/highscore-server/src/main.rs @@ -0,0 +1,18 @@ +use std::{env, error::Error, path::PathBuf}; + +use axum::Router; +use tdkpin_highscore_server::{HighScoreStore, router}; +use tokio::net::TcpListener; + +#[tokio::main] +async fn main() -> Result<(), Box> { + let bind = env::var("TDKPIN_HIGHSCORE_BIND").unwrap_or_else(|_| "127.0.0.1:3000".to_owned()); + let database = env::var_os("TDKPIN_HIGHSCORE_DB") + .map(PathBuf::from) + .unwrap_or_else(|| PathBuf::from("highscores.sqlite3")); + let app: Router = router(HighScoreStore::open(database)?); + let listener = TcpListener::bind(&bind).await?; + println!("TDK high-score service listening on http://{bind}"); + axum::serve(listener, app).await?; + Ok(()) +} diff --git a/tdkpin-rs/justfile b/tdkpin-rs/justfile index 9bfbaf4..ad22253 100644 --- a/tdkpin-rs/justfile +++ b/tdkpin-rs/justfile @@ -19,6 +19,15 @@ web-build: web-serve: web-build python3 -m http.server 8000 --directory web +highscore-server: + cargo run --manifest-path highscore-server/Cargo.toml + +test-highscore-server: + cargo test --manifest-path highscore-server/Cargo.toml + +clippy-highscore-server: + cargo clippy --manifest-path highscore-server/Cargo.toml --all-targets --all-features -- -D warnings + fmt: cargo +nightly fmt tombi format @@ -32,10 +41,10 @@ _fix: fix: _fix fmt -clippy: +clippy: clippy-highscore-server cargo clippy --workspace --all-targets --all-features -- -D warnings -test: +test: test-highscore-server cargo test --workspace --all-targets --all-features clean: