feat(fifa17): wire async economy handlers into the host via a runtime bridge (unrouted)

Bridges the synchronous thread-per-connection host to the async
transfer-market/pile handlers WITHOUT flipping the classifier. classify()
is untouched; production still proxies every economy route to Python. The
new dispatch is exercised only by the integration harness via
Server::try_handle_economy — handler wiring, not authority cutover.

async_bridge.rs: AsyncBridge owns ONE process-lifetime multi-threaded Tokio
runtime, shared by every connection via Arc. block_on() runs a future from
the sync dispatch thread; if invoked from within an ambient runtime it
offloads onto its own runtime + a std channel instead of panicking
("cannot start a runtime from within a runtime"). 4 unit tests incl. the
nested-runtime-safety case and concurrent multi-thread drivers.

lib.rs: EconomyRoute + classify_economy (mirrors the Python route table:
credits, purchasegroup, store/transaction, purchased, item DELETE/PUT,
ut/delete match/item/trade, auctionhouse/transfermarket, tradePile, trade).
EconomyServices (Core econ transport + durable MarketStore/PileStore + the
bridge + the pack-content pool), attached via Server::with_economy (kept out
of `new`/`from_config` so existing tests build a DB-less Server; production
from_config attachment is the barrier step). Server::try_handle_economy
dispatches: sync handlers (credits/purchasegroup/store-buy/pack-open/
quick-sell/match) inline; async handlers (market list/query/buy/cancel,
move) on the bridge via owned `async move` blocks. build_content_pool
derives the resolvable FIFA∩Core candidate pool from Core content.

market.rs: FIX the load-bearing hazard the FakeEconomy tests missed — the
async market handlers call the BLOCKING reqwest Core client, which panics
(reqwest::blocking::wait::enter) when run while a Tokio runtime is entered.
off_runtime() hops each Core call to a fresh OS thread with no runtime
entered, so blocking is legal. handle_move_items resolver gains `+ Sync`
(future must be Send for the bridge).

tests/economy_integration.rs: economy_full_sequence_through_dispatch drives
the WHOLE cluster through the REAL Server dispatch + bridge against a live
in-process Core (seeded with fifa17 dev content: 100k coins + owned cards),
on a plain OS thread (direct bridge path), over the real blocking
HttpCoreClient — no fakes: Store BUY (pool draw + shape + debit 400 + mint 5),
credits, quick-sell (reverse-resolve + credit), match WIN (+400), market
list->query->buy->query(sold)->second-buy-fails(no double debit), cancel
(cancelled not buyable), move-items, then reopen the durable market/pile
stores from disk (sold + pile persist). Deterministic. start_core_seeded
loads fifa17 dev content so /collection renders real definitions.

Tests: host 68 lib (+4 bridge) + 2 economy_integration + 24 host_test, all
green; adapter unchanged-green; clippy -D warnings + fmt clean.
This commit is contained in:
OpenFUT Agent
2026-08-13 21:30:10 +00:00
parent 0e2ca5a7c3
commit 580d80a86e
5 changed files with 898 additions and 6 deletions
+445 -2
View File
@@ -11,12 +11,21 @@
//! Safety: uses only a temp directory + `127.0.0.1:0` ephemeral ports. Never
//! touches the production Core DB, production ports/containers, or `.105`.
use openfut_adapter_fifa17::fut::catalog::Fifa17CardCatalog;
use openfut_adapter_fifa17::fut::entities::Fifa17Entities;
use openfut_adapter_fifa17::fut::store_session::StoreMode;
use openfut_identity::JsonIdentityStore;
use openfut_utas_host::async_bridge::AsyncBridge;
use openfut_utas_host::market_store::MarketStore;
use openfut_utas_host::pile_store::PileStore;
use openfut_utas_host::{
handle_credits, handle_match_end, handle_purchasegroup, overlay_massinfo_economy, CoreEconomy,
HttpCoreClient,
build_content_pool, handle_credits, handle_match_end, handle_purchasegroup,
overlay_massinfo_economy, CoreAccess, CoreEconomy, EconomyServices, Fifa17IdentityResolver,
HttpCoreClient, PassClient, Server,
};
use serde_json::{json, Value};
use std::collections::HashMap;
use std::sync::Arc;
/// Boot a Core instance against `db_url`, serving on an ephemeral port. Returns
/// the serve task handle and its base URL.
@@ -45,6 +54,53 @@ async fn start_core(db_url: &str) -> (tokio::task::JoinHandle<()>, String) {
(handle, format!("http://{addr}"))
}
/// Boot a Core with the FIFA17 dev CONTENT loaded (so `/collection` renders real
/// card definitions) and, on first boot, the dev inventory SEEDED (a fifa17
/// profile + club with 100k coins + one owned instance per definition). On
/// restart pass `seed=false`: content is reloaded but the durable DB is left as
/// is, proving persistence rather than re-seeding.
async fn start_core_seeded(db_url: &str, seed: bool) -> (tokio::task::JoinHandle<()>, String) {
use openfut_core::config::Config;
use openfut_core::seed::{seed_fifa17_dev, FIFA17_GAME};
use openfut_core::services::card_db::CardDb;
let data_dir = "../openfut-core/data";
let pool = openfut_core::db::init_pool(db_url, 5)
.await
.expect("core pool");
openfut_core::db::run_migrations(&pool)
.await
.expect("core migrations");
if seed {
let mut card_db = CardDb::load(data_dir).expect("card_db load");
card_db
.load_game_dev(data_dir, FIFA17_GAME)
.expect("load fifa17 dev content");
seed_fifa17_dev(&pool, &card_db)
.await
.expect("seed fifa17 dev inventory");
}
let cfg = Config {
listen_addr: "127.0.0.1:0".into(),
database_url: "sqlite::memory:".into(),
data_dir: data_dir.into(),
max_connections: 5,
dev_content_games: vec![FIFA17_GAME.to_string()],
content_packs: Vec::new(),
};
let app = openfut_core::app::build(pool, cfg)
.await
.expect("core app::build");
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
.await
.expect("bind ephemeral");
let addr = listener.local_addr().unwrap();
let handle = tokio::spawn(async move {
let _ = axum::serve(listener, app).await;
});
(handle, format!("http://{addr}"))
}
fn wait_ready(base: &str) {
let http = reqwest::blocking::Client::new();
// Generous ceiling (~30s): returns on first success, so it only ever waits
@@ -194,3 +250,390 @@ async fn economy_end_to_end_and_restart_persistence() {
std::fs::remove_dir_all(&dir).ok();
}
// ─────────────── Full economy sequence through the real host dispatch ────────
//
// Everything below drives the ACTUAL `Server::try_handle_economy` path (the same
// dispatch + async bridge the barrier will route production through), against a
// live in-process Core over the real blocking `HttpCoreClient`. No fakes. The
// sequence runs on a plain OS thread (no ambient Tokio runtime), exactly like the
// thread-per-connection server, so the bridge takes its DIRECT `block_on` path.
/// Facts captured from the write sequence, re-checked after reopening the stores.
struct SeqResult {
sold_listing: String,
moved_core_id: String,
}
/// Build a real `Server` with economy authority wired: real Core transport, a
/// catalog derived from the seeded content (so the pack pool + shaper resolve),
/// a persistent identity store, and the two durable SQLite stores opened via the
/// bridge. Returns the server, a direct Core client for balance assertions, and
/// the identity resolver (to reverse a wire id for the restart pile check).
fn build_econ_server(
base: &str,
dir: &std::path::Path,
) -> (Server, HttpCoreClient, Arc<Fifa17IdentityResolver>) {
let probe = HttpCoreClient::new(base, "fifa17");
let owned = probe.all_owned().expect("core collection");
assert!(!owned.is_empty(), "seed must grant a starter collection");
// A catalog mapping every seeded definition to a real-looking asset id (in
// production this is the shipped FIFA catalog; here it is derived so the E2E
// exercises real shaping without a static fixture).
let mut entries = String::new();
let mut seen = std::collections::HashSet::new();
let mut asset = 20000u32;
for it in &owned {
if !seen.insert(it.card_id.clone()) {
continue;
}
if !entries.is_empty() {
entries.push(',');
}
entries.push_str(&format!("\"{}\":{{\"asset_id\":{asset}}}", it.card_id));
asset += 1;
}
let doc = format!("{{\"schema_version\":1,\"game\":\"fifa17\",\"cards\":{{{entries}}}}}");
let catalog = Fifa17CardCatalog::from_json_str(&doc).expect("catalog");
let store = JsonIdentityStore::open(dir.join("identity.json").to_str().unwrap()).unwrap();
let resolver = Arc::new(Fifa17IdentityResolver::new(catalog, Arc::new(store)));
let entities = Arc::new(Fifa17Entities::from_maps(
HashMap::new(),
HashMap::new(),
HashMap::new(),
));
let core: Arc<dyn CoreAccess> = Arc::new(HttpCoreClient::new(base, "fifa17"));
let bridge = Arc::new(AsyncBridge::new().unwrap());
let market_path = dir.join("market.db").to_string_lossy().into_owned();
let market = Arc::new(
bridge
.block_on(async move { MarketStore::open(&market_path).await })
.expect("market store"),
);
let pile_path = dir.join("pile.db").to_string_lossy().into_owned();
let piles = Arc::new(
bridge
.block_on(async move { PileStore::open(&pile_path).await })
.expect("pile store"),
);
let econ: Arc<dyn CoreEconomy> = Arc::new(HttpCoreClient::new(base, "fifa17"));
let pool = Arc::new(build_content_pool(core.as_ref(), resolver.as_ref()));
assert!(
!pool.is_empty(),
"content pool derived from real Core content"
);
let services = Arc::new(EconomyServices {
econ,
market,
piles,
bridge,
pool,
});
let server = Server::new(
core,
entities,
resolver.clone(),
Arc::new(PassClient::new("http://127.0.0.1:9")),
33068179,
)
.with_economy(services);
(server, probe, resolver)
}
/// Drive the whole writer+reader cluster through the real dispatch. Panics on any
/// mismatch. Runs on a plain OS thread (no ambient runtime).
fn economy_sequence(base: &str, dir: &std::path::Path) -> SeqResult {
wait_ready(base);
// Core is seeded (start_core_seeded): a fifa17 profile with 100k coins + one
// owned instance per definition. No /auth/local — the profile already exists.
let (server, client, resolver) = build_econ_server(base, dir);
let start = client.balance().unwrap();
assert!(start >= 5000, "seeded dev balance present ({start})");
// 1) Store BUY (pack 1 = Bronze, price 400, 5 cards): debit + mint + reveal.
let buy = server
.try_handle_economy(
"PUT",
"/ut/game/fifa17/store/transaction",
&[],
br#"{"packId":1}"#,
None,
)
.expect("store BUY routed");
assert_eq!(buy.status, 200, "BUY 200");
let bv: Value = serde_json::from_slice(&buy.body).unwrap();
let items = bv["createPackResponse"]["itemList"]
.as_array()
.expect("itemList")
.clone();
assert_eq!(items.len(), 5, "pack 1 awards 5 cards");
assert_eq!(bv["createPackResponse"]["numberItems"], 5);
assert!(
items[0]["id"].as_i64().unwrap() >= 100_000_000,
"minted wire id above the FIFA floor"
);
assert_eq!(
client.balance().unwrap(),
start - 400,
"BUY debited exactly 400"
);
// 2) credits reads the SAME Core authority.
let cr = server
.try_handle_economy("GET", "/ut/game/fifa17/user/credits", &[], b"", None)
.unwrap();
let crv: Value = serde_json::from_slice(&cr.body).unwrap();
assert_eq!(
crv["currencies"][0]["funds"],
start - 400,
"credits == Core balance"
);
// 3) Quick-sell one minted card: reverse-resolve wire -> Core id, credit.
let sell_wire = items[0]["id"].as_i64().unwrap();
let before = client.balance().unwrap();
let qs = server
.try_handle_economy(
"DELETE",
&format!("/ut/game/fifa17/item/{sell_wire}"),
&[],
b"",
None,
)
.expect("quick-sell routed");
assert_eq!(qs.status, 200);
let qv: Value = serde_json::from_slice(&qs.body).unwrap();
assert_eq!(qv["items"].as_array().unwrap().len(), 1, "sold exactly one");
let after_sell = client.balance().unwrap();
assert!(
after_sell > before,
"quick-sell credited ({before}->{after_sell})"
);
assert_eq!(
qv["totalCredits"].as_i64().unwrap(),
after_sell,
"totalCredits == absolute Core balance"
);
// 4) Match END reward through dispatch (WIN = +400).
let before_match = client.balance().unwrap();
let mm = server
.try_handle_economy(
"POST",
"/ut/delete/game/fifa17/match",
&[],
br#"{"endReason":"WIN"}"#,
None,
)
.expect("match routed");
assert_eq!(mm.status, 200);
assert_eq!(
client.balance().unwrap(),
before_match + 400,
"WIN credited +400 via Core"
);
// 5) MARKET buy-now (async handlers via the bridge): list -> query -> buy ->
// query -> second buy fails, exactly one debit + one sale.
let list = server
.try_handle_economy(
"POST",
"/ut/game/fifa17/auctionhouse",
&[],
br#"{"itemData":{"id":777,"resourceId":777},"buyNowPrice":1000,"startingBid":500}"#,
None,
)
.expect("market list routed");
let lv: Value = serde_json::from_slice(&list.body).unwrap();
let trade_id = lv["id"].as_i64().expect("trade id");
let trade_path = format!("/ut/game/fifa17/trade/{trade_id}");
let q1 = server
.try_handle_economy("GET", "/ut/game/fifa17/tradePile", &[], b"", None)
.unwrap();
let q1v: Value = serde_json::from_slice(&q1.body).unwrap();
assert_eq!(
q1v["auctionInfo"].as_array().unwrap().len(),
1,
"listing active before buy"
);
let before_buy = client.balance().unwrap();
let buy1 = server
.try_handle_economy("POST", &trade_path, &[], b"{}", None)
.expect("market buy routed");
assert_eq!(buy1.status, 200);
assert_eq!(
client.balance().unwrap(),
before_buy - 1000,
"buy debited exactly the buy-now price"
);
let q2 = server
.try_handle_economy("GET", "/ut/game/fifa17/tradePile", &[], b"", None)
.unwrap();
let q2v: Value = serde_json::from_slice(&q2.body).unwrap();
assert_eq!(
q2v["auctionInfo"].as_array().unwrap().len(),
0,
"listing sold: no longer active"
);
let after_buy = client.balance().unwrap();
let buy2 = server
.try_handle_economy("POST", &trade_path, &[], b"{}", None)
.unwrap();
let buy2v: Value = serde_json::from_slice(&buy2.body).unwrap();
assert_eq!(
buy2v["auctionInfo"].as_array().unwrap().len(),
0,
"second buy sees a closed auction"
);
assert_eq!(
client.balance().unwrap(),
after_buy,
"second buy does NOT debit again"
);
// 6) MARKET cancel: a cancelled listing cannot be bought.
let clist = server
.try_handle_economy(
"POST",
"/ut/game/fifa17/auctionhouse",
&[],
br#"{"itemData":{"id":888,"resourceId":888},"buyNowPrice":1000,"startingBid":500}"#,
None,
)
.unwrap();
let cancel_id = serde_json::from_slice::<Value>(&clist.body).unwrap()["id"]
.as_i64()
.unwrap();
server
.try_handle_economy(
"DELETE",
&format!("/ut/delete/game/fifa17/trade/{cancel_id}"),
&[],
b"",
None,
)
.expect("market cancel routed");
let bal_before_cancel_buy = client.balance().unwrap();
let cancel_buy = server
.try_handle_economy(
"POST",
&format!("/ut/game/fifa17/trade/{cancel_id}"),
&[],
b"{}",
None,
)
.unwrap();
assert_eq!(
serde_json::from_slice::<Value>(&cancel_buy.body).unwrap()["auctionInfo"]
.as_array()
.unwrap()
.len(),
0,
"cancelled listing is not buyable"
);
assert_eq!(
client.balance().unwrap(),
bal_before_cancel_buy,
"buying a cancelled listing does not debit"
);
// 7) Move a still-owned minted card to the trade pile (durable pile metadata).
let move_wire = items[1]["id"].as_i64().unwrap();
let mv = server
.try_handle_economy(
"PUT",
"/ut/game/fifa17/item",
&[],
format!(r#"{{"itemData":[{{"id":{move_wire},"pile":"trade"}}]}}"#).as_bytes(),
None,
)
.expect("move routed");
let mvv: Value = serde_json::from_slice(&mv.body).unwrap();
assert_eq!(mvv["itemData"][0]["success"], true, "move recorded");
let moved_core_id = resolver
.owned_id_for_wire(move_wire)
.expect("moved item reverses to a Core id");
SeqResult {
sold_listing: trade_id.to_string(),
moved_core_id,
}
}
/// Reopen the durable market/pile SQLite stores from the SAME files (a fresh
/// process would do exactly this) and prove the sold listing and the pile move
/// persisted. Core-side coin/inventory persistence across a full Core restart is
/// proven by `economy_end_to_end_and_restart_persistence`; here the focus is the
/// host-owned durable stores.
fn verify_store_durability(dir: &std::path::Path, seq: &SeqResult) {
let bridge = AsyncBridge::new().unwrap();
let market_path = dir.join("market.db").to_string_lossy().into_owned();
let market = bridge
.block_on(async move { MarketStore::open(&market_path).await })
.unwrap();
let sold = seq.sold_listing.clone();
let m2 = market.clone();
let listing = bridge
.block_on(async move { m2.get_listing(&sold).await })
.expect("sold listing survives reopen");
assert_eq!(listing.state, "sold", "sold stays sold after reopen");
let pile_path = dir.join("pile.db").to_string_lossy().into_owned();
let piles = bridge
.block_on(async move { PileStore::open(&pile_path).await })
.unwrap();
let moved = seq.moved_core_id.clone();
let p2 = piles.clone();
let pile = bridge
.block_on(async move { p2.get(&moved).await })
.unwrap();
assert_eq!(
pile.as_deref(),
Some("trade"),
"pile move persisted after reopen"
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn economy_full_sequence_through_dispatch() {
let dir = std::env::temp_dir().join(format!(
"openfut-econ-dispatch-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
std::fs::create_dir_all(&dir).unwrap();
let db_url = format!("sqlite://{}/econ.db", dir.display());
// Core #1: run the full write sequence on a plain OS thread (direct bridge
// path). The join runs in spawn_blocking so Core's runtime keeps serving.
let (h1, base1) = start_core_seeded(&db_url, true).await;
let (b1, d1) = (base1.clone(), dir.clone());
let seq = tokio::task::spawn_blocking(move || {
let t = std::thread::spawn(move || economy_sequence(&b1, &d1));
t.join().expect("sequence thread")
})
.await
.expect("write sequence");
h1.abort();
// Durable host stores: reopen the market/pile files from disk (as a fresh
// process would) and prove sold/pile state persisted. No Core rebuild — the
// synthetic market mint uses the wire resourceId as a placeholder card id,
// which Core's content preflight (correctly) rejects on reboot; Core-side
// coin/inventory restart persistence is covered by the sibling test.
let d2 = dir.clone();
tokio::task::spawn_blocking(move || {
let t = std::thread::spawn(move || verify_store_durability(&d2, &seq));
t.join().expect("durability thread")
})
.await
.expect("durability phase");
std::fs::remove_dir_all(&dir).ok();
}