Skip to main content

sim_cli/
args.rs

1//! Clap argument groups shared by the commands that reach the server.
2//!
3//! Flattening these keeps the flag names, env vars, defaults, help text, and
4//! validation identical wherever a command takes a slot range, opens a
5//! WebSocket session, or toggles JSON output.
6
7use std::fmt;
8
9use clap::{Args, ValueEnum};
10use simulator_api::{BundleKind, RangeScope};
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 of the range (inclusive).
42    #[arg(long, env = "SIMULATOR_START_SLOT")]
43    pub start_slot: Option<u64>,
44
45    /// Last slot of the range (inclusive).
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    /// Blocks to execute per step; skipped slots are not counted. Defaults to
89    /// the whole range in a single step; set it lower to step through the range
90    /// in smaller increments.
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    /// Blocks to execute per continue request, defaulting to the `[start, end]`
97    /// count 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/// What a bundle holds, and so what it can be used for.
105#[derive(Copy, Clone, Debug, PartialEq, Eq, ValueEnum)]
106pub enum KindFilter {
107    /// The transactions a session executes.
108    #[value(name = "transactions")]
109    Transactions,
110    /// The account state `run --replay-account-state` replays.
111    #[value(name = "account-state", alias = "account_state")]
112    AccountState,
113}
114
115impl From<KindFilter> for BundleKind {
116    fn from(value: KindFilter) -> Self {
117        match value {
118            KindFilter::Transactions => Self::Blocks,
119            KindFilter::AccountState => Self::AccountState,
120        }
121    }
122}
123
124/// Who a range is available to.
125#[derive(Copy, Clone, Debug, PartialEq, Eq, ValueEnum)]
126pub enum ScopeFilter {
127    /// Ranges of prebuilt bundles, available to everyone.
128    Global,
129    /// Ranges of custom bundles, built for your API key.
130    User,
131}
132
133impl From<ScopeFilter> for RangeScope {
134    fn from(value: ScopeFilter) -> Self {
135        match value {
136            ScopeFilter::Global => Self::Global,
137            ScopeFilter::User => Self::User,
138        }
139    }
140}
141
142/// Deployment whose public WebSocket endpoint a session connects to.
143#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum, strum::Display)]
144#[strum(serialize_all = "lowercase")]
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://127.0.0.1:8090/backtest",
156            Self::Staging => "wss://staging.simulator.termina.technology/backtest",
157            Self::Production => "wss://simulator.termina.technology/backtest",
158        }
159    }
160}
161
162/// WebSocket connection settings shared by the commands that drive a session.
163#[derive(Debug, Clone, Args)]
164pub struct SimConnectionArgs {
165    /// Deployment to connect to (ignored when `--websocket-url` is set).
166    #[arg(long, env = "SIMULATOR_ENVIRONMENT", default_value_t = SimEnvironment::Staging)]
167    pub environment: SimEnvironment,
168
169    /// Explicit WebSocket URL, overriding the `--environment` default.
170    #[arg(long, env = "SIMULATOR_WEBSOCKET_URL")]
171    pub websocket_url: Option<String>,
172
173    /// Max seconds to wait for runtime capacity to scale out before failing the
174    /// create.
175    #[arg(long, env = "SIMULATOR_CAPACITY_WAIT_TIMEOUT_SECS")]
176    pub capacity_wait_timeout_secs: Option<u16>,
177}
178
179impl SimConnectionArgs {
180    /// Resolve the WebSocket endpoint: explicit URL wins, else the deployment
181    /// default.
182    pub fn websocket_endpoint(&self) -> String {
183        self.websocket_url
184            .clone()
185            .unwrap_or_else(|| self.environment.websocket_url().to_string())
186    }
187}
188
189/// Shared `--json` output toggle. Formats a command's result on stdout and
190/// means nothing else, so prompts belong on stderr.
191#[derive(Debug, Clone, Copy, Args)]
192pub struct JsonOutputArgs {
193    /// Print output as JSON.
194    #[arg(long)]
195    pub json: bool,
196}
197
198#[cfg(test)]
199mod tests {
200    use clap::Parser;
201    use rstest::rstest;
202
203    use super::*;
204
205    #[derive(Parser)]
206    struct Harness {
207        #[command(flatten)]
208        range: SimRangeArgs,
209    }
210
211    #[rstest]
212    #[case(SimEnvironment::Local, "local")]
213    #[case(SimEnvironment::Staging, "staging")]
214    #[case(SimEnvironment::Production, "production")]
215    fn environment_display_matches_clap_name(#[case] env: SimEnvironment, #[case] name: &str) {
216        assert_eq!(env.to_string(), name);
217        assert_eq!(env.to_possible_value().unwrap().get_name(), name);
218    }
219
220    #[test]
221    fn advance_count_rejects_zero() {
222        assert!(Harness::try_parse_from(["x", "--advance-count", "0"]).is_err());
223    }
224
225    #[test]
226    fn advance_count_defaults_to_full_span() {
227        let h = Harness::try_parse_from(["x"]).unwrap();
228        assert_eq!(h.range.advance_count, None);
229        assert_eq!(h.range.advance_count(100, 109), 10);
230    }
231
232    #[test]
233    fn resolve_or_defaults_then_validates() {
234        let unset = Harness::try_parse_from(["x"]).unwrap().range.bounds;
235        assert_eq!(unset.resolve_or(5, 10).unwrap(), (5, 10));
236
237        let reversed = Harness::try_parse_from(["x", "--start-slot", "10", "--end-slot", "5"])
238            .unwrap()
239            .range
240            .bounds;
241        assert!(reversed.resolve_or(0, 100).is_err());
242    }
243
244    #[test]
245    fn require_needs_both_bounds_in_order() {
246        let only_start = Harness::try_parse_from(["x", "--start-slot", "5"]).unwrap();
247        assert!(only_start.range.bounds.require().is_err());
248
249        let reversed =
250            Harness::try_parse_from(["x", "--start-slot", "10", "--end-slot", "5"]).unwrap();
251        assert!(reversed.range.bounds.require().is_err());
252
253        let ok = Harness::try_parse_from(["x", "--start-slot", "5", "--end-slot", "10"]).unwrap();
254        assert_eq!(ok.range.bounds.require().unwrap(), (5, 10));
255    }
256}