keep grouped_drop_kills as table
All checks were successful
CI / checks (push) Successful in 47s

This commit is contained in:
Robin Appelman 2026-11-19 21:24:55 +01:00
commit 2fe9c49f4e
8 changed files with 307 additions and 32 deletions

View file

@ -0,0 +1,34 @@
{
"db_name": "PostgreSQL",
"query": "\n INSERT INTO grouped_drop_kills (victim, attacker, attacker_class, count)\n VALUES ($1, $2, $3, 1)\n ON CONFLICT (victim, attacker, attacker_class) DO UPDATE\n SET count = grouped_drop_kills.count + 1;\n ",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Int8",
"Int8",
{
"Custom": {
"name": "class_type",
"kind": {
"Enum": [
"scout",
"soldier",
"pyro",
"demoman",
"heavyweapons",
"engineer",
"medic",
"sniper",
"spy",
"unknown"
]
}
}
}
]
},
"nullable": []
},
"hash": "ca2224ab6a108d99b07b367c3e701667d6c148a3face198cbe5aef5ebe79265b"
}

29
Cargo.lock generated
View file

@ -951,6 +951,7 @@ dependencies = [
"dotenvy",
"insta",
"main_error",
"pgtemp",
"serde",
"serde_json",
"serde_with",
@ -1162,6 +1163,18 @@ version = "2.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
[[package]]
name = "pgtemp"
version = "0.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d6d35886f9448b0a12b24c9fee002332d19b5c021af45745fa1731f140eaf14e"
dependencies = [
"libc",
"tempfile",
"tokio",
"url",
]
[[package]]
name = "pin-project-lite"
version = "0.2.17"
@ -1514,6 +1527,16 @@ version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
[[package]]
name = "signal-hook-registry"
version = "1.4.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b"
dependencies = [
"errno",
"libc",
]
[[package]]
name = "similar"
version = "2.7.0"
@ -1886,9 +1909,9 @@ dependencies = [
[[package]]
name = "tf-log-parser"
version = "0.1.3"
version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bdf88d9bce2693006421a7361e1d05809ca50549a70fbb97690135a8e719d5c1"
checksum = "6a1de5672085b771f4a5a61bc1aa88a42534685edbca45197c4771c543b77e26"
dependencies = [
"ahash",
"chrono",
@ -2005,7 +2028,9 @@ dependencies = [
"bytes",
"libc",
"mio",
"parking_lot",
"pin-project-lite",
"signal-hook-registry",
"socket2",
"tokio-macros",
"windows-sys",

View file

@ -24,7 +24,7 @@ sqlx = { version = "0.9.0", default-features = false, features = [
"runtime-tokio",
] }
steamid-ng = { version = "3.0.0", features = ["serde"] }
tf-log-parser = "0.1.0"
tf-log-parser = "0.1.4"
tokio = { version = "1.54.1", features = ["macros", "rt-multi-thread", "time"] }
tracing = "0.1.44"
tracing-subscriber = "0.3.23"
@ -34,3 +34,4 @@ whoami = { version = "2.1.3", default-features = false, features = ["std"] }
[dev-dependencies]
insta = { version = "1.49.0", features = ["ron"] }
test-case = "3.4.1"
pgtemp = "0.7.1"

View file

@ -19,8 +19,11 @@
extraPaths = [
./.sqlx
./tests
./schema.sql
];
nativeBuildInputs = pkgs: with pkgs; [postgresql];
nixosModules = {outputs, ...}: {
default = {
pkgs,

View file

@ -1,10 +1,11 @@
{
stdenv,
rustPlatform,
postgresql,
lib,
}: let
inherit (lib.sources) sourceByRegex;
src = sourceByRegex ../. ["Cargo.*" "(src|tests|.sqlx)(/.*)?"];
src = sourceByRegex ../. ["Cargo.*" "(src|tests|.sqlx)(/.*)?" "schema.sql"];
in
rustPlatform.buildRustPackage rec {
pname = "log-normalizer";
@ -17,4 +18,5 @@ in
cargoLock = {
lockFile = ../Cargo.lock;
};
nativeBuildInputs = [postgresql];
}

View file

@ -321,6 +321,14 @@ CREATE UNIQUE INDEX class_stats_player_id_type_idx ON class_stats USING BTREE (p
CREATE INDEX class_stats_player_id_valid_idx ON class_stats USING BTREE (player_id, is_valid);
CREATE OR REPLACE FUNCTION get_player_class (q_player_id BIGINT) RETURNS class_type AS $$
DECLARE
result class_type;
BEGIN
SELECT type INTO result FROM class_stats WHERE player_id = q_player_id ORDER by time desc limit 1;
RETURN result;
END; $$ LANGUAGE PLPGSQL IMMUTABLE;
CREATE TABLE player_weapon_stats (
id BIGSERIAL PRIMARY KEY,
class_stat_id BIGINT NOT NULL REFERENCES class_stats (id),
@ -507,37 +515,61 @@ CREATE INDEX kills_weapon_idx ON kills USING BTREE (weapon_id);
CREATE INDEX kills_victim_class_idx ON kills USING BTREE (victim_class, charge);
CREATE MATERIALIZED VIEW grouped_drop_kills AS
SELECT
CREATE INDEX kills_group_idx ON kills USING BTREE (
victim,
victim_class,
attacker,
attacker_class,
count(*),
count(DISTINCT log_id) AS logs
FROM
kills
WHERE
victim_class = 'medic'
AND charge = 100
GROUP BY
victim,
attacker,
attacker_class;
weapon_id
);
CREATE TABLE grouped_drop_kills (
id SERIAL PRIMARY KEY,
victim BIGINT NOT NULL,
attacker BIGINT NOT NULL,
attacker_class class_type NOT NULL,
count INT NOT NULL
);
CREATE UNIQUE INDEX grouped_drop_kills_idx ON grouped_drop_kills USING BTREE (victim, attacker, attacker_class);
CREATE MATERIALIZED VIEW medic_player_matchups AS
SELECT
a.steam_id AS steam_id_medic,
b.steam_id AS steam_id_other,
count(*)
FROM
players a
INNER JOIN players b ON a.log_id = b.log_id
WHERE
a.team != b.team
AND (a.ubers + a.drops) > 0
AND a.steam_id != b.steam_id
AND a.is_valid
GROUP BY
a.steam_id,
b.steam_id;
CREATE INDEX medic_player_matchups_steam_id_idx ON medic_player_matchups USING BTREE (steam_id_medic, steam_id_other);
CREATE MATERIALIZED VIEW drop_attribution AS
SELECT
attacker,
victim,
json_objectagg (attacker_class:count) AS by_class,
sum(count)::BIGINT AS total,
sum(logs)::INT AS logs
grouped_drop_kills.attacker,
grouped_drop_kills.victim,
json_objectagg (
grouped_drop_kills.attacker_class:grouped_drop_kills.count
) AS by_class,
sum(grouped_drop_kills.count)::BIGINT AS total,
max(medic_player_matchups.count)::INT AS logs
FROM
grouped_drop_kills
INNER JOIN medic_player_matchups ON (
grouped_drop_kills.victim = medic_player_matchups.steam_id_medic
AND grouped_drop_kills.attacker = medic_player_matchups.steam_id_other
)
GROUP BY
victim,
attacker;
grouped_drop_kills.victim,
grouped_drop_kills.attacker;
CREATE INDEX drop_attribution_victim_idx ON drop_attribution USING BTREE (victim, total DESC);

View file

@ -70,6 +70,23 @@ impl From<tf_log_parser::Class> for Class {
}
}
impl From<Class> for tf_log_parser::Class {
fn from(value: Class) -> Self {
match value {
Class::Scout => tf_log_parser::Class::Scout,
Class::Soldier => tf_log_parser::Class::Soldier,
Class::Pyro => tf_log_parser::Class::Pyro,
Class::Demoman => tf_log_parser::Class::DemoMan,
Class::HeavyWeapons => tf_log_parser::Class::HeavyWeapons,
Class::Engineer => tf_log_parser::Class::Engineer,
Class::Medic => tf_log_parser::Class::Medic,
Class::Sniper => tf_log_parser::Class::Sniper,
Class::Spy => tf_log_parser::Class::Spy,
Class::Unknown => tf_log_parser::Class::Unknown,
}
}
}
#[derive(Debug, Clone, Copy, sqlx::Type, Eq, PartialEq)]
#[sqlx(type_name = "game_mode")]
pub enum GameMode {

View file

@ -366,6 +366,7 @@ async fn weapon_id<'a>(
return Ok(*id);
}
// once we have postgresql 19, we can do INSERT .. ON CONFLICT DO SELECT
let id = sqlx::query_scalar!("SELECT id FROM weapons WHERE name = $1", name)
.fetch_optional(&mut **tx)
.await?;
@ -418,18 +419,178 @@ async fn store_kills<'a>(
)
.execute(&mut **tx)
.await?;
if kill.charge == Some(100) {
sqlx::query!(
r#"
INSERT INTO grouped_drop_kills (victim, attacker, attacker_class, count)
VALUES ($1, $2, $3, 1)
ON CONFLICT (victim, attacker, attacker_class) DO UPDATE
SET count = grouped_drop_kills.count + 1;
"#,
u64::from(kill.victim.id) as i64,
u64::from(kill.killer.id) as i64,
Class::from(kill.killer.class) as Class,
)
.execute(&mut **tx)
.await?;
}
}
Ok(())
}
// macro_rules! insert_fields {
// ($table:ident, {
// $($($field:ident => $value:expr),)+
// }) => {
// sqlx::query!(
// concat!("INSERT INTO ", stringify!($table), "(", stringify!$(field)) ") VALUES ()"\
// VALUES($1, $2, $3, $4, $5)",
// )
// };
// }
#[tokio::test]
async fn test_store_kills() {
use steamid_ng::{AccountType, Instance, InstanceFlags, InstanceType, Universe};
use tf_log_parser::{
data::Weapon,
module::{KillKind, Participant},
};
fn participant(id: u32, class: Class) -> Participant {
Participant {
class: class.into(),
id: SteamID::new(
id,
Instance::new(InstanceType::All, InstanceFlags::None),
AccountType::Individual,
Universe::Public,
),
}
}
fn steam_id(id: u32) -> i64 {
SteamID::new(
id,
Instance::new(InstanceType::All, InstanceFlags::None),
AccountType::Individual,
Universe::Public,
)
.steam64() as i64
}
use pgtemp::PgTempDB;
use sqlx::postgres::PgConnection;
use sqlx::prelude::*;
use sqlx::{query, query_as};
let db = PgTempDB::async_new().await;
let mut conn = PgConnection::connect(&db.connection_uri())
.await
.expect("failed to connect to temp db");
let schema = include_str!("../schema.sql");
for q in schema.split("\n\n") {
query(q).execute(&mut conn).await.expect("schema");
}
let mut tx = Connection::begin(&mut conn).await.expect("transaction");
query(
r#"
insert into logs(id, red_score, blue_score, length, game_mode, map, type, date, version)
VALUES(1, 2, 3, 4, '6v6', 'cp_process', 'cp', NOW(), 3)
"#,
)
.execute(&mut *tx)
.await
.expect("create log");
store_kills(
&mut tx,
1,
vec![Kill {
time: 1,
killer: participant(1, Class::Scout),
assister: None,
victim: participant(2, Class::Medic),
charge: Some(100),
weapon: Weapon::Scattergun,
kind: KillKind::Normal,
attacker_position: None,
assister_position: None,
victim_position: None,
}],
&mut HashMap::new(),
)
.await
.expect("store kills");
store_kills(
&mut tx,
1,
vec![Kill {
time: 10,
killer: participant(1, Class::Scout),
assister: None,
victim: participant(2, Class::Medic),
charge: Some(100),
weapon: Weapon::Scattergun,
kind: KillKind::Normal,
attacker_position: None,
assister_position: None,
victim_position: None,
}],
&mut HashMap::new(),
)
.await
.expect("store kills");
store_kills(
&mut tx,
1,
vec![Kill {
time: 10,
killer: participant(3, Class::Scout),
assister: None,
victim: participant(2, Class::Medic),
charge: Some(100),
weapon: Weapon::Scattergun,
kind: KillKind::Normal,
attacker_position: None,
assister_position: None,
victim_position: None,
}],
&mut HashMap::new(),
)
.await
.expect("store kills");
tx.commit().await.expect("commit");
#[derive(Debug, PartialEq, FromRow)]
struct GroupedDropKill {
victim: i64,
attacker: i64,
attacker_class: Class,
count: i32,
}
let grouped = query_as::<_, GroupedDropKill>(
r#"
select victim, attacker, attacker_class, count from grouped_drop_kills order by id asc
"#,
)
.fetch_all(&mut conn)
.await
.expect("create log");
assert_eq!(
vec![
GroupedDropKill {
victim: steam_id(2),
attacker: steam_id(1),
attacker_class: Class::Scout,
count: 2
},
GroupedDropKill {
victim: steam_id(2),
attacker: steam_id(3),
attacker_class: Class::Scout,
count: 1
}
],
grouped
);
}