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, strum::Display)]
144#[strum(serialize_all = "lowercase")]
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://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#[derive(Debug, Clone, Args)]
164pub struct SimConnectionArgs {
165 #[arg(long, env = "SIMULATOR_ENVIRONMENT", default_value_t = SimEnvironment::Staging)]
167 pub environment: SimEnvironment,
168
169 #[arg(long, env = "SIMULATOR_WEBSOCKET_URL")]
171 pub websocket_url: Option<String>,
172
173 #[arg(long, env = "SIMULATOR_CAPACITY_WAIT_TIMEOUT_SECS")]
176 pub capacity_wait_timeout_secs: Option<u16>,
177}
178
179impl SimConnectionArgs {
180 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#[derive(Debug, Clone, Copy, Args)]
192pub struct JsonOutputArgs {
193 #[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}