1use std::fmt;
9
10use clap::{Args, ValueEnum};
11
12#[derive(Debug)]
14pub enum SlotRangeError {
15 MissingBounds,
17 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#[derive(Debug, Clone, Args)]
40pub struct SlotBoundsArgs {
41 #[arg(long, env = "SIMULATOR_START_SLOT")]
43 pub start_slot: Option<u64>,
44
45 #[arg(long, env = "SIMULATOR_END_SLOT")]
47 pub end_slot: Option<u64>,
48}
49
50impl SlotBoundsArgs {
51 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 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#[derive(Debug, Clone, Args)]
84pub struct SimRangeArgs {
85 #[command(flatten)]
86 pub bounds: SlotBoundsArgs,
87
88 #[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 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#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
106pub enum SimEnvironment {
107 Local,
108 Staging,
109 Production,
110}
111
112impl SimEnvironment {
113 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#[derive(Debug, Clone, Args)]
136pub struct SimConnectionArgs {
137 #[arg(long, env = "SIMULATOR_ENVIRONMENT", default_value_t = SimEnvironment::Staging)]
139 pub environment: SimEnvironment,
140
141 #[arg(long, env = "SIMULATOR_WEBSOCKET_URL")]
143 pub websocket_url: Option<String>,
144
145 #[arg(long, env = "SIMULATOR_CAPACITY_WAIT_TIMEOUT_SECS")]
148 pub capacity_wait_timeout_secs: Option<u16>,
149}
150
151impl SimConnectionArgs {
152 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#[derive(Debug, Clone, Copy, Args)]
163pub struct JsonOutputArgs {
164 #[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}