1use std::collections::HashMap;
2use std::time::Instant;
3
4use serde_json::Value;
5
6use crate::protocol::{GameOutcomeReport, PlayerDeckInfo, MAX_FATAL_MESSAGE_CHARS};
7const PLAYER_SLOT_PREFIX: &str = "player-";
8
9#[derive(Debug, Clone)]
10pub struct QueuedEngineInput {
11 pub from_player: String,
12 pub state: Value,
13}
14
15#[derive(Debug, Default)]
16pub struct ReportedOutcome {
17 pub reported: bool,
18 pub game_over: bool,
19 pub winner_slot: Option<String>,
20 pub conceded_slots: Vec<String>,
21 pub fatal_message: Option<String>,
22 pub turns: Option<u32>,
23}
24
25#[derive(Debug)]
26pub struct GameReplayCache {
27 pub game_id: String,
28 pub started_at: Instant,
29 pub player_order: Vec<String>,
30 pub player_decks: Vec<PlayerDeckInfo>,
31 pub starting_life: i32,
32 pub last_state: Option<Value>,
33 pub last_state_by_slot: HashMap<String, Value>,
34 pub pending_prompts: HashMap<String, Value>,
35 pub pending_directives: HashMap<(String, String), Value>,
36 pub queued_inputs: HashMap<String, Vec<QueuedEngineInput>>,
37 pub outcome: ReportedOutcome,
38}
39
40impl GameReplayCache {
41 pub fn new(
42 game_id: String,
43 player_order: Vec<String>,
44 player_decks: Vec<PlayerDeckInfo>,
45 starting_life: i32,
46 ) -> Self {
47 GameReplayCache {
48 game_id,
49 started_at: Instant::now(),
50 player_order,
51 player_decks,
52 starting_life,
53 last_state: None,
54 last_state_by_slot: HashMap::new(),
55 pending_prompts: HashMap::new(),
56 pending_directives: HashMap::new(),
57 queued_inputs: HashMap::new(),
58 outcome: ReportedOutcome::default(),
59 }
60 }
61
62 pub fn observe(&mut self, envelope: &Value) {
63 match envelope.get("kind").and_then(Value::as_str) {
64 Some("state") => match envelope.get("forPlayer").and_then(Value::as_str) {
65 Some(slot) => {
66 self.last_state_by_slot
67 .insert(slot.to_string(), envelope.clone());
68 }
69 None => self.last_state = Some(envelope.clone()),
70 },
71 Some("stateDelta") => {
74 let slot = envelope.get("forPlayer").and_then(Value::as_str);
75 let previous = match slot {
76 Some(slot) => self.last_state_by_slot.remove(slot),
77 None => self.last_state.take(),
78 };
79 let Some(mut rebuilt) = previous else {
80 return;
81 };
82 let Some(patch) = envelope.get("patch") else {
83 self.restore_state(slot, rebuilt);
84 return;
85 };
86 if let Some(object) = rebuilt.as_object_mut() {
87 let base = object.remove("state").unwrap_or(Value::Null);
88 object.insert(
89 "state".to_string(),
90 manabrew_relay_protocol::state_delta::apply(&base, patch),
91 );
92 if let Some(fingerprint) = envelope.get("fingerprint") {
93 object.insert("fingerprint".to_string(), fingerprint.clone());
94 }
95 }
96 self.restore_state(slot, rebuilt);
97 }
98 Some("prompt") => {
99 if let Some(slot) = envelope.get("forPlayer").and_then(Value::as_str) {
100 self.pending_prompts
101 .insert(slot.to_string(), envelope.clone());
102 }
103 }
104 Some("engineDirective") => {
105 let slot = envelope.get("forPlayer").and_then(Value::as_str);
106 let kind = envelope.pointer("/directive/type").and_then(Value::as_str);
107 if let (Some(slot), Some(kind)) = (slot, kind) {
108 self.pending_directives
109 .insert((slot.to_string(), kind.to_string()), envelope.clone());
110 }
111 }
112 Some("response") => {
113 if let Some(slot) = envelope.get("fromPlayer").and_then(Value::as_str) {
114 self.pending_prompts.remove(slot);
115 }
116 }
117 _ => {}
118 }
119 }
120
121 fn restore_state(&mut self, slot: Option<&str>, state: Value) {
122 match slot {
123 Some(slot) => {
124 self.last_state_by_slot.insert(slot.to_string(), state);
125 }
126 None => self.last_state = Some(state),
127 }
128 }
129
130 pub fn record_outcome(&mut self, report: GameOutcomeReport) {
131 let seats = self.player_order.len();
132 self.outcome = ReportedOutcome {
133 reported: true,
134 game_over: report.game_over,
135 winner_slot: report.winner_slot,
136 conceded_slots: report.conceded_slots.into_iter().take(seats).collect(),
137 fatal_message: report
138 .fatal_message
139 .map(|message| message.chars().take(MAX_FATAL_MESSAGE_CHARS).collect()),
140 turns: report.turns,
141 };
142 }
143
144 pub fn state_after(&self, envelope: &Value) -> Option<&Value> {
148 match envelope.get("forPlayer").and_then(Value::as_str) {
149 Some(slot) => self.last_state_by_slot.get(slot),
150 None => self.last_state.as_ref(),
151 }
152 }
153
154 pub fn slot_for(&self, username: &str) -> Option<String> {
155 self.player_order
156 .iter()
157 .position(|name| name == username)
158 .map(|index| format!("{PLAYER_SLOT_PREFIX}{index}"))
159 }
160
161 pub fn username_for_slot(&self, slot: &str) -> Option<String> {
162 slot.strip_prefix(PLAYER_SLOT_PREFIX)
163 .and_then(|index| index.parse::<usize>().ok())
164 .and_then(|index| self.player_order.get(index).cloned())
165 }
166
167 pub fn queue_input(&mut self, host_username: &str, from_player: &str, state: Value) {
168 self.queued_inputs
169 .entry(host_username.to_string())
170 .or_default()
171 .push(QueuedEngineInput {
172 from_player: from_player.to_string(),
173 state,
174 });
175 }
176
177 pub fn queued_inputs_for(&self, username: &str) -> Vec<QueuedEngineInput> {
178 self.queued_inputs
179 .get(username)
180 .cloned()
181 .unwrap_or_default()
182 }
183
184 pub fn acknowledge_inputs(&mut self, host_username: &str) {
185 self.queued_inputs.remove(host_username);
186 }
187}
188
189#[cfg(test)]
190mod tests {
191 use super::*;
192 use manabrew_relay_protocol::state_delta;
193 use serde_json::json;
194
195 fn cache() -> GameReplayCache {
196 GameReplayCache::new("game-1".into(), vec!["alice".into()], Vec::new(), 40)
197 }
198
199 fn full(slot: &str, state: Value) -> Value {
200 json!({
201 "kind": "state",
202 "forPlayer": slot,
203 "fingerprint": state_delta::fingerprint(&state),
204 "state": state,
205 })
206 }
207
208 fn patch(slot: &str, previous: &Value, next: &Value) -> Value {
211 json!({
212 "kind": "stateDelta",
213 "forPlayer": slot,
214 "fingerprint": state_delta::fingerprint(next),
215 "patch": state_delta::diff(previous, next).expect("the boards differ"),
216 })
217 }
218
219 #[test]
220 fn folds_a_patch_into_the_board_it_hands_back() {
221 let before = json!({ "gameView": { "turn": 1, "phase": "MAIN1" } });
222 let after = json!({ "gameView": { "turn": 2, "phase": "MAIN1" } });
223 let mut replay = cache();
224 replay.observe(&full("player0", before.clone()));
225 let patch = patch("player0", &before, &after);
226 replay.observe(&patch);
227
228 let folded = replay.state_after(&patch).expect("a board for that seat");
229 assert_eq!(folded["state"], after);
230 assert_eq!(folded["fingerprint"], patch["fingerprint"]);
231 }
232
233 #[test]
234 fn a_patch_for_a_seat_with_no_board_leaves_nothing_to_hand_back() {
235 let mut replay = cache();
236 let patch = patch(
237 "player0",
238 &json!({ "gameView": { "turn": 1 } }),
239 &json!({ "gameView": { "turn": 2 } }),
240 );
241 replay.observe(&patch);
242 assert!(replay.state_after(&patch).is_none());
243 }
244
245 #[test]
246 fn seats_do_not_share_a_board() {
247 let mut replay = cache();
248 let mine = json!({ "gameView": { "hand": ["Swamp"] } });
249 let theirs = json!({ "gameView": { "hand": [] } });
250 replay.observe(&full("player0", mine.clone()));
251 replay.observe(&full("player1", theirs.clone()));
252
253 let patch = patch("player0", &mine, &json!({ "gameView": { "hand": [] } }));
254 replay.observe(&patch);
255
256 let other = replay
257 .state_after(&json!({ "kind": "stateDelta", "forPlayer": "player1" }))
258 .expect("player1 still has a board");
259 assert_eq!(other["state"], theirs);
260 }
261}