1use std::fmt;
9
10use clap::{Args, ValueEnum};
11use simulator_api::{BundleKind, RangeScope};
12
13#[derive(Debug)]
15pub enum SlotRangeError {
16 MissingBounds,
18 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#[derive(Debug, Clone, Args)]
41pub struct SlotBoundsArgs {
42 #[arg(long, env = "SIMULATOR_START_SLOT")]
44 pub start_slot: Option<u64>,
45
46 #[arg(long, env = "SIMULATOR_END_SLOT")]
48 pub end_slot: Option<u64>,
49}
50
51impl SlotBoundsArgs {
52 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 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#[derive(Debug, Clone, Args)]
85pub struct SimRangeArgs {
86 #[command(flatten)]
87 pub bounds: SlotBoundsArgs,
88
89 #[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 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#[derive(Copy, Clone, Debug, PartialEq, Eq, ValueEnum)]
107pub enum KindFilter {
108 #[value(name = "transactions")]
110 Transactions,
111 #[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#[derive(Copy, Clone, Debug, PartialEq, Eq, ValueEnum)]
127pub enum ScopeFilter {
128 Global,
130 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#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
145pub enum SimEnvironment {
146 Local,
147 Staging,
148 Production,
149}
150
151impl SimEnvironment {
152 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#[derive(Debug, Clone, Args)]
175pub struct SimConnectionArgs {
176 #[arg(long, env = "SIMULATOR_ENVIRONMENT", default_value_t = SimEnvironment::Staging)]
178 pub environment: SimEnvironment,
179
180 #[arg(long, env = "SIMULATOR_WEBSOCKET_URL")]
182 pub websocket_url: Option<String>,
183
184 #[arg(long, env = "SIMULATOR_CAPACITY_WAIT_TIMEOUT_SECS")]
187 pub capacity_wait_timeout_secs: Option<u16>,
188}
189
190impl SimConnectionArgs {
191 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#[derive(Debug, Clone, Copy, Args)]
203pub struct JsonOutputArgs {
204 #[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}