Compare commits
5 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 66c88fb48e | |||
| 9f3c545c46 | |||
| 352ad11bc4 | |||
| 3084a46dcc | |||
| 9b2c6b82f2 |
@@ -0,0 +1,10 @@
|
||||
-- Generic provenance/rerun-identity token for a transactionally imported profile.
|
||||
--
|
||||
-- Set by the generic profile-import path (services::import). A NULL value means
|
||||
-- the profile was created by normal gameplay / dev seeding, not an import, and
|
||||
-- MUST NOT be silently clobbered by an import targeting the same game. A
|
||||
-- matching token on a re-run is an idempotent no-op; a differing token against
|
||||
-- an already-imported game fails until an explicit update mode exists.
|
||||
--
|
||||
-- Core never interprets the token's structure; the importer adapter chooses it.
|
||||
ALTER TABLE profiles ADD COLUMN import_fingerprint TEXT;
|
||||
+65
-9
@@ -46,7 +46,34 @@ pub async fn build(pool: Pool, cfg: Config) -> Result<Router> {
|
||||
for game in &cfg.dev_content_games {
|
||||
card_db.load_game_dev(&cfg.data_dir, game)?;
|
||||
}
|
||||
for pack in &cfg.content_packs {
|
||||
card_db.load_pack(pack)?;
|
||||
}
|
||||
let card_db = Arc::new(card_db);
|
||||
|
||||
// Content preflight: every owned card MUST reference a loaded CardDefinition.
|
||||
// A real profile with owned players but missing definitions fails LOUDLY here
|
||||
// rather than silently serving an empty /collection. Empty owned_cards (fresh
|
||||
// DB, tests) passes. A SINGLE missing definition is caught, not only the
|
||||
// zero-loaded case.
|
||||
{
|
||||
let referenced: Vec<String> =
|
||||
sqlx::query_scalar("SELECT DISTINCT card_id FROM owned_cards")
|
||||
.fetch_all(&pool)
|
||||
.await?;
|
||||
let missing: Vec<String> = referenced
|
||||
.into_iter()
|
||||
.filter(|id| card_db.get(id).is_none())
|
||||
.collect();
|
||||
if !missing.is_empty() {
|
||||
let sample: Vec<&String> = missing.iter().take(5).collect();
|
||||
anyhow::bail!(
|
||||
"content preflight failed: {} owned card(s) reference CardDefinitionId(s) not loaded (e.g. {:?}). Load the production content pack via OPENFUT_CONTENT_PACKS.",
|
||||
missing.len(),
|
||||
sample
|
||||
);
|
||||
}
|
||||
}
|
||||
let pack_defs = Arc::new(load_pack_definitions(&cfg.data_dir)?);
|
||||
let obj_defs = Arc::new(load_objective_definitions(&cfg.data_dir)?);
|
||||
let sbc_defs = Arc::new(load_sbc_definitions(&cfg.data_dir)?);
|
||||
@@ -172,11 +199,16 @@ pub async fn build(pool: Pool, cfg: Config) -> Result<Router> {
|
||||
.route("/packs/open/:pack_id", post(routes::packs::post_open_pack))
|
||||
.route("/squad", get(routes::squad::get_squad))
|
||||
.route("/squad", post(routes::squad::post_squad))
|
||||
.route("/squad/ext", get(routes::squad::get_squad_ext))
|
||||
.route("/squad/replace", put(routes::squad::put_squad_replace))
|
||||
.route("/squads", get(routes::squad::get_squads))
|
||||
.route("/squads/:squad_id", get(routes::squad::get_squad_by_id))
|
||||
.route("/squads/:squad_id", delete(routes::squad::delete_squad))
|
||||
.route("/objectives", get(routes::objectives::get_objectives))
|
||||
.route("/objectives/:objective_id", get(routes::objectives::get_objective))
|
||||
.route(
|
||||
"/objectives/:objective_id",
|
||||
get(routes::objectives::get_objective),
|
||||
)
|
||||
.route(
|
||||
"/objectives/claim",
|
||||
post(routes::objectives::post_claim_objective),
|
||||
@@ -194,7 +226,10 @@ pub async fn build(pool: Pool, cfg: Config) -> Result<Router> {
|
||||
.route("/market", get(routes::market::get_market))
|
||||
.route("/market/buy", post(routes::market::post_market_buy))
|
||||
.route("/market/sell", post(routes::market::post_market_sell))
|
||||
.route("/market/trade-history", get(routes::market::get_trade_history))
|
||||
.route(
|
||||
"/market/trade-history",
|
||||
get(routes::market::get_trade_history),
|
||||
)
|
||||
.route("/market/refresh", post(routes::market::post_market_refresh))
|
||||
.route("/market/my-listings", get(routes::market::get_my_listings))
|
||||
.route(
|
||||
@@ -209,15 +244,36 @@ pub async fn build(pool: Pool, cfg: Config) -> Result<Router> {
|
||||
.route("/settings", get(routes::settings::get_settings))
|
||||
.route("/settings", put(routes::settings::put_settings))
|
||||
.route("/division", get(routes::division::get_division))
|
||||
.route("/division/history", get(routes::division::get_division_history))
|
||||
.route("/division/leaderboard", get(routes::division::get_division_leaderboard))
|
||||
.route(
|
||||
"/division/history",
|
||||
get(routes::division::get_division_history),
|
||||
)
|
||||
.route(
|
||||
"/division/leaderboard",
|
||||
get(routes::division::get_division_leaderboard),
|
||||
)
|
||||
.route("/achievements", get(routes::achievements::get_achievements))
|
||||
.route("/notifications", get(routes::notifications::get_notifications))
|
||||
.route("/notifications/read-all", post(routes::notifications::mark_all_notifications_read))
|
||||
.route("/notifications/:id/read", patch(routes::notifications::mark_notification_read))
|
||||
.route(
|
||||
"/notifications",
|
||||
get(routes::notifications::get_notifications),
|
||||
)
|
||||
.route(
|
||||
"/notifications/read-all",
|
||||
post(routes::notifications::mark_all_notifications_read),
|
||||
)
|
||||
.route(
|
||||
"/notifications/:id/read",
|
||||
patch(routes::notifications::mark_notification_read),
|
||||
)
|
||||
.route("/fut-champs", get(routes::fut_champs::get_fut_champs))
|
||||
.route("/fut-champs/start", post(routes::fut_champs::post_start_fut_champs))
|
||||
.route("/fut-champs/history", get(routes::fut_champs::get_champs_history))
|
||||
.route(
|
||||
"/fut-champs/start",
|
||||
post(routes::fut_champs::post_start_fut_champs),
|
||||
)
|
||||
.route(
|
||||
"/fut-champs/history",
|
||||
get(routes::fut_champs::get_champs_history),
|
||||
)
|
||||
.route(
|
||||
"/fut-champs/:session_id/result",
|
||||
post(routes::fut_champs::post_champs_result),
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use anyhow::Result;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Config {
|
||||
@@ -10,6 +11,11 @@ pub struct Config {
|
||||
/// loaded IN ADDITION to the default `data/cards` catalog. Empty by default —
|
||||
/// default/test content is never affected unless a game is named here.
|
||||
pub dev_content_games: Vec<String>,
|
||||
/// Explicit PRODUCTION content pack file paths (each a `CardDefinition[]`
|
||||
/// JSON), loaded IN ADDITION to `data/cards` and any dev pack. This is the
|
||||
/// production real-profile content path — deliberately NOT gated behind the
|
||||
/// dev-only `dev_content_games`.
|
||||
pub content_packs: Vec<PathBuf>,
|
||||
}
|
||||
|
||||
impl Config {
|
||||
@@ -33,6 +39,16 @@ impl Config {
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default(),
|
||||
content_packs: std::env::var("OPENFUT_CONTENT_PACKS")
|
||||
.ok()
|
||||
.map(|v| {
|
||||
v.split(',')
|
||||
.map(str::trim)
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(PathBuf::from)
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,6 +22,7 @@ pub async fn build_app(pool: db::Pool, data_dir: &str) -> Result<Router> {
|
||||
data_dir: data_dir.to_string(),
|
||||
max_connections: 1,
|
||||
dev_content_games: Vec::new(),
|
||||
content_packs: Vec::new(),
|
||||
};
|
||||
app::build(pool, cfg).await
|
||||
}
|
||||
|
||||
+29
-2
@@ -1,4 +1,4 @@
|
||||
use anyhow::Result;
|
||||
use anyhow::{Context, Result};
|
||||
use openfut_core::{config, db, seed};
|
||||
use tracing::info;
|
||||
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, EnvFilter};
|
||||
@@ -12,7 +12,9 @@ async fn main() -> Result<()> {
|
||||
EnvFilter::try_from_default_env()
|
||||
.unwrap_or_else(|_| "openfut_core=debug,tower_http=debug".into()),
|
||||
)
|
||||
.with(tracing_subscriber::fmt::layer())
|
||||
// Diagnostics on stderr so stdout carries only machine output (the
|
||||
// `import`/`seed-dev` subcommands print a clean JSON result there).
|
||||
.with(tracing_subscriber::fmt::layer().with_writer(std::io::stderr))
|
||||
.init();
|
||||
|
||||
let cfg = config::Config::from_env()?;
|
||||
@@ -30,6 +32,31 @@ async fn main() -> Result<()> {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// Opt-in generic import subcommand: `openfut-core import <request.json>`.
|
||||
// Reads a GAME-AGNOSTIC ProfileImportRequest (the importer adapter translates
|
||||
// FIFA17 source data into it), loads production content packs, runs preflight,
|
||||
// and applies one all-or-nothing transaction. FIFA17 semantics live entirely
|
||||
// in the adapter; Core only sees opaque ids + opaque extension bytes.
|
||||
if std::env::args().nth(1).as_deref() == Some("import") {
|
||||
let path = std::env::args()
|
||||
.nth(2)
|
||||
.context("usage: openfut-core import <request.json>")?;
|
||||
let pool = db::init_pool(&cfg.database_url, cfg.max_connections).await?;
|
||||
db::run_migrations(&pool).await?;
|
||||
let mut card_db = openfut_core::services::card_db::CardDb::load(&cfg.data_dir)?;
|
||||
for pack in &cfg.content_packs {
|
||||
card_db.load_pack(pack)?;
|
||||
}
|
||||
let raw = std::fs::read_to_string(&path)
|
||||
.with_context(|| format!("read import request {path}"))?;
|
||||
let req: openfut_core::services::import::ProfileImportRequest =
|
||||
serde_json::from_str(&raw).context("parse import request JSON")?;
|
||||
let outcome =
|
||||
openfut_core::services::import::apply_profile_import(&pool, &card_db, &req).await?;
|
||||
println!("{}", serde_json::to_string_pretty(&outcome)?);
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
info!("OpenFUT Core starting on {}", cfg.listen_addr);
|
||||
|
||||
let pool = db::init_pool(&cfg.database_url, cfg.max_connections).await?;
|
||||
|
||||
+141
-4
@@ -1,15 +1,21 @@
|
||||
use crate::extractors::GameId;
|
||||
use axum::{
|
||||
extract::{Path, State},
|
||||
extract::{Path, Query, State},
|
||||
Json,
|
||||
};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
use crate::{
|
||||
app::AppState,
|
||||
error::AppResult,
|
||||
models::squad::SaveSquadRequest,
|
||||
services::{club as club_svc, profile as profile_svc, squad as squad_svc},
|
||||
error::{AppError, AppResult},
|
||||
models::game_ext::OpaqueExtensionWrite,
|
||||
models::squad::{SaveSquadRequest, SlotAssignment, SquadReplacement},
|
||||
services::{
|
||||
club as club_svc, profile as profile_svc, squad as squad_svc,
|
||||
squad::SquadExtState,
|
||||
squad_rules::{ClientReportedEvaluation, DefaultSquadRules},
|
||||
},
|
||||
};
|
||||
|
||||
pub async fn get_squad(State(state): State<AppState>, game: GameId) -> AppResult<Json<Value>> {
|
||||
@@ -98,3 +104,134 @@ fn squad_response(
|
||||
"chemistry": chemistry,
|
||||
})
|
||||
}
|
||||
|
||||
// ─────────── Game-extension-aware squad transport (host composition) ─────────
|
||||
//
|
||||
// These two routes expose the already-existing extension services
|
||||
// (`read_squad_with_ext` / `replace_squad_with_extension`) over HTTP so a game
|
||||
// host can read/write the canonical squad AND its opaque game extension in one
|
||||
// Core round-trip. They add no domain logic — Core still owns validation,
|
||||
// ownership, the atomic transaction, the server fingerprint, and staleness; it
|
||||
// never interprets the extension payload.
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct ExtQuery {
|
||||
/// Opaque adapter namespace, e.g. `"fifa17.squad"`.
|
||||
pub namespace: String,
|
||||
}
|
||||
|
||||
/// `GET /squad/ext?namespace=…` — the active squad, its players, and its opaque
|
||||
/// extension with an explicit Fresh/Stale/Missing verdict. Never projects a
|
||||
/// stale blob; the caller decides policy.
|
||||
pub async fn get_squad_ext(
|
||||
State(state): State<AppState>,
|
||||
game: GameId,
|
||||
Query(q): Query<ExtQuery>,
|
||||
) -> AppResult<Json<Value>> {
|
||||
let profile = profile_svc::get_active_profile(&state.pool, game.as_str()).await?;
|
||||
let club = club_svc::get_club_by_profile(&state.pool, &profile.id).await?;
|
||||
let (squad, players, state_ext) =
|
||||
squad_svc::read_squad_with_ext(&state.pool, game.as_str(), &club.id, &q.namespace).await?;
|
||||
|
||||
let extension = match state_ext {
|
||||
SquadExtState::Fresh(row) => json!({
|
||||
"state": "fresh",
|
||||
"schema_version": row.schema_version,
|
||||
"payload": row.payload,
|
||||
"stored_fingerprint": row.canonical_fingerprint,
|
||||
}),
|
||||
SquadExtState::Stale {
|
||||
stored,
|
||||
current_fingerprint,
|
||||
} => json!({
|
||||
"state": "stale",
|
||||
"schema_version": stored.schema_version,
|
||||
"payload": stored.payload,
|
||||
"stored_fingerprint": stored.canonical_fingerprint,
|
||||
"current_fingerprint": current_fingerprint,
|
||||
}),
|
||||
SquadExtState::Missing => json!({ "state": "missing" }),
|
||||
};
|
||||
|
||||
Ok(Json(json!({
|
||||
"squad": squad,
|
||||
"players": players,
|
||||
"extension": extension,
|
||||
})))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct SlotReq {
|
||||
pub owned_card_id: String,
|
||||
pub slot: i64,
|
||||
#[serde(default)]
|
||||
pub is_captain: bool,
|
||||
#[serde(default)]
|
||||
pub is_on_bench: bool,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct ReplaceReq {
|
||||
#[serde(default)]
|
||||
pub name: Option<String>,
|
||||
#[serde(default)]
|
||||
pub formation: Option<String>,
|
||||
pub slots: Vec<SlotReq>,
|
||||
#[serde(default)]
|
||||
pub client_reported: ClientReportedEvaluation,
|
||||
pub extension: OpaqueExtensionWrite,
|
||||
}
|
||||
|
||||
/// `PUT /squad/replace` — full-replacement of the active squad's canonical slots
|
||||
/// plus its opaque game extension, in ONE Core transaction. Resolves the active
|
||||
/// squad in place (creates one if none exists). Ownership, duplicate, and size
|
||||
/// validation happen inside the service before any write.
|
||||
pub async fn put_squad_replace(
|
||||
State(state): State<AppState>,
|
||||
game: GameId,
|
||||
Json(req): Json<ReplaceReq>,
|
||||
) -> AppResult<Json<Value>> {
|
||||
let profile = profile_svc::get_active_profile(&state.pool, game.as_str()).await?;
|
||||
let club = club_svc::get_club_by_profile(&state.pool, &profile.id).await?;
|
||||
|
||||
// Replace the club's active squad in place; if there is none yet, create it.
|
||||
let squad_id = match squad_svc::get_squad(&state.pool, &club.id).await {
|
||||
Ok((s, _)) => Some(s.id),
|
||||
Err(AppError::NotFound(_)) => None,
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
|
||||
let replacement = SquadReplacement {
|
||||
name: req.name,
|
||||
formation: req.formation,
|
||||
slots: req
|
||||
.slots
|
||||
.into_iter()
|
||||
.map(|s| SlotAssignment {
|
||||
owned_card_id: s.owned_card_id,
|
||||
slot: s.slot,
|
||||
is_captain: s.is_captain,
|
||||
is_on_bench: s.is_on_bench,
|
||||
})
|
||||
.collect(),
|
||||
};
|
||||
|
||||
let out = squad_svc::replace_squad_with_extension(
|
||||
&state.pool,
|
||||
&state.card_db,
|
||||
&DefaultSquadRules,
|
||||
game.as_str(),
|
||||
&club.id,
|
||||
squad_id.as_deref(),
|
||||
&replacement,
|
||||
&req.client_reported,
|
||||
&req.extension,
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(Json(json!({
|
||||
"squad_id": out.squad.id,
|
||||
"canonical_fingerprint": out.canonical_fingerprint,
|
||||
"slots_written": out.slots_written,
|
||||
})))
|
||||
}
|
||||
|
||||
@@ -62,6 +62,23 @@ impl CardDb {
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
/// Merge an explicit PRODUCTION content pack file (a single
|
||||
/// `CardDefinition[]`). Unlike [`CardDb::load_game_dev`] this takes a direct
|
||||
/// path (the real-profile import emits one) and is the production content
|
||||
/// path — not gated behind dev content. Returns the number merged.
|
||||
pub fn load_pack(&mut self, path: &Path) -> Result<usize> {
|
||||
let content = std::fs::read_to_string(path)
|
||||
.with_context(|| format!("reading content pack {path:?}"))?;
|
||||
let batch: Vec<CardDefinition> =
|
||||
serde_json::from_str(&content).with_context(|| format!("parsing {path:?}"))?;
|
||||
let n = batch.len();
|
||||
for card in batch {
|
||||
self.cards.insert(card.id.clone(), card);
|
||||
}
|
||||
tracing::info!("Loaded {} production card definitions from {:?}", n, path);
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
pub fn get(&self, id: &str) -> Option<&CardDefinition> {
|
||||
self.cards.get(id)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,318 @@
|
||||
//! Generic, game-agnostic transactional profile import.
|
||||
//!
|
||||
//! Core installs a profile + club + owned cards + canonical squad + one opaque
|
||||
//! game extension in a SINGLE all-or-nothing SQLite transaction, stamped with a
|
||||
//! generic `source_fingerprint` provenance token. Core NEVER interprets FIFA17
|
||||
//! wire ids, resourceIds, `nextItemId`, or the extension payload — the
|
||||
//! `openfut-import-fifa17` adapter reads the Python profile, chooses every
|
||||
//! `CardDefinitionId` and every opaque `OwnedItemId`, builds the squad
|
||||
//! extension bytes, and hands Core this generic request.
|
||||
//!
|
||||
//! Invariants enforced here:
|
||||
//! - Definition preflight: every incoming `card_id` MUST already resolve in the
|
||||
//! loaded production content, so the transaction never creates ownership
|
||||
//! pointing at absent content.
|
||||
//! - Squad all-or-nothing: every active-squad `owned_item_id` MUST be among the
|
||||
//! imported ownership set before the transaction begins.
|
||||
//! - Rerun identity: identical `source_fingerprint` against an already-imported
|
||||
//! game is an idempotent no-op; a differing token fails; a pre-existing
|
||||
//! non-imported profile is never clobbered.
|
||||
//! - The whole thing commits together or not at all.
|
||||
|
||||
use crate::db::Pool;
|
||||
use crate::models::game_ext::{MAX_EXT_NAMESPACE_LEN, MAX_EXT_PAYLOAD_BYTES};
|
||||
use crate::services::card_db::CardDb;
|
||||
use crate::services::squad::squad_fingerprint;
|
||||
use anyhow::{bail, Context, Result};
|
||||
use chrono::Utc;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashSet;
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct ImportProfile {
|
||||
pub username: String,
|
||||
pub game_id: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct ImportClub {
|
||||
pub name: String,
|
||||
#[serde(default)]
|
||||
pub coins: i64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct ImportOwnedCard {
|
||||
/// Opaque, stable Core OwnedItemId chosen by the adapter. Core never parses
|
||||
/// why it is stable — it is a primary key, nothing more.
|
||||
pub owned_item_id: String,
|
||||
/// CardDefinitionId that MUST resolve in loaded production content.
|
||||
pub card_id: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct ImportSlot {
|
||||
pub owned_item_id: String,
|
||||
pub position_index: i64,
|
||||
#[serde(default)]
|
||||
pub is_captain: bool,
|
||||
#[serde(default)]
|
||||
pub is_on_bench: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct ImportExtension {
|
||||
/// Opaque adapter key, e.g. "fifa17.squad.v1".
|
||||
pub namespace: String,
|
||||
/// Adapter payload version (distinct from DB storage schema).
|
||||
pub schema_version: i64,
|
||||
/// Uninterpreted bytes-as-text. Core enforces only generic size bounds.
|
||||
pub payload: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct ImportSquad {
|
||||
pub formation: String,
|
||||
#[serde(default = "default_squad_name")]
|
||||
pub name: String,
|
||||
pub slots: Vec<ImportSlot>,
|
||||
pub extension: ImportExtension,
|
||||
}
|
||||
|
||||
fn default_squad_name() -> String {
|
||||
"My Squad".to_string()
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct ProfileImportRequest {
|
||||
/// Generic provenance/rerun-identity token. Core stores it verbatim.
|
||||
pub source_fingerprint: String,
|
||||
pub profile: ImportProfile,
|
||||
pub club: ImportClub,
|
||||
pub owned: Vec<ImportOwnedCard>,
|
||||
#[serde(default)]
|
||||
pub squad: Option<ImportSquad>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, PartialEq, Eq)]
|
||||
#[serde(tag = "outcome", rename_all = "snake_case")]
|
||||
pub enum ImportOutcome {
|
||||
/// A fresh import committed.
|
||||
Imported { owned: usize, squad_slots: usize },
|
||||
/// The same fingerprint was already imported for this game — no-op.
|
||||
AlreadyImported,
|
||||
}
|
||||
|
||||
/// Apply a generic transactional profile import. See module docs for invariants.
|
||||
pub async fn apply_profile_import(
|
||||
pool: &Pool,
|
||||
card_db: &CardDb,
|
||||
req: &ProfileImportRequest,
|
||||
) -> Result<ImportOutcome> {
|
||||
// ── 0. generic input validation (no writes) ──
|
||||
if req.source_fingerprint.trim().is_empty() {
|
||||
bail!("source_fingerprint must be non-empty");
|
||||
}
|
||||
if req.owned.is_empty() {
|
||||
bail!("import request has zero owned cards; refusing to import an empty profile");
|
||||
}
|
||||
|
||||
// ── 1. rerun identity / single-profile-per-game ──
|
||||
let existing: Option<(String, Option<String>)> = sqlx::query_as(
|
||||
"SELECT id, import_fingerprint FROM profiles \
|
||||
WHERE game_id = ? ORDER BY created_at ASC LIMIT 1",
|
||||
)
|
||||
.bind(&req.profile.game_id)
|
||||
.fetch_optional(pool)
|
||||
.await?;
|
||||
if let Some((_id, fp)) = existing {
|
||||
match fp {
|
||||
Some(fp) if fp == req.source_fingerprint => return Ok(ImportOutcome::AlreadyImported),
|
||||
Some(fp) => bail!(
|
||||
"game '{}' already imported from a different source (stored fingerprint {fp}, \
|
||||
incoming {}); refusing to overwrite without an explicit update mode",
|
||||
req.profile.game_id,
|
||||
req.source_fingerprint
|
||||
),
|
||||
None => bail!(
|
||||
"game '{}' already has a non-imported profile; refusing to clobber it",
|
||||
req.profile.game_id
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
// ── 2. definition preflight: every card_id MUST resolve in loaded content ──
|
||||
let mut missing: Vec<&str> = req
|
||||
.owned
|
||||
.iter()
|
||||
.filter(|o| card_db.get(&o.card_id).is_none())
|
||||
.map(|o| o.card_id.as_str())
|
||||
.collect();
|
||||
if !missing.is_empty() {
|
||||
missing.sort_unstable();
|
||||
missing.dedup();
|
||||
let sample = &missing[..missing.len().min(5)];
|
||||
bail!(
|
||||
"definition preflight failed: {} owned card(s) reference CardDefinitionId(s) not in \
|
||||
loaded content (e.g. {sample:?}); refusing to create ownership pointing at absent content",
|
||||
missing.len()
|
||||
);
|
||||
}
|
||||
|
||||
// ── 3. owned-item-id uniqueness ──
|
||||
let mut owned_ids: HashSet<&str> = HashSet::with_capacity(req.owned.len());
|
||||
for o in &req.owned {
|
||||
if !owned_ids.insert(o.owned_item_id.as_str()) {
|
||||
bail!(
|
||||
"duplicate OwnedItemId in import request: {}",
|
||||
o.owned_item_id
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ── 4. squad all-or-nothing + generic extension bounds (no writes) ──
|
||||
if let Some(sq) = &req.squad {
|
||||
let ns_len = sq.extension.namespace.len();
|
||||
if ns_len == 0 || ns_len > MAX_EXT_NAMESPACE_LEN {
|
||||
bail!(
|
||||
"extension namespace length {ns_len} out of bounds (1..={MAX_EXT_NAMESPACE_LEN})"
|
||||
);
|
||||
}
|
||||
if sq.extension.payload.len() > MAX_EXT_PAYLOAD_BYTES {
|
||||
bail!(
|
||||
"extension payload {} bytes exceeds MAX_EXT_PAYLOAD_BYTES ({MAX_EXT_PAYLOAD_BYTES})",
|
||||
sq.extension.payload.len()
|
||||
);
|
||||
}
|
||||
for slot in &sq.slots {
|
||||
if !owned_ids.contains(slot.owned_item_id.as_str()) {
|
||||
bail!(
|
||||
"active squad references OwnedItemId {} not present in imported ownership set; \
|
||||
squad import is all-or-nothing",
|
||||
slot.owned_item_id
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── 5. single transaction: everything commits together or not at all ──
|
||||
let now = Utc::now().to_rfc3339();
|
||||
let profile_id = Uuid::new_v4().to_string();
|
||||
let club_id = Uuid::new_v4().to_string();
|
||||
let mut tx = pool.begin().await?;
|
||||
|
||||
sqlx::query(
|
||||
"INSERT INTO profiles (id, username, level, xp, game_id, created_at, updated_at, import_fingerprint) \
|
||||
VALUES (?, ?, 1, 0, ?, ?, ?, ?)",
|
||||
)
|
||||
.bind(&profile_id)
|
||||
.bind(&req.profile.username)
|
||||
.bind(&req.profile.game_id)
|
||||
.bind(&now)
|
||||
.bind(&now)
|
||||
.bind(&req.source_fingerprint)
|
||||
.execute(&mut *tx)
|
||||
.await
|
||||
.context("insert profile")?;
|
||||
|
||||
sqlx::query(
|
||||
"INSERT INTO clubs (id, profile_id, name, coins, level, created_at, updated_at) \
|
||||
VALUES (?, ?, ?, ?, 1, ?, ?)",
|
||||
)
|
||||
.bind(&club_id)
|
||||
.bind(&profile_id)
|
||||
.bind(&req.club.name)
|
||||
.bind(req.club.coins)
|
||||
.bind(&now)
|
||||
.bind(&now)
|
||||
.execute(&mut *tx)
|
||||
.await
|
||||
.context("insert club")?;
|
||||
|
||||
for o in &req.owned {
|
||||
sqlx::query(
|
||||
"INSERT INTO owned_cards (id, club_id, card_id, is_loan, loan_matches_remaining, acquired_at) \
|
||||
VALUES (?, ?, ?, 0, NULL, ?)",
|
||||
)
|
||||
.bind(&o.owned_item_id)
|
||||
.bind(&club_id)
|
||||
.bind(&o.card_id)
|
||||
.bind(&now)
|
||||
.execute(&mut *tx)
|
||||
.await
|
||||
.with_context(|| format!("insert owned_card {}", o.owned_item_id))?;
|
||||
}
|
||||
|
||||
let mut squad_slots = 0usize;
|
||||
if let Some(sq) = &req.squad {
|
||||
let squad_id = Uuid::new_v4().to_string();
|
||||
sqlx::query(
|
||||
"INSERT INTO squads (id, club_id, name, formation, created_at, updated_at) \
|
||||
VALUES (?, ?, ?, ?, ?, ?)",
|
||||
)
|
||||
.bind(&squad_id)
|
||||
.bind(&club_id)
|
||||
.bind(&sq.name)
|
||||
.bind(&sq.formation)
|
||||
.bind(&now)
|
||||
.bind(&now)
|
||||
.execute(&mut *tx)
|
||||
.await
|
||||
.context("insert squad")?;
|
||||
|
||||
for slot in &sq.slots {
|
||||
sqlx::query(
|
||||
"INSERT INTO squad_players (id, squad_id, owned_card_id, position_index, is_captain, is_on_bench) \
|
||||
VALUES (?, ?, ?, ?, ?, ?)",
|
||||
)
|
||||
.bind(Uuid::new_v4().to_string())
|
||||
.bind(&squad_id)
|
||||
.bind(&slot.owned_item_id)
|
||||
.bind(slot.position_index)
|
||||
.bind(slot.is_captain)
|
||||
.bind(slot.is_on_bench)
|
||||
.execute(&mut *tx)
|
||||
.await
|
||||
.context("insert squad_player")?;
|
||||
}
|
||||
squad_slots = sq.slots.len();
|
||||
|
||||
// Core computes the canonical fingerprint over the COMMITTED squad — never
|
||||
// an adapter-supplied value — and persists the opaque extension atomically
|
||||
// in the same tx, exactly as the live squad-write path does.
|
||||
let canonical_fingerprint = squad_fingerprint(
|
||||
&squad_id,
|
||||
&sq.formation,
|
||||
sq.slots.iter().map(|s| {
|
||||
(
|
||||
s.position_index,
|
||||
s.owned_item_id.as_str(),
|
||||
s.is_captain,
|
||||
s.is_on_bench,
|
||||
)
|
||||
}),
|
||||
);
|
||||
sqlx::query(
|
||||
"INSERT OR REPLACE INTO game_entity_ext \
|
||||
(game_id, entity_kind, entity_id, namespace, schema_version, canonical_fingerprint, payload, updated_at) \
|
||||
VALUES (?, 'squad', ?, ?, ?, ?, ?, ?)",
|
||||
)
|
||||
.bind(&req.profile.game_id)
|
||||
.bind(&squad_id)
|
||||
.bind(&sq.extension.namespace)
|
||||
.bind(sq.extension.schema_version)
|
||||
.bind(&canonical_fingerprint)
|
||||
.bind(&sq.extension.payload)
|
||||
.bind(&now)
|
||||
.execute(&mut *tx)
|
||||
.await
|
||||
.context("insert game_entity_ext")?;
|
||||
}
|
||||
|
||||
tx.commit().await?;
|
||||
Ok(ImportOutcome::Imported {
|
||||
owned: req.owned.len(),
|
||||
squad_slots,
|
||||
})
|
||||
}
|
||||
+3
-2
@@ -2,19 +2,20 @@ pub mod achievement;
|
||||
pub mod card_db;
|
||||
pub mod checkin;
|
||||
pub mod club;
|
||||
pub mod notification;
|
||||
pub mod draft;
|
||||
pub mod event;
|
||||
pub mod fut_champs;
|
||||
pub mod game_ext;
|
||||
pub mod import;
|
||||
pub mod inventory;
|
||||
pub mod season;
|
||||
pub mod market;
|
||||
pub mod match_service;
|
||||
pub mod notification;
|
||||
pub mod objective;
|
||||
pub mod pack;
|
||||
pub mod profile;
|
||||
pub mod sbc;
|
||||
pub mod season;
|
||||
pub mod settings;
|
||||
pub mod squad;
|
||||
pub mod squad_rules;
|
||||
|
||||
@@ -497,7 +497,7 @@ pub async fn replace_squad_with_extension(
|
||||
/// computed; non-cryptographic (FNV-1a-64) — a stale-extension guard, not a
|
||||
/// security boundary. The encoding is sorted + delimited so it never depends on
|
||||
/// row/iteration order.
|
||||
fn squad_fingerprint<'a>(
|
||||
pub(crate) fn squad_fingerprint<'a>(
|
||||
squad_id: &str,
|
||||
formation: &str,
|
||||
slots: impl Iterator<Item = (i64, &'a str, bool, bool)>,
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
//! Content preflight: a real profile with owned players but a missing
|
||||
//! CardDefinition must fail startup LOUDLY, never serve a silent empty club.
|
||||
|
||||
use axum::{
|
||||
body::Body,
|
||||
http::{Request, StatusCode},
|
||||
};
|
||||
use openfut_core::services::card_db::CardDb;
|
||||
use tower::ServiceExt;
|
||||
|
||||
async fn fresh_pool() -> sqlx::SqlitePool {
|
||||
let p = sqlx::sqlite::SqlitePoolOptions::new()
|
||||
.max_connections(1)
|
||||
.connect("sqlite::memory:")
|
||||
.await
|
||||
.expect("in-memory sqlite");
|
||||
sqlx::migrate!("./migrations")
|
||||
.run(&p)
|
||||
.await
|
||||
.expect("migrations");
|
||||
p
|
||||
}
|
||||
|
||||
async fn create_profile(app: &axum::Router) {
|
||||
let resp = app
|
||||
.clone()
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.method("POST")
|
||||
.uri("/auth/local")
|
||||
.header("content-type", "application/json")
|
||||
.body(Body::from(r#"{"username":"CAGE"}"#))
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
resp.status(),
|
||||
StatusCode::OK,
|
||||
"auth/local should create a profile+club"
|
||||
);
|
||||
}
|
||||
|
||||
async fn insert_owned(pool: &sqlx::SqlitePool, id: &str, club_id: &str, card_id: &str) {
|
||||
sqlx::query(
|
||||
"INSERT INTO owned_cards (id, club_id, card_id, is_loan, loan_matches_remaining, acquired_at) \
|
||||
VALUES (?, ?, ?, 0, NULL, ?)",
|
||||
)
|
||||
.bind(id)
|
||||
.bind(club_id)
|
||||
.bind(card_id)
|
||||
.bind("2026-01-01T00:00:00Z")
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn preflight_fails_on_owned_card_missing_definition() {
|
||||
let pool = fresh_pool().await;
|
||||
// first build is fine: no owned cards yet.
|
||||
let app = openfut_core::build_app(pool.clone(), "data").await.unwrap();
|
||||
create_profile(&app).await;
|
||||
let club: String = sqlx::query_scalar("SELECT id FROM clubs LIMIT 1")
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
insert_owned(&pool, "oc-bogus", &club, "fifa17_definitely_missing_999999").await;
|
||||
|
||||
// second build must now fail preflight: one owned card references a def that
|
||||
// is not loaded — must not silently serve an empty collection.
|
||||
let err = openfut_core::build_app(pool.clone(), "data")
|
||||
.await
|
||||
.expect_err("preflight must fail on a missing definition");
|
||||
let msg = format!("{err:#}");
|
||||
assert!(
|
||||
msg.contains("content preflight failed"),
|
||||
"unexpected error: {msg}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn preflight_passes_when_owned_card_definition_is_loaded() {
|
||||
let pool = fresh_pool().await;
|
||||
// pick a definition that IS in the default data/cards catalog.
|
||||
let valid_id = CardDb::load("data")
|
||||
.unwrap()
|
||||
.all()
|
||||
.first()
|
||||
.map(|c| c.id.clone())
|
||||
.expect("data/cards must be non-empty");
|
||||
|
||||
let app = openfut_core::build_app(pool.clone(), "data").await.unwrap();
|
||||
create_profile(&app).await;
|
||||
let club: String = sqlx::query_scalar("SELECT id FROM clubs LIMIT 1")
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
insert_owned(&pool, "oc-valid", &club, &valid_id).await;
|
||||
|
||||
let _app = openfut_core::build_app(pool.clone(), "data")
|
||||
.await
|
||||
.expect("preflight passes when the owned card's definition is loaded");
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
//! Generic transactional profile import (services::import). These also serve as
|
||||
//! the Core-level half of the migration mutation battery: each hostile input is
|
||||
//! rejected BEFORE any partial write, and re-runs converge instead of duplicating.
|
||||
|
||||
use openfut_core::services::card_db::CardDb;
|
||||
use openfut_core::services::import::{
|
||||
apply_profile_import, ImportClub, ImportExtension, ImportOwnedCard, ImportProfile, ImportSlot,
|
||||
ImportSquad, ProfileImportRequest,
|
||||
};
|
||||
|
||||
async fn fresh_pool() -> sqlx::SqlitePool {
|
||||
let p = sqlx::sqlite::SqlitePoolOptions::new()
|
||||
.max_connections(1)
|
||||
.connect("sqlite::memory:")
|
||||
.await
|
||||
.expect("in-memory sqlite");
|
||||
sqlx::migrate!("./migrations")
|
||||
.run(&p)
|
||||
.await
|
||||
.expect("migrations");
|
||||
p
|
||||
}
|
||||
|
||||
fn valid_ids(n: usize) -> Vec<String> {
|
||||
let db = CardDb::load("data").expect("load data catalog");
|
||||
let ids: Vec<String> = db.all().iter().take(n).map(|c| c.id.clone()).collect();
|
||||
assert!(ids.len() >= n, "data catalog too small for test");
|
||||
ids
|
||||
}
|
||||
|
||||
fn owned(ids: &[String]) -> Vec<ImportOwnedCard> {
|
||||
ids.iter()
|
||||
.enumerate()
|
||||
.map(|(i, id)| ImportOwnedCard {
|
||||
owned_item_id: format!("oc-{i}"),
|
||||
card_id: id.clone(),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn squad_over(owned: &[ImportOwnedCard]) -> ImportSquad {
|
||||
ImportSquad {
|
||||
formation: "f433".into(),
|
||||
name: "OpenFUT".into(),
|
||||
slots: owned
|
||||
.iter()
|
||||
.take(3)
|
||||
.enumerate()
|
||||
.map(|(i, o)| ImportSlot {
|
||||
owned_item_id: o.owned_item_id.clone(),
|
||||
position_index: i as i64,
|
||||
is_captain: i == 0,
|
||||
is_on_bench: false,
|
||||
})
|
||||
.collect(),
|
||||
extension: ImportExtension {
|
||||
namespace: "fifa17.squad.v1".into(),
|
||||
schema_version: 1,
|
||||
payload: r#"{"custom":[]}"#.into(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn request(
|
||||
game: &str,
|
||||
fp: &str,
|
||||
owned: Vec<ImportOwnedCard>,
|
||||
squad: Option<ImportSquad>,
|
||||
) -> ProfileImportRequest {
|
||||
ProfileImportRequest {
|
||||
source_fingerprint: fp.into(),
|
||||
profile: ImportProfile {
|
||||
username: format!("CAGE-{game}"),
|
||||
game_id: game.into(),
|
||||
},
|
||||
club: ImportClub {
|
||||
name: "OpenFUT".into(),
|
||||
coins: 28_112_944,
|
||||
},
|
||||
owned,
|
||||
squad,
|
||||
}
|
||||
}
|
||||
|
||||
async fn count(pool: &sqlx::SqlitePool, table: &str) -> i64 {
|
||||
sqlx::query_scalar(&format!("SELECT COUNT(*) FROM {table}"))
|
||||
.fetch_one(pool)
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn imports_profile_club_owned_and_squad_in_one_shot() {
|
||||
let pool = fresh_pool().await;
|
||||
let db = CardDb::load("data").unwrap();
|
||||
let ids = valid_ids(5);
|
||||
let ow = owned(&ids);
|
||||
let sq = squad_over(&ow);
|
||||
let req = request("g_happy", "fp-happy", ow, Some(sq));
|
||||
|
||||
let out = apply_profile_import(&pool, &db, &req)
|
||||
.await
|
||||
.expect("import");
|
||||
assert!(matches!(
|
||||
out,
|
||||
openfut_core::services::import::ImportOutcome::Imported {
|
||||
owned: 5,
|
||||
squad_slots: 3
|
||||
}
|
||||
));
|
||||
|
||||
assert_eq!(count(&pool, "profiles").await, 1);
|
||||
assert_eq!(count(&pool, "clubs").await, 1);
|
||||
assert_eq!(count(&pool, "owned_cards").await, 5);
|
||||
assert_eq!(count(&pool, "squad_players").await, 3);
|
||||
// opaque extension persisted with a Core-computed fingerprint.
|
||||
let fp: String =
|
||||
sqlx::query_scalar("SELECT canonical_fingerprint FROM game_entity_ext LIMIT 1")
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(fp.len(), 16, "16-hex FNV fingerprint");
|
||||
let stored_import_fp: String =
|
||||
sqlx::query_scalar("SELECT import_fingerprint FROM profiles LIMIT 1")
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(stored_import_fp, "fp-happy");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rerun_same_fingerprint_is_idempotent_noop() {
|
||||
let pool = fresh_pool().await;
|
||||
let db = CardDb::load("data").unwrap();
|
||||
let ids = valid_ids(4);
|
||||
let mk = || {
|
||||
request(
|
||||
"g_rerun",
|
||||
"fp-x",
|
||||
owned(&ids),
|
||||
Some(squad_over(&owned(&ids))),
|
||||
)
|
||||
};
|
||||
|
||||
apply_profile_import(&pool, &db, &mk())
|
||||
.await
|
||||
.expect("first");
|
||||
let out = apply_profile_import(&pool, &db, &mk())
|
||||
.await
|
||||
.expect("second");
|
||||
assert_eq!(
|
||||
out,
|
||||
openfut_core::services::import::ImportOutcome::AlreadyImported
|
||||
);
|
||||
// no duplication.
|
||||
assert_eq!(count(&pool, "profiles").await, 1);
|
||||
assert_eq!(count(&pool, "owned_cards").await, 4);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn different_fingerprint_on_imported_game_fails() {
|
||||
let pool = fresh_pool().await;
|
||||
let db = CardDb::load("data").unwrap();
|
||||
let ids = valid_ids(3);
|
||||
apply_profile_import(&pool, &db, &request("g_diff", "fp-a", owned(&ids), None))
|
||||
.await
|
||||
.expect("first");
|
||||
let err = apply_profile_import(&pool, &db, &request("g_diff", "fp-b", owned(&ids), None))
|
||||
.await
|
||||
.expect_err("second, different fingerprint");
|
||||
assert!(format!("{err:#}").contains("different source"), "{err:#}");
|
||||
assert_eq!(count(&pool, "profiles").await, 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn missing_definition_fails_preflight_with_no_writes() {
|
||||
let pool = fresh_pool().await;
|
||||
let db = CardDb::load("data").unwrap();
|
||||
let mut ow = owned(&valid_ids(2));
|
||||
ow.push(ImportOwnedCard {
|
||||
owned_item_id: "oc-bad".into(),
|
||||
card_id: "fifa17_definitely_absent_999999".into(),
|
||||
});
|
||||
let err = apply_profile_import(&pool, &db, &request("g_miss", "fp", ow, None))
|
||||
.await
|
||||
.expect_err("missing definition must fail");
|
||||
assert!(
|
||||
format!("{err:#}").contains("definition preflight failed"),
|
||||
"{err:#}"
|
||||
);
|
||||
// preflight is before the tx: nothing was written.
|
||||
assert_eq!(count(&pool, "profiles").await, 0);
|
||||
assert_eq!(count(&pool, "owned_cards").await, 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn squad_slot_not_in_ownership_fails() {
|
||||
let pool = fresh_pool().await;
|
||||
let db = CardDb::load("data").unwrap();
|
||||
let ids = valid_ids(3);
|
||||
let ow = owned(&ids);
|
||||
let mut sq = squad_over(&ow);
|
||||
sq.slots[1].owned_item_id = "oc-not-owned".into();
|
||||
let err = apply_profile_import(&pool, &db, &request("g_sq", "fp", ow, Some(sq)))
|
||||
.await
|
||||
.expect_err("squad slot not owned must fail");
|
||||
assert!(format!("{err:#}").contains("all-or-nothing"), "{err:#}");
|
||||
assert_eq!(count(&pool, "profiles").await, 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn duplicate_owned_item_id_fails() {
|
||||
let pool = fresh_pool().await;
|
||||
let db = CardDb::load("data").unwrap();
|
||||
let ids = valid_ids(2);
|
||||
let mut ow = owned(&ids);
|
||||
ow[1].owned_item_id = ow[0].owned_item_id.clone();
|
||||
let err = apply_profile_import(&pool, &db, &request("g_dup", "fp", ow, None))
|
||||
.await
|
||||
.expect_err("duplicate OwnedItemId must fail");
|
||||
assert!(
|
||||
format!("{err:#}").contains("duplicate OwnedItemId"),
|
||||
"{err:#}"
|
||||
);
|
||||
assert_eq!(count(&pool, "profiles").await, 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn non_imported_profile_is_not_clobbered() {
|
||||
let pool = fresh_pool().await;
|
||||
let db = CardDb::load("data").unwrap();
|
||||
// simulate a gameplay/dev profile with NO import_fingerprint for this game.
|
||||
sqlx::query(
|
||||
"INSERT INTO profiles (id, username, level, xp, game_id, created_at, updated_at) \
|
||||
VALUES ('p0','someone',1,0,'g_clobber','2026-01-01T00:00:00Z','2026-01-01T00:00:00Z')",
|
||||
)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let ids = valid_ids(2);
|
||||
let err = apply_profile_import(&pool, &db, &request("g_clobber", "fp", owned(&ids), None))
|
||||
.await
|
||||
.expect_err("must refuse to clobber a non-imported profile");
|
||||
assert!(format!("{err:#}").contains("non-imported"), "{err:#}");
|
||||
assert_eq!(count(&pool, "owned_cards").await, 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn empty_owned_fails() {
|
||||
let pool = fresh_pool().await;
|
||||
let db = CardDb::load("data").unwrap();
|
||||
let err = apply_profile_import(&pool, &db, &request("g_empty", "fp", vec![], None))
|
||||
.await
|
||||
.expect_err("empty owned must fail");
|
||||
assert!(format!("{err:#}").contains("zero owned cards"), "{err:#}");
|
||||
}
|
||||
@@ -675,7 +675,7 @@ async fn test_draft_pick_advances_session() {
|
||||
assert_eq!(pick1["status"], "active");
|
||||
assert_eq!(pick1["progress"]["filled"], 1);
|
||||
assert_eq!(pick1["current_position"], "RB");
|
||||
assert!(pick1["candidates"].as_array().unwrap().len() >= 1);
|
||||
assert!(!pick1["candidates"].as_array().unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -2279,3 +2279,84 @@ async fn test_owned_query_parameter_order_invariance() {
|
||||
);
|
||||
assert_eq!(a["total"], b["total"]);
|
||||
}
|
||||
|
||||
|
||||
async fn json_put(app: &axum::Router, uri: &str, payload: Value) -> (StatusCode, Value) {
|
||||
let resp = app
|
||||
.clone()
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.method("PUT")
|
||||
.uri(uri)
|
||||
.header("content-type", "application/json")
|
||||
.body(Body::from(payload.to_string()))
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let status = resp.status();
|
||||
let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
|
||||
.await
|
||||
.unwrap();
|
||||
(status, serde_json::from_slice(&body).unwrap())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_squad_ext_replace_read_roundtrip_and_idempotency() {
|
||||
let app = build_test_app().await;
|
||||
auth(&app, "SquadExtUser").await;
|
||||
|
||||
// Owned cards from the starter pack.
|
||||
let (_, packs) = json_get(&app, "/packs").await;
|
||||
let pack_id = packs["packs"][0]["pack_id"].as_str().unwrap().to_string();
|
||||
json_post(&app, &format!("/packs/open/{pack_id}"), serde_json::json!({})).await;
|
||||
let (_, coll) = json_get(&app, "/collection").await;
|
||||
let ids: Vec<String> = coll["collection"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.take(2)
|
||||
.map(|c| c["owned_card_id"].as_str().unwrap().to_string())
|
||||
.collect();
|
||||
assert!(ids.len() >= 2, "starter pack should yield >=2 owned cards");
|
||||
|
||||
let payload = "{\"custom\":\"[1,2,3]\",\"kit_numbers\":{}}";
|
||||
let body = serde_json::json!({
|
||||
"name": "OpenFUT",
|
||||
"formation": "f442",
|
||||
"slots": [
|
||||
{"owned_card_id": ids[0], "slot": 0, "is_captain": true, "is_on_bench": false},
|
||||
{"owned_card_id": ids[1], "slot": 1, "is_captain": false, "is_on_bench": false},
|
||||
],
|
||||
"client_reported": {
|
||||
"client_reported_chemistry": 52,
|
||||
"client_reported_rating": 90,
|
||||
"client_reported_star_rating": 90
|
||||
},
|
||||
"extension": {"namespace": "fifa17.squad", "schema_version": 1, "payload": payload},
|
||||
});
|
||||
|
||||
let (s, put) = json_put(&app, "/squad/replace", body.clone()).await;
|
||||
assert_eq!(s, StatusCode::OK, "{put}");
|
||||
assert_eq!(put["slots_written"], 2);
|
||||
let fp = put["canonical_fingerprint"].as_str().unwrap().to_string();
|
||||
|
||||
// Read the canonical squad + opaque extension back: Fresh, payload verbatim.
|
||||
let (s, ext) = json_get(&app, "/squad/ext?namespace=fifa17.squad").await;
|
||||
assert_eq!(s, StatusCode::OK, "{ext}");
|
||||
assert_eq!(ext["extension"]["state"], "fresh");
|
||||
assert_eq!(ext["extension"]["payload"], payload, "opaque payload round-trips verbatim");
|
||||
assert_eq!(ext["extension"]["schema_version"], 1);
|
||||
assert_eq!(ext["extension"]["stored_fingerprint"], fp);
|
||||
assert_eq!(ext["squad"]["formation"], "f442");
|
||||
assert_eq!(ext["players"].as_array().unwrap().len(), 2);
|
||||
|
||||
// Idempotent: an identical replacement converges to the same fingerprint.
|
||||
let (s2, put2) = json_put(&app, "/squad/replace", body).await;
|
||||
assert_eq!(s2, StatusCode::OK);
|
||||
assert_eq!(put2["canonical_fingerprint"], fp, "identical PUT is idempotent");
|
||||
|
||||
// A different namespace has no stored extension: Missing, never fabricated.
|
||||
let (_, other) = json_get(&app, "/squad/ext?namespace=other.ns").await;
|
||||
assert_eq!(other["extension"]["state"], "missing");
|
||||
}
|
||||
Reference in New Issue
Block a user