1use serde::{Deserialize, Serialize};
15
16use crate::protocol::GameType;
17
18use super::types::{
19 default_dictionary, AdminGameInfo, AdventureEventKind, CustomMeta, DebugBackendGameState,
20 DebugHandlerGameState, DebugLobbyState, DebugPlayerInfo, DebugWebsocketContext, ErrorCode,
21 GameConfig, GamePlayerInfo, GameSnapshot, Grid, LobbyChange, LobbyGameInfo, LobbyPlayerInfo,
22 LobbyType, ModeCap, NewsItemPayload, Position, RematchCountdownState, RuneBoxStanding,
23 ScoreInfo, SpectatorInfo, TimerVoteState, TurnPassReason,
24};
25
26#[allow(clippy::large_enum_variant)]
29#[serde_with::serde_as]
30#[derive(Debug, Clone, Serialize, Deserialize)]
31#[serde(tag = "type", rename_all = "snake_case")]
32pub enum ServerMessage {
33 Hello {
40 heartbeat_interval_ms: u32,
42 #[serde(skip_serializing_if = "Option::is_none")]
44 server_version: Option<String>,
45 },
46
47 HeartbeatAck {
51 server_time: u64,
53 },
54
55 LobbyJoined {
60 lobby_id: String,
61 #[serde(skip_serializing_if = "Option::is_none")]
63 lobby_code: Option<String>,
64 lobby: LobbySnapshot,
66 },
67
68 LobbySnapshot { lobby: LobbySnapshot },
73
74 LobbyDelta { changes: Vec<LobbyChange> },
78
79 LobbyLeft,
81
82 ConnectionReplaced,
85
86 GameFull {
88 game_id: String,
90 game_type: GameType,
92 },
93 GameStarted {
100 game_id: String,
101 #[serde(default)]
110 game_type: GameType,
111 grid: Grid,
112 players: Vec<GamePlayerInfo>,
113 your_turn_order: u8,
115 #[serde_as(as = "serde_with::DisplayFromStr")]
117 current_turn: i64,
118 round: u8,
119 max_rounds: u8,
120 #[serde(skip_serializing_if = "Option::is_none")]
122 turn_time_limit: Option<u32>,
123 #[serde(default, skip_serializing_if = "Option::is_none")]
127 custom: Option<CustomMeta>,
128 #[serde(default, skip_serializing_if = "Option::is_none")]
131 time_remaining_ms: Option<u64>,
132 #[serde(default = "default_dictionary")]
136 dictionary: String,
137 },
138
139 GameSnapshot { game_id: String, game: GameSnapshot },
144
145 GameOver {
147 game_id: String,
148 final_scores: Vec<ScoreInfo>,
150 #[serde_as(as = "serde_with::DisplayFromStr")]
152 winner_id: i64,
153 #[serde(default)]
155 is_draw: bool,
156 },
157
158 GameCancelled { game_id: String, reason: String },
160
161 AdventureLevelResult {
166 level: u32,
168 score: i32,
170 stars: u8,
172 personal_best: bool,
174 #[serde(skip_serializing_if = "Option::is_none")]
178 unlocked_level: Option<u32>,
179 #[serde(skip_serializing_if = "Option::is_none")]
186 duration_ms: Option<u64>,
187 },
188
189 DailyResult {
192 seed: i64,
194 score: i32,
196 personal_best: i32,
198 rank: u32,
200 attempts_used: u8,
202 attempts_max: u8,
204 },
205
206 AdventureEvent {
212 game_id: String,
213 kind: AdventureEventKind,
214 affected_positions: Vec<Position>,
215 new_grid: Grid,
218 label: String,
221 },
222
223 PlayerJoined { player: LobbyPlayerInfo },
228
229 PlayerLeft {
231 #[serde_as(as = "serde_with::DisplayFromStr")]
232 player_id: i64,
233 #[serde(skip_serializing_if = "Option::is_none")]
234 reason: Option<String>,
235 },
236
237 PlayerReconnected {
239 #[serde_as(as = "serde_with::DisplayFromStr")]
240 player_id: i64,
241 #[serde(default, skip_serializing_if = "Option::is_none")]
243 game_id: Option<String>,
244 },
245
246 PlayerDisconnected {
248 #[serde(skip_serializing_if = "Option::is_none")]
249 game_id: Option<String>,
250 #[serde_as(as = "serde_with::DisplayFromStr")]
251 player_id: i64,
252 grace_period_seconds: u32,
254 },
255
256 WordScored {
258 #[serde_as(as = "serde_with::DisplayFromStr")]
259 player_id: i64,
260 game_id: String,
261 word: String,
262 score: i32,
263 path: Vec<super::types::Position>,
265 total_score: i32,
267 gems_earned: i32,
269 total_gems: i32,
271 new_grid: Grid,
273 },
274
275 RuneBoxWordAccepted {
282 game_id: String,
284 word: String,
286 letters: i32,
289 total_score: i32,
291 },
292
293 RuneBoxScoreChanged {
300 #[serde_as(as = "serde_with::DisplayFromStr")]
302 player_id: i64,
303 game_id: String,
305 total_score: i32,
307 },
308
309 RuneBoxRoundEnded {
324 game_id: String,
326 round: u8,
328 max_rounds: u8,
332 round_scores: Vec<ScoreInfo>,
335 #[serde_as(as = "Vec<serde_with::DisplayFromStr>")]
342 eliminated: Vec<i64>,
343 standings: Vec<RuneBoxStanding>,
348 #[serde(skip_serializing_if = "Option::is_none")]
353 next_round_starts_at: Option<chrono::DateTime<chrono::Utc>>,
354 },
355
356 TurnChanged {
358 #[serde_as(as = "serde_with::DisplayFromStr")]
359 player_id: i64,
360 game_id: String,
361 round: u8,
362 #[serde(skip_serializing_if = "Option::is_none")]
364 time_remaining: Option<u32>,
365 },
366
367 TurnPassed {
369 #[serde_as(as = "serde_with::DisplayFromStr")]
370 player_id: i64,
371 game_id: String,
372 #[serde(default, skip_serializing_if = "Option::is_none")]
374 reason: Option<TurnPassReason>,
375 },
376
377 RoundChanged {
379 game_id: String,
380 round: u8,
381 max_rounds: u8,
382 #[serde(skip_serializing_if = "Option::is_none")]
385 new_grid: Option<Grid>,
386 },
387
388 BoardShuffled {
390 #[serde_as(as = "serde_with::DisplayFromStr")]
391 player_id: i64,
392 game_id: String,
393 new_grid: Grid,
394 gems_spent: i32,
395 total_gems: i32,
397 },
398
399 TileSwapped {
401 #[serde_as(as = "serde_with::DisplayFromStr")]
402 player_id: i64,
403 game_id: String,
404 row: usize,
405 col: usize,
406 old_letter: char,
407 new_letter: char,
408 gems_spent: i32,
409 total_gems: i32,
411 },
412
413 SwapModeEntered {
415 #[serde_as(as = "serde_with::DisplayFromStr")]
416 player_id: i64,
417 game_id: String,
418 },
419
420 SwapModeExited {
422 #[serde_as(as = "serde_with::DisplayFromStr")]
423 player_id: i64,
424 game_id: String,
425 },
426
427 SpectatorJoined {
432 game_id: String,
433 game: GameSnapshot,
435 },
436
437 SpectatorAdded {
439 spectator: SpectatorInfo,
440 game_id: String,
441 },
442
443 SpectatorRemoved {
445 #[serde_as(as = "serde_with::DisplayFromStr")]
446 spectator_id: i64,
447 game_id: String,
448 },
449
450 SelectionUpdate {
455 #[serde_as(as = "serde_with::DisplayFromStr")]
456 player_id: i64,
457 game_id: String,
458 positions: Vec<super::types::Position>,
459 },
460
461 TimerVoteUpdate {
466 state: TimerVoteState,
467 game_id: String,
468 },
469
470 TurnTimerExpired {
472 #[serde_as(as = "serde_with::DisplayFromStr")]
473 player_id: i64,
474 game_id: String,
475 },
476
477 RematchCountdownUpdate {
484 state: RematchCountdownState,
486 previous_game_id: String,
488 },
489
490 PlayerLeftRematch {
494 #[serde_as(as = "serde_with::DisplayFromStr")]
495 player_id: i64,
496 previous_game_id: String,
498 },
499
500 RematchStarting {
504 #[serde(skip_serializing_if = "Option::is_none")]
506 #[serde_as(as = "Option<serde_with::DisplayFromStr>")]
507 triggered_by: Option<i64>,
508 previous_game_id: String,
510 },
511
512 PlayerPoolChanged {
517 #[serde_as(as = "serde_with::DisplayFromStr")]
518 player_id: i64,
519 old_pool: Option<GameType>,
520 new_pool: Option<GameType>,
521 },
522
523 AdminGamesList { games: Vec<AdminGameInfo> },
528
529 AdminGameDeleted { game_id: String },
531
532 #[serde(rename = "lobby_state")]
537 LobbyStateUpdate {
538 lobby_id: String,
539 players: Vec<LobbyPlayerInfo>,
540 games: Vec<LobbyGameInfo>,
541 },
542
543 DebugStateResponse {
548 timestamp: String,
549 player: DebugPlayerInfo,
550 websocket_context: DebugWebsocketContext,
551 lobby_state: Option<DebugLobbyState>,
552 backend_game_state: Option<DebugBackendGameState>,
553 handler_game_state: Option<DebugHandlerGameState>,
554 },
555
556 NewsAnnounced { item: NewsItemPayload },
570
571 Error {
576 code: ErrorCode,
577 message: String,
578 #[serde(skip_serializing_if = "Option::is_none")]
580 details: Option<serde_json::Value>,
581 },
582}
583
584impl ServerMessage {
585 #[must_use]
587 pub fn error(code: ErrorCode) -> Self {
588 Self::Error {
589 message: code.message().to_string(),
590 code,
591 details: None,
592 }
593 }
594
595 pub fn error_with_message(code: ErrorCode, message: impl Into<String>) -> Self {
597 Self::Error {
598 code,
599 message: message.into(),
600 details: None,
601 }
602 }
603
604 pub fn error_with_details(
606 code: ErrorCode,
607 message: impl Into<String>,
608 details: serde_json::Value,
609 ) -> Self {
610 Self::Error {
611 code,
612 message: message.into(),
613 details: Some(details),
614 }
615 }
616
617 #[must_use]
619 pub fn message_type(&self) -> &'static str {
620 match self {
621 Self::Hello { .. } => "hello",
622 Self::HeartbeatAck { .. } => "heartbeat_ack",
623 Self::LobbyJoined { .. } => "lobby_joined",
624 Self::LobbySnapshot { .. } => "lobby_snapshot",
625 Self::LobbyDelta { .. } => "lobby_delta",
626 Self::LobbyLeft => "lobby_left",
627 Self::ConnectionReplaced => "connection_replaced",
628 Self::GameFull { .. } => "game_full",
629 Self::GameStarted { .. } => "game_started",
630 Self::GameSnapshot { .. } => "game_snapshot",
631 Self::GameOver { .. } => "game_over",
632 Self::GameCancelled { .. } => "game_cancelled",
633 Self::AdventureLevelResult { .. } => "adventure_level_result",
634 Self::DailyResult { .. } => "daily_result",
635 Self::AdventureEvent { .. } => "adventure_event",
636 Self::PlayerJoined { .. } => "player_joined",
637 Self::PlayerLeft { .. } => "player_left",
638 Self::PlayerReconnected { .. } => "player_reconnected",
639 Self::PlayerDisconnected { .. } => "player_disconnected",
640 Self::PlayerPoolChanged { .. } => "player_pool_changed",
641 Self::WordScored { .. } => "word_scored",
642 Self::RuneBoxWordAccepted { .. } => "rune_box_word_accepted",
643 Self::RuneBoxScoreChanged { .. } => "rune_box_score_changed",
644 Self::RuneBoxRoundEnded { .. } => "rune_box_round_ended",
645 Self::TurnChanged { .. } => "turn_changed",
646 Self::TurnPassed { .. } => "turn_passed",
647 Self::RoundChanged { .. } => "round_changed",
648 Self::BoardShuffled { .. } => "board_shuffled",
649 Self::TileSwapped { .. } => "tile_swapped",
650 Self::SwapModeEntered { .. } => "swap_mode_entered",
651 Self::SwapModeExited { .. } => "swap_mode_exited",
652 Self::SpectatorJoined { .. } => "spectator_joined",
653 Self::SpectatorAdded { .. } => "spectator_added",
654 Self::SpectatorRemoved { .. } => "spectator_removed",
655 Self::SelectionUpdate { .. } => "selection_update",
656 Self::TimerVoteUpdate { .. } => "timer_vote_update",
657 Self::TurnTimerExpired { .. } => "turn_timer_expired",
658 Self::RematchCountdownUpdate { .. } => "rematch_countdown_update",
659 Self::PlayerLeftRematch { .. } => "player_left_rematch",
660 Self::RematchStarting { .. } => "rematch_starting",
661 Self::AdminGamesList { .. } => "admin_games_list",
662 Self::AdminGameDeleted { .. } => "admin_game_deleted",
663 Self::LobbyStateUpdate { .. } => "lobby_state",
664 Self::DebugStateResponse { .. } => "debug_state_response",
665
666 Self::NewsAnnounced { .. } => "news_announced",
667
668 Self::Error { .. } => "error",
669 }
670 }
671
672 #[must_use]
674 pub fn is_error(&self) -> bool {
675 matches!(self, Self::Error { .. })
676 }
677}
678
679impl TryFrom<serde_json::Value> for ServerMessage {
681 type Error = serde_json::Error;
682
683 fn try_from(
684 value: serde_json::Value,
685 ) -> Result<Self, <ServerMessage as TryFrom<serde_json::Value>>::Error> {
686 serde_json::from_value(value)
687 }
688}
689#[serde_with::serde_as]
695#[derive(Debug, Clone, Serialize, Deserialize)]
696pub struct LobbySnapshot {
697 pub lobby_id: String,
698 pub lobby_type: LobbyType,
699 #[serde(skip_serializing_if = "Option::is_none")]
700 pub lobby_code: Option<String>,
701 pub players: Vec<LobbyPlayerInfo>,
702 pub games: Vec<LobbyGameInfo>,
703 #[serde(default = "default_max_players")]
705 pub max_players: u8,
706 #[serde(default, skip_serializing_if = "Option::is_none")]
709 pub sandbox_config: Option<GameConfig>,
710 #[serde_as(as = "Option<serde_with::DisplayFromStr>")]
716 #[serde(default, skip_serializing_if = "Option::is_none")]
717 pub host_id: Option<i64>,
718 #[serde(default = "default_true")]
721 pub auto_rematch: bool,
722 #[serde(default = "default_dictionary")]
725 pub dictionary: String,
726 #[serde(default, skip_serializing_if = "Vec::is_empty")]
729 pub mode_caps: Vec<ModeCap>,
730}
731
732fn default_max_players() -> u8 {
733 6
734}
735
736fn default_true() -> bool {
737 true
738}
739
740#[cfg(test)]
741mod tests {
742 use super::*;
743 use crate::protocol::types::NewsNotificationType;
746 use crate::protocol::{types, GameType};
747
748 #[test]
749 fn test_server_message_into_json() {
750 let msg = ServerMessage::BoardShuffled {
751 player_id: 1_234_567_890,
752 game_id: "1234567890".to_string(),
753 new_grid: Grid::new(),
754 gems_spent: 0,
755 total_gems: 0,
756 };
757 let json = serde_json::to_string(&msg).unwrap();
758 assert!(json.contains(r#""type":"board_shuffled""#));
759 assert!(json.contains(r#""player_id":"1234567890""#));
760 assert!(json.contains(r#""game_id":"1234567890""#));
761 assert!(json.contains(r#""new_grid":[]"#));
762 assert!(json.contains(r#""gems_spent":0"#));
763 assert!(json.contains(r#""total_gems":0"#));
764 }
765
766 #[test]
767 fn test_heartbeat_ack_serialization() {
768 let msg = ServerMessage::HeartbeatAck {
769 server_time: 1_701_234_567_890,
770 };
771 let json = serde_json::to_string(&msg).unwrap();
772 assert!(json.contains(r#""type":"heartbeat_ack""#));
773 assert!(json.contains(r#""server_time":1701234567890"#));
774 }
775
776 #[test]
777 fn test_error_message_creation() {
778 let msg = ServerMessage::error(ErrorCode::NotYourTurn);
779 match msg {
780 ServerMessage::Error { code, message, .. } => {
781 assert_eq!(code, ErrorCode::NotYourTurn);
782 assert_eq!(message, "It's not your turn");
783 }
784 _ => panic!("Expected error message"),
785 }
786 }
787
788 #[test]
789 fn test_error_with_details() {
790 let msg = ServerMessage::error_with_details(
791 ErrorCode::InvalidPath,
792 "Tiles must be adjacent",
793 serde_json::json!({"positions": [[0,0], [2,2]]}),
794 );
795 match msg {
796 ServerMessage::Error { details, .. } => {
797 assert!(details.is_some());
798 }
799 _ => panic!("Expected error message"),
800 }
801 }
802
803 #[test]
804 fn test_player_joined_serialization() {
805 let msg = ServerMessage::PlayerJoined {
806 player: LobbyPlayerInfo {
807 user_id: 123,
808 username: "TestPlayer".to_string(),
809 name: None,
810 avatar_url: None,
811 banner_url: None,
812 accent_color: None,
813 current_game_pool: None,
814 active_game_id: None,
815 spectate_game_id: None,
816 },
817 };
818 let json = serde_json::to_string(&msg).unwrap();
819 assert!(json.contains(r#""type":"player_joined""#));
820 assert!(json.contains(r#""user_id":"123""#));
821 }
822
823 #[test]
824 fn test_message_type() {
825 assert_eq!(
826 ServerMessage::HeartbeatAck { server_time: 0 }.message_type(),
827 "heartbeat_ack"
828 );
829 assert_eq!(
830 ServerMessage::error(ErrorCode::NotYourTurn).message_type(),
831 "error"
832 );
833
834 assert_eq!(
838 ServerMessage::AdventureLevelResult {
839 level: 1,
840 score: 10,
841 stars: 1,
842 personal_best: true,
843 unlocked_level: None,
844 duration_ms: None,
845 }
846 .message_type(),
847 "adventure_level_result",
848 );
849 assert_eq!(
850 ServerMessage::AdventureEvent {
851 game_id: "g".to_string(),
852 kind: types::AdventureEventKind::Bomb,
853 affected_positions: vec![],
854 new_grid: vec![],
855 label: String::new(),
856 }
857 .message_type(),
858 "adventure_event",
859 );
860 }
861
862 #[test]
863 fn test_adventure_level_result_serialization() {
864 let msg = ServerMessage::AdventureLevelResult {
868 level: 3,
869 score: 120,
870 stars: 2,
871 personal_best: false,
872 unlocked_level: None,
873 duration_ms: None,
874 };
875 let json = serde_json::to_string(&msg).unwrap();
876 assert!(json.contains(r#""type":"adventure_level_result""#));
877 assert!(json.contains(r#""level":3"#));
878 assert!(json.contains(r#""score":120"#));
879 assert!(json.contains(r#""stars":2"#));
880 assert!(json.contains(r#""personal_best":false"#));
881 assert!(
882 !json.contains("unlocked_level"),
883 "unlocked_level should be omitted when None (got: {json})"
884 );
885 assert!(
886 !json.contains("duration_ms"),
887 "duration_ms should be omitted when None (got: {json})"
888 );
889
890 let msg = ServerMessage::AdventureLevelResult {
896 level: 3,
897 score: 120,
898 stars: 3,
899 personal_best: true,
900 unlocked_level: Some(4),
901 duration_ms: Some(123_456),
902 };
903 let json = serde_json::to_string(&msg).unwrap();
904 assert!(json.contains(r#""unlocked_level":4"#));
905 assert!(json.contains(r#""duration_ms":123456"#));
906
907 let parsed: ServerMessage = serde_json::from_str(&json).unwrap();
910 match parsed {
911 ServerMessage::AdventureLevelResult {
912 level,
913 score,
914 stars,
915 personal_best,
916 unlocked_level,
917 duration_ms,
918 } => {
919 assert_eq!(level, 3);
920 assert_eq!(score, 120);
921 assert_eq!(stars, 3);
922 assert!(personal_best);
923 assert_eq!(unlocked_level, Some(4));
924 assert_eq!(duration_ms, Some(123_456));
925 }
926 other => panic!("expected AdventureLevelResult, got {other:?}"),
927 }
928 }
929
930 #[test]
931 fn daily_result_serializes() {
932 let msg = ServerMessage::DailyResult {
933 seed: 1_592_668_382,
934 score: 240,
935 personal_best: 240,
936 rank: 3,
937 attempts_used: 1,
938 attempts_max: 1,
939 };
940 assert_eq!(msg.message_type(), "daily_result");
941 let s = serde_json::to_string(&msg).unwrap();
942 assert!(s.contains("\"type\":\"daily_result\""));
943 assert!(s.contains("\"rank\":3"));
944 let back: ServerMessage = serde_json::from_str(&s).unwrap();
945 assert!(matches!(back, ServerMessage::DailyResult { rank: 3, .. }));
946 }
947
948 #[test]
949 fn game_started_time_remaining_optional() {
950 let msg = ServerMessage::GameStarted {
951 game_type: GameType::Open,
952 game_id: "g1".into(),
953 grid: vec![],
954 players: vec![],
955 your_turn_order: 0,
956 current_turn: 42,
957 round: 1,
958 max_rounds: 1,
959 turn_time_limit: None,
960 custom: None,
961 time_remaining_ms: None,
962 dictionary: "main".to_string(),
963 };
964 let s = serde_json::to_string(&msg).unwrap();
965 assert!(!s.contains("time_remaining_ms"));
966 }
967
968 #[test]
969 fn test_adventure_event_serialization() {
970 let msg = ServerMessage::AdventureEvent {
971 game_id: "abc".to_string(),
972 kind: types::AdventureEventKind::Bomb,
973 affected_positions: vec![
974 types::Position { row: 1, col: 2 },
975 types::Position { row: 2, col: 2 },
976 ],
977 new_grid: vec![vec![
978 types::GridCell {
982 letter: 'A',
983 value: 1,
984 multiplier: None,
985 has_gem: false,
986 is_hole: false,
987 is_poisoned: false,
988 is_abducted: false,
989 },
990 types::GridCell {
991 letter: ' ',
992 value: 0,
993 multiplier: None,
994 has_gem: false,
995 is_hole: true,
996 is_poisoned: false,
997 is_abducted: false,
998 },
999 ]],
1000 label: "💣 Bomb!".to_string(),
1001 };
1002
1003 let json = serde_json::to_string(&msg).unwrap();
1004 assert!(json.contains(r#""type":"adventure_event""#));
1005 assert!(json.contains(r#""game_id":"abc""#));
1006 assert!(json.contains(r#""kind":"bomb""#));
1008 assert!(json.contains(r#""affected_positions":[{"row":1,"col":2}"#));
1010 assert!(json.contains(r#""letter":"A""#));
1012 assert!(json.contains(r#""is_hole":true"#));
1013
1014 let parsed: ServerMessage = serde_json::from_str(&json).unwrap();
1016 match parsed {
1017 ServerMessage::AdventureEvent {
1018 game_id,
1019 kind,
1020 affected_positions,
1021 new_grid,
1022 label,
1023 } => {
1024 assert_eq!(game_id, "abc");
1025 assert_eq!(kind, types::AdventureEventKind::Bomb);
1026 assert_eq!(affected_positions.len(), 2);
1027 assert_eq!(new_grid[0].len(), 2);
1028 assert!(new_grid[0][1].is_hole);
1029 assert_eq!(label, "💣 Bomb!");
1030 }
1031 other => panic!("expected AdventureEvent, got {other:?}"),
1032 }
1033 }
1034
1035 #[test]
1036 fn test_selection_update_serialization() {
1037 let msg = ServerMessage::SelectionUpdate {
1038 player_id: 11,
1039 game_id: "game1".to_string(),
1040 positions: vec![
1041 types::Position { row: 0, col: 0 },
1042 types::Position { row: 0, col: 1 },
1043 ],
1044 };
1045 let json = serde_json::to_string(&msg).unwrap();
1046 assert!(json.contains(r#""type":"selection_update""#));
1047 assert!(json.contains(r#""player_id":"11""#));
1048 assert!(json.contains(r#""game_id":"game1""#));
1049 }
1050
1051 #[test]
1052 fn test_player_queue_changed_serialization() {
1053 let msg = ServerMessage::PlayerPoolChanged {
1054 player_id: 123,
1055 old_pool: Some(GameType::Open),
1056 new_pool: Some(GameType::Adventure),
1057 };
1058 let json = serde_json::to_string(&msg).unwrap();
1059 assert!(json.contains(r#""type":"player_pool_changed""#));
1060 assert!(json.contains(r#""player_id":"123""#));
1061 assert!(json.contains(r#""old_pool":"open""#));
1062 assert!(json.contains(r#""new_pool":"adventure""#));
1063 }
1064
1065 #[test]
1066 fn test_debug_state_response_serialization() {
1067 let msg = ServerMessage::DebugStateResponse {
1068 timestamp: "2024-01-01T12:00:00Z".to_string(),
1069 player: DebugPlayerInfo {
1070 user_id: 987654321,
1071 username: "debug_user".to_string(),
1072 },
1073 websocket_context: DebugWebsocketContext {
1074 lobby_id: Some("lobby123".to_string()),
1075 game_id: Some("game456".to_string()),
1076 is_spectating: false,
1077 },
1078 lobby_state: Some(DebugLobbyState::Found {
1079 lobby_id: "lobby123".to_string(),
1080 player_in_lobby: true,
1081 lobby_player_ids: vec![111, 222, 333],
1082 active_game_id: Some("game456".to_string()),
1083 }),
1084 backend_game_state: Some(DebugBackendGameState::Found {
1085 game_id: "game456".to_string(),
1086 player_in_session_players: true,
1087 spectator_in_session: false,
1088 session_player_ids: vec![111, 222],
1089 session_spectator_ids: vec![],
1090 lobby_id: "lobby123".to_string(),
1091 }),
1092 handler_game_state: Some(DebugHandlerGameState::Found {
1093 game_id: "game456".to_string(),
1094 player_in_handler_game: true,
1095 handler_player_ids: vec![111, 222],
1096 current_turn_index: 0,
1097 round: 1,
1098 state: "in_progress".to_string(),
1099 }),
1100 };
1101
1102 let json = serde_json::to_string(&msg).unwrap();
1104
1105 assert!(json.contains(r#""type":"debug_state_response""#));
1107
1108 assert!(json.contains(r#""user_id":987654321"#));
1110 assert!(json.contains(r#""lobby_player_ids":[111,222,333]"#));
1111 assert!(json.contains(r#""session_player_ids":[111,222]"#));
1112 assert!(json.contains(r#""handler_player_ids":[111,222]"#));
1113
1114 assert!(json.contains(r#""timestamp":"2024-01-01T12:00:00Z""#));
1116 assert!(json.contains(r#""username":"debug_user""#));
1117 assert!(json.contains(r#""lobby_id":"lobby123""#));
1118 assert!(json.contains(r#""game_id":"game456""#));
1119 assert!(json.contains(r#""is_spectating":false"#));
1120 assert!(json.contains(r#""player_in_lobby":true"#));
1121
1122 let deserialized: ServerMessage = serde_json::from_str(&json).unwrap();
1124 match deserialized {
1125 ServerMessage::DebugStateResponse {
1126 timestamp,
1127 player,
1128 websocket_context,
1129 lobby_state,
1130 backend_game_state,
1131 handler_game_state,
1132 } => {
1133 assert_eq!(timestamp, "2024-01-01T12:00:00Z");
1134 assert_eq!(player.user_id, 987654321);
1135 assert_eq!(player.username, "debug_user");
1136 assert_eq!(websocket_context.lobby_id, Some("lobby123".to_string()));
1137 assert_eq!(websocket_context.game_id, Some("game456".to_string()));
1138 assert!(!websocket_context.is_spectating);
1139 assert!(lobby_state.is_some());
1140 assert!(backend_game_state.is_some());
1141 assert!(handler_game_state.is_some());
1142 }
1143 _ => panic!("Expected DebugStateResponse message"),
1144 }
1145 }
1146
1147 #[test]
1148 fn test_debug_state_response_with_errors() {
1149 let msg = ServerMessage::DebugStateResponse {
1151 timestamp: "2024-01-01T12:00:00Z".to_string(),
1152 player: DebugPlayerInfo {
1153 user_id: 123,
1154 username: "test".to_string(),
1155 },
1156 websocket_context: DebugWebsocketContext {
1157 lobby_id: None,
1158 game_id: None,
1159 is_spectating: false,
1160 },
1161 lobby_state: Some(DebugLobbyState::Error {
1162 error: "Lobby not found".to_string(),
1163 }),
1164 backend_game_state: Some(DebugBackendGameState::Error {
1165 error: "Game not found".to_string(),
1166 }),
1167 handler_game_state: Some(DebugHandlerGameState::Error {
1168 error: "Handler not found".to_string(),
1169 }),
1170 };
1171
1172 let json = serde_json::to_string(&msg).unwrap();
1173
1174 assert!(json.contains(r#""error":"Lobby not found""#));
1176 assert!(json.contains(r#""error":"Game not found""#));
1177 assert!(json.contains(r#""error":"Handler not found""#));
1178
1179 let deserialized: ServerMessage = serde_json::from_str(&json).unwrap();
1181 assert!(matches!(
1182 deserialized,
1183 ServerMessage::DebugStateResponse { .. }
1184 ));
1185 }
1186
1187 #[test]
1188 fn test_debug_state_response_minimal() {
1189 let msg = ServerMessage::DebugStateResponse {
1191 timestamp: "2024-01-01T12:00:00Z".to_string(),
1192 player: DebugPlayerInfo {
1193 user_id: 456,
1194 username: "minimal_user".to_string(),
1195 },
1196 websocket_context: DebugWebsocketContext {
1197 lobby_id: None,
1198 game_id: None,
1199 is_spectating: true,
1200 },
1201 lobby_state: None,
1202 backend_game_state: None,
1203 handler_game_state: None,
1204 };
1205
1206 let json = serde_json::to_string(&msg).unwrap();
1207
1208 assert!(json.contains(r#""type":"debug_state_response""#));
1210
1211 assert!(json.contains(r#""user_id":456"#));
1213 assert!(json.contains(r#""username":"minimal_user""#));
1214 assert!(json.contains(r#""is_spectating":true"#));
1215
1216 let deserialized: ServerMessage = serde_json::from_str(&json).unwrap();
1218 match deserialized {
1219 ServerMessage::DebugStateResponse {
1220 player,
1221 lobby_state,
1222 backend_game_state,
1223 handler_game_state,
1224 ..
1225 } => {
1226 assert_eq!(player.user_id, 456);
1227 assert!(lobby_state.is_none());
1228 assert!(backend_game_state.is_none());
1229 assert!(handler_game_state.is_none());
1230 }
1231 _ => panic!("Expected DebugStateResponse message"),
1232 }
1233 }
1234
1235 #[test]
1236 fn test_news_announced_round_trip() {
1237 let now = chrono::Utc::now();
1238 let expires = now + chrono::Duration::hours(1);
1239 let original = ServerMessage::NewsAnnounced {
1240 item: NewsItemPayload {
1241 id: "abc-123".to_string(),
1242 title: "Scheduled Maintenance".to_string(),
1243 message: "Servers will restart for ~5 minutes.".to_string(),
1244 notification_type: NewsNotificationType::Maintenance,
1245 created_at: now,
1246 expires_at: Some(expires),
1247 auto_hide_seconds: 0,
1248 refresh_on_every_login: false,
1249 priority: 100,
1250 },
1251 };
1252
1253 let json = serde_json::to_string(&original).unwrap();
1254 assert!(json.contains(r#""type":"news_announced""#));
1255 assert!(json.contains(r#""notification_type":"maintenance""#));
1256
1257 let parsed: ServerMessage = serde_json::from_str(&json).unwrap();
1258 match parsed {
1259 ServerMessage::NewsAnnounced { item } => {
1260 assert_eq!(item.id, "abc-123");
1261 assert_eq!(item.notification_type, NewsNotificationType::Maintenance);
1262 assert_eq!(item.priority, 100);
1263 assert_eq!(item.expires_at, Some(expires));
1264 }
1265 _ => panic!("Expected NewsAnnounced"),
1266 }
1267 }
1268
1269 #[test]
1270 fn game_started_custom_marker_roundtrips_and_omits_when_none() {
1271 use crate::protocol::types::CustomMeta;
1272
1273 let msg = ServerMessage::GameStarted {
1275 game_type: GameType::Open,
1276 game_id: "game-sandbox-1".to_string(),
1277 grid: vec![],
1278 players: vec![types::GamePlayerInfo {
1279 user_id: 111_222_333_444_555_666,
1280 username: "Player1".to_string(),
1281 name: None,
1282 avatar_url: None,
1283 turn_order: 0,
1284 score: 0,
1285 gems: 0,
1286 is_connected: true,
1287 team: None,
1288 }],
1289 your_turn_order: 0,
1290 current_turn: 111_222_333_444_555_666,
1291 round: 1,
1292 max_rounds: 5,
1293 turn_time_limit: None,
1294 custom: Some(CustomMeta {}),
1295 time_remaining_ms: None,
1296 dictionary: "main".to_string(),
1297 };
1298 let json = serde_json::to_string(&msg).unwrap();
1299 assert!(
1300 json.contains("\"custom\""),
1301 "custom should serialize when Some (got: {json})"
1302 );
1303 let back: ServerMessage = serde_json::from_str(&json).unwrap();
1304 assert!(
1305 matches!(
1306 back,
1307 ServerMessage::GameStarted {
1308 custom: Some(_),
1309 ..
1310 }
1311 ),
1312 "custom should deserialize as Some"
1313 );
1314
1315 let ffa = ServerMessage::GameStarted {
1317 game_type: GameType::Open,
1318 game_id: "game-ffa-1".to_string(),
1319 grid: vec![],
1320 players: vec![],
1321 your_turn_order: 0,
1322 current_turn: 111_222_333_444_555_666,
1323 round: 1,
1324 max_rounds: 5,
1325 turn_time_limit: None,
1326 custom: None,
1327 time_remaining_ms: None,
1328 dictionary: "main".to_string(),
1329 };
1330 let json2 = serde_json::to_string(&ffa).unwrap();
1331 assert!(
1332 !json2.contains("\"custom\""),
1333 "custom should be omitted when None (got: {json2})"
1334 );
1335 }
1336
1337 #[test]
1338 fn turn_passed_carries_an_optional_reason() {
1339 let m = ServerMessage::TurnPassed {
1340 player_id: 7,
1341 game_id: "g".into(),
1342 reason: Some(crate::TurnPassReason::Disconnected),
1343 };
1344 assert_eq!(serde_json::to_value(&m).unwrap()["reason"], "disconnected");
1345 let old: ServerMessage =
1346 serde_json::from_str(r#"{"type":"turn_passed","player_id":"7","game_id":"g"}"#)
1347 .unwrap();
1348 assert!(matches!(
1349 old,
1350 ServerMessage::TurnPassed { reason: None, .. }
1351 ));
1352 let none = ServerMessage::TurnPassed {
1353 player_id: 7,
1354 game_id: "g".into(),
1355 reason: None,
1356 };
1357 assert!(serde_json::to_value(&none).unwrap().get("reason").is_none());
1358 }
1359
1360 #[test]
1361 fn player_reconnected_names_its_game_when_known() {
1362 let m = ServerMessage::PlayerReconnected {
1363 player_id: 7,
1364 game_id: Some("g".into()),
1365 };
1366 assert_eq!(serde_json::to_value(&m).unwrap()["game_id"], "g");
1367 let none = ServerMessage::PlayerReconnected {
1368 player_id: 7,
1369 game_id: None,
1370 };
1371 assert!(serde_json::to_value(&none)
1372 .unwrap()
1373 .get("game_id")
1374 .is_none());
1375 let old: ServerMessage =
1376 serde_json::from_str(r#"{"type":"player_reconnected","player_id":"7"}"#).unwrap();
1377 assert!(matches!(
1378 old,
1379 ServerMessage::PlayerReconnected { game_id: None, .. }
1380 ));
1381 }
1382
1383 #[test]
1384 fn connection_replaced_is_a_bare_tag() {
1385 let m = ServerMessage::ConnectionReplaced;
1386 assert_eq!(
1387 serde_json::to_string(&m).unwrap(),
1388 r#"{"type":"connection_replaced"}"#
1389 );
1390 assert_eq!(m.message_type(), "connection_replaced");
1391 }
1392
1393 #[test]
1394 fn game_full_round_trips() {
1395 let m = ServerMessage::GameFull {
1396 game_id: "g".into(),
1397 game_type: GameType::Open,
1398 };
1399 let json = serde_json::to_string(&m).unwrap();
1400 assert_eq!(
1401 serde_json::from_str::<serde_json::Value>(&json).unwrap(),
1402 serde_json::from_str::<serde_json::Value>(
1403 r#"{"type":"game_full","game_id":"g","game_type":"open"}"#
1404 )
1405 .unwrap()
1406 );
1407 assert!(matches!(
1408 serde_json::from_str::<ServerMessage>(&json).unwrap(),
1409 ServerMessage::GameFull {
1410 game_type: GameType::Open,
1411 ..
1412 }
1413 ));
1414 assert_eq!(m.message_type(), "game_full");
1415 }
1416
1417 #[test]
1418 fn lobby_snapshot_mode_caps_are_additive() {
1419 let old = r#"{"lobby_id":"l","lobby_type":"custom","players":[],"games":[]}"#;
1420 let snap: LobbySnapshot = serde_json::from_str(old).unwrap();
1421 assert!(snap.mode_caps.is_empty());
1422 assert!(!serde_json::to_string(&snap).unwrap().contains("mode_caps"));
1423 let capped = LobbySnapshot {
1424 mode_caps: vec![crate::ModeCap {
1425 game_type: GameType::Open,
1426 max_players: 5,
1427 }],
1428 ..snap
1429 };
1430 let v = serde_json::to_value(&capped).unwrap();
1431 assert_eq!(
1432 v["mode_caps"],
1433 serde_json::json!([{"game_type":"open","max_players":5}])
1434 );
1435 }
1436
1437 #[test]
1438 fn connect_params_parse_kind_and_tab() {
1439 use crate::{ConnectKind, ConnectParams};
1440 assert_eq!(
1441 serde_json::to_string(&ConnectKind::TakeOver).unwrap(),
1442 r#""take_over""#
1443 );
1444 let p: ConnectParams = serde_json::from_str(r#"{"tab":"t1","kind":"take_over"}"#).unwrap();
1445 assert_eq!(p.tab.as_deref(), Some("t1"));
1446 assert_eq!(p.kind, Some(ConnectKind::TakeOver));
1447 let d = ConnectParams::default();
1448 assert!(d.tab.is_none() && d.kind.is_none());
1449 }
1450
1451 #[test]
1452 fn lobby_snapshot_carries_sandbox_config() {
1453 let mut snap = LobbySnapshot {
1455 lobby_id: "test-lobby".to_string(),
1456 lobby_type: LobbyType::Custom,
1457 lobby_code: None,
1458 players: vec![],
1459 games: vec![],
1460 max_players: 6,
1461 sandbox_config: None,
1462 host_id: None,
1463 auto_rematch: true,
1464 mode_caps: vec![],
1465 dictionary: "main".to_string(),
1466 };
1467 snap.sandbox_config = Some(GameConfig::default());
1468
1469 let json = serde_json::to_string(&snap).unwrap();
1470 assert!(
1471 json.contains("sandbox_config"),
1472 "sandbox_config should be present when Some (got: {json})"
1473 );
1474 let back: LobbySnapshot = serde_json::from_str(&json).unwrap();
1475 assert!(back.sandbox_config.is_some());
1476
1477 let plain = LobbySnapshot {
1479 lobby_id: "plain-lobby".to_string(),
1480 lobby_type: LobbyType::Custom,
1481 lobby_code: None,
1482 players: vec![],
1483 games: vec![],
1484 max_players: 6,
1485 sandbox_config: None,
1486 host_id: None,
1487 auto_rematch: true,
1488 mode_caps: vec![],
1489 dictionary: "main".to_string(),
1490 };
1491 assert!(
1492 !serde_json::to_string(&plain)
1493 .unwrap()
1494 .contains("sandbox_config"),
1495 "sandbox_config should be omitted when None"
1496 );
1497 assert!(
1498 !serde_json::to_string(&plain).unwrap().contains("host_id"),
1499 "host_id should be omitted when None"
1500 );
1501 }
1502
1503 #[test]
1504 fn lobby_snapshot_host_id_serializes_as_string_snowflake_safe() {
1505 let snowflake: i64 = 123_456_789_012_345_678; let snap = LobbySnapshot {
1510 lobby_id: "lobby".to_string(),
1511 lobby_type: LobbyType::Custom,
1512 lobby_code: None,
1513 players: vec![],
1514 games: vec![],
1515 max_players: 6,
1516 sandbox_config: None,
1517 host_id: Some(snowflake),
1518 auto_rematch: true,
1519 mode_caps: vec![],
1520 dictionary: "main".to_string(),
1521 };
1522 let json = serde_json::to_string(&snap).unwrap();
1523 assert!(
1525 json.contains(r#""host_id":"123456789012345678""#),
1526 "host_id must serialize as a quoted string, got: {json}"
1527 );
1528 let back: LobbySnapshot = serde_json::from_str(&json).unwrap();
1530 assert_eq!(back.host_id, Some(snowflake));
1531 }
1532
1533 #[test]
1534 fn runebox_word_accepted_round_trips() {
1535 let msg = ServerMessage::RuneBoxWordAccepted {
1536 game_id: "g1".to_string(),
1537 word: "RUNES".to_string(),
1538 letters: 5,
1539 total_score: 17,
1540 };
1541 let json = serde_json::to_string(&msg).unwrap();
1542 assert!(json.contains(r#""type":"rune_box_word_accepted""#));
1543 let back: ServerMessage = serde_json::from_str(&json).unwrap();
1544 match back {
1545 ServerMessage::RuneBoxWordAccepted {
1546 word,
1547 letters,
1548 total_score,
1549 ..
1550 } => {
1551 assert_eq!(word, "RUNES");
1552 assert_eq!(letters, 5);
1553 assert_eq!(total_score, 17);
1554 }
1555 other => panic!("wrong variant: {other:?}"),
1556 }
1557 }
1558
1559 #[test]
1560 fn runebox_score_changed_carries_no_word() {
1561 let msg = ServerMessage::RuneBoxScoreChanged {
1567 player_id: 1_234_567_890_123_456_789,
1568 game_id: "g1".to_string(),
1569 total_score: 12,
1570 };
1571 let json = serde_json::to_string(&msg).unwrap();
1572 assert!(
1573 !json.contains("word"),
1574 "opponent broadcast leaked a word: {json}"
1575 );
1576 assert!(
1578 json.contains(r#""player_id":"1234567890123456789""#),
1579 "player_id must serialize as a quoted string, got: {json}"
1580 );
1581 let back: ServerMessage = serde_json::from_str(&json).unwrap();
1582 match back {
1583 ServerMessage::RuneBoxScoreChanged {
1584 player_id,
1585 total_score,
1586 ..
1587 } => {
1588 assert_eq!(player_id, 1_234_567_890_123_456_789);
1589 assert_eq!(total_score, 12);
1590 }
1591 other => panic!("wrong variant: {other:?}"),
1592 }
1593 }
1594
1595 #[test]
1596 fn runebox_messages_have_distinct_wire_types() {
1597 let accepted = ServerMessage::RuneBoxWordAccepted {
1598 game_id: "g1".to_string(),
1599 word: "RUNES".to_string(),
1600 letters: 5,
1601 total_score: 5,
1602 };
1603 let changed = ServerMessage::RuneBoxScoreChanged {
1604 player_id: 1,
1605 game_id: "g1".to_string(),
1606 total_score: 5,
1607 };
1608 assert_eq!(accepted.message_type(), "rune_box_word_accepted");
1609 assert_eq!(changed.message_type(), "rune_box_score_changed");
1610 }
1611
1612 #[test]
1618 fn game_started_carries_its_game_type() {
1619 let msg = ServerMessage::GameStarted {
1620 game_type: GameType::RuneBox,
1621 game_id: "g1".to_string(),
1622 grid: vec![],
1623 players: vec![],
1624 your_turn_order: 0,
1625 current_turn: 1,
1626 round: 1,
1627 max_rounds: 3,
1628 turn_time_limit: None,
1629 custom: None,
1630 time_remaining_ms: Some(90_000),
1631 dictionary: "main".to_string(),
1632 };
1633 let json = serde_json::to_string(&msg).unwrap();
1634 assert!(
1635 json.contains(r#""game_type":"rune_box""#),
1636 "game_started must name the mode, got: {json}"
1637 );
1638 let back: ServerMessage = serde_json::from_str(&json).unwrap();
1639 match back {
1640 ServerMessage::GameStarted { game_type, .. } => {
1641 assert_eq!(game_type, GameType::RuneBox);
1642 }
1643 other => panic!("wrong variant: {other:?}"),
1644 }
1645 }
1646
1647 fn round_ended_sample(
1649 next_round_starts_at: Option<chrono::DateTime<chrono::Utc>>,
1650 ) -> ServerMessage {
1651 ServerMessage::RuneBoxRoundEnded {
1652 game_id: "g1".to_string(),
1653 round: 1,
1654 max_rounds: 2,
1655 round_scores: vec![
1656 ScoreInfo {
1657 user_id: 1_234_567_890_123_456_789,
1658 username: "Ada".to_string(),
1659 name: None,
1660 score: 41,
1661 },
1662 ScoreInfo {
1663 user_id: 8_876_543_210_987_654_321_i64,
1664 username: "Bo".to_string(),
1665 name: None,
1666 score: 12,
1667 },
1668 ],
1669 eliminated: vec![8_876_543_210_987_654_321_i64],
1670 standings: vec![RuneBoxStanding {
1671 player_id: 1_234_567_890_123_456_789,
1672 username: "Ada".to_string(),
1673 name: None,
1674 round_wins: 1,
1675 total_score: 41,
1676 eliminated: false,
1677 }],
1678 next_round_starts_at,
1679 }
1680 }
1681
1682 #[test]
1686 fn round_end_is_a_distinct_message_type_from_game_over() {
1687 let round_end = round_ended_sample(None);
1688 let match_end = ServerMessage::GameOver {
1689 game_id: "g1".to_string(),
1690 final_scores: vec![],
1691 winner_id: 1,
1692 is_draw: false,
1693 };
1694 assert_eq!(round_end.message_type(), "rune_box_round_ended");
1695 assert_eq!(match_end.message_type(), "game_over");
1696 assert_ne!(round_end.message_type(), match_end.message_type());
1697 }
1698
1699 #[test]
1700 fn round_ended_round_trips_with_snowflakes_as_strings() {
1701 let json = serde_json::to_string(&round_ended_sample(None)).unwrap();
1702 assert!(json.contains(r#""type":"rune_box_round_ended""#));
1703 assert!(
1707 json.contains(r#""eliminated":["8876543210987654321"]"#),
1708 "eliminated ids must be quoted strings, got: {json}"
1709 );
1710 assert!(
1711 json.contains(r#""player_id":"1234567890123456789""#),
1712 "standings player_id must be a quoted string, got: {json}"
1713 );
1714 assert!(
1715 json.contains(r#""user_id":"1234567890123456789""#),
1716 "round score user_id must be a quoted string, got: {json}"
1717 );
1718
1719 let back: ServerMessage = serde_json::from_str(&json).unwrap();
1720 match back {
1721 ServerMessage::RuneBoxRoundEnded {
1722 round,
1723 max_rounds,
1724 round_scores,
1725 eliminated,
1726 standings,
1727 next_round_starts_at,
1728 ..
1729 } => {
1730 assert_eq!(round, 1);
1731 assert_eq!(max_rounds, 2);
1732 assert_eq!(round_scores.len(), 2);
1733 assert_eq!(eliminated, vec![8_876_543_210_987_654_321_i64]);
1734 assert_eq!(standings[0].round_wins, 1);
1735 assert_eq!(standings[0].total_score, 41);
1736 assert!(!standings[0].eliminated);
1737 assert!(next_round_starts_at.is_none());
1738 }
1739 other => panic!("wrong variant: {other:?}"),
1740 }
1741 }
1742
1743 #[test]
1747 fn round_ended_leaks_no_words() {
1748 let json = serde_json::to_string(&round_ended_sample(None)).unwrap();
1749 assert!(
1750 !json.contains("word"),
1751 "round-end summary leaked a word field: {json}"
1752 );
1753 }
1754
1755 #[test]
1759 fn round_ended_omits_unscheduled_next_round() {
1760 let json = serde_json::to_string(&round_ended_sample(None)).unwrap();
1761 assert!(!json.contains("next_round_starts_at"), "got: {json}");
1762
1763 let at = chrono::DateTime::parse_from_rfc3339("2026-07-29T12:00:00Z")
1764 .unwrap()
1765 .with_timezone(&chrono::Utc);
1766 let json = serde_json::to_string(&round_ended_sample(Some(at))).unwrap();
1767 assert!(json.contains("next_round_starts_at"), "got: {json}");
1768 let back: ServerMessage = serde_json::from_str(&json).unwrap();
1769 match back {
1770 ServerMessage::RuneBoxRoundEnded {
1771 next_round_starts_at,
1772 ..
1773 } => assert_eq!(next_round_starts_at, Some(at)),
1774 other => panic!("wrong variant: {other:?}"),
1775 }
1776 }
1777
1778 #[test]
1779 fn a_snapshot_without_auto_rematch_reads_as_on() {
1780 let json = r#"{"lobby_id":"l","lobby_type":"channel","players":[],"games":[]}"#;
1781 let snap: LobbySnapshot = serde_json::from_str(json).unwrap();
1782 assert!(
1783 snap.auto_rematch,
1784 "an older server's snapshot must read as auto-rematch on"
1785 );
1786 }
1787
1788 #[test]
1789 fn a_snapshot_carries_auto_rematch_off() {
1790 let json = r#"{"lobby_id":"l","lobby_type":"channel","players":[],"games":[],"auto_rematch":false}"#;
1791 let snap: LobbySnapshot = serde_json::from_str(json).unwrap();
1792 assert!(!snap.auto_rematch);
1793 let out = serde_json::to_string(&snap).unwrap();
1794 assert!(out.contains(r#""auto_rematch":false"#), "{out}");
1795 }
1796
1797 #[test]
1798 fn a_snapshot_without_dictionary_reads_as_main() {
1799 let json = r#"{"lobby_id":"l","lobby_type":"channel","players":[],"games":[]}"#;
1800 let snap: LobbySnapshot = serde_json::from_str(json).unwrap();
1801 assert_eq!(snap.dictionary, "main");
1802 }
1803
1804 #[test]
1805 fn a_snapshot_always_serializes_dictionary() {
1806 let json = r#"{"lobby_id":"l","lobby_type":"channel","players":[],"games":[]}"#;
1807 let snap: LobbySnapshot = serde_json::from_str(json).unwrap();
1808 let out = serde_json::to_string(&snap).unwrap();
1809 assert!(out.contains(r#""dictionary":"main""#), "{out}");
1810 }
1811
1812 #[test]
1813 fn a_game_started_without_dictionary_reads_as_main() {
1814 let json = r#"{"type":"game_started","game_id":"g","grid":[],"players":[],"your_turn_order":0,"current_turn":"1","round":1,"max_rounds":3}"#;
1815 match serde_json::from_str::<ServerMessage>(json).unwrap() {
1816 ServerMessage::GameStarted { dictionary, .. } => assert_eq!(dictionary, "main"),
1817 other => panic!("wrong variant: {other:?}"),
1818 }
1819 }
1820}