feat(m5): client-server sync, offline queue and replay playback

This commit is contained in:
2026-10-24 23:37:13 +02:00
parent 4a9031b29c
commit 33bdc16fbd
22 changed files with 1419 additions and 184 deletions
+2 -1
View File
@@ -10,5 +10,6 @@ description = "CDylib bridge between Flutter and the deterministic simulation"
crate-type = ["cdylib", "staticlib"]
[dependencies]
sim.workspace = true
sim = { workspace = true, features = ["serde"] }
content.workspace = true
serde_json.workspace = true
+44
View File
@@ -64,6 +64,50 @@ mod tests {
assert_eq!(iron_arc_sim_version_code(), 100);
}
#[test]
fn replay_export_reproduces_state() {
unsafe {
let handle = match_api::iron_arc_new_match(77);
assert_eq!(match_api::iron_arc_fire(handle, 45_000, 65_536, 1), 0);
match_api::iron_arc_tick(handle, 400);
let hash = match_api::iron_arc_state_hash(handle);
let json_ptr = match_api::iron_arc_replay_json(handle);
assert!(!json_ptr.is_null(), "replay json must be produced");
let json = std::ffi::CStr::from_ptr(json_ptr)
.to_str()
.expect("utf8")
.to_string();
match_api::iron_arc_string_free(json_ptr);
assert!(json.contains(r#""commands""#));
let c_json = std::ffi::CString::new(json).expect("no nul bytes");
let playback = match_api::iron_arc_new_match_playback(c_json.as_ptr());
assert!(!playback.is_null(), "playback handle must be created");
assert_eq!(match_api::iron_arc_is_playback(playback), 1);
match_api::iron_arc_tick(playback, 400);
assert_eq!(
match_api::iron_arc_state_hash(playback),
hash,
"playback must reproduce the identical state"
);
match_api::iron_arc_free_match(playback);
match_api::iron_arc_free_match(handle);
}
}
#[test]
fn playback_rejects_foreign_content() {
unsafe {
let json = r#"{"v":1,"sim_version":"0.1.0","content_hash":"fnv1a:0000000000000000","seed":1,"mode":"hotseat","players":[{"tank":"a","loadout":[1,2,5]},{"tank":"b","loadout":[1,3,4]}],"commands":[],"final_hash":0,"duration_ticks":0}"#;
let c_json = std::ffi::CString::new(json).unwrap();
let handle = match_api::iron_arc_new_match_playback(c_json.as_ptr());
assert!(handle.is_null(), "content mismatch must be rejected");
}
}
#[test]
fn match_handle_roundtrip() {
unsafe {
+121 -1
View File
@@ -4,7 +4,12 @@
//! fixed-step loop and reads a snapshot for rendering. No data is pushed from
//! Rust; the renderer pulls.
use sim::state::{Command, Event, Phase, Sim};
use std::ffi::{CStr, CString};
use std::os::raw::c_char;
use sim::replay::{CommandRecord, ReplayV1};
use sim::state::{Command, Event, Phase, Sim, TankSpec};
use sim::terrain::WORLD_W;
/// Opaque match handle owned by Dart.
pub struct MatchHandle {
@@ -12,6 +17,8 @@ pub struct MatchHandle {
terrain_version: u32,
impacts: u32,
last_impact: [i32; 2],
/// When set, due commands are applied automatically while ticking.
playback: Option<(Vec<CommandRecord>, usize)>,
}
impl MatchHandle {
@@ -32,6 +39,7 @@ pub extern "C" fn iron_arc_new_match(seed: u64) -> *mut MatchHandle {
terrain_version: 0,
impacts: 0,
last_impact: [0, 0],
playback: None,
}))
}
@@ -97,6 +105,20 @@ pub unsafe extern "C" fn iron_arc_tick(handle: *mut MatchHandle, ticks: u32) ->
};
let mut impacts = 0;
for _ in 0..ticks {
// In playback mode, apply every command that is due at this tick.
if h.playback.is_some() {
let tick = h.sim.tick;
let mut pending: Vec<Command> = Vec::new();
if let Some((records, index)) = h.playback.as_mut() {
while *index < records.len() && records[*index].t <= tick {
pending.push(records[*index].c.to_command());
*index += 1;
}
}
for command in pending {
let _ = h.sim_mut().submit(command);
}
}
for event in h.sim_mut().tick() {
if let Event::Impact { x, y, .. } = event {
impacts += 1;
@@ -268,3 +290,101 @@ pub unsafe extern "C" fn iron_arc_last_impact(handle: *const MatchHandle, out: *
}
h.impacts
}
/// Serialises the recorded match as replay JSON (`ReplayV1`).
///
/// The returned string must be released with [`iron_arc_string_free`].
///
/// # Safety
/// `handle` must be a valid pointer from [`iron_arc_new_match`].
#[no_mangle]
pub unsafe extern "C" fn iron_arc_replay_json(handle: *const MatchHandle) -> *mut c_char {
let Some(h) = handle.as_ref() else {
return std::ptr::null_mut();
};
let replay = ReplayV1::capture(&h.sim, "hotseat", h.sim.tick);
match serde_json::to_string(&replay) {
Ok(json) => match CString::new(json) {
Ok(value) => value.into_raw(),
Err(_) => std::ptr::null_mut(),
},
Err(_) => std::ptr::null_mut(),
}
}
/// Frees a string returned by [`iron_arc_replay_json`].
///
/// # Safety
/// `value` must come from this library and must not be used afterwards.
#[no_mangle]
pub unsafe extern "C" fn iron_arc_string_free(value: *mut c_char) {
if !value.is_null() {
drop(CString::from_raw(value));
}
}
/// Creates a handle that replays the given replay JSON automatically.
///
/// Returns null when the JSON is invalid, the simulation version differs or the
/// content hash does not match the build.
///
/// # Safety
/// `json` must be a valid, null-terminated UTF-8 string.
#[no_mangle]
pub unsafe extern "C" fn iron_arc_new_match_playback(json: *const c_char) -> *mut MatchHandle {
if json.is_null() {
return std::ptr::null_mut();
}
let Ok(text) = CStr::from_ptr(json).to_str() else {
return std::ptr::null_mut();
};
let Ok(replay) = serde_json::from_str::<ReplayV1>(text) else {
return std::ptr::null_mut();
};
if replay.players.len() != 2 {
return std::ptr::null_mut();
}
let specs = [
TankSpec {
x: 220,
loadout: replay.players[0].loadout,
},
TankSpec {
x: WORLD_W - 220,
loadout: replay.players[1].loadout,
},
];
let content = content::Content::builtin();
if content.hash() != replay.content_hash {
return std::ptr::null_mut();
}
let sim = Sim::new(replay.seed, specs, content);
Box::into_raw(Box::new(MatchHandle {
sim,
terrain_version: 0,
impacts: 0,
last_impact: [0, 0],
playback: Some((replay.commands.clone(), 0)),
}))
}
/// True (1) when this handle replays a recorded match.
///
/// # Safety
/// `handle` must be a valid pointer from this library.
#[no_mangle]
pub unsafe extern "C" fn iron_arc_is_playback(handle: *const MatchHandle) -> i32 {
match handle.as_ref() {
Some(h) => i32::from(h.playback.is_some()),
None => 0,
}
}
/// Current state hash (used by the client to detect desync with the server).
///
/// # Safety
/// `handle` must be a valid pointer from this library.
#[no_mangle]
pub unsafe extern "C" fn iron_arc_state_hash(handle: *const MatchHandle) -> u64 {
handle.as_ref().map(|h| h.sim.state_hash()).unwrap_or(0)
}
+21 -11
View File
@@ -106,6 +106,16 @@ impl AppState {
}
}
/// Encodes a 64 bit hash as fixed-width hex (JSON numbers lose precision above 2^53).
fn hex64(value: u64) -> String {
format!("{value:016x}")
}
fn parse_hash(value: &str) -> Result<u64, ApiError> {
u64::from_str_radix(value, 16)
.map_err(|_| ApiError::bad_request("bad_hash", "expected 16 hex chars"))
}
fn hex(bytes: &[u8]) -> String {
let mut out = String::with_capacity(bytes.len() * 2);
for b in bytes {
@@ -288,7 +298,7 @@ struct CreateMatchResponse {
match_id: String,
seed: u64,
turn: u32,
state_hash: u64,
state_hash: String,
}
async fn create_match(
@@ -359,7 +369,7 @@ async fn create_match(
match_id: id,
seed,
turn: 1,
state_hash,
state_hash: hex64(state_hash),
}),
))
}
@@ -371,7 +381,7 @@ struct MatchStateBody {
current: u8,
phase: u8,
hp: [i32; 2],
state_hash: u64,
state_hash: String,
}
async fn get_match(
@@ -392,7 +402,7 @@ async fn get_match(
Phase::Finished => 2,
},
hp: [sim.tanks[0].hp, sim.tanks[1].hp],
state_hash: sim.state_hash(),
state_hash: hex64(sim.state_hash()),
})
};
if let Some(body) = live_body {
@@ -413,13 +423,13 @@ async fn get_match(
current: 0,
phase: 0,
hp: [0, 0],
state_hash: row.state_hash,
state_hash: hex64(row.state_hash),
}))
}
#[derive(Deserialize)]
struct TurnRequest {
expect_hash: u64,
expect_hash: String,
command: sim::replay::CommandDto,
}
@@ -428,7 +438,7 @@ struct TurnResponse {
accepted: bool,
turn: u32,
current: u8,
state_hash: u64,
state_hash: String,
impacts: u32,
}
@@ -447,7 +457,7 @@ async fn submit_turn(
if sim.phase != Phase::Aiming {
return Err(ApiError::conflict("state_conflict", "no turn is open"));
}
if sim.state_hash() != body.expect_hash {
if sim.state_hash() != parse_hash(&body.expect_hash)? {
return Err(ApiError::conflict(
"state_conflict",
"expect_hash does not match",
@@ -483,7 +493,7 @@ async fn submit_turn(
accepted: true,
turn,
current,
state_hash,
state_hash: hex64(state_hash),
impacts,
}))
}
@@ -503,7 +513,7 @@ struct Rewards {
#[derive(Serialize)]
struct ValidateResponse {
valid: bool,
final_hash: u64,
final_hash: String,
rewards: Rewards,
}
@@ -531,7 +541,7 @@ async fn validate_replay(
})?;
Ok(Json(ValidateResponse {
valid: true,
final_hash: hash,
final_hash: hex64(hash),
rewards: Rewards { scrap: 120, xp: 35 },
}))
}
+7 -4
View File
@@ -99,12 +99,12 @@ async fn create_match_and_play_a_turn() {
let (status, body) = call(&app, req).await;
assert_eq!(status, StatusCode::CREATED, "body: {body}");
let match_id = body["match_id"].as_str().unwrap().to_string();
let state_hash = body["state_hash"].as_u64().unwrap();
let state_hash = body["state_hash"].as_str().unwrap().to_string();
assert!(state.has_live_match(&match_id));
// Wrong expect_hash must be rejected.
let turn = json!({
"expect_hash": state_hash ^ 0xFF,
"expect_hash": "ffffffffffffffff",
"command": {"kind": "fire", "angle": 45000, "power": 65536, "w": 1}
});
let req = Request::builder()
@@ -134,7 +134,7 @@ async fn create_match_and_play_a_turn() {
assert_eq!(status, StatusCode::OK, "body: {body}");
assert_eq!(body["accepted"], true);
assert_eq!(body["turn"], 2);
assert!(body["state_hash"].as_u64().unwrap() != state_hash);
assert_ne!(body["state_hash"].as_str().unwrap(), state_hash);
}
fn build_replay(seed: u64) -> ReplayV1 {
@@ -175,7 +175,10 @@ async fn valid_replay_is_accepted() {
let (status, body) = call(&app, req).await;
assert_eq!(status, StatusCode::OK, "body: {body}");
assert_eq!(body["valid"], true);
assert_eq!(body["final_hash"].as_u64().unwrap(), replay.final_hash);
assert_eq!(
body["final_hash"].as_str().unwrap(),
format!("{:016x}", replay.final_hash)
);
}
#[tokio::test]