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