1use std::fmt;
8
9use clap::{Args, ValueEnum};
10use simulator_api::{BundleKind, RangeScope};
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(Copy, Clone, Debug, PartialEq, Eq, ValueEnum)]
106pub enum KindFilter {
107 #[value(name = "transactions")]
109 Transactions,
110 #[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#[derive(Copy, Clone, Debug, PartialEq, Eq, ValueEnum)]
126pub enum ScopeFilter {
127 Global,
129 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#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
144pub enum SimEnvironment {
145 Local,
146 Staging,
147 Production,
148}
149
150impl SimEnvironment {
151 pub fn websocket_url(self) -> &'static str {
153 match self {
154 Self::Local => "ws://localhost:8900/backtest",
155 Self::Staging => "wss://staging.simulator.termina.technology/backtest",
156 Self::Production => "wss://simulator.termina.technology/backtest",
157 }
158 }
159}
160
161impl fmt::Display for SimEnvironment {
162 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
163 f.write_str(match self {
164 Self::Local => "local",
165 Self::Staging => "staging",
166 Self::Production => "production",
167 })
168 }
169}
170
171#[derive(Debug, Clone, Args)]
173pub struct SimConnectionArgs {
174 #[arg(long, env = "SIMULATOR_ENVIRONMENT", default_value_t = SimEnvironment::Staging)]
176 pub environment: SimEnvironment,
177
178 #[arg(long, env = "SIMULATOR_WEBSOCKET_URL")]
180 pub websocket_url: Option<String>,
181
182 #[arg(long, env = "SIMULATOR_CAPACITY_WAIT_TIMEOUT_SECS")]
185 pub capacity_wait_timeout_secs: Option<u16>,
186}
187
188impl SimConnectionArgs {
189 pub fn websocket_endpoint(&self) -> String {
192 self.websocket_url
193 .clone()
194 .unwrap_or_else(|| self.environment.websocket_url().to_string())
195 }
196}
197
198#[derive(Debug, Clone, Copy, Args)]
201pub struct JsonOutputArgs {
202 #[arg(long)]
204 pub json: bool,
205}
206
207#[cfg(test)]
208mod tests {
209 use clap::Parser;
210
211 use super::*;
212
213 #[derive(Parser)]
214 struct Harness {
215 #[command(flatten)]
216 range: SimRangeArgs,
217 }
218
219 #[test]
220 fn advance_count_rejects_zero() {
221 assert!(Harness::try_parse_from(["x", "--advance-count", "0"]).is_err());
222 }
223
224 #[test]
225 fn advance_count_defaults_to_full_span() {
226 let h = Harness::try_parse_from(["x"]).unwrap();
227 assert_eq!(h.range.advance_count, None);
228 assert_eq!(h.range.advance_count(100, 109), 10);
229 }
230
231 #[test]
232 fn resolve_or_defaults_then_validates() {
233 let unset = Harness::try_parse_from(["x"]).unwrap().range.bounds;
234 assert_eq!(unset.resolve_or(5, 10).unwrap(), (5, 10));
235
236 let reversed = Harness::try_parse_from(["x", "--start-slot", "10", "--end-slot", "5"])
237 .unwrap()
238 .range
239 .bounds;
240 assert!(reversed.resolve_or(0, 100).is_err());
241 }
242
243 #[test]
244 fn require_needs_both_bounds_in_order() {
245 let only_start = Harness::try_parse_from(["x", "--start-slot", "5"]).unwrap();
246 assert!(only_start.range.bounds.require().is_err());
247
248 let reversed =
249 Harness::try_parse_from(["x", "--start-slot", "10", "--end-slot", "5"]).unwrap();
250 assert!(reversed.range.bounds.require().is_err());
251
252 let ok = Harness::try_parse_from(["x", "--start-slot", "5", "--end-slot", "10"]).unwrap();
253 assert_eq!(ok.range.bounds.require().unwrap(), (5, 10));
254 }
255}