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
+195
View File
@@ -0,0 +1,195 @@
import 'dart:convert';
import 'package:http/http.dart' as http;
/// Error returned by the referee service.
class ApiException implements Exception {
ApiException(this.statusCode, this.code, this.message);
final int statusCode;
final String code;
final String message;
@override
String toString() => 'ApiException($statusCode, $code): $message';
}
/// Result of `POST /v1/matches`.
class MatchInfo {
const MatchInfo({
required this.matchId,
required this.seed,
required this.turn,
required this.stateHash,
});
final String matchId;
final int seed;
final int turn;
final int stateHash;
}
/// Result of `POST /v1/matches/{id}/turn`.
class TurnResult {
const TurnResult({
required this.turn,
required this.current,
required this.stateHash,
required this.impacts,
});
final int turn;
final int current;
final int stateHash;
final int impacts;
}
/// Result of `POST /v1/matches/{id}/validate`.
class ValidateResult {
const ValidateResult({
required this.finalHash,
required this.scrap,
required this.xp,
});
final int finalHash;
final int scrap;
final int xp;
}
/// Thin client for the replay referee (`crates/server`).
class ApiClient {
ApiClient({required this.baseUrl, http.Client? client})
: _http = client ?? http.Client();
final String baseUrl;
final http.Client _http;
Uri _uri(String path) => Uri.parse('$baseUrl$path');
Future<Map<String, dynamic>> _decode(http.Response response) async {
final body = response.body.isEmpty
? <String, dynamic>{}
: jsonDecode(response.body) as Map<String, dynamic>;
if (response.statusCode >= 400) {
final error = (body['error'] as Map<String, dynamic>?) ?? const {};
throw ApiException(
response.statusCode,
error['code'] as String? ?? 'unknown',
error['message'] as String? ?? response.body,
);
}
return body;
}
/// Public health probe.
Future<Map<String, dynamic>> health() async {
final response = await _http.get(_uri('/v1/health'));
return _decode(response);
}
/// Exchanges a device id for a bearer token.
Future<String> authenticate(String deviceId) async {
final response = await _http.post(
_uri('/v1/auth/device'),
headers: const {'content-type': 'application/json'},
body: jsonEncode({'device_id': deviceId}),
);
final body = await _decode(response);
return body['token'] as String;
}
/// Creates a server-authoritative match.
Future<MatchInfo> createMatch({
required String token,
required String mode,
required String contentHash,
required String simVersion,
required List<List<int>> loadouts,
}) async {
final response = await _http.post(
_uri('/v1/matches'),
headers: {
'content-type': 'application/json',
'authorization': 'Bearer $token',
},
body: jsonEncode({
'mode': mode,
'content_hash': contentHash,
'sim_version': simVersion,
'players': [
{'tank': 'vanguard', 'loadout': loadouts[0]},
{'tank': 'longshot', 'loadout': loadouts[1]},
],
}),
);
final body = await _decode(response);
return MatchInfo(
matchId: body['match_id'] as String,
seed: (body['seed'] as num).toInt(),
turn: (body['turn'] as num).toInt(),
stateHash: _u64(body['state_hash']),
);
}
/// Submits one shot and lets the server resolve it.
Future<TurnResult> submitTurn({
required String token,
required String matchId,
required int expectHash,
required Map<String, Object?> command,
}) async {
final response = await _http.post(
_uri('/v1/matches/$matchId/turn'),
headers: {
'content-type': 'application/json',
'authorization': 'Bearer $token',
},
body: jsonEncode({'expect_hash': _hex64(expectHash), 'command': command}),
);
final body = await _decode(response);
return TurnResult(
turn: (body['turn'] as num).toInt(),
current: (body['current'] as num).toInt(),
stateHash: _u64(body['state_hash']),
impacts: (body['impacts'] as num?)?.toInt() ?? 0,
);
}
/// Submits a replay for validation (offline play, anti-cheat).
Future<ValidateResult> validate({
required String token,
required String replayJson,
String? matchId,
}) async {
final response = await _http.post(
_uri('/v1/matches/${matchId ?? 'offline'}/validate'),
headers: {
'content-type': 'application/json',
'authorization': 'Bearer $token',
},
body: jsonEncode({'match_id': matchId, 'replay': jsonDecode(replayJson)}),
);
final body = await _decode(response);
final rewards = (body['rewards'] as Map<String, dynamic>?) ?? const {};
return ValidateResult(
finalHash: _u64(body['final_hash']),
scrap: (rewards['scrap'] as num?)?.toInt() ?? 0,
xp: (rewards['xp'] as num?)?.toInt() ?? 0,
);
}
void close() => _http.close();
}
/// Hashes travel as fixed-width hex strings: JSON numbers lose precision above
/// 2^53, and u64 hashes routinely exceed that.
int _u64(Object? value) {
if (value is String) return BigInt.parse(value, radix: 16).toSigned(64).toInt();
if (value is int) return value.toUnsigned(64);
if (value is num) return value.toInt().toUnsigned(64);
return 0;
}
String _hex64(int value) =>
BigInt.from(value).toUnsigned(64).toRadixString(16).padLeft(16, '0');
+141
View File
@@ -0,0 +1,141 @@
import 'package:flutter/foundation.dart';
import 'api_client.dart';
import 'offline_queue.dart';
/// Connection state shown in the HUD.
enum SyncStatus { offline, connecting, online, desync, error }
/// Keeps a match in sync with the referee service.
///
/// Online: every shot is submitted with the pre-shot state hash; the server
/// resolves it and returns its own hash. A mismatch means the client and server
/// disagree (desync) and ranked play stops immediately.
/// Offline: replays are queued and validated later, rewards only after a
/// `valid: true` verdict.
class MatchSession extends ChangeNotifier {
MatchSession({
required this.client,
required this.queue,
required this.deviceId,
});
final ApiClient client;
final OfflineQueue queue;
String deviceId;
SyncStatus status = SyncStatus.offline;
String? matchId;
int? seed;
String? lastError;
int queued = 0;
String? _token;
String get statusLabel => switch (status) {
SyncStatus.offline => 'Offline',
SyncStatus.connecting => 'Verbinde…',
SyncStatus.online => 'Online · ${matchId ?? '-'}',
SyncStatus.desync => 'DESYNC – Ranked gestoppt',
SyncStatus.error => 'Fehler: ${lastError ?? '?'}',
};
Future<void> _ensureToken() async {
_token ??= await client.authenticate(deviceId);
}
/// Creates a server-authoritative match and returns its seed.
Future<int?> startOnlineMatch() async {
status = SyncStatus.connecting;
notifyListeners();
try {
await _ensureToken();
final health = await client.health();
final info = await client.createMatch(
token: _token!,
mode: 'ranked',
contentHash: health['content_hash'] as String,
simVersion: health['sim_version'] as String,
loadouts: const [
[1, 2, 5],
[1, 3, 4],
],
);
matchId = info.matchId;
seed = info.seed;
status = SyncStatus.online;
lastError = null;
notifyListeners();
return info.seed;
} catch (e) {
status = SyncStatus.error;
lastError = e.toString();
debugPrint('iron_arc: online start failed: $e');
notifyListeners();
return null;
}
}
/// Submits one shot. Falls back to the offline queue on transport errors.
Future<void> submitShot({
required int expectHash,
required Map<String, Object?> command,
required int localHashAfter,
required String replayJson,
}) async {
if (status != SyncStatus.online || matchId == null) {
await queue.add(replayJson);
queued = await queue.size();
notifyListeners();
return;
}
try {
final result = await client.submitTurn(
token: _token!,
matchId: matchId!,
expectHash: expectHash,
command: command,
);
if (result.stateHash != localHashAfter) {
status = SyncStatus.desync;
lastError = 'server ${result.stateHash} != local $localHashAfter';
notifyListeners();
}
} on ApiException catch (e) {
if (e.statusCode == 409 && e.code == 'state_conflict') {
status = SyncStatus.desync;
lastError = e.message;
} else {
await queue.add(replayJson);
queued = await queue.size();
}
notifyListeners();
} catch (e) {
await queue.add(replayJson);
queued = await queue.size();
lastError = e.toString();
notifyListeners();
}
}
/// Validates everything that was played offline.
/// Queues a finished offline match for later validation.
Future<void> enqueueReplay(String replayJson) async {
await queue.add(replayJson);
queued = await queue.size();
notifyListeners();
}
Future<int> flushQueue() async {
await _ensureToken();
final validated = await queue.flush(client, _token!);
queued = await queue.size();
notifyListeners();
return validated;
}
Future<void> refreshQueueSize() async {
queued = await queue.size();
notifyListeners();
}
}
+50
View File
@@ -0,0 +1,50 @@
import 'package:shared_preferences/shared_preferences.dart';
import 'api_client.dart';
/// Durable queue of replays that still need server validation.
///
/// Rewards are only granted after `valid: true`, so offline matches are played
/// locally and submitted later ("pending" in the UI).
class OfflineQueue {
static const _key = 'iron_arc.pending_replays';
Future<List<String>> pending() async {
final prefs = await SharedPreferences.getInstance();
return prefs.getStringList(_key) ?? const [];
}
Future<int> size() async => (await pending()).length;
Future<void> add(String replayJson) async {
final prefs = await SharedPreferences.getInstance();
final items = prefs.getStringList(_key) ?? <String>[];
items.add(replayJson);
await prefs.setStringList(_key, items);
}
/// Tries to validate every queued replay.
///
/// Rejected replays are dropped (no rewards), transport failures are kept.
Future<int> flush(ApiClient client, String token) async {
final prefs = await SharedPreferences.getInstance();
final items = prefs.getStringList(_key) ?? <String>[];
if (items.isEmpty) return 0;
final remaining = <String>[];
var validated = 0;
for (final replay in items) {
try {
await client.validate(token: token, replayJson: replay);
validated++;
} on ApiException catch (e) {
if (e.statusCode >= 400 && e.statusCode < 500) continue;
remaining.add(replay);
} catch (_) {
remaining.add(replay);
}
}
await prefs.setStringList(_key, remaining);
return validated;
}
}