Skip to main content

sectorsync_core/
command.rs

1//! Client command envelopes and validation decisions.
2
3use std::collections::VecDeque;
4
5use crate::barrier::{BarrierState, CommandQueueMode};
6use crate::ids::{ClientId, CommandId, EntityId, Tick};
7
8/// Client command priority.
9#[derive(Clone, Copy, Debug, PartialEq, Eq)]
10pub enum CommandPriority {
11    /// Normal gameplay command.
12    Normal,
13    /// Latency-sensitive command.
14    High,
15    /// Low-priority command that may be delayed under pressure.
16    Low,
17}
18
19/// Command envelope accepted by the generic command pipeline.
20#[derive(Clone, Debug, PartialEq, Eq)]
21pub struct CommandEnvelope {
22    /// Command id used for replay and audit.
23    pub id: CommandId,
24    /// Client that submitted the command.
25    pub client_id: ClientId,
26    /// Entity the command intends to control.
27    pub entity_id: EntityId,
28    /// Client-side sequence number.
29    pub sequence: u64,
30    /// Server tick observed when the command entered the runtime.
31    pub received_at: Tick,
32    /// Game-defined command kind.
33    pub kind: u32,
34    /// Command priority.
35    pub priority: CommandPriority,
36    /// Opaque payload owned by the embedding game.
37    pub payload: Vec<u8>,
38}
39
40/// Result of command validation.
41#[derive(Clone, Debug, PartialEq, Eq)]
42pub enum CommandDecision {
43    /// Command can be applied.
44    Accept,
45    /// Command is invalid and should not be applied.
46    Reject {
47        /// Machine-readable reject reason.
48        reason: CommandRejectReason,
49    },
50    /// Command should be treated as suspicious for audit purposes.
51    FlagSuspicious {
52        /// Suspicion score chosen by the embedding application.
53        score: u32,
54        /// Machine-readable reject or audit reason.
55        reason: CommandRejectReason,
56    },
57}
58
59/// Generic command reject reasons.
60#[derive(Clone, Copy, Debug, PartialEq, Eq)]
61pub enum CommandRejectReason {
62    /// Command failed schema or size validation.
63    InvalidSchema,
64    /// Command was submitted too frequently.
65    RateLimited,
66    /// Command was stale or replayed.
67    ReplayOrStale,
68    /// Command targeted an entity not owned by this station.
69    NotOwner,
70    /// Game-specific validator rejected the command.
71    GameRule,
72}
73
74/// Bounded queue limits by command priority.
75#[derive(Clone, Copy, Debug, PartialEq, Eq)]
76pub struct CommandQueueLimits {
77    /// High-priority queue capacity.
78    pub high: usize,
79    /// Normal-priority queue capacity.
80    pub normal: usize,
81    /// Low-priority queue capacity.
82    pub low: usize,
83}
84
85impl Default for CommandQueueLimits {
86    fn default() -> Self {
87        Self {
88            high: 1024,
89            normal: 8192,
90            low: 4096,
91        }
92    }
93}
94
95/// Barrier-aware command ingress policy.
96#[derive(Clone, Copy, Debug, PartialEq, Eq)]
97pub struct CommandIngress {
98    /// Current barrier state.
99    pub barrier_state: BarrierState,
100    /// Command behavior configured for the active barrier.
101    pub command_mode: CommandQueueMode,
102}
103
104impl CommandIngress {
105    /// Normal running ingress.
106    pub const RUNNING: Self = Self {
107        barrier_state: BarrierState::Running,
108        command_mode: CommandQueueMode::Buffer,
109    };
110}
111
112/// Outcome of enqueueing a command.
113#[derive(Clone, Copy, Debug, PartialEq, Eq)]
114pub enum CommandPushOutcome {
115    /// Command was queued for normal application.
116    Queued,
117    /// Command was buffered while a barrier is active.
118    BufferedByBarrier,
119}
120
121/// Command queue error.
122#[derive(Clone, Copy, Debug, PartialEq, Eq)]
123pub enum CommandQueueError {
124    /// Queue is full and caller must apply backpressure.
125    QueueFull(CommandPriority),
126    /// Barrier mode rejects this command.
127    RejectedByBarrier(CommandQueueMode),
128}
129
130impl core::fmt::Display for CommandQueueError {
131    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
132        match self {
133            Self::QueueFull(priority) => write!(f, "{priority:?} command queue is full"),
134            Self::RejectedByBarrier(mode) => {
135                write!(f, "command rejected by active barrier mode {mode:?}")
136            }
137        }
138    }
139}
140
141impl std::error::Error for CommandQueueError {}
142
143/// Bounded, priority-aware command queues for a station or gateway shard.
144#[derive(Clone, Debug)]
145pub struct CommandQueues {
146    limits: CommandQueueLimits,
147    high: VecDeque<CommandEnvelope>,
148    normal: VecDeque<CommandEnvelope>,
149    low: VecDeque<CommandEnvelope>,
150    barrier_buffer: VecDeque<CommandEnvelope>,
151}
152
153impl CommandQueues {
154    /// Creates empty command queues.
155    pub fn new(limits: CommandQueueLimits) -> Self {
156        Self {
157            limits,
158            high: VecDeque::with_capacity(limits.high),
159            normal: VecDeque::with_capacity(limits.normal),
160            low: VecDeque::with_capacity(limits.low),
161            barrier_buffer: VecDeque::new(),
162        }
163    }
164
165    /// Pushes a command through the barrier-aware ingress policy.
166    pub fn push(
167        &mut self,
168        command: CommandEnvelope,
169        ingress: CommandIngress,
170    ) -> Result<CommandPushOutcome, CommandQueueError> {
171        match ingress.barrier_state {
172            BarrierState::Running | BarrierState::Resuming => {
173                self.push_ready(command)?;
174                Ok(CommandPushOutcome::Queued)
175            }
176            BarrierState::Requested | BarrierState::WaitingTickBoundary | BarrierState::Frozen => {
177                match ingress.command_mode {
178                    CommandQueueMode::Buffer => {
179                        if self.barrier_buffer.len() >= self.barrier_buffer_capacity() {
180                            Err(CommandQueueError::QueueFull(command.priority))
181                        } else {
182                            self.barrier_buffer.push_back(command);
183                            Ok(CommandPushOutcome::BufferedByBarrier)
184                        }
185                    }
186                    CommandQueueMode::Reject | CommandQueueMode::Drain => {
187                        Err(CommandQueueError::RejectedByBarrier(ingress.command_mode))
188                    }
189                }
190            }
191        }
192    }
193
194    /// Moves commands buffered by a barrier back into priority queues.
195    ///
196    /// If a target priority queue is full, the first blocked command and all
197    /// commands after it remain in the barrier buffer for a later retry.
198    pub fn release_barrier_buffer(&mut self) -> Result<usize, CommandQueueError> {
199        let mut released = 0;
200        while let Some(priority) = self.barrier_buffer.front().map(|command| command.priority) {
201            if !self.has_ready_capacity(priority) {
202                return Err(CommandQueueError::QueueFull(priority));
203            }
204            let command = self
205                .barrier_buffer
206                .pop_front()
207                .expect("front command was checked above");
208            match priority {
209                CommandPriority::High => self.high.push_back(command),
210                CommandPriority::Normal => self.normal.push_back(command),
211                CommandPriority::Low => self.low.push_back(command),
212            }
213            released += 1;
214        }
215        Ok(released)
216    }
217
218    /// Drops commands buffered by a barrier.
219    pub fn clear_barrier_buffer(&mut self) -> usize {
220        let dropped = self.barrier_buffer.len();
221        self.barrier_buffer.clear();
222        dropped
223    }
224
225    /// Pops the next command, preferring high priority.
226    pub fn pop_next(&mut self) -> Option<CommandEnvelope> {
227        self.high
228            .pop_front()
229            .or_else(|| self.normal.pop_front())
230            .or_else(|| self.low.pop_front())
231    }
232
233    /// Returns queued command count excluding the barrier buffer.
234    pub fn ready_len(&self) -> usize {
235        self.high.len() + self.normal.len() + self.low.len()
236    }
237
238    /// Returns command count buffered by an active barrier.
239    pub fn barrier_buffer_len(&self) -> usize {
240        self.barrier_buffer.len()
241    }
242
243    /// Maximum commands retained while a barrier buffers ingress.
244    ///
245    /// The buffer uses the saturating sum of the three ready-queue limits so
246    /// integrations get a bounded default without a separate hidden capacity.
247    pub fn barrier_buffer_capacity(&self) -> usize {
248        self.limits
249            .high
250            .saturating_add(self.limits.normal)
251            .saturating_add(self.limits.low)
252    }
253
254    /// Returns total command count including barrier buffer.
255    pub fn total_len(&self) -> usize {
256        self.ready_len() + self.barrier_buffer.len()
257    }
258
259    /// Returns whether no commands are queued.
260    pub fn is_empty(&self) -> bool {
261        self.total_len() == 0
262    }
263
264    fn push_ready(&mut self, command: CommandEnvelope) -> Result<(), CommandQueueError> {
265        if !self.has_ready_capacity(command.priority) {
266            return Err(CommandQueueError::QueueFull(command.priority));
267        }
268        match command.priority {
269            CommandPriority::High => {
270                self.high.push_back(command);
271            }
272            CommandPriority::Normal => {
273                self.normal.push_back(command);
274            }
275            CommandPriority::Low => {
276                self.low.push_back(command);
277            }
278        }
279        Ok(())
280    }
281
282    fn has_ready_capacity(&self, priority: CommandPriority) -> bool {
283        match priority {
284            CommandPriority::High => self.high.len() < self.limits.high,
285            CommandPriority::Normal => self.normal.len() < self.limits.normal,
286            CommandPriority::Low => self.low.len() < self.limits.low,
287        }
288    }
289}
290
291#[cfg(test)]
292mod tests {
293    use super::*;
294
295    fn command(id: u64, priority: CommandPriority) -> CommandEnvelope {
296        CommandEnvelope {
297            id: CommandId::new(id),
298            client_id: ClientId::new(1),
299            entity_id: EntityId::new(10),
300            sequence: id,
301            received_at: Tick::new(0),
302            kind: 1,
303            priority,
304            payload: Vec::new(),
305        }
306    }
307
308    #[test]
309    fn command_queues_pop_by_priority() {
310        let mut queues = CommandQueues::new(CommandQueueLimits {
311            high: 2,
312            normal: 2,
313            low: 2,
314        });
315
316        queues
317            .push(command(1, CommandPriority::Low), CommandIngress::RUNNING)
318            .expect("low should queue");
319        queues
320            .push(command(2, CommandPriority::High), CommandIngress::RUNNING)
321            .expect("high should queue");
322        queues
323            .push(command(3, CommandPriority::Normal), CommandIngress::RUNNING)
324            .expect("normal should queue");
325
326        assert_eq!(queues.pop_next().expect("high").id, CommandId::new(2));
327        assert_eq!(queues.pop_next().expect("normal").id, CommandId::new(3));
328        assert_eq!(queues.pop_next().expect("low").id, CommandId::new(1));
329    }
330
331    #[test]
332    fn barrier_buffer_mode_holds_and_releases_commands() {
333        let mut queues = CommandQueues::new(CommandQueueLimits::default());
334        let ingress = CommandIngress {
335            barrier_state: BarrierState::Frozen,
336            command_mode: CommandQueueMode::Buffer,
337        };
338
339        let outcome = queues
340            .push(command(1, CommandPriority::Normal), ingress)
341            .expect("buffer should work");
342        assert_eq!(outcome, CommandPushOutcome::BufferedByBarrier);
343        assert_eq!(queues.ready_len(), 0);
344        assert_eq!(queues.barrier_buffer_len(), 1);
345
346        assert_eq!(
347            queues
348                .release_barrier_buffer()
349                .expect("release should work"),
350            1
351        );
352        assert_eq!(queues.ready_len(), 1);
353    }
354
355    #[test]
356    fn barrier_reject_mode_rejects_commands() {
357        let mut queues = CommandQueues::new(CommandQueueLimits::default());
358        let ingress = CommandIngress {
359            barrier_state: BarrierState::Frozen,
360            command_mode: CommandQueueMode::Reject,
361        };
362
363        let error = queues
364            .push(command(1, CommandPriority::Normal), ingress)
365            .expect_err("reject mode should reject");
366        assert_eq!(
367            error,
368            CommandQueueError::RejectedByBarrier(CommandQueueMode::Reject)
369        );
370    }
371
372    #[test]
373    fn barrier_buffer_is_bounded_by_ready_queue_limits() {
374        let mut queues = CommandQueues::new(CommandQueueLimits {
375            high: 1,
376            normal: 0,
377            low: 0,
378        });
379        let ingress = CommandIngress {
380            barrier_state: BarrierState::Frozen,
381            command_mode: CommandQueueMode::Buffer,
382        };
383
384        assert_eq!(queues.barrier_buffer_capacity(), 1);
385        queues
386            .push(command(1, CommandPriority::High), ingress)
387            .expect("first command should buffer");
388        let error = queues
389            .push(command(2, CommandPriority::High), ingress)
390            .expect_err("bounded barrier buffer should reject overflow");
391
392        assert_eq!(error, CommandQueueError::QueueFull(CommandPriority::High));
393        assert_eq!(queues.barrier_buffer_len(), 1);
394    }
395
396    #[test]
397    fn failed_barrier_release_keeps_blocked_command_buffered() {
398        let mut queues = CommandQueues::new(CommandQueueLimits {
399            high: 1,
400            normal: 0,
401            low: 0,
402        });
403        queues
404            .push(command(1, CommandPriority::High), CommandIngress::RUNNING)
405            .expect("ready queue should accept first command");
406        queues
407            .push(
408                command(2, CommandPriority::High),
409                CommandIngress {
410                    barrier_state: BarrierState::Frozen,
411                    command_mode: CommandQueueMode::Buffer,
412                },
413            )
414            .expect("barrier buffer should accept second command");
415
416        let error = queues
417            .release_barrier_buffer()
418            .expect_err("full ready queue should block release");
419        assert_eq!(error, CommandQueueError::QueueFull(CommandPriority::High));
420        assert_eq!(queues.barrier_buffer_len(), 1);
421        assert_eq!(
422            queues.pop_next().expect("first command should remain").id,
423            CommandId::new(1)
424        );
425        assert_eq!(queues.release_barrier_buffer(), Ok(1));
426        assert_eq!(
427            queues.pop_next().expect("second command should release").id,
428            CommandId::new(2)
429        );
430    }
431}