feat(match): atomic exactly-once match-completion transaction

Add complete_match: one BEGIN/COMMIT that validates identity + result,
enforces a durable (profile_id, match_identity) uniqueness guard
(migration 0022 match_completions), persists match history, and grants
coins + XP/level-ups + W/D/L/DNF statistics + objectives + achievements
exactly once. Any failure rolls the whole match back (no compensating
cleanup). Handles sequential/restart/concurrent replay, conflicting
re-report (first result canonical), DNF (loss economics, own stat
bucket) and no-contest (zero economic effect).

Adds tx-scoped variants: statistics::record_match_tx/
record_position_goals_tx, objective::increment_metric_tx,
achievement::check_and_unlock_tx. New MatchResultKind/CompleteMatchRequest/
MatchCompletionResult models + POST /matches/complete route.
This commit is contained in:
funman300
2026-08-20 16:38:16 +00:00
parent a034e74c16
commit b0306a9b1d
9 changed files with 1284 additions and 5 deletions
+93 -1
View File
@@ -1,6 +1,7 @@
use crate::{db::Pool, error::AppResult, models::statistics::Statistics};
use sqlx::{Sqlite, Transaction};
const SELECT_STATS: &str = "SELECT profile_id, matches_played, matches_won, matches_drawn, matches_lost, goals_scored, goals_conceded, packs_opened, sbcs_completed, total_coins_earned, win_streak, best_win_streak, updated_at FROM statistics WHERE profile_id = ?";
const SELECT_STATS: &str = "SELECT profile_id, matches_played, matches_won, matches_drawn, matches_lost, matches_dnf, goals_scored, goals_conceded, packs_opened, sbcs_completed, total_coins_earned, win_streak, best_win_streak, updated_at FROM statistics WHERE profile_id = ?";
pub async fn get_or_create(pool: &Pool, profile_id: &str) -> AppResult<Statistics> {
if let Some(s) = sqlx::query_as::<_, Statistics>(SELECT_STATS)
@@ -77,6 +78,77 @@ pub async fn record_match(
Ok(())
}
/// Record a completed match within an existing transaction (the atomic
/// match-completion path). `outcome` is `win` | `draw` | `loss` | `dnf`. A DNF
/// (abandon/quit) increments its own bucket — never `matches_lost` — and, like a
/// loss, resets the win streak. All-or-nothing with the caller's transaction; it
/// never commits on its own, so a later failure rolls this back with everything
/// else.
pub async fn record_match_tx(
tx: &mut Transaction<'_, Sqlite>,
profile_id: &str,
outcome: &str,
goals_for: i64,
goals_against: i64,
coins: i64,
now: &str,
) -> AppResult<()> {
sqlx::query("INSERT OR IGNORE INTO statistics (profile_id, updated_at) VALUES (?, ?)")
.bind(profile_id)
.bind(now)
.execute(&mut **tx)
.await?;
let current_streak: i64 =
sqlx::query_scalar("SELECT win_streak FROM statistics WHERE profile_id = ?")
.bind(profile_id)
.fetch_one(&mut **tx)
.await?;
let (w, d, l, dnf) = match outcome {
"win" => (1i64, 0i64, 0i64, 0i64),
"draw" => (0, 1, 0, 0),
"dnf" => (0, 0, 0, 1),
_ => (0, 0, 1, 0),
};
let new_streak = if outcome == "win" {
current_streak + 1
} else {
0
};
sqlx::query(
"UPDATE statistics SET
matches_played = matches_played + 1,
matches_won = matches_won + ?,
matches_drawn = matches_drawn + ?,
matches_lost = matches_lost + ?,
matches_dnf = matches_dnf + ?,
goals_scored = goals_scored + ?,
goals_conceded = goals_conceded + ?,
total_coins_earned = total_coins_earned + ?,
win_streak = ?,
best_win_streak = MAX(best_win_streak, ?),
updated_at = ?
WHERE profile_id = ?",
)
.bind(w)
.bind(d)
.bind(l)
.bind(dnf)
.bind(goals_for)
.bind(goals_against)
.bind(coins)
.bind(new_streak)
.bind(new_streak)
.bind(now)
.bind(profile_id)
.execute(&mut **tx)
.await?;
Ok(())
}
pub async fn increment_packs_opened(pool: &Pool, profile_id: &str) -> AppResult<()> {
get_or_create(pool, profile_id).await?;
let now = chrono::Utc::now().to_rfc3339();
@@ -121,6 +193,26 @@ pub async fn record_position_goals(
Ok(())
}
/// Transaction-scoped [`record_position_goals`] for the atomic match-completion
/// path.
pub async fn record_position_goals_tx(
tx: &mut Transaction<'_, Sqlite>,
profile_id: &str,
positions: &[String],
) -> AppResult<()> {
for position in positions {
sqlx::query(
"INSERT INTO position_goals (profile_id, position, goals) VALUES (?, ?, 1) \
ON CONFLICT(profile_id, position) DO UPDATE SET goals = goals + 1",
)
.bind(profile_id)
.bind(position)
.execute(&mut **tx)
.await?;
}
Ok(())
}
pub async fn get_position_goals(pool: &Pool, profile_id: &str) -> AppResult<Vec<(String, i64)>> {
let rows: Vec<(String, i64)> = sqlx::query_as(
"SELECT position, goals FROM position_goals WHERE profile_id = ? ORDER BY goals DESC",