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