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-fe47d13f296be60170a39f1f7bfd568993ed49e0f088a4e391206d71d84e8e4e.json b/api/.sqlx/query-2eebac3bfabb75d940a811c7d02153f5636493b3e42961fbcd3954122de76ef0.json similarity index 90% rename from api/.sqlx/query-fe47d13f296be60170a39f1f7bfd568993ed49e0f088a4e391206d71d84e8e4e.json rename to api/.sqlx/query-2eebac3bfabb75d940a811c7d02153f5636493b3e42961fbcd3954122de76ef0.json index 7d1d2fc..81b821c 100644 --- a/api/.sqlx/query-fe47d13f296be60170a39f1f7bfd568993ed49e0f088a4e391206d71d84e8e4e.json +++ b/api/.sqlx/query-2eebac3bfabb75d940a811c7d02153f5636493b3e42961fbcd3954122de76ef0.json @@ -1,6 +1,6 @@ { "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 LATERAL (SELECT tier FROM map_tiers WHERE map_id = shown.map_id AND track = shown.track\n ORDER BY assigned_at DESC LIMIT 1) tier ON $8\n ORDER BY shown.map, shown.track\n ", + "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": [ { @@ -57,7 +57,7 @@ "type_info": "Int2", "origin": { "Table": { - "table": "map_tiers", + "table": "current_map_tiers", "name": "tier" } } @@ -87,5 +87,5 @@ true ] }, - "hash": "fe47d13f296be60170a39f1f7bfd568993ed49e0f088a4e391206d71d84e8e4e" + "hash": "2eebac3bfabb75d940a811c7d02153f5636493b3e42961fbcd3954122de76ef0" } 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-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-7fc6e231d7984b3b86529449e28e100d4f3e2c846b85cb200ac020301aa634db.json b/api/.sqlx/query-7fc6e231d7984b3b86529449e28e100d4f3e2c846b85cb200ac020301aa634db.json deleted file mode 100644 index 8f7ceab..0000000 --- a/api/.sqlx/query-7fc6e231d7984b3b86529449e28e100d4f3e2c846b85cb200ac020301aa634db.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "\n SELECT count(*) AS \"total!\"\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 $5\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": "7fc6e231d7984b3b86529449e28e100d4f3e2c846b85cb200ac020301aa634db" -} 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-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-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-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-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-0e5fd428486c3ff6a9210aa1813d243795a041590b0a94267c0f6ed61a0f7746.json b/api/.sqlx/query-d90f77279563fb737789aa1953cf0b88a1da1097bdace556b747f7ff8a70b8a8.json similarity index 59% rename from api/.sqlx/query-0e5fd428486c3ff6a9210aa1813d243795a041590b0a94267c0f6ed61a0f7746.json rename to api/.sqlx/query-d90f77279563fb737789aa1953cf0b88a1da1097bdace556b747f7ff8a70b8a8.json index c7e603b..fed768d 100644 --- a/api/.sqlx/query-0e5fd428486c3ff6a9210aa1813d243795a041590b0a94267c0f6ed61a0f7746.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 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 ", + "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" } } @@ -163,7 +163,7 @@ false, false, false, - false, + true, null, false, null, @@ -173,5 +173,5 @@ true ] }, - "hash": "0e5fd428486c3ff6a9210aa1813d243795a041590b0a94267c0f6ed61a0f7746" + "hash": "d90f77279563fb737789aa1953cf0b88a1da1097bdace556b747f7ff8a70b8a8" } 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-d229738260622b500ce9606ced26758e381bc932126584a48c813acb6e272509.json b/api/.sqlx/query-e93ff3ff9338506b56ece4e87290320a4b6ef774cb4fa306d5a072fe9b9a3212.json similarity index 88% rename from api/.sqlx/query-d229738260622b500ce9606ced26758e381bc932126584a48c813acb6e272509.json rename to api/.sqlx/query-e93ff3ff9338506b56ece4e87290320a4b6ef774cb4fa306d5a072fe9b9a3212.json index 2c5680d..4ce9614 100644 --- a/api/.sqlx/query-d229738260622b500ce9606ced26758e381bc932126584a48c813acb6e272509.json +++ b/api/.sqlx/query-e93ff3ff9338506b56ece4e87290320a4b6ef774cb4fa306d5a072fe9b9a3212.json @@ -1,6 +1,6 @@ { "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 LATERAL (SELECT tier FROM map_tiers WHERE map_id = own.map_id AND track = own.track\n ORDER BY assigned_at DESC LIMIT 1) tier ON $11\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 ", + "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": [ { @@ -87,7 +87,7 @@ "type_info": "Int2", "origin": { "Table": { - "table": "map_tiers", + "table": "current_map_tiers", "name": "tier" } } @@ -117,8 +117,8 @@ null, false, false, - false + true ] }, - "hash": "d229738260622b500ce9606ced26758e381bc932126584a48c813acb6e272509" + "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/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/migrations/0054_current_map_tiers.sql b/api/crates/api/migrations/0054_current_map_tiers.sql new file mode 100644 index 0000000..e7b613d --- /dev/null +++ b/api/crates/api/migrations/0054_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/src/auth.rs b/api/crates/api/src/auth.rs index cda6ca2..df8b1a4 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,38 @@ 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. 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. +#[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 = UNAUTHORIZED, description = "Not signed in; no session was ended", body = ErrorBody), + (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)?; + let signed_in = signed_in.ok_or(ApiError::SignInRequired)?; + 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 +438,49 @@ 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: refused, so it never looks like it ended something. + let again = sign_out_everywhere("https://sourcejump.test").await; + assert_eq!(again.status, 401); + assert!(!again.headers.contains_key(header::LOCATION)); + let _: ErrorBody = again.json(); + } + #[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..0e7697c 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"), diff --git a/api/crates/api/src/leaderboards/standings.rs b/api/crates/api/src/leaderboards/standings.rs index ae609f5..92e2d72 100644 --- a/api/crates/api/src/leaderboards/standings.rs +++ b/api/crates/api/src/leaderboards/standings.rs @@ -150,8 +150,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 +262,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 ) diff --git a/api/crates/api/src/main.rs b/api/crates/api/src/main.rs index 0d66454..7a069bf 100644 --- a/api/crates/api/src/main.rs +++ b/api/crates/api/src/main.rs @@ -477,6 +477,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 +486,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/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..601869b 100644 --- a/api/crates/api/src/maps/list.rs +++ b/api/crates/api/src/maps/list.rs @@ -247,8 +247,7 @@ pub async fn list_maps( async fn map_stats(db: &sqlx::PgPool, tier_count: 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,8 +265,7 @@ async fn map_stats(db: &sqlx::PgPool, tier_count: Option) -> Result) -> Result now() - interval '7 days' GROUP BY map_id) week @@ -395,8 +392,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 @@ -516,8 +512,7 @@ async fn count_maps(tx: &mut sqlx::PgConnection, filter: &Filter<'_>) -> Result< WHERE last_run_at IS NOT NULL AND ($1::text IS NULL OR name ILIKE $1 ESCAPE '\' OR $2 <% name) 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, diff --git a/api/crates/api/src/players/personal_bests.rs b/api/crates/api/src/players/personal_bests.rs index 8238094..1f19bed 100644 --- a/api/crates/api/src/players/personal_bests.rs +++ b/api/crates/api/src/players/personal_bests.rs @@ -151,8 +151,7 @@ pub(super) async fn personal_bests( pb.style, m.name, pb.track LIMIT $5 ) own - LEFT JOIN LATERAL (SELECT tier FROM map_tiers WHERE map_id = own.map_id AND track = own.track - ORDER BY assigned_at DESC LIMIT 1) tier ON $11 + LEFT JOIN current_map_tiers tier ON $11 AND tier.map_id = own.map_id AND tier.track = own.track ORDER BY CASE WHEN $8 THEN own.finished_at END DESC, CASE WHEN $8 THEN own.run_id END DESC, own.style, own.map, own.track "#, @@ -231,8 +230,7 @@ async fn view_personal_bests( LIMIT $7 ) shown -- A legacy row's map_id is NULL, so it finds no tier. - LEFT JOIN LATERAL (SELECT tier FROM map_tiers WHERE map_id = shown.map_id AND track = shown.track - ORDER BY assigned_at DESC LIMIT 1) tier ON $8 + LEFT JOIN current_map_tiers tier ON $8 AND tier.map_id = shown.map_id AND tier.track = shown.track ORDER BY shown.map, shown.track "#, steamid64.get(), 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..88b40d4 --- /dev/null +++ b/api/crates/api/src/records/personal_bests.rs @@ -0,0 +1,243 @@ +//! 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. Keyed, unlike `…/records`: its only reader is a server deciding what to submit, which takes a key +//! anyway, and a key keeps a bulk lookup of 64 players at a time to servers we know. + +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, + servers::keys::ServerKey, +}; + +/// 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 = UNAUTHORIZED, description = "Missing, unknown or revoked API key", body = ErrorBody), + (status = UNPROCESSABLE_ENTITY, description = "Not a valid map name, or `players` isn't 1 to 64 SteamID64s", body = ErrorBody), + ), + security(("server_key" = [])), +)] +pub async fn players_personal_bests( + State(state): State, + _key: ServerKey, + 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); + } + // Checked as it goes, so a huge list is refused without being read to the end. + if parsed.len() > MAX_PLAYERS { + return Err(format!("players takes at most {MAX_PLAYERS} SteamID64s")); + } + } + Ok(parsed) +} + +#[cfg(test)] +mod tests { + use axum::{body::Body, http::Request}; + use serde_json::json; + use sqlx::PgPool; + + use super::{MAX_PLAYERS, PlayersPersonalBests, parse_players}; + use crate::{ + error::ErrorBody, + runs::tests::{run, setup}, + test_client::{self, TestResponse}, + }; + + async fn get(db: &PgPool, path: &str, key: Option<&str>) -> TestResponse { + let mut request = Request::get(path); + if let Some(key) = key { + request = request.header("authorization", format!("Bearer {key}")); + } + test_client::send(db, request.body(Body::empty()).unwrap()).await + } + + 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 = get( + &db, + &format!("/v1/maps/bhop_badges/personal-bests?players={GABE},{THIRD},{GABE}"), + Some(&key), + ) + .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 = get(&db, &path, Some(&key)).await.json(); + assert!(answer.personal_bests.is_empty(), "{path}"); + } + } + + #[sqlx::test] + async fn refuses_anything_but_1_to_64_steamid64s(db: PgPool) { + let key = setup(&db).await; + 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 = get( + &db, + &format!("/v1/maps/bhop_badges/personal-bests?players={players}"), + Some(&key), + ) + .await; + assert_eq!(response.status, 422, "{players}"); + let _: ErrorBody = response.json(); + } + assert_eq!( + get(&db, "/v1/maps/bhop_badges/personal-bests", Some(&key)) + .await + .status, + 400, + "players is required" + ); + } + + #[sqlx::test] + async fn refuses_a_request_without_a_valid_key(db: PgPool) { + setup(&db).await; + let path = format!("/v1/maps/bhop_badges/personal-bests?players={GABE}"); + for key in [None, Some("sj_not_a_key")] { + let response = get(&db, &path, key).await; + assert_eq!(response.status, 401, "{key:?}"); + let _: ErrorBody = response.json(); + } + } + + #[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/detail.rs b/api/crates/api/src/runs/detail.rs index 138ce95..ae70313 100644 --- a/api/crates/api/src/runs/detail.rs +++ b/api/crates/api/src/runs/detail.rs @@ -93,8 +93,7 @@ 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 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/runs/recent.rs b/api/crates/api/src/runs/recent.rs index 9187d88..13ff302 100644 --- a/api/crates/api/src/runs/recent.rs +++ b/api/crates/api/src/runs/recent.rs @@ -168,8 +168,7 @@ async fn count( r#" SELECT count(*) AS "total!" 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 $5 + LEFT JOIN current_map_tiers tier ON $5 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) @@ -206,8 +205,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/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/openapi.json b/api/openapi.json index 3097d0a..b7641cf 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": [ @@ -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": [ @@ -8192,6 +8305,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": [ @@ -8489,6 +8646,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.", diff --git a/docs/VISION.md b/docs/VISION.md index 7f62043..9191906 100644 --- a/docs/VISION.md +++ b/docs/VISION.md @@ -31,4 +31,4 @@ **References:** - `docs/design/reference.webp`: the direction for look and feel (dark slate, cyan accent, stat cards, medal rows, map cards). Not a target; see `docs/design-system.md`. - CS:GO KZ community sites: per-tier completions and "% of maps done" on profiles. -- Font: [Play](https://fonts.google.com/specimen/Play), used on the previous site. +- Font: [Geist](https://vercel.com/font). The previous site used [Play](https://fonts.google.com/specimen/Play). diff --git a/docs/api.md b/docs/api.md index 092768b..6ad5e53 100644 --- a/docs/api.md +++ b/docs/api.md @@ -1,5 +1,5 @@ # API -How the `/v1/` API behaves for game servers, and rules for every client. The website's own endpoints (sign-in, players, maps, servers, posts): `site-api.md`. The exact schema is `api/openapi.json`. Examples, checked by `cargo test`: `api/contract/`. +How the `/v1/` API behaves for game servers, and rules for every client. The website's own endpoints: `site-api.md`. The exact schema is `api/openapi.json`. Examples, checked by `cargo test`: `api/contract/`. ## Endpoints | Endpoint | Key | Code | @@ -7,7 +7,8 @@ How the `/v1/` API behaves for game servers, and rules for every client. The web | `GET /v1/ruleset` | no | `ruleset.rs` | | `GET /v1/maps/{map}/zones` | no | `zones.rs` | | `GET /v1/maps/{map}/records` | no | `records.rs` | -| `GET /v1/records/events`, `GET /v1/records/stream` | no | `record_events.rs`, `record_events/stream.rs` | +| `GET /v1/maps/{map}/personal-bests` | yes | `records/` | +| `GET /v1/records/events`, `…/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` | | `GET /v1/plugin/latest` | no | `plugin_releases.rs` | @@ -16,10 +17,10 @@ How the `/v1/` API behaves for game servers, and rules for every client. The web | `POST /v1/runs` | yes | `runs.rs`, `replays.rs` | | `GET /v1/replays/{run_id}` | no | `replays/download.rs` | | `POST /v1/anticheat/detections` | yes | `anticheat.rs` | -| `GET /v1/players`, `GET /v1/players/{player}`, `…/personal-bests` | no | `players/` | -| `GET /v1/auth/steam`, `GET /v1/auth/steam/callback`, `POST /v1/auth/sign-out` | browser | `auth.rs`, `auth/openid.rs` | -| `GET /v1/me` | session | `auth.rs`, `auth/sessions.rs` | -| `GET /v1/posts`, `GET /v1/posts/{post}`; `POST`, `PUT`, `DELETE` to write | no; session to write | `posts.rs`, `posts/` | +| `GET /v1/players`, `…/{player}`, `…/personal-bests` | no | `players/` | +| `GET /v1/auth/steam`, `…/callback`, `POST /v1/auth/sign-out` | browser | `auth.rs`, `auth/openid.rs` | +| `GET /v1/me`, `POST /v1/auth/sign-out-everywhere` | session | `auth.rs`, `auth/sessions.rs` | +| `GET /v1/posts`, `…/{post}`; `POST`, `PUT`, `DELETE` to write | no; session to write | `posts.rs`, `posts/` | | `/v1/staff/…`: log, keys, servers, listings | staff session | `staff.rs`, `staff/` | ## Rules every client can rely on @@ -43,21 +44,22 @@ How the `/v1/` API behaves for game servers, and rules for every client. The web - 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 there, 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 there, its tickrate matches the ruleset's `tickrate` if set, and the plugin reports the server as compliant. - Optional `player.country_code`: the server's `GeoipCode2` for the player (never their IP) sets their flag; unknown codes are ignored. - `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 adds a map by submitting a run on it; ranking it 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 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 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; 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 servers ask only for files they'll get. +- `…/records` marks each record `has_replay` by the same rule, so servers ask only for files they'll 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 on every board, with `rank`. +- All three send an `ETag` (`etag.rs`, a body hash); `If-None-Match` with it gets a bodiless `304` until it 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, 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`). diff --git a/docs/design-system.md b/docs/design-system.md index 9e35609..866f571 100644 --- a/docs/design-system.md +++ b/docs/design-system.md @@ -1,15 +1,15 @@ # Design system -One visual language that every page is built from, so pages can't drift apart. See it all at `/dev/ui` (dev builds only). +One visual language for every page, so pages can't drift apart. See it at `/dev/ui` (dev builds only). ## Direction "Classic" (2026-11-07): the old sourcejump.net, updated. Replaced "Navy". - A slate sheet (`bg`, `shadow-sheet`) between darker gutters. One cyan accent; at most one primary button per view. - Gamified but professional: medals, tier colors, WR badges, count-ups and small motions. No mascots, confetti, slogans or sales copy. -- Play for everything. Its digits are all the same width, so times line up in columns without a second font. +- Geist: 450 regular, 700 bold, matched to the old Play; Exo 2 bold (`font-server`) for server names. Times and tables use equal-width digits. - Corners: `rounded-md` (8px) for every frame, from a panel to a field or button; `rounded-sm` (4px) for badges and rows inside a frame. ## Tokens -`web/src/ui/tokens.css` holds every color, type size, radius, shadow and easing as Tailwind theme variables. Tailwind's own palette, radii, type scale and shadows are cleared, so `bg-red-500` or `rounded-3xl` don't compile. Spacing keeps Tailwind's 4px grid. +`web/src/ui/tokens.css` holds every color, type size, radius, shadow and easing as Tailwind theme variables. Tailwind's own palette, radii, type scale and shadows are cleared, so `bg-red-500` or `rounded-3xl` don't compile. Spacing keeps Tailwind's 4px grid. Breakpoints add `xs` (360px) for the narrowest phones. - Surfaces, darkest to lightest: `bg`, `surface`, `surface-raised`, `surface-overlay`. Borders: `border`, `border-strong`. - Text: `text`, `text-muted`, `text-subtle`. Accent: `accent`, `accent-hover`, `accent-soft`, `on-accent`. - Status: `success`, `warning`, `danger`, each with a `-soft` tint. Medals: `gold`, `silver`, `bronze`, `on-medal`. @@ -21,35 +21,36 @@ One visual language that every page is built from, so pages can't drift apart. S | Component | Use | |---|---| | `Page` | Every page's content area; `width` is `wide`, `narrow` (reading) or `fill` (inside a section layout that sets its own width, such as the staff area). Runs the page fade | -| `Masthead` | Full-width top band, plain or over a map picture; inside `Page width="fill"` (Players pages) | +| `Masthead` | Full-width top band, plain or over a map picture, in `Page width="fill"` (Players pages) | | `Link` | Every internal link; never prefetches. Lint blocks importing `next/link` elsewhere | | `Button`, `ButtonLink`, `ButtonAnchor` | `primary` (one per view), `secondary` (default), `ghost`; sizes `sm`, `md`. A `ghost` button with `aria-pressed` or `aria-expanded` shows the accent while on. `ButtonAnchor` is for full page loads, such as sign-in | | `Card`, `Label` | Bordered surface; `interactive` adds the hover lift. `Label` is the small uppercase heading | -| `StatCard` | Headline number with label and icon, counting up, and an optional short detail beside the number (never under it, so cards in a row stay one height). `null` shows a dash | +| `StatCard` | Headline number with label and icon, counting up, and an optional detail beside the number (not under it, so a row of cards stays one height). `null` shows a dash | | `Badge` | Short status: `neutral`, `accent` (WR), `success`, `warning`, `danger` | | `Medal` | Placement; medals for 1–3, a plain number after | | `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, staff lists; `numeric` cells right-align, `centered` heads center on narrow marks, `wrap` cells wrap. Scrolls sideways if too wide | +| `Table` + `TableHead`/`TableBody`/`TableRow`/`TableHeaderCell`/`TableCell` | `numeric` cells right-align, `centered` heads center on narrow marks, `wrap` cells wrap, `separated` rows start a group. Scrolls sideways if too wide; `phoneLead` + `phoneFill` size a phone's first view to end at a column's edge | | `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 | -| `ChoiceMenu` | "Label Value ▾": one choice from a list, in a `Menu` of radio items, changing the view in place, or following each option's `href` on a server page. Boards, profiles and the Maps page use a row of them (Style, Track, Runs; Sort, Records in; lead, 2026-10-26); quiet options are dimmed but choosable, disabled ones dimmed and kept in place. Word-width on phones too, so they sit side by side | +| `Segmented` | Looks like segmented `Tabs`, for a choice that changes the view in place, e.g. a chart range. The chosen option is in the accent | +| `ChoiceMenu` | "Label Value ▾": one choice from a list, in a `Menu` of radio items, changing the view in place, or following each option's `href` on a server page. Boards, profiles and the Maps page use a row of them (lead, 2026-10-26); Style lists Autosync after Normal (`menuOrder`); quiet options are dimmed but choosable, disabled ones dimmed and kept in place. Word-width on phones too, so they sit side by side | | `ChoiceBar` | The row those menus sit in, with any tabs beside them. Every page uses it, so the spacing between choices stays the same everywhere | -| `Pager` | Previous and next under a paged list; `param`: its address key | +| `Pager` | Page links under a paged list; `param`: its address key. Holds its widest row, so turning pages never moves it | | `DividedList`, `DividedSection` | Rows with lines between them, and a part set off by a line above, inside a `Card` or `Dialog`. The lines run to the surface's edges | | `StepChart` | A value that changes in steps over time (WR history). Hover snaps a crosshair to the nearest point; points take focus and open their link | -| `LineChart` | One count over time from zero (players online). Drawn in a fixed box stretched by CSS, so it fills its container before scripts load. Hover, tap or arrow keys pick a point; the parent shows its values. An optional second line (`y2`, gold) shows a part of the first on the same scale (world records among runs). Never two scales on one chart | -| `TierSpread` | How many maps hold each tier: a donut in tier colors beside each tier's count and share; each slice and row links to that tier's maps, the others dim, and "All" closes the list (Maps page) | -| `Tooltip` | Hint on hover and focus; the child must be focusable | +| `LineChart` | One count over time from zero (players online). CSS-stretched, so it fills its box before scripts load. Hover, tap or arrow keys pick a point; the parent shows its values. An optional second line (`y2`, gold) shows a part of the first on the same scale (world records among runs). Never two scales on one chart | +| `TierSpread` | Maps per tier: a donut beside each tier's count and share; slices and rows link to that tier's maps, the rest dim; "All tiers" goes back (Maps page) | +| `Dot` | "·" in a wrapping line; hidden on phones, where it could end one | +| `Tooltip` | Hint on hover and focus; child takes focus | | `Menu`, `MenuItem`, `MenuLink`, `MenuSeparator` | Menu button (account; `sheet`: phone menu) | -| `Dialog` | Controlled modal (`open`, `onClose`). A field marked `data-autofocus` takes focus on each opening (React's `autoFocus` fires only on mount). Closes itself, without calling `onClose`, when its page is hidden for Back | +| `Dialog` | Controlled modal (`open`, `onClose`). A field marked `data-autofocus` takes focus on each opening, not just the first. Closes itself, without calling `onClose`, when its page is hidden for Back | | `BrandIcon`, `SteamButton` | Community and Steam logos (`colored`: in their own colors); Steam sign-in | | `Input`, `SearchField`, `Textarea`, `CountUp` | Text field with optional icon; search, button inside; multi-line field; animated number | | `Prose` | Long-form HTML (a post's body) in the site's type. Only for HTML the API made safe | -The run dialog opens in place: `RunLink` adds `?run=` to the address with `history.pushState`, and `RunDialogHost` (in the root layout) opens at once and loads the run inside. Back or Escape closes it, and the address can be shared. A run link's `href` is `/runs/{id}`, the run's own page, for new tabs. A map page's style and track work the same way, with `replaceState`. +The run dialog opens in place: `RunLink` pushes `?run=` to the address and `RunDialogHost` (root layout) loads the run. Back or Escape closes it; the address can be shared. A run link's `href` is `/runs/{id}`, the run's own page, for new tabs. A map page's style and track work the same way, with `replaceState`. A `className` passed to a primitive is for placement (margin, width, grid), not restyling. Domain components (`RunRow`, `RunDialog`, …) live in `src/features//` and are built from these. @@ -64,7 +65,7 @@ Named utilities, so pages never write their own transitions: - `motion-draw`: an SVG line drawing itself in (a run's route); the shape needs `pathLength="1"`. - `motion-reveal`: a section rising in as it scrolls into view (scroll-driven; browsers without it show it at once). - `motion-settle`: a large picture easing out of a slight zoom as the page opens (the home header). -- `HeaderDepth` (`features/home/`): the home header's picture leans with the mouse, by a depth map of it (`scripts/header-depth.py`; rerun it when the picture changes). Dust drifts in the light shaft, and a click sends cyan traces crawling over the surfaces (`headerTraces.ts`). WebGL, running only while the header is on screen; off on touch screens and with reduced motion. +- `HeaderDepth` (`features/home/`): the home header's picture leans with the mouse, by a depth map of it (`scripts/header-depth.py`; rerun it when the picture changes). Dust drifts in the light shaft, and a click sends cyan traces crawling over the surfaces (`headerTraces.ts`). WebGL, only while on screen; off on touch screens and with reduced motion. The buttons above it get their own layer (`will-change-transform`): without it GPU Chromium dropped a hover's color after a frame. - `motion-pop`: a menu fading in with a slight drop and grow (`Menu`); `motion-fade`: its `sheet`'s dim. - `CountUp`: counts up when scrolled into view, and from the old value when it changes. A number already in view when the page loads stays as it is. - `page-fade`: between pages (see Navigation). @@ -72,12 +73,12 @@ Named utilities, so pages never write their own transitions: All of them respect `prefers-reduced-motion` and show their end state at once. ## Navigation -Pages swap in place with no full page load. The old page fades out quickly and the new one fades in, using React's `` in `Page` and the `page-fade` rules in `motion.css`. The header has its own view-transition name, so it stays still during the fade. Browsers without view transitions swap pages without the fade. A page with views, such as a map and its Manage view, keeps its header in a route layout and wraps each view in `PageView`: switching views fades the old one out and lifts the new one in (`view-flip`), and the header stays. +Pages swap in place: the old page fades out and the new one in (React's `` in `Page`, `page-fade` in `motion.css`); the header has its own transition name, so it stays still. Without view transitions, pages just swap. A page with views (a map and its Manage view) keeps its header in a route layout and wraps each view in `PageView`, which fades one out and lifts the next in (`view-flip`). Links never prefetch, whether in view or hovered (lead's choice, 2026-10-19). A page loads only once it's opened, and the fade covers the wait. `e2e/navigation.e2e.ts` checks that following a link doesn't reload the page. ## Layout shell (`web/src/features/site/`) -Header, page and footer sit on the sheet. The header is one sticky bar: wordmark, sections, search (`/`), Steam sign-in; footer: one line, community logos. Phones: menu, wordmark, search, account. Account and current section sit in ``, so every shell stays static. Search lives on the Players page. Section pages arrive with their roadmap slices. +Header, page and footer sit on the sheet. The header is one sticky bar: wordmark, sections, search (`/`), Steam sign-in; footer: one line, community logos. Phones: menu, wordmark, search, account. Account and current section sit in ``, so every shell stays static. Search lives on the Players page. ## Screenshot tests `npm run test:ui` (part of `just check`) screenshots `/dev/ui` wide, on a phone, with the menu open and with the dialog open, and fails on any pixel change. After an intended visual change: diff --git a/docs/plans/web-redesign-api.md b/docs/plans/web-redesign-api.md new file mode 100644 index 0000000..5accce0 --- /dev/null +++ b/docs/plans/web-redesign-api.md @@ -0,0 +1,50 @@ +# Web redesign: what the API side needs (plan) + +Temporary. What the November 2026 web redesign (branch `feat/mobile-profile-polish`) leaves for the lead on the API +side, and the shortcuts the web takes until then. Delete each item once it's done, and the file when it's empty. + +## To merge and deploy + +- **PR #16** (`api/profile-and-flags`): player avatars (`GET /v1/players/{player}/avatar`), a player's country from + the game server that saw them (migration `0052`), the true peak of players online (`0053`), and a personal best's + tier. The web already uses all four: against beta, avatars 404 and profile tier badges are missing until it ships. +- **Migration numbers:** PR #16 holds `0052` and `0053`. akanora's #26 also chose `0052`; on the integration branch + it is `0054`, after #16's. Merge #16 first. If #26 is merged upstream on its own as `0052`, #16's two must be + renumbered after it (sqlx rejects a reused version with different content). +- **akanora's PRs #24–#29** (sourcejump/sourcejump), on local branch `integrate/akanora-prs`, one cherry-pick each + with his authorship, then fixes, then one regenerated spec/types/query cache (commits before it don't build with + `SQLX_OFFLINE=true`, so it ships whole). `just check` passed (303 Rust tests, web tests) bar the screenshots. + - #27 Windows build, as submitted. #29 link previews and an error page, as submitted; previews checked. + - #26 one `current_map_tiers` view for the tier in force; also used by the three copies added since it branched. + Checked equal to the old lookup on every map and track, untiered ones included. + - #24 `GET /v1/maps/{map}/personal-bests?players=` (1–64 SteamID64s): each player's PB and rank on every board + of a map, in one request on map change. Changed to require a server key (401 first), and the 64 limit is + checked while parsing. **The plugin must send `Authorization` on it.** + - #28 sign out everywhere: same Origin check as sign-out, ends only that player's sessions. Changed to answer 401 + with no live session, rather than 303 as if it had worked. + - #25 your own place pinned under a map board's top: needs a signed-in check in a browser, not done yet. + +## API additions the web would use + +- **Personal bests in place order:** a profile now opens best place first. The API pages personal bests by map + only, so the web loads every page of a style's 2.0 list on open, 100 a request (shortcut in `PlayerStyles.tsx`). + A `sort=place` option on `GET /v1/players/{player}/personal-bests` would end that. Pre-2.0 views keep map order, + since legacy runs have no place. +- **One record per board:** home's "Latest world records" fetches 100 records to find 8 boards (shortcut in + `LiveNow.tsx`). A `distinct` option on `GET /v1/runs?records=true` would make it exact. +- **Map boards sorted by more than time:** sorting a map leaderboard by jumps, sync or date loads the whole board + (shortcut in `Leaderboard.tsx`). A `sort` parameter would serve boards with thousands of runs. + +## Open questions for the lead + +- **Style order:** the Style menus list Autosync right after Normal, a display order in the web + (`features/ruleset/menuOrder.ts`); the ruleset and the Ruleset page keep the ruleset's order. If the community + wants that to be the ruleset's own order, that's a ruleset migration, and `menuOrder` can go. + +## Practices the redesign settled + +- One font, Geist (450 and 700), with Exo 2 bold for server names only (the `font-server` token). +- Phone tables: `Table phoneLead` with a `phoneFill` column sizes the first view to end at the ranked column; + `Pager` reserves its widest row so turning a page never moves it (`design-system.md`). +- A board's first record shows "(NEW)" where other records show what they took off: `RecentRun.gap` is null only + for a board's first run, so the API's meaning of a null gap must stay that. diff --git a/docs/site-api.md b/docs/site-api.md index e8a8454..e690e50 100644 --- a/docs/site-api.md +++ b/docs/site-api.md @@ -1,12 +1,12 @@ # Site API -The website's endpoints; staff tools: `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, or Next.js locally). +Players sign in with Steam (OpenID 2.0); the endpoints answer browsers (redirects, cookies) via the site's origin. - 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 its SHA-256 is stored. It lasts 30 days from last use (expiry moves at most daily). -- Sign-out also needs our `Origin` header; a missing session gets `401` without `WWW-Authenticate`. +- 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 diff --git a/web/e2e/style-guide.e2e.ts-snapshots/desktop-chrome-linux.png b/web/e2e/style-guide.e2e.ts-snapshots/desktop-chrome-linux.png index 0b4e21e..a5a97a4 100644 Binary files a/web/e2e/style-guide.e2e.ts-snapshots/desktop-chrome-linux.png and b/web/e2e/style-guide.e2e.ts-snapshots/desktop-chrome-linux.png differ diff --git a/web/e2e/style-guide.e2e.ts-snapshots/dialog-chrome-linux.png b/web/e2e/style-guide.e2e.ts-snapshots/dialog-chrome-linux.png index cfe6776..da59c31 100644 Binary files a/web/e2e/style-guide.e2e.ts-snapshots/dialog-chrome-linux.png and b/web/e2e/style-guide.e2e.ts-snapshots/dialog-chrome-linux.png differ diff --git a/web/e2e/style-guide.e2e.ts-snapshots/menu-chrome-linux.png b/web/e2e/style-guide.e2e.ts-snapshots/menu-chrome-linux.png index df5e79e..20dde9a 100644 Binary files a/web/e2e/style-guide.e2e.ts-snapshots/menu-chrome-linux.png and b/web/e2e/style-guide.e2e.ts-snapshots/menu-chrome-linux.png differ diff --git a/web/e2e/style-guide.e2e.ts-snapshots/phone-chrome-linux.png b/web/e2e/style-guide.e2e.ts-snapshots/phone-chrome-linux.png index eb49329..e7e25be 100644 Binary files a/web/e2e/style-guide.e2e.ts-snapshots/phone-chrome-linux.png and b/web/e2e/style-guide.e2e.ts-snapshots/phone-chrome-linux.png differ diff --git a/web/src/api/schema.ts b/web/src/api/schema.ts index c54cb25..12fbab9 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; @@ -2366,6 +2407,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"][]; @@ -2495,6 +2560,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; @@ -3630,6 +3703,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?: { @@ -3989,6 +4101,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?: { diff --git a/web/src/app/dev/ui/page.tsx b/web/src/app/dev/ui/page.tsx index 4b8abe0..3c14e9c 100644 --- a/web/src/app/dev/ui/page.tsx +++ b/web/src/app/dev/ui/page.tsx @@ -146,7 +146,8 @@ export default function StyleGuidePage() {

- Play for everything. Its digits share one width, so times line up: + Geist for everything; times and tables use its equal-width digits, so + they line up:

{typeScale.map(([name, className]) => ( 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/globals.css b/web/src/app/globals.css index 3fc3984..36e617d 100644 --- a/web/src/app/globals.css +++ b/web/src/app/globals.css @@ -4,6 +4,17 @@ @import "../ui/motion.css"; @layer base { + /* Taps show the site's own pressed and hover states, not the browser's grey flash, and act without the + double-tap zoom delay. */ + html { + -webkit-tap-highlight-color: transparent; + } + a, + button, + [role="button"] { + touch-action: manipulation; + } + /* Tailwind leaves buttons with the default arrow; everything clickable here shows the hand. */ button:not(:disabled), [role="button"]:not([aria-disabled="true"]), @@ -17,11 +28,13 @@ background: var(--color-gutter); color: var(--color-text); font-family: var(--font-sans); + font-weight: var(--font-weight-normal); font-size: var(--text-base); line-height: var(--text-base--line-height); } - /* Play's figures are already equal width; this keeps times aligned if a fallback font is in use. */ + /* Geist's figures differ in width; times and table cells take its equal-width ones so columns line up. Elsewhere + they stay proportional, which is as wide as Play's were. */ time, td { font-variant-numeric: tabular-nums; diff --git a/web/src/app/layout.tsx b/web/src/app/layout.tsx index cc3b04a..25cf7a7 100644 --- a/web/src/app/layout.tsx +++ b/web/src/app/layout.tsx @@ -1,7 +1,7 @@ // Root layout: fonts, global styles, the header and footer, the run dialog, and site-wide metadata. import type { Metadata } from "next"; import Image from "next/image"; -import { Play } from "next/font/google"; +import { Exo_2, Geist } from "next/font/google"; import { Suspense } from "react"; import art from "@/features/site/header-interloper.webp"; import { RunDialogHost } from "@/features/runs/RunDialogHost"; @@ -10,9 +10,15 @@ import { SiteHeader } from "@/features/site/SiteHeader"; import { NavigationProgress } from "@/ui/NavigationProgress"; import "./globals.css"; -const play = Play({ - variable: "--font-play", - weight: ["400", "700"], +// A variable font, so the in-between weights the type tokens use (tokens.css) load in the one file. +const geist = Geist({ + variable: "--font-geist", + subsets: ["latin", "latin-ext", "cyrillic"], +}); +// Game servers' names (the `font-server` token): a bold face with more character than Geist, in its one weight. +const exo = Exo_2({ + variable: "--font-exo", + weight: "700", subsets: ["latin", "latin-ext", "cyrillic"], }); @@ -27,7 +33,10 @@ export const instant = false; export default function RootLayout({ children }: LayoutProps<"/">) { return ( - + {/* What shows in the gutters either side of the sheet: the header's map picture, blurred and darkened 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/players/[steamid]/page.tsx b/web/src/app/players/[steamid]/page.tsx index 7996c7d..8f5587d 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/players/page.tsx b/web/src/app/players/page.tsx index 6ee8c31..be0fb66 100644 --- a/web/src/app/players/page.tsx +++ b/web/src/app/players/page.tsx @@ -38,7 +38,10 @@ export default function PlayersPage({ searchParams }: PageProps<"/players">) {
} /> - + {/* A separate thing from the list above it, so a step further off than the page's usual gap; gone with no chart. */} +
+ +
); })} 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/activity/RecentRunTable.tsx b/web/src/features/activity/RecentRunTable.tsx index c1c72bb..7f12f89 100644 --- a/web/src/features/activity/RecentRunTable.tsx +++ b/web/src/features/activity/RecentRunTable.tsx @@ -308,9 +308,8 @@ export function RecentRunTable({ > {formatTime(run.time)} - {run.gap != null && ( - - )} + {/* No gap: the board's first run, a record that beat nothing. */} +
@@ -410,9 +409,8 @@ export function RecentRunTable({ {formatTime(run.time)} {/* Against the record when the run finished: what a new WR took off, or how far behind it was. */} - {run.gap != null && ( - - )} + {/* No gap: the board's first run, a record that beat nothing. */} + {/* Counted from now, which differs between the server's render and the browser's. */}