feat(consume): durable per-instance contract state + HTTP apply route
CI / Build, lint & test (push) Successful in 3m16s

`consume_item` was a complete, tested, atomic apply transaction with zero
production callers and no route -- it could not be reached over HTTP because
its effect is an in-process `ItemMutation` trait object and the host is a
separate process on a synchronous JSON boundary.

Closes that gap with a CLOSED, Core-validated effect vocabulary rather than a
pass-through: `InstanceEffect::AddContractMatches { amount, cap,
default_when_unset }`. A generic "apply this field/value" escape hatch would
hand economic authority back to the caller and break the architecture.

The read-modify-write runs INSIDE the caller's transaction
(`min(cap, COALESCE(contract_matches, default) + amount)`) so two concurrent
applies cannot lose an update, and the reported `granted` stays the requested
amount even when the cap clamps the total.

Migration 0028 adds `owned_cards.contract_matches` NULLABLE: NULL means "Core
tracks no contract here", which keeps the pack-fresh default (a FIFA-specific
7) out of Core and leaves every existing row unchanged in meaning. ADD COLUMN,
not a rebuild -- a rebuild would drop 0026's transfer trigger.

Two ordering fixes forced by putting this on the live path:
* consume_item moves from DEFERRED `pool.begin()` to `BEGIN IMMEDIATE`, the
  discipline economy.rs documents: three reads precede the first write, which
  is exactly the shape that returns SQLITE_BUSY past the busy handler.
* the replay answer now precedes source validation. With DestroyInstance the
  first apply deletes the source, so the old order answered a retry with 404
  instead of the recorded outcome -- replay semantics were unreachable.
This commit is contained in:
funman300
2026-08-22 18:23:05 +00:00
parent 233df1d99d
commit e8be289660
12 changed files with 1019 additions and 172 deletions
+112
View File
@@ -1115,6 +1115,118 @@ async fn test_quick_sell_owned_card() {
assert_eq!(coins_after, coins_before + coins_received);
}
/// `POST /consumables/apply` end to end, in the exact wire shape a game host
/// sends: destroy the consumable, move the target's contract counter, surface it
/// on `/collection`, and REPLAY (not re-apply) a retried request.
///
/// Built on its own pool so a consumable instance can be minted directly — the
/// starter packs only yield players, and Core has no route that creates one.
#[tokio::test]
async fn test_apply_contract_consumable_over_http() {
let pool = sqlx::sqlite::SqlitePoolOptions::new()
.connect("sqlite::memory:")
.await
.expect("in-memory sqlite");
sqlx::migrate!("./migrations")
.run(&pool)
.await
.expect("migrations");
let app = openfut_core::build_app(pool.clone(), "data")
.await
.expect("app build");
auth(&app, "ContractApplier").await;
let (_, packs) = json_get(&app, "/packs").await;
let pack_id = packs["packs"][0]["pack_id"].as_str().unwrap().to_string();
let (s, _) = json_post(
&app,
&format!("/packs/open/{pack_id}"),
serde_json::json!({}),
)
.await;
assert_eq!(s, StatusCode::OK);
let (_, coll) = json_get(&app, "/collection").await;
let target = coll["collection"][0].clone();
let target_id = target["owned_card_id"].as_str().unwrap().to_string();
let card_id = target["card"]["id"].as_str().unwrap().to_string();
assert!(
target["contract_matches"].is_null(),
"a pack-fresh instance must report NULL, not a substituted default"
);
// Mint the consumable into the target's own club, reusing a definition the
// content pack already loaded so `/collection` can still project it.
sqlx::query(
"INSERT INTO owned_cards (id, club_id, card_id, is_loan, acquired_at, content_kind) \
SELECT 'contract-card', club_id, ?, 0, ?, 'consumable' FROM owned_cards WHERE id = ?",
)
.bind(&card_id)
.bind("2026-01-01T00:00:00Z")
.bind(&target_id)
.execute(&pool)
.await
.expect("mint a consumable");
let request = serde_json::json!({
"action_identity": format!("fifa17:apply:contract-card->{target_id}"),
"source_owned_card_id": "contract-card",
"target_owned_card_id": target_id,
"target_kind": "player",
"effect": {
"kind": "add_contract_matches",
"amount": 15,
"cap": 99,
"default_when_unset": 7,
},
});
let (s, applied) = json_post(&app, "/consumables/apply", request.clone()).await;
assert_eq!(s, StatusCode::OK, "{applied}");
assert_eq!(applied["applied"], serde_json::json!(true));
assert_eq!(applied["source_destroyed"], serde_json::json!(true));
assert!(applied["source_quantity_after"].is_null());
assert_eq!(
applied["target_owned_card_id"],
serde_json::json!(target_id)
);
assert_eq!(
applied["effect"],
serde_json::json!({
"kind": "add_contract_matches", "granted": 15, "before": 7, "after": 22
})
);
let (_, after) = json_get(&app, "/collection").await;
let items = after["collection"].as_array().unwrap();
let projected = items
.iter()
.find(|c| c["owned_card_id"] == serde_json::json!(target_id))
.expect("target still owned");
assert_eq!(projected["contract_matches"], serde_json::json!(22));
assert!(
!items
.iter()
.any(|c| c["owned_card_id"] == serde_json::json!("contract-card")),
"the consumable must be spent, not merely marked"
);
// A retried request replays: no second grant, and no resurrection of the
// source it already destroyed.
let (s, replay) = json_post(&app, "/consumables/apply", request).await;
assert_eq!(s, StatusCode::OK);
assert_eq!(replay["applied"], serde_json::json!(false));
assert_eq!(replay["effect"], applied["effect"]);
let (_, twice) = json_get(&app, "/collection").await;
let projected = twice["collection"]
.as_array()
.unwrap()
.iter()
.find(|c| c["owned_card_id"] == serde_json::json!(target_id))
.expect("target still owned")
.clone();
assert_eq!(projected["contract_matches"], serde_json::json!(22));
}
#[tokio::test]
async fn test_objective_get_by_id() {
let app = build_test_app().await;