Skip to main content

degenbot_cli_core/
error.rs

1//! Typed console failures and the single [`CliError`] → [`ExitCode`] mapping
2//! (ADR-051 D1).
3//!
4//! The workspace lint `exit = "deny"` forbids a library from aborting the host
5//! process: `run` returns codes. `EX_CONFIG` (78, sysexits) is the typed fleet
6//! boot refusal lifted out of `DegenbotCLI.invoke`.
7
8use 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/// The process exit code a command run maps to.
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub enum ExitCode {
18    /// `0`: the command completed (including a `--dry-run`, which writes nothing,
19    /// and a cooperative `Cancelled` run, whose committed chunks stay durable).
20    Success,
21    /// `1`: a typed command failure, including a declined confirmation (the click
22    /// `Abort` arm).
23    Failure,
24    /// `78` (sysexits `EX_CONFIG`): the typed fleet boot refusal — the host cannot
25    /// host the fleet configuration (FF-T1).
26    Config,
27}
28
29impl ExitCode {
30    /// The numeric process exit code.
31    #[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/// An unrecognized label for a closed variant set: the rejected input plus the
42/// known labels.
43#[derive(Debug, Clone, PartialEq, Eq)]
44pub struct UnknownVariant {
45    /// The rejected input, verbatim.
46    pub raw: String,
47    /// The known labels, in declaration order.
48    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/// One exchange's committed resume state, snapshotted read-only from the
65/// operator database's `exchanges.last_update_block` cursor column.
66#[derive(Debug, Clone, PartialEq, Eq)]
67pub struct ExchangeResumeState {
68    /// The `exchanges.name` slug.
69    pub name: String,
70    /// The committed cursor; `None` when the exchange was never updated.
71    pub last_update_block: Option<i64>,
72}
73
74/// A `pool update` (or `pool verify`) core failure plus the run context the
75/// arm held when the core returned it.
76///
77/// The bare library text (`api error: backend connection task has stopped`)
78/// alone is not an operator diagnostic, and the arm must not have to
79/// reconstruct the run's identity at the print site — so the payload carries
80/// it structurally: the endpoint, the chain, the requested block range, and,
81/// for a mid-run failure, the per-exchange resume state read out of the
82/// operator database. The updater commits per chunk, so a failed run keeps
83/// every committed chunk and leaves the remaining exchanges' outstanding
84/// work recorded in their cursors; the failure report makes it visible.
85#[derive(Debug)]
86pub struct PoolUpdateFailure {
87    /// The underlying core error.
88    pub error: PoolRunError,
89    /// The RPC endpoint the run was bound to.
90    pub rpc_url: String,
91    /// The chain the run advances.
92    pub chain_id: i64,
93    /// The first block the run intended to process (the earliest committed
94    /// cursor + 1; mirrors the core's own `initial_start_block`).
95    pub from_block: u64,
96    /// The requested upper bound; `None` when the run targeted the chain tip.
97    pub to_block: Option<u64>,
98    /// The post-failure per-exchange resume snapshot; `None` when the
99    /// read-only cursor read itself failed (or a non-run failure carried no
100    /// snapshot).
101    pub resume: Option<Vec<ExchangeResumeState>>,
102}
103
104impl PoolUpdateFailure {
105    /// The operator-facing failure text.
106    #[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    /// The range half of the failure line: `A-B`, or `A onward` for a tip run.
131    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    /// Whether the core error is the RPC-connection class — a dropped or
139    /// unreachable transport. The provider layer maps the transport's
140    /// `BackendGone` (and the rest of the connection class) onto the
141    /// `Connection failed` / `Request timeout` variants, which is what the
142    /// updater surfaces inside `PoolRunError::Provider`.
143    ///
144    /// The provider error's type is not nameable at this console layer (it
145    /// lives in `degenbot-core`, which the console does not depend on), so the
146    /// class is read off the stable `#[error]` prefixes that layer renders;
147    /// the variant boundary is still matched structurally.
148    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    /// The per-exchange resume lines: which exchanges are current, which are
155    /// behind, and which were never updated — the outstanding work a rerun
156    /// picks up from the recorded cursors.
157    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                // A run targeting the chain tip leaves unprocessed work in
177                // front of every cursor, so none is current at the target.
178                (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/// A typed console failure.
212///
213/// Every variant carries the data the argv facade needs to render the
214/// operator-facing line through [`CliError::message`]; rendering itself is the
215/// facade's job (ADR-051 Q1).
216#[derive(Debug)]
217pub enum CliError {
218    /// The typed fleet boot refusal (FF-T1). Exits `EX_CONFIG` 78.
219    BootRefused(String),
220    /// The operator declined a confirmation prompt — the click `Abort` arm.
221    Aborted,
222    /// The `database upgrade` subcommand is retired: the database upgrades itself
223    /// at open (ADR-052), and `database heal` is the explicit repair.
224    DatabaseUpgradeRetired,
225    /// The file is a foreign `SQLite` database — the arm refuses to adopt it.
226    DatabaseForeign,
227    /// The schema state offers nothing for this arm (e.g. `cutover` on an empty
228    /// file with no legacy history).
229    DatabaseNothingToDo,
230    /// Any other database failure (I/O, integrity, heal verification).
231    Database(DbError),
232    /// A filesystem failure outside the database (e.g. `database reset`
233    /// bootstrapping a missing state-home directory chain).
234    Io(std::io::Error),
235    /// Driver-domain config resolution failed (ADR-051 D8).
236    Config(ConfigError),
237    /// An unknown chain selector (`--chain foo`): the console names chain slugs
238    /// (`base`, `ethereum`) or numeric chain ids.
239    UnknownChain {
240        /// The rejected selector, verbatim.
241        chain: String,
242    },
243    /// The deployments registry has no record for the resolved
244    /// `(chain_id, name)` pair.
245    UnknownDeployment {
246        /// The resolved chain id.
247        chain_id: u64,
248        /// The DEX name slug (the `--name` value).
249        name: String,
250    },
251    /// A malformed block identifier — the exact `Invalid block tag: {tag}`
252    /// refusal the Python `_resolve_to_block` raises.
253    InvalidBlockTag(String),
254    /// The RPC read that resolves a `tag:offset` block identifier failed.
255    BlockResolution(String),
256    /// The supplied address does not parse (the click `Abort` arm of
257    /// `aave position show`).
258    InvalidAddress(String),
259    /// A required command argument is missing or malformed (`--pool-manager`
260    /// on `--family v4`, an out-of-range chain id).
261    InvalidArgument(String),
262    /// `aave update` found no active Aave markets (the Python
263    /// `DegenbotValueError`).
264    NoActiveAaveMarkets,
265    /// An `aave reset` target that no `aave_v3_markets` row matches. The reset
266    /// refuses rather than registering one: a mistyped market name must not
267    /// silently create a market to then wipe.
268    UnknownAaveMarket {
269        /// The resolved chain id.
270        chain_id: u64,
271        /// The requested market name.
272        market_name: String,
273    },
274    /// An `aave reset` target that another process may be mid-update. The reset
275    /// refuses rather than racing a concurrent writer's chunk.
276    AaveMarketMidUpdate {
277        /// The market id.
278        market_id: i64,
279        /// The distributor lock path another process holds.
280        lock_path: String,
281    },
282    /// A `pool update` / `pool verify` core failure (DB/RPC/cancelled/
283    /// verification), wrapped with the run context the arm held when the core
284    /// returned it (endpoint, chain, requested range, per-exchange resume
285    /// state) so the rendered diagnostic is complete.
286    ///
287    /// The payload is boxed to keep the variant out of the
288    /// `result_large_err` budget every arm's `Result` shares.
289    PoolUpdate(Box<PoolUpdateFailure>),
290    /// An `aave` core failure (DB/RPC/verification/market-not-found).
291    AaveUpdate(AaveRunError),
292    /// A command arm that `block_on`s the process-wide shared runtime was invoked
293    /// from inside an existing `tokio` runtime. `run_pool_update`/`run_aave_update`
294    /// ride `get_runtime()` and must not nest; the arms hold the same
295    /// constraint.
296    RuntimeNested,
297    /// The operator host refused a command: the `{"ok": false, "error": ...}`
298    /// frame, rendered as one line (ADR-051 D6).
299    OperatorRefused(String),
300    /// A protocol-level failure talking to the operator host: an unreachable
301    /// socket, a timed-out exchange, or a malformed/non-object/missing-`ok`
302    /// response frame.
303    OperatorProtocol(String),
304    /// A client-side wire-hygiene refusal (an unknown `cordon_*` key, an
305    /// empty posture patch, an unknown hop-family string), raised BEFORE the
306    /// socket is touched. Domain validation stays server-side.
307    OperatorHygiene(String),
308}
309
310impl CliError {
311    /// The operator-facing line for this failure.
312    #[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
385/// Map a database error onto its typed console failure.
386///
387/// A foreign-file failure stays typed here — the facade must be able to point
388/// the operator at the right remedy without string matching.
389impl 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
398/// Map a config-resolution error onto its typed console failure.
399impl From<ConfigError> for CliError {
400    fn from(err: ConfigError) -> Self {
401        Self::Config(err)
402    }
403}
404
405/// THE one `CliError → ExitCode` mapping site (ADR-051 D1).
406impl From<&CliError> for ExitCode {
407    fn from(err: &CliError) -> Self {
408        match err {
409            // FF-T1: the typed fleet boot refusal is the lone `EX_CONFIG` arm.
410            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    //! The pool-failure rendering (the `pool update` diagnostic).
446    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}