Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

This file was deleted.

This file was deleted.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion api/contract/runs.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
"server_run_id": "9b2f6a1e-4c1d-4e7a-9a51-3f0f6f1c2d10",
"player": {
"steamid64": "76561197960287930",
"name": "gabe"
"name": "gabe",
"country_code": "SE"
},
"map": "bhop_badges",
"style": "normal",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
-- Whether `players.country_code` came from a game server: its GeoIP lookup of the player's address, sent with a
-- run. A player's country has one source at a time, so this and `country_chosen` are never both true. Which
-- source wins is in `docs/site-api.md`.
ALTER TABLE players
ADD COLUMN country_from_server boolean NOT NULL DEFAULT false,
ADD CONSTRAINT players_one_country_source CHECK (NOT (country_chosen AND country_from_server));
25 changes: 25 additions & 0 deletions api/crates/api/src/players.rs
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,31 @@ pub async fn record_name(
Ok(())
}

/// Makes `code`, found by a game server from the player's address, their country, replacing one they picked or
/// Steam's (the order is in `docs/site-api.md`). Only from their latest run, as for names: `record_name` has
/// already moved `name_seen_at` to the newest time a server saw them, so a run sent late from a queue can't roll
/// the country back.
pub async fn record_server_country(
conn: &mut PgConnection,
steamid64: SteamId64,
code: &str,
finished_at: DateTime<Utc>,
) -> Result<(), sqlx::Error> {
sqlx::query!(
r#"
UPDATE players SET country_code = $2, country_from_server = true, country_chosen = false
WHERE steamid64 = $1 AND name_seen_at <= $3
AND (country_code IS DISTINCT FROM $2 OR NOT country_from_server)
"#,
steamid64.get(),
code,
finished_at
)
.execute(conn)
.await?;
Ok(())
}

#[cfg(test)]
mod tests {
use super::SteamId64;
Expand Down
41 changes: 37 additions & 4 deletions api/crates/api/src/players/details.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
//! What players say about themselves on their profile, `PUT /v1/players/{player}/details`: their setup (mouse,
//! DPI, sensitivity, mouse pad, keyboard, monitor, aspect ratio) and a country to show instead of Steam's.
//! DPI, sensitivity, mouse pad, keyboard, monitor, aspect ratio) and a country to show (order: `docs/site-api.md`).
//!
//! Anyone can type anything here, so every field is checked once, at this boundary: short single lines of
//! text with no links or invisible characters, numbers in a sensible range, a ratio from a fixed list and a
Expand Down Expand Up @@ -216,7 +216,8 @@ pub struct DetailsInput {
pub monitor: Option<String>,
#[serde(default)]
pub aspect: Option<Aspect>,
/// An ISO 3166-1 alpha-2 code to show instead of the Steam profile's country; null to show Steam's.
/// An ISO 3166-1 alpha-2 code to show instead of Steam's or a game server's, until a run's server finds one;
/// null to stop showing the player's pick.
#[serde(default)]
pub country_code: Option<String>,
/// Required when staff change someone else's details: why, for the staff log.
Expand Down Expand Up @@ -346,12 +347,13 @@ async fn store(
)
.execute(&mut *tx)
.await?;
// Going back to Steam's country clears ours and marks the Steam profile stale, so the next view of the
// profile fetches it again.
// A pick replaces a game server's country. Dropping a pick clears it and marks the Steam profile stale, so
// the next view of the profile fetches Steam's again; dropping a pick the player doesn't have changes nothing.
sqlx::query!(
r#"
UPDATE players SET
country_chosen = $2::text IS NOT NULL,
country_from_server = country_from_server AND $2::text IS NULL,
country_code = CASE WHEN $2::text IS NOT NULL THEN $2
WHEN country_chosen THEN NULL ELSE country_code END,
steam_profile_fetched_at = CASE WHEN $2::text IS NULL AND country_chosen THEN NULL
Expand Down Expand Up @@ -539,6 +541,37 @@ mod tests {
);
}

#[sqlx::test]
async fn a_pick_replaces_a_servers_country_and_saving_without_one_keeps_it(db: PgPool) {
let token = player(&db, GABE, &[]).await;
sqlx::query("UPDATE players SET country_code = 'SE', country_from_server = true")
.execute(&db)
.await
.unwrap();
let country = || async {
sqlx::query_as::<_, (Option<String>, bool, bool)>(
"SELECT country_code, country_from_server, country_chosen FROM players",
)
.fetch_one(&db)
.await
.unwrap()
};

assert_eq!(
save(&db, &token, GABE, json!({ "dpi": 800 })).await.status,
204
);
assert_eq!(country().await, (Some("SE".into()), true, false));

sqlx::query("UPDATE player_details SET updated_at = now() - interval '1 minute'")
.execute(&db)
.await
.unwrap();
let body = json!({ "country_code": "fi" });
assert_eq!(save(&db, &token, GABE, body).await.status, 204);
assert_eq!(country().await, (Some("FI".into()), false, true));
}

#[sqlx::test]
async fn bad_values_are_refused(db: PgPool) {
let token = player(&db, GABE, &[]).await;
Expand Down
5 changes: 3 additions & 2 deletions api/crates/api/src/players/profile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,10 @@ pub struct PlayerProfile {
/// The name from their latest run, or from Steam if they haven't played yet.
pub name: String,
pub avatar_url: Option<String>,
/// ISO 3166-1 alpha-2: the one the player picked, or else their Steam profile's. None if neither has one.
/// ISO 3166-1 alpha-2: the latest one a game server found for them, the player's pick if they made it
/// since, or else their Steam profile's. None if none has one.
pub country_code: Option<String>,
/// Whether the player picked `country_code` themselves, rather than it coming from Steam.
/// Whether the player picked `country_code` themselves, rather than it coming from a game server or Steam.
pub country_chosen: bool,
/// Their setup, as they describe it. None when they've said nothing.
pub details: Option<PlayerDetails>,
Expand Down
49 changes: 47 additions & 2 deletions api/crates/api/src/players/steam_profile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -132,8 +132,8 @@ pub async fn refresh(db: &PgPool, steam: &Steam, steamid64: SteamId64) -> Result
r#"
UPDATE players SET
avatar_url = $2,
-- A country the player picked on their profile stays.
country_code = CASE WHEN country_chosen THEN country_code ELSE $3 END,
-- Steam's country comes last: one a game server found or the player picked stays.
country_code = CASE WHEN country_chosen OR country_from_server THEN country_code ELSE $3 END,
steam_profile_fetched_at = now(),
name = CASE WHEN name_seen_at = '-infinity' AND $4::text IS NOT NULL THEN $4 ELSE name END
WHERE steamid64 = $1
Expand Down Expand Up @@ -220,6 +220,51 @@ mod tests {
assert!(queue(&steam, first), "a finished refresh frees its place");
}

/// A stand-in for Steam that answers every profile with `PUBLIC`.
async fn fake_steam() -> Steam {
let app =
axum::Router::new().route("/profiles/{id}/", axum::routing::get(|| async { PUBLIC }));
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
Steam::with_base(&url::Url::parse(&format!("http://{address}/")).unwrap())
}

#[sqlx::test]
async fn steams_country_comes_after_a_servers_and_the_players_own(db: PgPool) {
// Steam's own (none yet), a game server's, and the player's pick.
let players = [
("[U:1:1]", None, false, false, Some("NO")),
("[U:1:2]", Some("SE"), true, false, Some("SE")),
("[U:1:3]", Some("FI"), false, true, Some("FI")),
];
for (id, code, from_server, chosen, expected) in players {
let steamid64 = SteamId64::parse_any(id).unwrap();
sqlx::query(
"INSERT INTO players (steamid64, name, name_seen_at, country_code, country_from_server, country_chosen)
VALUES ($1, 'nova', now(), $2, $3, $4)",
)
.bind(steamid64.get())
.bind(code)
.bind(from_server)
.bind(chosen)
.execute(&db)
.await
.unwrap();
// A Steam each, so no refresh waits its turn behind another.
refresh(&db, &fake_steam().await, steamid64).await.unwrap();

let (country, avatar): (Option<String>, Option<String>) =
sqlx::query_as("SELECT country_code, avatar_url FROM players WHERE steamid64 = $1")
.bind(steamid64.get())
.fetch_one(&db)
.await
.unwrap();
assert!(avatar.is_some(), "{id}: the profile was stored");
assert_eq!(country.as_deref(), expected, "{id}");
}
}

#[sqlx::test]
async fn a_failed_fetch_waits_before_trying_again(db: PgPool) {
let steamid64 = SteamId64::parse_any("76561197960287930").unwrap();
Expand Down
92 changes: 92 additions & 0 deletions api/crates/api/src/runs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,13 @@ pub struct RunPlayer {
#[schema(value_type = String, example = "76561197960287930")]
pub steamid64: SteamId64,
pub name: String,
/// The player's country, as the game server found it from their address with SourceMod's `GeoipCode2`: an ISO
/// 3166-1 alpha-2 code. Leave it out when the lookup finds nothing; send only the code, never the address. It
/// becomes the player's flag. A code SourceJump doesn't know as a country is ignored and the run is stored
/// anyway. Runs only: detections ignore it.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[schema(example = "SE")]
pub country_code: Option<String>,
}

/// SourceJump's answer to a run. A resend gets the same answer, with a fresh upload link if one applies.
Expand Down Expand Up @@ -224,6 +231,15 @@ async fn store(

let finished_at = DateTime::from_timestamp(run.finished_at, 0).expect("checked before storing");
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
.player
.country_code
.as_deref()
.and_then(players::countries::known_code)
{
players::record_server_country(conn, run.player.steamid64, code, finished_at).await?;
}
let ban = restrictions::records_ban(conn, run.player.steamid64).await?;
let map_id = maps::id_for(conn, &run.map).await?;

Expand Down Expand Up @@ -610,6 +626,82 @@ pub(crate) mod tests {
assert_eq!(submit(&db, &key, &any).await.status, 201);
}

/// The run player's `country_code`, `country_from_server` and `country_chosen`.
async fn country(db: &PgPool) -> (Option<String>, bool, bool) {
sqlx::query_as(
"SELECT country_code, country_from_server, country_chosen FROM players WHERE steamid64 = 76561197960287930",
)
.fetch_one(db)
.await
.unwrap()
}

fn with_country(server_run_id: &str, code: &str) -> Value {
let mut body = run(server_run_id, 30.0);
body["player"]["country_code"] = json!(code);
body
}

#[sqlx::test]
async fn the_country_a_server_found_replaces_a_pick_and_steams(db: PgPool) {
let key = setup(&db).await;

assert_eq!(
submit(&db, &key, &with_country("a", "se")).await.status,
201
);
assert_eq!(country(&db).await, (Some("SE".into()), true, false));

// The player picks their own; a run without a country leaves it, the next one with a country replaces it.
sqlx::query("UPDATE players SET country_code = 'NO', country_chosen = true, country_from_server = false")
.execute(&db)
.await
.unwrap();
assert_eq!(submit(&db, &key, &run("b", 31.0)).await.status, 201);
assert_eq!(country(&db).await, (Some("NO".into()), false, true));
assert_eq!(
submit(&db, &key, &with_country("c", "SE")).await.status,
201
);
assert_eq!(country(&db).await, (Some("SE".into()), true, false));

// A resend changes nothing, whatever country it carries.
assert_eq!(
submit(&db, &key, &with_country("a", "fi")).await.status,
200
);
assert_eq!(country(&db).await, (Some("SE".into()), true, false));
}

#[sqlx::test]
async fn a_country_sourcejump_doesnt_know_is_ignored_and_the_run_stored(db: PgPool) {
let key = setup(&db).await;

for (id, code) in [("a", "XX"), ("b", "A1"), ("c", "EU"), ("d", "Sweden")] {
assert_eq!(
submit(&db, &key, &with_country(id, code)).await.status,
201,
"{code}"
);
}

assert_eq!(count(&db, "runs").await, 4);
assert_eq!(country(&db).await, (None, false, false));
}

#[sqlx::test]
async fn a_run_sent_late_cant_roll_the_country_back(db: PgPool) {
let key = setup(&db).await;
let mut newer = with_country("a", "SE");
newer["finished_at"] = json!(1_792_400_100);

submit(&db, &key, &newer).await;
submit(&db, &key, &with_country("b", "FI")).await;

assert_eq!(count(&db, "runs").await, 2);
assert_eq!(country(&db).await, (Some("SE".into()), true, false));
}

#[sqlx::test]
async fn runs_need_a_valid_key(db: PgPool) {
setup(&db).await;
Expand Down
Loading