Skip to main content

runecast_protocol/protocol/
client_messages.rs

1//! Client-to-server messages.
2//!
3//! All messages that can be sent from the frontend client to the backend server.
4//! Messages are tagged with `type` field for JSON serialization.
5//!
6//! # Categories
7//!
8//! - **Connection**: Handshake, heartbeat, acknowledgments
9//! - **Lobby**: Join, leave, create lobbies
10//! - **Game Lifecycle**: Start, end games
11//! - **Game Actions**: Submit words, pass turn, use powers
12//! - **Spectator**: Watch games, join as player
13//! - **Timer Vote**: Vote to start turn timer
14//! - **Admin**: Administrative commands
15
16use serde::{Deserialize, Serialize};
17
18use super::types::{AdventureEventKind, GameConfig, GameType, Position};
19
20/// Messages sent from client to server.
21#[derive(Debug, Clone, Serialize, Deserialize)]
22#[serde(tag = "type", rename_all = "snake_case")]
23pub enum ClientMessage {
24    // ========================================================================
25    // Connection Messages
26    // ========================================================================
27    /// Keep-alive ping. Server responds with `HeartbeatAck`.
28    ///
29    /// Should be sent every 20-30 seconds to survive proxy timeouts.
30    Heartbeat,
31
32    /// Request a full state sync from the server.
33    ///
34    /// Used to recover from state desync between client and server.
35    /// Server responds with `LobbySnapshot` and optionally `GameSnapshot`.
36    RequestSync,
37
38    /// Request debug state information for diagnosing context issues.
39    ///
40    /// Returns detailed information about the player's current state
41    /// in the WebSocket handler, lobby, and game systems.
42    DebugState,
43
44    // ========================================================================
45    // Lobby Messages
46    // ========================================================================
47    /// Join a channel-based lobby (default Discord Activity behavior).
48    ///
49    /// The lobby is automatically created if it doesn't exist.
50    JoinChannelLobby {
51        /// Discord channel ID
52        channel_id: String,
53        /// Discord guild ID (optional for DM activities)
54        #[serde(skip_serializing_if = "Option::is_none")]
55        guild_id: Option<String>,
56    },
57
58    /// Create a new custom lobby with a shareable code.
59    ///
60    /// Returns a 6-character code that others can use to join.
61    CreateCustomLobby,
62
63    /// Join an existing custom lobby by its code.
64    JoinCustomLobby {
65        /// 6-character lobby code (case-insensitive)
66        lobby_code: String,
67    },
68
69    /// Leave the current lobby.
70    ///
71    /// If in a game, this also leaves the game.
72    LeaveLobby,
73
74    // ========================================================================
75    // Game Pool Messages (waiting room for game matching)
76    // ========================================================================
77    /// Join a game pool within the lobby.
78    ///
79    /// Players must join a game pool to be matched for that game type.
80    /// Only one game pool can be joined at a time.
81    JoinGamePool {
82        /// The game type pool to join
83        game_type: GameType,
84    },
85
86    /// Leave the current game pool.
87    ///
88    /// Returns the player to the main lobby view.
89    LeaveGamePool,
90
91    // ========================================================================
92    // Game Lifecycle Messages
93    // ========================================================================
94    /// Host-only: update the live sandbox config for the current lobby.
95    /// Rejected by the server if the caller is not the host or lacks the
96    /// `sandbox_enabled` capability.
97    SetSandboxConfig { config: GameConfig },
98
99    /// Host-only: fire a random event immediately in the current custom game.
100    TriggerAdventureEvent { kind: AdventureEventKind },
101
102    /// Start a new game in the current lobby.
103    ///
104    /// By default, any player can start. Can be restricted to host only
105    /// via server configuration.
106    ///
107    /// Requirements:
108    /// - Must be in a lobby
109    /// - 1-6 connected players
110    /// - No game already in progress
111    StartGame {
112        /// Optional game configuration
113        #[serde(default, skip_serializing_if = "Option::is_none")]
114        config: Option<GameConfig>,
115    },
116
117    // ========================================================================
118    // Game Action Messages (only valid when Playing)
119    // ========================================================================
120    /// Submit a word during your turn.
121    ///
122    /// The word is derived from the positions on the grid.
123    /// Positions must form a valid path (adjacent cells, no repeats).
124    SubmitWord {
125        game_id: String,
126        /// The word being submitted (for validation)
127        word: String,
128        /// Grid positions forming the word path
129        positions: Vec<Position>,
130    },
131
132    /// Pass your turn without submitting a word.
133    ///
134    /// Awards 0 points and advances to the next player.
135    PassTurn { game_id: String },
136
137    /// Shuffle the board (costs 1 gem).
138    ///
139    /// Randomizes tile positions while keeping their properties
140    /// (letters, multipliers, gems stay on tiles, just positions change).
141    ShuffleBoard { game_id: String },
142
143    /// Enter swap mode (for UI feedback).
144    ///
145    /// Broadcasts to other players that you're considering a swap.
146    /// Triggers wobble animation on their screens.
147    EnterSwapMode { game_id: String },
148
149    /// Exit swap mode without swapping.
150    ExitSwapMode { game_id: String },
151
152    /// Swap a tile's letter (costs 3 gems).
153    ///
154    /// Changes the letter on a specific tile. The multiplier and gem
155    /// status of the tile are preserved.
156    SwapTile {
157        game_id: String,
158        row: usize,
159        col: usize,
160        /// New letter (A-Z)
161        new_letter: char,
162    },
163
164    // ========================================================================
165    // Spectator Messages
166    // ========================================================================
167    /// Join a game as a spectator.
168    ///
169    /// Spectators can view the game but cannot interact with it.
170    SpectateGame { game_id: String },
171
172    /// Join an active game.
173    ///
174    /// The player is added at the end of the turn order.
175    /// Previous rounds count as 0 points.
176    JoinGame { game_id: String },
177
178    /// Leave spectator mode and return to lobby view.
179    LeaveSpectator { game_id: String },
180
181    /// Legacy leave game message.
182    LeaveGame { game_id: String },
183
184    // ========================================================================
185    // Live Update Messages
186    // ========================================================================
187    /// Broadcast current tile selection to other players.
188    ///
189    /// Sent as the player selects tiles, allowing spectators and
190    /// other players to see the selection in real-time.
191    SelectionUpdate {
192        game_id: String,
193        positions: Vec<Position>,
194    },
195
196    // ========================================================================
197    // Timer Vote Messages
198    // ========================================================================
199    /// Initiate a vote to start a turn timer on the current player.
200    ///
201    /// Requirements:
202    /// - At least 3 players in game
203    /// - Not your turn
204    /// - No vote already in progress
205    /// - Not in cooldown
206    InitiateTimerVote { game_id: String },
207
208    /// Vote yes on an active timer vote.
209    ///
210    /// Requirements:
211    /// - Vote must be in progress
212    /// - You haven't already voted
213    /// - You didn't initiate the vote
214    /// - Not your turn
215    VoteForTimer { game_id: String },
216
217    // ========================================================================
218    // Rematch Messages
219    // ========================================================================
220    /// Trigger early rematch start for all players.
221    ///
222    /// Cancels the countdown and starts the game immediately for everyone
223    /// still in the rematch pool.
224    TriggerRematch {
225        /// The game that just ended (for validation)
226        previous_game_id: String,
227    },
228
229    /// Leave the rematch pool and return to lobby.
230    ///
231    /// The player will be removed from the rematch player list and
232    /// other players will be notified.
233    LeaveRematch {
234        /// The game to leave rematch for
235        previous_game_id: String,
236    },
237
238    /// Switch the current lobby's auto-rematch setting. Any lobby member may send
239    /// it; the server broadcasts `LobbyChange::AutoRematchChanged` in a
240    /// `LobbyDelta`, and sending the current value again changes nothing.
241    SetAutoRematch { enabled: bool },
242
243    /// Switch which dictionary the current lobby's games use. Any lobby member
244    /// may send it; the server broadcasts `LobbyChange::DictionaryChanged` in a
245    /// `LobbyDelta`, and sending the current value again changes nothing. Only
246    /// `main` is ranked.
247    SetLobbyDictionary { dictionary: String },
248
249    // ========================================================================
250    // Admin Messages
251    // ========================================================================
252    /// Request list of games (admin only).
253    AdminGetGames,
254
255    /// Delete a specific game (admin only).
256    AdminDeleteGame { game_id: String },
257
258    // ========================================================================
259    // System Messages (server-generated, not sent by clients)
260    // ========================================================================
261    /// Player disconnected from WebSocket.
262    ///
263    /// This message is generated by the backend when a WebSocket connection
264    /// closes unexpectedly. It is dispatched to handlers to trigger grace
265    /// period logic and schedule cleanup timers.
266    ///
267    /// **Not sent by clients** - synthesized by the server.
268    PlayerDisconnected {
269        /// The lobby the player was in (if any)
270        #[serde(skip_serializing_if = "Option::is_none")]
271        lobby_id: Option<String>,
272        /// The game the player was in (if any)
273        #[serde(skip_serializing_if = "Option::is_none")]
274        game_id: Option<String>,
275    },
276}
277
278impl ClientMessage {
279    /// Get the message type as a string (for logging/debugging).
280    #[must_use]
281    pub fn message_type(&self) -> &'static str {
282        match self {
283            Self::Heartbeat => "heartbeat",
284            Self::RequestSync => "request_sync",
285            Self::DebugState => "debug_state",
286            Self::JoinChannelLobby { .. } => "join_channel_lobby",
287            Self::CreateCustomLobby => "create_custom_lobby",
288            Self::JoinCustomLobby { .. } => "join_custom_lobby",
289            Self::LeaveLobby => "leave_lobby",
290            Self::JoinGamePool { .. } => "join_game_pool",
291            Self::LeaveGamePool => "leave_game_pool",
292            Self::SetSandboxConfig { .. } => "set_sandbox_config",
293            Self::TriggerAdventureEvent { .. } => "trigger_adventure_event",
294            Self::StartGame { .. } => "start_game",
295            Self::SubmitWord { .. } => "submit_word",
296            Self::PassTurn { .. } => "pass_turn",
297            Self::ShuffleBoard { .. } => "shuffle_board",
298            Self::EnterSwapMode { .. } => "enter_swap_mode",
299            Self::ExitSwapMode { .. } => "exit_swap_mode",
300            Self::SwapTile { .. } => "swap_tile",
301            Self::JoinGame { .. } => "join_game",
302            Self::SpectateGame { .. } => "spectate_game",
303            Self::LeaveSpectator { .. } => "leave_spectator",
304            Self::LeaveGame { .. } => "leave_game",
305            Self::SelectionUpdate { .. } => "selection_update",
306            Self::InitiateTimerVote { .. } => "initiate_timer_vote",
307            Self::VoteForTimer { .. } => "vote_for_timer",
308            Self::TriggerRematch { .. } => "trigger_rematch",
309            Self::LeaveRematch { .. } => "leave_rematch",
310            Self::SetAutoRematch { .. } => "set_auto_rematch",
311            Self::SetLobbyDictionary { .. } => "set_lobby_dictionary",
312            Self::AdminGetGames => "admin_get_games",
313            Self::AdminDeleteGame { .. } => "admin_delete_game",
314            Self::PlayerDisconnected { .. } => "player_disconnected",
315        }
316    }
317
318    /// Check if this message requires the sender to be in a lobby.
319    #[must_use]
320    pub fn requires_lobby(&self) -> bool {
321        matches!(
322            self,
323            Self::LeaveLobby
324                | Self::JoinGamePool { .. }
325                | Self::LeaveGamePool
326                | Self::StartGame { .. }
327                | Self::SubmitWord { .. }
328                | Self::PassTurn { .. }
329                | Self::ShuffleBoard { .. }
330                | Self::EnterSwapMode { .. }
331                | Self::ExitSwapMode { .. }
332                | Self::SwapTile { .. }
333                | Self::SpectateGame { .. }
334                | Self::JoinGame { .. }
335                | Self::LeaveSpectator { .. }
336                | Self::SelectionUpdate { .. }
337                | Self::InitiateTimerVote { .. }
338                | Self::VoteForTimer { .. }
339                | Self::TriggerRematch { .. }
340                | Self::LeaveRematch { .. }
341                | Self::SetAutoRematch { .. }
342                | Self::SetLobbyDictionary { .. }
343                | Self::AdminGetGames
344                | Self::AdminDeleteGame { .. }
345        )
346    }
347
348    /// Check if this message requires an active game.
349    #[must_use]
350    pub fn requires_active_game(&self) -> bool {
351        matches!(
352            self,
353            Self::SubmitWord { .. }
354                | Self::PassTurn { .. }
355                | Self::ShuffleBoard { .. }
356                | Self::EnterSwapMode { .. }
357                | Self::ExitSwapMode { .. }
358                | Self::SwapTile { .. }
359                | Self::SelectionUpdate { .. }
360                | Self::InitiateTimerVote { .. }
361                | Self::VoteForTimer { .. }
362        )
363    }
364
365    /// Check if this message requires it to be the sender's turn.
366    #[must_use]
367    pub fn requires_turn(&self) -> bool {
368        matches!(
369            self,
370            Self::SubmitWord { .. }
371                | Self::PassTurn { .. }
372                | Self::ShuffleBoard { .. }
373                | Self::SwapTile { .. }
374        )
375    }
376}
377
378#[cfg(test)]
379mod tests {
380    use super::*;
381
382    #[test]
383    fn test_heartbeat_serialization() {
384        let msg = ClientMessage::Heartbeat;
385        let json = serde_json::to_string(&msg).unwrap();
386        assert_eq!(json, r#"{"type":"heartbeat"}"#);
387    }
388
389    #[test]
390    fn test_join_channel_lobby_serialization() {
391        let msg = ClientMessage::JoinChannelLobby {
392            channel_id: "123456".to_string(),
393            guild_id: Some("789".to_string()),
394        };
395        let json = serde_json::to_string(&msg).unwrap();
396        assert!(json.contains(r#""type":"join_channel_lobby""#));
397        assert!(json.contains(r#""channel_id":"123456""#));
398        assert!(json.contains(r#""guild_id":"789""#));
399    }
400
401    #[test]
402    fn test_submit_word_serialization() {
403        let msg = ClientMessage::SubmitWord {
404            game_id: "game_1".to_string(),
405            word: "HELLO".to_string(),
406            positions: vec![
407                Position { row: 0, col: 0 },
408                Position { row: 0, col: 1 },
409                Position { row: 1, col: 1 },
410            ],
411        };
412        let json = serde_json::to_string(&msg).unwrap();
413        assert!(json.contains(r#""type":"submit_word""#));
414        assert!(json.contains(r#""word":"HELLO""#));
415    }
416
417    #[test]
418    fn test_deserialize_heartbeat() {
419        let json = r#"{"type":"heartbeat"}"#;
420        let msg: ClientMessage = serde_json::from_str(json).unwrap();
421        assert!(matches!(msg, ClientMessage::Heartbeat));
422    }
423
424    #[test]
425    fn test_deserialize_join_channel_lobby() {
426        let json = r#"{"type":"join_channel_lobby","channel_id":"123","guild_id":null}"#;
427        let msg: ClientMessage = serde_json::from_str(json).unwrap();
428        match msg {
429            ClientMessage::JoinChannelLobby {
430                channel_id,
431                guild_id,
432            } => {
433                assert_eq!(channel_id, "123");
434                assert!(guild_id.is_none());
435            }
436            _ => panic!("Wrong message type"),
437        }
438    }
439
440    #[test]
441    fn test_message_type() {
442        assert_eq!(ClientMessage::Heartbeat.message_type(), "heartbeat");
443        assert_eq!(
444            ClientMessage::StartGame { config: None }.message_type(),
445            "start_game"
446        );
447    }
448
449    #[test]
450    fn test_requires_lobby() {
451        assert!(!ClientMessage::Heartbeat.requires_lobby());
452        assert!(!ClientMessage::CreateCustomLobby.requires_lobby());
453        assert!(ClientMessage::StartGame { config: None }.requires_lobby());
454    }
455
456    #[test]
457    fn test_requires_turn() {
458        assert!(!ClientMessage::Heartbeat.requires_turn());
459        assert!(!ClientMessage::InitiateTimerVote {
460            game_id: "game_1".to_string()
461        }
462        .requires_turn());
463        assert!(ClientMessage::PassTurn {
464            game_id: "game_1".to_string()
465        }
466        .requires_turn());
467        assert!(ClientMessage::SubmitWord {
468            game_id: "game_1".to_string(),
469            word: "TEST".to_string(),
470            positions: vec![]
471        }
472        .requires_turn());
473    }
474
475    #[test]
476    fn test_start_game_serialization_without_config() {
477        // Test with config: None - should skip serializing the config field
478        let msg = ClientMessage::StartGame { config: None };
479        let json = serde_json::to_string(&msg).unwrap();
480        assert_eq!(json, r#"{"type":"start_game"}"#);
481    }
482
483    #[test]
484    fn test_start_game_serialization_with_default_config() {
485        // Test with default config (regenerate_board_each_round: false)
486        let msg = ClientMessage::StartGame {
487            config: Some(GameConfig::default()),
488        };
489        let json = serde_json::to_string(&msg).unwrap();
490        assert!(json.contains(r#""type":"start_game""#));
491        assert!(json.contains(r#""regenerate_board_each_round":false"#));
492        assert!(json.contains(r#""grid_size":5"#));
493    }
494
495    #[test]
496    fn test_start_game_serialization_with_custom_config() {
497        // Test with custom config (regenerate_board_each_round: true)
498        let msg = ClientMessage::StartGame {
499            config: Some(GameConfig {
500                regenerate_board_each_round: true,
501                grid_size: 5,
502                adventure_level: None,
503                level_targets: None,
504                num_rounds: None,
505                bots: Vec::new(),
506                custom: None,
507                events: None,
508            }),
509        };
510        let json = serde_json::to_string(&msg).unwrap();
511        assert!(json.contains(r#""type":"start_game""#));
512        assert!(json.contains(r#""regenerate_board_each_round":true"#));
513    }
514
515    #[test]
516    fn test_start_game_deserialization_without_config() {
517        // Test deserializing without config field - should default to None
518        let json = r#"{"type":"start_game"}"#;
519        let msg: ClientMessage = serde_json::from_str(json).unwrap();
520        match msg {
521            ClientMessage::StartGame { config } => {
522                assert!(config.is_none());
523            }
524            _ => panic!("Wrong message type"),
525        }
526    }
527
528    #[test]
529    fn test_start_game_deserialization_with_config() {
530        // Test deserializing with config field
531        let json = r#"{"type":"start_game","config":{"regenerate_board_each_round":true}}"#;
532        let msg: ClientMessage = serde_json::from_str(json).unwrap();
533        match msg {
534            ClientMessage::StartGame { config } => {
535                assert!(config.is_some());
536                assert!(config.unwrap().regenerate_board_each_round);
537            }
538            _ => panic!("Wrong message type"),
539        }
540    }
541
542    #[test]
543    fn set_sandbox_config_round_trips() {
544        let msg = ClientMessage::SetSandboxConfig {
545            config: GameConfig::default(),
546        };
547        let json = serde_json::to_string(&msg).unwrap();
548        assert!(json.contains(r#""type":"set_sandbox_config""#));
549        let back: ClientMessage = serde_json::from_str(&json).unwrap();
550        assert!(matches!(back, ClientMessage::SetSandboxConfig { .. }));
551    }
552
553    #[test]
554    fn trigger_adventure_event_round_trips() {
555        let msg = ClientMessage::TriggerAdventureEvent {
556            kind: AdventureEventKind::Snake,
557        };
558        let json = serde_json::to_string(&msg).unwrap();
559        assert!(json.contains(r#""type":"trigger_adventure_event""#));
560        assert!(json.contains(r#""kind":"snake""#));
561        let back: ClientMessage = serde_json::from_str(&json).unwrap();
562        assert!(matches!(
563            back,
564            ClientMessage::TriggerAdventureEvent {
565                kind: AdventureEventKind::Snake
566            }
567        ));
568    }
569
570    #[test]
571    fn set_auto_rematch_parses_and_needs_a_lobby() {
572        let msg: ClientMessage =
573            serde_json::from_str(r#"{"type":"set_auto_rematch","enabled":false}"#).unwrap();
574        assert!(matches!(
575            msg,
576            ClientMessage::SetAutoRematch { enabled: false }
577        ));
578        assert_eq!(msg.message_type(), "set_auto_rematch");
579        assert!(msg.requires_lobby());
580    }
581
582    #[test]
583    fn set_lobby_dictionary_round_trips() {
584        let json = r#"{"type":"set_lobby_dictionary","dictionary":"urban"}"#;
585        let msg: ClientMessage = serde_json::from_str(json).unwrap();
586        assert!(matches!(
587            &msg,
588            ClientMessage::SetLobbyDictionary { dictionary } if dictionary == "urban"
589        ));
590        assert_eq!(msg.message_type(), "set_lobby_dictionary");
591        assert!(msg.requires_lobby());
592        assert_eq!(serde_json::to_string(&msg).unwrap(), json);
593    }
594}