diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..a772311 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,3 @@ +# Every text file is LF in the working tree too, on any OS and whatever core.autocrlf says: the doc budget, +# Prettier and the committed OpenAPI spec compare bytes, and checked-out CRLF made them fail on Windows. +* text=auto eol=lf diff --git a/.github/workflows/check.yml b/.github/workflows/check.yml index 0557806..c298996 100644 --- a/.github/workflows/check.yml +++ b/.github/workflows/check.yml @@ -1,5 +1,8 @@ # What `just check` runs, on every push and pull request, except the style guide screenshots (`test:ui`): # their reference images come from the lead's machine, and a CI runner's fonts render them differently. +# It also builds the site as a deploy does, with no API to reach, so a page that reads the API while being +# prerendered fails here instead of in `just deploy`. Not in `just check`: it writes the `.next/` that +# `next dev` is using. name: Check on: push: @@ -55,3 +58,4 @@ jobs: - run: npm run --silent typecheck - run: npm run --silent api:check - run: npm run --silent test + - run: npm run --silent build diff --git a/api/.sqlx/query-6d5c79bf0a98fc5ae3f16b32f513e467a9d8d869254ded27b29f11a124efe852.json b/api/.sqlx/query-01f7dd297b27ffd70d058c7c02094146e2c7bc8d6c35edad46bb4a32514d6caf.json similarity index 69% rename from api/.sqlx/query-6d5c79bf0a98fc5ae3f16b32f513e467a9d8d869254ded27b29f11a124efe852.json rename to api/.sqlx/query-01f7dd297b27ffd70d058c7c02094146e2c7bc8d6c35edad46bb4a32514d6caf.json index 0a1eb8e..8186b14 100644 --- a/api/.sqlx/query-6d5c79bf0a98fc5ae3f16b32f513e467a9d8d869254ded27b29f11a124efe852.json +++ b/api/.sqlx/query-01f7dd297b27ffd70d058c7c02094146e2c7bc8d6c35edad46bb4a32514d6caf.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT m.name, m.listed_at AS \"listed_at!\",\n (SELECT tier FROM map_tiers WHERE map_id = m.id AND track = 0 ORDER BY assigned_at DESC LIMIT 1)\n AS tier\n FROM maps m WHERE m.last_run_at IS NOT NULL AND m.listed_at IS NOT NULL\n ORDER BY m.listed_at DESC, m.name LIMIT $1", + "query": "SELECT m.name, m.listed_at AS \"listed_at!\",\n (SELECT tier FROM current_map_tiers WHERE map_id = m.id AND track = 0) AS tier\n FROM maps m WHERE m.last_run_at IS NOT NULL AND m.listed_at IS NOT NULL\n ORDER BY m.listed_at DESC, m.name LIMIT $1", "describe": { "columns": [ { @@ -43,5 +43,5 @@ null ] }, - "hash": "6d5c79bf0a98fc5ae3f16b32f513e467a9d8d869254ded27b29f11a124efe852" + "hash": "01f7dd297b27ffd70d058c7c02094146e2c7bc8d6c35edad46bb4a32514d6caf" } diff --git a/api/.sqlx/query-07cad333640d67941225c6a4460ca571d81156888fd6095e31ce97381600e2df.json b/api/.sqlx/query-07cad333640d67941225c6a4460ca571d81156888fd6095e31ce97381600e2df.json deleted file mode 100644 index 5f3a590..0000000 --- a/api/.sqlx/query-07cad333640d67941225c6a4460ca571d81156888fd6095e31ce97381600e2df.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "\n WITH tiers AS (\n SELECT DISTINCT ON (map_id, track) map_id, track, tier FROM map_tiers\n WHERE $1 ORDER BY map_id, track, assigned_at DESC\n )\n INSERT INTO standings_boards (map_id, style, track, best, tier)\n SELECT b.map_id, b.style, b.track, b.best, t.tier\n FROM (SELECT map_id, style, track, min(time) AS best FROM personal_bests GROUP BY 1, 2, 3) b\n LEFT JOIN tiers t ON t.map_id = b.map_id AND t.track = b.track\n ", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "Bool" - ] - }, - "nullable": [] - }, - "hash": "07cad333640d67941225c6a4460ca571d81156888fd6095e31ce97381600e2df" -} diff --git a/api/.sqlx/query-2ace85f3e3bdc6a6def3f8f678ec0cb744b8109b774c914cd1b9b9119b346316.json b/api/.sqlx/query-0b0d82934ef77f36365f54641adb343ca18be82be0ae291192fb51553d169faa.json similarity index 76% rename from api/.sqlx/query-2ace85f3e3bdc6a6def3f8f678ec0cb744b8109b774c914cd1b9b9119b346316.json rename to api/.sqlx/query-0b0d82934ef77f36365f54641adb343ca18be82be0ae291192fb51553d169faa.json index 551cd91..b22cab5 100644 --- a/api/.sqlx/query-2ace85f3e3bdc6a6def3f8f678ec0cb744b8109b774c914cd1b9b9119b346316.json +++ b/api/.sqlx/query-0b0d82934ef77f36365f54641adb343ca18be82be0ae291192fb51553d169faa.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT count(*) AS \"count!\" FROM maps m\n WHERE last_run_at IS NOT NULL AND ($1::text IS NULL OR name ILIKE $1 ESCAPE '\\' OR $2 <% name)\n AND ($3::bigint IS NULL OR $4 = EXISTS (\n SELECT 1 FROM personal_bests WHERE player_steamid64 = $3 AND map_id = m.id AND style = $5 AND track = 0))\n AND ($6::smallint IS NULL OR $6 = (SELECT tier FROM map_tiers WHERE map_id = m.id AND track = 0\n ORDER BY assigned_at DESC LIMIT 1))", + "query": "SELECT count(*) AS \"count!\" FROM maps m\n WHERE last_run_at IS NOT NULL AND ($1::text IS NULL OR name ILIKE $1 ESCAPE '\\' OR $2 <% name)\n AND ($3::bigint IS NULL OR $4 = EXISTS (\n SELECT 1 FROM personal_bests WHERE player_steamid64 = $3 AND map_id = m.id AND style = $5 AND track = 0))\n AND ($6::smallint IS NULL OR $6 = (SELECT tier FROM current_map_tiers WHERE map_id = m.id AND track = 0))", "describe": { "columns": [ { @@ -24,5 +24,5 @@ null ] }, - "hash": "2ace85f3e3bdc6a6def3f8f678ec0cb744b8109b774c914cd1b9b9119b346316" + "hash": "0b0d82934ef77f36365f54641adb343ca18be82be0ae291192fb51553d169faa" } diff --git a/api/.sqlx/query-5908cb42b04e7bac898e44cbf0794b37074219d331b5867e24d08c3a7309093d.json b/api/.sqlx/query-1a0e27664607e0670e544ee08057854a1e1811b463d3d3ffbb52e4f17372a3ed.json similarity index 86% rename from api/.sqlx/query-5908cb42b04e7bac898e44cbf0794b37074219d331b5867e24d08c3a7309093d.json rename to api/.sqlx/query-1a0e27664607e0670e544ee08057854a1e1811b463d3d3ffbb52e4f17372a3ed.json index baccabe..3cb673f 100644 --- a/api/.sqlx/query-5908cb42b04e7bac898e44cbf0794b37074219d331b5867e24d08c3a7309093d.json +++ b/api/.sqlx/query-1a0e27664607e0670e544ee08057854a1e1811b463d3d3ffbb52e4f17372a3ed.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "\n SELECT DISTINCT ON (pb.track, pb.style)\n pb.track, pb.style, pb.time, pb.run_id, r.finished_at,\n count(*) OVER (PARTITION BY pb.track, pb.style) AS \"players!\",\n p.steamid64::text AS \"steamid64!\", p.name, p.avatar_url, p.country_code,\n (SELECT tier FROM map_tiers WHERE map_id = pb.map_id AND track = pb.track\n ORDER BY assigned_at DESC LIMIT 1) AS tier\n FROM personal_bests pb\n JOIN runs r ON r.id = pb.run_id\n JOIN players p ON p.steamid64 = pb.player_steamid64\n WHERE pb.map_id = $1\n ORDER BY pb.track, pb.style, pb.time, r.finished_at\n ", + "query": "\n SELECT DISTINCT ON (pb.track, pb.style)\n pb.track, pb.style, pb.time, pb.run_id, r.finished_at,\n count(*) OVER (PARTITION BY pb.track, pb.style) AS \"players!\",\n p.steamid64::text AS \"steamid64!\", p.name, p.avatar_url, p.country_code,\n (SELECT tier FROM current_map_tiers WHERE map_id = pb.map_id AND track = pb.track) AS tier\n FROM personal_bests pb\n JOIN runs r ON r.id = pb.run_id\n JOIN players p ON p.steamid64 = pb.player_steamid64\n WHERE pb.map_id = $1\n ORDER BY pb.track, pb.style, pb.time, r.finished_at\n ", "describe": { "columns": [ { @@ -129,5 +129,5 @@ null ] }, - "hash": "5908cb42b04e7bac898e44cbf0794b37074219d331b5867e24d08c3a7309093d" + "hash": "1a0e27664607e0670e544ee08057854a1e1811b463d3d3ffbb52e4f17372a3ed" } diff --git a/api/.sqlx/query-1ecf840d0bc2ceee01d3d972ba891b00d083add43c10351eed6e9b01523375c6.json b/api/.sqlx/query-2a38093fec6e9d0acd79a5b259840efd337e92717d9581aaa6ffab06b750704d.json similarity index 89% rename from api/.sqlx/query-1ecf840d0bc2ceee01d3d972ba891b00d083add43c10351eed6e9b01523375c6.json rename to api/.sqlx/query-2a38093fec6e9d0acd79a5b259840efd337e92717d9581aaa6ffab06b750704d.json index b3e15ca..f132edf 100644 --- a/api/.sqlx/query-1ecf840d0bc2ceee01d3d972ba891b00d083add43c10351eed6e9b01523375c6.json +++ b/api/.sqlx/query-2a38093fec6e9d0acd79a5b259840efd337e92717d9581aaa6ffab06b750704d.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "\n SELECT r.id, r.map_id, m.name AS map, r.style, r.track, r.time, r.jumps, r.strafes, r.sync, r.perfs,\n r.avg_velocity, r.max_velocity, r.tickrate, r.finished_at, r.ruleset_version,\n r.invalidated_at IS NOT NULL AS \"invalidated!\", s.id AS server_id, s.name AS server_name,\n p.steamid64::text AS \"steamid64!\", p.name, p.avatar_url, p.country_code,\n EXISTS (SELECT 1 FROM personal_bests WHERE run_id = r.id) AS \"personal_best!\",\n (SELECT min(time) FROM personal_bests\n WHERE map_id = r.map_id AND style = r.style AND track = r.track) AS world_record_time,\n (SELECT tier FROM map_tiers WHERE map_id = r.map_id AND track = r.track\n ORDER BY assigned_at DESC LIMIT 1) AS tier,\n ci.id AS \"image_id?\", ci.key AS \"image_key?\", ci.focus AS \"image_focus?\",\n (SELECT host(h.ip) || ':' || h.port FROM server_heartbeats h\n JOIN server_listings l ON l.ip = h.ip AND l.port = h.port\n WHERE h.server_id = s.id ORDER BY h.received_at DESC LIMIT 1) AS server_address\n FROM runs r\n JOIN maps m ON m.id = r.map_id\n LEFT JOIN map_images ci ON ci.map_id = m.id AND ci.position = 0\n JOIN servers s ON s.id = r.server_id\n JOIN players p ON p.steamid64 = r.player_steamid64\n WHERE r.id = $1\n ", + "query": "\n SELECT r.id, r.map_id, m.name AS map, r.style, r.track, r.time, r.jumps, r.strafes, r.sync, r.perfs,\n r.avg_velocity, r.max_velocity, r.tickrate, r.finished_at, r.ruleset_version,\n r.invalidated_at IS NOT NULL AS \"invalidated!\", s.id AS server_id, s.name AS server_name,\n p.steamid64::text AS \"steamid64!\", p.name, p.avatar_url, p.country_code,\n EXISTS (SELECT 1 FROM personal_bests WHERE run_id = r.id) AS \"personal_best!\",\n (SELECT min(time) FROM personal_bests\n WHERE map_id = r.map_id AND style = r.style AND track = r.track) AS world_record_time,\n (SELECT tier FROM current_map_tiers WHERE map_id = r.map_id AND track = r.track) AS tier,\n ci.id AS \"image_id?\", ci.key AS \"image_key?\", ci.focus AS \"image_focus?\",\n (SELECT host(h.ip) || ':' || h.port FROM server_heartbeats h\n JOIN server_listings l ON l.ip = h.ip AND l.port = h.port\n WHERE h.server_id = s.id ORDER BY h.received_at DESC LIMIT 1) AS server_address\n FROM runs r\n JOIN maps m ON m.id = r.map_id\n LEFT JOIN map_images ci ON ci.map_id = m.id AND ci.position = 0\n JOIN servers s ON s.id = r.server_id\n JOIN players p ON p.steamid64 = r.player_steamid64\n WHERE r.id = $1\n ", "describe": { "columns": [ { @@ -324,11 +324,11 @@ null, null, null, - false, - false, - false, + true, + true, + true, null ] }, - "hash": "1ecf840d0bc2ceee01d3d972ba891b00d083add43c10351eed6e9b01523375c6" + "hash": "2a38093fec6e9d0acd79a5b259840efd337e92717d9581aaa6ffab06b750704d" } diff --git a/api/.sqlx/query-2a8a5bfced30494d8986461a6f1985b427e314cb7eed714a3fbbdd6023ef7d9c.json b/api/.sqlx/query-2a8a5bfced30494d8986461a6f1985b427e314cb7eed714a3fbbdd6023ef7d9c.json deleted file mode 100644 index 1186ab4..0000000 --- a/api/.sqlx/query-2a8a5bfced30494d8986461a6f1985b427e314cb7eed714a3fbbdd6023ef7d9c.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "\n SELECT max(tier) FROM (\n SELECT DISTINCT ON (map_id, track) tier FROM map_tiers ORDER BY map_id, track, assigned_at DESC\n ) in_force\n ", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "max", - "type_info": "Int2", - "origin": "Expression" - } - ], - "parameters": { - "Left": [] - }, - "nullable": [ - null - ] - }, - "hash": "2a8a5bfced30494d8986461a6f1985b427e314cb7eed714a3fbbdd6023ef7d9c" -} diff --git a/api/.sqlx/query-2eebac3bfabb75d940a811c7d02153f5636493b3e42961fbcd3954122de76ef0.json b/api/.sqlx/query-2eebac3bfabb75d940a811c7d02153f5636493b3e42961fbcd3954122de76ef0.json new file mode 100644 index 0000000..81b821c --- /dev/null +++ b/api/.sqlx/query-2eebac3bfabb75d940a811c7d02153f5636493b3e42961fbcd3954122de76ef0.json @@ -0,0 +1,91 @@ +{ + "db_name": "PostgreSQL", + "query": "\n SELECT shown.map AS \"map!\", shown.track AS \"track!\", shown.time AS \"time!\",\n CASE WHEN NOT shown.legacy THEN 1 + (\n SELECT count(*) FROM personal_bests faster\n WHERE faster.map_id = shown.map_id AND faster.style = $2 AND faster.track = shown.track\n AND faster.time < shown.time) END AS rank,\n CASE WHEN NOT shown.legacy THEN (\n SELECT min(best.time) FROM personal_bests best\n WHERE best.map_id = shown.map_id AND best.style = $2 AND best.track = shown.track)\n END AS world_record_time,\n shown.legacy AS \"legacy!\", shown.id AS \"id!\", shown.finished_at, tier.tier AS \"tier?\"\n FROM (\n SELECT DISTINCT ON (both_kinds.map, both_kinds.track) both_kinds.*\n FROM (\n SELECT m.name AS map, pb.map_id, pb.track, pb.time, false AS legacy, pb.run_id AS id,\n pb.finished_at\n FROM personal_bests pb\n JOIN maps m ON m.id = pb.map_id\n WHERE $3 AND pb.player_steamid64 = $1 AND pb.style = $2 AND pb.track = $4\n UNION ALL\n SELECT lm.name, NULL::bigint, $4::smallint, l.time, true, l.id::bigint, l.finished_at\n FROM legacy_personal_bests l\n JOIN legacy_maps lm ON lm.id = l.map_id\n WHERE l.player_steamid64 = $1 AND NOT EXISTS (SELECT 1 FROM records_bans b WHERE b.player_steamid64 = $1)\n ) both_kinds\n WHERE $5::text IS NULL OR (both_kinds.map, both_kinds.track) > ($5, $6::smallint)\n ORDER BY both_kinds.map, both_kinds.track, both_kinds.time, both_kinds.legacy\n LIMIT $7\n ) shown\n -- A legacy row's map_id is NULL, so it finds no tier.\n LEFT JOIN current_map_tiers tier ON $8 AND tier.map_id = shown.map_id AND tier.track = shown.track\n ORDER BY shown.map, shown.track\n ", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "map!", + "type_info": "Text", + "origin": "Expression" + }, + { + "ordinal": 1, + "name": "track!", + "type_info": "Int2", + "origin": "Expression" + }, + { + "ordinal": 2, + "name": "time!", + "type_info": "Float8", + "origin": "Expression" + }, + { + "ordinal": 3, + "name": "rank", + "type_info": "Int8", + "origin": "Expression" + }, + { + "ordinal": 4, + "name": "world_record_time", + "type_info": "Float8", + "origin": "Expression" + }, + { + "ordinal": 5, + "name": "legacy!", + "type_info": "Bool", + "origin": "Expression" + }, + { + "ordinal": 6, + "name": "id!", + "type_info": "Int8", + "origin": "Expression" + }, + { + "ordinal": 7, + "name": "finished_at", + "type_info": "Timestamptz", + "origin": "Expression" + }, + { + "ordinal": 8, + "name": "tier?", + "type_info": "Int2", + "origin": { + "Table": { + "table": "current_map_tiers", + "name": "tier" + } + } + } + ], + "parameters": { + "Left": [ + "Int8", + "Text", + "Bool", + "Int2", + "Text", + "Int2", + "Int8", + "Bool" + ] + }, + "nullable": [ + null, + null, + null, + null, + null, + null, + null, + null, + true + ] + }, + "hash": "2eebac3bfabb75d940a811c7d02153f5636493b3e42961fbcd3954122de76ef0" +} diff --git a/api/.sqlx/query-3b66a34af765c0b490013bfc8378b7d50cff03772f620d213bb0983c9405c40b.json b/api/.sqlx/query-3b66a34af765c0b490013bfc8378b7d50cff03772f620d213bb0983c9405c40b.json new file mode 100644 index 0000000..ccb1ae4 --- /dev/null +++ b/api/.sqlx/query-3b66a34af765c0b490013bfc8378b7d50cff03772f620d213bb0983c9405c40b.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM map_cards WHERE map_id = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Int8" + ] + }, + "nullable": [] + }, + "hash": "3b66a34af765c0b490013bfc8378b7d50cff03772f620d213bb0983c9405c40b" +} diff --git a/api/.sqlx/query-4c09e53a43e1c3f9862537c21606c89f29db1377e6bb0e0449f2e4fe91912fcf.json b/api/.sqlx/query-4c09e53a43e1c3f9862537c21606c89f29db1377e6bb0e0449f2e4fe91912fcf.json new file mode 100644 index 0000000..94cb7c5 --- /dev/null +++ b/api/.sqlx/query-4c09e53a43e1c3f9862537c21606c89f29db1377e6bb0e0449f2e4fe91912fcf.json @@ -0,0 +1,43 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT m.name, week.players AS \"players!\",\n (SELECT tier FROM current_map_tiers WHERE map_id = m.id AND track = 0) AS tier\n FROM (SELECT map_id, count(DISTINCT player_steamid64) AS players FROM runs\n WHERE invalidated_at IS NULL AND finished_at > now() - interval '7 days'\n GROUP BY map_id) week\n JOIN maps m ON m.id = week.map_id\n WHERE $2::smallint IS NULL OR $2 =\n (SELECT tier FROM current_map_tiers WHERE map_id = m.id AND track = 0)\n ORDER BY week.players DESC, m.name LIMIT $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "name", + "type_info": "Text", + "origin": { + "Table": { + "table": "maps", + "name": "name" + } + } + }, + { + "ordinal": 1, + "name": "players!", + "type_info": "Int8", + "origin": "Expression" + }, + { + "ordinal": 2, + "name": "tier", + "type_info": "Int2", + "origin": "Expression" + } + ], + "parameters": { + "Left": [ + "Int8", + "Int2" + ] + }, + "nullable": [ + false, + null, + null + ] + }, + "hash": "4c09e53a43e1c3f9862537c21606c89f29db1377e6bb0e0449f2e4fe91912fcf" +} diff --git a/api/.sqlx/query-4d15f7b63cc1357d0f7bd08a497b0201d51891b09b5a2e8451c269958c283cb1.json b/api/.sqlx/query-4d15f7b63cc1357d0f7bd08a497b0201d51891b09b5a2e8451c269958c283cb1.json new file mode 100644 index 0000000..281c45c --- /dev/null +++ b/api/.sqlx/query-4d15f7b63cc1357d0f7bd08a497b0201d51891b09b5a2e8451c269958c283cb1.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "\n UPDATE players SET\n country_chosen = $2::text IS NOT NULL,\n country_from_server = country_from_server AND $2::text IS NULL,\n country_code = CASE WHEN $2::text IS NOT NULL THEN $2\n WHEN country_chosen THEN NULL ELSE country_code END,\n steam_profile_fetched_at = CASE WHEN $2::text IS NULL AND country_chosen THEN NULL\n ELSE steam_profile_fetched_at END\n WHERE steamid64 = $1\n ", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Int8", + "Text" + ] + }, + "nullable": [] + }, + "hash": "4d15f7b63cc1357d0f7bd08a497b0201d51891b09b5a2e8451c269958c283cb1" +} diff --git a/api/.sqlx/query-4d51428dd0d449fca9ffbd5f4b4d7282d57807a6e359d484401c6b20a4a9ab7d.json b/api/.sqlx/query-4d51428dd0d449fca9ffbd5f4b4d7282d57807a6e359d484401c6b20a4a9ab7d.json new file mode 100644 index 0000000..053f752 --- /dev/null +++ b/api/.sqlx/query-4d51428dd0d449fca9ffbd5f4b4d7282d57807a6e359d484401c6b20a4a9ab7d.json @@ -0,0 +1,86 @@ +{ + "db_name": "PostgreSQL", + "query": "\n SELECT m.id AS \"id!\", m.name AS \"name!\", i.key AS \"cover?\", t.tier AS \"tier?\", c.key AS \"card?\", c.made_from AS \"made_from?\"\n FROM maps m\n LEFT JOIN map_images i ON i.map_id = m.id AND i.position = 0\n LEFT JOIN current_map_tiers t ON t.map_id = m.id AND t.track = 0\n LEFT JOIN map_cards c ON c.map_id = m.id\n WHERE i.key IS NOT NULL OR c.map_id IS NOT NULL\n ", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id!", + "type_info": "Int8", + "origin": { + "Table": { + "table": "maps", + "name": "id" + } + } + }, + { + "ordinal": 1, + "name": "name!", + "type_info": "Text", + "origin": { + "Table": { + "table": "maps", + "name": "name" + } + } + }, + { + "ordinal": 2, + "name": "cover?", + "type_info": "Text", + "origin": { + "Table": { + "table": "map_images", + "name": "key" + } + } + }, + { + "ordinal": 3, + "name": "tier?", + "type_info": "Int2", + "origin": { + "Table": { + "table": "current_map_tiers", + "name": "tier" + } + } + }, + { + "ordinal": 4, + "name": "card?", + "type_info": "Text", + "origin": { + "Table": { + "table": "map_cards", + "name": "key" + } + } + }, + { + "ordinal": 5, + "name": "made_from?", + "type_info": "Text", + "origin": { + "Table": { + "table": "map_cards", + "name": "made_from" + } + } + } + ], + "parameters": { + "Left": [] + }, + "nullable": [ + true, + true, + false, + true, + true, + true + ] + }, + "hash": "4d51428dd0d449fca9ffbd5f4b4d7282d57807a6e359d484401c6b20a4a9ab7d" +} diff --git a/api/.sqlx/query-d9981b3f571b8329c85152b64c076f7bc368ed7c6fd70dd425eb876c6964e236.json b/api/.sqlx/query-59705d13fd2ea053c2f4777f701f2fe6c613d590d86aa3db45c32f258ce69752.json similarity index 57% rename from api/.sqlx/query-d9981b3f571b8329c85152b64c076f7bc368ed7c6fd70dd425eb876c6964e236.json rename to api/.sqlx/query-59705d13fd2ea053c2f4777f701f2fe6c613d590d86aa3db45c32f258ce69752.json index d5c0a59..135dfe0 100644 --- a/api/.sqlx/query-d9981b3f571b8329c85152b64c076f7bc368ed7c6fd70dd425eb876c6964e236.json +++ b/api/.sqlx/query-59705d13fd2ea053c2f4777f701f2fe6c613d590d86aa3db45c32f258ce69752.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT tier.tier AS \"tier?\", count(*) AS \"maps!\" FROM maps m\n LEFT JOIN LATERAL (SELECT tier FROM map_tiers WHERE map_id = m.id AND track = 0\n ORDER BY assigned_at DESC LIMIT 1) tier ON true\n WHERE m.last_run_at IS NOT NULL\n GROUP BY tier.tier", + "query": "SELECT tier.tier AS \"tier?\", count(*) AS \"maps!\" FROM maps m\n LEFT JOIN current_map_tiers tier ON tier.map_id = m.id AND tier.track = 0\n WHERE m.last_run_at IS NOT NULL\n GROUP BY tier.tier", "describe": { "columns": [ { @@ -9,7 +9,7 @@ "type_info": "Int2", "origin": { "Table": { - "table": "map_tiers", + "table": "current_map_tiers", "name": "tier" } } @@ -25,9 +25,9 @@ "Left": [] }, "nullable": [ - false, + true, null ] }, - "hash": "d9981b3f571b8329c85152b64c076f7bc368ed7c6fd70dd425eb876c6964e236" + "hash": "59705d13fd2ea053c2f4777f701f2fe6c613d590d86aa3db45c32f258ce69752" } diff --git a/api/.sqlx/query-0eba6af91c197b4a7c14d17531e8c815bfb0fed762575ba2069fee0dfe790f9c.json b/api/.sqlx/query-5b3ad4aac7217ba3a603adcf938d933c1fdf51108b8b45030fae0d9a3195d941.json similarity index 84% rename from api/.sqlx/query-0eba6af91c197b4a7c14d17531e8c815bfb0fed762575ba2069fee0dfe790f9c.json rename to api/.sqlx/query-5b3ad4aac7217ba3a603adcf938d933c1fdf51108b8b45030fae0d9a3195d941.json index 362f45f..53a71f4 100644 --- a/api/.sqlx/query-0eba6af91c197b4a7c14d17531e8c815bfb0fed762575ba2069fee0dfe790f9c.json +++ b/api/.sqlx/query-5b3ad4aac7217ba3a603adcf938d933c1fdf51108b8b45030fae0d9a3195d941.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "\n SELECT r.id, m.name AS map, r.style, r.track, r.time, r.sync, r.strafes, r.jumps, r.finished_at, r.was_record,\n r.player_steamid64::text AS \"steamid64!\", p.name AS player, s.name AS server_name,\n (SELECT st->>'name' FROM rulesets, jsonb_array_elements(document->'styles') st\n WHERE st->>'key' = r.style ORDER BY version DESC LIMIT 1) AS style_name,\n (SELECT min(o.time) FROM runs o\n WHERE o.map_id = r.map_id AND o.style = r.style AND o.track = r.track\n AND o.invalidated_at IS NULL AND (o.finished_at, o.id) < (r.finished_at, r.id))\n AS previous_record,\n (SELECT min(o.time) FROM runs o\n WHERE o.map_id = r.map_id AND o.style = r.style AND o.track = r.track\n AND o.player_steamid64 = r.player_steamid64\n AND o.invalidated_at IS NULL AND (o.finished_at, o.id) < (r.finished_at, r.id))\n AS previous_personal_best,\n (SELECT tier FROM map_tiers WHERE map_id = r.map_id AND track = r.track\n ORDER BY assigned_at DESC LIMIT 1) AS tier,\n (SELECT key FROM map_images WHERE map_id = r.map_id AND position = 0) AS image_key,\n (SELECT host(h.ip) || ':' || h.port FROM server_heartbeats h\n JOIN server_listings l ON l.ip = h.ip AND l.port = h.port\n WHERE h.server_id = s.id ORDER BY h.received_at DESC LIMIT 1) AS server_address\n FROM unnest($1::bigint[]) WITH ORDINALITY AS wanted (run_id, place)\n JOIN runs r ON r.id = wanted.run_id\n JOIN maps m ON m.id = r.map_id\n JOIN players p ON p.steamid64 = r.player_steamid64\n JOIN servers s ON s.id = r.server_id\n ORDER BY wanted.place\n ", + "query": "\n SELECT r.id, m.name AS map, r.style, r.track, r.time, r.sync, r.strafes, r.jumps, r.finished_at, r.was_record,\n r.player_steamid64::text AS \"steamid64!\", p.name AS player, s.name AS server_name,\n (SELECT st->>'name' FROM rulesets, jsonb_array_elements(document->'styles') st\n WHERE st->>'key' = r.style ORDER BY version DESC LIMIT 1) AS style_name,\n (SELECT min(o.time) FROM runs o\n WHERE o.map_id = r.map_id AND o.style = r.style AND o.track = r.track\n AND o.invalidated_at IS NULL AND (o.finished_at, o.id) < (r.finished_at, r.id))\n AS previous_record,\n (SELECT min(o.time) FROM runs o\n WHERE o.map_id = r.map_id AND o.style = r.style AND o.track = r.track\n AND o.player_steamid64 = r.player_steamid64\n AND o.invalidated_at IS NULL AND (o.finished_at, o.id) < (r.finished_at, r.id))\n AS previous_personal_best,\n (SELECT tier FROM current_map_tiers WHERE map_id = r.map_id AND track = r.track) AS tier,\n (SELECT key FROM map_images WHERE map_id = r.map_id AND position = 0) AS image_key,\n (SELECT host(h.ip) || ':' || h.port FROM server_heartbeats h\n JOIN server_listings l ON l.ip = h.ip AND l.port = h.port\n WHERE h.server_id = s.id ORDER BY h.received_at DESC LIMIT 1) AS server_address\n FROM unnest($1::bigint[]) WITH ORDINALITY AS wanted (run_id, place)\n JOIN runs r ON r.id = wanted.run_id\n JOIN maps m ON m.id = r.map_id\n JOIN players p ON p.steamid64 = r.player_steamid64\n JOIN servers s ON s.id = r.server_id\n ORDER BY wanted.place\n ", "describe": { "columns": [ { @@ -205,5 +205,5 @@ null ] }, - "hash": "0eba6af91c197b4a7c14d17531e8c815bfb0fed762575ba2069fee0dfe790f9c" + "hash": "5b3ad4aac7217ba3a603adcf938d933c1fdf51108b8b45030fae0d9a3195d941" } diff --git a/api/.sqlx/query-5b96b09bc4c70d599055c6375d2f0f915f4a4e28b9956a6498e4818632ace6b5.json b/api/.sqlx/query-5b96b09bc4c70d599055c6375d2f0f915f4a4e28b9956a6498e4818632ace6b5.json new file mode 100644 index 0000000..4b5be87 --- /dev/null +++ b/api/.sqlx/query-5b96b09bc4c70d599055c6375d2f0f915f4a4e28b9956a6498e4818632ace6b5.json @@ -0,0 +1,23 @@ +{ + "db_name": "PostgreSQL", + "query": "\n WITH now AS MATERIALIZED (\n SELECT b.map_id, b.style, b.track,\n (SELECT min(pb.time) FROM personal_bests pb\n WHERE pb.map_id = b.map_id AND pb.style = b.style AND pb.track = b.track) AS best,\n CASE WHEN $5 THEN (SELECT t.tier FROM current_map_tiers t\n WHERE t.map_id = b.map_id AND t.track = b.track) END AS tier\n FROM unnest($1::int8[], $2::text[], $3::int2[]) AS b (map_id, style, track)\n ), runners AS MATERIALIZED (\n SELECT DISTINCT player_steamid64, style, track > 0 AS bonus FROM runs WHERE id = ANY($4)\n ), moved AS (\n SELECT now.*, stored.best AS stored_best, stored.tier AS stored_tier\n FROM now JOIN standings_boards stored USING (map_id, style, track)\n WHERE now.best IS NOT NULL AND (now.best, now.tier) IS DISTINCT FROM (stored.best, stored.tier)\n ), changes AS (\n SELECT pb.style, pb.track > 0 AS bonus, pb.player_steamid64,\n sum(coalesce(points_for(m.tier, pb.time, m.best, pb.track > 0, $6, $7, $8, $9, $10), 0)\n - coalesce(points_for(m.stored_tier, pb.time, m.stored_best, pb.track > 0,\n $6, $7, $8, $9, $10), 0)) AS change\n FROM moved m\n JOIN personal_bests pb ON pb.map_id = m.map_id AND pb.style = m.style AND pb.track = m.track\n -- The runs' players are summed again below.\n WHERE NOT EXISTS (\n SELECT 1 FROM runners r\n WHERE r.player_steamid64 = pb.player_steamid64 AND r.style = pb.style AND r.bonus = (pb.track > 0)\n )\n GROUP BY 1, 2, 3\n ), moved_totals AS (\n UPDATE standings s SET points = s.points + c.change FROM changes c\n WHERE s.style = c.style AND s.bonus = c.bonus AND s.player_steamid64 = c.player_steamid64\n AND c.change <> 0\n ), emptied AS (\n DELETE FROM standings_boards stored USING now\n WHERE stored.map_id = now.map_id AND stored.style = now.style AND stored.track = now.track\n AND now.best IS NULL\n )\n INSERT INTO standings_boards (map_id, style, track, best, tier)\n SELECT map_id, style, track, best, tier FROM now WHERE best IS NOT NULL\n ON CONFLICT (map_id, style, track) DO UPDATE SET best = excluded.best, tier = excluded.tier\n ", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Int8Array", + "TextArray", + "Int2Array", + "Int8Array", + "Bool", + "Float8", + "Float8", + "Float8", + "Float8", + "Float8" + ] + }, + "nullable": [] + }, + "hash": "5b96b09bc4c70d599055c6375d2f0f915f4a4e28b9956a6498e4818632ace6b5" +} diff --git a/api/.sqlx/query-647fe5591a0b95a2cc88f192f8a68a771ad4a997b964775a1c1b903fea4d3c2c.json b/api/.sqlx/query-647fe5591a0b95a2cc88f192f8a68a771ad4a997b964775a1c1b903fea4d3c2c.json new file mode 100644 index 0000000..fbf1f26 --- /dev/null +++ b/api/.sqlx/query-647fe5591a0b95a2cc88f192f8a68a771ad4a997b964775a1c1b903fea4d3c2c.json @@ -0,0 +1,40 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT name, avatar_url FROM legacy_players WHERE steamid64 = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "name", + "type_info": "Text", + "origin": { + "Table": { + "table": "legacy_players", + "name": "name" + } + } + }, + { + "ordinal": 1, + "name": "avatar_url", + "type_info": "Text", + "origin": { + "Table": { + "table": "legacy_players", + "name": "avatar_url" + } + } + } + ], + "parameters": { + "Left": [ + "Int8" + ] + }, + "nullable": [ + false, + true + ] + }, + "hash": "647fe5591a0b95a2cc88f192f8a68a771ad4a997b964775a1c1b903fea4d3c2c" +} diff --git a/api/.sqlx/query-6b63f952f79d6fbd02d80515bc721a8e25a5c4f20739438661fe00bcedbbce49.json b/api/.sqlx/query-6b63f952f79d6fbd02d80515bc721a8e25a5c4f20739438661fe00bcedbbce49.json new file mode 100644 index 0000000..1da6bab --- /dev/null +++ b/api/.sqlx/query-6b63f952f79d6fbd02d80515bc721a8e25a5c4f20739438661fe00bcedbbce49.json @@ -0,0 +1,102 @@ +{ + "db_name": "PostgreSQL", + "query": "\n SELECT m.id, m.name, m.description, m.created_at, m.last_run_at, m.players,\n (SELECT key FROM map_cards WHERE map_id = m.id) AS card_key,\n (SELECT count(*) FROM runs WHERE map_id = m.id AND invalidated_at IS NULL) AS \"runs!\"\n FROM maps m WHERE m.name = $1\n ", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id", + "type_info": "Int8", + "origin": { + "Table": { + "table": "maps", + "name": "id" + } + } + }, + { + "ordinal": 1, + "name": "name", + "type_info": "Text", + "origin": { + "Table": { + "table": "maps", + "name": "name" + } + } + }, + { + "ordinal": 2, + "name": "description", + "type_info": "Text", + "origin": { + "Table": { + "table": "maps", + "name": "description" + } + } + }, + { + "ordinal": 3, + "name": "created_at", + "type_info": "Timestamptz", + "origin": { + "Table": { + "table": "maps", + "name": "created_at" + } + } + }, + { + "ordinal": 4, + "name": "last_run_at", + "type_info": "Timestamptz", + "origin": { + "Table": { + "table": "maps", + "name": "last_run_at" + } + } + }, + { + "ordinal": 5, + "name": "players", + "type_info": "Int4", + "origin": { + "Table": { + "table": "maps", + "name": "players" + } + } + }, + { + "ordinal": 6, + "name": "card_key", + "type_info": "Text", + "origin": "Expression" + }, + { + "ordinal": 7, + "name": "runs!", + "type_info": "Int8", + "origin": "Expression" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + false, + false, + true, + false, + true, + false, + null, + null + ] + }, + "hash": "6b63f952f79d6fbd02d80515bc721a8e25a5c4f20739438661fe00bcedbbce49" +} diff --git a/api/.sqlx/query-8154635f139165e32da730d724f8884f499df1fa7fbf249e5bce5a8d99d8c7c4.json b/api/.sqlx/query-724fdf8d089f3e5c7c055d7d2840e391bbbcadf1e56576c65f8d24b88330aa5b.json similarity index 76% rename from api/.sqlx/query-8154635f139165e32da730d724f8884f499df1fa7fbf249e5bce5a8d99d8c7c4.json rename to api/.sqlx/query-724fdf8d089f3e5c7c055d7d2840e391bbbcadf1e56576c65f8d24b88330aa5b.json index dcda92c..9854c93 100644 --- a/api/.sqlx/query-8154635f139165e32da730d724f8884f499df1fa7fbf249e5bce5a8d99d8c7c4.json +++ b/api/.sqlx/query-724fdf8d089f3e5c7c055d7d2840e391bbbcadf1e56576c65f8d24b88330aa5b.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "\n SELECT m.name, ci.id AS \"image_id?\", ci.key AS \"image_key?\", ci.focus AS \"image_focus?\", m.last_run_at,\n (SELECT tier FROM map_tiers t WHERE t.map_id = m.id AND t.track = 0\n ORDER BY assigned_at DESC LIMIT 1) AS tier,\n (SELECT max(version) FROM map_zones z WHERE z.map_id = m.id) AS zone_version\n FROM maps m\n LEFT JOIN map_images ci ON ci.map_id = m.id AND ci.position = 0\n WHERE m.name ILIKE $1 ESCAPE '\\' AND (NOT $4 OR m.last_run_at IS NULL)\n ORDER BY m.name\n LIMIT $2 OFFSET $3\n ", + "query": "\n SELECT m.name, ci.id AS \"image_id?\", ci.key AS \"image_key?\", ci.focus AS \"image_focus?\", m.last_run_at,\n (SELECT tier FROM current_map_tiers t WHERE t.map_id = m.id AND t.track = 0) AS tier,\n (SELECT max(version) FROM map_zones z WHERE z.map_id = m.id) AS zone_version\n FROM maps m\n LEFT JOIN map_images ci ON ci.map_id = m.id AND ci.position = 0\n WHERE m.name ILIKE $1 ESCAPE '\\' AND (NOT $4 OR m.last_run_at IS NULL)\n ORDER BY m.name\n LIMIT $2 OFFSET $3\n ", "describe": { "columns": [ { @@ -89,5 +89,5 @@ null ] }, - "hash": "8154635f139165e32da730d724f8884f499df1fa7fbf249e5bce5a8d99d8c7c4" + "hash": "724fdf8d089f3e5c7c055d7d2840e391bbbcadf1e56576c65f8d24b88330aa5b" } diff --git a/api/.sqlx/query-75a9b88f71b7718e03b201065fb006af20e5491663e23e7d4dc6416ebee0a020.json b/api/.sqlx/query-75a9b88f71b7718e03b201065fb006af20e5491663e23e7d4dc6416ebee0a020.json new file mode 100644 index 0000000..1d2e98d --- /dev/null +++ b/api/.sqlx/query-75a9b88f71b7718e03b201065fb006af20e5491663e23e7d4dc6416ebee0a020.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM sessions WHERE player_steamid64 = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Int8" + ] + }, + "nullable": [] + }, + "hash": "75a9b88f71b7718e03b201065fb006af20e5491663e23e7d4dc6416ebee0a020" +} diff --git a/api/.sqlx/query-812bc73f084e7a5f90687cc457d9f91cac3b29f0211e6db655536f3c7eb9ec28.json b/api/.sqlx/query-812bc73f084e7a5f90687cc457d9f91cac3b29f0211e6db655536f3c7eb9ec28.json new file mode 100644 index 0000000..6db845f --- /dev/null +++ b/api/.sqlx/query-812bc73f084e7a5f90687cc457d9f91cac3b29f0211e6db655536f3c7eb9ec28.json @@ -0,0 +1,29 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT count(*) AS \"count!\" FROM maps m\n WHERE last_run_at IS NOT NULL AND ($1::text IS NULL OR name ILIKE $1 ESCAPE '\\' OR $2 <% name\n OR EXISTS (SELECT 1 FROM world_record_holders h JOIN players p ON p.steamid64 = h.player_steamid64\n WHERE h.map_id = m.id AND h.style = $5 AND h.track = 0 AND p.name ILIKE $7 ESCAPE '\\'))\n AND ($3::bigint IS NULL OR $4 = EXISTS (\n SELECT 1 FROM personal_bests WHERE player_steamid64 = $3 AND map_id = m.id AND style = $5 AND track = 0))\n AND ($6::smallint IS NULL OR $6 = (SELECT tier FROM current_map_tiers WHERE map_id = m.id AND track = 0))", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "count!", + "type_info": "Int8", + "origin": "Expression" + } + ], + "parameters": { + "Left": [ + "Text", + "Text", + "Int8", + "Bool", + "Text", + "Int2", + "Text" + ] + }, + "nullable": [ + null + ] + }, + "hash": "812bc73f084e7a5f90687cc457d9f91cac3b29f0211e6db655536f3c7eb9ec28" +} diff --git a/api/.sqlx/query-891ebfc26057e472077bd48e10b736a799c3edf11b57a1c8d9208c528360eb3b.json b/api/.sqlx/query-891ebfc26057e472077bd48e10b736a799c3edf11b57a1c8d9208c528360eb3b.json index e34ab12..f6017d1 100644 --- a/api/.sqlx/query-891ebfc26057e472077bd48e10b736a799c3edf11b57a1c8d9208c528360eb3b.json +++ b/api/.sqlx/query-891ebfc26057e472077bd48e10b736a799c3edf11b57a1c8d9208c528360eb3b.json @@ -99,7 +99,7 @@ false, true, null, - true, + false, true, true ] diff --git a/api/.sqlx/query-8e5923b7bc514b6f049477cb1bb1592b470e280661f42180c0ea57f6a36d2fa3.json b/api/.sqlx/query-8e5923b7bc514b6f049477cb1bb1592b470e280661f42180c0ea57f6a36d2fa3.json new file mode 100644 index 0000000..859f51a --- /dev/null +++ b/api/.sqlx/query-8e5923b7bc514b6f049477cb1bb1592b470e280661f42180c0ea57f6a36d2fa3.json @@ -0,0 +1,48 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT m.name, m.listed_at AS \"listed_at!\",\n (SELECT tier FROM current_map_tiers WHERE map_id = m.id AND track = 0) AS tier\n FROM maps m WHERE m.last_run_at IS NOT NULL AND m.listed_at IS NOT NULL\n AND ($2::smallint IS NULL OR $2 =\n (SELECT tier FROM current_map_tiers WHERE map_id = m.id AND track = 0))\n ORDER BY m.listed_at DESC, m.name LIMIT $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "name", + "type_info": "Text", + "origin": { + "Table": { + "table": "maps", + "name": "name" + } + } + }, + { + "ordinal": 1, + "name": "listed_at!", + "type_info": "Timestamptz", + "origin": { + "Table": { + "table": "maps", + "name": "listed_at" + } + } + }, + { + "ordinal": 2, + "name": "tier", + "type_info": "Int2", + "origin": "Expression" + } + ], + "parameters": { + "Left": [ + "Int8", + "Int2" + ] + }, + "nullable": [ + false, + true, + null + ] + }, + "hash": "8e5923b7bc514b6f049477cb1bb1592b470e280661f42180c0ea57f6a36d2fa3" +} diff --git a/api/.sqlx/query-91b58f8ef10a47005cc0b0c35ee66733d0a6e9298a9e7bbdcac70b2048a81488.json b/api/.sqlx/query-91b58f8ef10a47005cc0b0c35ee66733d0a6e9298a9e7bbdcac70b2048a81488.json new file mode 100644 index 0000000..f910d7b --- /dev/null +++ b/api/.sqlx/query-91b58f8ef10a47005cc0b0c35ee66733d0a6e9298a9e7bbdcac70b2048a81488.json @@ -0,0 +1,341 @@ +{ + "db_name": "PostgreSQL", + "query": "\n SELECT r.id, r.map_id, m.name AS map, r.style, r.track, r.time, r.jumps, r.strafes, r.sync, r.perfs,\n r.avg_velocity, r.max_velocity, r.tickrate, r.finished_at, r.ruleset_version,\n r.invalidated_at IS NOT NULL AS \"invalidated!\", s.id AS server_id, s.name AS server_name,\n p.steamid64::text AS \"steamid64!\", p.name, p.avatar_url, p.country_code,\n EXISTS (SELECT 1 FROM personal_bests WHERE run_id = r.id) AS \"personal_best!\",\n (SELECT min(time) FROM personal_bests\n WHERE map_id = r.map_id AND style = r.style AND track = r.track) AS world_record_time,\n (SELECT tier FROM current_map_tiers WHERE map_id = r.map_id AND track = r.track) AS tier,\n ci.id AS \"image_id?\", ci.key AS \"image_key?\", ci.focus AS \"image_focus?\",\n (SELECT key FROM map_cards WHERE map_id = r.map_id) AS map_card_key,\n (SELECT host(h.ip) || ':' || h.port FROM server_heartbeats h\n JOIN server_listings l ON l.ip = h.ip AND l.port = h.port\n WHERE h.server_id = s.id ORDER BY h.received_at DESC LIMIT 1) AS server_address\n FROM runs r\n JOIN maps m ON m.id = r.map_id\n LEFT JOIN map_images ci ON ci.map_id = m.id AND ci.position = 0\n JOIN servers s ON s.id = r.server_id\n JOIN players p ON p.steamid64 = r.player_steamid64\n WHERE r.id = $1\n ", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id", + "type_info": "Int8", + "origin": { + "Table": { + "table": "runs", + "name": "id" + } + } + }, + { + "ordinal": 1, + "name": "map_id", + "type_info": "Int8", + "origin": { + "Table": { + "table": "runs", + "name": "map_id" + } + } + }, + { + "ordinal": 2, + "name": "map", + "type_info": "Text", + "origin": { + "Table": { + "table": "maps", + "name": "name" + } + } + }, + { + "ordinal": 3, + "name": "style", + "type_info": "Text", + "origin": { + "Table": { + "table": "runs", + "name": "style" + } + } + }, + { + "ordinal": 4, + "name": "track", + "type_info": "Int2", + "origin": { + "Table": { + "table": "runs", + "name": "track" + } + } + }, + { + "ordinal": 5, + "name": "time", + "type_info": "Float8", + "origin": { + "Table": { + "table": "runs", + "name": "time" + } + } + }, + { + "ordinal": 6, + "name": "jumps", + "type_info": "Int4", + "origin": { + "Table": { + "table": "runs", + "name": "jumps" + } + } + }, + { + "ordinal": 7, + "name": "strafes", + "type_info": "Int4", + "origin": { + "Table": { + "table": "runs", + "name": "strafes" + } + } + }, + { + "ordinal": 8, + "name": "sync", + "type_info": "Float4", + "origin": { + "Table": { + "table": "runs", + "name": "sync" + } + } + }, + { + "ordinal": 9, + "name": "perfs", + "type_info": "Float4", + "origin": { + "Table": { + "table": "runs", + "name": "perfs" + } + } + }, + { + "ordinal": 10, + "name": "avg_velocity", + "type_info": "Float4", + "origin": { + "Table": { + "table": "runs", + "name": "avg_velocity" + } + } + }, + { + "ordinal": 11, + "name": "max_velocity", + "type_info": "Float4", + "origin": { + "Table": { + "table": "runs", + "name": "max_velocity" + } + } + }, + { + "ordinal": 12, + "name": "tickrate", + "type_info": "Float4", + "origin": { + "Table": { + "table": "runs", + "name": "tickrate" + } + } + }, + { + "ordinal": 13, + "name": "finished_at", + "type_info": "Timestamptz", + "origin": { + "Table": { + "table": "runs", + "name": "finished_at" + } + } + }, + { + "ordinal": 14, + "name": "ruleset_version", + "type_info": "Int4", + "origin": { + "Table": { + "table": "runs", + "name": "ruleset_version" + } + } + }, + { + "ordinal": 15, + "name": "invalidated!", + "type_info": "Bool", + "origin": "Expression" + }, + { + "ordinal": 16, + "name": "server_id", + "type_info": "Int8", + "origin": { + "Table": { + "table": "servers", + "name": "id" + } + } + }, + { + "ordinal": 17, + "name": "server_name", + "type_info": "Text", + "origin": { + "Table": { + "table": "servers", + "name": "name" + } + } + }, + { + "ordinal": 18, + "name": "steamid64!", + "type_info": "Text", + "origin": "Expression" + }, + { + "ordinal": 19, + "name": "name", + "type_info": "Text", + "origin": { + "Table": { + "table": "players", + "name": "name" + } + } + }, + { + "ordinal": 20, + "name": "avatar_url", + "type_info": "Text", + "origin": { + "Table": { + "table": "players", + "name": "avatar_url" + } + } + }, + { + "ordinal": 21, + "name": "country_code", + "type_info": "Text", + "origin": { + "Table": { + "table": "players", + "name": "country_code" + } + } + }, + { + "ordinal": 22, + "name": "personal_best!", + "type_info": "Bool", + "origin": "Expression" + }, + { + "ordinal": 23, + "name": "world_record_time", + "type_info": "Float8", + "origin": "Expression" + }, + { + "ordinal": 24, + "name": "tier", + "type_info": "Int2", + "origin": "Expression" + }, + { + "ordinal": 25, + "name": "image_id?", + "type_info": "Int8", + "origin": { + "Table": { + "table": "map_images", + "name": "id" + } + } + }, + { + "ordinal": 26, + "name": "image_key?", + "type_info": "Text", + "origin": { + "Table": { + "table": "map_images", + "name": "key" + } + } + }, + { + "ordinal": 27, + "name": "image_focus?", + "type_info": "Int2", + "origin": { + "Table": { + "table": "map_images", + "name": "focus" + } + } + }, + { + "ordinal": 28, + "name": "map_card_key", + "type_info": "Text", + "origin": "Expression" + }, + { + "ordinal": 29, + "name": "server_address", + "type_info": "Text", + "origin": "Expression" + } + ], + "parameters": { + "Left": [ + "Int8" + ] + }, + "nullable": [ + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + null, + false, + false, + null, + false, + true, + true, + null, + null, + null, + false, + false, + false, + null, + null + ] + }, + "hash": "91b58f8ef10a47005cc0b0c35ee66733d0a6e9298a9e7bbdcac70b2048a81488" +} diff --git a/api/.sqlx/query-93eea59cfcf180c2a844d37d091ea617589d12ed2e0a83bdd21fadded3c3d003.json b/api/.sqlx/query-93eea59cfcf180c2a844d37d091ea617589d12ed2e0a83bdd21fadded3c3d003.json new file mode 100644 index 0000000..90db3ff --- /dev/null +++ b/api/.sqlx/query-93eea59cfcf180c2a844d37d091ea617589d12ed2e0a83bdd21fadded3c3d003.json @@ -0,0 +1,23 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT coalesce(max(players), 0) AS \"players!\" FROM server_activity_peaks\n WHERE day >= (now() AT TIME ZONE 'UTC')::date - $1::int", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "players!", + "type_info": "Int4", + "origin": "Expression" + } + ], + "parameters": { + "Left": [ + "Int4" + ] + }, + "nullable": [ + null + ] + }, + "hash": "93eea59cfcf180c2a844d37d091ea617589d12ed2e0a83bdd21fadded3c3d003" +} diff --git a/api/.sqlx/query-98312a84043aeb3d9a514bd5a2a3c47074e452da7a1fbfcdbef35f1b7ffd120a.json b/api/.sqlx/query-98312a84043aeb3d9a514bd5a2a3c47074e452da7a1fbfcdbef35f1b7ffd120a.json new file mode 100644 index 0000000..f5d4034 --- /dev/null +++ b/api/.sqlx/query-98312a84043aeb3d9a514bd5a2a3c47074e452da7a1fbfcdbef35f1b7ffd120a.json @@ -0,0 +1,27 @@ +{ + "db_name": "PostgreSQL", + "query": "\n SELECT count(*) AS \"total!\"\n FROM runs r\n LEFT JOIN current_map_tiers tier ON $5 AND tier.map_id = r.map_id AND tier.track = r.track\n WHERE r.invalidated_at IS NULL\n AND (NOT $4 OR r.was_record)\n AND ($1::text IS NULL OR r.style = $1)\n AND ($2::text IS NULL OR ($2 = 'main') = (r.track = 0))\n AND ($3::smallint IS NULL OR tier.tier >= $3)\n ", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "total!", + "type_info": "Int8", + "origin": "Expression" + } + ], + "parameters": { + "Left": [ + "Text", + "Text", + "Int2", + "Bool", + "Bool" + ] + }, + "nullable": [ + null + ] + }, + "hash": "98312a84043aeb3d9a514bd5a2a3c47074e452da7a1fbfcdbef35f1b7ffd120a" +} diff --git a/api/.sqlx/query-a973e3651cccc5eda8cb8d30757435a668d6e76642ce55d5040addaaddf5c017.json b/api/.sqlx/query-a973e3651cccc5eda8cb8d30757435a668d6e76642ce55d5040addaaddf5c017.json new file mode 100644 index 0000000..e45a363 --- /dev/null +++ b/api/.sqlx/query-a973e3651cccc5eda8cb8d30757435a668d6e76642ce55d5040addaaddf5c017.json @@ -0,0 +1,12 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM server_activity_peaks WHERE day < current_date - 400", + "describe": { + "columns": [], + "parameters": { + "Left": [] + }, + "nullable": [] + }, + "hash": "a973e3651cccc5eda8cb8d30757435a668d6e76642ce55d5040addaaddf5c017" +} diff --git a/api/.sqlx/query-afab3e0ac85c5c3927e1c168bf9899a13871b3f97e7980698e7a864b8c129840.json b/api/.sqlx/query-afab3e0ac85c5c3927e1c168bf9899a13871b3f97e7980698e7a864b8c129840.json new file mode 100644 index 0000000..b4055b4 --- /dev/null +++ b/api/.sqlx/query-afab3e0ac85c5c3927e1c168bf9899a13871b3f97e7980698e7a864b8c129840.json @@ -0,0 +1,40 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT name, avatar_url FROM players WHERE steamid64 = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "name", + "type_info": "Text", + "origin": { + "Table": { + "table": "players", + "name": "name" + } + } + }, + { + "ordinal": 1, + "name": "avatar_url", + "type_info": "Text", + "origin": { + "Table": { + "table": "players", + "name": "avatar_url" + } + } + } + ], + "parameters": { + "Left": [ + "Int8" + ] + }, + "nullable": [ + false, + true + ] + }, + "hash": "afab3e0ac85c5c3927e1c168bf9899a13871b3f97e7980698e7a864b8c129840" +} diff --git a/api/.sqlx/query-b34a02fb7fd0b0e3d9de88721cce3a3dbcd335a1cedf1f478478b2f750be1ac8.json b/api/.sqlx/query-b34a02fb7fd0b0e3d9de88721cce3a3dbcd335a1cedf1f478478b2f750be1ac8.json new file mode 100644 index 0000000..10e8bf2 --- /dev/null +++ b/api/.sqlx/query-b34a02fb7fd0b0e3d9de88721cce3a3dbcd335a1cedf1f478478b2f750be1ac8.json @@ -0,0 +1,21 @@ +{ + "db_name": "PostgreSQL", + "query": "\n SELECT max(tier) FROM current_map_tiers\n ", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "max", + "type_info": "Int2", + "origin": "Expression" + } + ], + "parameters": { + "Left": [] + }, + "nullable": [ + null + ] + }, + "hash": "b34a02fb7fd0b0e3d9de88721cce3a3dbcd335a1cedf1f478478b2f750be1ac8" +} diff --git a/api/.sqlx/query-b65cb8b86e6d60caca640368f859f7e2d63c8f537445936874d29cc166c12b6e.json b/api/.sqlx/query-b65cb8b86e6d60caca640368f859f7e2d63c8f537445936874d29cc166c12b6e.json new file mode 100644 index 0000000..5ad3f22 --- /dev/null +++ b/api/.sqlx/query-b65cb8b86e6d60caca640368f859f7e2d63c8f537445936874d29cc166c12b6e.json @@ -0,0 +1,16 @@ +{ + "db_name": "PostgreSQL", + "query": "\n INSERT INTO map_cards (map_id, key, made_from) VALUES ($1, $2, $3)\n ON CONFLICT (map_id) DO UPDATE SET key = excluded.key, made_from = excluded.made_from, made_at = now()\n ", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Int8", + "Text", + "Text" + ] + }, + "nullable": [] + }, + "hash": "b65cb8b86e6d60caca640368f859f7e2d63c8f537445936874d29cc166c12b6e" +} diff --git a/api/.sqlx/query-b7bc9dd0125e73f089f2f336d9f68f8f8b71b1eaa9c775c823a31459e8b00820.json b/api/.sqlx/query-b7bc9dd0125e73f089f2f336d9f68f8f8b71b1eaa9c775c823a31459e8b00820.json new file mode 100644 index 0000000..26d5f71 --- /dev/null +++ b/api/.sqlx/query-b7bc9dd0125e73f089f2f336d9f68f8f8b71b1eaa9c775c823a31459e8b00820.json @@ -0,0 +1,52 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT name, avatar_url, steam_profile_fetched_at FROM players WHERE steamid64 = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "name", + "type_info": "Text", + "origin": { + "Table": { + "table": "players", + "name": "name" + } + } + }, + { + "ordinal": 1, + "name": "avatar_url", + "type_info": "Text", + "origin": { + "Table": { + "table": "players", + "name": "avatar_url" + } + } + }, + { + "ordinal": 2, + "name": "steam_profile_fetched_at", + "type_info": "Timestamptz", + "origin": { + "Table": { + "table": "players", + "name": "steam_profile_fetched_at" + } + } + } + ], + "parameters": { + "Left": [ + "Int8" + ] + }, + "nullable": [ + false, + true, + true + ] + }, + "hash": "b7bc9dd0125e73f089f2f336d9f68f8f8b71b1eaa9c775c823a31459e8b00820" +} diff --git a/api/.sqlx/query-bb9da91e5dd31ed43150f400c10c670dc4b504cea6a119b2f98bb5bfb3dea670.json b/api/.sqlx/query-bb9da91e5dd31ed43150f400c10c670dc4b504cea6a119b2f98bb5bfb3dea670.json deleted file mode 100644 index ecdd558..0000000 --- a/api/.sqlx/query-bb9da91e5dd31ed43150f400c10c670dc4b504cea6a119b2f98bb5bfb3dea670.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "\n WITH now AS MATERIALIZED (\n SELECT b.map_id, b.style, b.track,\n (SELECT min(pb.time) FROM personal_bests pb\n WHERE pb.map_id = b.map_id AND pb.style = b.style AND pb.track = b.track) AS best,\n CASE WHEN $5 THEN (SELECT t.tier FROM map_tiers t WHERE t.map_id = b.map_id AND t.track = b.track\n ORDER BY t.assigned_at DESC LIMIT 1) END AS tier\n FROM unnest($1::int8[], $2::text[], $3::int2[]) AS b (map_id, style, track)\n ), runners AS MATERIALIZED (\n SELECT DISTINCT player_steamid64, style, track > 0 AS bonus FROM runs WHERE id = ANY($4)\n ), moved AS (\n SELECT now.*, stored.best AS stored_best, stored.tier AS stored_tier\n FROM now JOIN standings_boards stored USING (map_id, style, track)\n WHERE now.best IS NOT NULL AND (now.best, now.tier) IS DISTINCT FROM (stored.best, stored.tier)\n ), changes AS (\n SELECT pb.style, pb.track > 0 AS bonus, pb.player_steamid64,\n sum(coalesce(points_for(m.tier, pb.time, m.best, pb.track > 0, $6, $7, $8, $9, $10), 0)\n - coalesce(points_for(m.stored_tier, pb.time, m.stored_best, pb.track > 0,\n $6, $7, $8, $9, $10), 0)) AS change\n FROM moved m\n JOIN personal_bests pb ON pb.map_id = m.map_id AND pb.style = m.style AND pb.track = m.track\n -- The runs' players are summed again below.\n WHERE NOT EXISTS (\n SELECT 1 FROM runners r\n WHERE r.player_steamid64 = pb.player_steamid64 AND r.style = pb.style AND r.bonus = (pb.track > 0)\n )\n GROUP BY 1, 2, 3\n ), moved_totals AS (\n UPDATE standings s SET points = s.points + c.change FROM changes c\n WHERE s.style = c.style AND s.bonus = c.bonus AND s.player_steamid64 = c.player_steamid64\n AND c.change <> 0\n ), emptied AS (\n DELETE FROM standings_boards stored USING now\n WHERE stored.map_id = now.map_id AND stored.style = now.style AND stored.track = now.track\n AND now.best IS NULL\n )\n INSERT INTO standings_boards (map_id, style, track, best, tier)\n SELECT map_id, style, track, best, tier FROM now WHERE best IS NOT NULL\n ON CONFLICT (map_id, style, track) DO UPDATE SET best = excluded.best, tier = excluded.tier\n ", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "Int8Array", - "TextArray", - "Int2Array", - "Int8Array", - "Bool", - "Float8", - "Float8", - "Float8", - "Float8", - "Float8" - ] - }, - "nullable": [] - }, - "hash": "bb9da91e5dd31ed43150f400c10c670dc4b504cea6a119b2f98bb5bfb3dea670" -} diff --git a/api/.sqlx/query-bf0b6142252f2a50b0f7709347f6dc1326618003da8ee7441ed60865af2775a7.json b/api/.sqlx/query-bf0b6142252f2a50b0f7709347f6dc1326618003da8ee7441ed60865af2775a7.json new file mode 100644 index 0000000..0d333b9 --- /dev/null +++ b/api/.sqlx/query-bf0b6142252f2a50b0f7709347f6dc1326618003da8ee7441ed60865af2775a7.json @@ -0,0 +1,191 @@ +{ + "db_name": "PostgreSQL", + "query": "\n WITH holder_maps AS (\n SELECT h.map_id FROM world_record_holders h\n JOIN players p ON p.steamid64 = h.player_steamid64\n WHERE $11::text IS NOT NULL AND h.style = $5 AND h.track = 0\n AND p.name ILIKE $11 ESCAPE '\\'\n ), listed AS (\n SELECT m.id, m.name, m.last_run_at, m.players, tier.tier,\n row_number() OVER (ORDER BY\n -- How well the name matches: exactly, by a word's start (\"candy\" in bhop_candy), or within.\n CASE WHEN $6::text IS NULL OR m.name = $6 THEN 0\n WHEN starts_with(m.name, $6) OR strpos(m.name, '_' || $6) > 0 THEN 1\n WHEN m.name ILIKE $1 ESCAPE '\\' THEN 2\n WHEN m.id IN (SELECT map_id FROM holder_maps) THEN 3 ELSE 4 END,\n CASE WHEN m.name NOT ILIKE $1 ESCAPE '\\' AND $7 <% m.name\n THEN word_similarity($7, m.name) END DESC NULLS LAST,\n CASE WHEN $2 = 'recent' THEN m.last_run_at END DESC,\n CASE WHEN $2 = 'newest' THEN m.listed_at END DESC NULLS LAST,\n CASE $2 WHEN 'popular' THEN -m.players WHEN 'least_popular' THEN m.players END,\n CASE $2 WHEN 'hardest' THEN -tier.tier WHEN 'easiest' THEN tier.tier END NULLS LAST,\n CASE $2 WHEN 'longest_record' THEN -record.time WHEN 'shortest_record' THEN record.time END\n NULLS LAST,\n CASE WHEN $2 = 'newest_record' THEN record.finished_at END DESC NULLS LAST,\n CASE WHEN $2 = 'oldest_record' THEN record.finished_at END NULLS LAST,\n CASE WHEN $2 = 'name_desc' THEN m.name END DESC,\n m.name\n ) AS position\n FROM maps m\n LEFT JOIN current_map_tiers tier ON tier.map_id = m.id AND tier.track = 0\n -- Every map's record, read only for the sorts that need it: the page below reads the page's own.\n LEFT JOIN LATERAL (\n SELECT pb.time, r.finished_at\n FROM personal_bests pb JOIN runs r ON r.id = pb.run_id\n WHERE $2 IN ('longest_record', 'shortest_record', 'newest_record', 'oldest_record') AND pb.map_id = m.id AND pb.style = $5 AND pb.track = 0\n ORDER BY pb.time, r.finished_at\n LIMIT 1\n ) record ON true\n WHERE m.last_run_at IS NOT NULL AND ($1::text IS NULL OR m.name ILIKE $1 ESCAPE '\\'\n OR $7 <% m.name OR m.id IN (SELECT map_id FROM holder_maps))\n AND ($8::bigint IS NULL OR $9 = EXISTS (\n SELECT 1 FROM personal_bests WHERE player_steamid64 = $8 AND map_id = m.id AND style = $5 AND track = 0))\n AND ($10::smallint IS NULL OR tier.tier = $10)\n ), page AS (\n SELECT * FROM listed WHERE position > $4 ORDER BY position LIMIT $3\n )\n SELECT page.name, ci.id AS \"image_id?\", ci.key AS \"image_key?\", ci.focus AS \"image_focus?\", page.last_run_at AS \"last_run_at!\", page.players::int8 AS \"players!\",\n counts.bonuses AS \"bonuses!\", page.tier AS \"tier?\",\n wr.time AS \"wr_time?\", wr.run_id AS \"wr_run_id?\", wr.finished_at AS \"wr_finished_at?\",\n p.steamid64::text AS \"wr_steamid64?\", p.name AS \"wr_name?\", p.avatar_url AS \"wr_avatar_url?\",\n p.country_code AS \"wr_country_code?\"\n FROM page\n LEFT JOIN map_images ci ON ci.map_id = page.id AND ci.position = 0\n CROSS JOIN LATERAL (\n SELECT count(DISTINCT track) FILTER (WHERE track > 0) AS bonuses\n FROM personal_bests WHERE map_id = page.id\n ) counts\n LEFT JOIN LATERAL (\n SELECT pb.player_steamid64, pb.time, pb.run_id, r.finished_at\n FROM personal_bests pb JOIN runs r ON r.id = pb.run_id\n WHERE pb.map_id = page.id AND pb.style = $5 AND pb.track = 0\n ORDER BY pb.time, r.finished_at\n LIMIT 1\n ) wr ON true\n LEFT JOIN players p ON p.steamid64 = wr.player_steamid64\n ORDER BY page.position\n ", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "name", + "type_info": "Text", + "origin": { + "Table": { + "table": "maps", + "name": "name" + } + } + }, + { + "ordinal": 1, + "name": "image_id?", + "type_info": "Int8", + "origin": { + "Table": { + "table": "map_images", + "name": "id" + } + } + }, + { + "ordinal": 2, + "name": "image_key?", + "type_info": "Text", + "origin": { + "Table": { + "table": "map_images", + "name": "key" + } + } + }, + { + "ordinal": 3, + "name": "image_focus?", + "type_info": "Int2", + "origin": { + "Table": { + "table": "map_images", + "name": "focus" + } + } + }, + { + "ordinal": 4, + "name": "last_run_at!", + "type_info": "Timestamptz", + "origin": { + "Table": { + "table": "maps", + "name": "last_run_at" + } + } + }, + { + "ordinal": 5, + "name": "players!", + "type_info": "Int8", + "origin": "Expression" + }, + { + "ordinal": 6, + "name": "bonuses!", + "type_info": "Int8", + "origin": "Expression" + }, + { + "ordinal": 7, + "name": "tier?", + "type_info": "Int2", + "origin": { + "Table": { + "table": "current_map_tiers", + "name": "tier" + } + } + }, + { + "ordinal": 8, + "name": "wr_time?", + "type_info": "Float8", + "origin": { + "Table": { + "table": "personal_bests", + "name": "time" + } + } + }, + { + "ordinal": 9, + "name": "wr_run_id?", + "type_info": "Int8", + "origin": { + "Table": { + "table": "personal_bests", + "name": "run_id" + } + } + }, + { + "ordinal": 10, + "name": "wr_finished_at?", + "type_info": "Timestamptz", + "origin": { + "Table": { + "table": "runs", + "name": "finished_at" + } + } + }, + { + "ordinal": 11, + "name": "wr_steamid64?", + "type_info": "Text", + "origin": "Expression" + }, + { + "ordinal": 12, + "name": "wr_name?", + "type_info": "Text", + "origin": { + "Table": { + "table": "players", + "name": "name" + } + } + }, + { + "ordinal": 13, + "name": "wr_avatar_url?", + "type_info": "Text", + "origin": { + "Table": { + "table": "players", + "name": "avatar_url" + } + } + }, + { + "ordinal": 14, + "name": "wr_country_code?", + "type_info": "Text", + "origin": { + "Table": { + "table": "players", + "name": "country_code" + } + } + } + ], + "parameters": { + "Left": [ + "Text", + "Text", + "Int8", + "Int8", + "Text", + "Text", + "Text", + "Int8", + "Bool", + "Int2", + "Text" + ] + }, + "nullable": [ + false, + false, + false, + false, + true, + null, + null, + true, + true, + true, + true, + null, + true, + true, + true + ] + }, + "hash": "bf0b6142252f2a50b0f7709347f6dc1326618003da8ee7441ed60865af2775a7" +} diff --git a/api/.sqlx/query-c105f82668f6dffc122fd260c3000f3b398402da30de05d54339d0b2a1d852c3.json b/api/.sqlx/query-c105f82668f6dffc122fd260c3000f3b398402da30de05d54339d0b2a1d852c3.json new file mode 100644 index 0000000..33b215e --- /dev/null +++ b/api/.sqlx/query-c105f82668f6dffc122fd260c3000f3b398402da30de05d54339d0b2a1d852c3.json @@ -0,0 +1,54 @@ +{ + "db_name": "PostgreSQL", + "query": "\n WITH bounds AS (\n SELECT make_interval(mins => $1) AS bucket,\n date_bin(make_interval(mins => $1), now(), TIMESTAMPTZ '2000-01-01') AS current,\n date_bin(make_interval(mins => $3), now(), TIMESTAMPTZ '2000-01-01') AS latest\n ), buckets AS (\n SELECT generate_series(current - $2 * bucket, current - bucket, bucket) AS at FROM bounds\n ), per_server AS (\n SELECT date_bin(bounds.bucket, h.received_at, TIMESTAMPTZ '2000-01-01') AS at,\n h.ip, h.port, avg(h.players) AS players\n FROM server_heartbeat_log h\n CROSS JOIN bounds\n JOIN server_listings l ON l.ip = h.ip AND l.port = h.port\n WHERE h.received_at >= bounds.current - $2 * bounds.bucket AND h.received_at < bounds.current\n GROUP BY 1, 2, 3\n ), online AS (\n SELECT m.at, sum(latest.players) AS players\n FROM bounds\n CROSS JOIN generate_series(\n bounds.current - $2 * bounds.bucket,\n bounds.latest,\n make_interval(mins => $3)\n ) AS m(at)\n CROSS JOIN LATERAL (\n SELECT DISTINCT ON (h.ip, h.port) h.players\n FROM server_heartbeat_log h\n JOIN server_listings l ON l.ip = h.ip AND l.port = h.port\n WHERE h.received_at > m.at - make_interval(mins => $4) AND h.received_at <= m.at\n ORDER BY h.ip, h.port, h.received_at DESC\n ) latest\n GROUP BY m.at\n ), peaks AS (\n SELECT date_bin(bounds.bucket, online.at, TIMESTAMPTZ '2000-01-01') AS at, max(online.players) AS players\n FROM online CROSS JOIN bounds\n GROUP BY 1\n ), whole AS (\n SELECT coalesce(max(online.players), 0)::int AS players\n FROM online CROSS JOIN bounds\n WHERE online.at >= bounds.current - $2 * bounds.bucket\n )\n SELECT b.at AS \"at!\", count(p.ip)::int AS \"servers!\", coalesce(round(sum(p.players)), 0)::int AS \"players!\",\n coalesce(pk.players, 0)::int AS \"peak_players!\", whole.players AS \"range_peak!\"\n FROM buckets b\n CROSS JOIN whole\n LEFT JOIN per_server p ON p.at = b.at\n LEFT JOIN peaks pk ON pk.at = b.at\n GROUP BY b.at, pk.players, whole.players\n ORDER BY b.at\n ", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "at!", + "type_info": "Timestamptz", + "origin": "Expression" + }, + { + "ordinal": 1, + "name": "servers!", + "type_info": "Int4", + "origin": "Expression" + }, + { + "ordinal": 2, + "name": "players!", + "type_info": "Int4", + "origin": "Expression" + }, + { + "ordinal": 3, + "name": "peak_players!", + "type_info": "Int4", + "origin": "Expression" + }, + { + "ordinal": 4, + "name": "range_peak!", + "type_info": "Int4", + "origin": "Expression" + } + ], + "parameters": { + "Left": [ + "Int4", + "Float8", + "Int4", + "Int4" + ] + }, + "nullable": [ + null, + null, + null, + null, + null + ] + }, + "hash": "c105f82668f6dffc122fd260c3000f3b398402da30de05d54339d0b2a1d852c3" +} diff --git a/api/.sqlx/query-cd24562230febd3f5cbef6bd3b0f52dec58960f3fbd47a69728e4e020db12a66.json b/api/.sqlx/query-cd24562230febd3f5cbef6bd3b0f52dec58960f3fbd47a69728e4e020db12a66.json new file mode 100644 index 0000000..bc5c891 --- /dev/null +++ b/api/.sqlx/query-cd24562230febd3f5cbef6bd3b0f52dec58960f3fbd47a69728e4e020db12a66.json @@ -0,0 +1,176 @@ +{ + "db_name": "PostgreSQL", + "query": "\n WITH listed AS (\n SELECT r.id, r.map_id, r.style, r.track, r.player_steamid64, r.time, r.finished_at, r.was_record,\n tier.tier\n FROM runs r\n LEFT JOIN current_map_tiers tier ON $7 AND tier.map_id = r.map_id AND tier.track = r.track\n WHERE r.invalidated_at IS NULL\n AND (NOT $4 OR r.was_record)\n AND ($1::text IS NULL OR r.style = $1)\n AND ($2::text IS NULL OR ($2 = 'main') = (r.track = 0))\n AND ($3::smallint IS NULL OR tier.tier >= $3)\n AND ($5::timestamptz IS NULL OR (r.finished_at, r.id) < ($5, $6::bigint))\n ORDER BY r.finished_at DESC, r.id DESC\n LIMIT $8\n )\n SELECT l.id, l.style, l.track, l.time, l.finished_at, l.was_record, l.tier AS \"tier?\", prior.best AS \"best?\",\n m.name AS map, place.placement AS \"placement?\",\n p.steamid64::text AS \"steamid64!\", p.name, p.avatar_url, p.country_code\n FROM listed l\n CROSS JOIN LATERAL (\n SELECT min(e.time) AS best FROM runs e\n WHERE e.map_id = l.map_id AND e.style = l.style AND e.track = l.track\n AND e.invalidated_at IS NULL AND (e.finished_at, e.id) < (l.finished_at, l.id)\n ) prior\n JOIN maps m ON m.id = l.map_id\n JOIN players p ON p.steamid64 = l.player_steamid64\n LEFT JOIN LATERAL (\n SELECT 1 + count(*) AS placement FROM (\n SELECT 1 FROM runs e\n WHERE e.map_id = l.map_id AND e.style = l.style AND e.track = l.track\n AND e.invalidated_at IS NULL AND (e.finished_at, e.id) < (l.finished_at, l.id)\n AND e.player_steamid64 <> l.player_steamid64\n GROUP BY e.player_steamid64\n HAVING min(e.time) < l.time\n ) faster\n ) place ON NOT EXISTS (\n SELECT 1 FROM runs e\n WHERE e.map_id = l.map_id AND e.style = l.style AND e.track = l.track\n AND e.invalidated_at IS NULL AND (e.finished_at, e.id) < (l.finished_at, l.id)\n AND e.player_steamid64 = l.player_steamid64 AND e.time <= l.time\n )\n ORDER BY l.finished_at DESC, l.id DESC\n ", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id", + "type_info": "Int8", + "origin": { + "Table": { + "table": "runs", + "name": "id" + } + } + }, + { + "ordinal": 1, + "name": "style", + "type_info": "Text", + "origin": { + "Table": { + "table": "runs", + "name": "style" + } + } + }, + { + "ordinal": 2, + "name": "track", + "type_info": "Int2", + "origin": { + "Table": { + "table": "runs", + "name": "track" + } + } + }, + { + "ordinal": 3, + "name": "time", + "type_info": "Float8", + "origin": { + "Table": { + "table": "runs", + "name": "time" + } + } + }, + { + "ordinal": 4, + "name": "finished_at", + "type_info": "Timestamptz", + "origin": { + "Table": { + "table": "runs", + "name": "finished_at" + } + } + }, + { + "ordinal": 5, + "name": "was_record", + "type_info": "Bool", + "origin": { + "Table": { + "table": "runs", + "name": "was_record" + } + } + }, + { + "ordinal": 6, + "name": "tier?", + "type_info": "Int2", + "origin": { + "Table": { + "table": "current_map_tiers", + "name": "tier" + } + } + }, + { + "ordinal": 7, + "name": "best?", + "type_info": "Float8", + "origin": "Expression" + }, + { + "ordinal": 8, + "name": "map", + "type_info": "Text", + "origin": { + "Table": { + "table": "maps", + "name": "name" + } + } + }, + { + "ordinal": 9, + "name": "placement?", + "type_info": "Int8", + "origin": "Expression" + }, + { + "ordinal": 10, + "name": "steamid64!", + "type_info": "Text", + "origin": "Expression" + }, + { + "ordinal": 11, + "name": "name", + "type_info": "Text", + "origin": { + "Table": { + "table": "players", + "name": "name" + } + } + }, + { + "ordinal": 12, + "name": "avatar_url", + "type_info": "Text", + "origin": { + "Table": { + "table": "players", + "name": "avatar_url" + } + } + }, + { + "ordinal": 13, + "name": "country_code", + "type_info": "Text", + "origin": { + "Table": { + "table": "players", + "name": "country_code" + } + } + } + ], + "parameters": { + "Left": [ + "Text", + "Text", + "Int2", + "Bool", + "Timestamptz", + "Int8", + "Bool", + "Int8" + ] + }, + "nullable": [ + false, + false, + false, + false, + false, + false, + true, + null, + false, + null, + null, + false, + true, + true + ] + }, + "hash": "cd24562230febd3f5cbef6bd3b0f52dec58960f3fbd47a69728e4e020db12a66" +} diff --git a/api/.sqlx/query-cd642019090b4cdad7393d73198b396a9950973f74105558d979c8dabb664333.json b/api/.sqlx/query-cd642019090b4cdad7393d73198b396a9950973f74105558d979c8dabb664333.json new file mode 100644 index 0000000..5a8cd7c --- /dev/null +++ b/api/.sqlx/query-cd642019090b4cdad7393d73198b396a9950973f74105558d979c8dabb664333.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "\n INSERT INTO standings_boards (map_id, style, track, best, tier)\n SELECT b.map_id, b.style, b.track, b.best, t.tier\n FROM (SELECT map_id, style, track, min(time) AS best FROM personal_bests GROUP BY 1, 2, 3) b\n LEFT JOIN current_map_tiers t ON $1 AND t.map_id = b.map_id AND t.track = b.track\n ", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Bool" + ] + }, + "nullable": [] + }, + "hash": "cd642019090b4cdad7393d73198b396a9950973f74105558d979c8dabb664333" +} diff --git a/api/.sqlx/query-f59c5bfdd8ebefa4312bf431ce8f63aedc42365c6b6809b13146ec436ca8f7c2.json b/api/.sqlx/query-d26414df0abf398bda09dccdafcd315b7ba5f4c8c40779dde663ee8272e27ebe.json similarity index 57% rename from api/.sqlx/query-f59c5bfdd8ebefa4312bf431ce8f63aedc42365c6b6809b13146ec436ca8f7c2.json rename to api/.sqlx/query-d26414df0abf398bda09dccdafcd315b7ba5f4c8c40779dde663ee8272e27ebe.json index 4efb421..eedb98e 100644 --- a/api/.sqlx/query-f59c5bfdd8ebefa4312bf431ce8f63aedc42365c6b6809b13146ec436ca8f7c2.json +++ b/api/.sqlx/query-d26414df0abf398bda09dccdafcd315b7ba5f4c8c40779dde663ee8272e27ebe.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT m.name, week.players AS \"players!\",\n (SELECT tier FROM map_tiers WHERE map_id = m.id AND track = 0 ORDER BY assigned_at DESC LIMIT 1)\n AS tier\n FROM (SELECT map_id, count(DISTINCT player_steamid64) AS players FROM runs\n WHERE invalidated_at IS NULL AND finished_at > now() - interval '7 days'\n GROUP BY map_id) week\n JOIN maps m ON m.id = week.map_id\n ORDER BY week.players DESC, m.name LIMIT $1", + "query": "SELECT m.name, week.players AS \"players!\",\n (SELECT tier FROM current_map_tiers WHERE map_id = m.id AND track = 0) AS tier\n FROM (SELECT map_id, count(DISTINCT player_steamid64) AS players FROM runs\n WHERE invalidated_at IS NULL AND finished_at > now() - interval '7 days'\n GROUP BY map_id) week\n JOIN maps m ON m.id = week.map_id\n ORDER BY week.players DESC, m.name LIMIT $1", "describe": { "columns": [ { @@ -38,5 +38,5 @@ null ] }, - "hash": "f59c5bfdd8ebefa4312bf431ce8f63aedc42365c6b6809b13146ec436ca8f7c2" + "hash": "d26414df0abf398bda09dccdafcd315b7ba5f4c8c40779dde663ee8272e27ebe" } diff --git a/api/.sqlx/query-d50668dfc10a377af5ec4507105877fd56c32b625c17faa483739ead4c3c3a1b.json b/api/.sqlx/query-d50668dfc10a377af5ec4507105877fd56c32b625c17faa483739ead4c3c3a1b.json new file mode 100644 index 0000000..4c70ab6 --- /dev/null +++ b/api/.sqlx/query-d50668dfc10a377af5ec4507105877fd56c32b625c17faa483739ead4c3c3a1b.json @@ -0,0 +1,91 @@ +{ + "db_name": "PostgreSQL", + "query": "\n SELECT pb.player_steamid64::text AS \"steamid64!\", pb.style, pb.track, pb.time, pb.run_id,\n pb.finished_at,\n 1 + (SELECT count(*) FROM personal_bests faster\n WHERE faster.map_id = pb.map_id AND faster.style = pb.style AND faster.track = pb.track\n AND faster.time < pb.time) AS \"rank!\"\n FROM personal_bests pb\n JOIN maps m ON m.id = pb.map_id\n WHERE m.name = $1 AND pb.player_steamid64 = ANY($2)\n ORDER BY pb.player_steamid64, pb.style, pb.track\n ", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "steamid64!", + "type_info": "Text", + "origin": "Expression" + }, + { + "ordinal": 1, + "name": "style", + "type_info": "Text", + "origin": { + "Table": { + "table": "personal_bests", + "name": "style" + } + } + }, + { + "ordinal": 2, + "name": "track", + "type_info": "Int2", + "origin": { + "Table": { + "table": "personal_bests", + "name": "track" + } + } + }, + { + "ordinal": 3, + "name": "time", + "type_info": "Float8", + "origin": { + "Table": { + "table": "personal_bests", + "name": "time" + } + } + }, + { + "ordinal": 4, + "name": "run_id", + "type_info": "Int8", + "origin": { + "Table": { + "table": "personal_bests", + "name": "run_id" + } + } + }, + { + "ordinal": 5, + "name": "finished_at", + "type_info": "Timestamptz", + "origin": { + "Table": { + "table": "personal_bests", + "name": "finished_at" + } + } + }, + { + "ordinal": 6, + "name": "rank!", + "type_info": "Int8", + "origin": "Expression" + } + ], + "parameters": { + "Left": [ + "Text", + "Int8Array" + ] + }, + "nullable": [ + null, + false, + false, + false, + false, + false, + null + ] + }, + "hash": "d50668dfc10a377af5ec4507105877fd56c32b625c17faa483739ead4c3c3a1b" +} diff --git a/api/.sqlx/query-79f8a533b9ffccdb99dad6b682bac3b451a29743fab3da841bd22e572864ff19.json b/api/.sqlx/query-d90f77279563fb737789aa1953cf0b88a1da1097bdace556b747f7ff8a70b8a8.json similarity index 60% rename from api/.sqlx/query-79f8a533b9ffccdb99dad6b682bac3b451a29743fab3da841bd22e572864ff19.json rename to api/.sqlx/query-d90f77279563fb737789aa1953cf0b88a1da1097bdace556b747f7ff8a70b8a8.json index 186b6c9..fed768d 100644 --- a/api/.sqlx/query-79f8a533b9ffccdb99dad6b682bac3b451a29743fab3da841bd22e572864ff19.json +++ b/api/.sqlx/query-d90f77279563fb737789aa1953cf0b88a1da1097bdace556b747f7ff8a70b8a8.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "\n WITH listed AS (\n SELECT r.id, r.map_id, r.style, r.track, r.player_steamid64, r.time, r.finished_at, r.was_record,\n tier.tier\n FROM runs r\n LEFT JOIN LATERAL (SELECT tier FROM map_tiers WHERE map_id = r.map_id AND track = r.track\n ORDER BY assigned_at DESC LIMIT 1) tier ON $7\n WHERE r.invalidated_at IS NULL\n AND (NOT $4 OR r.was_record)\n AND ($1::text IS NULL OR r.style = $1)\n AND ($2::text IS NULL OR ($2 = 'main') = (r.track = 0))\n AND ($3::smallint IS NULL OR tier.tier >= $3)\n AND ($5::timestamptz IS NULL OR (r.finished_at, r.id) < ($5, $6::bigint))\n ORDER BY r.finished_at DESC, r.id DESC\n LIMIT $8\n )\n SELECT l.id, l.style, l.track, l.time, l.finished_at, l.was_record, l.tier AS \"tier?\", prior.best AS \"best?\",\n m.name AS map, place.placement AS \"placement?\",\n p.steamid64::text AS \"steamid64!\", p.name, p.avatar_url, p.country_code\n FROM listed l\n CROSS JOIN LATERAL (\n SELECT min(e.time) AS best FROM runs e\n WHERE e.map_id = l.map_id AND e.style = l.style AND e.track = l.track\n AND e.invalidated_at IS NULL AND (e.finished_at, e.id) < (l.finished_at, l.id)\n ) prior\n JOIN maps m ON m.id = l.map_id\n JOIN players p ON p.steamid64 = l.player_steamid64\n LEFT JOIN LATERAL (\n SELECT 1 + count(*) AS placement FROM (\n SELECT 1 FROM runs e\n WHERE e.map_id = l.map_id AND e.style = l.style AND e.track = l.track\n AND e.invalidated_at IS NULL AND (e.finished_at, e.id) < (l.finished_at, l.id)\n AND e.player_steamid64 <> l.player_steamid64\n GROUP BY e.player_steamid64\n HAVING min(e.time) < l.time\n ) faster\n ) place ON NOT EXISTS (\n SELECT 1 FROM runs e\n WHERE e.map_id = l.map_id AND e.style = l.style AND e.track = l.track\n AND e.invalidated_at IS NULL AND (e.finished_at, e.id) < (l.finished_at, l.id)\n AND e.player_steamid64 = l.player_steamid64 AND e.time <= l.time\n )\n ORDER BY l.finished_at DESC, l.id DESC\n ", + "query": "\n WITH listed AS (\n SELECT r.id, r.map_id, r.style, r.track, r.player_steamid64, r.time, r.finished_at, r.was_record,\n tier.tier\n FROM runs r\n LEFT JOIN current_map_tiers tier ON $7 AND tier.map_id = r.map_id AND tier.track = r.track\n WHERE r.invalidated_at IS NULL\n AND (NOT $4 OR r.was_record)\n AND ($1::text IS NULL OR r.style = $1)\n AND ($2::text IS NULL OR ($2 = 'main') = (r.track = 0))\n AND ($3::smallint IS NULL OR tier.tier >= $3)\n AND ($5::timestamptz IS NULL OR (r.finished_at, r.id) < ($5, $6::bigint))\n ORDER BY r.finished_at DESC, r.id DESC\n LIMIT $8 OFFSET $9\n )\n SELECT l.id, l.style, l.track, l.time, l.finished_at, l.was_record, l.tier AS \"tier?\", prior.best AS \"best?\",\n m.name AS map, place.placement AS \"placement?\",\n p.steamid64::text AS \"steamid64!\", p.name, p.avatar_url, p.country_code\n FROM listed l\n CROSS JOIN LATERAL (\n SELECT min(e.time) AS best FROM runs e\n WHERE e.map_id = l.map_id AND e.style = l.style AND e.track = l.track\n AND e.invalidated_at IS NULL AND (e.finished_at, e.id) < (l.finished_at, l.id)\n ) prior\n JOIN maps m ON m.id = l.map_id\n JOIN players p ON p.steamid64 = l.player_steamid64\n LEFT JOIN LATERAL (\n SELECT 1 + count(*) AS placement FROM (\n SELECT 1 FROM runs e\n WHERE e.map_id = l.map_id AND e.style = l.style AND e.track = l.track\n AND e.invalidated_at IS NULL AND (e.finished_at, e.id) < (l.finished_at, l.id)\n AND e.player_steamid64 <> l.player_steamid64\n GROUP BY e.player_steamid64\n HAVING min(e.time) < l.time\n ) faster\n ) place ON NOT EXISTS (\n SELECT 1 FROM runs e\n WHERE e.map_id = l.map_id AND e.style = l.style AND e.track = l.track\n AND e.invalidated_at IS NULL AND (e.finished_at, e.id) < (l.finished_at, l.id)\n AND e.player_steamid64 = l.player_steamid64 AND e.time <= l.time\n )\n ORDER BY l.finished_at DESC, l.id DESC\n ", "describe": { "columns": [ { @@ -75,7 +75,7 @@ "type_info": "Int2", "origin": { "Table": { - "table": "map_tiers", + "table": "current_map_tiers", "name": "tier" } } @@ -152,6 +152,7 @@ "Timestamptz", "Int8", "Bool", + "Int8", "Int8" ] }, @@ -162,7 +163,7 @@ false, false, false, - false, + true, null, false, null, @@ -172,5 +173,5 @@ true ] }, - "hash": "79f8a533b9ffccdb99dad6b682bac3b451a29743fab3da841bd22e572864ff19" + "hash": "d90f77279563fb737789aa1953cf0b88a1da1097bdace556b747f7ff8a70b8a8" } diff --git a/api/.sqlx/query-dcb58271af8e4bd7cb98a4cbf285784d2d295afaa6ba7731b9ba1fe7e22e101d.json b/api/.sqlx/query-dcb58271af8e4bd7cb98a4cbf285784d2d295afaa6ba7731b9ba1fe7e22e101d.json new file mode 100644 index 0000000..4ad9d2e --- /dev/null +++ b/api/.sqlx/query-dcb58271af8e4bd7cb98a4cbf285784d2d295afaa6ba7731b9ba1fe7e22e101d.json @@ -0,0 +1,39 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT document->'styles' @> jsonb_build_array(jsonb_build_object('key', $2::text)) AS \"ranked!\",\n (document->>'tickrate')::real AS tickrate,\n GREATEST(published_at, (SELECT created_at FROM servers WHERE id = $3)) AS \"earliest!\"\n FROM rulesets WHERE version = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "ranked!", + "type_info": "Bool", + "origin": "Expression" + }, + { + "ordinal": 1, + "name": "tickrate", + "type_info": "Float4", + "origin": "Expression" + }, + { + "ordinal": 2, + "name": "earliest!", + "type_info": "Timestamptz", + "origin": "Expression" + } + ], + "parameters": { + "Left": [ + "Int4", + "Text", + "Int8" + ] + }, + "nullable": [ + null, + null, + null + ] + }, + "hash": "dcb58271af8e4bd7cb98a4cbf285784d2d295afaa6ba7731b9ba1fe7e22e101d" +} diff --git a/api/.sqlx/query-193e0dc6d22809860b4dea9586b0edf496fe92c72a15be5c2b8948824a3d8b8f.json b/api/.sqlx/query-e3f2da6a4f3a50d27266595df7bae4b4440593c64f0391a05a9a99191b169bed.json similarity index 57% rename from api/.sqlx/query-193e0dc6d22809860b4dea9586b0edf496fe92c72a15be5c2b8948824a3d8b8f.json rename to api/.sqlx/query-e3f2da6a4f3a50d27266595df7bae4b4440593c64f0391a05a9a99191b169bed.json index 9c9760e..36105bc 100644 --- a/api/.sqlx/query-193e0dc6d22809860b4dea9586b0edf496fe92c72a15be5c2b8948824a3d8b8f.json +++ b/api/.sqlx/query-e3f2da6a4f3a50d27266595df7bae4b4440593c64f0391a05a9a99191b169bed.json @@ -1,15 +1,15 @@ { "db_name": "PostgreSQL", - "query": "SELECT tier FROM map_tiers WHERE map_id = $1 AND track = $2 ORDER BY assigned_at DESC LIMIT 1", + "query": "SELECT tier AS \"tier!\" FROM current_map_tiers WHERE map_id = $1 AND track = $2", "describe": { "columns": [ { "ordinal": 0, - "name": "tier", + "name": "tier!", "type_info": "Int2", "origin": { "Table": { - "table": "map_tiers", + "table": "current_map_tiers", "name": "tier" } } @@ -22,8 +22,8 @@ ] }, "nullable": [ - false + true ] }, - "hash": "193e0dc6d22809860b4dea9586b0edf496fe92c72a15be5c2b8948824a3d8b8f" + "hash": "e3f2da6a4f3a50d27266595df7bae4b4440593c64f0391a05a9a99191b169bed" } diff --git a/api/.sqlx/query-e9012bc9223b6610b7c31d60ea297dabf0f4666650de0b0bb02053016bbae597.json b/api/.sqlx/query-e9012bc9223b6610b7c31d60ea297dabf0f4666650de0b0bb02053016bbae597.json new file mode 100644 index 0000000..56c3130 --- /dev/null +++ b/api/.sqlx/query-e9012bc9223b6610b7c31d60ea297dabf0f4666650de0b0bb02053016bbae597.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "\n INSERT INTO server_activity_peaks AS p (day, players)\n SELECT (now() AT TIME ZONE 'UTC')::date, coalesce(sum(latest.players), 0)\n FROM (\n SELECT DISTINCT ON (h.ip, h.port) h.players\n FROM server_heartbeat_log h\n JOIN server_listings l ON l.ip = h.ip AND l.port = h.port\n WHERE h.received_at > now() - make_interval(mins => $1)\n ORDER BY h.ip, h.port, h.received_at DESC\n ) latest\n ON CONFLICT (day) DO UPDATE SET players = greatest(p.players, excluded.players)\n ", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Int4" + ] + }, + "nullable": [] + }, + "hash": "e9012bc9223b6610b7c31d60ea297dabf0f4666650de0b0bb02053016bbae597" +} diff --git a/api/.sqlx/query-e93ff3ff9338506b56ece4e87290320a4b6ef774cb4fa306d5a072fe9b9a3212.json b/api/.sqlx/query-e93ff3ff9338506b56ece4e87290320a4b6ef774cb4fa306d5a072fe9b9a3212.json new file mode 100644 index 0000000..4ce9614 --- /dev/null +++ b/api/.sqlx/query-e93ff3ff9338506b56ece4e87290320a4b6ef774cb4fa306d5a072fe9b9a3212.json @@ -0,0 +1,124 @@ +{ + "db_name": "PostgreSQL", + "query": "\n SELECT own.style AS \"style!\", own.map AS \"map!\", own.track AS \"track!\", own.time AS \"time!\",\n 1 + (SELECT count(*) FROM personal_bests faster\n WHERE faster.map_id = own.map_id AND faster.style = own.style\n AND faster.track = own.track AND faster.time < own.time) AS \"rank!\",\n (SELECT min(best.time) FROM personal_bests best\n WHERE best.map_id = own.map_id AND best.style = own.style\n AND best.track = own.track) AS \"world_record_time!\",\n own.run_id AS \"run_id!\", own.finished_at AS \"finished_at!\", tier.tier AS \"tier?\"\n FROM (\n SELECT pb.style, pb.map_id, m.name AS map, pb.track, pb.time, pb.run_id, pb.finished_at\n FROM personal_bests pb\n JOIN maps m ON m.id = pb.map_id\n WHERE pb.player_steamid64 = $1\n AND ($2::text IS NULL OR pb.style = $2)\n AND ($3::text IS NULL OR (m.name, pb.track) > ($3, $4::smallint))\n AND ($6::bool IS NULL OR (pb.track > 0) = $6)\n AND (NOT $7 OR EXISTS (\n SELECT 1 FROM world_record_holders h\n WHERE h.player_steamid64 = $1 AND h.map_id = pb.map_id AND h.style = pb.style\n AND h.track = pb.track))\n AND ($9::timestamptz IS NULL OR (pb.finished_at, pb.run_id) < ($9, $10::int8))\n ORDER BY CASE WHEN $8 THEN pb.finished_at END DESC, CASE WHEN $8 THEN pb.run_id END DESC,\n pb.style, m.name, pb.track\n LIMIT $5\n ) own\n LEFT JOIN current_map_tiers tier ON $11 AND tier.map_id = own.map_id AND tier.track = own.track\n ORDER BY CASE WHEN $8 THEN own.finished_at END DESC, CASE WHEN $8 THEN own.run_id END DESC,\n own.style, own.map, own.track\n ", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "style!", + "type_info": "Text", + "origin": { + "Table": { + "table": "personal_bests", + "name": "style" + } + } + }, + { + "ordinal": 1, + "name": "map!", + "type_info": "Text", + "origin": { + "Table": { + "table": "maps", + "name": "name" + } + } + }, + { + "ordinal": 2, + "name": "track!", + "type_info": "Int2", + "origin": { + "Table": { + "table": "personal_bests", + "name": "track" + } + } + }, + { + "ordinal": 3, + "name": "time!", + "type_info": "Float8", + "origin": { + "Table": { + "table": "personal_bests", + "name": "time" + } + } + }, + { + "ordinal": 4, + "name": "rank!", + "type_info": "Int8", + "origin": "Expression" + }, + { + "ordinal": 5, + "name": "world_record_time!", + "type_info": "Float8", + "origin": "Expression" + }, + { + "ordinal": 6, + "name": "run_id!", + "type_info": "Int8", + "origin": { + "Table": { + "table": "personal_bests", + "name": "run_id" + } + } + }, + { + "ordinal": 7, + "name": "finished_at!", + "type_info": "Timestamptz", + "origin": { + "Table": { + "table": "personal_bests", + "name": "finished_at" + } + } + }, + { + "ordinal": 8, + "name": "tier?", + "type_info": "Int2", + "origin": { + "Table": { + "table": "current_map_tiers", + "name": "tier" + } + } + } + ], + "parameters": { + "Left": [ + "Int8", + "Text", + "Text", + "Int2", + "Int8", + "Bool", + "Bool", + "Bool", + "Timestamptz", + "Int8", + "Bool" + ] + }, + "nullable": [ + false, + false, + false, + false, + null, + null, + false, + false, + true + ] + }, + "hash": "e93ff3ff9338506b56ece4e87290320a4b6ef774cb4fa306d5a072fe9b9a3212" +} diff --git a/api/.sqlx/query-74493942786aa14a6e95ebe6198c28ffd2d175e76f4408e7706e54aedb353845.json b/api/.sqlx/query-e9f09b3277fa13f62738502dad4dcb41391bbe8710c67fe523098acc3af22b33.json similarity index 66% rename from api/.sqlx/query-74493942786aa14a6e95ebe6198c28ffd2d175e76f4408e7706e54aedb353845.json rename to api/.sqlx/query-e9f09b3277fa13f62738502dad4dcb41391bbe8710c67fe523098acc3af22b33.json index 2f81701..e61c244 100644 --- a/api/.sqlx/query-74493942786aa14a6e95ebe6198c28ffd2d175e76f4408e7706e54aedb353845.json +++ b/api/.sqlx/query-e9f09b3277fa13f62738502dad4dcb41391bbe8710c67fe523098acc3af22b33.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "\n WITH listed AS (\n SELECT m.id, m.name, m.last_run_at, m.players, tier.tier,\n row_number() OVER (ORDER BY\n -- How well the name matches: exactly, by a word's start (\"candy\" in bhop_candy), or within.\n CASE WHEN $6::text IS NULL OR m.name = $6 THEN 0\n WHEN starts_with(m.name, $6) OR strpos(m.name, '_' || $6) > 0 THEN 1\n WHEN m.name ILIKE $1 ESCAPE '\\' THEN 2 ELSE 3 END,\n CASE WHEN m.name NOT ILIKE $1 ESCAPE '\\' THEN word_similarity($7, m.name) END DESC NULLS LAST,\n CASE WHEN $2 = 'recent' THEN m.last_run_at END DESC,\n CASE WHEN $2 = 'newest' THEN m.listed_at END DESC NULLS LAST,\n CASE $2 WHEN 'popular' THEN -m.players WHEN 'least_popular' THEN m.players END,\n CASE $2 WHEN 'hardest' THEN -tier.tier WHEN 'easiest' THEN tier.tier END NULLS LAST,\n CASE $2 WHEN 'longest_record' THEN -record.time WHEN 'shortest_record' THEN record.time END\n NULLS LAST,\n CASE WHEN $2 = 'newest_record' THEN record.finished_at END DESC NULLS LAST,\n CASE WHEN $2 = 'oldest_record' THEN record.finished_at END NULLS LAST,\n CASE WHEN $2 = 'name_desc' THEN m.name END DESC,\n m.name\n ) AS position\n FROM maps m\n LEFT JOIN LATERAL (SELECT tier FROM map_tiers WHERE map_id = m.id AND track = 0\n ORDER BY assigned_at DESC LIMIT 1) tier ON true\n -- Every map's record, read only for the sorts that need it: the page below reads the page's own.\n LEFT JOIN LATERAL (\n SELECT pb.time, r.finished_at\n FROM personal_bests pb JOIN runs r ON r.id = pb.run_id\n WHERE $2 IN ('longest_record', 'shortest_record', 'newest_record', 'oldest_record') AND pb.map_id = m.id AND pb.style = $5 AND pb.track = 0\n ORDER BY pb.time, r.finished_at\n LIMIT 1\n ) record ON true\n WHERE m.last_run_at IS NOT NULL AND ($1::text IS NULL OR m.name ILIKE $1 ESCAPE '\\' OR $7 <% m.name)\n AND ($8::bigint IS NULL OR $9 = EXISTS (\n SELECT 1 FROM personal_bests WHERE player_steamid64 = $8 AND map_id = m.id AND style = $5 AND track = 0))\n AND ($10::smallint IS NULL OR tier.tier = $10)\n ), page AS (\n SELECT * FROM listed WHERE position > $4 ORDER BY position LIMIT $3\n )\n SELECT page.name, ci.id AS \"image_id?\", ci.key AS \"image_key?\", ci.focus AS \"image_focus?\", page.last_run_at AS \"last_run_at!\", page.players::int8 AS \"players!\",\n counts.bonuses AS \"bonuses!\", page.tier AS \"tier?\",\n wr.time AS \"wr_time?\", wr.run_id AS \"wr_run_id?\", wr.finished_at AS \"wr_finished_at?\",\n p.steamid64::text AS \"wr_steamid64?\", p.name AS \"wr_name?\", p.avatar_url AS \"wr_avatar_url?\",\n p.country_code AS \"wr_country_code?\"\n FROM page\n LEFT JOIN map_images ci ON ci.map_id = page.id AND ci.position = 0\n CROSS JOIN LATERAL (\n SELECT count(DISTINCT track) FILTER (WHERE track > 0) AS bonuses\n FROM personal_bests WHERE map_id = page.id\n ) counts\n LEFT JOIN LATERAL (\n SELECT pb.player_steamid64, pb.time, pb.run_id, r.finished_at\n FROM personal_bests pb JOIN runs r ON r.id = pb.run_id\n WHERE pb.map_id = page.id AND pb.style = $5 AND pb.track = 0\n ORDER BY pb.time, r.finished_at\n LIMIT 1\n ) wr ON true\n LEFT JOIN players p ON p.steamid64 = wr.player_steamid64\n ORDER BY page.position\n ", + "query": "\n WITH listed AS (\n SELECT m.id, m.name, m.last_run_at, m.players, tier.tier,\n row_number() OVER (ORDER BY\n -- How well the name matches: exactly, by a word's start (\"candy\" in bhop_candy), or within.\n CASE WHEN $6::text IS NULL OR m.name = $6 THEN 0\n WHEN starts_with(m.name, $6) OR strpos(m.name, '_' || $6) > 0 THEN 1\n WHEN m.name ILIKE $1 ESCAPE '\\' THEN 2 ELSE 3 END,\n CASE WHEN m.name NOT ILIKE $1 ESCAPE '\\' THEN word_similarity($7, m.name) END DESC NULLS LAST,\n CASE WHEN $2 = 'recent' THEN m.last_run_at END DESC,\n CASE WHEN $2 = 'newest' THEN m.listed_at END DESC NULLS LAST,\n CASE $2 WHEN 'popular' THEN -m.players WHEN 'least_popular' THEN m.players END,\n CASE $2 WHEN 'hardest' THEN -tier.tier WHEN 'easiest' THEN tier.tier END NULLS LAST,\n CASE $2 WHEN 'longest_record' THEN -record.time WHEN 'shortest_record' THEN record.time END\n NULLS LAST,\n CASE WHEN $2 = 'newest_record' THEN record.finished_at END DESC NULLS LAST,\n CASE WHEN $2 = 'oldest_record' THEN record.finished_at END NULLS LAST,\n CASE WHEN $2 = 'name_desc' THEN m.name END DESC,\n m.name\n ) AS position\n FROM maps m\n LEFT JOIN current_map_tiers tier ON tier.map_id = m.id AND tier.track = 0\n -- Every map's record, read only for the sorts that need it: the page below reads the page's own.\n LEFT JOIN LATERAL (\n SELECT pb.time, r.finished_at\n FROM personal_bests pb JOIN runs r ON r.id = pb.run_id\n WHERE $2 IN ('longest_record', 'shortest_record', 'newest_record', 'oldest_record') AND pb.map_id = m.id AND pb.style = $5 AND pb.track = 0\n ORDER BY pb.time, r.finished_at\n LIMIT 1\n ) record ON true\n WHERE m.last_run_at IS NOT NULL AND ($1::text IS NULL OR m.name ILIKE $1 ESCAPE '\\' OR $7 <% m.name)\n AND ($8::bigint IS NULL OR $9 = EXISTS (\n SELECT 1 FROM personal_bests WHERE player_steamid64 = $8 AND map_id = m.id AND style = $5 AND track = 0))\n AND ($10::smallint IS NULL OR tier.tier = $10)\n ), page AS (\n SELECT * FROM listed WHERE position > $4 ORDER BY position LIMIT $3\n )\n SELECT page.name, ci.id AS \"image_id?\", ci.key AS \"image_key?\", ci.focus AS \"image_focus?\", page.last_run_at AS \"last_run_at!\", page.players::int8 AS \"players!\",\n counts.bonuses AS \"bonuses!\", page.tier AS \"tier?\",\n wr.time AS \"wr_time?\", wr.run_id AS \"wr_run_id?\", wr.finished_at AS \"wr_finished_at?\",\n p.steamid64::text AS \"wr_steamid64?\", p.name AS \"wr_name?\", p.avatar_url AS \"wr_avatar_url?\",\n p.country_code AS \"wr_country_code?\"\n FROM page\n LEFT JOIN map_images ci ON ci.map_id = page.id AND ci.position = 0\n CROSS JOIN LATERAL (\n SELECT count(DISTINCT track) FILTER (WHERE track > 0) AS bonuses\n FROM personal_bests WHERE map_id = page.id\n ) counts\n LEFT JOIN LATERAL (\n SELECT pb.player_steamid64, pb.time, pb.run_id, r.finished_at\n FROM personal_bests pb JOIN runs r ON r.id = pb.run_id\n WHERE pb.map_id = page.id AND pb.style = $5 AND pb.track = 0\n ORDER BY pb.time, r.finished_at\n LIMIT 1\n ) wr ON true\n LEFT JOIN players p ON p.steamid64 = wr.player_steamid64\n ORDER BY page.position\n ", "describe": { "columns": [ { @@ -76,7 +76,7 @@ "type_info": "Int2", "origin": { "Table": { - "table": "map_tiers", + "table": "current_map_tiers", "name": "tier" } } @@ -176,7 +176,7 @@ true, null, null, - false, + true, true, true, true, @@ -186,5 +186,5 @@ true ] }, - "hash": "74493942786aa14a6e95ebe6198c28ffd2d175e76f4408e7706e54aedb353845" + "hash": "e9f09b3277fa13f62738502dad4dcb41391bbe8710c67fe523098acc3af22b33" } diff --git a/api/.sqlx/query-edba6cf047a4c41a5fa80bf5e5c6de783bb61e2e78949dd939cb2c7979de7869.json b/api/.sqlx/query-edba6cf047a4c41a5fa80bf5e5c6de783bb61e2e78949dd939cb2c7979de7869.json new file mode 100644 index 0000000..00c8f4a --- /dev/null +++ b/api/.sqlx/query-edba6cf047a4c41a5fa80bf5e5c6de783bb61e2e78949dd939cb2c7979de7869.json @@ -0,0 +1,16 @@ +{ + "db_name": "PostgreSQL", + "query": "\n UPDATE players SET country_code = $2, country_from_server = true, country_chosen = false\n WHERE steamid64 = $1 AND name_seen_at <= $3\n AND (country_code IS DISTINCT FROM $2 OR NOT country_from_server)\n ", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Int8", + "Text", + "Timestamptz" + ] + }, + "nullable": [] + }, + "hash": "edba6cf047a4c41a5fa80bf5e5c6de783bb61e2e78949dd939cb2c7979de7869" +} diff --git a/api/.sqlx/query-fb61c057eeaad93846cb18dc80de808b8f42a0540f9eee7761f8845c487934f8.json b/api/.sqlx/query-fb61c057eeaad93846cb18dc80de808b8f42a0540f9eee7761f8845c487934f8.json new file mode 100644 index 0000000..88c2c6b --- /dev/null +++ b/api/.sqlx/query-fb61c057eeaad93846cb18dc80de808b8f42a0540f9eee7761f8845c487934f8.json @@ -0,0 +1,17 @@ +{ + "db_name": "PostgreSQL", + "query": "\n UPDATE players SET\n avatar_url = $2,\n -- Steam's country comes last: one a game server found or the player picked stays.\n country_code = CASE WHEN country_chosen OR country_from_server THEN country_code ELSE $3 END,\n steam_profile_fetched_at = now(),\n name = CASE WHEN name_seen_at = '-infinity' AND $4::text IS NOT NULL THEN $4 ELSE name END\n WHERE steamid64 = $1\n ", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Int8", + "Text", + "Text", + "Text" + ] + }, + "nullable": [] + }, + "hash": "fb61c057eeaad93846cb18dc80de808b8f42a0540f9eee7761f8845c487934f8" +} diff --git a/api/.sqlx/query-fcee15572f69a3e3be73825baaade8e35340f56f7b698f6a9eacd18a61dc092e.json b/api/.sqlx/query-fcee15572f69a3e3be73825baaade8e35340f56f7b698f6a9eacd18a61dc092e.json new file mode 100644 index 0000000..d038de9 --- /dev/null +++ b/api/.sqlx/query-fcee15572f69a3e3be73825baaade8e35340f56f7b698f6a9eacd18a61dc092e.json @@ -0,0 +1,23 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT set_config('lock_timeout', $1, true)", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "set_config", + "type_info": "Text", + "origin": "Expression" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + null + ] + }, + "hash": "fcee15572f69a3e3be73825baaade8e35340f56f7b698f6a9eacd18a61dc092e" +} diff --git a/api/.sqlx/query-fd5b8736cae460ef4bcd20932b9e4543feced1f02ad9e893892c36eed2e9a69d.json b/api/.sqlx/query-fd5b8736cae460ef4bcd20932b9e4543feced1f02ad9e893892c36eed2e9a69d.json new file mode 100644 index 0000000..8bf4ecc --- /dev/null +++ b/api/.sqlx/query-fd5b8736cae460ef4bcd20932b9e4543feced1f02ad9e893892c36eed2e9a69d.json @@ -0,0 +1,44 @@ +{ + "db_name": "PostgreSQL", + "query": "\n WITH days AS (\n SELECT generate_series((today - $1::int)::timestamp, (today - 1)::timestamp, interval '1 day')::date AS day\n FROM (SELECT (now() AT TIME ZONE 'UTC')::date AS today) t\n )\n SELECT days.day::timestamp AT TIME ZONE 'UTC' AS \"at!\",\n count(d.ip)::int AS \"servers!\",\n coalesce(round(sum(d.players_sum::float8 / d.heartbeats)), 0)::int AS \"players!\",\n coalesce(pk.players, 0) AS \"peak_players!\"\n FROM days\n LEFT JOIN server_activity_daily d ON d.day = days.day\n AND EXISTS (SELECT 1 FROM server_listings l WHERE l.ip = d.ip AND l.port = d.port)\n LEFT JOIN server_activity_peaks pk ON pk.day = days.day\n GROUP BY days.day, pk.players\n ORDER BY days.day\n ", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "at!", + "type_info": "Timestamptz", + "origin": "Expression" + }, + { + "ordinal": 1, + "name": "servers!", + "type_info": "Int4", + "origin": "Expression" + }, + { + "ordinal": 2, + "name": "players!", + "type_info": "Int4", + "origin": "Expression" + }, + { + "ordinal": 3, + "name": "peak_players!", + "type_info": "Int4", + "origin": "Expression" + } + ], + "parameters": { + "Left": [ + "Int4" + ] + }, + "nullable": [ + null, + null, + null, + null + ] + }, + "hash": "fd5b8736cae460ef4bcd20932b9e4543feced1f02ad9e893892c36eed2e9a69d" +} diff --git a/api/Cargo.lock b/api/Cargo.lock index 3f8cdc9..0aa6ddc 100644 --- a/api/Cargo.lock +++ b/api/Cargo.lock @@ -2,6 +2,22 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "ab_glyph" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01c0457472c38ea5bd1c3b5ada5e368271cb550be7a4ca4a0b4634e9913f6cc2" +dependencies = [ + "ab_glyph_rasterizer", + "owned_ttf_parser", +] + +[[package]] +name = "ab_glyph_rasterizer" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "366ffbaa4442f4684d91e2cd7c5ea7c4ed8add41959a31447066e279e432b618" + [[package]] name = "adler2" version = "2.0.1" @@ -1424,6 +1440,15 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" +[[package]] +name = "owned_ttf_parser" +version = "0.25.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "36820e9051aca1014ddc75770aab4d68bc1e9e632f0f5627c4086bc216fb583b" +dependencies = [ + "ttf-parser", +] + [[package]] name = "parking" version = "2.2.1" @@ -2100,6 +2125,7 @@ dependencies = [ name = "sourcejump-api" version = "0.1.0" dependencies = [ + "ab_glyph", "axum", "axum-extra", "chrono", @@ -2632,6 +2658,12 @@ version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" +[[package]] +name = "ttf-parser" +version = "0.25.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31" + [[package]] name = "typenum" version = "1.20.1" diff --git a/api/contract/maps-personal-bests.json b/api/contract/maps-personal-bests.json new file mode 100644 index 0000000..7b05fda --- /dev/null +++ b/api/contract/maps-personal-bests.json @@ -0,0 +1,28 @@ +{ + "method": "GET", + "path": "/v1/maps/bhop_badges/personal-bests?players=76561197960287930,76561197960287931", + "status": 200, + "response": { + "map": "bhop_badges", + "personal_bests": [ + { + "steamid64": "76561197960287930", + "style": "normal", + "track": 0, + "time": 42.42, + "rank": 1, + "run_id": 1, + "finished_at": "2026-10-19T08:53:20Z" + }, + { + "steamid64": "76561197960287930", + "style": "normal", + "track": 1, + "time": 12.5, + "rank": 3, + "run_id": 2, + "finished_at": "2026-10-19T08:55:00Z" + } + ] + } +} diff --git a/api/crates/api/Cargo.toml b/api/crates/api/Cargo.toml index ffece1b..472c2f8 100644 --- a/api/crates/api/Cargo.toml +++ b/api/crates/api/Cargo.toml @@ -6,6 +6,7 @@ publish.workspace = true license.workspace = true [dependencies] +ab_glyph = "0.2.32" axum = "0.8.9" axum-extra = { version = "0.12.6", features = ["cookie"] } chrono = { version = "0.4.45", default-features = false, features = ["serde", "std"] } diff --git a/api/crates/api/assets/play/OFL.txt b/api/crates/api/assets/play/OFL.txt new file mode 100644 index 0000000..e265281 --- /dev/null +++ b/api/crates/api/assets/play/OFL.txt @@ -0,0 +1,93 @@ +Copyright (c) 2011, Jonas Hecksher, Playtypes, e-types AS (lasse@e-types.com), with Reserved Font Name 'Play', 'Playtype', 'Playtype Sans'. + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/api/crates/api/assets/play/Play-Bold.ttf b/api/crates/api/assets/play/Play-Bold.ttf new file mode 100644 index 0000000..f60bdd1 Binary files /dev/null and b/api/crates/api/assets/play/Play-Bold.ttf differ diff --git a/api/crates/api/assets/play/Play-Regular.ttf b/api/crates/api/assets/play/Play-Regular.ttf new file mode 100644 index 0000000..caaa68c Binary files /dev/null and b/api/crates/api/assets/play/Play-Regular.ttf differ diff --git a/api/crates/api/migrations/0052_current_map_tiers.sql b/api/crates/api/migrations/0052_current_map_tiers.sql new file mode 100644 index 0000000..e7b613d --- /dev/null +++ b/api/crates/api/migrations/0052_current_map_tiers.sql @@ -0,0 +1,8 @@ +-- The tier in force per map and track: the newest assignment in `map_tiers`, which is append-only history. +-- Queries read this instead of each repeating "newest first, take one" (14 copies before it). Conditions on +-- map_id and track reach the primary key through the view, so one map's or track's lookup still reads only its +-- own rows. It says nothing of whether tiers are in force yet (the `tiers` policy); callers still decide that. +CREATE VIEW current_map_tiers AS +SELECT DISTINCT ON (map_id, track) map_id, track, tier, assigned_at, assigned_by +FROM map_tiers +ORDER BY map_id, track, assigned_at DESC; diff --git a/api/crates/api/migrations/0053_map_cards.sql b/api/crates/api/migrations/0053_map_cards.sql new file mode 100644 index 0000000..458a034 --- /dev/null +++ b/api/crates/api/migrations/0053_map_cards.sql @@ -0,0 +1,31 @@ +-- Each map's link card: the picture link previews show for its page, drawn from its cover, name and tier +-- (`maps/card.rs`). A job keeps one card per map with a cover and deletes the one it replaces, so they never pile +-- up. No foreign key to maps, as with standings_boards: checking one locks the map's row, which the ingest can +-- hold for as long as a standings recount takes. +CREATE TABLE map_cards ( + map_id bigint PRIMARY KEY, + -- The stored JPEG, named by its content. + key text NOT NULL UNIQUE CHECK (key ~ '^maps/[a-z0-9_.-]+/card-[0-9a-f]{12}\.jpg$'), + -- What it was drawn from (design version, cover and tier); a card whose inputs changed is drawn again. + made_from text NOT NULL, + made_at timestamptz NOT NULL DEFAULT now() +); + +-- The job sleeps until a card may be out of date, and these wake it: a map's pictures change (the first is the +-- cover), a main track's tier is set, or a tier count is published. Triggers rather than calls in the code, so +-- every way of changing these (site, CLI, imports) wakes it. Postgres sends a notification only once its +-- transaction commits and merges identical ones within it; the job takes every waiting one per wake-up, so a +-- burst (a picture import) costs a pass or two. +CREATE FUNCTION map_cards_wake() RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN + PERFORM pg_notify('map_cards', ''); + RETURN NULL; +END +$$; + +CREATE TRIGGER map_images_wake_map_cards AFTER INSERT OR UPDATE OR DELETE ON map_images + FOR EACH STATEMENT EXECUTE FUNCTION map_cards_wake(); +CREATE TRIGGER map_tiers_wake_map_cards AFTER INSERT ON map_tiers + FOR EACH ROW WHEN (NEW.track = 0) EXECUTE FUNCTION map_cards_wake(); +CREATE TRIGGER policies_wake_map_cards AFTER INSERT ON policies + FOR EACH ROW WHEN (NEW.name = 'tiers') EXECUTE FUNCTION map_cards_wake(); diff --git a/api/crates/api/src/auth.rs b/api/crates/api/src/auth.rs index cda6ca2..8bfa556 100644 --- a/api/crates/api/src/auth.rs +++ b/api/crates/api/src/auth.rs @@ -75,6 +75,7 @@ pub fn routes() -> OpenApiRouter { .routes(routes!(start)) .routes(routes!(callback)) .routes(routes!(sign_out)) + .routes(routes!(sign_out_everywhere)) .routes(routes!(me)) } @@ -189,6 +190,37 @@ async fn sign_out( )) } +/// Ends every session of the signed-in player, in every browser, and signs this one out. A form on the +/// website posts here. Without a live session it only clears this browser's cookie, as signing out does. +#[utoipa::path( + post, + path = "/v1/auth/sign-out-everywhere", + tag = "auth", + params(ReturnQuery), + responses( + (status = SEE_OTHER, description = "Back to the page the player came from, signed out everywhere"), + (status = FORBIDDEN, description = "Not sent from SourceJump's own pages", body = ErrorBody), + ), +)] +async fn sign_out_everywhere( + State(state): State, + headers: HeaderMap, + jar: CookieJar, + signed_in: Option, + Query(query): Query, +) -> Result<(CookieJar, Redirect), ApiError> { + sessions::require_same_origin(&headers, &state.public_url)?; + if let Some(signed_in) = signed_in { + sessions::end_all(&state.db, signed_in.steamid64).await?; + tracing::info!(steamid64 = %signed_in.steamid64, "signed out everywhere"); + } + let return_to = ReturnTo::new(query.return_to.as_deref()); + Ok(( + jar.remove(sessions::removal_cookie()), + Redirect::to(return_to.as_str()), + )) +} + /// The signed-in player, from the session cookie. #[utoipa::path( get, @@ -405,6 +437,48 @@ mod tests { assert_eq!(me_with(&state, &token).await.status, 401); } + #[sqlx::test] + async fn signing_out_everywhere_ends_every_session_of_the_player_only(db: PgPool) { + let state = state(&db, fake_steam(true).await); + let token = session_from(&sign_in(&state).await); + let player = players::SteamId64::try_from(openid::tests::PLAYER.to_owned()).unwrap(); + // The same player signed in on another computer, and someone else signed in. + let elsewhere = sessions::create(&db, player).await.unwrap(); + let other = players::SteamId64::try_from("76561197960287931".to_owned()).unwrap(); + players::ensure_exists(&db, other).await.unwrap(); + let someone_else = sessions::create(&db, other).await.unwrap(); + let sign_out_everywhere = |origin: &'static str| { + test_client::send_to( + state.clone(), + Request::post("/v1/auth/sign-out-everywhere?return_to=/maps") + .header(header::COOKIE, format!("sj_session={token}")) + .header(header::ORIGIN, origin) + .body(Body::empty()) + .unwrap(), + ) + }; + + assert_eq!( + sign_out_everywhere("https://evil.example").await.status, + 403 + ); + assert_eq!(me_with(&state, &elsewhere).await.status, 200); + + let response = sign_out_everywhere("https://sourcejump.test").await; + assert_eq!(response.status, 303); + assert_eq!(response.headers[header::LOCATION], "/maps"); + let removed = set_cookie(&response, "sj_session").expect("the session cookie is removed"); + assert!(removed.starts_with("sj_session=;"), "{removed}"); + assert_eq!(me_with(&state, &token).await.status, 401); + assert_eq!(me_with(&state, &elsewhere).await.status, 401); + assert_eq!(me_with(&state, &someone_else).await.status, 200); + + // Again without a live session: nothing to end, and the same way back. + let again = sign_out_everywhere("https://sourcejump.test").await; + assert_eq!(again.status, 303); + assert_eq!(again.headers[header::LOCATION], "/maps"); + } + #[sqlx::test] async fn start_sends_the_browser_to_steam(db: PgPool) { let response = test_client::get(&db, "/v1/auth/steam?return_to=//evil.example").await; diff --git a/api/crates/api/src/auth/sessions.rs b/api/crates/api/src/auth/sessions.rs index f7e99f2..cc5b484 100644 --- a/api/crates/api/src/auth/sessions.rs +++ b/api/crates/api/src/auth/sessions.rs @@ -40,6 +40,17 @@ pub async fn create(db: &PgPool, steamid64: SteamId64) -> Result Result<(), sqlx::Error> { + sqlx::query!( + "DELETE FROM sessions WHERE player_steamid64 = $1", + steamid64.get() + ) + .execute(db) + .await?; + Ok(()) +} + pub async fn end(db: &PgPool, token: &str) -> Result<(), sqlx::Error> { sqlx::query!("DELETE FROM sessions WHERE hash = $1", &hash(token)[..]) .execute(db) diff --git a/api/crates/api/src/contract.rs b/api/crates/api/src/contract.rs index a64446c..33a5585 100644 --- a/api/crates/api/src/contract.rs +++ b/api/crates/api/src/contract.rs @@ -9,13 +9,14 @@ use sqlx::PgPool; use crate::{ anticheat::DetectionAccepted, error::ErrorBody, plugin_releases::PluginRelease, - record_events::RecordEvents, records::MapRecords, ruleset::Ruleset, runs::RunAccepted, + record_events::RecordEvents, records::MapRecords, + records::personal_bests::PlayersPersonalBests, ruleset::Ruleset, runs::RunAccepted, servers::heartbeat::HeartbeatResponse, servers::keys, test_client, zones::Zone, }; type ResponseCheck = fn(&str, &Value); -const EXAMPLES: [(&str, &str, ResponseCheck); 9] = [ +const EXAMPLES: [(&str, &str, ResponseCheck); 10] = [ ( "ruleset", include_str!("../../../contract/ruleset.json"), @@ -41,6 +42,11 @@ const EXAMPLES: [(&str, &str, ResponseCheck); 9] = [ include_str!("../../../contract/maps-records.json"), round_trips::, ), + ( + "maps-personal-bests", + include_str!("../../../contract/maps-personal-bests.json"), + round_trips::, + ), ( "records-events", include_str!("../../../contract/records-events.json"), @@ -81,6 +87,8 @@ async fn examples_match_the_api(db: PgPool) { .await .unwrap(); let key = keys::issue(&db, "Example server").await.unwrap().key; + // The examples' runs carry fixed times. + crate::runs::tests::backdate(&db).await; for (name, text, check_response) in EXAMPLES { let example: Value = serde_json::from_str(text).unwrap(); diff --git a/api/crates/api/src/leaderboards/standings.rs b/api/crates/api/src/leaderboards/standings.rs index ae609f5..0f2daeb 100644 --- a/api/crates/api/src/leaderboards/standings.rs +++ b/api/crates/api/src/leaderboards/standings.rs @@ -37,6 +37,12 @@ use crate::{ /// The advisory lock every recount holds: "standings" in ASCII. const LOCK: i64 = 0x7374_616e_6469_6e67; +/// How long the ingest waits for another recount to finish. A recount after a personal best takes milliseconds; +/// only a full one (a policy published, or a new formula after a deploy) takes seconds. Waiting behind that +/// would hold the map's row and one of the request pool's connections throughout, and every run arriving +/// meanwhile would do the same until the pool ran out and the whole site stalled. Past this the run gets a +/// 500, and its server sends it again later (`docs/api.md`). +const INGEST_LOCK_WAIT: &str = "2s"; /// How often `watch_ended_bans` looks. Looking costs a few index reads per records ban ever given. const ENDED_BANS_INTERVAL: Duration = Duration::from_mins(5); @@ -93,6 +99,20 @@ pub async fn refresh_runs(conn: &mut PgConnection, run_ids: &[i64]) -> Result<() refresh(conn, &boards, run_ids).await } +/// `refresh_runs` for a run the ingest just stored, giving up on the lock after `INGEST_LOCK_WAIT`. +/// +/// The limit lasts to the end of the ingest's transaction, which this ends: the recount waits for nothing +/// else, as only recounts write its tables and they take turns. +pub async fn refresh_stored_run(conn: &mut PgConnection, run_id: i64) -> Result<(), sqlx::Error> { + sqlx::query!( + "SELECT set_config('lock_timeout', $1, true)", + INGEST_LOCK_WAIT + ) + .fetch_one(&mut *conn) + .await?; + refresh_runs(conn, &[run_id]).await +} + /// After a track's tier changed: recounts its board in every style. pub async fn refresh_track( conn: &mut PgConnection, @@ -150,8 +170,8 @@ async fn refresh( SELECT b.map_id, b.style, b.track, (SELECT min(pb.time) FROM personal_bests pb WHERE pb.map_id = b.map_id AND pb.style = b.style AND pb.track = b.track) AS best, - CASE WHEN $5 THEN (SELECT t.tier FROM map_tiers t WHERE t.map_id = b.map_id AND t.track = b.track - ORDER BY t.assigned_at DESC LIMIT 1) END AS tier + CASE WHEN $5 THEN (SELECT t.tier FROM current_map_tiers t + WHERE t.map_id = b.map_id AND t.track = b.track) END AS tier FROM unnest($1::int8[], $2::text[], $3::int2[]) AS b (map_id, style, track) ), runners AS MATERIALIZED ( SELECT DISTINCT player_steamid64, style, track > 0 AS bonus FROM runs WHERE id = ANY($4) @@ -262,14 +282,10 @@ pub async fn refresh_all(conn: &mut PgConnection) -> Result<(), sqlx::Error> { .await?; sqlx::query!( r#" - WITH tiers AS ( - SELECT DISTINCT ON (map_id, track) map_id, track, tier FROM map_tiers - WHERE $1 ORDER BY map_id, track, assigned_at DESC - ) INSERT INTO standings_boards (map_id, style, track, best, tier) SELECT b.map_id, b.style, b.track, b.best, t.tier FROM (SELECT map_id, style, track, min(time) AS best FROM personal_bests GROUP BY 1, 2, 3) b - LEFT JOIN tiers t ON t.map_id = b.map_id AND t.track = b.track + LEFT JOIN current_map_tiers t ON $1 AND t.map_id = b.map_id AND t.track = b.track "#, formula.tiers ) @@ -518,6 +534,39 @@ pub(crate) mod tests { assert_totals_current(&db).await; } + /// Behind a long recount, a new personal best gives up waiting instead of holding its connection: the + /// server gets a 500, nothing of the run is kept, and sending it again later stores and counts it once. + #[sqlx::test] + async fn the_ingest_gives_up_waiting_behind_a_long_recount(db: PgPool) { + let key = setup(&db).await; + test_client::post(&db, "/v1/runs", Some(&key), &run("a", 30.0)).await; + + let mut holder = db.begin().await.unwrap(); + super::lock(&mut holder).await.unwrap(); + let started = std::time::Instant::now(); + let refused = test_client::post(&db, "/v1/runs", Some(&key), &run("b", 29.0)).await; + assert_eq!(refused.status, 500, "a 5xx, which servers send again later"); + assert!( + started.elapsed() < Duration::from_secs(5), + "gave up after the wait" + ); + let kept: i64 = sqlx::query_scalar("SELECT count(*) FROM runs WHERE server_run_id = 'b'") + .fetch_one(&db) + .await + .unwrap(); + assert_eq!(kept, 0, "the run's transaction was rolled back"); + + holder.commit().await.unwrap(); + let stored = test_client::post(&db, "/v1/runs", Some(&key), &run("b", 29.0)).await; + assert_eq!(stored.status, 201); + let best: f64 = sqlx::query_scalar("SELECT time FROM personal_bests") + .fetch_one(&db) + .await + .unwrap(); + assert_eq!(best, 29.0); + assert_totals_current(&db).await; + } + /// A tier change waiting for the standings lock, then a full recount behind it. They once deadlocked, when /// recounts wrote personal bests. #[sqlx::test] diff --git a/api/crates/api/src/main.rs b/api/crates/api/src/main.rs index 0d66454..adb6df6 100644 --- a/api/crates/api/src/main.rs +++ b/api/crates/api/src/main.rs @@ -67,7 +67,9 @@ usage: sourcejump-api [command] privileges revoke ... take them away again (logged) privileges list name every privilege legacy import replace the pre-2.0 records with the old site's dump, carrying its bans over (logged) - world-records rebuild recount the stored world records from the runs and say how many rows were wrong"; + world-records rebuild recount the stored world records from the runs and say how many rows were wrong + site-card draw the site's link card from a picture (web/src/features/home/header.png) into + a JPEG file (web/public/link-card.jpg)"; #[tokio::main] async fn main() -> Result<(), Box> { @@ -163,6 +165,7 @@ async fn main() -> Result<(), Box> { } ["legacy", "import", folder] => import_legacy(folder).await, ["world-records", "rebuild"] => rebuild_world_records().await, + ["site-card", picture, file] => draw_site_card(picture, file), ["help" | "--help"] => { println!("{USAGE}"); Ok(()) @@ -171,6 +174,13 @@ async fn main() -> Result<(), Box> { } } +fn draw_site_card(picture: &str, file: &str) -> Result<(), Box> { + let picture = std::fs::read(picture).map_err(|error| format!("{picture}: {error}"))?; + std::fs::write(file, maps::card::draw::site_card(&picture)?)?; + println!("Drew the site's link card into {file}."); + Ok(()) +} + async fn make_viewer_file(map: &str, file: &str) -> Result<(), Box> { let map = maps::MapName::try_from(map.to_owned())?; let (db, storage) = (connect().await?, storage::Storage::from_env()?); @@ -405,6 +415,7 @@ async fn serve() -> Result<(), Box> { staging.clone(), )); tokio::spawn(daily_totals::run(db.clone())); + tokio::spawn(maps::card::run(db.clone(), storage.clone())); tokio::spawn(leaderboards::standings::watch_ended_bans(db.clone())); tokio::spawn(record_events::run(db.clone())); tokio::spawn(servers::heartbeat::run(db.clone())); @@ -477,6 +488,8 @@ async fn shutdown_signal() { let ctrl_c = async { tokio::signal::ctrl_c().await.ok(); }; + // SIGTERM exists only on Unix; elsewhere (a contributor's Windows machine) Ctrl+C is the only way to stop. + #[cfg(unix)] let terminate = async { if let Ok(mut sig) = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) @@ -484,6 +497,8 @@ async fn shutdown_signal() { sig.recv().await; } }; + #[cfg(not(unix))] + let terminate = std::future::pending::<()>(); tokio::select! { () = ctrl_c => {}, () = terminate => {}, diff --git a/api/crates/api/src/maps.rs b/api/crates/api/src/maps.rs index 6e15a9e..aa8fdbb 100644 --- a/api/crates/api/src/maps.rs +++ b/api/crates/api/src/maps.rs @@ -1,6 +1,7 @@ //! Maps, identified by their lowercase name, and the map pages' endpoints: the map list, a map's details, //! its leaderboards and its WR history, each map's file for the web viewer, and the stock content it draws on. +pub mod card; mod detail; pub mod image; mod leaderboard; diff --git a/api/crates/api/src/maps/card.rs b/api/crates/api/src/maps/card.rs new file mode 100644 index 0000000..0b69ca4 --- /dev/null +++ b/api/crates/api/src/maps/card.rs @@ -0,0 +1,343 @@ +//! Maps' link cards (`map_cards`): the picture a link to a map or one of its runs shows on Discord and elsewhere. +//! `draw.rs` draws them; a job here keeps them current. +//! +//! A card is drawn from the map's cover, name and tier and nothing that changes often, so it stays right and +//! there is one per map, however many links are shared. The job draws a card when a map gets a cover, or its +//! cover or tier in force changes, and deletes the one it replaces; a map whose pictures are all removed loses +//! its card. It sleeps until triggers on those tables wake it (`migrations/0053_map_cards.sql`), then checks +//! every map in one small query and draws only what's out of date. Cards are stored like map pictures, under a name from their content, so caches keep them for good. +//! Pages without a card (maps without a cover, and every other page) show the site's card, which the web app +//! serves itself (`draw::site_card`). + +pub mod draw; + +use std::{collections::HashSet, fmt::Write, time::Duration}; + +use sha2::{Digest, Sha256}; +use sqlx::{PgPool, postgres::PgListener}; + +use super::{ + image::{LARGE, file_key}, + tiers, +}; +use crate::storage::Storage; + +/// The channel the triggers notify. +const CHANNEL: &str = "map_cards"; +/// A pass without a wake-up, for a notification lost while the listener reconnected. +const FALLBACK: Duration = Duration::from_hours(1); +const LISTEN_RETRY: Duration = Duration::from_secs(5); +/// Raise when `draw.rs` changes how cards look, so every card is drawn again. +const DESIGN: u32 = 1; + +/// Runs for as long as the API does. Reconnects on its own. +pub async fn run(db: PgPool, storage: Storage) { + // Cards that couldn't be drawn, by map and inputs, so a broken cover is reported once rather than on every + // pass; a new cover or tier tries again. + let mut failed = HashSet::new(); + loop { + if let Err(error) = listen(&db, &storage, &mut failed).await { + tracing::warn!(%error, "map card listener lost; reconnecting"); + } + tokio::time::sleep(LISTEN_RETRY).await; + } +} + +/// A pass, then another each time a trigger wakes it or the fallback runs out. +async fn listen( + db: &PgPool, + storage: &Storage, + failed: &mut HashSet<(i64, String)>, +) -> Result<(), sqlx::Error> { + let mut listener = PgListener::connect_with(db).await?; + listener.listen(CHANNEL).await?; + loop { + // The first pass covers whatever changed while nobody listened: at startup, or before a reconnect. + if let Err(error) = refresh(db, storage, failed).await { + tracing::error!(%error, "map card pass failed; trying again on the next change"); + } + if let Ok(woken) = tokio::time::timeout(FALLBACK, listener.recv()).await { + woken?; + } + // Changes that came in a burst are all covered by the next pass. + while listener.next_buffered().is_some() {} + } +} + +/// Draws every card that's missing or out of date, and removes those of maps without a cover. +pub async fn refresh( + db: &PgPool, + storage: &Storage, + failed: &mut HashSet<(i64, String)>, +) -> Result<(), sqlx::Error> { + // Tiers show only once the community has decided a count, as everywhere else. + let tier_count = tiers::tier_count(db).await?; + let maps = sqlx::query!( + r#" + SELECT m.id AS "id!", m.name AS "name!", i.key AS "cover?", t.tier AS "tier?", c.key AS "card?", c.made_from AS "made_from?" + FROM maps m + LEFT JOIN map_images i ON i.map_id = m.id AND i.position = 0 + LEFT JOIN current_map_tiers t ON t.map_id = m.id AND t.track = 0 + LEFT JOIN map_cards c ON c.map_id = m.id + WHERE i.key IS NOT NULL OR c.map_id IS NOT NULL + "# + ) + .fetch_all(db) + .await?; + + for map in maps { + let Some(cover) = map.cover else { + let card = map + .card + .expect("the query lists only maps with a cover or a card"); + remove(db, storage, map.id, &card).await?; + continue; + }; + let tier = map.tier.filter(|_| tier_count.is_some()); + let made_from = made_from(&cover, tier); + if map.made_from.as_deref() == Some(made_from.as_str()) { + continue; + } + let attempt = (map.id, made_from); + if failed.contains(&attempt) { + continue; + } + let made_from = &attempt.1; + match make(db, storage, map.id, &map.name, &cover, tier, made_from).await { + Ok(()) => { + if let Some(old) = map.card { + delete_file(storage, &old).await; + } + } + Err(error) => { + tracing::error!(map = %map.name, %error, "couldn't make the map's card"); + failed.insert(attempt); + } + } + } + Ok(()) +} + +/// What a card is drawn from, as stored in `map_cards.made_from`. +fn made_from(cover: &str, tier: Option) -> String { + let tier = tier.map_or_else(|| "-".to_owned(), |tier| tier.to_string()); + format!("{DESIGN}/{cover}/{tier}") +} + +/// Draws and stores a map's card and records it. Drawing takes a fraction of a second of CPU, so it runs off the +/// async threads. +async fn make( + db: &PgPool, + storage: &Storage, + map_id: i64, + name: &str, + cover: &str, + tier: Option, + made_from: &str, +) -> Result<(), String> { + let picture = storage + .get(&file_key(cover, LARGE)) + .await + .map_err(|error| format!("reading the cover: {error}"))?; + let card = { + let name = name.to_owned(); + tokio::task::spawn_blocking(move || draw::map_card(&picture, &name, tier)) + .await + .map_err(|error| format!("drawing: {error}"))?? + }; + let key = format!("maps/{name}/card-{}.jpg", short_hash(&card)); + storage + .put_immutable(&key, "image/jpeg", None, card) + .await + .map_err(|error| format!("storing: {error}"))?; + sqlx::query!( + r#" + INSERT INTO map_cards (map_id, key, made_from) VALUES ($1, $2, $3) + ON CONFLICT (map_id) DO UPDATE SET key = excluded.key, made_from = excluded.made_from, made_at = now() + "#, + map_id, + key, + made_from + ) + .execute(db) + .await + .map_err(|error| format!("recording: {error}"))?; + Ok(()) +} + +async fn remove( + db: &PgPool, + storage: &Storage, + map_id: i64, + card: &str, +) -> Result<(), sqlx::Error> { + sqlx::query!("DELETE FROM map_cards WHERE map_id = $1", map_id) + .execute(db) + .await?; + delete_file(storage, card).await; + Ok(()) +} + +/// Deletes a card's file once nothing points at it. A failure leaves an unused file behind, which costs little, +/// so it's logged rather than retried. +async fn delete_file(storage: &Storage, key: &str) { + if let Err(error) = storage.delete(key).await { + tracing::warn!(%key, %error, "couldn't delete a replaced map card"); + } +} + +/// The first 12 hex digits of the SHA-256, as map pictures are named. +fn short_hash(bytes: &[u8]) -> String { + let mut hash = String::with_capacity(12); + for byte in &Sha256::digest(bytes)[..6] { + write!(hash, "{byte:02x}").expect("writing to a String can't fail"); + } + hash +} + +#[cfg(test)] +mod tests { + use sqlx::PgPool; + + use super::*; + use crate::{ + maps::{MapName, image::tests::png}, + staff::{map_images, maps::set_tier}, + }; + + const MAP: &str = "bhop_fresh"; + + async fn card_of(db: &PgPool) -> Option<(String, String)> { + sqlx::query!("SELECT c.key, c.made_from FROM map_cards c JOIN maps m ON m.id = c.map_id") + .fetch_optional(db) + .await + .unwrap() + .map(|row| (row.key, row.made_from)) + } + + fn cards_stored(storage: &Storage) -> Vec { + let mut keys: Vec = storage + .objects + .lock() + .unwrap() + .keys() + .filter(|key| key.contains("/card-")) + .cloned() + .collect(); + keys.sort(); + keys + } + + #[sqlx::test] + async fn keeps_one_current_card_per_map_with_a_cover(db: PgPool) { + let storage = Storage::for_tests(); + let mut failed = HashSet::new(); + let map = MapName::try_from(MAP.to_owned()).unwrap(); + sqlx::query!("INSERT INTO maps (name) VALUES ($1)", MAP) + .execute(&db) + .await + .unwrap(); + + // No cover, no card. + refresh(&db, &storage, &mut failed).await.unwrap(); + assert_eq!(card_of(&db).await, None); + + let image = map_images::add_image(&db, &storage, None, &map, png(1920, 1080)) + .await + .unwrap(); + refresh(&db, &storage, &mut failed).await.unwrap(); + let (first, made_from) = card_of(&db).await.expect("a card for the cover"); + assert!( + made_from.ends_with("/-"), + "no tier while tiers aren't decided: {made_from}" + ); + assert_eq!(cards_stored(&storage), std::slice::from_ref(&first)); + + // A tier is published and set. + sqlx::query!( + r#"INSERT INTO policies (name, version, value) VALUES ('tiers', 1, '{"count": 6}')"# + ) + .execute(&db) + .await + .unwrap(); + set_tier(&db, None, &map, 0, 3).await.unwrap(); + refresh(&db, &storage, &mut failed).await.unwrap(); + let (second, made_from) = card_of(&db).await.unwrap(); + assert!(made_from.ends_with("/3"), "{made_from}"); + assert_ne!(second, first); + assert_eq!( + cards_stored(&storage), + [second], + "the replaced card is deleted" + ); + + // Nothing changed: nothing drawn. + refresh(&db, &storage, &mut failed).await.unwrap(); + assert_eq!(cards_stored(&storage).len(), 1); + + map_images::remove_image(&db, &storage, None, &map, image) + .await + .unwrap(); + refresh(&db, &storage, &mut failed).await.unwrap(); + assert_eq!(card_of(&db).await, None); + assert_eq!(cards_stored(&storage), Vec::::new()); + } + + #[sqlx::test] + async fn a_cover_that_cant_be_drawn_is_tried_once(db: PgPool) { + let storage = Storage::for_tests(); + let mut failed = HashSet::new(); + let map = MapName::try_from(MAP.to_owned()).unwrap(); + sqlx::query!("INSERT INTO maps (name) VALUES ($1)", MAP) + .execute(&db) + .await + .unwrap(); + let image = map_images::add_image(&db, &storage, None, &map, png(1920, 1080)) + .await + .unwrap(); + let key = sqlx::query_scalar!("SELECT key FROM map_images WHERE id = $1", image) + .fetch_one(&db) + .await + .unwrap(); + storage + .objects + .lock() + .unwrap() + .insert(file_key(&key, LARGE), b"damaged".to_vec()); + + refresh(&db, &storage, &mut failed).await.unwrap(); + assert_eq!(card_of(&db).await, None); + assert_eq!(failed.len(), 1); + } + + #[sqlx::test] + async fn cover_and_tier_changes_wake_the_job(db: PgPool) { + let storage = Storage::for_tests(); + let map = MapName::try_from(MAP.to_owned()).unwrap(); + sqlx::query!("INSERT INTO maps (name) VALUES ($1)", MAP) + .execute(&db) + .await + .unwrap(); + let mut listener = PgListener::connect_with(&db).await.unwrap(); + listener.listen(CHANNEL).await.unwrap(); + let mut woken = async || { + tokio::time::timeout(Duration::from_secs(5), listener.recv()) + .await + .is_ok() + }; + + map_images::add_image(&db, &storage, None, &map, png(1920, 1080)) + .await + .unwrap(); + assert!(woken().await, "a new cover"); + sqlx::query!( + r#"INSERT INTO policies (name, version, value) VALUES ('tiers', 1, '{"count": 6}')"# + ) + .execute(&db) + .await + .unwrap(); + assert!(woken().await, "a tier count"); + set_tier(&db, None, &map, 0, 3).await.unwrap(); + assert!(woken().await, "a main track's tier"); + } +} diff --git a/api/crates/api/src/maps/card/draw.rs b/api/crates/api/src/maps/card/draw.rs new file mode 100644 index 0000000..bed4e0f --- /dev/null +++ b/api/crates/api/src/maps/card/draw.rs @@ -0,0 +1,369 @@ +//! Drawing link cards: the 1200×630 pictures that link previews (Discord, Steam, X) show for a page. A map's card +//! is its cover with the SourceJump wordmark, the map's tier icon and its name; the site's card, used where a page +//! has no picture of its own, is the home page's header picture with the wordmark and the site's description. +//! +//! Text is set in Play, the site's font (`assets/play/`, SIL Open Font License), so cards match the pages. +//! Cards are JPEG rather than the WebP the map pictures use: some link previewers still don't show WebP. + +// Pixel positions move between whole and fractional numbers here; all of them are a few thousand at most, far +// inside what f32 holds exactly, and the drawing code skips any that land off the card. +#![allow( + clippy::cast_precision_loss, + clippy::cast_possible_truncation, + clippy::cast_sign_loss +)] + +use std::{io::Cursor, sync::LazyLock}; + +use ab_glyph::{Font, FontRef, Glyph, PxScale, ScaleFont, point}; +use image::{ImageReader, RgbImage, RgbaImage, codecs::jpeg::JpegEncoder, imageops::FilterType}; + +/// Open Graph's recommended size; Discord and X show it without cropping. +pub const SIZE: (u32, u32) = (1200, 630); +/// JPEG quality, 0–100. 85 keeps the text's edges clean at around 60–90 KB a card. +const QUALITY: u8 = 85; + +/// The site's colours (`web/src/ui/tokens.css`): the page background, text, muted text and accent. +const BACKGROUND: [u8; 3] = [0x0e, 0x16, 0x22]; +const TEXT: [u8; 3] = [0xe3, 0xea, 0xf3]; +const TEXT_SOFT: [u8; 3] = [0xc4, 0xd0, 0xe0]; +const ACCENT: [u8; 3] = [0x00, 0xc8, 0xf0]; + +/// The space between the card's edge and its text, as on the site's pages at their widest. +const MARGIN: f32 = 64.0; + +static BOLD: LazyLock> = LazyLock::new(|| { + FontRef::try_from_slice(include_bytes!("../../../assets/play/Play-Bold.ttf")) + .expect("the bundled font is valid") +}); +static REGULAR: LazyLock> = LazyLock::new(|| { + FontRef::try_from_slice(include_bytes!("../../../assets/play/Play-Regular.ttf")) + .expect("the bundled font is valid") +}); + +/// The tier icons the Discord record feed shows (`scripts/tier-icons.py`), shared so a map's tier looks the same +/// in a record post and in a link to the map. Index is the tier. +const TIER_ICONS: [&[u8]; 11] = [ + include_bytes!("../../../../../../web/public/tiers/t0.png"), + include_bytes!("../../../../../../web/public/tiers/t1.png"), + include_bytes!("../../../../../../web/public/tiers/t2.png"), + include_bytes!("../../../../../../web/public/tiers/t3.png"), + include_bytes!("../../../../../../web/public/tiers/t4.png"), + include_bytes!("../../../../../../web/public/tiers/t5.png"), + include_bytes!("../../../../../../web/public/tiers/t6.png"), + include_bytes!("../../../../../../web/public/tiers/t7.png"), + include_bytes!("../../../../../../web/public/tiers/t8.png"), + include_bytes!("../../../../../../web/public/tiers/t9.png"), + include_bytes!("../../../../../../web/public/tiers/t10.png"), +]; +const TIER_ICON_SIZE: u32 = 112; + +/// The site's description, as the web app's root layout gives it. +const SITE_DESCRIPTION: &str = "Global records for the Counter-Strike: Source bunnyhop community."; + +/// A map's card: the cover (a stored map picture), the wordmark, the tier icon when there is a tier to show, and +/// the name. A tier without an icon (above 10) is left out rather than drawn some other way. +pub fn map_card(cover: &[u8], name: &str, tier: Option) -> Result, String> { + let mut card = background(cover)?; + // Darkened at the top for the wordmark and more at the bottom for the name, so both read on a bright cover. + shade_down( + &mut card, + &[ + (0.0, 0.82), + (0.30, 0.0), + (0.45, 0.0), + (0.72, 0.78), + (1.0, 0.96), + ], + ); + wordmark(&mut card, 34.0, MARGIN, 52.0); + + let center = SIZE.1 as f32 - 58.0 - TIER_ICON_SIZE as f32 / 2.0; + let mut left = MARGIN; + if let Some(icon) = tier.and_then(|tier| TIER_ICONS.get(usize::try_from(tier).ok()?)) { + let icon = image::load_from_memory(icon) + .expect("the bundled tier icons are valid") + .to_rgba8(); + let icon = + image::imageops::resize(&icon, TIER_ICON_SIZE, TIER_ICON_SIZE, FilterType::Lanczos3); + overlay( + &mut card, + &icon, + left as i64, + (center - TIER_ICON_SIZE as f32 / 2.0) as i64, + ); + left += TIER_ICON_SIZE as f32 + 28.0; + } + let (px, name) = fit(&BOLD, name, SIZE.0 as f32 - MARGIN - left); + let line = Line::new(&BOLD, px, 0.0, &name); + line.draw(&mut card, left, line.baseline_centered_on(center), |_| TEXT); + encode(&card) +} + +/// The site's card, for pages without a picture of their own: the given picture (the home page's header) with +/// the wordmark and the site's description over a shade from the left. Made once with the API's `site-card` +/// command and committed to the web app. +pub fn site_card(picture: &[u8]) -> Result, String> { + let mut card = background(picture)?; + shade_across(&mut card, &[(0.0, 0.82), (0.45, 0.35), (0.70, 0.0)]); + let description = Line::new(®ULAR, 30.0, 0.0, SITE_DESCRIPTION); + let description_baseline = SIZE.1 as f32 - 72.0; + description.draw(&mut card, MARGIN, description_baseline, |_| TEXT_SOFT); + wordmark(&mut card, 72.0, MARGIN, description_baseline - 160.0); + encode(&card) +} + +/// "SOURCEJUMP" in the header's style: bold capitals spaced a tenth of their size apart, "JUMP" in the accent. +/// `top` is where the capitals start. +fn wordmark(card: &mut RgbImage, px: f32, left: f32, top: f32) { + let line = Line::new(&BOLD, px, px * 0.1, "SOURCEJUMP"); + let baseline = top + line.cap_height(); + line.draw( + card, + left, + baseline, + |index| if index < 6 { TEXT } else { ACCENT }, + ); +} + +/// The largest size from 84 px down to 52 px at which the name fits in `width`; a name too long even then is +/// cut short with an ellipsis. +fn fit(font: &FontRef<'static>, name: &str, width: f32) -> (f32, String) { + const LARGEST: f32 = 84.0; + const SMALLEST: f32 = 52.0; + let mut px = LARGEST; + while px > SMALLEST && Line::new(font, px, 0.0, name).width > width { + px -= 2.0; + } + if Line::new(font, px, 0.0, name).width <= width { + return (px, name.to_owned()); + } + let mut kept: Vec = name.chars().collect(); + while !kept.is_empty() { + kept.pop(); + let shortened: String = kept.iter().chain(['…'].iter()).collect(); + if Line::new(font, px, 0.0, &shortened).width <= width { + return (px, shortened); + } + } + (px, "…".to_owned()) +} + +/// One line of text, laid out with the font's kerning and extra `spacing` between letters. +struct Line<'a> { + font: &'a FontRef<'static>, + px: f32, + glyphs: Vec, + width: f32, +} + +impl<'a> Line<'a> { + fn new(font: &'a FontRef<'static>, px: f32, spacing: f32, text: &str) -> Self { + let scaled = font.as_scaled(PxScale::from(px)); + let mut glyphs = Vec::new(); + let mut x = 0.0; + let mut previous = None; + for character in text.chars() { + let id = font.glyph_id(character); + if let Some(previous) = previous { + x += scaled.kern(previous, id) + spacing; + } + glyphs.push(id.with_scale_and_position(px, point(x, 0.0))); + x += scaled.h_advance(id); + previous = Some(id); + } + Self { + font, + px, + glyphs, + width: x, + } + } + + /// How far capitals reach above the baseline. + fn cap_height(&self) -> f32 { + let scaled = self.font.as_scaled(PxScale::from(self.px)); + let h = self.font.glyph_id('H'); + scaled + .outline_glyph(h.with_scale(self.px)) + .map_or(scaled.ascent(), |outline| -outline.px_bounds().min.y) + } + + /// The baseline that centres the line's capitals and lowercase on `center`: halfway up the x-height reads as + /// the middle of a lowercase map name better than the middle of the font's whole ascent and descent. + fn baseline_centered_on(&self, center: f32) -> f32 { + let scaled = self.font.as_scaled(PxScale::from(self.px)); + let x_height = scaled + .outline_glyph(self.font.glyph_id('x').with_scale(self.px)) + .map_or(self.cap_height() * 0.7, |outline| { + -outline.px_bounds().min.y + }); + center + (self.cap_height() + x_height) / 4.0 + } + + /// Draws the line with its left edge at `left` and its baseline at `baseline`; `color` picks each letter's + /// colour by its index. + fn draw( + &self, + card: &mut RgbImage, + left: f32, + baseline: f32, + color: impl Fn(usize) -> [u8; 3], + ) { + for (index, glyph) in self.glyphs.iter().enumerate() { + let mut glyph = glyph.clone(); + glyph.position = point(glyph.position.x + left, glyph.position.y + baseline); + let Some(outline) = self.font.outline_glyph(glyph) else { + continue; // a space + }; + let bounds = outline.px_bounds(); + let rgb = color(index); + outline.draw(|x, y, coverage| { + let x = bounds.min.x as i64 + i64::from(x); + let y = bounds.min.y as i64 + i64::from(y); + blend(card, x, y, rgb, coverage.min(1.0)); + }); + } + } +} + +/// The picture scaled and cropped around its centre to fill the card. +fn background(picture: &[u8]) -> Result { + let decoded = ImageReader::new(Cursor::new(picture)) + .with_guessed_format() + .map_err(|_| "the picture couldn't be read".to_owned())? + .decode() + .map_err(|error| format!("the picture couldn't be decoded: {error}"))?; + Ok(decoded + .resize_to_fill(SIZE.0, SIZE.1, FilterType::Lanczos3) + .to_rgb8()) +} + +/// Lays the background colour over the card from top to bottom, as opaque as `stops` say at each height +/// (position 0–1, opacity 0–1), in straight lines between them. +fn shade_down(card: &mut RgbImage, stops: &[(f32, f32)]) { + let height = card.height(); + for y in 0..height { + let opacity = along(stops, y as f32 / (height - 1) as f32); + for x in 0..card.width() { + blend(card, i64::from(x), i64::from(y), BACKGROUND, opacity); + } + } +} + +/// `shade_down`, from left to right. +fn shade_across(card: &mut RgbImage, stops: &[(f32, f32)]) { + let width = card.width(); + for x in 0..width { + let opacity = along(stops, x as f32 / (width - 1) as f32); + for y in 0..card.height() { + blend(card, i64::from(x), i64::from(y), BACKGROUND, opacity); + } + } +} + +/// The value at `position` on a line through `stops`; flat beyond the first and last. +fn along(stops: &[(f32, f32)], position: f32) -> f32 { + let mut value = stops.first().map_or(0.0, |stop| stop.1); + for pair in stops.windows(2) { + let ((from, a), (to, b)) = (pair[0], pair[1]); + if position >= from { + value = if position >= to { + b + } else { + a + (b - a) * (position - from) / (to - from) + }; + } + } + value +} + +/// Lays `color` over one pixel at `opacity`; pixels off the card are skipped. +fn blend(card: &mut RgbImage, x: i64, y: i64, color: [u8; 3], opacity: f32) { + let (Ok(x), Ok(y)) = (u32::try_from(x), u32::try_from(y)) else { + return; + }; + if x >= card.width() || y >= card.height() || opacity <= 0.0 { + return; + } + let pixel = card.get_pixel_mut(x, y); + for (channel, target) in pixel.0.iter_mut().zip(color) { + let mixed = f32::from(*channel) + (f32::from(target) - f32::from(*channel)) * opacity; + *channel = mixed.round().clamp(0.0, 255.0) as u8; + } +} + +/// Lays a picture with transparency over the card, its top left corner at (`left`, `top`). +fn overlay(card: &mut RgbImage, picture: &RgbaImage, left: i64, top: i64) { + for (x, y, pixel) in picture.enumerate_pixels() { + let [r, g, b, a] = pixel.0; + blend( + card, + left + i64::from(x), + top + i64::from(y), + [r, g, b], + f32::from(a) / 255.0, + ); + } +} + +fn encode(card: &RgbImage) -> Result, String> { + let mut jpeg = Vec::new(); + JpegEncoder::new_with_quality(&mut jpeg, QUALITY) + .encode_image(card) + .map_err(|error| format!("the card couldn't be encoded: {error}"))?; + Ok(jpeg) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::maps::image::tests::png; + + fn decode(jpeg: &[u8]) -> RgbImage { + image::load_from_memory(jpeg).unwrap().to_rgb8() + } + + #[test] + fn a_map_card_is_a_1200_by_630_jpeg_from_any_cover() { + for (width, height) in [(1920, 1080), (2560, 1080), (800, 800)] { + let card = map_card(&png(width, height), "bhop_badges", Some(3)).unwrap(); + assert_eq!(&card[..2], [0xff, 0xd8], "JPEG"); + assert_eq!(decode(&card).dimensions(), SIZE); + } + assert!(map_card(b"not a picture", "bhop_badges", None).is_err()); + } + + #[test] + fn long_names_shrink_and_then_are_cut_short() { + let room = SIZE.0 as f32 - 2.0 * MARGIN; + assert_eq!( + fit(&BOLD, "bhop_badges", room), + (84.0, "bhop_badges".to_owned()) + ); + let (px, name) = fit(&BOLD, "bhop_a_rather_long_map_name_v2", room); + assert!( + px < 84.0 && name == "bhop_a_rather_long_map_name_v2", + "{px} {name}" + ); + let (px, name) = fit(&BOLD, &"bhop_".repeat(12), room); + assert_eq!(px, 52.0); + assert!(name.ends_with('…'), "{name}"); + assert!(Line::new(&BOLD, px, 0.0, &name).width <= room); + } + + #[test] + fn the_shade_follows_its_stops() { + let stops = [(0.0, 0.8), (0.5, 0.0), (1.0, 1.0)]; + assert!((along(&stops, 0.0) - 0.8).abs() < 1e-6); + assert!((along(&stops, 0.25) - 0.4).abs() < 1e-6); + assert!(along(&stops, 0.5).abs() < 1e-6); + assert!((along(&stops, 1.0) - 1.0).abs() < 1e-6); + } + + #[test] + fn the_site_card_is_1200_by_630() { + let card = site_card(&png(1376, 768)).unwrap(); + assert_eq!(decode(&card).dimensions(), SIZE); + } +} diff --git a/api/crates/api/src/maps/detail.rs b/api/crates/api/src/maps/detail.rs index 9b638ae..6e3f3ae 100644 --- a/api/crates/api/src/maps/detail.rs +++ b/api/crates/api/src/maps/detail.rs @@ -178,8 +178,7 @@ async fn tracks( pb.track, pb.style, pb.time, pb.run_id, r.finished_at, count(*) OVER (PARTITION BY pb.track, pb.style) AS "players!", p.steamid64::text AS "steamid64!", p.name, p.avatar_url, p.country_code, - (SELECT tier FROM map_tiers WHERE map_id = pb.map_id AND track = pb.track - ORDER BY assigned_at DESC LIMIT 1) AS tier + (SELECT tier FROM current_map_tiers WHERE map_id = pb.map_id AND track = pb.track) AS tier FROM personal_bests pb JOIN runs r ON r.id = pb.run_id JOIN players p ON p.steamid64 = pb.player_steamid64 diff --git a/api/crates/api/src/maps/list.rs b/api/crates/api/src/maps/list.rs index ad52592..beb6771 100644 --- a/api/crates/api/src/maps/list.rs +++ b/api/crates/api/src/maps/list.rs @@ -24,9 +24,9 @@ const MAX_LIMIT: i64 = 100; #[derive(Debug, Deserialize, IntoParams)] pub struct MapsQuery { - /// Part of a map name. Case doesn't matter, and spaces stand for underscores. The map of exactly that - /// name comes first, then maps with a word starting with it, then other matches, each in the chosen - /// sort; near misses for a typo come last, closest first. + /// Part of a map name or a main-track world record holder's name in the chosen style. Case doesn't + /// matter; spaces in map names stand for underscores. Exact map names come first, then word starts, + /// other map matches and record holders, each in the chosen sort; near misses come last. q: Option, /// Default `name`. #[param(inline)] @@ -114,7 +114,7 @@ pub struct MapList { pub stats: MapStats, } -/// The whole list at a glance, whatever the search or filter. +/// Global totals and tier-scoped newest and weekly lists. #[derive(Debug, Serialize, Deserialize, ToSchema)] pub struct MapStats { /// Maps with at least one run. @@ -122,6 +122,8 @@ pub struct MapStats { /// Of those, the maps whose main track has each tier, tier 1 first. Empty until a tier count is /// published. pub by_tier: Vec, + /// The tier the newest and weekly lists describe; None describes all tiers. Totals remain global. + pub tier: Option, /// The maps that joined the list last, newest first. pub newest: Vec, /// The maps the most players finished a run on in the last 7 days, most first. @@ -191,6 +193,12 @@ pub async fn list_maps( let sort = query.sort.unwrap_or(MapSort::Name).key(); let search = query.q.as_deref().and_then(search_name); let pattern = search.as_deref().map(name_search::contains_pattern); + let holder_pattern = query + .q + .as_deref() + .map(str::trim) + .filter(|q| !q.is_empty()) + .map(name_search::contains_pattern); // Most map names start with "bhop_", which would make every map a near miss of every search. let near = search .as_deref() @@ -203,6 +211,7 @@ pub async fn list_maps( }; let filter = Filter { pattern: pattern.as_deref(), + holder_pattern: holder_pattern.as_deref(), near, style: style.as_deref(), completed_by: query.completed.and(player).map(SteamId64::get), @@ -218,7 +227,7 @@ pub async fn list_maps( tx.commit().await?; let tier_count = tiers::tier_count(&state.db).await?; - let list_stats = map_stats(&state.db, tier_count).await?; + let list_stats = map_stats(&state.db, tier_count, query.tier).await?; let (player, completed) = match player { Some(player) => ( known_player(&state.db, player).await?, @@ -244,11 +253,14 @@ pub async fn list_maps( /// Maps with a run, how many hold each main-track tier once tiers are in force, the newest of them and the /// week's most played. -async fn map_stats(db: &sqlx::PgPool, tier_count: Option) -> Result { +async fn map_stats( + db: &sqlx::PgPool, + tier_count: Option, + tier: Option, +) -> Result { let rows = sqlx::query!( r#"SELECT tier.tier AS "tier?", count(*) AS "maps!" FROM maps m - LEFT JOIN LATERAL (SELECT tier FROM map_tiers WHERE map_id = m.id AND track = 0 - ORDER BY assigned_at DESC LIMIT 1) tier ON true + LEFT JOIN current_map_tiers tier ON tier.map_id = m.id AND tier.track = 0 WHERE m.last_run_at IS NOT NULL GROUP BY tier.tier"# ) @@ -266,11 +278,13 @@ async fn map_stats(db: &sqlx::PgPool, tier_count: Option) -> Result) -> Result now() - interval '7 days' GROUP BY map_id) week JOIN maps m ON m.id = week.map_id + WHERE $2::smallint IS NULL OR $2 = + (SELECT tier FROM current_map_tiers WHERE map_id = m.id AND track = 0) ORDER BY week.players DESC, m.name LIMIT $1"#, - PLAYED_THIS_WEEK + PLAYED_THIS_WEEK, + tier ) .fetch_all(db) .await? @@ -306,6 +322,7 @@ async fn map_stats(db: &sqlx::PgPool, tier_count: Option) -> Result 0 THEN 1 - WHEN m.name ILIKE $1 ESCAPE '\' THEN 2 ELSE 3 END, - CASE WHEN m.name NOT ILIKE $1 ESCAPE '\' THEN word_similarity($7, m.name) END DESC NULLS LAST, + WHEN m.name ILIKE $1 ESCAPE '\' THEN 2 + WHEN m.id IN (SELECT map_id FROM holder_maps) THEN 3 ELSE 4 END, + CASE WHEN m.name NOT ILIKE $1 ESCAPE '\' AND $7 <% m.name + THEN word_similarity($7, m.name) END DESC NULLS LAST, CASE WHEN $2 = 'recent' THEN m.last_run_at END DESC, CASE WHEN $2 = 'newest' THEN m.listed_at END DESC NULLS LAST, CASE $2 WHEN 'popular' THEN -m.players WHEN 'least_popular' THEN m.players END, @@ -395,8 +419,7 @@ async fn listed_page( m.name ) AS position FROM maps m - LEFT JOIN LATERAL (SELECT tier FROM map_tiers WHERE map_id = m.id AND track = 0 - ORDER BY assigned_at DESC LIMIT 1) tier ON true + LEFT JOIN current_map_tiers tier ON tier.map_id = m.id AND tier.track = 0 -- Every map's record, read only for the sorts that need it: the page below reads the page's own. LEFT JOIN LATERAL ( SELECT pb.time, r.finished_at @@ -405,7 +428,8 @@ async fn listed_page( ORDER BY pb.time, r.finished_at LIMIT 1 ) record ON true - WHERE m.last_run_at IS NOT NULL AND ($1::text IS NULL OR m.name ILIKE $1 ESCAPE '\' OR $7 <% m.name) + WHERE m.last_run_at IS NOT NULL AND ($1::text IS NULL OR m.name ILIKE $1 ESCAPE '\' + OR $7 <% m.name OR m.id IN (SELECT map_id FROM holder_maps)) AND ($8::bigint IS NULL OR $9 = EXISTS ( SELECT 1 FROM personal_bests WHERE player_steamid64 = $8 AND map_id = m.id AND style = $5 AND track = 0)) AND ($10::smallint IS NULL OR tier.tier = $10) @@ -442,7 +466,8 @@ async fn listed_page( filter.near, filter.completed_by, filter.completed, - filter.tier + filter.tier, + filter.holder_pattern ) .fetch_all(tx) .await @@ -499,6 +524,8 @@ impl ListedMap { struct Filter<'a> { /// The search as an `ILIKE` pattern. pattern: Option<&'a str>, + /// The original search, preserving spaces in player names. + holder_pattern: Option<&'a str>, /// The search's term for near misses. near: Option<&'a str>, style: Option<&'a str>, @@ -513,17 +540,19 @@ struct Filter<'a> { async fn count_maps(tx: &mut sqlx::PgConnection, filter: &Filter<'_>) -> Result { sqlx::query_scalar!( r#"SELECT count(*) AS "count!" FROM maps m - WHERE last_run_at IS NOT NULL AND ($1::text IS NULL OR name ILIKE $1 ESCAPE '\' OR $2 <% name) + WHERE last_run_at IS NOT NULL AND ($1::text IS NULL OR name ILIKE $1 ESCAPE '\' OR $2 <% name + OR EXISTS (SELECT 1 FROM world_record_holders h JOIN players p ON p.steamid64 = h.player_steamid64 + WHERE h.map_id = m.id AND h.style = $5 AND h.track = 0 AND p.name ILIKE $7 ESCAPE '\')) AND ($3::bigint IS NULL OR $4 = EXISTS ( SELECT 1 FROM personal_bests WHERE player_steamid64 = $3 AND map_id = m.id AND style = $5 AND track = 0)) - AND ($6::smallint IS NULL OR $6 = (SELECT tier FROM map_tiers WHERE map_id = m.id AND track = 0 - ORDER BY assigned_at DESC LIMIT 1))"#, + AND ($6::smallint IS NULL OR $6 = (SELECT tier FROM current_map_tiers WHERE map_id = m.id AND track = 0))"#, filter.pattern, filter.near, filter.completed_by, filter.completed, filter.style, - filter.tier + filter.tier, + filter.holder_pattern ) .fetch_one(tx) .await @@ -628,6 +657,73 @@ mod tests { ); } + #[sqlx::test] + async fn searches_current_main_track_record_holders_in_the_selected_style(db: PgPool) { + let key = setup(&db).await; + sqlx::query( + r#"INSERT INTO rulesets (version, document) + SELECT 2, jsonb_set(document, '{styles}', + (document->'styles') || '[{"key":"sw","name":"Sideways","settings":{}}]'::jsonb) + FROM rulesets WHERE version = 1"#, + ) + .execute(&db) + .await + .unwrap(); + for (id, map, player, name, time, style, track) in [ + ( + "holder-main", + "bhop_badges", + 0, + "Speed Runner", + 30.0, + "normal", + 0, + ), + ( + "holder-second", + "bhop_arcane", + 0, + "Speed Runner", + 15.0, + "normal", + 0, + ), + ("slower", "bhop_badges", 1, "Bonus Hero", 40.0, "normal", 0), + ("bonus", "bhop_badges", 1, "Bonus Hero", 10.0, "normal", 1), + ("sideways", "bhop_badges", 1, "Bonus Hero", 20.0, "sw", 0), + ("tied", "bhop_badges", 2, "Co Holder", 30.0, "normal", 0), + ] { + let mut body = run(id, time); + body["map"] = json!(map); + body["player"] = json!({ + "steamid64": (76_561_197_960_287_930_i64 + player).to_string(), + "name": name, + }); + body["style"] = json!(style); + body["track"] = json!(track); + body["ruleset_version"] = json!(2); + assert_eq!( + test_client::post(&db, "/v1/runs", Some(&key), &body) + .await + .status, + 201 + ); + } + let page: MapList = test_client::get(&db, "/v1/maps?q=SPEED%20RUNNER&limit=1&offset=1") + .await + .json(); + assert_eq!(page.total, 2); + assert_eq!(page.maps.len(), 1); + assert_eq!(page.maps[0].name, "bhop_badges"); + assert_eq!(names(&db, "/v1/maps?q=Co%20Holder").await, ["bhop_badges"]); + assert_eq!(names(&db, "/v1/maps?q=Bonus%20Hero").await.len(), 0); + assert_eq!( + names(&db, "/v1/maps?q=Bonus%20Hero&style=sw").await, + ["bhop_badges"] + ); + assert_eq!(names(&db, "/v1/maps?q=%25").await.len(), 0); + } + /// `bhop_badges`' stored player count, and the count its personal bests give. async fn badges_players(db: &PgPool) -> (i32, i64) { sqlx::query_as( @@ -719,6 +815,79 @@ mod tests { assert_eq!(week, [("bhop_badges", 2), ("bhop_arcane", 1)]); } + #[sqlx::test] + async fn stats_rank_within_a_tier_before_taking_the_top_five(db: PgPool) { + let key = setup(&db).await; + let policy = crate::policies::Policy::Tiers(crate::policies::TiersPolicy { count: 2 }); + crate::policies::publish(&mut db.acquire().await.unwrap(), &policy) + .await + .unwrap(); + for index in 0..12 { + let name = format!("bhop_tier_{index:02}"); + let players = if index < 5 { 2 } else { 1 }; + for player in 0..players { + let mut body = run(&format!("tier-{index}-{player}"), 30.0); + body["map"] = json!(name); + body["player"] = json!({ + "steamid64": (76_561_197_960_287_930_i64 + player).to_string(), + "name": format!("player-{player}"), + }); + assert_eq!( + test_client::post(&db, "/v1/runs", Some(&key), &body) + .await + .status, + 201 + ); + } + let map = crate::maps::MapName::try_from(name.clone()).unwrap(); + crate::staff::maps::set_tier(&db, None, &map, 0, if index < 5 { 1 } else { 2 }) + .await + .unwrap(); + sqlx::query( + "UPDATE maps SET listed_at = now() - $1 * interval '1 minute' WHERE name = $2", + ) + .bind(f64::from(index)) + .bind(name) + .execute(&db) + .await + .unwrap(); + } + sqlx::query("UPDATE runs SET finished_at = now() - interval '1 day'") + .execute(&db) + .await + .unwrap(); + + let all: MapList = test_client::get(&db, "/v1/maps").await.json(); + assert_eq!(all.stats.tier, None); + assert!( + all.stats + .played_this_week + .iter() + .all(|map| map.tier == Some(1)) + ); + assert!(all.stats.newest.iter().all(|map| map.tier == Some(1))); + + let filtered: MapList = test_client::get(&db, "/v1/maps?tier=2").await.json(); + let expected: Vec<_> = (5..10) + .map(|index| format!("bhop_tier_{index:02}")) + .collect(); + assert_eq!(filtered.stats.tier, Some(2)); + assert_eq!( + (filtered.stats.maps, filtered.stats.by_tier), + (12, vec![5, 7]) + ); + assert_eq!(filtered.stats.played_this_week.len(), 5); + assert_eq!(filtered.stats.newest.len(), 5); + for (index, map) in filtered.stats.played_this_week.iter().enumerate() { + assert_eq!(map.name, expected[index]); + assert_eq!((map.tier, map.players), (Some(2), 1)); + } + for (index, map) in filtered.stats.newest.iter().enumerate() { + assert_eq!(map.name, expected[index]); + assert_eq!(map.tier, Some(2)); + } + } + #[sqlx::test] async fn sorts_by_record_and_filters_by_completion(db: PgPool) { let key = setup(&db).await; diff --git a/api/crates/api/src/players/profile.rs b/api/crates/api/src/players/profile.rs index 3dd23fa..aad9f2c 100644 --- a/api/crates/api/src/players/profile.rs +++ b/api/crates/api/src/players/profile.rs @@ -323,6 +323,7 @@ mod tests { .execute(&db) .await .unwrap(); + crate::runs::tests::backdate(&db).await; let mut sideways = run("c", 40.0); sideways["style"] = json!("sw"); sideways["ruleset_version"] = json!(2); diff --git a/api/crates/api/src/record_events/discord/post.rs b/api/crates/api/src/record_events/discord/post.rs index fb56fc9..7d66f27 100644 --- a/api/crates/api/src/record_events/discord/post.rs +++ b/api/crates/api/src/record_events/discord/post.rs @@ -133,8 +133,7 @@ async fn records( AND o.player_steamid64 = r.player_steamid64 AND o.invalidated_at IS NULL AND (o.finished_at, o.id) < (r.finished_at, r.id)) AS previous_personal_best, - (SELECT tier FROM map_tiers WHERE map_id = r.map_id AND track = r.track - ORDER BY assigned_at DESC LIMIT 1) AS tier, + (SELECT tier FROM current_map_tiers WHERE map_id = r.map_id AND track = r.track) AS tier, (SELECT key FROM map_images WHERE map_id = r.map_id AND position = 0) AS image_key, (SELECT host(h.ip) || ':' || h.port FROM server_heartbeats h JOIN server_listings l ON l.ip = h.ip AND l.port = h.port diff --git a/api/crates/api/src/records.rs b/api/crates/api/src/records.rs index 166f0bb..f738e8f 100644 --- a/api/crates/api/src/records.rs +++ b/api/crates/api/src/records.rs @@ -1,5 +1,7 @@ //! A map's records, `GET /v1/maps/{map}/records`: the top personal bests per style and track, for the -//! plugin's in-game records display. +//! plugin's in-game records display. Connected players' own bests on the map are in `records/personal_bests.rs`. + +pub mod personal_bests; use axum::{ Json, @@ -54,9 +56,11 @@ pub struct Record { } pub fn routes() -> OpenApiRouter { - // Servers check a map's records on every map change; most of the time nothing's new. + // Servers check a map's records and their players' personal bests on every map change; most of the time + // nothing's new. OpenApiRouter::new() .routes(routes!(map_records)) + .routes(routes!(personal_bests::players_personal_bests)) .layer(axum::middleware::from_fn(crate::etag::conditional)) } diff --git a/api/crates/api/src/records/personal_bests.rs b/api/crates/api/src/records/personal_bests.rs new file mode 100644 index 0000000..6013c87 --- /dev/null +++ b/api/crates/api/src/records/personal_bests.rs @@ -0,0 +1,214 @@ +//! Players' personal bests on one map, `GET /v1/maps/{map}/personal-bests?players=`: what a game server reads +//! on map change for everyone connected, so it skips submitting runs that aren't faster than the player's +//! SourceJump PB (`docs/domain.md`). One request covers every player, style and track, instead of one per +//! leaderboard. + +use axum::{ + Json, + extract::{Path, Query, State}, +}; +use chrono::{DateTime, Utc}; +use serde::{Deserialize, Serialize}; +use utoipa::{IntoParams, ToSchema}; + +use crate::{ + app::AppState, + error::{ApiError, ErrorBody}, + maps::MapName, + players::SteamId64, +}; + +/// A server holds at most 64 players, so one request covers everyone on it. +const MAX_PLAYERS: usize = 64; + +#[derive(Debug, Deserialize, IntoParams)] +pub struct PersonalBestsQuery { + /// Players by SteamID64, comma-separated: 1 to 64 of them. Repeats count once. + players: String, +} + +#[derive(Debug, Serialize, Deserialize, ToSchema)] +pub struct PlayersPersonalBests { + pub map: String, + /// Sorted by player, style and track. A player with no personal best on the map has no entries. One flat + /// list keeps it simple to read in SourcePawn. + pub personal_bests: Vec, +} + +#[derive(Debug, Serialize, Deserialize, ToSchema)] +pub struct PlayerPersonalBest { + /// SteamID64, as a string. + pub steamid64: String, + pub style: String, + /// 0 is the main track, 1 and up are bonuses. + pub track: i16, + /// Seconds. + pub time: f64, + /// Place on the leaderboard; equal times share a place, as in `…/records`. + pub rank: i64, + pub run_id: i64, + pub finished_at: DateTime, +} + +/// These players' SourceJump personal bests on the map, every style and track. An unknown map, or players +/// without runs on it, give an empty list. +#[utoipa::path( + get, + path = "/v1/maps/{map}/personal-bests", + tag = "maps", + params(("map" = String, Path, description = "Map name"), PersonalBestsQuery), + responses( + (status = OK, body = PlayersPersonalBests), + (status = UNPROCESSABLE_ENTITY, description = "Not a valid map name, or `players` isn't 1 to 64 SteamID64s", body = ErrorBody), + ), +)] +pub async fn players_personal_bests( + State(state): State, + Path(map): Path, + Query(query): Query, +) -> Result, ApiError> { + let map = MapName::try_from(map).map_err(ApiError::Invalid)?; + let players = parse_players(&query.players).map_err(ApiError::Invalid)?; + + // A place is one more than the faster personal bests on the board, read from its index; a slow player on a + // big board counts more entries, but never more than the board holds. + let personal_bests = sqlx::query_as!( + PlayerPersonalBest, + r#" + SELECT pb.player_steamid64::text AS "steamid64!", pb.style, pb.track, pb.time, pb.run_id, + pb.finished_at, + 1 + (SELECT count(*) FROM personal_bests faster + WHERE faster.map_id = pb.map_id AND faster.style = pb.style AND faster.track = pb.track + AND faster.time < pb.time) AS "rank!" + FROM personal_bests pb + JOIN maps m ON m.id = pb.map_id + WHERE m.name = $1 AND pb.player_steamid64 = ANY($2) + ORDER BY pb.player_steamid64, pb.style, pb.track + "#, + map.as_str(), + &players + ) + .fetch_all(&state.db) + .await?; + + Ok(Json(PlayersPersonalBests { + map: map.into(), + personal_bests, + })) +} + +/// Each player named in `players`, once. +fn parse_players(players: &str) -> Result, String> { + let mut parsed = Vec::new(); + for text in players.split(',') { + let steamid64 = SteamId64::try_from(text.trim().to_owned())?.get(); + if !parsed.contains(&steamid64) { + parsed.push(steamid64); + } + } + if parsed.len() > MAX_PLAYERS { + return Err(format!("players takes at most {MAX_PLAYERS} SteamID64s")); + } + Ok(parsed) +} + +#[cfg(test)] +mod tests { + use serde_json::json; + use sqlx::PgPool; + + use super::{MAX_PLAYERS, PlayersPersonalBests, parse_players}; + use crate::{ + error::ErrorBody, + runs::tests::{run, setup}, + test_client, + }; + + const GABE: &str = "76561197960287930"; + const SECOND: &str = "76561197960287931"; + const THIRD: &str = "76561197960287932"; + + #[sqlx::test] + async fn lists_each_players_bests_with_their_place(db: PgPool) { + let key = setup(&db).await; + let mut second = run("b", 29.0); + second["player"] = json!({ "steamid64": SECOND, "name": "second" }); + let mut third = run("c", 29.0); + third["player"] = json!({ "steamid64": THIRD, "name": "third" }); + let mut bonus = run("d", 50.0); + bonus["track"] = json!(1); + let mut elsewhere = run("e", 10.0); + elsewhere["map"] = json!("bhop_other"); + for body in [run("a", 30.0), second, third, bonus, elsewhere] { + let status = test_client::post(&db, "/v1/runs", Some(&key), &body) + .await + .status; + assert_eq!(status, 201); + } + + let answer: PlayersPersonalBests = test_client::get( + &db, + &format!("/v1/maps/bhop_badges/personal-bests?players={GABE},{THIRD},{GABE}"), + ) + .await + .json(); + + assert_eq!(answer.map, "bhop_badges"); + let summary: Vec<_> = answer + .personal_bests + .iter() + .map(|pb| (pb.steamid64.as_str(), pb.track, pb.time, pb.rank)) + .collect(); + // The two 29s share first place; the 30 is third. The run on another map isn't listed. + assert_eq!( + summary, + [(GABE, 0, 30.0, 3), (GABE, 1, 50.0, 1), (THIRD, 0, 29.0, 1)] + ); + } + + #[sqlx::test] + async fn an_unknown_map_or_a_player_without_runs_gives_an_empty_list(db: PgPool) { + let key = setup(&db).await; + test_client::post(&db, "/v1/runs", Some(&key), &run("a", 30.0)).await; + + for path in [ + format!("/v1/maps/bhop_none/personal-bests?players={GABE}"), + format!("/v1/maps/bhop_badges/personal-bests?players={SECOND}"), + ] { + let answer: PlayersPersonalBests = test_client::get(&db, &path).await.json(); + assert!(answer.personal_bests.is_empty(), "{path}"); + } + } + + #[sqlx::test] + async fn refuses_anything_but_1_to_64_steamid64s(db: PgPool) { + let too_many = (0..=MAX_PLAYERS as u64) + .map(|n| (76_561_197_960_287_930 + n).to_string()) + .collect::>() + .join(","); + for players in ["", "STEAM_0:0:1", "76561197960287930,,", too_many.as_str()] { + let response = test_client::get( + &db, + &format!("/v1/maps/bhop_badges/personal-bests?players={players}"), + ) + .await; + assert_eq!(response.status, 422, "{players}"); + let _: ErrorBody = response.json(); + } + assert_eq!( + test_client::get(&db, "/v1/maps/bhop_badges/personal-bests") + .await + .status, + 400, + "players is required" + ); + } + + #[test] + fn repeats_count_once() { + assert_eq!( + parse_players("76561197960287930, 76561197960287930").unwrap(), + [76_561_197_960_287_930] + ); + } +} diff --git a/api/crates/api/src/runs.rs b/api/crates/api/src/runs.rs index dc2460e..c877588 100644 --- a/api/crates/api/src/runs.rs +++ b/api/crates/api/src/runs.rs @@ -202,9 +202,8 @@ async fn store( if let Some(id) = existing(conn, key.server_id, &run.server_run_id).await? { return answer_for_existing(conn, id).await; } - check_ruleset(conn, run).await?; - let finished_at = DateTime::from_timestamp(run.finished_at, 0).expect("checked before storing"); + check_ruleset(conn, run, key.server_id, finished_at).await?; players::record_name(conn, run.player.steamid64, &run.player.name, finished_at).await?; let ban = restrictions::records_ban(conn, run.player.steamid64).await?; let map_id = maps::id_for(conn, &run.map).await?; @@ -248,7 +247,7 @@ async fn store( }; // Last: the recount holds the standings lock, which every other recount waits on, until this commits. if new_personal_best { - crate::leaderboards::standings::refresh_runs(conn, &[id]).await?; + crate::leaderboards::standings::refresh_stored_run(conn, id).await?; } Ok(Stored { @@ -259,14 +258,23 @@ async fn store( }) } -/// Whether the run's ruleset version exists, ranks its style and, if it names one, allows its tickrate. -async fn check_ruleset(conn: &mut PgConnection, run: &RunSubmission) -> Result<(), ApiError> { +/// Whether the run's ruleset version exists, ranks its style and, if it names one, allows its tickrate, and +/// whether the run finished after that version and its server existed. Nothing ranked can be older than both, so +/// an earlier time is a broken clock (0 is 1970); taken as is, it would win ties and rewrite WR history. +async fn check_ruleset( + conn: &mut PgConnection, + run: &RunSubmission, + server_id: i64, + finished_at: DateTime, +) -> Result<(), ApiError> { let ruleset = sqlx::query!( r#"SELECT document->'styles' @> jsonb_build_array(jsonb_build_object('key', $2::text)) AS "ranked!", - (document->>'tickrate')::real AS tickrate + (document->>'tickrate')::real AS tickrate, + GREATEST(published_at, (SELECT created_at FROM servers WHERE id = $3)) AS "earliest!" FROM rulesets WHERE version = $1"#, run.ruleset_version, - run.style + run.style, + server_id ) .fetch_optional(conn) .await? @@ -276,6 +284,12 @@ async fn check_ruleset(conn: &mut PgConnection, run: &RunSubmission) -> Result<( run.ruleset_version )) })?; + if finished_at < ruleset.earliest - servers::CLOCK_SLACK { + return Err(ApiError::Invalid(format!( + "finished_at is before ruleset version {} or this server existed; check the server's clock", + run.ruleset_version + ))); + } if !ruleset.ranked { return Err(ApiError::Invalid(format!( "style {:?} is not ranked in ruleset version {}", @@ -405,7 +419,7 @@ pub(crate) mod tests { use super::RunAccepted; use crate::{error::ErrorBody, servers::keys, test_client}; - /// Publishes a ruleset ranking `normal` and returns a fresh server key. + /// Publishes a ruleset ranking `normal` and returns a fresh server key, both backdated. pub(crate) async fn setup(db: &PgPool) -> String { sqlx::query( r#"INSERT INTO rulesets (version, document) VALUES (1, '{ @@ -417,7 +431,23 @@ pub(crate) mod tests { .execute(db) .await .unwrap(); - keys::issue(db, "Test server").await.unwrap().key + let key = keys::issue(db, "Test server").await.unwrap().key; + backdate(db).await; + key + } + + /// Dates every ruleset and server early in 2026, so the fixed times tests submit come after them. Rulesets + /// refuse changes, so this lifts that guard for the moment; each test has a database of its own. + pub(crate) async fn backdate(db: &PgPool) { + sqlx::raw_sql( + "ALTER TABLE rulesets DISABLE TRIGGER rulesets_immutable; + UPDATE rulesets SET published_at = '2026-01-01Z'; + ALTER TABLE rulesets ENABLE TRIGGER rulesets_immutable; + UPDATE servers SET created_at = '2026-01-01Z';", + ) + .execute(db) + .await + .unwrap(); } /// A valid run on `bhop_badges`, normal style, main track. @@ -521,6 +551,7 @@ pub(crate) mod tests { async fn the_same_run_id_from_another_server_is_a_different_run(db: PgPool) { let key = setup(&db).await; let other = keys::issue(&db, "Other server").await.unwrap().key; + backdate(&db).await; let first: RunAccepted = submit(&db, &key, &run("a", 30.0)).await.json(); let second = submit(&db, &other, &run("a", 31.0)).await; @@ -565,6 +596,44 @@ pub(crate) mod tests { assert_eq!(count(&db, "runs").await, 0); } + #[sqlx::test] + async fn a_run_cant_finish_before_its_ruleset_or_server_existed(db: PgPool) { + let old_key = setup(&db).await; + sqlx::query("INSERT INTO rulesets (version, document) SELECT 2, document FROM rulesets WHERE version = 1") + .execute(&db) + .await + .unwrap(); + let new_key = keys::issue(&db, "New server").await.unwrap().key; + let now = chrono::Utc::now().timestamp(); + let at = |id: &str, finished_at: i64, ruleset: i64| { + let mut body = run(id, 30.0); + body["finished_at"] = json!(finished_at); + body["ruleset_version"] = json!(ruleset); + body + }; + + for (key, body) in [ + (&old_key, at("a", 0, 1)), + (&old_key, at("b", now - 3600, 2)), + (&new_key, at("c", now - 3600, 1)), + ] { + let response = submit(&db, key, &body).await; + assert_eq!(response.status, 422, "{body}"); + assert!( + response + .json::() + .error + .contains("check the server's clock") + ); + } + // A clock a minute behind ours is within the slack. + assert_eq!( + submit(&db, &new_key, &at("d", now - 60, 2)).await.status, + 201 + ); + assert_eq!(count(&db, "runs").await, 1); + } + #[sqlx::test] async fn a_ruleset_with_a_tickrate_ranks_runs_at_that_tickrate_only(db: PgPool) { let key = setup(&db).await; @@ -575,6 +644,7 @@ pub(crate) mod tests { .execute(&db) .await .unwrap(); + backdate(&db).await; let at = |id: &str, tickrate: f64| { let mut body = run(id, 30.0); body["ruleset_version"] = json!(2); diff --git a/api/crates/api/src/runs/detail.rs b/api/crates/api/src/runs/detail.rs index 138ce95..f38b4df 100644 --- a/api/crates/api/src/runs/detail.rs +++ b/api/crates/api/src/runs/detail.rs @@ -27,6 +27,8 @@ pub struct RunDetail { pub map: String, /// The map's cover picture. None until staff add one. pub map_image: Option, + /// The picture a link to the map shows (1200×630 JPEG), which links to its runs show too; see `MapDetail`. + pub map_card_url: Option, pub style: String, /// 0 is the main track, 1 and up are bonuses. pub track: i16, @@ -93,9 +95,9 @@ pub async fn run_detail( EXISTS (SELECT 1 FROM personal_bests WHERE run_id = r.id) AS "personal_best!", (SELECT min(time) FROM personal_bests WHERE map_id = r.map_id AND style = r.style AND track = r.track) AS world_record_time, - (SELECT tier FROM map_tiers WHERE map_id = r.map_id AND track = r.track - ORDER BY assigned_at DESC LIMIT 1) AS tier, + (SELECT tier FROM current_map_tiers WHERE map_id = r.map_id AND track = r.track) AS tier, ci.id AS "image_id?", ci.key AS "image_key?", ci.focus AS "image_focus?", + (SELECT key FROM map_cards WHERE map_id = r.map_id) AS map_card_key, (SELECT host(h.ip) || ':' || h.port FROM server_heartbeats h JOIN server_listings l ON l.ip = h.ip AND l.port = h.port WHERE h.server_id = s.id ORDER BY h.received_at DESC LIMIT 1) AS server_address @@ -149,6 +151,7 @@ pub async fn run_detail( }, map: row.map, map_image: MapImage::cover(&state.storage, row.image_id, row.image_key, row.image_focus), + map_card_url: row.map_card_key.map(|key| state.storage.public_url(&key)), style: row.style, track: row.track, // Tiers assigned before a tier count was published aren't in force. diff --git a/api/crates/api/src/runs/recent.rs b/api/crates/api/src/runs/recent.rs index 00d0416..5b576f3 100644 --- a/api/crates/api/src/runs/recent.rs +++ b/api/crates/api/src/runs/recent.rs @@ -162,8 +162,7 @@ async fn page( SELECT r.id, r.map_id, r.style, r.track, r.player_steamid64, r.time, r.finished_at, r.was_record, tier.tier FROM runs r - LEFT JOIN LATERAL (SELECT tier FROM map_tiers WHERE map_id = r.map_id AND track = r.track - ORDER BY assigned_at DESC LIMIT 1) tier ON $7 + LEFT JOIN current_map_tiers tier ON $7 AND tier.map_id = r.map_id AND tier.track = r.track WHERE r.invalidated_at IS NULL AND (NOT $4 OR r.was_record) AND ($1::text IS NULL OR r.style = $1) diff --git a/api/crates/api/src/servers.rs b/api/crates/api/src/servers.rs index 9b4df3b..6378d2d 100644 --- a/api/crates/api/src/servers.rs +++ b/api/crates/api/src/servers.rs @@ -19,15 +19,16 @@ pub fn routes() -> OpenApiRouter { .routes(routes!(activity::server_activity)) } -/// How far ahead of our clock a server's clock may run. Beyond that the time is wrong or made up, and it -/// would win every "newest" comparison: a player's name, Activity order, a map's last run. -const MAX_CLOCK_AHEAD: TimeDelta = TimeDelta::minutes(5); +/// How far a server's clock may be off from ours. A time further ahead is wrong or made up, and would win every +/// "newest" comparison: a player's name, Activity order, a map's last run. A run's time further behind its ruleset +/// or server would win ties and rewrite WR history (`runs::check_ruleset`). +pub const CLOCK_SLACK: TimeDelta = TimeDelta::minutes(5); /// Reads a time a game server reports (`finished_at`, `detected_at`), in Unix seconds by its clock. pub fn server_time(field: &str, unix: i64, now: DateTime) -> Result, String> { let at = DateTime::from_timestamp(unix, 0) .ok_or_else(|| format!("{field} is not a valid Unix time"))?; - if at > now + MAX_CLOCK_AHEAD { + if at > now + CLOCK_SLACK { return Err(format!( "{field} is in the future; check the server's clock" )); diff --git a/api/crates/api/src/staff/maps.rs b/api/crates/api/src/staff/maps.rs index d8beadf..b6ac38d 100644 --- a/api/crates/api/src/staff/maps.rs +++ b/api/crates/api/src/staff/maps.rs @@ -69,7 +69,7 @@ pub async fn set_tier( .await? .ok_or(NO_MAP)?; let in_force = sqlx::query_scalar!( - "SELECT tier FROM map_tiers WHERE map_id = $1 AND track = $2 ORDER BY assigned_at DESC LIMIT 1", + r#"SELECT tier AS "tier!" FROM current_map_tiers WHERE map_id = $1 AND track = $2"#, map_id, track ) @@ -309,8 +309,7 @@ pub async fn list_staff_maps( let rows = sqlx::query!( r#" SELECT m.name, ci.id AS "image_id?", ci.key AS "image_key?", ci.focus AS "image_focus?", m.last_run_at, - (SELECT tier FROM map_tiers t WHERE t.map_id = m.id AND t.track = 0 - ORDER BY assigned_at DESC LIMIT 1) AS tier, + (SELECT tier FROM current_map_tiers t WHERE t.map_id = m.id AND t.track = 0) AS tier, (SELECT max(version) FROM map_zones z WHERE z.map_id = m.id) AS zone_version FROM maps m LEFT JOIN map_images ci ON ci.map_id = m.id AND ci.position = 0 diff --git a/api/crates/api/src/staff/policies.rs b/api/crates/api/src/staff/policies.rs index 1699991..1a7ae60 100644 --- a/api/crates/api/src/staff/policies.rs +++ b/api/crates/api/src/staff/policies.rs @@ -43,9 +43,7 @@ pub async fn publish_policy( // A smaller count would leave maps rated above it; staff move those first. let highest = sqlx::query_scalar!( r#" - SELECT max(tier) FROM ( - SELECT DISTINCT ON (map_id, track) tier FROM map_tiers ORDER BY map_id, track, assigned_at DESC - ) in_force + SELECT max(tier) FROM current_map_tiers "# ) .fetch_one(&mut *tx) diff --git a/api/crates/api/src/staff/runs.rs b/api/crates/api/src/staff/runs.rs index cda8e93..ad7ed9d 100644 --- a/api/crates/api/src/staff/runs.rs +++ b/api/crates/api/src/staff/runs.rs @@ -1118,6 +1118,7 @@ mod tests { async fn revoking_a_key_can_invalidate_every_run_its_server_sent(db: PgPool) { let key = setup(&db).await; let other = keys::issue(&db, "Other server").await.unwrap(); + crate::runs::tests::backdate(&db).await; submit(&db, &key, "g1", GABE, 30.0, 0).await; submit(&db, &other.key, "z1", ZED, 35.0, 0).await; // A run sent with the server's earlier key goes too. diff --git a/api/openapi.json b/api/openapi.json index 91d277d..38076b7 100644 --- a/api/openapi.json +++ b/api/openapi.json @@ -134,6 +134,54 @@ } } }, + "/v1/auth/sign-out-everywhere": { + "post": { + "tags": [ + "auth" + ], + "summary": "Ends every session of the signed-in player, in every browser, and signs this one out. A form on the\nwebsite posts here. Unlike signing out, it needs a live session: answering a request without one as if it\nhad worked would tell the player their other browsers were signed out when nothing was ended.", + "operationId": "sign_out_everywhere", + "parameters": [ + { + "name": "return_to", + "in": "query", + "description": "The page to come back to: a path on this site, such as `/maps`. Anything else means `/`.", + "required": false, + "schema": { + "type": [ + "string", + "null" + ] + } + } + ], + "responses": { + "303": { + "description": "Back to the page the player came from, signed out everywhere" + }, + "401": { + "description": "Not signed in; no session was ended", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + }, + "403": { + "description": "Not sent from SourceJump's own pages", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + } + } + } + }, "/v1/auth/steam": { "get": { "tags": [ @@ -540,7 +588,7 @@ { "name": "q", "in": "query", - "description": "Part of a map name. Case doesn't matter, and spaces stand for underscores. The map of exactly that\nname comes first, then maps with a word starting with it, then other matches, each in the chosen\nsort; near misses for a typo come last, closest first.", + "description": "Part of a map name or a main-track world record holder's name in the chosen style. Case doesn't\nmatter; spaces in map names stand for underscores. Exact map names come first, then word starts,\nother map matches and record holders, each in the chosen sort; near misses come last.", "required": false, "schema": { "type": [ @@ -861,6 +909,71 @@ } } }, + "/v1/maps/{map}/personal-bests": { + "get": { + "tags": [ + "maps" + ], + "summary": "These players' SourceJump personal bests on the map, every style and track. An unknown map, or players\nwithout runs on it, give an empty list.", + "operationId": "players_personal_bests", + "parameters": [ + { + "name": "map", + "in": "path", + "description": "Map name", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "players", + "in": "query", + "description": "Players by SteamID64, comma-separated: 1 to 64 of them. Repeats count once.", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PlayersPersonalBests" + } + } + } + }, + "401": { + "description": "Missing, unknown or revoked API key", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + }, + "422": { + "description": "Not a valid map name, or `players` isn't 1 to 64 SteamID64s", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + } + }, + "security": [ + { + "server_key": [] + } + ] + } + }, "/v1/maps/{map}/records": { "get": { "tags": [ @@ -1189,6 +1302,69 @@ } } }, + "/v1/players/{player}/avatar": { + "get": { + "tags": [ + "players" + ], + "summary": "Redirects to the player's Steam avatar. Takes a `SteamID64`, `SteamID2` or `SteamID3`. Only players\nSourceJump knows are looked up on Steam; a player known only from the old site gets the avatar it had.", + "operationId": "player_avatar", + "parameters": [ + { + "name": "player", + "in": "path", + "description": "SteamID64, SteamID2 (STEAM_0:1:2) or SteamID3 ([U:1:4])", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "No avatar yet: a placeholder with the player's initials, cached five minutes", + "content": { + "image/svg+xml": { + "schema": { + "type": "string" + } + } + } + }, + "302": { + "description": "To the avatar on Steam's CDN; cached a day", + "headers": { + "Location": { + "schema": { + "type": "string" + }, + "description": "The avatar's URL" + } + } + }, + "404": { + "description": "SourceJump has no such player", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + }, + "422": { + "description": "Not a SteamID", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + } + } + } + }, "/v1/players/{player}/details": { "put": { "tags": [ @@ -2039,6 +2215,19 @@ "format": "int64" } }, + { + "name": "offset", + "in": "query", + "description": "Runs to skip, for going straight to a page. Default 0. Counted after `cursor` when both are given.", + "required": false, + "schema": { + "type": [ + "integer", + "null" + ], + "format": "int64" + } + }, { "name": "cursor", "in": "query", @@ -2063,7 +2252,7 @@ } }, "422": { - "description": "Not a valid tier, limit or cursor", + "description": "Not a valid tier, limit, offset or cursor", "content": { "application/json": { "schema": { @@ -5917,7 +6106,8 @@ "required": [ "at", "servers", - "players" + "players", + "peak_players" ], "properties": { "at": { @@ -5925,6 +6115,11 @@ "format": "date-time", "description": "Where the bucket starts." }, + "peak_players": { + "type": "integer", + "format": "int32", + "description": "The most players online at once during the bucket, across listed servers: each server's latest\nheartbeat count, summed at the same moment. Up to a month, sampled every 5 minutes; for a year, the\nday's highest total at any heartbeat." + }, "players": { "type": "integer", "format": "int32", @@ -6191,7 +6386,7 @@ "string", "null" ], - "description": "An ISO 3166-1 alpha-2 code to show instead of the Steam profile's country; null to show Steam's." + "description": "An ISO 3166-1 alpha-2 code to show instead of Steam's or a game server's, until a run's server finds one;\nnull to stop showing the player's pick." }, "dpi": { "type": [ @@ -7667,7 +7862,7 @@ }, "MapStats": { "type": "object", - "description": "The whole list at a glance, whatever the search or filter.", + "description": "Global totals and tier-scoped newest and weekly lists.", "required": [ "maps", "by_tier", @@ -7701,6 +7896,14 @@ "$ref": "#/components/schemas/PlayedMap" }, "description": "The maps the most players finished a run on in the last 7 days, most first." + }, + "tier": { + "type": [ + "integer", + "null" + ], + "format": "int32", + "description": "The tier the newest and weekly lists describe; None describes all tiers. Totals remain global." } } }, @@ -7945,6 +8148,14 @@ "style": { "type": "string" }, + "tier": { + "type": [ + "integer", + "null" + ], + "format": "int32", + "description": "The board's tier. None while tiers aren't in force or staff haven't set this board's, and for a legacy\nrun." + }, "time": { "type": "number", "format": "double", @@ -7954,6 +8165,14 @@ "type": "integer", "format": "int32", "description": "0 is the main track, 1 and up are bonuses." + }, + "world_record_time": { + "type": [ + "number", + "null" + ], + "format": "double", + "description": "The board's 2.0 record time, as on its map leaderboard, so a client can show the gap to it. None for a\nlegacy run." } } }, @@ -8094,6 +8313,50 @@ } } }, + "PlayerPersonalBest": { + "type": "object", + "required": [ + "steamid64", + "style", + "track", + "time", + "rank", + "run_id", + "finished_at" + ], + "properties": { + "finished_at": { + "type": "string", + "format": "date-time" + }, + "rank": { + "type": "integer", + "format": "int64", + "description": "Place on the leaderboard; equal times share a place, as in `…/records`." + }, + "run_id": { + "type": "integer", + "format": "int64" + }, + "steamid64": { + "type": "string", + "description": "SteamID64, as a string." + }, + "style": { + "type": "string" + }, + "time": { + "type": "number", + "format": "double", + "description": "Seconds." + }, + "track": { + "type": "integer", + "format": "int32", + "description": "0 is the main track, 1 and up are bonuses." + } + } + }, "PlayerPrivileges": { "type": "object", "required": [ @@ -8135,14 +8398,14 @@ }, "country_chosen": { "type": "boolean", - "description": "Whether the player picked `country_code` themselves, rather than it coming from Steam." + "description": "Whether the player picked `country_code` themselves, rather than it coming from a game server or Steam." }, "country_code": { "type": [ "string", "null" ], - "description": "ISO 3166-1 alpha-2: the one the player picked, or else their Steam profile's. None if neither has one." + "description": "ISO 3166-1 alpha-2: the latest one a game server found for them, the player's pick if they made it\nsince, or else their Steam profile's. None if none has one." }, "details": { "oneOf": [ @@ -8202,6 +8465,14 @@ "$ref": "#/components/schemas/PlayerStyle" }, "description": "One entry per style they hold a personal best in, sorted by style key. Counts are 2.0 alone." + }, + "tier_count": { + "type": [ + "integer", + "null" + ], + "format": "int32", + "description": "Number of tiers in force; None while the community hasn't set tiers, and personal bests then have no\ntier." } } }, @@ -8383,6 +8654,25 @@ } } }, + "PlayersPersonalBests": { + "type": "object", + "required": [ + "map", + "personal_bests" + ], + "properties": { + "map": { + "type": "string" + }, + "personal_bests": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PlayerPersonalBest" + }, + "description": "Sorted by player, style and track. A player with no personal best on the map has no entries. One flat\nlist keeps it simple to read in SourcePawn." + } + } + }, "PluginRelease": { "type": "object", "description": "A published `sourcejump.smx` build.", @@ -8858,7 +9148,8 @@ "RecentRuns": { "type": "object", "required": [ - "runs" + "runs", + "total" ], "properties": { "next_cursor": { @@ -8882,6 +9173,11 @@ ], "format": "int32", "description": "Number of tiers in force; None while the community hasn't set tiers, and runs then have no tier." + }, + "total": { + "type": "integer", + "format": "int64", + "description": "How many runs match the filters, across all pages." } } }, @@ -9677,6 +9973,14 @@ "name" ], "properties": { + "country_code": { + "type": [ + "string", + "null" + ], + "description": "The player's country, as the game server found it from their address with SourceMod's `GeoipCode2`: an ISO\n3166-1 alpha-2 code. Leave it out when the lookup finds nothing; send only the code, never the address. It\nbecomes the player's flag. A code SourceJump doesn't know as a country is ignored and the run is stored\nanyway. Runs only: detections ignore it.", + "example": "SE" + }, "name": { "type": "string" }, @@ -9899,6 +10203,7 @@ "required": [ "range", "bucket_minutes", + "peak_players", "points" ], "properties": { @@ -9906,6 +10211,11 @@ "type": "integer", "format": "int32" }, + "peak_players": { + "type": "integer", + "format": "int32", + "description": "The most players online at once across listed servers over the whole range, from the start of its\nfirst point up to now, the bucket in progress included: no point reads higher, and a shorter range never\nreads higher than a longer one." + }, "points": { "type": "array", "items": { diff --git a/deploy/deploy.sh b/deploy/deploy.sh index c96d320..e467617 100755 --- a/deploy/deploy.sh +++ b/deploy/deploy.sh @@ -18,7 +18,7 @@ command -v musl-gcc >/dev/null || { echo "musl-gcc is missing: sudo apt install (cd api && SQLX_OFFLINE=true CC_x86_64_unknown_linux_musl=musl-gcc \ cargo build --release --locked --target x86_64-unknown-linux-musl -p sourcejump-api) # Standalone server, plus the static assets Next expects next to it. -(cd web && npm run build) +(cd web && SJ_SITE_URL="https://$SITE_ADDRESS" npm run build) rm -rf web/.next/standalone/.next/static cp -r web/.next/static web/.next/standalone/.next/static if [ -d web/public ]; then cp -r web/public web/.next/standalone/; fi diff --git a/docs/api.md b/docs/api.md index 4153656..5d5105d 100644 --- a/docs/api.md +++ b/docs/api.md @@ -6,7 +6,7 @@ How the `/v1/` API behaves for game servers, and rules every client can rely on. |---|---|---| | `GET /v1/ruleset` | no | `ruleset.rs` | | `GET /v1/maps/{map}/zones` | no | `zones.rs` | -| `GET /v1/maps/{map}/records` | no | `records.rs` | +| `GET /v1/maps/{map}/records`, `…/personal-bests` | no | `records.rs`, `records/` | | `GET /v1/records/events`, `GET /v1/records/stream` | no | `record_events.rs`, `record_events/stream.rs` | | `GET /v1/maps`, `GET /v1/maps/{map}`, `…/leaderboard`, `…/wr-history` | no | `maps/` | | `GET /v1/runs/{id}` | no | `runs/detail.rs` | @@ -23,12 +23,12 @@ How the `/v1/` API behaves for game servers, and rules every client can rely on. | `/v1/staff/…`: log, keys, servers, listings | staff session | `staff.rs`, `staff/` | ## Rules every client can rely on -- **Errors** always have the body `{"error": "..."}`. The message is for people; don't match on it. -- **Retrying:** `2xx` means stored. Network errors, `5xx` and `429` (too many) are temporary: keep the item queued and resend it later. Any other `4xx` is final: the request breaks a rule and resending never works, so the plugin drops it. +- **Errors** have the body `{"error": "..."}`, for people; don't match on it. +- **Retrying:** `2xx` means stored. Network errors, `5xx` and `429` (too many) are temporary: keep the item queued, resend later. Any other `4xx` is final: the request breaks a rule, so the plugin drops it. - **Idempotency:** runs and detections carry an ID from the game server (`server_run_id`, `server_detection_id`), unique per server. A resend gets `200` with the first answer and changes nothing; the first send gets `201`. - **SteamID64s** are JSON strings: too big for a JavaScript number, and SourcePawn has no 64-bit integers. - **Map names** are lowercased; other characters than `a-z 0-9 _ - .`, or only dots, are rejected. -- **Server times** (`finished_at`, `detected_at`) are Unix seconds by the game server's clock. The API also records when it received each item. Times over 5 minutes ahead of the API's clock get `422`. +- **Server times** (`finished_at`, `detected_at`) are Unix seconds by the game server's clock. The API also stores when it got each. `422` if over 5 minutes ahead of the API's clock, or a run over 5 minutes before its ruleset version or server existed. ## Keys - One key per server, sent as `Authorization: Bearer sj_…`. Only its SHA-256 is stored, so a lost key is replaced, never recovered. @@ -43,20 +43,21 @@ How the `/v1/` API behaves for game servers, and rules every client can rely on. - Over 64 KB gets `413`. Hostnames lose control characters, cut to 64. An IP (IPv6: /64) may send 120 at once, then 30 a minute; more get `429`, before any key check (`heartbeat_limit.rs`). ## Runs -- Accepted only if the run's ruleset version exists, its style is ranked in that version, its tickrate matches the ruleset's `tickrate` if set, and the plugin reports the server as compliant. Field ranges are checked once, at the boundary. +- Accepted only if the run's ruleset version exists, its style is ranked in that version, its tickrate matches the ruleset's `tickrate` if set, and the plugin reports the server as compliant. - `personal_bests` holds each player's fastest run per map, style and track, updated in the same transaction. A tie keeps the earlier run. - Any keyed server can add a map by submitting a run on it. Which maps are ranked is a separate decision. ## Replays - The `replays` policy decides which replays are wanted (`request`: `new_personal_best`, the lead's call on 2026-10-19; `every_run` or `nothing`) and which styles' replays are public (`public_styles`: every ranked style, lead 2026-11-03). A missing policy asks for nothing and makes nothing public. -- A wanted replay gets a presigned `PUT` link, valid for an hour, to `uploads/replays/-.replay` in a private bucket. The server uploads there directly. A resend of the run returns a fresh link, with `last_refusal` (reason, time) if the last upload was refused, or no link once the replay is stored (delete the local copy). +- A wanted replay gets a presigned `PUT` link, valid for an hour, to `uploads/replays/-.replay` in a private bucket. A resend of the run returns a fresh link, with `last_refusal` (reason, time) if the last upload was refused, or no link once the replay is stored (delete the local copy). - Every 30 s a job (`replays/processing.rs`) lists the uploads and checks each against its run: shavit format 12 only, frames fill the file exactly, same map (any case), track, player and tickrate, and the time within half a tick. Over 128 MB is refused. A good file is stored as SJR (`replays/sjr.rs`, a fifth the size) at `replays/-.sjr`; the upload is deleted. A bad one is deleted, its reason kept on the `replays` row, and the server may upload again. A stored replay never changes; a failing upload is retried. - The bucket is public; random keys mean only the API reveals files. `GET /v1/runs/{id}` gives the SJR link (`replay.sjr_url`; invalidated runs too, lead 2026-11-03), its route from above (`replay.route`, `replay-viewer.md`), and `GET /v1/replays/{run_id}` the shavit file, rebuilt byte for byte at its first download and kept (own random key), only while the run is valid and its style is public. - `GET /v1/maps/{map}/records` marks each record `has_replay` by the same rule, so a server only asks for files it will get. ## Map records for `/wr` - `GET /v1/maps/{map}/leaderboard?style=&track=` pages one board (`total`, `next_cursor`); `player=` (any SteamID) adds their best and rank as `player_entry`. Opaque cursors name where a page ended, so paging survives that player improving; old run-ID ones work while the run is a PB. Its rows and `…/records`' carry `points` and `has_replay`. -- Both send an `ETag` (`etag.rs`, a body hash); `If-None-Match` with it gets a bodiless `304` until the answer changes. So do `/v1/ruleset`, `…/zones` and `/v1/plugin/latest`. +- `…/personal-bests?players=` (1–64 SteamID64s): their bests in every style and track, with `rank`. +- All three send an `ETag` (`etag.rs`, a body hash); `If-None-Match` with it gets a bodiless `304` until the answer changes. So do `/v1/ruleset`, `…/zones` and `/v1/plugin/latest`. ## Record events - `GET /v1/records/events` lists what happened to records, for servers announcing them or playing them on their bot: `run` (a new personal best, or a restored run that is one again), `replay` (its replay stored) and `invalidated` (staff took a run off a board; read the map's records again). Events are written with their change and kept a week. `previous_time` is the player's best on the board before that run, as it stood then (null: none; migration 0043). The same events feed the Discord posts of records and personal bests (`record_events/discord.rs`). @@ -66,7 +67,7 @@ How the `/v1/` API behaves for game servers, and rules every client can rely on. - The ruleset's `features.record_events` and `features.record_stream` tell the plugin to follow them (migration 0035). ## Policies and versioned data -Rulesets, zone sets and `policies` (community policy the plugin doesn't need: `servers`, `replays`, `tiers`, typed in `policies.rs`) are append-only: database triggers refuse updates and deletes. A change is a new version, and the newest version is in force. Runs record the ruleset version they were played under. A new version ships as a migration (lead, 2026-10-21); a test checks every ruleset they publish (`RulesetDocument::check`). The CLI's `tiers count` publishes the tier count, logged. +Rulesets, zone sets and `policies` (community policy the plugin doesn't need: `servers`, `replays`, `tiers`, typed in `policies.rs`) are append-only: database triggers refuse updates and deletes. A change is a new version, and the newest version is in force. Runs record the ruleset version they were played under. A new version ships as a migration (lead, 2026-10-21); a test checks every ruleset they publish (`RulesetDocument::check`). - Ranked styles carry shavit `settings` and `flags`; `RankedStyle` (`ruleset.rs`) says how they match. Provisional values: migrations 0041–0042 (lead, 2026-11-04). ## Zones diff --git a/docs/deploy.md b/docs/deploy.md index ac0af89..baaedc9 100644 --- a/docs/deploy.md +++ b/docs/deploy.md @@ -6,8 +6,8 @@ One VPS runs everything as systemd services under the `sourcejump` user: - **cloudflared** carries all web traffic from Cloudflare, which ends TLS, to Caddy on `127.0.0.1:80`. The firewall (ufw) lets in only SSH, rate-limited (6 new connections per 30 s per address); SSH takes keys only. A separate nftables table (`drop-ip-options.service`) drops IPv4 packets carrying IP options, which CVE-2026-98432 needs. - **Caddy** listens on localhost over plain HTTP. `/v1/*` and `/health` go to the API on `127.0.0.1:8080`; every other path goes to the web app on `127.0.0.1:3000`. One domain serves both, so the plugin and the browser use the same base URL. It sets `X-Forwarded-For` to Cloudflare's `Cf-Connecting-IP`, and security headers on every response (no framing, `nosniff`, referrer policy, HSTS). Template: `deploy/Caddyfile`. The web app's own `/v1` proxy exists only under `next dev`. - **API**: the static binary at `/opt/sourcejump/api/`. It applies pending migrations when it starts, so a deploy is "copy, restart". Config: `/etc/sourcejump/api.env`, including the object-storage settings (`SJ_S3_*`, with `SJ_S3_PUBLIC_URL` where browsers read public files such as map images); it refuses to start without them. -- **Web**: the Next.js standalone build at `/opt/sourcejump/web/`, run by Node 24. It reaches the API over loopback (`SJ_API_URL`). Config: `/etc/sourcejump/web.env`, where `NODE_OPTIONS` caps its heap. -- **Postgres 18**: database and role `sourcejump`, reached over the local socket with peer authentication, so there is no database password. Requests use their own pool of 10 connections, where a statement may run 5 s (`query_time_limit.rs`); startup, jobs and the CLI use one without the limit, and recounts and invalidations lift it. +- **Web**: the Next.js standalone build at `/opt/sourcejump/web/`, run by Node 24. It reaches the API over loopback (`SJ_API_URL`). `just deploy` builds it with `SJ_SITE_URL` from `SITE_ADDRESS`, for link previews' whole addresses. Config: `/etc/sourcejump/web.env`, where `NODE_OPTIONS` caps its heap. +- **Postgres 18**: database and role `sourcejump`, reached over the local socket with peer authentication, so there is no database password. Requests use their own pool of 10 connections, where a statement may run 5 s (`query_time_limit.rs`); startup, jobs and the CLI use one without the limit, and recounts and invalidations lift it. A run being stored waits at most 2 s for another recount, then gets a `500` its server resends (`standings.rs`). Each environment has a file `deploy/environments/.env` with `SSH_TARGET` (a `Host` alias from your `~/.ssh/config` that logs in as root; server addresses stay out of the repo), `SITE_ADDRESS` (the domain) and optionally `NOINDEX=true`, which makes Caddy send `X-Robots-Tag: noindex, nofollow` on every response. These hold no secrets and are committed. diff --git a/docs/design-system.md b/docs/design-system.md index ad898a2..4293cc8 100644 --- a/docs/design-system.md +++ b/docs/design-system.md @@ -30,7 +30,7 @@ One visual language that every page is built from, so pages can't drift apart. S | `TierBadge` | `tier` and `tierCount` from the API | | `Avatar` | Steam avatar or initials; `sm` to `xl` | | `Flag` | Country flag from an ISO code, a grey placeholder without one; `hint` replaces its tooltip | -| `Table` + `TableHead`/`TableBody`/`TableRow`/`TableHeaderCell`/`TableCell` | Leaderboards and staff lists; `numeric` cells right-align, `wrap` cells let long names wrap. Scrolls sideways inside its frame when too wide | +| `Table` + `TableHead`/`TableBody`/`TableRow`/`TableHeaderCell`/`TableCell` | Leaderboards and staff lists; `numeric` cells right-align, `wrap` cells let long names wrap, a `separated` row starts a group apart. Scrolls sideways inside its frame when too wide | | `Tabs` | Panels on one page; `underline` or `segmented` | | `LinkTabs` | Looks like `Tabs`, but each tab is a link: a view the server renders, such as the Maps page's sort | | `Segmented` | Looks like segmented `Tabs`, for a choice that changes the view in place (a server's activity range, a post's kind). The chosen option is in the accent | diff --git a/docs/site-api.md b/docs/site-api.md index 36ecdcd..c66f82a 100644 --- a/docs/site-api.md +++ b/docs/site-api.md @@ -1,54 +1,56 @@ # Site API -What the endpoints behind the website do: sign-in, players, maps, the server list and community posts; the staff tools are in `staff-api.md`. Rules for every client (errors, retries, SteamIDs) and game servers' endpoints: `api.md`. +The website's endpoints; staff tools: `staff-api.md`. Rules for every client and game servers' endpoints: `api.md`. ## Sign-in and sessions -Players sign in with Steam (OpenID 2.0); the endpoints answer browsers (redirects, cookies) via the site's origin (Caddy in production, Next.js locally). -- Steam must confirm its answer (`check_authentication`). Only signed fields are read, the return URL must be our callback, a nonce works once, under 5 minutes old (`openid_nonces`). The callback URL must carry the value `/v1/auth/steam` put in the `sj_sign_in` cookie, tying sign-in to its browser. Refused: `/sign-in/failed`; cancelled: back where they were. +Steam OpenID sign-in uses the configured site origin for cookies and callbacks, canonicalizing aliases first. +- Steam must confirm its answer (`check_authentication`). Only signed fields are read, the return URL must be our callback, a nonce works once, within 5 minutes (`openid_nonces`). The callback must carry the value `/v1/auth/steam` put in the `sj_sign_in` cookie, tying sign-in to its browser. Refused: `/sign-in/failed`; cancelled: back where they were. - `return_to` must be a path on our site; anything else becomes `/`. -- A session is 32 random bytes in the `sj_session` cookie (`HttpOnly; Secure; SameSite=Lax`). Only the SHA-256 is stored. It lasts 30 days from last use (expiry moves at most daily). -- Sign-out also requires our `Origin` header. A missing session answers `401` without `WWW-Authenticate`. -- `SJ_PUBLIC_URL` is where players reach the site; redirects and the origin check use it. +- A session is 32 random bytes in the `sj_session` cookie (`HttpOnly; Secure; SameSite=Lax`); only its SHA-256 is stored. It lasts 30 days from last use (expiry moves at most daily). +- Sign-out needs our `Origin`; so does `…/sign-out-everywhere`, which ends all their sessions. A missing session gets `401` without `WWW-Authenticate`. +- `SJ_PUBLIC_URL`, where players reach the site, builds redirects and the origin check. ## Players and privileges -- Profiles take a SteamID64, SteamID2 or SteamID3 and answer with the SteamID64. Placements rank personal bests per map, style and track; equal times share a place. -- Per style, a profile counts completed maps (main tracks, out of the map list's count), completed bonuses and world records, and carries the first 50 main-track personal bests by map; `…/personal-bests?style=&tracks=main|bonuses&cursor=` pages on, and `records=true` keeps only world records (2.0 only). Without `style` it lists every style, newest first; `all_styles` counts across styles. Ranks: `main_standing`, `bonus_standing` (lead, 2026-11-04). -- `PUT /v1/players/{player}/details` (rules in `players/details.rs`): setup and a country (`GET /v1/countries`), a save per 5 s; others' need `manage_bans` and a logged reason. Old-site setup shows first. -- Avatar, country (unless the player picked one) and (until a run gives one) name come from their public Steam profile XML, fetched at sign-in and on viewing one over a day old (an hour after a failed one): one request per 2 s, 50 queued, one per player. Country names map to ISO codes in `players/countries.rs`. -- Staff privileges are a bitmap in `players.privileges` (`players/privileges.rs`). Bit positions never change; the API names privileges and never sends numbers. `players.restrictions` is unused (bans hold restrictions). The CLI's `privileges grant …`, `revoke`, `list` and the staff tools share `staff/privileges.rs`. +- Profiles take a SteamID64, SteamID2 or SteamID3 and answer with a SteamID64. +- Per style, a profile counts completed maps (main tracks, out of the map list's count), completed bonuses and world records, and carries the first 50 main-track PBs by map; `…/personal-bests?style=&tracks=main|bonuses&cursor=` pages on; `records=true` keeps only 2.0 world records. Without `style`, every style, newest first; `all_styles` counts across styles. Ranks: `main_standing`, `bonus_standing` (lead, 2026-11-04). PBs have a placement (ties share one), `tier` and `world_record_time`; profiles `tier_count`. +- `PUT /v1/players/{player}/details` (`players/details.rs`): setup and a country (`GET /v1/countries`), a save per 5 s; others' need `manage_bans` and a logged reason. Old-site setup shows first. +- Country: a run's server GeoIP code, else the player's pick (shown until the next such run), else Steam's. +- Avatar, country and (until a run gives one) name come from the public Steam profile XML, fetched at sign-in, and when a day old after a run, view or `…/avatar` (an hour after a failure): one request per 2 s, 50 queued, one per player. Country names map to ISO codes in `players/countries.rs`. +- `GET /v1/players/{player}/avatar` (`players/avatar.rs`) 302s to the stored Steam CDN avatar (cached a day); if none, fetched unpaced (4 at once, 4 s), else an initials SVG (5 min). Unknown: 404, no fetch; legacy-only: the old site's. +- Staff privileges: a bitmap in `players.privileges` (`players/privileges.rs`); bit positions never change; the API names them, never numbers. `players.restrictions` is unused (bans hold restrictions). The CLI's `privileges grant …`, `revoke`, `list` and the staff tools share `staff/privileges.rs`. ## Maps and leaderboards -- The map list holds every map with a run (`maps.last_run_at`, set by the ingest); whether one is ranked is open. Sorts: name, players, last/first run (`listed_at`), tier, main-track record; `tier` keeps one tier. `player` (any SteamID form) with `completed=true|false` keeps maps whose main track they have or haven't finished in the list's style; `completed` counts them. `stats`: tiers, 5 newest, 5 most players this week. -- Leaderboards rank personal bests per map, style and track; equal times share a place, and the earlier run is listed first. The world record of a tie belongs to whoever set it first. -- `GET /v1/maps/{map}` carries every style and track's top 25, `next_cursor` and WR history, so a map page switches between them without another request. `…/leaderboard?cursor=` pages on from there; cursors are opaque. -- WR history is every run faster than all runs that finished before it on that leaderboard, by `finished_at`. Ties don't count. +- Maps with runs (`maps.last_run_at`). `q` searches map names and the style's main WR holders. Sorts: name, players, last/first run (`listed_at`), tier and main WR. `tier` keeps one main tier. `player` (any SteamID) with `completed=true|false` filters the style's main completions; `completed` counts them. Global `stats` totals; newest and weekly lists take five within `stats.tier` (null: all). Weekly counts distinct players. +- Leaderboards rank PBs per map, style and track; equal times share a place, the earlier run listed first. A tie's world record belongs to whoever set it first. +- `GET /v1/maps/{map}` carries every style and track's top 25, `next_cursor` and WR history, for map pages to switch locally. `…/leaderboard?cursor=` pages on from there; cursors are opaque. +- WR history: every run faster than all finished before it on that board, by `finished_at`; ties don't count. - Tiers: the `tiers` policy holds the tier count, `map_tiers` the tier per map and track (append-only, newest in force). The API serves no tier until a count is published. -- Any run opens by ID with stats, server and place (while it's a personal best); compliance and keys stay private. -- Pre-2.0 runs (`legacy_*` tables, `legacy.rs`) count toward no 2.0 standing: not WRs, WR histories, placements or `…/records`. The normal style's main track has two more views, `view=all` (each player's faster of 2.0 and legacy) and `view=legacy`, on `…/leaderboard` and `…/personal-bests`; entries carry `legacy`; a legacy `run_id` is the old site's, at `GET /v1/legacy-runs/{id}` (no run page). A map's `legacy_record_history` charts the Pre-2.0 view. Banned players' legacy runs are left out. Legacy-only maps and players get pages and show in search. -- The tier count is published with the CLI's `tiers count` (it can't drop below a tier a map holds). Staff rate tracks and set images and descriptions on the map's Manage view (`/maps/{map}/manage`), or with the CLI's `maps tier` and `maps image`, logged. -- A map holds up to 10 pictures (`map_images`, in order; the first is the cover). The API reads PNG, JPEG or WebP up to 15 MB, crops to 16:9, centred (at least 1920×1080), and stores 1920×1080 and 480×270 WebP at quality 80 (`maps/image.rs`), named by content hash, cached for good, deleted with the picture. `GET /v1/maps/{map}` carries `images`, each with both URLs and `focus` (0–100, the strip a banner shows); lists carry the cover as `image`. Browsers read the files from `SJ_S3_PUBLIC_URL`; the API only writes them (ADR 0006). +- Any run opens by ID with stats, server and place (while a PB); compliance and keys stay private. +- Pre-2.0 runs (`legacy_*` tables, `legacy.rs`) count toward no 2.0 standing: not WRs, WR histories, placements or `…/records`. The normal style's main track also has `view=all` (each player's faster of 2.0 and legacy) and `view=legacy` on `…/leaderboard` and `…/personal-bests`; entries carry `legacy`; a legacy `run_id` is the old site's, at `GET /v1/legacy-runs/{id}` (no run page). A map's `legacy_record_history` charts the Pre-2.0 view. Banned players' legacy runs are left out. Legacy-only maps and players have pages and show in search. +- The CLI's `tiers count` publishes the count (never below a tier a map holds). Staff rate tracks and set images and descriptions on the map's Manage view (`/maps/{map}/manage`), or with the CLI's `maps tier` and `maps image`, logged. +- A map holds up to 10 pictures (`map_images`, ordered; first is the cover). The API takes PNG, JPEG or WebP ≤15 MB, crops to 16:9, centred (at least 1920×1080), and stores 1920×1080 and 480×270 WebP at quality 80 (`maps/image.rs`), named by content hash, cached for good, deleted with the picture. `GET /v1/maps/{map}` carries `images`, each with both URLs and `focus` (0–100, the strip a banner shows); lists carry the cover as `image`. Browsers read them from `SJ_S3_PUBLIC_URL`; the API only writes (ADR 0006). - Staff set `description` (≤1000 chars), `released` (year, month or day) and `mapper` (made if new) ## Player leaderboards - `GET /v1/leaderboards?style=&track=main|bonuses` gives, in one style and kind of track, the top 20 (`limit`) by points and by tracks completed (`leaderboards.rs`); equal shown (rounded) values share a rank. `view=legacy` ranks legacy records (one style, main tracks, the old site's tiers), banned players left out; never counted toward 2.0. `GET /v1/leaderboards/points|completed` is one list in full (`limit`, `offset`, `total`), and each player's world records in that style and kind of track (`leaderboards/list.rs`). -- Points per personal best: a map is worth `base` at tier 1, times `growth_percent` each tier up (a bonus `bonus_percent` of that at its own tier); finishing earns `finish_percent`, the rest is speed, `(WR ÷ time) ^ speed_exponent` (SQL `points_for`). Untiered tracks earn none. The `points` policy holds the values; until one is published the API uses `PointsPolicy::DRAFT` (50, 200, 50, 4, 25) and says `draft` (lead, 2026-10-26). -- Stored, not computed per visit (lead, 2026-10-26): `personal_bests.points`, `standings` (per style, main and bonuses apart) and `legacy_standings`, recounted by `leaderboards/standings.rs` where they change: a track when a personal best or its tier changes there (a new WR moves all points); everything on a points or tiers policy, or at startup if the formula changed; legacy on bans, lifts, imports. One advisory lock serializes recounts. So are world records (`leaderboards/world_records.rs`): holders and `runs.was_record`, per board. +- Points per PB: a map is worth `base` at tier 1, times `growth_percent` each tier up (a bonus `bonus_percent` of that at its own tier); finishing earns `finish_percent`, the rest is speed, `(WR ÷ time) ^ speed_exponent` (SQL `points_for`). Untiered tracks earn none. The `points` policy holds the values; until one is published the API uses `PointsPolicy::DRAFT` (50, 200, 50, 4, 25) and says `draft` (lead, 2026-10-26). +- Stored, not computed per visit (lead, 2026-10-26): `personal_bests.points`, `standings` (per style, main and bonuses apart) and `legacy_standings`, recounted by `leaderboards/standings.rs` where they change: a track when a PB or its tier changes there (a new WR moves all points); everything on a points or tiers policy, or at startup if the formula changed; legacy on bans, lifts, imports. One advisory lock serializes recounts. So are world records (`leaderboards/world_records.rs`): holders and `runs.was_record`, per board. ## Activity -- `GET /v1/runs?style=&track=main|bonus&min_tier=&records=&cursor=` (`runs/recent.rs`): valid runs newest first by `finished_at`, each with its board's tier, `placement` counted against the valid runs before it (null unless it beat the player's own best), `world_record` (as in WR history) and its `gap` to the record it faced. `min_tier` matches nothing until a tier count is published. +- `GET /v1/runs?style=&track=main|bonus&min_tier=&records=&cursor=&offset=` (`runs/recent.rs`, with `total`): valid runs newest first by `finished_at`, each with its board's tier, `placement` against the valid runs before it (null unless a PB), `world_record` (as in WR history) and `gap` to the record it faced. `min_tier` matches nothing until a tier count is published. ## Daily totals - `GET /v1/daily-totals/players|runs?range=month|year|all` (`daily_totals.rs`, hourly): players with a time (incl. pre-2.0), 2.0 runs and WRs per UTC day. ## Server list -- `GET /v1/servers` shows only addresses in `server_listings`, kept by staff (lead, 2026-10-20), heard from within the `servers` policy's `listed_hours` (24); `online` means within `online_minutes` (25). Without the policy the list is empty. *Connected*: the latest heartbeat had a still-valid key. Compliance and versions aren't public. `whitelist` (staff-set: only approved players join) puts it under the Whitelist tab. -- Listed servers' heartbeats also go to `server_heartbeat_log` (players, 30 days) and `server_activity_daily` (per-server UTC-day totals, 400 days). `…/activity?range=day|week|month` buckets the log (20 min, 2 h, 8 h); `year` reads the daily totals. Per bucket: servers heard from, and their average players summed. -- Staff with `manage_servers` see every server on `/servers`: unlisted ones dimmed, toggles to list or unlist and to mark whitelist, and a dialog with its last report (versions, plugins, compliance, reported IP, key), loaded in the browser, never in the server render. The CLI's `servers seen`, `servers list ` and `servers unlist ` do the same. +- `GET /v1/servers` shows only addresses in `server_listings`, kept by staff (lead, 2026-10-20), heard from within the `servers` policy's `listed_hours` (24); `online` means within `online_minutes` (25). No policy, no list. *Connected*: the latest heartbeat had a still-valid key. Compliance and versions aren't public. `whitelist` (staff-set: only approved players join) puts it under the Whitelist tab. +- Listed servers' heartbeats also go to `server_heartbeat_log` (players, 30 days) and, per UTC day for 400 days, `server_activity_daily` (per-server totals) and `server_activity_peaks`. `…/activity?range=day|week|month` buckets the log (20 min, 2 h, 8 h), `year` the daily tables. Per bucket: servers heard from, their average players summed, `peak_players` (most online at once); the top-level one, the whole range through now (never above a longer range's). +- Staff with `manage_servers` see every server on `/servers`: unlisted ones dimmed, listing and whitelist toggles, and a dialog with its last report (versions, plugins, compliance, reported IP, key), browser-loaded, never server-rendered. The CLI's `servers seen` and `servers list|unlist ` do the same. ## Community posts -- Articles (Markdown) and YouTube videos (a link with an optional note; the site links out and embeds nothing, lead 2026-10-20). Players with `post_community` post and change or remove their own; `manage_posts` edits anyone's, with a `reason` and logged (`edit_post`, fields changed) when it's someone else's and changes something. Every write needs a session and our `Origin`. -- `body_html` is rendered on each read by `posts/markdown.rs`, the only place deciding what HTML a post may contain: raw HTML becomes text, images their alt text, and links keep only web, mail and on-site addresses, opening `nofollow noopener`. -- A video link in any common form is stored as its YouTube ID (`posts/youtube.rs`), served back as a watch link. -- Pages link to `/community/{id}-{slug}`; only the ID counts, so a new title doesn't break links. Removing a post hides it and keeps the row. `DELETE /v1/posts/{post}` is for the author only. +- Articles (Markdown) and YouTube videos (a link with an optional note; the site links out and embeds nothing, lead 2026-10-20). `post_community` lets players post and change or remove their own; `manage_posts` edits anyone's, with a `reason`, logged (`edit_post`, fields changed) if someone else's and changed. Every write needs a session and our `Origin`. +- `body_html` is rendered on each read by `posts/markdown.rs`, sole judge of the HTML a post may hold: raw HTML becomes text, images their alt text, and links keep only web, mail and on-site addresses, opening `nofollow noopener`. +- Video links in any common form are stored as YouTube IDs (`posts/youtube.rs`), served as watch links. +- Pages link to `/community/{id}-{slug}`; only the ID counts, so retitling keeps links. Removal hides a post (the row stays); `DELETE /v1/posts/{post}` is the author's alone. ## Run comments - `/v1/runs/{id}/comments` (`runs/comments.rs`): players not banned from posting comment and reply one level deep (plain text, one per 30 s); the runner pins one; authors `DELETE` theirs (lead 2026-10-29). 25 threads a page, 3 replies each; more at `…/replies`. diff --git a/web/e2e/maps-cards.e2e.ts b/web/e2e/maps-cards.e2e.ts new file mode 100644 index 0000000..f600667 --- /dev/null +++ b/web/e2e/maps-cards.e2e.ts @@ -0,0 +1,305 @@ +// Map-card regressions: real podiums, complete text, responsive columns and stable image dimensions. +import { expect, test, type Locator } from "@playwright/test"; +import type { Schemas } from "../src/api/client"; +import { formatTime } from "../src/features/runs/time"; + +async function expectTextInside(card: Locator) { + const clipped = await card.evaluate((element) => { + const bounds = element.getBoundingClientRect(); + const walker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT); + const failures: string[] = []; + let node; + while ((node = walker.nextNode())) { + if (!node.textContent?.trim()) continue; + const range = document.createRange(); + range.selectNodeContents(node); + for (const rect of Array.from(range.getClientRects())) { + if ( + rect.left < bounds.left - 1 || + rect.right > bounds.right + 1 || + rect.top < bounds.top - 1 || + rect.bottom > bounds.bottom + 1 + ) { + failures.push(node.textContent); + } + } + } + return failures; + }); + expect(clipped).toEqual([]); +} + +test("cards show the API's top three for the chosen style", async ({ + page, + request, +}) => { + const response = await request.get("/v1/maps?limit=1&sort=popular"); + const list = (await response.json()) as Schemas["MapList"]; + const map = list.maps[0]!; + const result = await request.get( + `/v1/maps/${encodeURIComponent(map.name)}/leaderboard?style=${list.style}&limit=3`, + ); + const board = (await result.json()) as Schemas["Leaderboard"]; + await page.goto("/maps"); + const card = page.locator(`[data-map="${map.name}"]`); + await expect(card).toBeVisible(); + const rows = card.locator("ol > li"); + await expect(rows).toHaveCount(board.entries.length); + for (let index = 0; index < board.entries.length; index++) { + const entry = board.entries[index]!; + await expect( + rows.nth(index).getByLabel(`Placement ${entry.rank}`), + ).toBeVisible(); + await expect( + rows.nth(index).getByText(entry.player.name, { exact: true }), + ).toBeVisible(); + await expect( + rows.nth(index).getByText(formatTime(entry.time), { exact: true }), + ).toBeVisible(); + } + await expectTextInside(card); + const preview = await card.evaluate((element) => { + const cover = element.firstElementChild!; + const image = cover.firstElementChild!; + const records = element.querySelector("ol")!; + return { + bottom: cover.getBoundingClientRect().bottom, + records: records.getBoundingClientRect().top, + mask: getComputedStyle(image).maskImage, + filter: getComputedStyle(image).filter, + }; + }); + expect(preview.bottom).toBeLessThanOrEqual(preview.records); + expect(preview.mask).toBe("none"); + expect(preview.filter).toBe("none"); +}); + +test("map hover stays still and the preview opens the map", async ({ + page, +}) => { + await page.goto("/maps"); + const card = page.locator("[data-map]").first(); + await expect(card).toBeVisible(); + await card.scrollIntoViewIfNeeded(); + const before = await card.boundingBox(); + const border = await card.evaluate( + (element) => getComputedStyle(element).borderColor, + ); + await card.hover(); + expect(await card.boundingBox()).toEqual(before); + expect( + await card.evaluate((element) => getComputedStyle(element).borderColor), + ).not.toBe(border); + const href = await card.locator("h3 a").getAttribute("href"); + const preview = await card.locator(":scope > div").first().boundingBox(); + await page.mouse.click( + preview!.x + preview!.width / 2, + preview!.y + preview!.height / 2, + ); + await expect(page).toHaveURL(new RegExp(`${href}$`)); +}); + +test("player links and replay controls work independently of the map link", async ({ + page, +}) => { + await page.goto("/maps"); + const card = page.locator("[data-map]").first(); + await expect(card).toBeVisible(); + await page.evaluate(() => { + (window as { mapsStillHere?: boolean }).mapsStillHere = true; + }); + const replay = card + .getByRole("link", { name: "Watch replay", exact: true }) + .first(); + const href = await replay.getAttribute("href"); + const id = /\/runs\/(\d+)/.exec(href!)![1]; + await replay.click(); + await expect(page).toHaveURL(new RegExp(`/maps\\?replay=${id}$`)); + const dialog = page.getByRole("dialog"); + await expect(dialog).toBeVisible(); + await expect(dialog.getByRole("link", { name: "Run page" })).toHaveAttribute( + "href", + `/runs/${id}`, + ); + expect( + await page.evaluate( + () => (window as { mapsStillHere?: boolean }).mapsStillHere, + ), + ).toBe(true); + await page.keyboard.press("Escape"); + await expect(dialog).toBeHidden(); + await expect(page).toHaveURL(/\/maps$/); + await expect(replay).toBeFocused(); + const player = card + .locator("ol > li") + .first() + .locator('a[href^="/players/"]'); + await expect( + card.locator("ol > li").first().locator('a[href^="/players/"]'), + ).toHaveCount(1); + const profile = await player.getAttribute("href"); + const avatar = player.locator(":scope > span").first(); + const name = player.locator(":scope > span").nth(1); + const color = await name.evaluate( + (element) => getComputedStyle(element).color, + ); + const avatarBorder = await avatar + .locator("img, span") + .first() + .evaluate((element) => getComputedStyle(element).borderColor); + await avatar.hover(); + await expect + .poll(() => name.evaluate((element) => getComputedStyle(element).color)) + .not.toBe(color); + expect( + await avatar + .locator("img, span") + .first() + .evaluate((element) => getComputedStyle(element).borderColor), + ).toBe(avatarBorder); + await avatar.click(); + await expect(page).toHaveURL(new RegExp(`${profile}$`)); + await page.goBack(); + await player.locator(":scope > span").nth(1).click(); + await expect(page).toHaveURL(new RegExp(`${profile}$`)); + await expect(dialog).toBeHidden(); +}); + +test("cards keep complete names and long times inside at every breakpoint", async ({ + page, +}) => { + await page.goto("/maps"); + const card = page.locator("[data-map]").first(); + await expect(card).toBeVisible(); + await page.evaluate(() => document.fonts.ready); + await card.evaluate((element) => { + element.querySelector("h3 a")!.textContent = + "bhop_" + "long_map_name_".repeat(5).slice(0, 59); + for (const row of Array.from(element.querySelectorAll("ol > li"))) { + const player = row.querySelector('a[href^="/players/"]')!; + const result = row.lastElementChild!; + player.children[1]!.textContent = + "Long player name 玩家 日本語 Кириллица"; + result.children[0]!.querySelector("a")!.textContent = "1:23:45.678"; + result.children[1]!.textContent = "+2:34:56.789"; + } + }); + for (const width of [1920, 1440, 1084, 1080, 1024, 768, 390, 320]) { + await page.setViewportSize({ width, height: 1000 }); + await expectTextInside(card); + expect( + await page.evaluate( + () => document.documentElement.scrollWidth > innerWidth, + ), + ).toBe(false); + const layout = await card.evaluate((element) => ({ + width: element.clientWidth, + result: getComputedStyle( + element.querySelector("ol > li > span:last-child")!, + ).display, + })); + expect(layout.result).toBe(layout.width >= 320 ? "grid" : "flex"); + if (width === 1920 || width === 1440) { + const columns = await card + .locator("xpath=../..") + .evaluate( + (element) => + getComputedStyle(element).gridTemplateColumns.split(" ").length, + ); + expect(columns).toBe(width === 1920 ? 4 : 3); + } + } +}); + +test("loading avatars and map pictures does not move the podium", async ({ + page, +}) => { + await page.route( + /avatars(?:\.[a-z]+)?\.steamstatic\.com|\/v1\/players\/[^/]+\/avatar/, + (route) => route.abort(), + ); + await page.goto("/maps"); + const card = page.locator("[data-map]").first(); + await expect(card).toBeVisible(); + await page.evaluate(() => document.fonts.ready); + const before = await card.locator("ol").boundingBox(); + await card + .locator("img") + .evaluateAll((images) => + Promise.all( + images.map((image) => + (image as HTMLImageElement).decode().catch(() => {}), + ), + ), + ); + expect(await card.locator("ol").boundingBox()).toEqual(before); + await expect(card.locator("ol img")).toHaveCount(0); + await expectTextInside(card); +}); + +test("a single finisher and an empty style stay honest and readable", async ({ + page, + request, +}) => { + let selected: { list: Schemas["MapList"]; style: string } | undefined; + for (const style of ["scroll", "hsw"]) { + const response = await request.get(`/v1/maps?style=${style}&limit=100`); + if (!response.ok()) continue; + const list = (await response.json()) as Schemas["MapList"]; + if ( + list.style === style && + list.maps.some((map) => !map.world_record) && + list.maps.some((map) => map.world_record) + ) { + selected = { list, style }; + break; + } + } + test.skip( + !selected, + "The current API data has no style with both empty and populated boards.", + ); + const { list, style } = selected!; + const empty = list.maps.find((map) => !map.world_record)!; + await page.setViewportSize({ width: 390, height: 900 }); + await page.goto(`/maps?style=${style}&q=${encodeURIComponent(empty.name)}`); + const emptyCard = page.locator(`[data-map="${empty!.name}"]`); + await expect( + emptyCard.getByText("No times in this style", { exact: true }), + ).toBeVisible(); + await expect(emptyCard.getByLabel("Placement 1")).toHaveCount(0); + await expectTextInside(emptyCard); + await expect(emptyCard.locator("h3 a")).toHaveAttribute( + "href", + `/maps/${empty.name}?style=${style}`, + ); + + // Pick an actual sparse board rather than inventing second and third place. + let single: string | undefined; + for (const map of list.maps + .filter((map) => map.world_record) + .sort((a, b) => a.players - b.players) + .slice(0, 6)) { + const response = await request.get( + `/v1/maps/${encodeURIComponent(map.name)}/leaderboard?style=${style}&limit=3`, + ); + const board = (await response.json()) as Schemas["Leaderboard"]; + if (board.total === 1) { + single = map.name; + break; + } + } + test.skip( + !single, + "The current API data has no sampled board with one finisher.", + ); + await page.goto(`/maps?style=${style}&q=${encodeURIComponent(single!)}`); + const singleCard = page.locator(`[data-map="${single}"]`); + await expect(singleCard.locator("ol > li")).toHaveCount(1); + await expect(singleCard.getByText(/ranked times? in this style/)).toHaveCount( + 0, + ); + await expect(singleCard.getByLabel("Placement 1")).toBeVisible(); + await expect(singleCard.getByLabel("Placement 2")).toHaveCount(0); + await expectTextInside(singleCard); +}); diff --git a/web/e2e/maps-overview.e2e.ts b/web/e2e/maps-overview.e2e.ts new file mode 100644 index 0000000..5529378 --- /dev/null +++ b/web/e2e/maps-overview.e2e.ts @@ -0,0 +1,342 @@ +// Regression checks for the Maps overview's alignment and filtered layouts. +import { expect, test, type Locator } from "@playwright/test"; +import type { Schemas } from "../src/api/client"; + +async function expectAligned(overview: Locator) { + const geometry = await overview.evaluate((element) => { + const nav = element.querySelector("nav")!; + const links = nav.querySelectorAll("li a"); + const reset = nav.querySelector("a")!.getBoundingClientRect(); + const first = links[0]!.firstElementChild!.getBoundingClientRect(); + const last = + links[links.length - 1]!.lastElementChild!.getBoundingClientRect(); + const panel = element.getBoundingClientRect(); + const graph = element.querySelector("svg")!.getBoundingClientRect(); + const legend = nav.getBoundingClientRect(); + const center = (rect: DOMRect) => rect.y + rect.height / 2; + return { + left: Math.abs(reset.left - first.left), + right: Math.abs(reset.right - last.right), + graph: Math.abs(center(graph) - center(panel)), + legend: Math.abs(center(legend) - center(panel)), + headings: Array.from(element.querySelectorAll("section h2")).map( + (heading) => heading.getBoundingClientRect().top, + ), + }; + }); + expect(geometry.left).toBeLessThan(1); + expect(geometry.right).toBeLessThan(1); + expect(geometry.graph).toBeLessThan(1); + expect(geometry.legend).toBeLessThan(1); + for (const top of geometry.headings) { + expect(Math.abs(top - geometry.headings[0]!)).toBeLessThan(1); + } +} + +test("the overview stays centered and the reset matches the tier columns", async ({ + page, +}) => { + await page.goto("/maps"); + const overview = page.getByRole("region", { + name: "Map overview", + exact: true, + }); + const nav = overview.getByRole("navigation", { name: "Filter maps by tier" }); + await expect(nav).toBeVisible(); + await page.evaluate(() => document.fonts.ready); + await expectAligned(overview); + + // The page name remains available to screen readers without adding a visible heading. + const heading = await page + .getByRole("heading", { name: "Maps", exact: true }) + .boundingBox(); + expect(heading!.height).toBeLessThanOrEqual(1); + + const reset = nav.getByRole("link", { name: /All tiers/ }); + const firstTier = nav.locator("li a").first(); + const bounds = await firstTier.boundingBox(); + await firstTier.hover(); + expect(await firstTier.boundingBox()).toEqual(bounds); + await reset.focus(); + await page.keyboard.press("Tab"); + await expect(firstTier).toBeFocused(); + await page.keyboard.press("Enter"); + await expect(firstTier).toHaveAttribute("aria-current", "true"); + await expectAligned(overview); + await reset.click(); + await expect(reset).toHaveAttribute("aria-current", "true"); + await expectAligned(overview); + + await page.setViewportSize({ width: 1920, height: 1000 }); + const spacing = await overview.evaluate((element) => { + const groups = Array.from(element.querySelectorAll("section")); + return { + trailing: + element.getBoundingClientRect().right - + groups[groups.length - 1]!.getBoundingClientRect().right, + columnGaps: groups.map( + (group) => + group.getBoundingClientRect().right - + (group.querySelector("ul") ?? group).getBoundingClientRect().right, + ), + }; + }); + expect(spacing.trailing).toBeLessThanOrEqual(21); + for (const gap of spacing.columnGaps) expect(gap).toBeLessThan(1); + const controls = await overview.locator("xpath=../..").evaluate((element) => { + const frame = element + .querySelector('[aria-label="Map overview"]')! + .parentElement!.getBoundingClientRect(); + const input = element + .querySelector('input[type="search"]')! + .getBoundingClientRect(); + const buttons = element.querySelectorAll('button[aria-haspopup="menu"]'); + const first = buttons[0]!.getBoundingClientRect(); + const gallery = document + .querySelector("[data-map]")! + .closest("section")! + .getBoundingClientRect(); + return { + searchWidth: input.width, + left: Math.abs(first.left - gallery.left), + right: Math.abs(input.right - gallery.right), + separated: input.top - frame.bottom, + frameCenter: Math.abs( + (frame.left + frame.right - gallery.left - gallery.right) / 2, + ), + frameWidth: frame.width, + pageWidth: gallery.width, + }; + }); + expect(controls.searchWidth).toBeLessThanOrEqual(320); + expect(controls.left).toBeLessThan(1); + expect(controls.right).toBeLessThan(1); + expect(controls.separated).toBeGreaterThanOrEqual(20); + expect(controls.frameCenter).toBeLessThan(1); + expect(controls.frameWidth).toBeLessThan(controls.pageWidth); +}); + +test("the donut has clean sector boundaries, animates hover and has no click focus box", async ({ + page, +}) => { + await page.emulateMedia({ reducedMotion: "no-preference" }); + await page.goto("/maps"); + const chart = page.getByRole("img", { name: /Maps per tier/ }); + await expect(chart).toBeVisible(); + const geometry = await chart.evaluate((svg) => { + const rect = svg.getBoundingClientRect(); + const reset = svg.parentElement!.querySelector("nav > a")!.textContent!; + const total = Number(reset.match(/([\d,]+) maps/)![1]!.replaceAll(",", "")); + const links = Array.from(svg.querySelectorAll("a")); + const count = Number( + links[0]! + .getAttribute("aria-label")! + .match(/: ([\d,]+) maps/)![1]! + .replaceAll(",", ""), + ); + const angle = (((((count / total) * 100) / 2) * 3.6 - 90) * Math.PI) / 180; + const hit = (share: number, radius: number) => { + const angle = (share / 100) * Math.PI * 2 - Math.PI / 2; + return ( + document + .elementFromPoint( + rect.x + rect.width * (0.5 + (radius / 100) * Math.cos(angle)), + rect.y + rect.height * (0.5 + (radius / 100) * Math.sin(angle)), + ) + ?.closest("svg a") + ?.getAttribute("aria-label") ?? null + ); + }; + let start = 0; + const samples = links.map((link) => { + const label = link.getAttribute("aria-label")!; + const count = Number( + label.match(/: ([\d,]+) maps/)![1]!.replaceAll(",", ""), + ); + const length = (count / total) * 100; + const sample = { + label, + middle: [33, 40, 47].map((radius) => hit(start + length / 2, radius)), + seam: + length === 100 + ? [] + : [33, 40, 47].map((radius) => hit(start, radius)), + }; + start += length; + return sample; + }); + return { + samples, + x: rect.x + rect.width * (0.5 + 0.4 * Math.cos(angle)), + y: rect.y + rect.height * (0.5 + 0.4 * Math.sin(angle)), + }; + }); + for (const sample of geometry.samples) { + for (const middle of sample.middle) expect(middle).toBe(sample.label); + for (const seam of sample.seam) expect(seam).toBeNull(); + } + const highlight = chart.locator("a").first().locator("path").last(); + await expect(highlight).toHaveCSS("opacity", "0"); + await page.mouse.move(geometry.x, geometry.y); + const hovered = await chart + .locator("a") + .first() + .locator("path") + .last() + .evaluate(async (path) => { + await Promise.all( + path.getAnimations().map((animation) => animation.finished), + ); + const style = getComputedStyle(path); + return { + transition: style.transitionProperty, + duration: parseFloat(style.transitionDuration), + }; + }); + await expect(highlight).toHaveCSS("opacity", "1"); + expect(hovered.transition).toContain("opacity"); + expect(hovered.duration).toBeGreaterThan(0); + await page.mouse.click(geometry.x, geometry.y); + await expect(chart.locator("text").first()).not.toHaveText("All"); + expect( + await chart + .locator("a") + .first() + .evaluate((link) => getComputedStyle(link).outlineStyle), + ).toBe("none"); +}); + +test("a filtered short list is centered and its details stay beside the names", async ({ + page, + request, +}) => { + const response = await request.get("/v1/maps?limit=1"); + expect(response.ok()).toBe(true); + const { stats } = (await response.json()) as { stats: Schemas["MapStats"] }; + const tier = + stats.by_tier.findIndex((_, index) => { + const newest = stats.newest.filter( + (map) => map.tier === index + 1, + ).length; + const played = stats.played_this_week.filter( + (map) => map.tier === index + 1, + ).length; + return ( + (newest > 0 && newest < 5 && played === 0) || + (played > 0 && played < 5 && newest === 0) + ); + }) + 1; + test.skip( + tier === 0, + "The current API data has no tier with just one short summary list.", + ); + + await page.goto("/maps"); + const headingPositions = await page + .getByRole("region", { name: "Map overview", exact: true }) + .locator("section") + .evaluateAll((sections) => + Object.fromEntries( + sections.map((section) => [ + section.getAttribute("aria-label"), + section.querySelector("h2")!.getBoundingClientRect().top, + ]), + ), + ); + + await page.goto(`/maps?tier=${tier}`); + const overview = page.getByRole("region", { + name: "Map overview", + exact: true, + }); + await expect(overview.getByRole("navigation")).toBeVisible(); + await page.evaluate(() => document.fonts.ready); + await expectAligned(overview); + const filteredHeading = await overview + .locator("section:has(ul)") + .first() + .evaluate((section) => ({ + name: section.getAttribute("aria-label")!, + top: section.querySelector("h2")!.getBoundingClientRect().top, + })); + expect( + Math.abs(filteredHeading.top - headingPositions[filteredHeading.name]), + ).toBeLessThan(1); + const list = overview.locator("section:has(ul)").first().locator("ul"); + await expect(list).toHaveCount(1); + const layout = await list.evaluate((element) => + Array.from(element.querySelectorAll("a")).map((row) => { + const name = row.children[1]!.getBoundingClientRect(); + const detail = row.children[2]!.getBoundingClientRect(); + return { + width: row.getBoundingClientRect().width, + gap: detail.left - name.right, + top: Math.abs(detail.top - name.top), + }; + }), + ); + for (const row of layout) { + expect(row.width).toBeLessThan(250); + expect(Math.abs(row.gap - 8)).toBeLessThan(1); + expect(row.top).toBeLessThan(1); + } +}); + +test("the compact legend fits a narrow phone without changing its reset alignment", async ({ + page, +}) => { + await page.setViewportSize({ width: 320, height: 900 }); + await page.goto("/maps"); + const nav = page.getByRole("navigation", { name: "Filter maps by tier" }); + await expect(nav).toBeVisible(); + const edges = await nav.evaluate((element) => { + const reset = element.querySelector("a")!.getBoundingClientRect(); + const links = element.querySelectorAll("li a"); + return { + left: + reset.left - links[0]!.firstElementChild!.getBoundingClientRect().left, + right: + reset.right - + links[links.length - 1]!.lastElementChild!.getBoundingClientRect() + .right, + overflow: document.documentElement.scrollWidth > innerWidth, + }; + }); + expect(Math.abs(edges.left)).toBeLessThan(1); + expect(Math.abs(edges.right)).toBeLessThan(1); + expect(edges.overflow).toBe(false); +}); + +test("searching a WR holder shows their maps", async ({ page, request }) => { + const response = await request.get("/v1/maps?limit=100"); + expect(response.ok()).toBe(true); + const all = (await response.json()) as Schemas["MapList"]; + const holder = all.maps.find((map) => map.world_record)?.world_record?.player + .name; + test.skip( + !holder, + "The current data has no world record holders to search for.", + ); + const matches = await request.get( + `/v1/maps?q=${encodeURIComponent(holder!)}&sort=popular`, + ); + expect(matches.ok()).toBe(true); + const filtered = (await matches.json()) as Schemas["MapList"]; + expect(filtered.total).toBeGreaterThan(0); + + await page.goto("/maps"); + await page + .getByRole("searchbox", { + name: "Search maps, WR holders, or enter a SteamID", + exact: true, + }) + .fill(holder!); + await expect(page).toHaveURL((url) => url.searchParams.get("q") === holder); + const cards = page.locator("[data-map]"); + await expect(cards).toHaveCount(filtered.maps.length); + expect( + await cards.evaluateAll((elements) => + elements.map((element) => element.getAttribute("data-map")), + ), + ).toEqual(filtered.maps.map((map) => map.name)); +}); diff --git a/web/next.config.ts b/web/next.config.ts index bbe0a26..dfa36f5 100644 --- a/web/next.config.ts +++ b/web/next.config.ts @@ -3,6 +3,9 @@ import type { NextConfig } from "next"; const nextConfig: NextConfig = { // Self-contained server build for the VPS (ADR 0005). output: "standalone", + // Where players reach the site, for the whole addresses link previews need (`metadataBase` in the root + // layout). Fixed at build time, which `just deploy` does per environment from its SITE_ADDRESS. + env: { SJ_SITE_URL: process.env.SJ_SITE_URL ?? "http://localhost:3000" }, cacheComponents: true, partialPrefetching: true, images: { diff --git a/web/public/link-card.jpg b/web/public/link-card.jpg new file mode 100644 index 0000000..7d9ad3c Binary files /dev/null and b/web/public/link-card.jpg differ diff --git a/web/src/api/schema.ts b/web/src/api/schema.ts index 239e647..a6b0e3b 100644 --- a/web/src/api/schema.ts +++ b/web/src/api/schema.ts @@ -55,6 +55,27 @@ export interface paths { patch?: never; trace?: never; }; + "/v1/auth/sign-out-everywhere": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Ends every session of the signed-in player, in every browser, and signs this one out. A form on the + * website posts here. Unlike signing out, it needs a live session: answering a request without one as if it + * had worked would tell the player their other browsers were signed out when nothing was ended. + */ + post: operations["sign_out_everywhere"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/v1/auth/steam": { parameters: { query?: never; @@ -245,6 +266,26 @@ export interface paths { patch?: never; trace?: never; }; + "/v1/maps/{map}/personal-bests": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * These players' SourceJump personal bests on the map, every style and track. An unknown map, or players + * without runs on it, give an empty list. + */ + get: operations["players_personal_bests"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/v1/maps/{map}/records": { parameters: { query?: never; @@ -353,6 +394,26 @@ export interface paths { patch?: never; trace?: never; }; + "/v1/players/{player}/avatar": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Redirects to the player's Steam avatar. Takes a `SteamID64`, `SteamID2` or `SteamID3`. Only players + * SourceJump knows are looked up on Steam; a player known only from the old site gets the avatar it had. + */ + get: operations["player_avatar"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/v1/players/{player}/details": { parameters: { query?: never; @@ -1446,6 +1507,13 @@ export interface components { * @description Where the bucket starts. */ at: string; + /** + * Format: int32 + * @description The most players online at once during the bucket, across listed servers: each server's latest + * heartbeat count, summed at the same moment. Up to a month, sampled every 5 minutes; for a year, the + * day's highest total at any heartbeat. + */ + peak_players: number; /** * Format: int32 * @description The average player count of each of those servers during the bucket, summed. @@ -1537,7 +1605,10 @@ export interface components { /** @description New details for a profile. Every field is replaced: leave one out or null to clear it. */ DetailsInput: { aspect?: components["schemas"]["Aspect"] | null; - /** @description An ISO 3166-1 alpha-2 code to show instead of the Steam profile's country; null to show Steam's. */ + /** + * @description An ISO 3166-1 alpha-2 code to show instead of Steam's or a game server's, until a run's server finds one; + * null to stop showing the player's pick. + */ country_code?: string | null; /** * Format: int32 @@ -2147,7 +2218,7 @@ export interface components { /** @description Sorted by style, track and rank. One flat list keeps it simple to read in SourcePawn. */ records: components["schemas"]["Record"][]; }; - /** @description The whole list at a glance, whatever the search or filter. */ + /** @description Global totals and tier-scoped newest and weekly lists. */ MapStats: { /** * @description Of those, the maps whose main track has each tier, tier 1 first. Empty until a tier count is @@ -2163,6 +2234,11 @@ export interface components { newest: components["schemas"]["NewestMap"][]; /** @description The maps the most players finished a run on in the last 7 days, most first. */ played_this_week: components["schemas"]["PlayedMap"][]; + /** + * Format: int32 + * @description The tier the newest and weekly lists describe; None describes all tiers. Totals remain global. + */ + tier?: number | null; }; MapStyle: { /** @description The top of the leaderboard, so a map page can switch styles and tracks without asking again. */ @@ -2266,6 +2342,12 @@ export interface components { /** Format: int64 */ run_id: number; style: string; + /** + * Format: int32 + * @description The board's tier. None while tiers aren't in force or staff haven't set this board's, and for a legacy + * run. + */ + tier?: number | null; /** * Format: double * @description Seconds. @@ -2276,6 +2358,12 @@ export interface components { * @description 0 is the main track, 1 and up are bonuses. */ track: number; + /** + * Format: double + * @description The board's 2.0 record time, as on its map leaderboard, so a client can show the gap to it. None for a + * legacy run. + */ + world_record_time?: number | null; }; PersonalBestPage: { /** @description Pass as `cursor` for the personal bests after these. None at the end. */ @@ -2324,6 +2412,30 @@ export interface components { PlayerList: { players: components["schemas"]["PlayerSummary"][]; }; + PlayerPersonalBest: { + /** Format: date-time */ + finished_at: string; + /** + * Format: int64 + * @description Place on the leaderboard; equal times share a place, as in `…/records`. + */ + rank: number; + /** Format: int64 */ + run_id: number; + /** @description SteamID64, as a string. */ + steamid64: string; + style: string; + /** + * Format: double + * @description Seconds. + */ + time: number; + /** + * Format: int32 + * @description 0 is the main track, 1 and up are bonuses. + */ + track: number; + }; PlayerPrivileges: { /** @description What the player holds after the change. */ privileges: components["schemas"]["Privilege"][]; @@ -2335,9 +2447,12 @@ export interface components { */ all_styles: components["schemas"]["StyleTotals"]; avatar_url?: string | null; - /** @description Whether the player picked `country_code` themselves, rather than it coming from Steam. */ + /** @description Whether the player picked `country_code` themselves, rather than it coming from a game server or Steam. */ country_chosen: boolean; - /** @description ISO 3166-1 alpha-2: the one the player picked, or else their Steam profile's. None if neither has one. */ + /** + * @description ISO 3166-1 alpha-2: the latest one a game server found for them, the player's pick if they made it + * since, or else their Steam profile's. None if none has one. + */ country_code?: string | null; details?: components["schemas"]["PlayerDetails"] | null; /** @description Whether `details` are what they had on the old site, shown until they save their own. */ @@ -2368,6 +2483,12 @@ export interface components { steamid64: string; /** @description One entry per style they hold a personal best in, sorted by style key. Counts are 2.0 alone. */ styles: components["schemas"]["PlayerStyle"][]; + /** + * Format: int32 + * @description Number of tiers in force; None while the community hasn't set tiers, and personal bests then have no + * tier. + */ + tier_count?: number | null; }; /** * @description A player as leaderboards, records and runs show them: enough to draw their name, avatar and flag, and to @@ -2444,6 +2565,14 @@ export interface components { */ players: number; }; + PlayersPersonalBests: { + map: string; + /** + * @description Sorted by player, style and track. A player with no personal best on the map has no entries. One flat + * list keeps it simple to read in SourcePawn. + */ + personal_bests: components["schemas"]["PlayerPersonalBest"][]; + }; /** @description A published `sourcejump.smx` build. */ PluginRelease: { download_url: string; @@ -2657,6 +2786,11 @@ export interface components { * @description Number of tiers in force; None while the community hasn't set tiers, and runs then have no tier. */ tier_count?: number | null; + /** + * Format: int64 + * @description How many runs match the filters, across all pages. + */ + total: number; }; Record: { /** Format: date-time */ @@ -2992,6 +3126,14 @@ export interface components { world_record_time?: number | null; }; RunPlayer: { + /** + * @description The player's country, as the game server found it from their address with SourceMod's `GeoipCode2`: an ISO + * 3166-1 alpha-2 code. Leave it out when the lookup finds nothing; send only the code, never the address. It + * becomes the player's flag. A code SourceJump doesn't know as a country is ignored and the run is stored + * anyway. Runs only: detections ignore it. + * @example SE + */ + country_code?: string | null; name: string; /** @example 76561197960287930 */ steamid64: string; @@ -3110,6 +3252,13 @@ export interface components { ServerActivity: { /** Format: int32 */ bucket_minutes: number; + /** + * Format: int32 + * @description The most players online at once across listed servers over the whole range, from the start of its + * first point up to now, the bucket in progress included: no point reads higher, and a shorter range never + * reads higher than a longer one. + */ + peak_players: number; /** * @description Oldest first, one per bucket, empty buckets included. The bucket still in progress is left out, so the * last point isn't a partial count. @@ -3559,6 +3708,45 @@ export interface operations { }; }; }; + sign_out_everywhere: { + parameters: { + query?: { + /** @description The page to come back to: a path on this site, such as `/maps`. Anything else means `/`. */ + return_to?: string | null; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Back to the page the player came from, signed out everywhere */ + 303: { + headers: { + [name: string]: unknown; + }; + content?: never; + }; + /** @description Not signed in; no session was ended */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ErrorBody"]; + }; + }; + /** @description Not sent from SourceJump's own pages */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ErrorBody"]; + }; + }; + }; + }; start: { parameters: { query?: { @@ -3774,9 +3962,9 @@ export interface operations { parameters: { query?: { /** - * @description Part of a map name. Case doesn't matter, and spaces stand for underscores. The map of exactly that - * name comes first, then maps with a word starting with it, then other matches, each in the chosen - * sort; near misses for a typo come last, closest first. + * @description Part of a map name or a main-track world record holder's name in the chosen style. Case doesn't + * matter; spaces in map names stand for underscores. Exact map names come first, then word starts, + * other map matches and record holders, each in the chosen sort; near misses come last. */ q?: string | null; /** @description Default `name`. */ @@ -3918,6 +4106,49 @@ export interface operations { }; }; }; + players_personal_bests: { + parameters: { + query: { + /** @description Players by SteamID64, comma-separated: 1 to 64 of them. Repeats count once. */ + players: string; + }; + header?: never; + path: { + /** @description Map name */ + map: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["PlayersPersonalBests"]; + }; + }; + /** @description Missing, unknown or revoked API key */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ErrorBody"]; + }; + }; + /** @description Not a valid map name, or `players` isn't 1 to 64 SteamID64s */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ErrorBody"]; + }; + }; + }; + }; map_records: { parameters: { query?: { @@ -4144,6 +4375,56 @@ export interface operations { }; }; }; + player_avatar: { + parameters: { + query?: never; + header?: never; + path: { + /** @description SteamID64, SteamID2 (STEAM_0:1:2) or SteamID3 ([U:1:4]) */ + player: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description No avatar yet: a placeholder with the player's initials, cached five minutes */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "image/svg+xml": string; + }; + }; + /** @description To the avatar on Steam's CDN; cached a day */ + 302: { + headers: { + /** @description The avatar's URL */ + Location?: string; + [name: string]: unknown; + }; + content?: never; + }; + /** @description SourceJump has no such player */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ErrorBody"]; + }; + }; + /** @description Not a SteamID */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ErrorBody"]; + }; + }; + }; + }; update_player_details: { parameters: { query?: never; @@ -4688,6 +4969,8 @@ export interface operations { records?: boolean | null; /** @description 1 to 100. Default 50. */ limit?: number | null; + /** @description Runs to skip, for going straight to a page. Default 0. Counted after `cursor` when both are given. */ + offset?: number | null; /** @description Continue after this point: a `next_cursor` from an earlier page with the same filters. */ cursor?: string | null; }; @@ -4705,7 +4988,7 @@ export interface operations { "application/json": components["schemas"]["RecentRuns"]; }; }; - /** @description Not a valid tier, limit or cursor */ + /** @description Not a valid tier, limit, offset or cursor */ 422: { headers: { [name: string]: unknown; diff --git a/web/src/app/error.tsx b/web/src/app/error.tsx new file mode 100644 index 0000000..b33d5cd --- /dev/null +++ b/web/src/app/error.tsx @@ -0,0 +1,36 @@ +"use client"; +// The page for an unexpected failure while showing any page below the root layout, so the header and footer stay +// and the player can try again or move on, instead of a blank error screen. +import { useEffect } from "react"; +import { Button, ButtonLink } from "@/ui/Button"; +import { Page } from "@/ui/Page"; + +export default function ErrorPage({ + error, + retry, +}: { + error: unknown; + retry: () => void; +}) { + useEffect(() => { + // The server logs its own failures; this keeps the browser's in its console for whoever reports one. + console.error(error); + }, [error]); + + return ( + +
+

Something went wrong

+

+ This page couldn't be shown. Try again, or come back in a moment. +

+
+ + Go to the home page +
+
+
+ ); +} diff --git a/web/src/app/layout.tsx b/web/src/app/layout.tsx index 07418f3..afb0cf8 100644 --- a/web/src/app/layout.tsx +++ b/web/src/app/layout.tsx @@ -3,6 +3,7 @@ import type { Metadata } from "next"; import { Play } from "next/font/google"; import { Suspense } from "react"; import { RunDialogHost } from "@/features/runs/RunDialogHost"; +import { SITE_CARD } from "@/features/site/linkPreview"; import { SiteFooter } from "@/features/site/SiteFooter"; import { SiteHeader } from "@/features/site/SiteHeader"; import { NavigationProgress } from "@/ui/NavigationProgress"; @@ -15,9 +16,14 @@ const play = Play({ }); export const metadata: Metadata = { + // Link previews need whole addresses, such as the site card's; `SJ_SITE_URL` is set when building (next.config). + metadataBase: new URL(process.env.SJ_SITE_URL ?? "http://localhost:3000"), title: { default: "SourceJump", template: "%s · SourceJump" }, description: "Global records for the Counter-Strike: Source bunnyhop community.", + // Pages without a link preview of their own show the site's card, under their own title. + openGraph: { siteName: "SourceJump", type: "website", images: [SITE_CARD] }, + twitter: { card: "summary_large_image", images: [SITE_CARD] }, }; // Pages wait for their data and arrive whole; the progress bar covers the wait. diff --git a/web/src/app/maps/[map]/layout.tsx b/web/src/app/maps/[map]/layout.tsx index e5ba9bf..432becd 100644 --- a/web/src/app/maps/[map]/layout.tsx +++ b/web/src/app/maps/[map]/layout.tsx @@ -7,7 +7,7 @@ export default function MapLayout({ children, }: LayoutProps<"/maps/[map]">) { return ( - + {params.then(({ map }) => ( ))} diff --git a/web/src/app/maps/[map]/page.tsx b/web/src/app/maps/[map]/page.tsx index 91c6490..abed4d4 100644 --- a/web/src/app/maps/[map]/page.tsx +++ b/web/src/app/maps/[map]/page.tsx @@ -1,12 +1,19 @@ // A map's page: its description, leaderboards per style and track, and their WR history, under the map's header. import type { Metadata } from "next"; +import { getMap } from "@/features/maps/mapDetail"; +import { mapPreview } from "@/features/maps/mapPreview"; import { MapView } from "@/features/maps/MapView"; +import { currentStyles } from "@/features/ruleset/styles"; import { PageView } from "@/ui/Page"; export async function generateMetadata({ params, }: PageProps<"/maps/[map]">): Promise { - return { title: decodeURIComponent((await params).map) }; + const name = decodeURIComponent((await params).map); + // The same reads as the page's own (`getMap` is per request), so the preview costs no extra request. + const [result, styles] = await Promise.all([getMap(name), currentStyles()]); + const map = result?.data; + return map ? mapPreview(map, styles.keys, styles.name) : { title: name }; } export default function MapPage({ params }: PageProps<"/maps/[map]">) { diff --git a/web/src/app/maps/page.tsx b/web/src/app/maps/page.tsx index cde80b7..8f37dcc 100644 --- a/web/src/app/maps/page.tsx +++ b/web/src/app/maps/page.tsx @@ -1,4 +1,4 @@ -// Maps page: every map with a finished run, searchable, with its world record in a chosen style. +// Maps page: the difficulty overview, filters and maps with a finished run in the chosen style. import type { Metadata } from "next"; import { MapList } from "@/features/maps/MapList"; import { Page } from "@/ui/Page"; @@ -10,8 +10,7 @@ export const metadata: Metadata = { export default function MapsPage({ searchParams }: PageProps<"/maps">) { return ( - -

Maps

+ {searchParams.then((params) => ( ))} diff --git a/web/src/app/players/[steamid]/page.tsx b/web/src/app/players/[steamid]/page.tsx index f29f57d..f20e976 100644 --- a/web/src/app/players/[steamid]/page.tsx +++ b/web/src/app/players/[steamid]/page.tsx @@ -1,10 +1,19 @@ // A player's profile page, under their header. Any SteamID form works in the URL and lands on the SteamID64 // address. import type { Metadata } from "next"; +import { getPlayer } from "@/features/players/playerDetail"; +import { playerPreview } from "@/features/players/playerPreview"; import { PlayerProfile } from "@/features/players/PlayerProfile"; import { PageView } from "@/ui/Page"; -export const metadata: Metadata = { title: "Player" }; +export async function generateMetadata({ + params, +}: PageProps<"/players/[steamid]">): Promise { + // The same read as the header's (`getPlayer` is per request), so the preview costs no extra request. + const steamid = decodeURIComponent((await params).steamid); + const player = (await getPlayer(steamid))?.data; + return player ? playerPreview(player) : { title: "Player" }; +} export default function PlayerPage({ params, diff --git a/web/src/app/runs/[id]/page.tsx b/web/src/app/runs/[id]/page.tsx index 8dd2821..ee1237b 100644 --- a/web/src/app/runs/[id]/page.tsx +++ b/web/src/app/runs/[id]/page.tsx @@ -2,14 +2,19 @@ // staff act on the run here. // Following a run link within the site opens the run dialog instead. import type { Metadata } from "next"; +import { currentStyles } from "@/features/ruleset/styles"; import { getRun, RunDetails } from "@/features/runs/RunDetails"; +import { runPreview } from "@/features/runs/runPreview"; import { Page } from "@/ui/Page"; export async function generateMetadata({ params, }: PageProps<"/runs/[id]">): Promise { - const run = await getRun((await params).id); - return { title: run ? `${run.player.name} on ${run.map}` : "Run" }; + const [run, styles] = await Promise.all([ + getRun((await params).id), + currentStyles(), + ]); + return run ? runPreview(run, styles.name) : { title: "Run" }; } export default function RunPage({ params }: PageProps<"/runs/[id]">) { diff --git a/web/src/features/dailyTotals/DailyTotals.tsx b/web/src/features/dailyTotals/DailyTotals.tsx index 06d2281..1d25da9 100644 --- a/web/src/features/dailyTotals/DailyTotals.tsx +++ b/web/src/features/dailyTotals/DailyTotals.tsx @@ -1,5 +1,6 @@ // Loads every range of one of the site's daily totals for its chart: players for the Players page, runs and // world records for the Activity page. Nothing shows if they can't be loaded; the page works without it. +import { connection } from "next/server"; import { api } from "@/api/client"; import { DailyTotalsChart, @@ -10,6 +11,8 @@ import { const ranges = ["month", "year", "all"] as const satisfies TotalsRange[]; export async function DailyTotals({ kind }: { kind: DailyTotalsData["kind"] }) { + // At request time, as `LiveNow`: the API isn't reachable while the site is built. + await connection(); // Both endpoints take the same range and return their own totals type, so one fetch serves either kind. const data: DailyTotalsData = { kind, diff --git a/web/src/features/home/LiveNow.tsx b/web/src/features/home/LiveNow.tsx index 0244998..a477a00 100644 --- a/web/src/features/home/LiveNow.tsx +++ b/web/src/features/home/LiveNow.tsx @@ -1,5 +1,6 @@ // The home page's live part: the newest world records beside the busiest servers online right now. import { ArrowRight } from "lucide-react"; +import { connection } from "next/server"; import type { CSSProperties } from "react"; import { api, type Schemas } from "@/api/client"; import { currentStyles } from "@/features/ruleset/styles"; @@ -16,6 +17,9 @@ const RECORDS = 6; const SERVERS = 4; export async function LiveNow() { + // Read at request time, never while the site is built: the API isn't reachable then, and a build-time read + // would be kept in the static shell. + await connection(); const [records, servers, styles] = await Promise.all([ api .GET("/v1/runs", { params: { query: { records: true, limit: RECORDS } } }) diff --git a/web/src/features/maps/Leaderboard.tsx b/web/src/features/maps/Leaderboard.tsx index aea520d..ddbf0f7 100644 --- a/web/src/features/maps/Leaderboard.tsx +++ b/web/src/features/maps/Leaderboard.tsx @@ -1,19 +1,29 @@ "use client"; // A map's leaderboard for one style, track and view: the 2.0 top comes with the page, other views load their -// first page when chosen, and "Show more" loads the rest a page at a time. The signed-in player's row stands -// out, and legacy runs carry the Pre-2.0 badge. +// first page when chosen, and "Show more" loads the rest a page at a time. Headings sort it: the API orders +// boards by time only, so sorting by anything else loads the whole board and sorts it here. The signed-in +// player's row stands out; on the 2.0 board, when it isn't among the rows shown, it's pinned below them. Legacy +// runs carry the Pre-2.0 badge. import { useEffect, useState } from "react"; import { api, type Schemas } from "@/api/client"; import { LegacyBadge } from "@/features/legacy/LegacyBadge"; import type { View } from "@/features/legacy/views"; +import { ReplayLink } from "@/features/replays/ReplayLink"; import { RunLink } from "@/features/runs/RunLink"; -import { formatDate, formatGap, formatTime } from "@/features/runs/time"; +import { + formatAge, + formatDate, + formatGap, + formatTime, +} from "@/features/runs/time"; import { Avatar } from "@/ui/Avatar"; import { Badge } from "@/ui/Badge"; import { Button } from "@/ui/Button"; +import { classNames } from "@/ui/classNames"; import { Flag } from "@/ui/Flag"; import { Link } from "@/ui/Link"; import { Medal } from "@/ui/Medal"; +import { SortButton } from "@/ui/SortButton"; import { Table, TableBody, @@ -22,10 +32,63 @@ import { TableHeaderCell, TableRow, } from "@/ui/Table"; +import { avatarSrc } from "@/features/players/avatarSrc"; const PAGE_SIZE = 50; +/** The API's largest page, for loading a whole board to sort. */ +const FULL_PAGE_SIZE = 100; const sync = new Intl.NumberFormat("en", { maximumFractionDigits: 1 }); +type Entry = Schemas["LeaderboardEntry"]; +type SortKey = "time" | "player" | "jumps" | "strafes" | "sync" | "date"; +interface Sort { + key: SortKey; + descending: boolean; +} + +/** Which way a column sorts on its first click: best sync and newest date first, the rest from the smallest. */ +const descendingFirst: Record = { + time: false, + player: false, + jumps: false, + strafes: false, + sync: true, + date: true, +}; + +/** Entries in the chosen order; ties keep the board's order by time. */ +function sorted(entries: Entry[], sort: Sort): Entry[] { + if (sort.key === "time" && !sort.descending) return entries; + const value = (entry: Entry): number | string => { + switch (sort.key) { + case "time": + return entry.time; + case "player": + return entry.player.name.toLowerCase(); + case "jumps": + return entry.jumps; + case "strafes": + return entry.strafes; + case "sync": + return entry.sync; + case "date": + // Runs without a date sort as the oldest. + return entry.finished_at ? Date.parse(entry.finished_at) : 0; + } + }; + const direction = sort.descending ? -1 : 1; + return entries + .map((entry, index) => ({ entry, index, value: value(entry) })) + .sort((a, b) => + a.value < b.value + ? -direction + : a.value > b.value + ? direction + : a.index - b.index, + ) + .map(({ entry }) => entry); +} + /** A page of a board, as the leaderboard endpoint or (for 2.0's top) the map's details give it. */ export type BoardPage = Pick< Schemas["Leaderboard"], @@ -55,6 +118,9 @@ export function Leaderboard({ const [cursor, setCursor] = useState(first?.next_cursor); const [loading, setLoading] = useState(false); const [failed, setFailed] = useState(false); + const [sort, setSort] = useState({ key: "time", descending: false }); + // The signed-in player's own entry, wherever on the board it is. Only the 2.0 board ranks them. + const [mine, setMine] = useState(); // A refreshed page (after a staff change, say) brings a new first page; start again from it. const [shownFrom, setShownFrom] = useState(first); if (first && shownFrom !== first) { @@ -64,12 +130,12 @@ export function Leaderboard({ setCursor(first.next_cursor); } - function fetchPage(after: string | undefined) { + function fetchPage(after: string | undefined, limit = PAGE_SIZE) { return api .GET("/v1/maps/{map}/leaderboard", { params: { path: { map }, - query: { style, track, view, limit: PAGE_SIZE, cursor: after }, + query: { style, track, view, limit, cursor: after }, }, }) .then((result) => result.data) @@ -96,6 +162,39 @@ export function Leaderboard({ show(loaded, after); } + /** + * Sorts by a column: again on the same one turns it around. Any order but time's needs the whole board. + * shortcut: loads every row in the browser, 100 a request; fine for boards of a few hundred players, ask the API + * for a `sort` parameter when boards grow to thousands. + */ + async function sortBy(key: SortKey) { + const next: Sort = + sort.key === key + ? { key, descending: !sort.descending } + : { key, descending: descendingFirst[key] }; + if (key !== "time" && cursor) { + setLoading(true); + setFailed(false); + let all = entries; + let after: string | null | undefined = cursor; + while (after) { + const loaded = await fetchPage(after, FULL_PAGE_SIZE); + if (!loaded) { + setLoading(false); + setFailed(true); + return; + } + all = [...all, ...loaded.entries]; + after = loaded.next_cursor; + setPage(loaded); + } + setEntries(all); + setCursor(undefined); + setLoading(false); + } + setSort(next); + } + // Views other than 2.0's don't come with the map; their first page loads once the view is chosen. useEffect(() => { if (!first) @@ -103,6 +202,23 @@ export function Leaderboard({ // eslint-disable-next-line react-hooks/exhaustive-deps -- the key remounts this for another board }, []); + // The top that comes with the map doesn't carry the player's own place; one row is asked for here, unless + // they're already in that top. + useEffect(() => { + if (!me || view !== "current") return; + if (first?.entries.some((entry) => entry.player.steamid64 === me)) return; + void api + .GET("/v1/maps/{map}/leaderboard", { + params: { + path: { map }, + query: { style, track, limit: 1, player: me }, + }, + }) + .then((result) => setMine(result.data?.player_entry ?? undefined)) + .catch(() => undefined); + // eslint-disable-next-line react-hooks/exhaustive-deps -- the key remounts this for another board + }, []); + if (!page) { return failed ? (

@@ -112,86 +228,124 @@ export function Leaderboard({ } const fastest = page.fastest_time; const record = page.world_record_time; + // Once "Show more" (or sorting, which loads the whole board) reaches them, their row is in the list and isn't + // pinned twice. + const pinned = + mine && + !entries.some((entry) => entry.run_id === mine.run_id && !entry.legacy) + ? mine + : undefined; + const heading = (key: SortKey, label: string) => ( + void sortBy(key)} + /> + ); + const ariaSort = (key: SortKey) => + sort.key === key + ? sort.descending + ? ("descending" as const) + : ("ascending" as const) + : undefined; return (

- +
- Place - Player - Time - Gap - Jumps - Strafes - Sync - Date + {/* Short columns center under their names: a medal, a WR badge and a few digits are all narrower than + the heading, and right-aligned they sat off to one side of it. Times and dates keep to the right. + Place and Gap follow the time, so Time sorts for them. */} + {/* "#" on a phone, as on Activity: the word would widen the column well past its medals. */} + + Place + + # + + Place + + + {heading("player", "Player")} + + + {heading("time", "Time")} + + {/* Narrow padding keeps the play button close to the time, as on Activity. */} + + Replay + + {/* On a phone the gap and age go under the time instead, and these columns step aside. */} + + Gap + + + {heading("jumps", "Jumps")} + + + {heading("strafes", "Strafes")} + + + {heading("sync", "Sync")} + + + {heading("date", "Date")} + - {entries.map((entry) => ( - ( + - - {/* Medals mark 2.0 standings; the other views are lists by time. */} - - - - - - - {entry.player.name} - - - {entry.legacy && } - - - - - {formatTime(entry.time)} - - - - {!entry.legacy && entry.time === record ? ( - WR - ) : entry.time === fastest || fastest == null ? null : ( - formatGap(entry.time - fastest) - )} - - - {entry.jumps} - - - {entry.strafes} - - - {sync.format(entry.sync)}% - - - {entry.finished_at ? ( - - ) : ( - "–" - )} - - + entry={entry} + view={view} + mine={entry.player.steamid64 === me} + record={record} + fastest={fastest} + /> ))} + {pinned && ( + // Its own body, so the line above it reads as a gap in the list rather than the next place. + + + + )}
@@ -201,7 +355,7 @@ export function Leaderboard({ {failed && ( - More couldn't be loaded. Try again. + The rest of the board couldn't be loaded. Try again. )} {cursor && ( @@ -217,3 +371,127 @@ export function Leaderboard({
); } + +/** One player's row: place, player, time (with the gap and age under it on a phone), replay, gap, stats and date. */ +function EntryRow({ + entry, + view, + mine, + record, + fastest, + separated = false, +}: { + entry: Entry; + view: View; + /** The signed-in player's own row, which stands out. */ + mine: boolean; + record: number | null | undefined; + fastest: number | null | undefined; + /** Set apart from the rows above it. */ + separated?: boolean; +}) { + return ( + + + {/* Medals mark 2.0 standings; the other views are lists by time. */} + + + + + {/* On a phone the player column takes only the room left (`max-w-0` with full width), and a long + name ends in an ellipsis rather than pushing the times off the screen. */} + + + + {/* Left out on a phone, as on Activity's rows there: the name needs the room more. */} + + {entry.player.name} + + {/* A missing country's placeholder costs a phone's narrow column more than it tells. */} + + {entry.legacy && } + + + + + + + {formatTime(entry.time)} + + {/* On a phone, the Gap column's record mark beside the time; a gap goes on the line below. */} + {!entry.legacy && entry.time === record && ( + + WR + + )} + + {/* Under the time on a phone: the gap and how long ago. Beside the time, the longest gap would + widen the whole column and leave the names a few letters. */} + + {!(!entry.legacy && entry.time === record) && + entry.time !== fastest && + fastest != null && ( + + ({formatGap(entry.time - fastest)}) + + )} + {entry.finished_at && ( + // Counted from now, which differs between the server's render and the browser's. + + )} + + + + + {/* Replays open by 2.0 run ID; a pre-2.0 run's ID is the old site's. */} + {!entry.legacy && } + + + {!entry.legacy && entry.time === record ? ( + WR + ) : entry.time === fastest || fastest == null ? null : ( + {formatGap(entry.time - fastest)} + )} + + + {entry.jumps} + + + {entry.strafes} + + + {sync.format(entry.sync)}% + + + {entry.finished_at ? ( + + ) : ( + "–" + )} + + + ); +} diff --git a/web/src/features/maps/MapBanner.tsx b/web/src/features/maps/MapBanner.tsx index 9f7734f..b147fe1 100644 --- a/web/src/features/maps/MapBanner.tsx +++ b/web/src/features/maps/MapBanner.tsx @@ -1,6 +1,9 @@ "use client"; // A map's banner: its cover, cropped to the strip staff chose. Clicking it shows all the map's pictures whole, -// in a Lightbox. Staff controls for the Manage view come in as `children`, laid over it. +// in a Lightbox. The map's title comes in as `title` and its view tabs as `tabs`. On wide screens (lg up) both are +// laid over the picture's lower edge, so the board below starts sooner. Narrower, a long name and the tabs don't fit +// over it, so the title sits under it on the page and only the tabs stay on the picture. Staff controls for the +// Manage view come in as `children`, laid over the picture too. import { Images } from "lucide-react"; import { type ReactNode, useState } from "react"; import type { Schemas } from "@/api/client"; @@ -10,9 +13,15 @@ import { MapImage } from "./MapImage"; export function MapBanner({ map, images, + title, + tabs, children, }: { map: string; + /** The page's heading, over the picture's bottom left. Clicks pass through it to the picture, bar its links. */ + title?: ReactNode; + /** The map's view tabs, beside the title, or on the picture on a phone. */ + tabs?: ReactNode; /** In order; the first is the cover. */ images: Schemas["MapImage"][]; children?: ReactNode; @@ -22,27 +31,41 @@ export function MapBanner({ return (
- {cover ? ( - - ) : ( - - )} - {images.length > 1 && ( - - - {images.length} - +
+ {cover ? ( + + ) : ( + + )} + {images.length > 1 && ( + + + {images.length} + + )} + {tabs && ( +
{tabs}
+ )} +
+ {title && ( + // On wide screens, laid straight over the picture, readable by its own shadow rather than a plate or a scrim. +
+
+
{title}
+ {tabs &&
{tabs}
} +
+
)} {children} document.getElementById("map-banner-figures"), + () => null, + ); const hasLegacy = map.legacy_players > 0; if (map.tracks.length === 0 && !hasLegacy) { return ( @@ -86,102 +94,177 @@ export function MapBoards({ window.history.replaceState(null, "", url); } + const history = + // The Pre-2.0 view shows the old site's records instead; the two histories are never mixed. + view === "legacy" ? ( + + ) : ( + board && ( + + ) + ); + + // The board comes first, so it starts within the first screen; the record and totals sit on the choices' line, + // and the history follows the board. + // The choices sit close to the board they pick; the history, a separate thing, stands a step further off. return ( <> -
- {board ? ( - +
+
+ + ({ + value: key, + label: name(key), + quiet: !hasRuns(key), + }))} + value={styleKey} + onChange={(style) => choose({ style })} + /> + ({ + value: String(t), + label: trackName(t), + quiet: !map.tracks.some((known) => known.track === t), + }))} + value={String(trackNumber)} + onChange={(value) => choose({ track: Number(value) })} + /> + choose({ view: next })} + /> + {track && + track.track > 0 && + track.tier != null && + map.tier_count != null && ( + + )} + + + {bannerSlot && + createPortal( + , + bannerSlot, + )} +
+ + {view === "current" && !board ? ( + + Nobody has a {name(styleKey)} run on{" "} + {trackNumber === 0 ? "the main track" : trackName(trackNumber)} yet. + {onLegacyBoard && " Its pre-2.0 runs are under Runs."} + ) : ( - )} - -
- - ({ - value: key, - label: name(key), - quiet: !hasRuns(key), - }))} - value={styleKey} - onChange={(style) => choose({ style })} - /> - ({ - value: String(t), - label: trackName(t), - quiet: !map.tracks.some((known) => known.track === t), - }))} - value={String(trackNumber)} - onChange={(value) => choose({ track: Number(value) })} - /> - choose({ view: next })} - /> - {track && - track.track > 0 && - track.tier != null && - map.tier_count != null && ( - - )} - + {history &&
{history}
} + + ); +} - {/* The Pre-2.0 view shows the old site's records instead; the two histories are never mixed. */} - {view === "legacy" ? ( - - ) : ( - board && ( - - ) - )} +const number = new Intl.NumberFormat("en"); - {view === "current" && !board ? ( - - Nobody has a {name(styleKey)} run on{" "} - {trackNumber === 0 ? "the main track" : trackName(trackNumber)} yet. - {onLegacyBoard && " Its pre-2.0 runs are under Runs."} - - ) : ( - +/** The banner slot never changes once the page is drawn, so there's nothing to subscribe to. */ +function noChanges() { + return () => {}; +} + +/** The chosen board's world record, players and runs: on the choices' line, or (compact) on the banner. */ +function Figures({ + board, + totals, + compact = false, + className, +}: { + board: Schemas["MapStyle"] | undefined; + totals: { players: number; runs: number }; + compact?: boolean; + className?: string; +}) { + const figure = compact ? "font-bold" : "text-lg font-bold"; + return ( +
+ > +
+
World record
+
+ {board ? ( + + {formatTime(board.world_record.time)} + + ) : ( + – + )} +
+
+ + +
+ ); +} + +/** A count on the choices' line, the number first: "69 players". */ +function Total({ + label, + value, + figure, +}: { + label: string; + value: number; + figure: string; +}) { + return ( +
+
{label}
+
+ {number.format(value)} +
+
); } @@ -229,19 +312,3 @@ function HistoryCard({ ); } - -function WorldRecordCard({ record }: { record: Schemas["WorldRecord"] }) { - return ( - - {/* Laid out like StatCard, so the three cards' labels and numbers line up. */} -
- -
-

- - {formatTime(record.time)} - -

-
- ); -} diff --git a/web/src/features/maps/MapCard.module.css b/web/src/features/maps/MapCard.module.css new file mode 100644 index 0000000..803e6f2 --- /dev/null +++ b/web/src/features/maps/MapCard.module.css @@ -0,0 +1,104 @@ +/* Shared podium columns switch with the card's width, not the viewport's. */ +.cards { + grid-template-columns: minmax(0, 1fr); +} + +.cover { + aspect-ratio: 5 / 2; + min-block-size: calc(var(--spacing) * 32); +} + +.preview { + transition: filter var(--duration-fast); +} + +@media (prefers-reduced-motion: reduce) { + .preview { + transition: none; + } +} + +.podium { + align-content: start; + grid-template-columns: auto auto minmax(0, 1fr); +} + +.entry { + min-block-size: calc(var(--spacing) * 12); + grid-column: 1 / -1; + grid-template-columns: subgrid; +} + +.rank { + grid-column: 1; + grid-row: 1; +} + +.playerLink { + grid-column: 2 / -1; + grid-row: 1; + grid-template-columns: subgrid; +} + +.avatar { + grid-column: 1; + grid-row: 1; + align-self: center; +} + +.player { + grid-column: 2; + grid-row: 1; +} + +.result { + grid-column: 3; + grid-row: 2; +} + +/* Wide cards share aligned time and gap columns; narrow cards put both below the name. */ +@container (min-width: 20rem) { + .podium { + grid-template-columns: + auto auto minmax(0, 1fr) + max-content max-content; + } + + .entry { + min-block-size: calc(var(--spacing) * 8); + } + + .playerLink, + .result { + align-self: center; + } + + .playerLink { + grid-column: 2 / span 2; + } + + .result { + display: grid; + grid-column: 4 / span 2; + grid-row: 1; + grid-template-columns: subgrid; + } +} + +@container (min-width: 42rem) { + .cards { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } +} + +@container (min-width: 64rem) { + .cards { + grid-template-columns: repeat(3, minmax(0, 1fr)); + } +} + +@container (min-width: 88rem) { + .cards { + grid-template-columns: repeat(4, minmax(0, 1fr)); + } +} diff --git a/web/src/features/maps/MapCard.tsx b/web/src/features/maps/MapCard.tsx new file mode 100644 index 0000000..d6365b5 --- /dev/null +++ b/web/src/features/maps/MapCard.tsx @@ -0,0 +1,208 @@ +// Map details overlay the preview; records and the signed-in player's PB sit plainly below it. +import type { Schemas } from "@/api/client"; +import { avatarSrc } from "@/features/players/avatarSrc"; +import { ReplayLink } from "@/features/replays/ReplayLink"; +import { RunLink } from "@/features/runs/RunLink"; +import { formatGap, formatTime } from "@/features/runs/time"; +import { Avatar } from "@/ui/Avatar"; +import { Badge } from "@/ui/Badge"; +import { classNames } from "@/ui/classNames"; +import { Link } from "@/ui/Link"; +import { Medal } from "@/ui/Medal"; +import { TierBadge } from "@/ui/TierBadge"; +import { MapImage } from "./MapImage"; +import type { MapLeader } from "./mapPodiums"; +import styles from "./MapCard.module.css"; + +const number = new Intl.NumberFormat("en"); + +export function MapCard({ + map, + tierCount, + leaders, + styleName, + styleKey, + showPersonalBest = false, + personalBest, +}: { + map: Schemas["MapSummary"]; + tierCount: number | null | undefined; + leaders: readonly MapLeader[] | null; + styleName: string; + styleKey?: string; + showPersonalBest?: boolean; + personalBest?: MapLeader | null; +}) { + const entries = + leaders ?? (map.world_record ? [{ ...map.world_record, rank: 1 }] : []); + const record = entries[0]; + const fastest = record?.time ?? 0; + + return ( +
+
+ +
+
+ {map.tier != null && tierCount != null && ( + + + + )} +

+ + {map.name} + +

+
+

+ + {number.format(map.players)}{" "} + {map.players === 1 ? "player" : "players"} + + {map.bonuses > 0 && ( + + {number.format(map.bonuses)}{" "} + {map.bonuses === 1 ? "bonus" : "bonuses"} + + )} +

+
+
+
+
    + {entries.map((entry) => ( +
  1. + + + + + + + + + {entry.player.name} + + + + + + {formatTime(entry.time)} + + + + {entry.run_id === record?.run_id ? ( + + WR + + ) : ( + + {formatGap(entry.time - fastest)} + + )} + +
  2. + ))} + {entries.length === 0 && ( +
  3. + {leaders === null + ? "Times couldn't be loaded" + : "No times in this style"} +
  4. + )} +
+ {showPersonalBest && ( +
+ Your PB + {personalBest ? ( + <> + + #{number.format(personalBest.rank)} + + + + {formatTime(personalBest.time)} + + {personalBest.time > fastest && fastest > 0 ? ( + + ({formatGap(personalBest.time - fastest)}) + + ) : fastest > 0 ? ( + + {personalBest.run_id === record?.run_id ? "WR" : "WR tie"} + + ) : null} + + + ) : ( + + {personalBest === null ? "Not completed" : "Couldn't load PB"} + + )} +
+ )} +
+
+ ); +} diff --git a/web/src/features/maps/MapHeader.tsx b/web/src/features/maps/MapHeader.tsx index 4082e73..adfa957 100644 --- a/web/src/features/maps/MapHeader.tsx +++ b/web/src/features/maps/MapHeader.tsx @@ -1,4 +1,4 @@ -// The top of a map's pages: its banner, name and main tier, when it was released and who made it, and the +// The top of a map's pages: its banner with, laid over it, the name and main tier, when it was released and who made it, and the // Map / Zones switch (with Manage for staff). It sits in the map's layout, so switching between the views leaves it in place. import { notFound } from "next/navigation"; import type { Schemas } from "@/api/client"; @@ -34,36 +34,55 @@ export async function MapHeader({ name }: { name: string }) { (map !== undefined || staffMap?.known === true); return ( - <> - - {canEdit && cover && } - -
-
-

{map?.name ?? name}

- {mainTier != null && tierCount != null && ( - - )} - {/* A map without a finished run has no page to switch to. */} - {map && ( - - )} -
-

-

-

-
- + +
+ {/* Inline, so a long name wraps with the badge after it, and `align-middle` centers the badge on the + name's lowercase letters, where the eye reads its middle, rather than on the line box. */} +
+

{map?.name ?? name}

+ {mainTier != null && tierCount != null && ( + + {/* Over the picture (lg up), a dark fill of its own, as the tabs and picture count have, so its + outline and label read on any picture; on the page below lg it needs none. */} + + + )} +
+

+

+

+ {/* Below lg, where the title sits under the picture, the map's boards put the chosen board's record, players and runs here (MapBoards), so + its leaderboard starts higher up the screen. */} +
+
+ + } + tabs={ + // A map without a finished run has no page to switch to. + map && ( + + ) + } + > + {canEdit && cover && } + ); } diff --git a/web/src/features/maps/MapImage.tsx b/web/src/features/maps/MapImage.tsx index 19f234d..71719cd 100644 --- a/web/src/features/maps/MapImage.tsx +++ b/web/src/features/maps/MapImage.tsx @@ -8,7 +8,8 @@ import { classNames } from "@/ui/classNames"; const sizes = { thumbnail: "h-10 w-14 rounded-md sm:h-12 sm:w-20", tile: "h-14 w-24 rounded-md sm:h-20 sm:w-36", - banner: "h-36 w-full rounded-lg sm:h-48", + card: "aspect-video w-full rounded-none border-0", + banner: "h-36 w-full rounded-md lg:h-44", }; export function MapImage({ diff --git a/web/src/features/maps/MapList.tsx b/web/src/features/maps/MapList.tsx index 73a8f62..d1102a7 100644 --- a/web/src/features/maps/MapList.tsx +++ b/web/src/features/maps/MapList.tsx @@ -1,21 +1,20 @@ // The Maps page's totals (maps, tiered maps, maps per tier), its search, sort, style and completion choices, -// and one row per map with its picture, tier and world record. Staff who manage maps also get a "No runs yet" tab +// and one card per map with its picture, tier and top three. Staff who manage maps also get a "No runs yet" tab // and a "Map files" tab for uploading viewer files in bulk, and can set up a map by name before its first run. -import { Search, X } from "lucide-react"; -import Form from "next/form"; +import { X } from "lucide-react"; import type { CSSProperties } from "react"; import { api, type Schemas } from "@/api/client"; import { signedInPlayer } from "@/features/auth/signedInPlayer"; import { currentStyles } from "@/features/ruleset/styles"; import { STEAMID } from "@/features/players/steamId"; -import { formatSince, formatTime } from "@/features/runs/time"; +import { formatSince } from "@/features/runs/time"; import { BulkUpload } from "@/features/staff/maps/BulkUpload"; import { UnplayedMaps } from "@/features/staff/maps/UnplayedMaps"; import { Avatar } from "@/ui/Avatar"; -import { Button, ButtonLink } from "@/ui/Button"; +import { ButtonLink } from "@/ui/Button"; import { Card } from "@/ui/Card"; -import { Flag } from "@/ui/Flag"; -import { Input } from "@/ui/Input"; +import { classNames } from "@/ui/classNames"; +import { SearchField } from "@/ui/SearchField"; import { Link } from "@/ui/Link"; import { ChoiceBar } from "@/ui/ChoiceBar"; import { ChoiceMenu } from "@/ui/ChoiceMenu"; @@ -24,9 +23,13 @@ import { Pager } from "@/ui/Pager"; import { TierBadge } from "@/ui/TierBadge"; import { TierSpread } from "@/ui/TierSpread"; import { managesMaps } from "./MapHeader"; -import { MapImage } from "./MapImage"; +import { MapCard } from "./MapCard"; +import { mapPodiums } from "./mapPodiums"; +import cardStyles from "./MapCard.module.css"; +import overviewStyles from "./MapOverview.module.css"; import { MAP_NAME } from "./mapName"; import { tierParam } from "./tierParam"; +import { avatarSrc } from "@/features/players/avatarSrc"; const PAGE_SIZE = 50; /** In groups (players, name, tier, record), each starting below a line in the menu. */ @@ -116,6 +119,7 @@ export async function MapList({ params }: { params: MapListParams }) { if (files) { return (
+

Maps

{staffTabs}
@@ -150,6 +154,7 @@ export async function MapList({ params }: { params: MapListParams }) { .catch(() => undefined); const list = result?.data; const style = list?.style ?? requestedStyle; + const podiums = await mapPodiums(list?.maps ?? [], style, me?.steamid64); const typedName = q.toLowerCase(); const offerSetUp = staff && @@ -203,91 +208,78 @@ export async function MapList({ params }: { params: MapListParams }) { }; return ( -
+
+

Maps

{list && ( - href({ tier: choice })} - newestHref={href({ sort: "newest", tier: null, page: 1 })} - /> + + href({ tier: choice })} + newestHref={href({ sort: "newest", page: 1 })} + /> + )} -
- {/* Searching keeps the chosen tab, sort, style and completion filter. */} - {unplayed && } - {completion !== "all" && filterPlayer && ( - <> - - - - )} - {sort !== DEFAULT_SORT && ( - - )} - {requestedStyle && ( - - )} - {tier != null && } - - -
- - {!unplayed && ( - <> - ({ - value: s.key, - label: s.label, - startsGroup: "startsGroup" in s, - href: href({ sort: s.key }), - }))} - value={sort} - /> - {styles.keys.length > 1 && ( +
+ + {!unplayed && ( + <> ({ - value: key, - label: styles.name(key), - href: href({ style: key }), + label="Sort" + options={sorts.map((s) => ({ + value: s.key, + label: s.label, + startsGroup: "startsGroup" in s, + href: href({ sort: s.key }), }))} - value={style ?? styles.keys[0] ?? ""} + value={sort} /> - )} - ({ - value: c.key, - label: c.label, - detail: completionDetail[c.key], - href: href({ completion: c.key }), - disabled: c.key !== "all" && !filterPlayer, - }))} - value={completion} - /> - {completion !== "all" && player && ( - 1 && ( + ({ + value: key, + label: styles.name(key), + href: href({ style: key }), + }))} + value={style ?? styles.keys[0] ?? ""} + /> + )} + ({ + value: c.key, + label: c.label, + detail: completionDetail[c.key], + href: href({ completion: c.key }), + disabled: c.key !== "all" && !filterPlayer, + }))} + value={completion} /> - )} - - )} - {/* Staff only, out of the way of the menus everyone uses. */} - {staff &&
{staffTabs}
} -
+ {completion !== "all" && player && ( + + )} + + )} + {/* Staff only, out of the way of the menus everyone uses. */} + {staff &&
{staffTabs}
} + + +
{/* With no results, the empty card below offers this instead. */} {offerSetUp && list && list.maps.length > 0 && ( @@ -314,7 +306,7 @@ export async function MapList({ params }: { params: MapListParams }) { : completion === "no" ? "This player has completed every map here." : q - ? "No map with a run has that name." + ? "No maps match that name or WR holder." : tier != null ? `No map with a run has tier ${tier}.` : "No map has a finished run yet."} @@ -326,30 +318,59 @@ export async function MapList({ params }: { params: MapListParams }) { )} ) : ( - <> - {/* Keyed by what's shown, so a new sort or style remounts every row and they all enter together; - keyed by map alone, rows that stay on the page would swap in place without moving. */} -
    +
    +
    +

    + {q + ? `Maps matching “${q}”` + : tier != null + ? `Tier ${tier} maps` + : "All maps"} +

    +

    + {number.format(list.total)} maps in this view +

    +
    +
      {list.maps.map((map, index) => (
    • - +
    • ))}
    - href({ page: p })} - /> - + {list.total > PAGE_SIZE && ( +
    + href({ page: p })} + /> +
    + )} +
    )}
); @@ -376,92 +397,129 @@ function MapStats({ newestHref: string; }) { const tiered = stats.by_tier.reduce((sum, count) => sum + count, 0); - const hasTiers = stats.by_tier.length > 0; - if ( - !hasTiers && - stats.newest.length === 0 && - stats.played_this_week.length === 0 - ) + const hasTiers = stats.by_tier.length > 0 && stats.maps > 0; + const newest = stats.newest.filter( + (map) => selected == null || map.tier === selected, + ); + const playedThisWeek = stats.played_this_week.filter( + (map) => selected == null || map.tier === selected, + ); + if (!hasTiers && newest.length === 0 && playedThisWeek.length === 0) return null; - // The chart keeps the width it needs; the lists share what is left equally, each with a full-height divider. + const weeklyScoped = + selected == null || + stats.tier === selected || + stats.played_this_week.length < 5 || + playedThisWeek.length === 5; + const hasWeekly = stats.maps > 0; return ( - +
{hasTiers && ( - +
+ +
)} - {stats.newest.length > 0 && ( +
({ + maps={newest.map((map) => ({ name: map.name, tier: map.tier, detail: formatSince(map.listed_at), }))} tierCount={tierCount} /> - )} - {stats.played_this_week.length > 0 && ( - ({ - name: map.name, - tier: map.tier, - detail: `${number.format(map.players)} ${map.players === 1 ? "player" : "players"}`, - }))} - tierCount={tierCount} - /> - )} - + {hasWeekly && ( + ({ + name: map.name, + tier: map.tier, + detail: `${number.format(map.players)} ${map.players === 1 ? "player" : "players"}`, + }))} + tierCount={tierCount} + /> + )} +
+
); } /** One of the map stats' lists: a heading, linked to the matching sort if there is one, then a few maps with a detail each. */ function MapStatsList({ title, + empty, href, maps, tierCount, }: { title: string; + empty?: string; href?: string; maps: { name: string; tier?: number | null; detail: string }[]; tierCount: number | null | undefined; }) { return ( -
-

+
+

{href ? ( - + {title} ) : ( title )}

-
    - {maps.map((map) => ( -
  • - - {map.tier != null && tierCount != null && ( - - )} - - {map.name} - - {map.detail} - -
  • - ))} -
+ {maps.length === 0 ? ( +

{empty}

+ ) : ( +
    + {maps.map((map) => ( +
  • + + {map.tier != null && tierCount != null ? ( + + ) : ( + + )} + + {map.name} + + + {map.detail} + + +
  • + ))} +
+ )}
); } @@ -484,11 +542,7 @@ function FilterPlayer({ href={`/players/${player.steamid64}`} className="hover:text-accent flex items-center gap-2" > - + {player.name} ) : ( @@ -504,49 +558,3 @@ function FilterPlayer({ ); } - -function MapRow({ - map, - tierCount, -}: { - map: Schemas["MapSummary"]; - tierCount: number | null | undefined; -}) { - const wr = map.world_record; - return ( - - - - - {map.tier != null && tierCount != null && ( - - )} - {map.name} - - - {map.players === 1 ? "1 player" : `${map.players} players`} - {map.bonuses > 0 && - ` · ${map.bonuses === 1 ? "1 bonus" : `${map.bonuses} bonuses`}`} - - - {wr ? ( - - - {formatTime(wr.time)} - - - {wr.player.name} - - - - ) : ( - - No record in this style - - )} - - ); -} diff --git a/web/src/features/maps/MapOverview.module.css b/web/src/features/maps/MapOverview.module.css new file mode 100644 index 0000000..cf3e0b2 --- /dev/null +++ b/web/src/features/maps/MapOverview.module.css @@ -0,0 +1,160 @@ +/* A centered overview sits above the separate map controls; summary rows keep their details close. */ +.overview { + display: grid; + gap: calc(var(--spacing) * 4); + min-inline-size: 0; + max-inline-size: 80rem; + margin-inline: auto; +} + +.toolbar { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: calc(var(--spacing) * 3); + min-inline-size: 0; +} + +.search { + order: -1; + min-inline-size: 0; +} + +.search input { + border-color: var(--color-border-strong); + background-color: var(--color-bg); +} + +.search input:focus { + border-color: var(--color-accent); +} + +.summaries { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: calc(var(--spacing) * 4); + border-block-start: 1px solid var(--color-border); + padding-block-start: calc(var(--spacing) * 4); + min-inline-size: 0; +} + +.summary { + display: flex; + flex-direction: column; + gap: calc(var(--spacing) * 2); + min-inline-size: 0; +} + +.list { + display: grid; + gap: calc(var(--spacing) * 2); +} + +.link { + display: grid; + grid-template-columns: auto minmax(0, 1fr); + align-items: start; + gap: 0 calc(var(--spacing) * 1.5); + min-block-size: calc(var(--spacing) * 10); +} + +.detail { + grid-column: 2; + grid-row: 2; + align-self: center; +} + +.link > :first-child { + grid-column: 1; + grid-row: 2; +} + +.link > :nth-child(2) { + grid-column: 1 / -1; + grid-row: 1; +} + +@media (min-width: 80rem) { + .overview { + grid-template-columns: auto minmax(0, 1fr); + align-items: center; + gap: calc(var(--spacing) * 6); + } + + .summaries { + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: calc(var(--spacing) * 6); + border-block-start: 0; + border-inline-start: 1px solid var(--color-border); + padding-block-start: 0; + padding-inline-start: calc(var(--spacing) * 6); + } + + .summary { + gap: calc(var(--spacing) * 2); + min-block-size: calc(var(--spacing) * 44); + } + + .summary + .summary { + border-inline-start: 1px solid var(--color-border); + padding-inline-start: calc(var(--spacing) * 6); + } + + .summary h2 { + display: flex; + align-items: center; + min-block-size: calc(var(--spacing) * 8); + } + + .list { + grid-template-columns: auto auto auto; + justify-content: start; + gap: var(--spacing) calc(var(--spacing) * 2); + } + + .list > li, + .link { + display: grid; + grid-column: 1 / -1; + grid-template-columns: subgrid; + } + + .link { + align-items: center; + column-gap: calc(var(--spacing) * 2); + min-block-size: calc(var(--spacing) * 6); + } + + .link > :first-child, + .link > :nth-child(2), + .detail { + grid-row: 1; + } + + .link > :nth-child(2) { + grid-column: 2; + } + + .detail { + grid-column: 3; + text-align: end; + font-size: var(--text-sm); + line-height: var(--text-sm--line-height); + } +} + +@media (min-width: 48rem) { + .search { + order: 0; + inline-size: 20rem; + flex: none; + margin-inline-start: auto; + } +} + +.summaries:only-child { + grid-column: 1 / -1; + border: 0; + padding: 0; +} diff --git a/web/src/features/maps/MapZoneView.tsx b/web/src/features/maps/MapZoneView.tsx index edb49d1..e773331 100644 --- a/web/src/features/maps/MapZoneView.tsx +++ b/web/src/features/maps/MapZoneView.tsx @@ -1,8 +1,9 @@ "use client"; -// A map's zones from above, and on asking, in 3D. The plan is drawn from the zones alone; the map itself -// downloads only once someone asks for the 3D view. -import { Box } from "lucide-react"; -import { useState } from "react"; +// A map's zones in 3D, shown on asking, as a run's replay is: until then a poster of the map with a button, so +// nothing heavy loads with the page. Hiding it, or leaving the page, unloads the view. A map without a file for +// the 3D view yet shows its zones from above instead. +import { Box, X } from "lucide-react"; +import { useEffect, useState } from "react"; import type { Schemas } from "@/api/client"; import { ZoneEditor } from "@/features/staff/maps/ZoneEditor"; import { ZonePlan } from "@/features/staff/maps/ZonePlan"; @@ -13,16 +14,63 @@ export function MapZoneView({ zones, viewerFile, tracks, + cover, }: { map: string; zones: Schemas["Zone"][]; - /** Null when the map has no file for the 3D view yet; the plan still shows. */ + /** Null when the map has no file for the 3D view yet; the plan shows instead. */ viewerFile: Schemas["ViewerFile"] | null; tracks: number[]; + /** The map's cover picture, for the poster. */ + cover: Schemas["MapImage"] | undefined; }) { - const [in3d, setIn3d] = useState(false); - if (in3d && viewerFile) { + const [shown, setShown] = useState(false); + // Next keeps a page left behind alive but hidden, and tears down its effects; back on it, the poster shows + // again rather than the 3D view, as the replay player does. + useEffect(() => () => setShown(false), []); + + if (!viewerFile) { + return ( + <> +

+ No 3D view yet: staff haven't uploaded this map's file. +

+ + + ); + } + + if (!shown) { return ( +
+ {cover && ( + // The map's picture, dimmed, so the space reads as this map until the view loads. Decorative only. + // eslint-disable-next-line @next/next/no-img-element + + )} + +
+ ); + } + + return ( + <> + - ); - } - return ( - <> - - {viewerFile && ( - - )} ); } diff --git a/web/src/features/maps/MapZones.tsx b/web/src/features/maps/MapZones.tsx index e6edc1b..2c088a5 100644 --- a/web/src/features/maps/MapZones.tsx +++ b/web/src/features/maps/MapZones.tsx @@ -37,6 +37,7 @@ export async function MapZones({ name }: { name: string }) { zones={zones.data} viewerFile={map.viewer_file ?? null} tracks={map.tracks.map((track) => track.track)} + cover={map.images[0]} /> )} diff --git a/web/src/features/maps/mapPodiums.test.ts b/web/src/features/maps/mapPodiums.test.ts new file mode 100644 index 0000000..8f8e65c --- /dev/null +++ b/web/src/features/maps/mapPodiums.test.ts @@ -0,0 +1,82 @@ +// PBs use the selected style and viewer, and a failed lookup must not look like an uncompleted map. +import { beforeEach, expect, it, vi } from "vitest"; +import type { Schemas } from "../../api/client"; +import { mapPodiums } from "./mapPodiums"; + +const { get } = vi.hoisted(() => ({ get: vi.fn() })); +vi.mock("next/cache", () => ({ cacheLife: vi.fn() })); +vi.mock("@/api/client", () => ({ api: { GET: get } })); + +const entry = { + rank: 5, + player: { name: "Runner", steamid64: "76561198000000001" }, + time: 12, + run_id: 73, +}; +const record = { + ...entry, + rank: 1, + time: 10, + run_id: 70, + player: { name: "Leader", steamid64: "76561198000000003" }, +}; +const map: Schemas["MapSummary"] = { + name: "bhop_test", + players: 10, + bonuses: 0, + last_run_at: "2026-11-09T00:00:00Z", + world_record: { ...record, finished_at: "2026-11-09T00:00:00Z" }, +}; + +beforeEach(() => { + get.mockReset(); +}); + +it("loads the viewer's PB in the same style-scoped request as the podium", async () => { + get.mockResolvedValue({ data: { entries: [record], player_entry: entry } }); + const result = await mapPodiums([map], "scroll", entry.player.steamid64); + expect(get).toHaveBeenCalledOnce(); + expect(get.mock.calls[0]![1].params.query).toEqual({ + style: "scroll", + track: 0, + limit: 3, + player: entry.player.steamid64, + }); + expect(result.get(map.name)?.personalBest).toEqual(entry); + expect(result.get(map.name)?.entries).toEqual([record]); +}); + +it("scopes each viewer independently and omits PBs for signed-out visitors", async () => { + get.mockImplementation(async (_path, options) => ({ + data: { + entries: [record], + player_entry: + options.params.query.player === entry.player.steamid64 ? entry : null, + }, + })); + expect( + (await mapPodiums([map], "normal", entry.player.steamid64)).get(map.name) + ?.personalBest, + ).toEqual(entry); + expect( + (await mapPodiums([map], "normal", "76561198000000002")).get(map.name) + ?.personalBest, + ).toBeNull(); + expect( + (await mapPodiums([map], "normal")).get(map.name)?.personalBest, + ).toBeUndefined(); +}); + +it("distinguishes an empty style from a failed request", async () => { + const empty = await mapPodiums( + [{ ...map, world_record: null }], + "normal", + entry.player.steamid64, + ); + expect(empty.get(map.name)?.personalBest).toBeNull(); + expect(get).not.toHaveBeenCalled(); + get.mockRejectedValue(new Error("unreachable")); + expect( + (await mapPodiums([map], "normal", entry.player.steamid64)).get(map.name), + ).toBeNull(); +}); diff --git a/web/src/features/maps/mapPodiums.ts b/web/src/features/maps/mapPodiums.ts new file mode 100644 index 0000000..7a12672 --- /dev/null +++ b/web/src/features/maps/mapPodiums.ts @@ -0,0 +1,73 @@ +// Map-card podiums and the viewer's public PB, cached per style and player in bounded batches. +import { cacheLife } from "next/cache"; +import { api, type Schemas } from "@/api/client"; + +export type MapLeader = Pick< + Schemas["LeaderboardEntry"], + "rank" | "player" | "time" | "run_id" +>; + +export interface MapPodium { + entries: readonly MapLeader[]; + personalBest?: MapLeader | null; +} + +export async function mapPodiums( + maps: Schemas["MapSummary"][], + style: string | null | undefined, + player?: string, +): Promise> { + const podiums = new Map(); + if (!style) return podiums; + // Avoid issuing a page's worth of independent requests to the beta API at once. + for (let offset = 0; offset < maps.length; offset += 6) { + const batch = await Promise.all( + maps.slice(offset, offset + 6).map(async (map) => { + if (!map.world_record) + return [ + map.name, + { entries: [], personalBest: player ? null : undefined }, + ] as const; + const leaders = await cachedPodium({ + map: map.name, + style, + record: map.world_record.run_id, + player, + }).catch(() => null); + return [map.name, leaders] as const; + }), + ); + for (const [map, leaders] of batch) podiums.set(map, leaders); + if (batch.every(([, leaders]) => leaders === null)) break; + } + return podiums; +} + +async function cachedPodium(key: { + map: string; + style: string; + // A new WR changes the key, so cached cards cannot contradict the map list's winner. + record: number; + // PBs are public, but each viewer must have a separate cache entry. + player?: string; +}): Promise { + "use cache"; + cacheLife({ stale: 30, revalidate: 30, expire: 300 }); + const { data, response } = await api.GET("/v1/maps/{map}/leaderboard", { + params: { + path: { map: key.map }, + query: { style: key.style, track: 0, limit: 3, player: key.player }, + }, + signal: AbortSignal.timeout(5000), + }); + if (!data) throw new Error(`Map podium answered ${response.status}`); + return { + entries: data.entries.map(({ rank, player, time, run_id }) => ({ + rank, + player, + time, + run_id, + })), + personalBest: key.player ? (data.player_entry ?? null) : undefined, + }; +} diff --git a/web/src/features/maps/mapPreview.test.ts b/web/src/features/maps/mapPreview.test.ts new file mode 100644 index 0000000..4ddff57 --- /dev/null +++ b/web/src/features/maps/mapPreview.test.ts @@ -0,0 +1,76 @@ +// The text of a map page's link preview. +import { describe, expect, it } from "vitest"; +import type { Schemas } from "@/api/client"; +import { mapDescription } from "./mapPreview"; + +const names: Record = { normal: "Normal", sw: "Sideways" }; +const styleName = (key: string) => names[key] ?? key; +const gabe = { + steamid64: "76561197960287930", + name: "gabe", + avatar_url: null, + country_code: null, +}; + +function board(style: string, time: number) { + return { + style, + players: 1, + runs: 1, + world_record: { player: gabe, time, run_id: 1, finished_at: "" }, + leaderboard: [], + next_cursor: null, + wr_history: [], + }; +} + +function map(overrides: Partial): Schemas["MapDetail"] { + return { + name: "bhop_badges", + images: [], + players: 44, + runs: 90, + tier_count: null, + tracks: [], + legacy_players: 0, + legacy_runs: 0, + all_players: 0, + legacy_record_history: [], + ...overrides, + } as Schemas["MapDetail"]; +} + +describe("mapDescription", () => { + it("names the tier, the opening board's record and the players", () => { + const tracks = [ + { track: 0, tier: 5, styles: [board("sw", 80), board("normal", 64.211)] }, + { track: 1, tier: null, styles: [board("normal", 10)] }, + ]; + expect( + mapDescription( + map({ tracks, tier_count: 10 }), + ["normal", "sw"], + styleName, + ), + ).toBe( + "Tier 5. World record 1:04.211 by gabe in Normal. 44 players, 1 bonus.", + ); + }); + + it("leaves out tiers until a tier count is published", () => { + const tracks = [{ track: 0, tier: 5, styles: [board("normal", 30)] }]; + expect(mapDescription(map({ tracks }), ["normal"], styleName)).toBe( + "World record 30.000 by gabe in Normal. 44 players.", + ); + }); + + it("says when a map has only pre-2.0 records", () => { + expect( + mapDescription( + map({ players: 0, legacy_players: 3 }), + ["normal"], + styleName, + ), + ).toBe("Pre-2.0 records only. 0 players."); + }); +}); diff --git a/web/src/features/maps/mapPreview.ts b/web/src/features/maps/mapPreview.ts new file mode 100644 index 0000000..271a6f5 --- /dev/null +++ b/web/src/features/maps/mapPreview.ts @@ -0,0 +1,54 @@ +// A map page's link preview: its tier, the world record of the board the page opens on, and how many play it. +import type { Metadata } from "next"; +import type { Schemas } from "@/api/client"; +// Relative imports, as the unit tests resolve no `@/` paths. +import { formatTime } from "../runs/time"; +import { count, linkPreview } from "../site/linkPreview"; + +/** The cover's full size, as the API stores it (`docs/site-api.md`). */ +const COVER = { width: 1920, height: 1080 }; + +export function mapPreview( + map: Schemas["MapDetail"], + styleOrder: string[], + styleName: (key: string) => string, +): Metadata { + const cover = map.images[0]; + return linkPreview({ + title: map.name, + description: mapDescription(map, styleOrder, styleName), + picture: cover && { url: cover.url, ...COVER, wide: true }, + }); +} + +/** Plain facts, in the order a player looks for them: how hard, the time to beat, how busy. */ +export function mapDescription( + map: Schemas["MapDetail"], + styleOrder: string[], + styleName: (key: string) => string, +): string { + const main = map.tracks.find((track) => track.track === 0); + // The board the page opens on: the first ranked style with runs on the main track. + const board = styleOrder + .map((key) => main?.styles.find((style) => style.style === key)) + .find((style) => style !== undefined); + const bonuses = map.tracks.filter((track) => track.track > 0).length; + + const parts: string[] = []; + if (main?.tier != null && map.tier_count != null) { + parts.push(`Tier ${main.tier}`); + } + if (board) { + const record = board.world_record; + parts.push( + `World record ${formatTime(record.time)} by ${record.player.name} in ${styleName(board.style)}`, + ); + } else if (map.legacy_players > 0) { + parts.push("Pre-2.0 records only"); + } + const players = count(map.players, "player", "players"); + parts.push( + bonuses > 0 ? `${players}, ${count(bonuses, "bonus", "bonuses")}` : players, + ); + return `${parts.join(". ")}.`; +} diff --git a/web/src/features/players/playerPreview.test.ts b/web/src/features/players/playerPreview.test.ts new file mode 100644 index 0000000..776030f --- /dev/null +++ b/web/src/features/players/playerPreview.test.ts @@ -0,0 +1,31 @@ +// The text of a player page's link preview. +import { describe, expect, it } from "vitest"; +import type { Schemas } from "@/api/client"; +import { playerDescription } from "./playerPreview"; + +describe("playerDescription", () => { + const player = { + first_run_at: "2026-10-01T00:00:00Z", + map_count: 570, + legacy_maps: 0, + all_styles: { completed_maps: 120, completed_bonuses: 4, world_records: 3 }, + } as Schemas["PlayerProfile"]; + + it("counts finished maps and world records across styles", () => { + expect(playerDescription(player)).toBe( + "Finished 120 of 570 maps, with 3 world records, across all styles.", + ); + expect( + playerDescription({ + ...player, + all_styles: { ...player.all_styles, world_records: 0 }, + }), + ).toBe("Finished 120 of 570 maps, across all styles."); + }); + + it("describes a player with only pre-2.0 records", () => { + expect( + playerDescription({ ...player, first_run_at: null, legacy_maps: 1 }), + ).toBe("Pre-2.0 records on 1 map."); + }); +}); diff --git a/web/src/features/players/playerPreview.ts b/web/src/features/players/playerPreview.ts new file mode 100644 index 0000000..eaab089 --- /dev/null +++ b/web/src/features/players/playerPreview.ts @@ -0,0 +1,30 @@ +// A player page's link preview: their name, avatar, and what they've finished across every style. +import type { Metadata } from "next"; +import type { Schemas } from "@/api/client"; +// A relative import, as the unit tests resolve no `@/` paths. +import { count, linkPreview } from "../site/linkPreview"; + +export function playerPreview(player: Schemas["PlayerProfile"]): Metadata { + return linkPreview({ + title: player.name, + description: playerDescription(player), + picture: player.avatar_url + ? { url: player.avatar_url, wide: false } + : undefined, + }); +} + +export function playerDescription(player: Schemas["PlayerProfile"]): string { + const all = player.all_styles; + if (player.first_run_at == null) { + return player.legacy_maps > 0 + ? `Pre-2.0 records on ${count(player.legacy_maps, "map", "maps")}.` + : "No runs yet."; + } + const maps = `Finished ${all.completed_maps} of ${count(player.map_count, "map", "maps")}`; + const records = + all.world_records > 0 + ? `, with ${count(all.world_records, "world record", "world records")}` + : ""; + return `${maps}${records}, across all styles.`; +} diff --git a/web/src/features/runs/runPreview.test.ts b/web/src/features/runs/runPreview.test.ts new file mode 100644 index 0000000..9ca07df --- /dev/null +++ b/web/src/features/runs/runPreview.test.ts @@ -0,0 +1,31 @@ +// The text of a run page's link preview. +import { describe, expect, it } from "vitest"; +import type { Schemas } from "@/api/client"; +import { runDescription } from "./runPreview"; + +const styleName = (key: string) => (key === "normal" ? "Normal" : key); + +describe("runDescription", () => { + const run = { + time: 74.581, + style: "normal", + track: 0, + invalidated: false, + rank: 31, + } as Schemas["RunDetail"]; + + it("gives the time, style, track and place", () => { + expect(runDescription(run, styleName)).toBe( + "1:14.581 in Normal on the main track. Place 31.", + ); + expect(runDescription({ ...run, track: 2, rank: null }, styleName)).toBe( + "1:14.581 in Normal on bonus 2.", + ); + }); + + it("says an invalidated run is invalidated, without a place", () => { + expect( + runDescription({ ...run, invalidated: true, rank: null }, styleName), + ).toBe("1:14.581 in Normal on the main track. Invalidated."); + }); +}); diff --git a/web/src/features/runs/runPreview.ts b/web/src/features/runs/runPreview.ts new file mode 100644 index 0000000..e17288b --- /dev/null +++ b/web/src/features/runs/runPreview.ts @@ -0,0 +1,31 @@ +// A run page's link preview: who ran which map, the time, and its place while it's a personal best, over the map's +// card. Runs share their map's card, so there are only as many cards as maps. +import type { Metadata } from "next"; +import type { Schemas } from "@/api/client"; +// A relative import, as the unit tests resolve no `@/` paths. +import { card, linkPreview } from "../site/linkPreview"; +import { formatTime, trackName } from "./time"; + +export function runPreview( + run: Schemas["RunDetail"], + styleName: (key: string) => string, +): Metadata { + return linkPreview({ + title: `${run.player.name} on ${run.map}`, + description: runDescription(run, styleName), + picture: run.map_card_url ? card(run.map_card_url) : undefined, + }); +} + +export function runDescription( + run: Schemas["RunDetail"], + styleName: (key: string) => string, +): string { + const where = + run.track === 0 ? "the main track" : trackName(run.track).toLowerCase(); + const time = `${formatTime(run.time)} in ${styleName(run.style)} on ${where}.`; + // An invalidated run's page says so without the reason (`docs/domain.md`). + if (run.invalidated) return `${time} Invalidated.`; + // Only while it's a personal best; "Place 1" rather than "World record", since tied places share it. + return run.rank == null ? time : `${time} Place ${run.rank}.`; +} diff --git a/web/src/features/servers/ServerList.tsx b/web/src/features/servers/ServerList.tsx index bd03a94..66d6ba6 100644 --- a/web/src/features/servers/ServerList.tsx +++ b/web/src/features/servers/ServerList.tsx @@ -1,10 +1,13 @@ // The Servers page: activity over time, then the listed servers running the SourceJump plugin, online ones // first. Staff with manage_servers also see unlisted servers there, and list or unlist them in place. +import { connection } from "next/server"; import { api } from "@/api/client"; import { ServerActivity } from "./ServerActivity"; import { ServerRows } from "./ServerRows"; export async function ServerList() { + // At request time, as `LiveNow`: the API isn't reachable while the site is built. + await connection(); const [result, day, week, month, year] = await Promise.all([ api.GET("/v1/servers").catch(() => undefined), ...(["day", "week", "month", "year"] as const).map((range) => diff --git a/web/src/features/site/AccountMenu.tsx b/web/src/features/site/AccountMenu.tsx index 4ef1ddc..ffcb117 100644 --- a/web/src/features/site/AccountMenu.tsx +++ b/web/src/features/site/AccountMenu.tsx @@ -1,6 +1,6 @@ "use client"; -// The signed-in player's menu: their profile, the staff area for staff, and signing out. -import { LogOut, ShieldCheck, User } from "lucide-react"; +// The signed-in player's menu: their profile, the staff area for staff, and signing out, here or everywhere. +import { LogOut, MonitorX, ShieldCheck, User } from "lucide-react"; import type { Schemas } from "@/api/client"; import { isStaff } from "@/features/staff/sections"; import { Avatar } from "@/ui/Avatar"; @@ -8,6 +8,7 @@ import { Menu, MenuItem, MenuLink, MenuSeparator } from "@/ui/Menu"; import { useReturnTo } from "./useReturnTo"; const SIGN_OUT_FORM = "sign-out"; +const SIGN_OUT_EVERYWHERE_FORM = "sign-out-everywhere"; export function AccountMenu({ me }: { me: Schemas["Me"] }) { const returnTo = useReturnTo(); @@ -20,6 +21,13 @@ export function AccountMenu({ me }: { me: Schemas["Me"] }) { action={`/v1/auth/sign-out?return_to=${encodeURIComponent(returnTo)}`} hidden /> + {/* Ends the player's sessions in every browser, such as one left signed in on someone else's computer. */} +