diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..a772311 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,3 @@ +# Every text file is LF in the working tree too, on any OS and whatever core.autocrlf says: the doc budget, +# Prettier and the committed OpenAPI spec compare bytes, and checked-out CRLF made them fail on Windows. +* text=auto eol=lf diff --git a/api/.sqlx/query-3b66a34af765c0b490013bfc8378b7d50cff03772f620d213bb0983c9405c40b.json b/api/.sqlx/query-3b66a34af765c0b490013bfc8378b7d50cff03772f620d213bb0983c9405c40b.json new file mode 100644 index 0000000..ccb1ae4 --- /dev/null +++ b/api/.sqlx/query-3b66a34af765c0b490013bfc8378b7d50cff03772f620d213bb0983c9405c40b.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM map_cards WHERE map_id = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Int8" + ] + }, + "nullable": [] + }, + "hash": "3b66a34af765c0b490013bfc8378b7d50cff03772f620d213bb0983c9405c40b" +} diff --git a/api/.sqlx/query-4d51428dd0d449fca9ffbd5f4b4d7282d57807a6e359d484401c6b20a4a9ab7d.json b/api/.sqlx/query-4d51428dd0d449fca9ffbd5f4b4d7282d57807a6e359d484401c6b20a4a9ab7d.json new file mode 100644 index 0000000..7b7d4b1 --- /dev/null +++ b/api/.sqlx/query-4d51428dd0d449fca9ffbd5f4b4d7282d57807a6e359d484401c6b20a4a9ab7d.json @@ -0,0 +1,86 @@ +{ + "db_name": "PostgreSQL", + "query": "\n SELECT m.id AS \"id!\", m.name AS \"name!\", i.key AS \"cover?\", t.tier AS \"tier?\", c.key AS \"card?\", c.made_from AS \"made_from?\"\n FROM maps m\n LEFT JOIN map_images i ON i.map_id = m.id AND i.position = 0\n LEFT JOIN current_map_tiers t ON t.map_id = m.id AND t.track = 0\n LEFT JOIN map_cards c ON c.map_id = m.id\n WHERE i.key IS NOT NULL OR c.map_id IS NOT NULL\n ", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id!", + "type_info": "Int8", + "origin": { + "Table": { + "table": "maps", + "name": "id" + } + } + }, + { + "ordinal": 1, + "name": "name!", + "type_info": "Text", + "origin": { + "Table": { + "table": "maps", + "name": "name" + } + } + }, + { + "ordinal": 2, + "name": "cover?", + "type_info": "Text", + "origin": { + "Table": { + "table": "map_images", + "name": "key" + } + } + }, + { + "ordinal": 3, + "name": "tier?", + "type_info": "Int2", + "origin": { + "Table": { + "table": "current_map_tiers", + "name": "tier" + } + } + }, + { + "ordinal": 4, + "name": "card?", + "type_info": "Text", + "origin": { + "Table": { + "table": "map_cards", + "name": "key" + } + } + }, + { + "ordinal": 5, + "name": "made_from?", + "type_info": "Text", + "origin": { + "Table": { + "table": "map_cards", + "name": "made_from" + } + } + } + ], + "parameters": { + "Left": [] + }, + "nullable": [ + true, + true, + true, + true, + false, + false + ] + }, + "hash": "4d51428dd0d449fca9ffbd5f4b4d7282d57807a6e359d484401c6b20a4a9ab7d" +} diff --git a/api/.sqlx/query-676619a6533392a7555d60a4b03c6ef5b08272252fc21ebf8a7e3bb712604e84.json b/api/.sqlx/query-6b63f952f79d6fbd02d80515bc721a8e25a5c4f20739438661fe00bcedbbce49.json similarity index 78% rename from api/.sqlx/query-676619a6533392a7555d60a4b03c6ef5b08272252fc21ebf8a7e3bb712604e84.json rename to api/.sqlx/query-6b63f952f79d6fbd02d80515bc721a8e25a5c4f20739438661fe00bcedbbce49.json index f2fc9ea..1da6bab 100644 --- a/api/.sqlx/query-676619a6533392a7555d60a4b03c6ef5b08272252fc21ebf8a7e3bb712604e84.json +++ b/api/.sqlx/query-6b63f952f79d6fbd02d80515bc721a8e25a5c4f20739438661fe00bcedbbce49.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "\n SELECT m.id, m.name, m.description, m.created_at, m.last_run_at, m.players,\n (SELECT count(*) FROM runs WHERE map_id = m.id AND invalidated_at IS NULL) AS \"runs!\"\n FROM maps m WHERE m.name = $1\n ", + "query": "\n SELECT m.id, m.name, m.description, m.created_at, m.last_run_at, m.players,\n (SELECT key FROM map_cards WHERE map_id = m.id) AS card_key,\n (SELECT count(*) FROM runs WHERE map_id = m.id AND invalidated_at IS NULL) AS \"runs!\"\n FROM maps m WHERE m.name = $1\n ", "describe": { "columns": [ { @@ -71,6 +71,12 @@ }, { "ordinal": 6, + "name": "card_key", + "type_info": "Text", + "origin": "Expression" + }, + { + "ordinal": 7, "name": "runs!", "type_info": "Int8", "origin": "Expression" @@ -88,8 +94,9 @@ false, true, false, + null, null ] }, - "hash": "676619a6533392a7555d60a4b03c6ef5b08272252fc21ebf8a7e3bb712604e84" + "hash": "6b63f952f79d6fbd02d80515bc721a8e25a5c4f20739438661fe00bcedbbce49" } diff --git a/api/.sqlx/query-2a38093fec6e9d0acd79a5b259840efd337e92717d9581aaa6ffab06b750704d.json b/api/.sqlx/query-91b58f8ef10a47005cc0b0c35ee66733d0a6e9298a9e7bbdcac70b2048a81488.json similarity index 89% rename from api/.sqlx/query-2a38093fec6e9d0acd79a5b259840efd337e92717d9581aaa6ffab06b750704d.json rename to api/.sqlx/query-91b58f8ef10a47005cc0b0c35ee66733d0a6e9298a9e7bbdcac70b2048a81488.json index f132edf..f910d7b 100644 --- a/api/.sqlx/query-2a38093fec6e9d0acd79a5b259840efd337e92717d9581aaa6ffab06b750704d.json +++ b/api/.sqlx/query-91b58f8ef10a47005cc0b0c35ee66733d0a6e9298a9e7bbdcac70b2048a81488.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 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 ", + "query": "\n SELECT r.id, r.map_id, m.name AS map, r.style, r.track, r.time, r.jumps, r.strafes, r.sync, r.perfs,\n r.avg_velocity, r.max_velocity, r.tickrate, r.finished_at, r.ruleset_version,\n r.invalidated_at IS NOT NULL AS \"invalidated!\", s.id AS server_id, s.name AS server_name,\n p.steamid64::text AS \"steamid64!\", p.name, p.avatar_url, p.country_code,\n EXISTS (SELECT 1 FROM personal_bests WHERE run_id = r.id) AS \"personal_best!\",\n (SELECT min(time) FROM personal_bests\n WHERE map_id = r.map_id AND style = r.style AND track = r.track) AS world_record_time,\n (SELECT tier FROM current_map_tiers WHERE map_id = r.map_id AND track = r.track) AS tier,\n ci.id AS \"image_id?\", ci.key AS \"image_key?\", ci.focus AS \"image_focus?\",\n (SELECT key FROM map_cards WHERE map_id = r.map_id) AS map_card_key,\n (SELECT host(h.ip) || ':' || h.port FROM server_heartbeats h\n JOIN server_listings l ON l.ip = h.ip AND l.port = h.port\n WHERE h.server_id = s.id ORDER BY h.received_at DESC LIMIT 1) AS server_address\n FROM runs r\n JOIN maps m ON m.id = r.map_id\n LEFT JOIN map_images ci ON ci.map_id = m.id AND ci.position = 0\n JOIN servers s ON s.id = r.server_id\n JOIN players p ON p.steamid64 = r.player_steamid64\n WHERE r.id = $1\n ", "describe": { "columns": [ { @@ -288,6 +288,12 @@ }, { "ordinal": 28, + "name": "map_card_key", + "type_info": "Text", + "origin": "Expression" + }, + { + "ordinal": 29, "name": "server_address", "type_info": "Text", "origin": "Expression" @@ -324,11 +330,12 @@ null, null, null, - true, - true, - true, + false, + false, + false, + null, null ] }, - "hash": "2a38093fec6e9d0acd79a5b259840efd337e92717d9581aaa6ffab06b750704d" + "hash": "91b58f8ef10a47005cc0b0c35ee66733d0a6e9298a9e7bbdcac70b2048a81488" } diff --git a/api/.sqlx/query-b65cb8b86e6d60caca640368f859f7e2d63c8f537445936874d29cc166c12b6e.json b/api/.sqlx/query-b65cb8b86e6d60caca640368f859f7e2d63c8f537445936874d29cc166c12b6e.json new file mode 100644 index 0000000..5ad3f22 --- /dev/null +++ b/api/.sqlx/query-b65cb8b86e6d60caca640368f859f7e2d63c8f537445936874d29cc166c12b6e.json @@ -0,0 +1,16 @@ +{ + "db_name": "PostgreSQL", + "query": "\n INSERT INTO map_cards (map_id, key, made_from) VALUES ($1, $2, $3)\n ON CONFLICT (map_id) DO UPDATE SET key = excluded.key, made_from = excluded.made_from, made_at = now()\n ", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Int8", + "Text", + "Text" + ] + }, + "nullable": [] + }, + "hash": "b65cb8b86e6d60caca640368f859f7e2d63c8f537445936874d29cc166c12b6e" +} diff --git a/api/.sqlx/query-94fc7bc47f40fce082f22ac4279c3ac1cfe1bb24e6c680cac989e733b98d2555.json b/api/.sqlx/query-dcb58271af8e4bd7cb98a4cbf285784d2d295afaa6ba7731b9ba1fe7e22e101d.json similarity index 55% rename from api/.sqlx/query-94fc7bc47f40fce082f22ac4279c3ac1cfe1bb24e6c680cac989e733b98d2555.json rename to api/.sqlx/query-dcb58271af8e4bd7cb98a4cbf285784d2d295afaa6ba7731b9ba1fe7e22e101d.json index 0543a93..4ad9d2e 100644 --- a/api/.sqlx/query-94fc7bc47f40fce082f22ac4279c3ac1cfe1bb24e6c680cac989e733b98d2555.json +++ b/api/.sqlx/query-dcb58271af8e4bd7cb98a4cbf285784d2d295afaa6ba7731b9ba1fe7e22e101d.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT document->'styles' @> jsonb_build_array(jsonb_build_object('key', $2::text)) AS \"ranked!\",\n (document->>'tickrate')::real AS tickrate\n FROM rulesets WHERE version = $1", + "query": "SELECT document->'styles' @> jsonb_build_array(jsonb_build_object('key', $2::text)) AS \"ranked!\",\n (document->>'tickrate')::real AS tickrate,\n GREATEST(published_at, (SELECT created_at FROM servers WHERE id = $3)) AS \"earliest!\"\n FROM rulesets WHERE version = $1", "describe": { "columns": [ { @@ -14,18 +14,26 @@ "name": "tickrate", "type_info": "Float4", "origin": "Expression" + }, + { + "ordinal": 2, + "name": "earliest!", + "type_info": "Timestamptz", + "origin": "Expression" } ], "parameters": { "Left": [ "Int4", - "Text" + "Text", + "Int8" ] }, "nullable": [ + null, null, null ] }, - "hash": "94fc7bc47f40fce082f22ac4279c3ac1cfe1bb24e6c680cac989e733b98d2555" + "hash": "dcb58271af8e4bd7cb98a4cbf285784d2d295afaa6ba7731b9ba1fe7e22e101d" } diff --git a/api/.sqlx/query-fcee15572f69a3e3be73825baaade8e35340f56f7b698f6a9eacd18a61dc092e.json b/api/.sqlx/query-fcee15572f69a3e3be73825baaade8e35340f56f7b698f6a9eacd18a61dc092e.json new file mode 100644 index 0000000..d038de9 --- /dev/null +++ b/api/.sqlx/query-fcee15572f69a3e3be73825baaade8e35340f56f7b698f6a9eacd18a61dc092e.json @@ -0,0 +1,23 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT set_config('lock_timeout', $1, true)", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "set_config", + "type_info": "Text", + "origin": "Expression" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + null + ] + }, + "hash": "fcee15572f69a3e3be73825baaade8e35340f56f7b698f6a9eacd18a61dc092e" +} diff --git a/api/Cargo.lock b/api/Cargo.lock index 3f8cdc9..0aa6ddc 100644 --- a/api/Cargo.lock +++ b/api/Cargo.lock @@ -2,6 +2,22 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "ab_glyph" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01c0457472c38ea5bd1c3b5ada5e368271cb550be7a4ca4a0b4634e9913f6cc2" +dependencies = [ + "ab_glyph_rasterizer", + "owned_ttf_parser", +] + +[[package]] +name = "ab_glyph_rasterizer" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "366ffbaa4442f4684d91e2cd7c5ea7c4ed8add41959a31447066e279e432b618" + [[package]] name = "adler2" version = "2.0.1" @@ -1424,6 +1440,15 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" +[[package]] +name = "owned_ttf_parser" +version = "0.25.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "36820e9051aca1014ddc75770aab4d68bc1e9e632f0f5627c4086bc216fb583b" +dependencies = [ + "ttf-parser", +] + [[package]] name = "parking" version = "2.2.1" @@ -2100,6 +2125,7 @@ dependencies = [ name = "sourcejump-api" version = "0.1.0" dependencies = [ + "ab_glyph", "axum", "axum-extra", "chrono", @@ -2632,6 +2658,12 @@ version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" +[[package]] +name = "ttf-parser" +version = "0.25.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31" + [[package]] name = "typenum" version = "1.20.1" diff --git a/api/crates/api/Cargo.toml b/api/crates/api/Cargo.toml index ffece1b..472c2f8 100644 --- a/api/crates/api/Cargo.toml +++ b/api/crates/api/Cargo.toml @@ -6,6 +6,7 @@ publish.workspace = true license.workspace = true [dependencies] +ab_glyph = "0.2.32" axum = "0.8.9" axum-extra = { version = "0.12.6", features = ["cookie"] } chrono = { version = "0.4.45", default-features = false, features = ["serde", "std"] } diff --git a/api/crates/api/assets/play/OFL.txt b/api/crates/api/assets/play/OFL.txt new file mode 100644 index 0000000..e265281 --- /dev/null +++ b/api/crates/api/assets/play/OFL.txt @@ -0,0 +1,93 @@ +Copyright (c) 2011, Jonas Hecksher, Playtypes, e-types AS (lasse@e-types.com), with Reserved Font Name 'Play', 'Playtype', 'Playtype Sans'. + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/api/crates/api/assets/play/Play-Bold.ttf b/api/crates/api/assets/play/Play-Bold.ttf new file mode 100644 index 0000000..f60bdd1 Binary files /dev/null and b/api/crates/api/assets/play/Play-Bold.ttf differ diff --git a/api/crates/api/assets/play/Play-Regular.ttf b/api/crates/api/assets/play/Play-Regular.ttf new file mode 100644 index 0000000..caaa68c Binary files /dev/null and b/api/crates/api/assets/play/Play-Regular.ttf differ diff --git a/api/crates/api/migrations/0055_map_cards.sql b/api/crates/api/migrations/0055_map_cards.sql new file mode 100644 index 0000000..458a034 --- /dev/null +++ b/api/crates/api/migrations/0055_map_cards.sql @@ -0,0 +1,31 @@ +-- Each map's link card: the picture link previews show for its page, drawn from its cover, name and tier +-- (`maps/card.rs`). A job keeps one card per map with a cover and deletes the one it replaces, so they never pile +-- up. No foreign key to maps, as with standings_boards: checking one locks the map's row, which the ingest can +-- hold for as long as a standings recount takes. +CREATE TABLE map_cards ( + map_id bigint PRIMARY KEY, + -- The stored JPEG, named by its content. + key text NOT NULL UNIQUE CHECK (key ~ '^maps/[a-z0-9_.-]+/card-[0-9a-f]{12}\.jpg$'), + -- What it was drawn from (design version, cover and tier); a card whose inputs changed is drawn again. + made_from text NOT NULL, + made_at timestamptz NOT NULL DEFAULT now() +); + +-- The job sleeps until a card may be out of date, and these wake it: a map's pictures change (the first is the +-- cover), a main track's tier is set, or a tier count is published. Triggers rather than calls in the code, so +-- every way of changing these (site, CLI, imports) wakes it. Postgres sends a notification only once its +-- transaction commits and merges identical ones within it; the job takes every waiting one per wake-up, so a +-- burst (a picture import) costs a pass or two. +CREATE FUNCTION map_cards_wake() RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN + PERFORM pg_notify('map_cards', ''); + RETURN NULL; +END +$$; + +CREATE TRIGGER map_images_wake_map_cards AFTER INSERT OR UPDATE OR DELETE ON map_images + FOR EACH STATEMENT EXECUTE FUNCTION map_cards_wake(); +CREATE TRIGGER map_tiers_wake_map_cards AFTER INSERT ON map_tiers + FOR EACH ROW WHEN (NEW.track = 0) EXECUTE FUNCTION map_cards_wake(); +CREATE TRIGGER policies_wake_map_cards AFTER INSERT ON policies + FOR EACH ROW WHEN (NEW.name = 'tiers') EXECUTE FUNCTION map_cards_wake(); diff --git a/api/crates/api/src/contract.rs b/api/crates/api/src/contract.rs index 0e7697c..33a5585 100644 --- a/api/crates/api/src/contract.rs +++ b/api/crates/api/src/contract.rs @@ -87,6 +87,8 @@ async fn examples_match_the_api(db: PgPool) { .await .unwrap(); let key = keys::issue(&db, "Example server").await.unwrap().key; + // The examples' runs carry fixed times. + crate::runs::tests::backdate(&db).await; for (name, text, check_response) in EXAMPLES { let example: Value = serde_json::from_str(text).unwrap(); diff --git a/api/crates/api/src/leaderboards/standings.rs b/api/crates/api/src/leaderboards/standings.rs index 92e2d72..0f2daeb 100644 --- a/api/crates/api/src/leaderboards/standings.rs +++ b/api/crates/api/src/leaderboards/standings.rs @@ -37,6 +37,12 @@ use crate::{ /// The advisory lock every recount holds: "standings" in ASCII. const LOCK: i64 = 0x7374_616e_6469_6e67; +/// How long the ingest waits for another recount to finish. A recount after a personal best takes milliseconds; +/// only a full one (a policy published, or a new formula after a deploy) takes seconds. Waiting behind that +/// would hold the map's row and one of the request pool's connections throughout, and every run arriving +/// meanwhile would do the same until the pool ran out and the whole site stalled. Past this the run gets a +/// 500, and its server sends it again later (`docs/api.md`). +const INGEST_LOCK_WAIT: &str = "2s"; /// How often `watch_ended_bans` looks. Looking costs a few index reads per records ban ever given. const ENDED_BANS_INTERVAL: Duration = Duration::from_mins(5); @@ -93,6 +99,20 @@ pub async fn refresh_runs(conn: &mut PgConnection, run_ids: &[i64]) -> Result<() refresh(conn, &boards, run_ids).await } +/// `refresh_runs` for a run the ingest just stored, giving up on the lock after `INGEST_LOCK_WAIT`. +/// +/// The limit lasts to the end of the ingest's transaction, which this ends: the recount waits for nothing +/// else, as only recounts write its tables and they take turns. +pub async fn refresh_stored_run(conn: &mut PgConnection, run_id: i64) -> Result<(), sqlx::Error> { + sqlx::query!( + "SELECT set_config('lock_timeout', $1, true)", + INGEST_LOCK_WAIT + ) + .fetch_one(&mut *conn) + .await?; + refresh_runs(conn, &[run_id]).await +} + /// After a track's tier changed: recounts its board in every style. pub async fn refresh_track( conn: &mut PgConnection, @@ -514,6 +534,39 @@ pub(crate) mod tests { assert_totals_current(&db).await; } + /// Behind a long recount, a new personal best gives up waiting instead of holding its connection: the + /// server gets a 500, nothing of the run is kept, and sending it again later stores and counts it once. + #[sqlx::test] + async fn the_ingest_gives_up_waiting_behind_a_long_recount(db: PgPool) { + let key = setup(&db).await; + test_client::post(&db, "/v1/runs", Some(&key), &run("a", 30.0)).await; + + let mut holder = db.begin().await.unwrap(); + super::lock(&mut holder).await.unwrap(); + let started = std::time::Instant::now(); + let refused = test_client::post(&db, "/v1/runs", Some(&key), &run("b", 29.0)).await; + assert_eq!(refused.status, 500, "a 5xx, which servers send again later"); + assert!( + started.elapsed() < Duration::from_secs(5), + "gave up after the wait" + ); + let kept: i64 = sqlx::query_scalar("SELECT count(*) FROM runs WHERE server_run_id = 'b'") + .fetch_one(&db) + .await + .unwrap(); + assert_eq!(kept, 0, "the run's transaction was rolled back"); + + holder.commit().await.unwrap(); + let stored = test_client::post(&db, "/v1/runs", Some(&key), &run("b", 29.0)).await; + assert_eq!(stored.status, 201); + let best: f64 = sqlx::query_scalar("SELECT time FROM personal_bests") + .fetch_one(&db) + .await + .unwrap(); + assert_eq!(best, 29.0); + assert_totals_current(&db).await; + } + /// A tier change waiting for the standings lock, then a full recount behind it. They once deadlocked, when /// recounts wrote personal bests. #[sqlx::test] diff --git a/api/crates/api/src/main.rs b/api/crates/api/src/main.rs index 7a069bf..adb6df6 100644 --- a/api/crates/api/src/main.rs +++ b/api/crates/api/src/main.rs @@ -67,7 +67,9 @@ usage: sourcejump-api [command] privileges revoke ... take them away again (logged) privileges list name every privilege legacy import replace the pre-2.0 records with the old site's dump, carrying its bans over (logged) - world-records rebuild recount the stored world records from the runs and say how many rows were wrong"; + world-records rebuild recount the stored world records from the runs and say how many rows were wrong + site-card draw the site's link card from a picture (web/src/features/home/header.png) into + a JPEG file (web/public/link-card.jpg)"; #[tokio::main] async fn main() -> Result<(), Box> { @@ -163,6 +165,7 @@ async fn main() -> Result<(), Box> { } ["legacy", "import", folder] => import_legacy(folder).await, ["world-records", "rebuild"] => rebuild_world_records().await, + ["site-card", picture, file] => draw_site_card(picture, file), ["help" | "--help"] => { println!("{USAGE}"); Ok(()) @@ -171,6 +174,13 @@ async fn main() -> Result<(), Box> { } } +fn draw_site_card(picture: &str, file: &str) -> Result<(), Box> { + let picture = std::fs::read(picture).map_err(|error| format!("{picture}: {error}"))?; + std::fs::write(file, maps::card::draw::site_card(&picture)?)?; + println!("Drew the site's link card into {file}."); + Ok(()) +} + async fn make_viewer_file(map: &str, file: &str) -> Result<(), Box> { let map = maps::MapName::try_from(map.to_owned())?; let (db, storage) = (connect().await?, storage::Storage::from_env()?); @@ -405,6 +415,7 @@ async fn serve() -> Result<(), Box> { staging.clone(), )); tokio::spawn(daily_totals::run(db.clone())); + tokio::spawn(maps::card::run(db.clone(), storage.clone())); tokio::spawn(leaderboards::standings::watch_ended_bans(db.clone())); tokio::spawn(record_events::run(db.clone())); tokio::spawn(servers::heartbeat::run(db.clone())); diff --git a/api/crates/api/src/maps.rs b/api/crates/api/src/maps.rs index 6e15a9e..aa8fdbb 100644 --- a/api/crates/api/src/maps.rs +++ b/api/crates/api/src/maps.rs @@ -1,6 +1,7 @@ //! Maps, identified by their lowercase name, and the map pages' endpoints: the map list, a map's details, //! its leaderboards and its WR history, each map's file for the web viewer, and the stock content it draws on. +pub mod card; mod detail; pub mod image; mod leaderboard; diff --git a/api/crates/api/src/maps/card.rs b/api/crates/api/src/maps/card.rs new file mode 100644 index 0000000..0b69ca4 --- /dev/null +++ b/api/crates/api/src/maps/card.rs @@ -0,0 +1,343 @@ +//! Maps' link cards (`map_cards`): the picture a link to a map or one of its runs shows on Discord and elsewhere. +//! `draw.rs` draws them; a job here keeps them current. +//! +//! A card is drawn from the map's cover, name and tier and nothing that changes often, so it stays right and +//! there is one per map, however many links are shared. The job draws a card when a map gets a cover, or its +//! cover or tier in force changes, and deletes the one it replaces; a map whose pictures are all removed loses +//! its card. It sleeps until triggers on those tables wake it (`migrations/0053_map_cards.sql`), then checks +//! every map in one small query and draws only what's out of date. Cards are stored like map pictures, under a name from their content, so caches keep them for good. +//! Pages without a card (maps without a cover, and every other page) show the site's card, which the web app +//! serves itself (`draw::site_card`). + +pub mod draw; + +use std::{collections::HashSet, fmt::Write, time::Duration}; + +use sha2::{Digest, Sha256}; +use sqlx::{PgPool, postgres::PgListener}; + +use super::{ + image::{LARGE, file_key}, + tiers, +}; +use crate::storage::Storage; + +/// The channel the triggers notify. +const CHANNEL: &str = "map_cards"; +/// A pass without a wake-up, for a notification lost while the listener reconnected. +const FALLBACK: Duration = Duration::from_hours(1); +const LISTEN_RETRY: Duration = Duration::from_secs(5); +/// Raise when `draw.rs` changes how cards look, so every card is drawn again. +const DESIGN: u32 = 1; + +/// Runs for as long as the API does. Reconnects on its own. +pub async fn run(db: PgPool, storage: Storage) { + // Cards that couldn't be drawn, by map and inputs, so a broken cover is reported once rather than on every + // pass; a new cover or tier tries again. + let mut failed = HashSet::new(); + loop { + if let Err(error) = listen(&db, &storage, &mut failed).await { + tracing::warn!(%error, "map card listener lost; reconnecting"); + } + tokio::time::sleep(LISTEN_RETRY).await; + } +} + +/// A pass, then another each time a trigger wakes it or the fallback runs out. +async fn listen( + db: &PgPool, + storage: &Storage, + failed: &mut HashSet<(i64, String)>, +) -> Result<(), sqlx::Error> { + let mut listener = PgListener::connect_with(db).await?; + listener.listen(CHANNEL).await?; + loop { + // The first pass covers whatever changed while nobody listened: at startup, or before a reconnect. + if let Err(error) = refresh(db, storage, failed).await { + tracing::error!(%error, "map card pass failed; trying again on the next change"); + } + if let Ok(woken) = tokio::time::timeout(FALLBACK, listener.recv()).await { + woken?; + } + // Changes that came in a burst are all covered by the next pass. + while listener.next_buffered().is_some() {} + } +} + +/// Draws every card that's missing or out of date, and removes those of maps without a cover. +pub async fn refresh( + db: &PgPool, + storage: &Storage, + failed: &mut HashSet<(i64, String)>, +) -> Result<(), sqlx::Error> { + // Tiers show only once the community has decided a count, as everywhere else. + let tier_count = tiers::tier_count(db).await?; + let maps = sqlx::query!( + r#" + SELECT m.id AS "id!", m.name AS "name!", i.key AS "cover?", t.tier AS "tier?", c.key AS "card?", c.made_from AS "made_from?" + FROM maps m + LEFT JOIN map_images i ON i.map_id = m.id AND i.position = 0 + LEFT JOIN current_map_tiers t ON t.map_id = m.id AND t.track = 0 + LEFT JOIN map_cards c ON c.map_id = m.id + WHERE i.key IS NOT NULL OR c.map_id IS NOT NULL + "# + ) + .fetch_all(db) + .await?; + + for map in maps { + let Some(cover) = map.cover else { + let card = map + .card + .expect("the query lists only maps with a cover or a card"); + remove(db, storage, map.id, &card).await?; + continue; + }; + let tier = map.tier.filter(|_| tier_count.is_some()); + let made_from = made_from(&cover, tier); + if map.made_from.as_deref() == Some(made_from.as_str()) { + continue; + } + let attempt = (map.id, made_from); + if failed.contains(&attempt) { + continue; + } + let made_from = &attempt.1; + match make(db, storage, map.id, &map.name, &cover, tier, made_from).await { + Ok(()) => { + if let Some(old) = map.card { + delete_file(storage, &old).await; + } + } + Err(error) => { + tracing::error!(map = %map.name, %error, "couldn't make the map's card"); + failed.insert(attempt); + } + } + } + Ok(()) +} + +/// What a card is drawn from, as stored in `map_cards.made_from`. +fn made_from(cover: &str, tier: Option) -> String { + let tier = tier.map_or_else(|| "-".to_owned(), |tier| tier.to_string()); + format!("{DESIGN}/{cover}/{tier}") +} + +/// Draws and stores a map's card and records it. Drawing takes a fraction of a second of CPU, so it runs off the +/// async threads. +async fn make( + db: &PgPool, + storage: &Storage, + map_id: i64, + name: &str, + cover: &str, + tier: Option, + made_from: &str, +) -> Result<(), String> { + let picture = storage + .get(&file_key(cover, LARGE)) + .await + .map_err(|error| format!("reading the cover: {error}"))?; + let card = { + let name = name.to_owned(); + tokio::task::spawn_blocking(move || draw::map_card(&picture, &name, tier)) + .await + .map_err(|error| format!("drawing: {error}"))?? + }; + let key = format!("maps/{name}/card-{}.jpg", short_hash(&card)); + storage + .put_immutable(&key, "image/jpeg", None, card) + .await + .map_err(|error| format!("storing: {error}"))?; + sqlx::query!( + r#" + INSERT INTO map_cards (map_id, key, made_from) VALUES ($1, $2, $3) + ON CONFLICT (map_id) DO UPDATE SET key = excluded.key, made_from = excluded.made_from, made_at = now() + "#, + map_id, + key, + made_from + ) + .execute(db) + .await + .map_err(|error| format!("recording: {error}"))?; + Ok(()) +} + +async fn remove( + db: &PgPool, + storage: &Storage, + map_id: i64, + card: &str, +) -> Result<(), sqlx::Error> { + sqlx::query!("DELETE FROM map_cards WHERE map_id = $1", map_id) + .execute(db) + .await?; + delete_file(storage, card).await; + Ok(()) +} + +/// Deletes a card's file once nothing points at it. A failure leaves an unused file behind, which costs little, +/// so it's logged rather than retried. +async fn delete_file(storage: &Storage, key: &str) { + if let Err(error) = storage.delete(key).await { + tracing::warn!(%key, %error, "couldn't delete a replaced map card"); + } +} + +/// The first 12 hex digits of the SHA-256, as map pictures are named. +fn short_hash(bytes: &[u8]) -> String { + let mut hash = String::with_capacity(12); + for byte in &Sha256::digest(bytes)[..6] { + write!(hash, "{byte:02x}").expect("writing to a String can't fail"); + } + hash +} + +#[cfg(test)] +mod tests { + use sqlx::PgPool; + + use super::*; + use crate::{ + maps::{MapName, image::tests::png}, + staff::{map_images, maps::set_tier}, + }; + + const MAP: &str = "bhop_fresh"; + + async fn card_of(db: &PgPool) -> Option<(String, String)> { + sqlx::query!("SELECT c.key, c.made_from FROM map_cards c JOIN maps m ON m.id = c.map_id") + .fetch_optional(db) + .await + .unwrap() + .map(|row| (row.key, row.made_from)) + } + + fn cards_stored(storage: &Storage) -> Vec { + let mut keys: Vec = storage + .objects + .lock() + .unwrap() + .keys() + .filter(|key| key.contains("/card-")) + .cloned() + .collect(); + keys.sort(); + keys + } + + #[sqlx::test] + async fn keeps_one_current_card_per_map_with_a_cover(db: PgPool) { + let storage = Storage::for_tests(); + let mut failed = HashSet::new(); + let map = MapName::try_from(MAP.to_owned()).unwrap(); + sqlx::query!("INSERT INTO maps (name) VALUES ($1)", MAP) + .execute(&db) + .await + .unwrap(); + + // No cover, no card. + refresh(&db, &storage, &mut failed).await.unwrap(); + assert_eq!(card_of(&db).await, None); + + let image = map_images::add_image(&db, &storage, None, &map, png(1920, 1080)) + .await + .unwrap(); + refresh(&db, &storage, &mut failed).await.unwrap(); + let (first, made_from) = card_of(&db).await.expect("a card for the cover"); + assert!( + made_from.ends_with("/-"), + "no tier while tiers aren't decided: {made_from}" + ); + assert_eq!(cards_stored(&storage), std::slice::from_ref(&first)); + + // A tier is published and set. + sqlx::query!( + r#"INSERT INTO policies (name, version, value) VALUES ('tiers', 1, '{"count": 6}')"# + ) + .execute(&db) + .await + .unwrap(); + set_tier(&db, None, &map, 0, 3).await.unwrap(); + refresh(&db, &storage, &mut failed).await.unwrap(); + let (second, made_from) = card_of(&db).await.unwrap(); + assert!(made_from.ends_with("/3"), "{made_from}"); + assert_ne!(second, first); + assert_eq!( + cards_stored(&storage), + [second], + "the replaced card is deleted" + ); + + // Nothing changed: nothing drawn. + refresh(&db, &storage, &mut failed).await.unwrap(); + assert_eq!(cards_stored(&storage).len(), 1); + + map_images::remove_image(&db, &storage, None, &map, image) + .await + .unwrap(); + refresh(&db, &storage, &mut failed).await.unwrap(); + assert_eq!(card_of(&db).await, None); + assert_eq!(cards_stored(&storage), Vec::::new()); + } + + #[sqlx::test] + async fn a_cover_that_cant_be_drawn_is_tried_once(db: PgPool) { + let storage = Storage::for_tests(); + let mut failed = HashSet::new(); + let map = MapName::try_from(MAP.to_owned()).unwrap(); + sqlx::query!("INSERT INTO maps (name) VALUES ($1)", MAP) + .execute(&db) + .await + .unwrap(); + let image = map_images::add_image(&db, &storage, None, &map, png(1920, 1080)) + .await + .unwrap(); + let key = sqlx::query_scalar!("SELECT key FROM map_images WHERE id = $1", image) + .fetch_one(&db) + .await + .unwrap(); + storage + .objects + .lock() + .unwrap() + .insert(file_key(&key, LARGE), b"damaged".to_vec()); + + refresh(&db, &storage, &mut failed).await.unwrap(); + assert_eq!(card_of(&db).await, None); + assert_eq!(failed.len(), 1); + } + + #[sqlx::test] + async fn cover_and_tier_changes_wake_the_job(db: PgPool) { + let storage = Storage::for_tests(); + let map = MapName::try_from(MAP.to_owned()).unwrap(); + sqlx::query!("INSERT INTO maps (name) VALUES ($1)", MAP) + .execute(&db) + .await + .unwrap(); + let mut listener = PgListener::connect_with(&db).await.unwrap(); + listener.listen(CHANNEL).await.unwrap(); + let mut woken = async || { + tokio::time::timeout(Duration::from_secs(5), listener.recv()) + .await + .is_ok() + }; + + map_images::add_image(&db, &storage, None, &map, png(1920, 1080)) + .await + .unwrap(); + assert!(woken().await, "a new cover"); + sqlx::query!( + r#"INSERT INTO policies (name, version, value) VALUES ('tiers', 1, '{"count": 6}')"# + ) + .execute(&db) + .await + .unwrap(); + assert!(woken().await, "a tier count"); + set_tier(&db, None, &map, 0, 3).await.unwrap(); + assert!(woken().await, "a main track's tier"); + } +} diff --git a/api/crates/api/src/maps/card/draw.rs b/api/crates/api/src/maps/card/draw.rs new file mode 100644 index 0000000..bed4e0f --- /dev/null +++ b/api/crates/api/src/maps/card/draw.rs @@ -0,0 +1,369 @@ +//! Drawing link cards: the 1200×630 pictures that link previews (Discord, Steam, X) show for a page. A map's card +//! is its cover with the SourceJump wordmark, the map's tier icon and its name; the site's card, used where a page +//! has no picture of its own, is the home page's header picture with the wordmark and the site's description. +//! +//! Text is set in Play, the site's font (`assets/play/`, SIL Open Font License), so cards match the pages. +//! Cards are JPEG rather than the WebP the map pictures use: some link previewers still don't show WebP. + +// Pixel positions move between whole and fractional numbers here; all of them are a few thousand at most, far +// inside what f32 holds exactly, and the drawing code skips any that land off the card. +#![allow( + clippy::cast_precision_loss, + clippy::cast_possible_truncation, + clippy::cast_sign_loss +)] + +use std::{io::Cursor, sync::LazyLock}; + +use ab_glyph::{Font, FontRef, Glyph, PxScale, ScaleFont, point}; +use image::{ImageReader, RgbImage, RgbaImage, codecs::jpeg::JpegEncoder, imageops::FilterType}; + +/// Open Graph's recommended size; Discord and X show it without cropping. +pub const SIZE: (u32, u32) = (1200, 630); +/// JPEG quality, 0–100. 85 keeps the text's edges clean at around 60–90 KB a card. +const QUALITY: u8 = 85; + +/// The site's colours (`web/src/ui/tokens.css`): the page background, text, muted text and accent. +const BACKGROUND: [u8; 3] = [0x0e, 0x16, 0x22]; +const TEXT: [u8; 3] = [0xe3, 0xea, 0xf3]; +const TEXT_SOFT: [u8; 3] = [0xc4, 0xd0, 0xe0]; +const ACCENT: [u8; 3] = [0x00, 0xc8, 0xf0]; + +/// The space between the card's edge and its text, as on the site's pages at their widest. +const MARGIN: f32 = 64.0; + +static BOLD: LazyLock> = LazyLock::new(|| { + FontRef::try_from_slice(include_bytes!("../../../assets/play/Play-Bold.ttf")) + .expect("the bundled font is valid") +}); +static REGULAR: LazyLock> = LazyLock::new(|| { + FontRef::try_from_slice(include_bytes!("../../../assets/play/Play-Regular.ttf")) + .expect("the bundled font is valid") +}); + +/// The tier icons the Discord record feed shows (`scripts/tier-icons.py`), shared so a map's tier looks the same +/// in a record post and in a link to the map. Index is the tier. +const TIER_ICONS: [&[u8]; 11] = [ + include_bytes!("../../../../../../web/public/tiers/t0.png"), + include_bytes!("../../../../../../web/public/tiers/t1.png"), + include_bytes!("../../../../../../web/public/tiers/t2.png"), + include_bytes!("../../../../../../web/public/tiers/t3.png"), + include_bytes!("../../../../../../web/public/tiers/t4.png"), + include_bytes!("../../../../../../web/public/tiers/t5.png"), + include_bytes!("../../../../../../web/public/tiers/t6.png"), + include_bytes!("../../../../../../web/public/tiers/t7.png"), + include_bytes!("../../../../../../web/public/tiers/t8.png"), + include_bytes!("../../../../../../web/public/tiers/t9.png"), + include_bytes!("../../../../../../web/public/tiers/t10.png"), +]; +const TIER_ICON_SIZE: u32 = 112; + +/// The site's description, as the web app's root layout gives it. +const SITE_DESCRIPTION: &str = "Global records for the Counter-Strike: Source bunnyhop community."; + +/// A map's card: the cover (a stored map picture), the wordmark, the tier icon when there is a tier to show, and +/// the name. A tier without an icon (above 10) is left out rather than drawn some other way. +pub fn map_card(cover: &[u8], name: &str, tier: Option) -> Result, String> { + let mut card = background(cover)?; + // Darkened at the top for the wordmark and more at the bottom for the name, so both read on a bright cover. + shade_down( + &mut card, + &[ + (0.0, 0.82), + (0.30, 0.0), + (0.45, 0.0), + (0.72, 0.78), + (1.0, 0.96), + ], + ); + wordmark(&mut card, 34.0, MARGIN, 52.0); + + let center = SIZE.1 as f32 - 58.0 - TIER_ICON_SIZE as f32 / 2.0; + let mut left = MARGIN; + if let Some(icon) = tier.and_then(|tier| TIER_ICONS.get(usize::try_from(tier).ok()?)) { + let icon = image::load_from_memory(icon) + .expect("the bundled tier icons are valid") + .to_rgba8(); + let icon = + image::imageops::resize(&icon, TIER_ICON_SIZE, TIER_ICON_SIZE, FilterType::Lanczos3); + overlay( + &mut card, + &icon, + left as i64, + (center - TIER_ICON_SIZE as f32 / 2.0) as i64, + ); + left += TIER_ICON_SIZE as f32 + 28.0; + } + let (px, name) = fit(&BOLD, name, SIZE.0 as f32 - MARGIN - left); + let line = Line::new(&BOLD, px, 0.0, &name); + line.draw(&mut card, left, line.baseline_centered_on(center), |_| TEXT); + encode(&card) +} + +/// The site's card, for pages without a picture of their own: the given picture (the home page's header) with +/// the wordmark and the site's description over a shade from the left. Made once with the API's `site-card` +/// command and committed to the web app. +pub fn site_card(picture: &[u8]) -> Result, String> { + let mut card = background(picture)?; + shade_across(&mut card, &[(0.0, 0.82), (0.45, 0.35), (0.70, 0.0)]); + let description = Line::new(®ULAR, 30.0, 0.0, SITE_DESCRIPTION); + let description_baseline = SIZE.1 as f32 - 72.0; + description.draw(&mut card, MARGIN, description_baseline, |_| TEXT_SOFT); + wordmark(&mut card, 72.0, MARGIN, description_baseline - 160.0); + encode(&card) +} + +/// "SOURCEJUMP" in the header's style: bold capitals spaced a tenth of their size apart, "JUMP" in the accent. +/// `top` is where the capitals start. +fn wordmark(card: &mut RgbImage, px: f32, left: f32, top: f32) { + let line = Line::new(&BOLD, px, px * 0.1, "SOURCEJUMP"); + let baseline = top + line.cap_height(); + line.draw( + card, + left, + baseline, + |index| if index < 6 { TEXT } else { ACCENT }, + ); +} + +/// The largest size from 84 px down to 52 px at which the name fits in `width`; a name too long even then is +/// cut short with an ellipsis. +fn fit(font: &FontRef<'static>, name: &str, width: f32) -> (f32, String) { + const LARGEST: f32 = 84.0; + const SMALLEST: f32 = 52.0; + let mut px = LARGEST; + while px > SMALLEST && Line::new(font, px, 0.0, name).width > width { + px -= 2.0; + } + if Line::new(font, px, 0.0, name).width <= width { + return (px, name.to_owned()); + } + let mut kept: Vec = name.chars().collect(); + while !kept.is_empty() { + kept.pop(); + let shortened: String = kept.iter().chain(['…'].iter()).collect(); + if Line::new(font, px, 0.0, &shortened).width <= width { + return (px, shortened); + } + } + (px, "…".to_owned()) +} + +/// One line of text, laid out with the font's kerning and extra `spacing` between letters. +struct Line<'a> { + font: &'a FontRef<'static>, + px: f32, + glyphs: Vec, + width: f32, +} + +impl<'a> Line<'a> { + fn new(font: &'a FontRef<'static>, px: f32, spacing: f32, text: &str) -> Self { + let scaled = font.as_scaled(PxScale::from(px)); + let mut glyphs = Vec::new(); + let mut x = 0.0; + let mut previous = None; + for character in text.chars() { + let id = font.glyph_id(character); + if let Some(previous) = previous { + x += scaled.kern(previous, id) + spacing; + } + glyphs.push(id.with_scale_and_position(px, point(x, 0.0))); + x += scaled.h_advance(id); + previous = Some(id); + } + Self { + font, + px, + glyphs, + width: x, + } + } + + /// How far capitals reach above the baseline. + fn cap_height(&self) -> f32 { + let scaled = self.font.as_scaled(PxScale::from(self.px)); + let h = self.font.glyph_id('H'); + scaled + .outline_glyph(h.with_scale(self.px)) + .map_or(scaled.ascent(), |outline| -outline.px_bounds().min.y) + } + + /// The baseline that centres the line's capitals and lowercase on `center`: halfway up the x-height reads as + /// the middle of a lowercase map name better than the middle of the font's whole ascent and descent. + fn baseline_centered_on(&self, center: f32) -> f32 { + let scaled = self.font.as_scaled(PxScale::from(self.px)); + let x_height = scaled + .outline_glyph(self.font.glyph_id('x').with_scale(self.px)) + .map_or(self.cap_height() * 0.7, |outline| { + -outline.px_bounds().min.y + }); + center + (self.cap_height() + x_height) / 4.0 + } + + /// Draws the line with its left edge at `left` and its baseline at `baseline`; `color` picks each letter's + /// colour by its index. + fn draw( + &self, + card: &mut RgbImage, + left: f32, + baseline: f32, + color: impl Fn(usize) -> [u8; 3], + ) { + for (index, glyph) in self.glyphs.iter().enumerate() { + let mut glyph = glyph.clone(); + glyph.position = point(glyph.position.x + left, glyph.position.y + baseline); + let Some(outline) = self.font.outline_glyph(glyph) else { + continue; // a space + }; + let bounds = outline.px_bounds(); + let rgb = color(index); + outline.draw(|x, y, coverage| { + let x = bounds.min.x as i64 + i64::from(x); + let y = bounds.min.y as i64 + i64::from(y); + blend(card, x, y, rgb, coverage.min(1.0)); + }); + } + } +} + +/// The picture scaled and cropped around its centre to fill the card. +fn background(picture: &[u8]) -> Result { + let decoded = ImageReader::new(Cursor::new(picture)) + .with_guessed_format() + .map_err(|_| "the picture couldn't be read".to_owned())? + .decode() + .map_err(|error| format!("the picture couldn't be decoded: {error}"))?; + Ok(decoded + .resize_to_fill(SIZE.0, SIZE.1, FilterType::Lanczos3) + .to_rgb8()) +} + +/// Lays the background colour over the card from top to bottom, as opaque as `stops` say at each height +/// (position 0–1, opacity 0–1), in straight lines between them. +fn shade_down(card: &mut RgbImage, stops: &[(f32, f32)]) { + let height = card.height(); + for y in 0..height { + let opacity = along(stops, y as f32 / (height - 1) as f32); + for x in 0..card.width() { + blend(card, i64::from(x), i64::from(y), BACKGROUND, opacity); + } + } +} + +/// `shade_down`, from left to right. +fn shade_across(card: &mut RgbImage, stops: &[(f32, f32)]) { + let width = card.width(); + for x in 0..width { + let opacity = along(stops, x as f32 / (width - 1) as f32); + for y in 0..card.height() { + blend(card, i64::from(x), i64::from(y), BACKGROUND, opacity); + } + } +} + +/// The value at `position` on a line through `stops`; flat beyond the first and last. +fn along(stops: &[(f32, f32)], position: f32) -> f32 { + let mut value = stops.first().map_or(0.0, |stop| stop.1); + for pair in stops.windows(2) { + let ((from, a), (to, b)) = (pair[0], pair[1]); + if position >= from { + value = if position >= to { + b + } else { + a + (b - a) * (position - from) / (to - from) + }; + } + } + value +} + +/// Lays `color` over one pixel at `opacity`; pixels off the card are skipped. +fn blend(card: &mut RgbImage, x: i64, y: i64, color: [u8; 3], opacity: f32) { + let (Ok(x), Ok(y)) = (u32::try_from(x), u32::try_from(y)) else { + return; + }; + if x >= card.width() || y >= card.height() || opacity <= 0.0 { + return; + } + let pixel = card.get_pixel_mut(x, y); + for (channel, target) in pixel.0.iter_mut().zip(color) { + let mixed = f32::from(*channel) + (f32::from(target) - f32::from(*channel)) * opacity; + *channel = mixed.round().clamp(0.0, 255.0) as u8; + } +} + +/// Lays a picture with transparency over the card, its top left corner at (`left`, `top`). +fn overlay(card: &mut RgbImage, picture: &RgbaImage, left: i64, top: i64) { + for (x, y, pixel) in picture.enumerate_pixels() { + let [r, g, b, a] = pixel.0; + blend( + card, + left + i64::from(x), + top + i64::from(y), + [r, g, b], + f32::from(a) / 255.0, + ); + } +} + +fn encode(card: &RgbImage) -> Result, String> { + let mut jpeg = Vec::new(); + JpegEncoder::new_with_quality(&mut jpeg, QUALITY) + .encode_image(card) + .map_err(|error| format!("the card couldn't be encoded: {error}"))?; + Ok(jpeg) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::maps::image::tests::png; + + fn decode(jpeg: &[u8]) -> RgbImage { + image::load_from_memory(jpeg).unwrap().to_rgb8() + } + + #[test] + fn a_map_card_is_a_1200_by_630_jpeg_from_any_cover() { + for (width, height) in [(1920, 1080), (2560, 1080), (800, 800)] { + let card = map_card(&png(width, height), "bhop_badges", Some(3)).unwrap(); + assert_eq!(&card[..2], [0xff, 0xd8], "JPEG"); + assert_eq!(decode(&card).dimensions(), SIZE); + } + assert!(map_card(b"not a picture", "bhop_badges", None).is_err()); + } + + #[test] + fn long_names_shrink_and_then_are_cut_short() { + let room = SIZE.0 as f32 - 2.0 * MARGIN; + assert_eq!( + fit(&BOLD, "bhop_badges", room), + (84.0, "bhop_badges".to_owned()) + ); + let (px, name) = fit(&BOLD, "bhop_a_rather_long_map_name_v2", room); + assert!( + px < 84.0 && name == "bhop_a_rather_long_map_name_v2", + "{px} {name}" + ); + let (px, name) = fit(&BOLD, &"bhop_".repeat(12), room); + assert_eq!(px, 52.0); + assert!(name.ends_with('…'), "{name}"); + assert!(Line::new(&BOLD, px, 0.0, &name).width <= room); + } + + #[test] + fn the_shade_follows_its_stops() { + let stops = [(0.0, 0.8), (0.5, 0.0), (1.0, 1.0)]; + assert!((along(&stops, 0.0) - 0.8).abs() < 1e-6); + assert!((along(&stops, 0.25) - 0.4).abs() < 1e-6); + assert!(along(&stops, 0.5).abs() < 1e-6); + assert!((along(&stops, 1.0) - 1.0).abs() < 1e-6); + } + + #[test] + fn the_site_card_is_1200_by_630() { + let card = site_card(&png(1376, 768)).unwrap(); + assert_eq!(decode(&card).dimensions(), SIZE); + } +} diff --git a/api/crates/api/src/maps/detail.rs b/api/crates/api/src/maps/detail.rs index 6e3f3ae..5402977 100644 --- a/api/crates/api/src/maps/detail.rs +++ b/api/crates/api/src/maps/detail.rs @@ -41,6 +41,10 @@ pub struct MapDetail { pub name: String, /// Up to 10 pictures, in order; the first is the cover. pub images: Vec, + /// The picture a link to the map shows (1200×630 JPEG): the cover with the map's name and tier in force. + /// None while the map has no cover; a new cover or tier gets a new card within a minute or two + /// (`maps/card.rs`). + pub card_url: Option, /// Staff's description of the map, plain text. pub description: Option, /// When it was released, as precisely as staff know; none when unknown. @@ -121,6 +125,7 @@ pub async fn map_detail( let found = sqlx::query!( r#" SELECT m.id, m.name, m.description, m.created_at, m.last_run_at, m.players, + (SELECT key FROM map_cards WHERE map_id = m.id) AS card_key, (SELECT count(*) FROM runs WHERE map_id = m.id AND invalidated_at IS NULL) AS "runs!" FROM maps m WHERE m.name = $1 "#, @@ -147,6 +152,7 @@ pub async fn map_detail( Ok(Json(MapDetail { name: found.name, images: image::images_of(&state.db, &state.storage, found.id).await?, + card_url: found.card_key.map(|key| state.storage.public_url(&key)), description: found.description, released: release.date, mapper: release.mapper, @@ -292,6 +298,7 @@ fn known_only_before_2_0( MapDetail { name: map.into(), images: Vec::new(), + card_url: None, description: None, released: None, mapper: None, diff --git a/api/crates/api/src/maps/list.rs b/api/crates/api/src/maps/list.rs index beb6771..1035221 100644 --- a/api/crates/api/src/maps/list.rs +++ b/api/crates/api/src/maps/list.rs @@ -661,9 +661,9 @@ mod tests { async fn searches_current_main_track_record_holders_in_the_selected_style(db: PgPool) { let key = setup(&db).await; sqlx::query( - r#"INSERT INTO rulesets (version, document) + r#"INSERT INTO rulesets (version, document, published_at) SELECT 2, jsonb_set(document, '{styles}', - (document->'styles') || '[{"key":"sw","name":"Sideways","settings":{}}]'::jsonb) + (document->'styles') || '[{"key":"sw","name":"Sideways","settings":{}}]'::jsonb), published_at FROM rulesets WHERE version = 1"#, ) .execute(&db) diff --git a/api/crates/api/src/players/profile.rs b/api/crates/api/src/players/profile.rs index ea97b13..5420145 100644 --- a/api/crates/api/src/players/profile.rs +++ b/api/crates/api/src/players/profile.rs @@ -338,6 +338,7 @@ mod tests { .execute(&db) .await .unwrap(); + crate::runs::tests::backdate(&db).await; let mut sideways = run("c", 40.0); sideways["style"] = json!("sw"); sideways["ruleset_version"] = json!(2); diff --git a/api/crates/api/src/runs.rs b/api/crates/api/src/runs.rs index 93103f3..1a7add4 100644 --- a/api/crates/api/src/runs.rs +++ b/api/crates/api/src/runs.rs @@ -227,9 +227,8 @@ async fn store( if let Some(id) = existing(conn, key.server_id, &run.server_run_id).await? { return answer_for_existing(conn, id).await; } - check_ruleset(conn, run).await?; - let finished_at = DateTime::from_timestamp(run.finished_at, 0).expect("checked before storing"); + check_ruleset(conn, run, key.server_id, finished_at).await?; players::record_name(conn, run.player.steamid64, &run.player.name, finished_at).await?; // An unknown code costs the player a flag, never their run. if let Some(code) = run @@ -282,7 +281,7 @@ async fn store( }; // Last: the recount holds the standings lock, which every other recount waits on, until this commits. if new_personal_best { - crate::leaderboards::standings::refresh_runs(conn, &[id]).await?; + crate::leaderboards::standings::refresh_stored_run(conn, id).await?; } Ok(Stored { @@ -293,14 +292,23 @@ async fn store( }) } -/// Whether the run's ruleset version exists, ranks its style and, if it names one, allows its tickrate. -async fn check_ruleset(conn: &mut PgConnection, run: &RunSubmission) -> Result<(), ApiError> { +/// Whether the run's ruleset version exists, ranks its style and, if it names one, allows its tickrate, and +/// whether the run finished after that version and its server existed. Nothing ranked can be older than both, so +/// an earlier time is a broken clock (0 is 1970); taken as is, it would win ties and rewrite WR history. +async fn check_ruleset( + conn: &mut PgConnection, + run: &RunSubmission, + server_id: i64, + finished_at: DateTime, +) -> Result<(), ApiError> { let ruleset = sqlx::query!( r#"SELECT document->'styles' @> jsonb_build_array(jsonb_build_object('key', $2::text)) AS "ranked!", - (document->>'tickrate')::real AS tickrate + (document->>'tickrate')::real AS tickrate, + GREATEST(published_at, (SELECT created_at FROM servers WHERE id = $3)) AS "earliest!" FROM rulesets WHERE version = $1"#, run.ruleset_version, - run.style + run.style, + server_id ) .fetch_optional(conn) .await? @@ -310,6 +318,12 @@ async fn check_ruleset(conn: &mut PgConnection, run: &RunSubmission) -> Result<( run.ruleset_version )) })?; + if finished_at < ruleset.earliest - servers::CLOCK_SLACK { + return Err(ApiError::Invalid(format!( + "finished_at is before ruleset version {} or this server existed; check the server's clock", + run.ruleset_version + ))); + } if !ruleset.ranked { return Err(ApiError::Invalid(format!( "style {:?} is not ranked in ruleset version {}", @@ -439,7 +453,7 @@ pub(crate) mod tests { use super::RunAccepted; use crate::{error::ErrorBody, servers::keys, test_client}; - /// Publishes a ruleset ranking `normal` and returns a fresh server key. + /// Publishes a ruleset ranking `normal` and returns a fresh server key, both backdated. pub(crate) async fn setup(db: &PgPool) -> String { sqlx::query( r#"INSERT INTO rulesets (version, document) VALUES (1, '{ @@ -451,7 +465,23 @@ pub(crate) mod tests { .execute(db) .await .unwrap(); - keys::issue(db, "Test server").await.unwrap().key + let key = keys::issue(db, "Test server").await.unwrap().key; + backdate(db).await; + key + } + + /// Dates every ruleset and server early in 2026, so the fixed times tests submit come after them. Rulesets + /// refuse changes, so this lifts that guard for the moment; each test has a database of its own. + pub(crate) async fn backdate(db: &PgPool) { + sqlx::raw_sql( + "ALTER TABLE rulesets DISABLE TRIGGER rulesets_immutable; + UPDATE rulesets SET published_at = '2026-01-01Z'; + ALTER TABLE rulesets ENABLE TRIGGER rulesets_immutable; + UPDATE servers SET created_at = '2026-01-01Z';", + ) + .execute(db) + .await + .unwrap(); } /// A valid run on `bhop_badges`, normal style, main track. @@ -555,6 +585,7 @@ pub(crate) mod tests { async fn the_same_run_id_from_another_server_is_a_different_run(db: PgPool) { let key = setup(&db).await; let other = keys::issue(&db, "Other server").await.unwrap().key; + backdate(&db).await; let first: RunAccepted = submit(&db, &key, &run("a", 30.0)).await.json(); let second = submit(&db, &other, &run("a", 31.0)).await; @@ -599,6 +630,44 @@ pub(crate) mod tests { assert_eq!(count(&db, "runs").await, 0); } + #[sqlx::test] + async fn a_run_cant_finish_before_its_ruleset_or_server_existed(db: PgPool) { + let old_key = setup(&db).await; + sqlx::query("INSERT INTO rulesets (version, document) SELECT 2, document FROM rulesets WHERE version = 1") + .execute(&db) + .await + .unwrap(); + let new_key = keys::issue(&db, "New server").await.unwrap().key; + let now = chrono::Utc::now().timestamp(); + let at = |id: &str, finished_at: i64, ruleset: i64| { + let mut body = run(id, 30.0); + body["finished_at"] = json!(finished_at); + body["ruleset_version"] = json!(ruleset); + body + }; + + for (key, body) in [ + (&old_key, at("a", 0, 1)), + (&old_key, at("b", now - 3600, 2)), + (&new_key, at("c", now - 3600, 1)), + ] { + let response = submit(&db, key, &body).await; + assert_eq!(response.status, 422, "{body}"); + assert!( + response + .json::() + .error + .contains("check the server's clock") + ); + } + // A clock a minute behind ours is within the slack. + assert_eq!( + submit(&db, &new_key, &at("d", now - 60, 2)).await.status, + 201 + ); + assert_eq!(count(&db, "runs").await, 1); + } + #[sqlx::test] async fn a_ruleset_with_a_tickrate_ranks_runs_at_that_tickrate_only(db: PgPool) { let key = setup(&db).await; @@ -609,6 +678,7 @@ pub(crate) mod tests { .execute(&db) .await .unwrap(); + backdate(&db).await; let at = |id: &str, tickrate: f64| { let mut body = run(id, 30.0); body["ruleset_version"] = json!(2); diff --git a/api/crates/api/src/runs/detail.rs b/api/crates/api/src/runs/detail.rs index ae70313..f38b4df 100644 --- a/api/crates/api/src/runs/detail.rs +++ b/api/crates/api/src/runs/detail.rs @@ -27,6 +27,8 @@ pub struct RunDetail { pub map: String, /// The map's cover picture. None until staff add one. pub map_image: Option, + /// The picture a link to the map shows (1200×630 JPEG), which links to its runs show too; see `MapDetail`. + pub map_card_url: Option, pub style: String, /// 0 is the main track, 1 and up are bonuses. pub track: i16, @@ -95,6 +97,7 @@ pub async fn run_detail( WHERE map_id = r.map_id AND style = r.style AND track = r.track) AS world_record_time, (SELECT tier FROM current_map_tiers WHERE map_id = r.map_id AND track = r.track) AS tier, ci.id AS "image_id?", ci.key AS "image_key?", ci.focus AS "image_focus?", + (SELECT key FROM map_cards WHERE map_id = r.map_id) AS map_card_key, (SELECT host(h.ip) || ':' || h.port FROM server_heartbeats h JOIN server_listings l ON l.ip = h.ip AND l.port = h.port WHERE h.server_id = s.id ORDER BY h.received_at DESC LIMIT 1) AS server_address @@ -148,6 +151,7 @@ pub async fn run_detail( }, map: row.map, map_image: MapImage::cover(&state.storage, row.image_id, row.image_key, row.image_focus), + map_card_url: row.map_card_key.map(|key| state.storage.public_url(&key)), style: row.style, track: row.track, // Tiers assigned before a tier count was published aren't in force. diff --git a/api/crates/api/src/servers.rs b/api/crates/api/src/servers.rs index 9b4df3b..6378d2d 100644 --- a/api/crates/api/src/servers.rs +++ b/api/crates/api/src/servers.rs @@ -19,15 +19,16 @@ pub fn routes() -> OpenApiRouter { .routes(routes!(activity::server_activity)) } -/// How far ahead of our clock a server's clock may run. Beyond that the time is wrong or made up, and it -/// would win every "newest" comparison: a player's name, Activity order, a map's last run. -const MAX_CLOCK_AHEAD: TimeDelta = TimeDelta::minutes(5); +/// How far a server's clock may be off from ours. A time further ahead is wrong or made up, and would win every +/// "newest" comparison: a player's name, Activity order, a map's last run. A run's time further behind its ruleset +/// or server would win ties and rewrite WR history (`runs::check_ruleset`). +pub const CLOCK_SLACK: TimeDelta = TimeDelta::minutes(5); /// Reads a time a game server reports (`finished_at`, `detected_at`), in Unix seconds by its clock. pub fn server_time(field: &str, unix: i64, now: DateTime) -> Result, String> { let at = DateTime::from_timestamp(unix, 0) .ok_or_else(|| format!("{field} is not a valid Unix time"))?; - if at > now + MAX_CLOCK_AHEAD { + if at > now + CLOCK_SLACK { return Err(format!( "{field} is in the future; check the server's clock" )); diff --git a/api/crates/api/src/staff/runs.rs b/api/crates/api/src/staff/runs.rs index cda8e93..ad7ed9d 100644 --- a/api/crates/api/src/staff/runs.rs +++ b/api/crates/api/src/staff/runs.rs @@ -1118,6 +1118,7 @@ mod tests { async fn revoking_a_key_can_invalidate_every_run_its_server_sent(db: PgPool) { let key = setup(&db).await; let other = keys::issue(&db, "Other server").await.unwrap(); + crate::runs::tests::backdate(&db).await; submit(&db, &key, "g1", GABE, 30.0, 0).await; submit(&db, &other.key, "z1", ZED, 35.0, 0).await; // A run sent with the server's earlier key goes too. diff --git a/api/openapi.json b/api/openapi.json index 38076b7..1b173bf 100644 --- a/api/openapi.json +++ b/api/openapi.json @@ -7636,6 +7636,13 @@ "format": "int64", "description": "Players on its \"2.0 + pre-2.0\" view, each counted once. 0 when there are no pre-2.0 runs." }, + "card_url": { + "type": [ + "string", + "null" + ], + "description": "The picture a link to the map shows (1200×630 JPEG): the cover with the map's name and tier in force.\nNone while the map has no cover; a new cover or tier gets a new card within a minute or two\n(`maps/card.rs`)." + }, "created_at": { "type": [ "string", @@ -9848,6 +9855,13 @@ "map": { "type": "string" }, + "map_card_url": { + "type": [ + "string", + "null" + ], + "description": "The picture a link to the map shows (1200×630 JPEG), which links to its runs show too; see `MapDetail`." + }, "map_image": { "oneOf": [ { diff --git a/deploy/deploy.sh b/deploy/deploy.sh index c96d320..e467617 100755 --- a/deploy/deploy.sh +++ b/deploy/deploy.sh @@ -18,7 +18,7 @@ command -v musl-gcc >/dev/null || { echo "musl-gcc is missing: sudo apt install (cd api && SQLX_OFFLINE=true CC_x86_64_unknown_linux_musl=musl-gcc \ cargo build --release --locked --target x86_64-unknown-linux-musl -p sourcejump-api) # Standalone server, plus the static assets Next expects next to it. -(cd web && npm run build) +(cd web && SJ_SITE_URL="https://$SITE_ADDRESS" npm run build) rm -rf web/.next/standalone/.next/static cp -r web/.next/static web/.next/standalone/.next/static if [ -d web/public ]; then cp -r web/public web/.next/standalone/; fi diff --git a/docs/deploy.md b/docs/deploy.md index ac0af89..baaedc9 100644 --- a/docs/deploy.md +++ b/docs/deploy.md @@ -6,8 +6,8 @@ One VPS runs everything as systemd services under the `sourcejump` user: - **cloudflared** carries all web traffic from Cloudflare, which ends TLS, to Caddy on `127.0.0.1:80`. The firewall (ufw) lets in only SSH, rate-limited (6 new connections per 30 s per address); SSH takes keys only. A separate nftables table (`drop-ip-options.service`) drops IPv4 packets carrying IP options, which CVE-2026-98432 needs. - **Caddy** listens on localhost over plain HTTP. `/v1/*` and `/health` go to the API on `127.0.0.1:8080`; every other path goes to the web app on `127.0.0.1:3000`. One domain serves both, so the plugin and the browser use the same base URL. It sets `X-Forwarded-For` to Cloudflare's `Cf-Connecting-IP`, and security headers on every response (no framing, `nosniff`, referrer policy, HSTS). Template: `deploy/Caddyfile`. The web app's own `/v1` proxy exists only under `next dev`. - **API**: the static binary at `/opt/sourcejump/api/`. It applies pending migrations when it starts, so a deploy is "copy, restart". Config: `/etc/sourcejump/api.env`, including the object-storage settings (`SJ_S3_*`, with `SJ_S3_PUBLIC_URL` where browsers read public files such as map images); it refuses to start without them. -- **Web**: the Next.js standalone build at `/opt/sourcejump/web/`, run by Node 24. It reaches the API over loopback (`SJ_API_URL`). Config: `/etc/sourcejump/web.env`, where `NODE_OPTIONS` caps its heap. -- **Postgres 18**: database and role `sourcejump`, reached over the local socket with peer authentication, so there is no database password. Requests use their own pool of 10 connections, where a statement may run 5 s (`query_time_limit.rs`); startup, jobs and the CLI use one without the limit, and recounts and invalidations lift it. +- **Web**: the Next.js standalone build at `/opt/sourcejump/web/`, run by Node 24. It reaches the API over loopback (`SJ_API_URL`). `just deploy` builds it with `SJ_SITE_URL` from `SITE_ADDRESS`, for link previews' whole addresses. Config: `/etc/sourcejump/web.env`, where `NODE_OPTIONS` caps its heap. +- **Postgres 18**: database and role `sourcejump`, reached over the local socket with peer authentication, so there is no database password. Requests use their own pool of 10 connections, where a statement may run 5 s (`query_time_limit.rs`); startup, jobs and the CLI use one without the limit, and recounts and invalidations lift it. A run being stored waits at most 2 s for another recount, then gets a `500` its server resends (`standings.rs`). Each environment has a file `deploy/environments/.env` with `SSH_TARGET` (a `Host` alias from your `~/.ssh/config` that logs in as root; server addresses stay out of the repo), `SITE_ADDRESS` (the domain) and optionally `NOINDEX=true`, which makes Caddy send `X-Robots-Tag: noindex, nofollow` on every response. These hold no secrets and are committed. diff --git a/docs/plans/web-redesign-api.md b/docs/plans/web-redesign-api.md index 5accce0..1ef31f3 100644 --- a/docs/plans/web-redesign-api.md +++ b/docs/plans/web-redesign-api.md @@ -10,7 +10,8 @@ side, and the shortcuts the web takes until then. Delete each item once it's don 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). + renumbered after it (sqlx rejects a reused version with different content). This preview keeps its applied + `0052`–`0054` unchanged; upstream's identical tier view is already `0054`, and its `0053_map_cards` is `0055` here. - **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. diff --git a/web/src/api/schema.ts b/web/src/api/schema.ts index a6b0e3b..2cc592f 100644 --- a/web/src/api/schema.ts +++ b/web/src/api/schema.ts @@ -2118,6 +2118,12 @@ export interface components { * @description Players on its "2.0 + pre-2.0" view, each counted once. 0 when there are no pre-2.0 runs. */ all_players: number; + /** + * @description The picture a link to the map shows (1200×630 JPEG): the cover with the map's name and tier in force. + * None while the map has no cover; a new cover or tier gets a new card within a minute or two + * (`maps/card.rs`). + */ + card_url?: string | null; /** * Format: date-time * @description When SourceJump first saw the map: its first run or zone import. None for a map known only from @@ -3056,6 +3062,8 @@ export interface components { /** Format: int32 */ jumps: number; map: string; + /** @description The picture a link to the map shows (1200×630 JPEG), which links to its runs show too; see `MapDetail`. */ + map_card_url?: string | null; map_image?: components["schemas"]["MapImage"] | null; /** * Format: float diff --git a/web/src/features/dailyTotals/DailyTotals.tsx b/web/src/features/dailyTotals/DailyTotals.tsx index 9da64c6..7d8c0cd 100644 --- a/web/src/features/dailyTotals/DailyTotals.tsx +++ b/web/src/features/dailyTotals/DailyTotals.tsx @@ -1,5 +1,6 @@ // Loads every range of one of the site's daily totals for its chart: players for the Players page, runs and // world records for the Activity page. Nothing shows if they can't be loaded; the page works without it. +import { connection } from "next/server"; import { api } from "@/api/client"; import { DailyTotalsChart, @@ -20,6 +21,7 @@ export async function DailyTotals({ /** Draws on the parent's surface instead of its own card. */ plain?: boolean; }) { + await connection(); // Both endpoints take the same range and return their own totals type, so one fetch serves either kind. const data: DailyTotalsData = { kind, diff --git a/web/src/features/home/LiveNow.tsx b/web/src/features/home/LiveNow.tsx index 6322a3a..ad41798 100644 --- a/web/src/features/home/LiveNow.tsx +++ b/web/src/features/home/LiveNow.tsx @@ -1,6 +1,7 @@ // The home page's live part, under its header: the numbers that say how busy SourceJump is (players on now, the // latest day's runs, the week's world records), the newest world records beside the top of the points board, then // the servers people are playing on now. +import { connection } from "next/server"; import type { CSSProperties, ReactNode } from "react"; import { api, type Schemas } from "@/api/client"; import { currentStyles } from "@/features/ruleset/styles"; @@ -35,6 +36,7 @@ const SERVERS = 4; const numbers = new Intl.NumberFormat("en"); export async function LiveNow() { + await connection(); // Each part shows what it has; one that can't be loaded says so, or (a fact) leaves its number out. const [records, servers, leaders, runs, styles] = await Promise.all([ api diff --git a/web/src/features/servers/ServerList.tsx b/web/src/features/servers/ServerList.tsx index 873b93b..a76abe7 100644 --- a/web/src/features/servers/ServerList.tsx +++ b/web/src/features/servers/ServerList.tsx @@ -2,11 +2,13 @@ // first. Staff with manage_servers also see unlisted servers there, and list or unlist them in place. From sm // up this is one board; combining the chart and the list into one board read badly on a phone, so it keeps // them as two boards there. +import { connection } from "next/server"; import { api } from "@/api/client"; import { ServerActivity } from "./ServerActivity"; import { ServerRows } from "./ServerRows"; export async function ServerList() { + await connection(); const [result, day, week, month, year] = await Promise.all([ api.GET("/v1/servers").catch(() => undefined), ...(["day", "week", "month", "year"] as const).map((range) =>