//! 裁判计时规则与选手端快照跟随。所有时间来自调用方的单调时钟。 //! UDP 会话锁定到首次收到的来源;掉线不自动换裁判,需显式重新接收。 use crate::snapshot::{resolve_outcomes, MatchOutcome, TeamHealthDto}; use protocol::MatchState; use serde::{Deserialize, Serialize}; use std::net::Ipv4Addr; pub const SYNC_LEASE_MS: u64 = 1500; #[derive(Debug, Clone, Deserialize)] #[serde(tag = "type", rename_all = "camelCase")] pub enum MatchAction { Prepare, SkipPreparation, Countdown { seconds: u32, }, PausePlayer { team: u8, reason: String, approved: bool, }, PauseOfficial { reason: String, }, Resume, End, Reset, } #[derive(Debug, Clone, Serialize)] #[serde(rename_all = "camelCase")] pub struct MatchView { pub phase: &'static str, pub resume_phase: &'static str, pub pause_kind: Option<&'static str>, pub applicant: Option, pub reason: String, pub remaining_ms: u32, pub elapsed_ms: u32, pub pause_remaining_ms: Option, pub pause_elapsed_ms: u32, pub connected: bool, /// 前端最多可从这份快照继续推算多久;超过后冻结并显示断连。 pub fresh_for_ms: u64, pub source: Option, pub sync_error: Option, } pub struct MatchClock { authority: bool, local_session: u64, state: MatchState, at: u64, source: Option<(Ipv4Addr, u64)>, received_at: Option, result: Option, } fn idle(session: u64) -> MatchState { MatchState { session: session.max(1), sequence: 0, phase: 0, resume_phase: 0, pause_kind: 0, applicant: 255, remaining_ms: 0, elapsed_ms: 0, pause_remaining_ms: u32::MAX, pause_elapsed_ms: 0, reason: String::new(), } } fn phase(n: u8) -> &'static str { [ "idle", "preparation", "ready", "countdown", "running", "paused", "finished", ] .get(n as usize) .copied() .unwrap_or("idle") } fn clear_pause(s: &mut MatchState) { s.resume_phase = 0; s.pause_kind = 0; s.applicant = 255; s.reason.clear(); s.pause_remaining_ms = u32::MAX; s.pause_elapsed_ms = 0; } fn project(s: &mut MatchState, delta: u64) { let delta = delta.min(u32::MAX as u64) as u32; if matches!(s.phase, 1 | 3 | 4) { let spent = delta.min(s.remaining_ms); s.remaining_ms -= spent; if s.phase == 4 { s.elapsed_ms = (s.elapsed_ms + spent).min(180_000); } } else if s.phase == 5 { s.pause_elapsed_ms = s.pause_elapsed_ms.saturating_add(delta); if s.pause_kind == 1 { s.pause_remaining_ms = s.pause_remaining_ms.saturating_sub(delta); } } } impl MatchClock { pub fn new(authority: bool, session: u64, now: u64) -> Self { Self { authority, local_session: session.max(1), state: idle(session), at: now, source: None, received_at: None, result: None, } } pub fn set_authority(&mut self, authority: bool, now: u64) { if self.authority != authority { self.authority = authority; // 新的裁判会话,不能让旧的延迟包恢复上一局。 self.local_session = self.local_session.wrapping_add(1).max(1); self.state = idle(self.local_session); self.at = now; self.source = None; self.received_at = None; self.result = None; } } fn advance(&mut self, now: u64) { let delta = now.saturating_sub(self.at); self.at = now; if self.state.phase == 3 && delta >= self.state.remaining_ms as u64 { let rest = delta - self.state.remaining_ms as u64; self.state.phase = 4; self.state.remaining_ms = 180_000; self.state.elapsed_ms = 0; project(&mut self.state, rest); } else { project(&mut self.state, delta); } if self.state.remaining_ms == 0 { if self.state.phase == 1 { self.state.phase = 2; } else if self.state.phase == 4 { self.state.phase = 6; } } } pub fn action(&mut self, action: MatchAction, now: u64) -> Result<(), String> { if !self.authority { return Err("只有裁判端可以控制比赛计时".into()); } self.advance(now); match action { MatchAction::Prepare if matches!(self.state.phase, 0 | 6) && self.result.is_none() => { let seq = self.state.sequence; self.state = idle(self.local_session); self.state.sequence = seq; self.state.phase = 1; self.state.remaining_ms = 180_000; } MatchAction::SkipPreparation if matches!(self.state.phase, 1 | 2) => { self.state.phase = 2; self.state.remaining_ms = 0; } MatchAction::Countdown { seconds } if self.state.phase == 2 && (1..=60).contains(&seconds) => { self.state.phase = 3; self.state.remaining_ms = seconds * 1000; } MatchAction::PausePlayer { team, reason, approved, } => { if !approved { return Err("选手技术暂停须经主裁判批准".into()); } if team > 1 { return Err("请选择申请暂停的队伍".into()); } self.pause(1, team, reason)?; } MatchAction::PauseOfficial { reason } => self.pause(2, 255, reason)?, MatchAction::Resume if self.state.phase == 5 => { self.state.phase = self.state.resume_phase; clear_pause(&mut self.state); } MatchAction::End if (1..=5).contains(&self.state.phase) => { self.state.phase = 6; clear_pause(&mut self.state); } MatchAction::Reset if matches!(self.state.phase, 0 | 6) => { let seq = self.state.sequence; self.state = idle(self.local_session); self.state.sequence = seq; self.result = None; } _ => { return Err( "当前比赛阶段不允许此操作;准备结束后才能开始开赛倒计时(1–60 秒)".into(), ) } } self.state.sequence = self.state.sequence.saturating_add(1); Ok(()) } /// 装甲板复位期间保持结束状态,先停止扣血;确认满血后再 Reset 到未开始。 pub fn begin_reset(&mut self, has_outcome: bool, now: u64) -> Result { if !self.authority { return Err("只有裁判端可以重置比赛".into()); } self.advance(now); if !matches!(self.state.phase, 0 | 6) && !has_outcome { return Err("比赛尚未结束,请先结束本局再重置".into()); } self.state.phase = 6; clear_pause(&mut self.state); self.state.sequence = self.state.sequence.saturating_add(1); Ok(self.state.clone()) } /// 首次归零结束正在进行的对局;后续上报不得重新结算。 pub fn finish_on_health(&mut self, hp: [Option; 2], now: u64) -> bool { if !self.authority || self.result.is_some() { return false; } self.advance(now); let playing = self.state.phase == 4 || (self.state.phase == 5 && self.state.resume_phase == 4); if !playing || !hp.contains(&Some(0)) { return false; } let outcomes = match hp { [Some(0), Some(0)] => [3, 3], [Some(0), Some(hp)] if hp > 0 => [2, 1], [Some(hp), Some(0)] if hp > 0 => [1, 2], [Some(0), _] => [2, 0], _ => [0, 2], }; self.state.phase = 6; clear_pause(&mut self.state); self.state.sequence = self.state.sequence.saturating_add(1); self.result = Some(protocol::MatchResult { session: self.state.session, sequence: self.state.sequence, result_id: self.state.sequence, remaining_ms: self.state.remaining_ms, elapsed_ms: self.state.elapsed_ms, outcomes, }); true } pub fn result_packet(&self) -> Option { if !self.authority || self.state.phase != 6 { return None; } self.result.map(|result| protocol::MatchResult { sequence: self.state.sequence, ..result }) } /// 终局只投影锁定结论,不篡改装甲板的真实血量。正式选手端以裁判结论为准。 pub fn apply_outcomes(&self, health: &mut [TeamHealthDto]) { for entry in health.iter_mut() { entry.outcome = None; } if let Some(result) = self.result { for entry in health { entry.outcome = match result.outcomes.get(usize::from(entry.team)) { Some(1) => Some(MatchOutcome::Victory), Some(2) => Some(MatchOutcome::Defeat), Some(3) => Some(MatchOutcome::Draw), _ => None, }; } } else if (self.authority && self.state.phase != 6) || (!self.authority && self.source.is_none()) { resolve_outcomes(health); } } pub fn receive_result( &mut self, result: protocol::MatchResult, ip: Ipv4Addr, now: u64, ) -> bool { if self.authority || !result.valid() { return false; } if let Some(previous) = self.result { if previous.session == result.session && (result.result_id < previous.result_id || (result.result_id == previous.result_id && (result.outcomes != previous.outcomes || result.remaining_ms != previous.remaining_ms || result.elapsed_ms != previous.elapsed_ms))) { return false; } } let same_snapshot = self.source == Some((ip, result.session)) && self.state.sequence == result.sequence && self.state.phase == 6 && self.state.remaining_ms == result.remaining_ms && self.state.elapsed_ms == result.elapsed_ms; if !same_snapshot { let mut state = idle(result.session); state.sequence = result.sequence; state.phase = 6; state.remaining_ms = result.remaining_ms; state.elapsed_ms = result.elapsed_ms; if !self.receive(state, ip, now) { return false; } } let changed = self.result != Some(result); self.result = Some(result); changed } fn pause(&mut self, kind: u8, team: u8, reason: String) -> Result<(), String> { if !(1..=4).contains(&self.state.phase) { return Err("当前阶段不能申请技术暂停".into()); } let reason = reason.trim(); if reason.is_empty() || reason.len() > 192 || reason.chars().any(char::is_control) { return Err("请填写暂停原因(最多 192 个 UTF-8 字节,不含换行)".into()); } self.state.resume_phase = self.state.phase; self.state.phase = 5; self.state.pause_kind = kind; self.state.applicant = team; self.state.reason = reason.into(); self.state.pause_elapsed_ms = 0; self.state.pause_remaining_ms = if kind == 1 { 300_000 } else { u32::MAX }; Ok(()) } pub fn broadcast(&mut self, now: u64) -> Option { if !self.authority { return None; } self.advance(now); self.state.sequence = self.state.sequence.saturating_add(1); Some(self.state.clone()) } pub fn receive(&mut self, packet: MatchState, ip: Ipv4Addr, now: u64) -> bool { if self.authority || !packet.valid() { return false; } if let Some(source) = self.source { if source != (ip, packet.session) || packet.sequence <= self.state.sequence { return false; } } self.source = Some((ip, packet.session)); if packet.phase != 6 { self.result = None; } self.state = packet; self.received_at = Some(now); true } /// 明确的人为操作才允许切换裁判会话(例如裁判应用重启)。 pub fn release_source(&mut self) -> Result<(), String> { if self.authority { return Err("裁判端不接收其他裁判的计时".into()); } self.source = None; self.received_at = None; self.state = idle(self.local_session); self.result = None; Ok(()) } pub fn view(&mut self, now: u64) -> MatchView { if self.authority { self.advance(now); } let age = self.received_at.map(|at| now.saturating_sub(at)); let connected = self.authority || age.is_some_and(|age| age < SYNC_LEASE_MS); let mut s = self.state.clone(); if !self.authority { project(&mut s, age.unwrap_or(0).min(SYNC_LEASE_MS)); } MatchView { phase: phase(s.phase), resume_phase: phase(s.resume_phase), pause_kind: match s.pause_kind { 1 => Some("player"), 2 => Some("official"), _ => None, }, applicant: (s.applicant <= 1).then_some(s.applicant), reason: s.reason, remaining_ms: s.remaining_ms, elapsed_ms: s.elapsed_ms, pause_remaining_ms: (s.pause_remaining_ms != u32::MAX).then_some(s.pause_remaining_ms), pause_elapsed_ms: s.pause_elapsed_ms, connected, fresh_for_ms: if self.authority { SYNC_LEASE_MS } else { SYNC_LEASE_MS.saturating_sub(age.unwrap_or(SYNC_LEASE_MS)) }, source: self.source.map(|(ip, _)| ip.to_string()), sync_error: None, } } } #[cfg(test)] mod tests { use super::*; fn ready(c: &mut MatchClock) { c.action(MatchAction::Prepare, 0).unwrap(); assert_eq!(c.view(180_000).phase, "ready"); } fn running(c: &mut MatchClock) { c.action(MatchAction::Prepare, 0).unwrap(); c.action(MatchAction::SkipPreparation, 100).unwrap(); c.action(MatchAction::Countdown { seconds: 1 }, 100) .unwrap(); assert_eq!(c.view(1100).phase, "running"); } #[test] fn first_knockout_stops_time_and_locks_result_through_late_health_and_reset_attempts() { let mut c = MatchClock::new(true, 44, 0); assert!(!c.finish_on_health([Some(0), Some(10)], 0)); running(&mut c); assert!(c.finish_on_health([Some(0), Some(10)], 2100)); let result = c.result_packet().unwrap(); assert_eq!(result.outcomes, [2, 1]); assert_eq!( (c.view(10_000).phase, c.view(10_000).elapsed_ms), ("finished", 1000) ); assert!(!c.finish_on_health([Some(0), Some(0)], 10_000)); assert!(!c.finish_on_health([Some(100), Some(0)], 10_000)); let names = ["红队".into(), "蓝队".into()]; let mut health = [ TeamHealthDto::present(0, Some(1), [0; 4], 25, &names), TeamHealthDto::present(1, Some(2), [0; 4], 25, &names), ]; c.apply_outcomes(&mut health); assert_eq!(health[0].outcome, Some(MatchOutcome::Defeat)); assert_eq!(health[1].outcome, Some(MatchOutcome::Victory)); assert_eq!(health[1].hp, Some(0), "结论锁定不篡改真实上报"); assert!(c.action(MatchAction::Prepare, 10_000).is_err()); c.begin_reset(true, 10_000).unwrap(); assert_eq!(c.result_packet().unwrap().result_id, result.result_id); c.action(MatchAction::Reset, 10_000).unwrap(); assert!(c.result_packet().is_none()); c.action(MatchAction::Prepare, 10_000).unwrap(); } #[test] fn knockout_handles_paused_play_draw_and_missing_opponent_without_inventing_a_win() { for (hp, expected) in [ ([Some(0), Some(0)], [3, 3]), ([Some(0), None], [2, 0]), ([None, Some(0)], [0, 2]), ] { let mut c = MatchClock::new(true, 44, 0); running(&mut c); c.action( MatchAction::PauseOfficial { reason: "检查".into(), }, 2100, ) .unwrap(); assert!(c.finish_on_health(hp, 2200)); assert_eq!(c.result_packet().unwrap().outcomes, expected); } assert!(!MatchClock::new(false, 2, 0).finish_on_health([Some(0), Some(10)], 0)); } #[test] fn result_sync_is_self_contained_order_independent_and_cannot_revive_after_reset() { let mut referee = MatchClock::new(true, 44, 0); running(&mut referee); referee.finish_on_health([Some(10), Some(0)], 2100); let state = referee.broadcast(2100).unwrap(); let result = referee.result_packet().unwrap(); for result_first in [false, true] { let mut player = MatchClock::new(false, 2, 0); if result_first { assert!(player.receive_result(result, Ipv4Addr::LOCALHOST, 0)); assert!(!player.receive(state.clone(), Ipv4Addr::LOCALHOST, 1)); } else { assert!(player.receive(state.clone(), Ipv4Addr::LOCALHOST, 0)); assert!(player.receive_result(result, Ipv4Addr::LOCALHOST, 1)); } assert_eq!(player.view(1).phase, "finished"); assert!(!player.receive_result(result, Ipv4Addr::LOCALHOST, 1400)); assert!(!player.view(1500).connected, "重复回执不能续约"); assert!(!player.receive_result( protocol::MatchResult { outcomes: [2, 1], ..result }, Ipv4Addr::LOCALHOST, 1501 )); assert!(!player.receive_result(result, Ipv4Addr::new(1, 2, 3, 4), 1501)); referee.action(MatchAction::Reset, 2200).unwrap(); let reset = referee.broadcast(2200).unwrap(); assert!(player.receive(reset, Ipv4Addr::LOCALHOST, 1600)); assert!(!player.receive_result(result, Ipv4Addr::LOCALHOST, 1601)); assert!(player.result.is_none()); } } #[test] fn preparation_waits_for_referee_then_countdown_carries_excess_time() { let mut c = MatchClock::new(true, 1, 0); ready(&mut c); assert_eq!(c.view(240_000).phase, "ready"); assert!(c .action(MatchAction::Countdown { seconds: 0 }, 240_000) .is_err()); c.action(MatchAction::Countdown { seconds: 5 }, 240_000) .unwrap(); let v = c.view(247_450); assert_eq!( (v.phase, v.remaining_ms, v.elapsed_ms), ("running", 177_550, 2450) ); let v = c.view(500_000); assert_eq!((v.phase, v.elapsed_ms), ("finished", 180_000)); } #[test] fn skip_preparation_waits_for_confirmation_and_syncs_without_changing_session() { let mut c = MatchClock::new(true, 44, 0); assert!(c.action(MatchAction::SkipPreparation, 0).is_err()); c.action(MatchAction::Prepare, 0).unwrap(); c.action(MatchAction::SkipPreparation, 1000).unwrap(); let packet = c.broadcast(1000).unwrap(); assert_eq!( (packet.phase, packet.remaining_ms, packet.elapsed_ms), (2, 0, 0) ); let mut follower = MatchClock::new(false, 2, 0); assert!(follower.receive(packet.clone(), Ipv4Addr::LOCALHOST, 1000)); assert_eq!(follower.view(1000).phase, "ready"); assert!(follower.action(MatchAction::SkipPreparation, 1000).is_err()); assert_eq!(c.view(200_000).phase, "ready"); // 重复操作、准备刚好自然结束时均保持待开赛。 c.action(MatchAction::SkipPreparation, 200_000).unwrap(); c.action(MatchAction::Countdown { seconds: 5 }, 200_000) .unwrap(); assert!(c.action(MatchAction::SkipPreparation, 201_000).is_err()); assert_eq!(c.view(205_000).phase, "running"); assert!(c.action(MatchAction::SkipPreparation, 205_000).is_err()); let later = c.broadcast(205_000).unwrap(); assert_eq!(later.session, packet.session); assert!(later.sequence > packet.sequence); assert!(follower.receive(later, Ipv4Addr::LOCALHOST, 205_000)); assert!(!follower.receive(packet, Ipv4Addr::LOCALHOST, 205_000)); assert_eq!(follower.view(205_000).phase, "running"); } #[test] fn reset_after_a_verdict_stops_the_match_then_clears_all_round_state() { let mut c = MatchClock::new(true, 44, 0); ready(&mut c); c.action(MatchAction::Countdown { seconds: 1 }, 180_000) .unwrap(); assert!(c.begin_reset(false, 185_000).is_err()); c.action( MatchAction::PauseOfficial { reason: "检查".into(), }, 185_000, ) .unwrap(); let stopped = c.begin_reset(true, 186_000).unwrap(); assert_eq!((stopped.phase, stopped.pause_kind), (6, 0)); assert_eq!(c.view(190_000).elapsed_ms, 4000); c.action(MatchAction::Reset, 190_000).unwrap(); let state = c.broadcast(190_000).unwrap(); assert_eq!( ( state.phase, state.remaining_ms, state.elapsed_ms, state.pause_elapsed_ms ), (0, 0, 0, 0) ); assert_eq!(state.resume_phase, 0); assert!(state.reason.is_empty()); assert_eq!(state.session, stopped.session); assert!(state.sequence > stopped.sequence); assert!(state.valid()); assert!(MatchClock::new(false, 1, 0).begin_reset(true, 0).is_err()); } #[test] fn pause_approval_freezes_time_and_expiry_never_resumes() { let mut c = MatchClock::new(true, 1, 0); c.action(MatchAction::Prepare, 0).unwrap(); assert!(c .action( MatchAction::PausePlayer { team: 0, reason: "故障".into(), approved: false }, 1000 ) .is_err()); c.action( MatchAction::PausePlayer { team: 1, reason: "更换电池".into(), approved: true, }, 1000, ) .unwrap(); let v = c.view(401_000); assert_eq!( (v.phase, v.remaining_ms, v.pause_remaining_ms), ("paused", 179_000, Some(0)) ); c.action(MatchAction::Resume, 401_000).unwrap(); assert_eq!(c.view(402_000).remaining_ms, 178_000); c.action( MatchAction::PauseOfficial { reason: "场地检查".into(), }, 402_000, ) .unwrap(); let v = c.view(802_000); assert_eq!( (v.pause_remaining_ms, v.pause_elapsed_ms, v.remaining_ms), (None, 400_000, 178_000) ); } #[test] fn pause_preserves_countdown_and_running_and_rejects_invalid_transitions() { for (phase, at) in [(3, 181_000), (4, 187_000)] { let mut c = MatchClock::new(true, 1, 0); ready(&mut c); c.action(MatchAction::Countdown { seconds: 5 }, 180_000) .unwrap(); assert!(c .action( MatchAction::PauseOfficial { reason: "\n".into() }, at ) .is_err()); c.action( MatchAction::PauseOfficial { reason: "检查".into(), }, at, ) .unwrap(); assert_eq!(c.state.resume_phase, phase); let before = c.view(at).remaining_ms; assert!(c.action(MatchAction::Prepare, at).is_err()); c.action(MatchAction::Resume, at + 900_000).unwrap(); assert_eq!(c.view(at + 900_000).remaining_ms, before); } } #[test] fn network_follower_locks_session_rejects_reorder_freezes_and_rejoins() { let mut sender = MatchClock::new(true, 44, 0); sender.action(MatchAction::Prepare, 0).unwrap(); let mut follower = MatchClock::new(false, 2, 0); let ip = Ipv4Addr::LOCALHOST; let p = sender.broadcast(1000).unwrap(); assert!(follower.receive(p.clone(), ip, 1000)); assert!(!follower.receive(p.clone(), ip, 1100)); assert!(!follower.receive( sender.broadcast(1200).unwrap(), Ipv4Addr::new(1, 2, 3, 4), 1200 )); assert!(!follower.view(2500).connected); let frozen = follower.view(2500).remaining_ms; assert_eq!(follower.view(99_000).remaining_ms, frozen); assert!(follower.receive(sender.broadcast(100_000).unwrap(), ip, 100_000)); assert!(follower.view(100_000).connected); let mut reboot = MatchClock::new(true, 99, 0); let p = reboot.broadcast(0).unwrap(); assert!(!follower.receive(p.clone(), ip, 101_000)); follower.release_source().unwrap(); assert!(follower.receive(p, ip, 102_000)); assert!(follower.action(MatchAction::Prepare, 102_000).is_err()); } #[test] fn role_change_starts_a_new_session_and_never_broadcasts_as_player() { let mut c = MatchClock::new(true, 1, 0); c.action(MatchAction::Prepare, 0).unwrap(); c.set_authority(false, 1000); assert!(c.broadcast(1000).is_none()); assert_eq!(c.view(1000).phase, "idle"); c.set_authority(true, 2000); assert_ne!(c.broadcast(2000).unwrap().session, 1); } }