//! Server connection and the websocket protocol loop. //! //! A com keeps a *single* connection to `/ws/com`. Every game it is assigned is //! multiplexed over that socket in game-tagged envelopes, so the com never opens //! a per-game `/ws`. The per-game protocol loop ([`play_game`]) is otherwise the //! same one a normal `/ws` client speaks — it just reads and writes its messages //! through in-process channels instead of owning a socket. use std::collections::HashMap; use std::fmt; use std::time::{Duration, Instant}; use futures_util::{SinkExt, StreamExt}; use serde_json::{json, Value}; use tokio::sync::mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender}; use tokio_tungstenite::tungstenite::Message as WsMessage; use stellar::{GameEngine, StarConfig, StarGambitConfig}; use crate::{legal_actions, Com, Game}; /// How the game ended, as reported by the server's RESULT message. #[derive(Debug, Clone)] pub struct Outcome { /// Winner id (`"A"`/`"B"` slot marker or a player id), or empty on draw. pub winner: String, /// Game-end SGN, e.g. `"0=FF"` (player 0 forfeited) or `"0==1"` (draw). pub reason: String, } /// Anything that can go wrong while joining or playing a game. #[derive(Debug)] pub enum ComError { Ws(tokio_tungstenite::tungstenite::Error), Json(serde_json::Error), Runtime(std::io::Error), /// The websocket closed before the game produced a result. ConnectionClosed, /// The com failed to make progress: it returned the same no-progress /// output (all-illegal or empty) three times in a row, or made no progress /// at all for 20 consecutive calls. Treated as a crashed com; the game is /// abandoned. ComCrashed { output: Vec }, /// The server sent something we couldn't make sense of. Protocol(String), /// Connected to a game that was already full; the com is a spectator. Spectator, } impl fmt::Display for ComError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { ComError::Ws(e) => write!(f, "websocket error: {e}"), ComError::Json(e) => write!(f, "json error: {e}"), ComError::Runtime(e) => write!(f, "runtime error: {e}"), ComError::ConnectionClosed => write!(f, "connection closed before the game ended"), ComError::ComCrashed { output } => { write!(f, "com crashed: repeated no-progress output {output:?}") } ComError::Protocol(s) => write!(f, "protocol error: {s}"), ComError::Spectator => write!(f, "joined as spectator (game already full)"), } } } impl std::error::Error for ComError {} impl From for ComError { fn from(e: tokio_tungstenite::tungstenite::Error) -> Self { ComError::Ws(e) } } impl From for ComError { fn from(e: serde_json::Error) -> Self { ComError::Json(e) } } /// Connect to `server` as a registered com using `com_token`. /// /// Metalith pushes game assignments and *all* game traffic over a single /// persistent WebSocket (`/ws/com`). `factory` is called once per assigned game /// to build that game's [`Com`]. The function blocks indefinitely, reconnecting /// after disconnections with a 5-second back-off. Max-concurrent enforcement is /// handled server-side; no semaphore is needed here. /// /// `server` is an HTTP base URL such as `"http://localhost"`; the WebSocket /// base is derived from it (`http`→`ws`, `https`→`wss`). pub fn run_as_com(server: &str, com_token: &str, factory: F) -> Result<(), ComError> where F: Fn() -> B + 'static, B: Com + 'static, { let rt = tokio::runtime::Builder::new_current_thread() .enable_all() .build() .map_err(ComError::Runtime)?; let local = tokio::task::LocalSet::new(); local.block_on(&rt, async move { let ws_base = ws_base(server); let com_ws_url = format!( "{}/ws/com?token={}", ws_base, urlencoding::encode(com_token) ); eprintln!("[sg-sdk] connecting as registered com to {ws_base}"); loop { match tokio_tungstenite::connect_async(&com_ws_url).await { Err(e) => { eprintln!("[sg-sdk] com WS connect error: {e}; retrying in 5s"); } Ok((ws, _)) => { eprintln!("[sg-sdk] com WS connected"); run_session(ws, &factory).await; eprintln!("[sg-sdk] com WS disconnected; retrying in 5s"); } } tokio::time::sleep(Duration::from_secs(5)).await; } }) } /// Derive the WebSocket base URL from an HTTP base (`http`→`ws`, /// `https`→`wss`; a bare host defaults to `ws`). fn ws_base(server: &str) -> String { let http = server.trim_end_matches('/'); if let Some(rest) = http.strip_prefix("https://") { format!("wss://{rest}") } else if let Some(rest) = http.strip_prefix("http://") { format!("ws://{rest}") } else { format!("ws://{http}") } } /// Drive one com socket until it disconnects. /// /// Demultiplexes inbound envelopes to per-game tasks and funnels every game's /// outbound frames back through one writer task (which also keeps the socket /// alive with periodic pings). Returns when the socket closes; the caller /// reconnects. async fn run_session(ws: WsStream, factory: &F) where F: Fn() -> B, B: Com + 'static, { let (mut write, mut read) = ws.split(); // Single writer: every game task sends already-framed messages here. let (out_tx, mut out_rx) = unbounded_channel::(); let writer = tokio::task::spawn_local(async move { let mut ping = tokio::time::interval(Duration::from_secs(5)); loop { tokio::select! { msg = out_rx.recv() => match msg { Some(m) => { if write.send(m).await.is_err() { break; } } None => break, }, _ = ping.tick() => { if write.send(WsMessage::Ping(Vec::new())).await.is_err() { break; } } } } }); // game_id -> inbound channel feeding that game's play loop. let mut games: HashMap> = HashMap::new(); while let Some(frame) = read.next().await { let text = match frame { Ok(WsMessage::Text(t)) => t, Ok(WsMessage::Close(_)) | Err(_) => break, Ok(_) => continue, // ping/pong/binary }; let Ok(value) = serde_json::from_str::(&text) else { continue; }; match value.get("T").and_then(|t| t.as_str()) { // Per-game message. The first one for an unseen game spins up its // play loop (the inner message is then delivered to it). Some("g") => { let data = value.get("D"); let game_id = data .and_then(|d| d.get("g")) .and_then(|g| g.as_str()) .map(str::to_string); let inner = data.and_then(|d| d.get("m")); let (Some(game_id), Some(inner)) = (game_id, inner) else { continue; }; if !games.contains_key(&game_id) { let (in_tx, in_rx) = unbounded_channel::(); games.insert(game_id.clone(), in_tx); let com = factory(); let out = out_tx.clone(); let gid = game_id.clone(); tokio::task::spawn_local(async move { match play_game(&gid, in_rx, out, com).await { Ok(o) => eprintln!( "[sg-sdk] {gid} over: winner={} reason={}", o.winner, o.reason ), Err(e) => eprintln!("[sg-sdk] {gid} error: {e}"), } }); } if let Some(tx) = games.get(&game_id) { let _ = tx.send(inner.to_string()); } } // The game's connection is finished: drop its inbound channel so // the play loop winds down. Some("c_end") => { if let Some(game_id) = value .get("D") .and_then(|d| d.get("g")) .and_then(|g| g.as_str()) { games.remove(game_id); } } _ => {} } } // Socket gone: drop every game's inbound channel so its loop ends, then // stop the writer. games.clear(); writer.abort(); } type WsStream = tokio_tungstenite::WebSocketStream>; /// Play a single game to completion over the multiplexed socket. /// /// `inbound` yields the inner `/ws` messages (JSON text) the server addressed to /// this game; `out` accepts game-tagged envelopes destined for the socket. The /// protocol is identical to a direct `/ws` client — only the transport differs. async fn play_game( game_id: &str, mut inbound: UnboundedReceiver, out: UnboundedSender, mut com: impl Com, ) -> Result { send_game(&out, game_id, json!({"T": "j", "D": {"s": 0}}))?; let mut me: i32 = i32::MIN; // unknown until YOU_ARE let mut engine: Option = None; let mut next_ack: i64 = 1; let start = Instant::now(); while let Some(text) = inbound.recv().await { let msg: Value = serde_json::from_str(&text)?; let kind = msg.get("T").and_then(|t| t.as_str()).unwrap_or(""); let data = msg.get("D").cloned().unwrap_or_else(|| json!({})); match kind { // YOU_ARE: our slot (0/1 = player, negative = spectator). "u" => { me = data.get("p").and_then(|p| p.as_i64()).unwrap_or(i32::MIN as i64) as i32; if me < 0 { return Err(ComError::Spectator); } } // LOBBY: accept the match whenever we're in the lobby. "lb" => { send_game(&out, game_id, json!({"T": "ac", "D": {}}))?; } // HISTORY: (re)build local state from config + full SGN. "h" => { engine = Some(build_engine(&data)?); } // ACTION: an opponent action (our own are never echoed). "a" => { if let (Some(eng), Some(action)) = (engine.as_mut(), data.get("a").and_then(|a| a.as_str())) { if action.contains('=') { // Opponent claimed a game end. Ack via the step-based // acknowledge message at the exact step they used — the // server matches on step to identify the ack, not a // duplicate action. if let Some(step) = data.get("s").and_then(|s| s.as_i64()) { send_game(&out, game_id, json!({"T": "ack", "D": {"s": step}}))?; } // Apply locally for consistency; errors are fine — the // game is terminal regardless. if let Ok(next) = eng.execute(action) { *eng = next; } } else { match eng.execute(action) { Ok(next) => { *eng = next; } // Drifted out of sync — ask for fresh history. Err(_) => { send_game(&out, game_id, json!({"T": "j", "D": {"s": 0}}))?; } } } } } // RESULT: game over. "r" => { return Ok(Outcome { winner: data.get("w").and_then(|w| w.as_str()).unwrap_or("").to_string(), reason: data.get("r").and_then(|r| r.as_str()).unwrap_or("").to_string(), }); } _ => {} } // After processing whatever just happened, play out our turn if it // has become ours. if me == 0 || me == 1 { if let Some(eng) = engine.as_mut() { take_turn(&out, game_id, &mut com, eng, me, &mut next_ack, start)?; } } } // Inbound closed (c_end or socket drop) without a RESULT. Err(ComError::ConnectionClosed) } /// Drive the com for as long as it is our turn. /// /// Each [`Com::act`] call may return several actions (e.g. a whole turn). Every /// action is validated against the engine *before* it is sent: legal ones are /// transmitted (one protocol message each, so the server's per-step accounting /// stays in lockstep) and applied locally; illegal ones are skipped with a /// warning rather than aborting the game. /// /// A call that makes no progress (all-illegal or empty) is retried — `act` is /// called again with the same state. The com is considered crashed (returning /// [`ComError::ComCrashed`] so the caller disconnects from this game) if it /// returns the *same* no-progress output three times in a row, or makes no /// progress at all for 20 consecutive calls. fn take_turn( out: &UnboundedSender, game_id: &str, com: &mut impl Com, engine: &mut GameEngine, me: i32, next_ack: &mut i64, start: Instant, ) -> Result<(), ComError> { // The last no-progress output and how many times running it has repeated, // plus a total count of consecutive no-progress calls (whatever the output). let mut stalled_on: Option> = None; let mut stall_count: u32 = 0; let mut no_progress_count: u32 = 0; while engine.result.is_none() && engine.whos_turn == me { if legal_actions(engine).is_empty() { break; } let response = { let game = Game { engine, me }; com.act(&game) }; let mut progressed = false; for token in response.iter().flat_map(|s| s.split_whitespace()) { // The engine needs a timestamp to validate END; the server wants a // bare "END" (it stamps the real time itself). Elapsed millis are // fine locally — the engine uses the time only for clocks // (server-authoritative) and never in the position hash. let local = if token == "END" { format!("END:{}", start.elapsed().as_millis()) } else { token.to_string() }; // Validate locally before sending. Illegal actions are skipped, not // fatal, so a buggy com degrades gracefully instead of crashing. let next = match engine.execute(&local) { Ok(next) => next, Err(e) => { eprintln!("[sg-sdk] skipping illegal action {token:?}: {e:?}"); continue; } }; // Accepted — send the bare token, then commit the applied state so // the step counter stays aligned with the server. let step = engine.game_log.len() as i64 + 1; let ack = *next_ack; *next_ack += 1; send_game(out, game_id, json!({"T": "a", "D": {"a": token, "s": step, "i": ack}}))?; *engine = next; progressed = true; // Stop feeding tokens once the turn (or game) is over. if engine.result.is_some() || engine.whos_turn != me { break; } } if progressed { // Real progress resets the stall tracking. stalled_on = None; stall_count = 0; no_progress_count = 0; continue; } // No legal action came out of this call. The com is considered crashed // if it either repeats the *same* no-progress output 3 times in a row, // or makes no progress at all for 20 consecutive calls (e.g. varying // illegal junk that never trips the same-output check). no_progress_count += 1; if stalled_on.as_ref() == Some(&response) { stall_count += 1; } else { stalled_on = Some(response.clone()); stall_count = 1; } eprintln!( "[sg-sdk] com produced no legal action \ (same {stall_count}/3, total {no_progress_count}/20): {response:?}" ); if stall_count >= 3 || no_progress_count >= 20 { return Err(ComError::ComCrashed { output: response }); } // Otherwise loop and call `act` again with the same game state. } Ok(()) } /// Wrap an inner `/ws` message in a game-tagged envelope and queue it for the /// shared socket writer. fn send_game( out: &UnboundedSender, game_id: &str, inner: Value, ) -> Result<(), ComError> { let envelope = json!({"T": "g", "D": {"g": game_id, "m": inner}}); out.send(WsMessage::Text(envelope.to_string())) .map_err(|_| ComError::ConnectionClosed) } /// Build a fresh [`GameEngine`] from a HISTORY payload and replay its SGN. fn build_engine(data: &Value) -> Result { let config = data .get("config") .ok_or_else(|| ComError::Protocol("history missing config".into()))?; let size = config .get("size") .and_then(|s| s.as_i64()) .ok_or_else(|| ComError::Protocol("config missing size".into()))? as i32; let counts = match config.get("ships") { Some(ships) => vec![ ships.get("fighter").and_then(|x| x.as_i64()).unwrap_or(3) as i32, ships.get("cruiser").and_then(|x| x.as_i64()).unwrap_or(2) as i32, ships.get("dreadnought").and_then(|x| x.as_i64()).unwrap_or(1) as i32, 0, ], None => vec![3, 2, 1, 0], }; let cfg = StarGambitConfig::from_star_config(&StarConfig::with_counts(size, counts)); let mut engine = GameEngine::new_game(cfg); if let Some(sgn) = data.get("g").and_then(|g| g.as_str()) { if !sgn.trim().is_empty() { engine = engine .execute(sgn) .map_err(|e| ComError::Protocol(format!("replaying history failed: {e:?}")))?; } } Ok(engine) }