Skip to main content

sim_cli/
args.rs

1//! Clap argument groups shared across every simulator-driving command on both
2//! CLI binaries (`sim`, `backtest-driver`, and its `benchmark` subcommand).
3//!
4//! Flattening these keeps the flag names, env vars, defaults, help text, and
5//! validation identical wherever a command takes a slot range, opens a
6//! WebSocket session, or toggles JSON output.
7
8use std::fmt;
9
10use clap::{Args, ValueEnum};
11
12/// Failure validating a slot range supplied on the command line.
13#[derive(Debug)]
14pub enum SlotRangeError {
15    /// A command that requires an explicit range was given neither bound.
16    MissingBounds,
17    /// `start_slot` exceeded `end_slot`.
18    OutOfOrder { start: u64, end: u64 },
19}
20
21impl fmt::Display for SlotRangeError {
22    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
23        match self {
24            Self::MissingBounds => f.write_str("--start-slot and --end-slot are required"),
25            Self::OutOfOrder { start, end } => {
26                write!(
27                    f,
28                    "--start-slot ({start}) must not exceed --end-slot ({end})"
29                )
30            }
31        }
32    }
33}
34
35impl std::error::Error for SlotRangeError {}
36
37/// Inclusive `[start, end]` slot bounds. Optional so each command can default
38/// or require them while sharing one flag/env spelling and one ordering check.
39#[derive(Debug, Clone, Args)]
40pub struct SlotBoundsArgs {
41    /// First slot (inclusive) to simulate.
42    #[arg(long, env = "SIMULATOR_START_SLOT")]
43    pub start_slot: Option<u64>,
44
45    /// Last slot (inclusive) to simulate.
46    #[arg(long, env = "SIMULATOR_END_SLOT")]
47    pub end_slot: Option<u64>,
48}
49
50impl SlotBoundsArgs {
51    /// Both bounds, validated `start <= end` — for commands that require an
52    /// explicit range (no built-in defaults).
53    pub fn require(&self) -> Result<(u64, u64), SlotRangeError> {
54        match (self.start_slot, self.end_slot) {
55            (Some(start), Some(end)) => Self::checked(start, end),
56            _ => Err(SlotRangeError::MissingBounds),
57        }
58    }
59
60    /// Resolve both bounds, falling back to the given defaults for any omitted,
61    /// then validate `start <= end`.
62    pub fn resolve_or(
63        &self,
64        default_start: u64,
65        default_end: u64,
66    ) -> Result<(u64, u64), SlotRangeError> {
67        Self::checked(
68            self.start_slot.unwrap_or(default_start),
69            self.end_slot.unwrap_or(default_end),
70        )
71    }
72
73    fn checked(start: u64, end: u64) -> Result<(u64, u64), SlotRangeError> {
74        if start <= end {
75            Ok((start, end))
76        } else {
77            Err(SlotRangeError::OutOfOrder { start, end })
78        }
79    }
80}
81
82/// Slot range and stepping granularity, shared by every range-driving command.
83#[derive(Debug, Clone, Args)]
84pub struct SimRangeArgs {
85    #[command(flatten)]
86    pub bounds: SlotBoundsArgs,
87
88    /// Slots to advance per continue request. Defaults to the whole range — one
89    /// request — so a run measures execution rather than per-slot control
90    /// round-trips. Lower it only to test finer-grained session stepping.
91    #[arg(long, env = "SIMULATOR_ADVANCE_COUNT", value_parser = clap::value_parser!(u64).range(1..))]
92    pub advance_count: Option<u64>,
93}
94
95impl SimRangeArgs {
96    /// Slots to advance per continue request, defaulting to the full `[start,
97    /// end]` span so the whole range rides a single request.
98    pub fn advance_count(&self, start: u64, end: u64) -> u64 {
99        self.advance_count
100            .unwrap_or_else(|| end.saturating_sub(start).saturating_add(1))
101    }
102}
103
104/// Deployment whose public WebSocket endpoint a session connects to.
105#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
106pub enum SimEnvironment {
107    Local,
108    Staging,
109    Production,
110}
111
112impl SimEnvironment {
113    /// Default backtest WebSocket URL for this deployment.
114    pub fn websocket_url(self) -> &'static str {
115        match self {
116            Self::Local => "ws://localhost:8900/backtest",
117            Self::Staging => "wss://staging.simulator.termina.technology/backtest",
118            Self::Production => "wss://simulator.termina.technology/backtest",
119        }
120    }
121}
122
123impl fmt::Display for SimEnvironment {
124    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
125        f.write_str(match self {
126            Self::Local => "local",
127            Self::Staging => "staging",
128            Self::Production => "production",
129        })
130    }
131}
132
133/// WebSocket connection settings shared by the session-driving commands
134/// (`backtest-driver` and `benchmark remote`).
135#[derive(Debug, Clone, Args)]
136pub struct SimConnectionArgs {
137    /// Deployment to connect to (ignored when `--websocket-url` is set).
138    #[arg(long, env = "SIMULATOR_ENVIRONMENT", default_value_t = SimEnvironment::Staging)]
139    pub environment: SimEnvironment,
140
141    /// Explicit WebSocket URL, overriding the `--environment` default.
142    #[arg(long, env = "SIMULATOR_WEBSOCKET_URL")]
143    pub websocket_url: Option<String>,
144
145    /// Max seconds to wait for runtime capacity to scale out before failing the
146    /// create.
147    #[arg(long, env = "SIMULATOR_CAPACITY_WAIT_TIMEOUT_SECS")]
148    pub capacity_wait_timeout_secs: Option<u16>,
149}
150
151impl SimConnectionArgs {
152    /// Resolve the WebSocket endpoint: explicit URL wins, else the deployment
153    /// default.
154    pub fn websocket_endpoint(&self) -> String {
155        self.websocket_url
156            .clone()
157            .unwrap_or_else(|| self.environment.websocket_url().to_string())
158    }
159}
160
161/// Shared `--json` output toggle for the read-only query commands.
162#[derive(Debug, Clone, Copy, Args)]
163pub struct JsonOutputArgs {
164    /// Print output as JSON.
165    #[arg(long)]
166    pub json: bool,
167}
168
169#[cfg(test)]
170mod tests {
171    use clap::Parser;
172
173    use super::*;
174
175    #[derive(Parser)]
176    struct Harness {
177        #[command(flatten)]
178        range: SimRangeArgs,
179    }
180
181    #[test]
182    fn advance_count_rejects_zero() {
183        assert!(Harness::try_parse_from(["x", "--advance-count", "0"]).is_err());
184    }
185
186    #[test]
187    fn advance_count_defaults_to_full_span() {
188        let h = Harness::try_parse_from(["x"]).unwrap();
189        assert_eq!(h.range.advance_count, None);
190        assert_eq!(h.range.advance_count(100, 109), 10);
191    }
192
193    #[test]
194    fn resolve_or_defaults_then_validates() {
195        let unset = Harness::try_parse_from(["x"]).unwrap().range.bounds;
196        assert_eq!(unset.resolve_or(5, 10).unwrap(), (5, 10));
197
198        let reversed = Harness::try_parse_from(["x", "--start-slot", "10", "--end-slot", "5"])
199            .unwrap()
200            .range
201            .bounds;
202        assert!(reversed.resolve_or(0, 100).is_err());
203    }
204
205    #[test]
206    fn require_needs_both_bounds_in_order() {
207        let only_start = Harness::try_parse_from(["x", "--start-slot", "5"]).unwrap();
208        assert!(only_start.range.bounds.require().is_err());
209
210        let reversed =
211            Harness::try_parse_from(["x", "--start-slot", "10", "--end-slot", "5"]).unwrap();
212        assert!(reversed.range.bounds.require().is_err());
213
214        let ok = Harness::try_parse_from(["x", "--start-slot", "5", "--end-slot", "10"]).unwrap();
215        assert_eq!(ok.range.bounds.require().unwrap(), (5, 10));
216    }
217}