1use std::fmt;
9
10use degenbot_aave::RunError as AaveRunError;
11use degenbot_config::ConfigError;
12use degenbot_db::DbError;
13use degenbot_pool_updater::RunError as PoolRunError;
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub enum ExitCode {
18 Success,
21 Failure,
24 Config,
27}
28
29impl ExitCode {
30 #[must_use]
32 pub const fn code(self) -> i32 {
33 match self {
34 Self::Success => 0,
35 Self::Failure => 1,
36 Self::Config => 78,
37 }
38 }
39}
40
41#[derive(Debug, Clone, PartialEq, Eq)]
44pub struct UnknownVariant {
45 pub raw: String,
47 pub known: Vec<&'static str>,
49}
50
51impl fmt::Display for UnknownVariant {
52 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
53 write!(
54 f,
55 "unknown variant {:?}: expected one of {}",
56 self.raw,
57 self.known.join(", ")
58 )
59 }
60}
61
62impl std::error::Error for UnknownVariant {}
63
64#[derive(Debug, Clone, PartialEq, Eq)]
67pub struct ExchangeResumeState {
68 pub name: String,
70 pub last_update_block: Option<i64>,
72}
73
74#[derive(Debug)]
86pub struct PoolUpdateFailure {
87 pub error: PoolRunError,
89 pub rpc_url: String,
91 pub chain_id: i64,
93 pub from_block: u64,
96 pub to_block: Option<u64>,
98 pub resume: Option<Vec<ExchangeResumeState>>,
102}
103
104impl PoolUpdateFailure {
105 #[must_use]
107 pub fn message(&self) -> String {
108 let error_text = self.error.to_string();
109 let range = self.range_text();
110 let mut lines = if self.is_rpc_connection_failure(&error_text) {
111 vec![
112 format!(
113 "Chain {}: the RPC connection to {} dropped mid-run while advancing blocks \
114 {}; chunks already committed are kept. Rerunning resumes from the recorded \
115 per-exchange cursors.",
116 self.chain_id, self.rpc_url, range
117 ),
118 format!(" underlying error: {error_text}"),
119 ]
120 } else {
121 vec![format!(
122 "Chain {}: pool update against {} failed while advancing blocks {}: {error_text}",
123 self.chain_id, self.rpc_url, range
124 )]
125 };
126 lines.extend(self.resume_lines());
127 lines.join("\n")
128 }
129
130 fn range_text(&self) -> String {
132 match self.to_block {
133 Some(to) => format!("{}-{to}", self.from_block),
134 None => format!("{} onward (the chain tip)", self.from_block),
135 }
136 }
137
138 fn is_rpc_connection_failure(&self, error_text: &str) -> bool {
149 matches!(&self.error, PoolRunError::Provider(_))
150 && (error_text.starts_with("rpc error: Connection failed: ")
151 || error_text.starts_with("rpc error: Request timeout: "))
152 }
153
154 fn resume_lines(&self) -> Vec<String> {
158 let Some(rows) = &self.resume else {
159 return vec![
160 " exchange cursor state unavailable: the read-only resume check failed"
161 .to_string(),
162 ];
163 };
164 if rows.is_empty() {
165 return vec![format!(
166 " no active exchanges were registered for chain {}.",
167 self.chain_id
168 )];
169 }
170 let mut current = Vec::new();
171 let mut behind = Vec::new();
172 let mut never_updated = Vec::new();
173 for row in rows {
174 match (row.last_update_block, self.to_block) {
175 (None, _) => never_updated.push(row.name.clone()),
176 (Some(block), None) => {
179 behind.push(format!("{} (block {block})", row.name));
180 }
181 (Some(block), Some(to)) => {
182 let to = i64::try_from(to).unwrap_or(i64::MAX);
183 if block >= to {
184 current.push(row.name.clone());
185 } else {
186 behind.push(format!("{} (block {block})", row.name));
187 }
188 }
189 }
190 }
191 let mut lines = Vec::new();
192 if !current.is_empty() {
193 lines.push(format!(
194 " current at the requested target: {}",
195 current.join(", ")
196 ));
197 }
198 if !behind.is_empty() {
199 lines.push(format!(
200 " behind (last committed block): {}",
201 behind.join(", ")
202 ));
203 }
204 if !never_updated.is_empty() {
205 lines.push(format!(" never updated: {}", never_updated.join(", ")));
206 }
207 lines
208 }
209}
210
211#[derive(Debug)]
217pub enum CliError {
218 BootRefused(String),
220 Aborted,
222 DatabaseUpgradeRetired,
225 DatabaseForeign,
227 DatabaseNothingToDo,
230 Database(DbError),
232 Io(std::io::Error),
235 Config(ConfigError),
237 UnknownChain {
240 chain: String,
242 },
243 UnknownDeployment {
246 chain_id: u64,
248 name: String,
250 },
251 InvalidBlockTag(String),
254 BlockResolution(String),
256 InvalidAddress(String),
259 InvalidArgument(String),
262 NoActiveAaveMarkets,
265 UnknownAaveMarket {
269 chain_id: u64,
271 market_name: String,
273 },
274 AaveMarketMidUpdate {
277 market_id: i64,
279 lock_path: String,
281 },
282 PoolUpdate(Box<PoolUpdateFailure>),
290 AaveUpdate(AaveRunError),
292 RuntimeNested,
297 OperatorRefused(String),
300 OperatorProtocol(String),
304 OperatorHygiene(String),
308}
309
310impl CliError {
311 #[must_use]
313 pub fn message(&self) -> String {
314 match self {
315 Self::BootRefused(message)
316 | Self::BlockResolution(message)
317 | Self::InvalidArgument(message)
318 | Self::OperatorRefused(message)
319 | Self::OperatorProtocol(message)
320 | Self::OperatorHygiene(message) => message.clone(),
321 Self::Aborted => "Aborted!".to_string(),
322 Self::DatabaseUpgradeRetired => {
323 "the database upgrades itself at open; for an explicit repair, run \
324 `degenbot database heal`"
325 .to_string()
326 }
327 Self::DatabaseForeign => {
328 "The database is unrecognized (a foreign SQLite file); refused.".to_string()
329 }
330 Self::DatabaseNothingToDo => {
331 "The database has no legacy history; there is nothing to cut over.".to_string()
332 }
333 Self::Database(err) => err.to_string(),
334 Self::Io(err) => err.to_string(),
335 Self::Config(err) => err.to_string(),
336 Self::UnknownChain { chain } => format!(
337 "Unknown chain {chain:?}: expected a chain slug (base, ethereum) or a numeric \
338 chain id."
339 ),
340 Self::UnknownDeployment { chain_id, name } => {
341 format!("The deployments registry has no record for {name:?} on chain {chain_id}.")
342 }
343 Self::InvalidBlockTag(tag) => format!("Invalid block tag: {tag}"),
344 Self::InvalidAddress(address) => format!("Invalid address: {address}"),
345 Self::NoActiveAaveMarkets => "No active Aave markets found.".to_string(),
346 Self::UnknownAaveMarket {
347 chain_id,
348 market_name,
349 } => format!("No Aave V3 market named {market_name:?} on chain {chain_id}."),
350 Self::AaveMarketMidUpdate {
351 market_id,
352 lock_path,
353 } => format!(
354 "Aave market {market_id} is mid-update (another process holds {lock_path}); \
355 refusing to reset it."
356 ),
357 Self::PoolUpdate(failure) => failure.message(),
358 Self::AaveUpdate(err) => err.to_string(),
359 Self::RuntimeNested => "the command arms own their tokio runtime; do not run them \
360 from inside an existing runtime"
361 .to_string(),
362 }
363 }
364}
365
366impl fmt::Display for CliError {
367 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
368 f.write_str(&self.message())
369 }
370}
371
372impl std::error::Error for CliError {
373 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
374 match self {
375 Self::Database(err) => Some(err),
376 Self::Config(err) => Some(err),
377 Self::PoolUpdate(failure) => Some(&failure.error),
378 Self::AaveUpdate(err) => Some(err),
379 Self::Io(err) => Some(err),
380 _ => None,
381 }
382 }
383}
384
385impl From<DbError> for CliError {
390 fn from(err: DbError) -> Self {
391 match err {
392 DbError::UnrecognizedSchema => Self::DatabaseForeign,
393 other => Self::Database(other),
394 }
395 }
396}
397
398impl From<ConfigError> for CliError {
400 fn from(err: ConfigError) -> Self {
401 Self::Config(err)
402 }
403}
404
405impl From<&CliError> for ExitCode {
407 fn from(err: &CliError) -> Self {
408 match err {
409 CliError::BootRefused(_) => Self::Config,
411 CliError::Aborted
412 | CliError::DatabaseUpgradeRetired
413 | CliError::DatabaseForeign
414 | CliError::DatabaseNothingToDo
415 | CliError::Database(_)
416 | CliError::Io(_)
417 | CliError::Config(_)
418 | CliError::UnknownChain { .. }
419 | CliError::UnknownDeployment { .. }
420 | CliError::InvalidBlockTag(_)
421 | CliError::BlockResolution(_)
422 | CliError::InvalidAddress(_)
423 | CliError::InvalidArgument(_)
424 | CliError::NoActiveAaveMarkets
425 | CliError::UnknownAaveMarket { .. }
426 | CliError::AaveMarketMidUpdate { .. }
427 | CliError::PoolUpdate(_)
428 | CliError::AaveUpdate(_)
429 | CliError::RuntimeNested
430 | CliError::OperatorRefused(_)
431 | CliError::OperatorProtocol(_)
432 | CliError::OperatorHygiene(_) => Self::Failure,
433 }
434 }
435}
436
437impl From<CliError> for ExitCode {
438 fn from(err: CliError) -> Self {
439 Self::from(&err)
440 }
441}
442
443#[cfg(test)]
444mod tests {
445 use super::*;
447 use degenbot_db::DbError;
448
449 #[test]
450 fn non_connection_failure_names_endpoint_chain_range_and_error() {
451 let failure = PoolUpdateFailure {
452 error: PoolRunError::Db(DbError::MissingRow("chunk row".to_string())),
453 rpc_url: "http://reth.local:8545".to_string(),
454 chain_id: 8453,
455 from_block: 26_055_206,
456 to_block: Some(26_059_263),
457 resume: None,
458 };
459 let message = failure.message();
460 assert!(message.contains("http://reth.local:8545"), "{message}");
461 assert!(message.contains("8453"), "{message}");
462 assert!(message.contains("blocks 26055206-26059263"), "{message}");
463 assert!(
464 message.contains("required row not found: chunk row"),
465 "{message}"
466 );
467 assert!(!message.contains("dropped mid-run"), "{message}");
468 }
469
470 #[test]
471 fn tip_run_reports_an_open_ended_range() {
472 let failure = PoolUpdateFailure {
473 error: PoolRunError::Db(DbError::MissingRow("tip".to_string())),
474 rpc_url: "http://reth.local:8545".to_string(),
475 chain_id: 1,
476 from_block: 5,
477 to_block: None,
478 resume: None,
479 };
480 assert!(failure
481 .message()
482 .contains("blocks 5 onward (the chain tip)"));
483 }
484
485 #[test]
486 fn resume_groups_render_current_behind_and_never_updated() {
487 let failure = PoolUpdateFailure {
488 error: PoolRunError::Db(DbError::MissingRow("row".to_string())),
489 rpc_url: "http://reth.local:8545".to_string(),
490 chain_id: 8453,
491 from_block: 1,
492 to_block: Some(100),
493 resume: Some(vec![
494 ExchangeResumeState {
495 name: "uniswap_v2".to_string(),
496 last_update_block: Some(100),
497 },
498 ExchangeResumeState {
499 name: "uniswap_v3".to_string(),
500 last_update_block: Some(50),
501 },
502 ExchangeResumeState {
503 name: "uniswap_v4".to_string(),
504 last_update_block: None,
505 },
506 ]),
507 };
508 let message = failure.message();
509 assert!(
510 message.contains("current at the requested target: uniswap_v2"),
511 "{message}"
512 );
513 assert!(
514 message.contains("behind (last committed block): uniswap_v3 (block 50)"),
515 "{message}"
516 );
517 assert!(message.contains("never updated: uniswap_v4"), "{message}");
518 }
519
520 #[test]
521 fn a_tip_run_leaves_no_exchange_current_at_the_target() {
522 let failure = PoolUpdateFailure {
523 error: PoolRunError::Db(DbError::MissingRow("row".to_string())),
524 rpc_url: "http://reth.local:8545".to_string(),
525 chain_id: 8453,
526 from_block: 1,
527 to_block: None,
528 resume: Some(vec![ExchangeResumeState {
529 name: "uniswap_v2".to_string(),
530 last_update_block: Some(26_059_263),
531 }]),
532 };
533 let message = failure.message();
534 assert!(
535 !message.contains("current at the requested target"),
536 "{message}"
537 );
538 assert!(
539 message.contains("behind (last committed block): uniswap_v2 (block 26059263)"),
540 "{message}"
541 );
542 }
543
544 #[test]
545 fn an_unavailable_snapshot_is_said_so() {
546 let failure = PoolUpdateFailure {
547 error: PoolRunError::Db(DbError::MissingRow("row".to_string())),
548 rpc_url: "http://reth.local:8545".to_string(),
549 chain_id: 8453,
550 from_block: 1,
551 to_block: Some(100),
552 resume: None,
553 };
554 assert!(failure
555 .message()
556 .contains("exchange cursor state unavailable"),);
557 }
558}