Skip to main content

camel_api/
error.rs

1use std::fmt;
2use std::sync::Arc;
3use thiserror::Error;
4
5/// Typed security-validation error for fail-closed config/startup checks (ADR-0033).
6///
7/// Each variant corresponds to a specific Batch 1+ security validation that refuses
8/// to start with a misconfigured or dangerous default. Operators can `match` on
9/// these variants for programmatic error handling.
10#[derive(Debug, Clone, PartialEq, Eq, Error)]
11#[non_exhaustive]
12pub enum ConfigValidationError {
13    #[error(
14        "aggregator config requires at least one completion bound (size, timeout, predicate, or interval)"
15    )]
16    AggregatorMissingCompletionBound,
17
18    /// Raised when an Aggregator has none of: max_buckets, a Timeout completion
19    /// condition, or a bucket_ttl. At least one memory-release bound is mandatory
20    /// (R3-M2) so a unique-correlation-key flood cannot grow the bucket map
21    /// without limit.
22    #[error("aggregator requires at least one of max_buckets, completionTimeout, or bucket_ttl")]
23    AggregatorMissingMemoryBound,
24
25    /// Raised when an Aggregator has a Timeout completion condition but no
26    /// `bucket_ttl`. The R3-M3 timeout-task cap may skip spawning a dedicated
27    /// timeout task under flood; without `bucket_ttl` there is no fallback
28    /// eviction path and the bucket leaks until shutdown. Requiring `bucket_ttl`
29    /// whenever Timeout is present makes the cap-skip degradation safe by
30    /// construction.
31    #[error(
32        "aggregator Timeout completion requires bucket_ttl (memory-release bound for the timeout-task cap fallback)"
33    )]
34    AggregatorTimeoutRequiresTtl,
35
36    #[error("throttler max_requests must be > 0")]
37    ThrottlerMaxRequestsZero,
38
39    #[error("loop step must specify either 'count' or 'while', not both")]
40    LoopConflictingCountAndWhile,
41
42    #[error("on_exceptions clause cannot set both steps and handled_by (delegation is exclusive)")]
43    OnExceptionStepsHandledByConflict,
44
45    #[error("loop step must specify either 'count' or 'while'")]
46    LoopMissingCountOrWhile,
47
48    #[error("SQL use_message_body_for_sql requires allow_dynamic_query=true")]
49    SqlDynamicQueryWithoutAllowDynamic,
50}
51
52/// Typed error for constructing an [`EndpointUri`](crate::EndpointUri) from a base URI
53/// plus a `parameters:` map.
54///
55/// Every variant names the offending key or input in its `Display` text so failures
56/// are diagnosable without losing the context of what was rejected.
57#[derive(Debug, Clone, PartialEq, Eq, Error)]
58#[non_exhaustive]
59pub enum EndpointUriError {
60    /// A `parameters:` key collides with a key already present in the base URI query.
61    #[error(
62        "endpoint URI parameter `{key}` duplicates a key already present in the base URI query"
63    )]
64    DuplicateKey { key: String },
65
66    /// The base URI has no non-empty scheme (no `:` before the path).
67    #[error("endpoint URI is missing a scheme (expected `scheme:path`)")]
68    MissingScheme,
69
70    /// The base URI query contains a pair with an empty key (e.g. `?=value`).
71    #[error("endpoint URI query contains a pair with an empty key")]
72    EmptyQueryKey,
73
74    /// A `parameters:` key is empty or contains a reserved/unsafe character.
75    #[error("endpoint URI parameter key `{key}` is empty or contains a reserved character")]
76    InvalidParamKey { key: String },
77}
78
79/// Classification of a language-expression evaluation failure.
80///
81/// Matchable class attached to [`CamelError::ExpressionFailed`] so route-level
82/// error handlers can discriminate failure kinds programmatically without
83/// parsing message text. Variants carry no data — diagnostics that need detail
84/// live on the `ExpressionFailed` variant itself.
85#[derive(Clone, Copy, Debug, PartialEq, Eq)]
86#[non_exhaustive]
87pub enum ExpressionErrorClass {
88    /// Evaluation failed at runtime (engine error not covered by a finer class).
89    Runtime,
90    /// Arithmetic failure (overflow, division by zero, NaN rejection, ...).
91    Arithmetic,
92    /// Value type does not match the expected type.
93    TypeMismatch,
94    /// Referenced function is not registered with the language engine.
95    FunctionNotFound,
96    /// A configured evaluation limit was exceeded.
97    Limit,
98    /// Evaluation exceeded its time budget.
99    Timeout,
100    /// The result or input body could not be converted to the declared destination type.
101    Conversion,
102    /// The expression or document source could not be parsed.
103    Parse,
104}
105
106impl ExpressionErrorClass {
107    /// Stable lowercase kebab-case name used in diagnostic messages.
108    pub fn as_str(&self) -> &'static str {
109        match self {
110            Self::Runtime => "runtime",
111            Self::Arithmetic => "arithmetic",
112            Self::TypeMismatch => "type-mismatch",
113            Self::FunctionNotFound => "function-not-found",
114            Self::Limit => "limit",
115            Self::Timeout => "timeout",
116            Self::Conversion => "conversion",
117            Self::Parse => "parse",
118        }
119    }
120}
121
122impl fmt::Display for ExpressionErrorClass {
123    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
124        f.write_str(self.as_str())
125    }
126}
127
128/// 1-based position inside the expression source text, as reported by the
129/// language engine. Not a route-definition position.
130#[derive(Clone, Copy, Debug, PartialEq, Eq)]
131pub struct ErrorPosition {
132    /// 1-based line inside the expression source.
133    pub line: u32,
134    /// 1-based column inside the expression source.
135    pub column: u32,
136}
137
138impl fmt::Display for ErrorPosition {
139    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
140        write!(f, "{}:{}", self.line, self.column)
141    }
142}
143
144/// Source and destination type names for a failed result conversion.
145///
146/// Both fields are TYPE NAMES (trusted config strings, e.g. `f64`,
147/// `property p`); runtime values never enter this struct.
148#[derive(Clone, Debug, PartialEq, Eq)]
149pub struct ConversionDetail {
150    /// Type name of the value the engine produced.
151    pub source_type: String,
152    /// Type name (or destination description) the value was converted to.
153    pub target: String,
154}
155
156/// Position suffix: `" at {line}:{column}"` when present, empty otherwise.
157fn expression_position_suffix(position: &Option<ErrorPosition>) -> String {
158    match position {
159        Some(pos) => format!(" at {pos}"),
160        None => String::new(),
161    }
162}
163
164/// Conversion suffix: `" while converting {source_type} to {target}"` when
165/// present, empty otherwise.
166fn expression_conversion_suffix(conversion: &Option<ConversionDetail>) -> String {
167    match conversion {
168        Some(detail) => format!(
169            " while converting {} to {}",
170            detail.source_type, detail.target
171        ),
172        None => String::new(),
173    }
174}
175
176/// Opaque handle to an underlying error, preserving its source chain without
177/// exposing the concrete type.
178///
179/// The opacity contract: the pointee is reachable only through
180/// [`std::error::Error::source()`] (returned directly — no `Arc` wrapper hop),
181/// the inner handle is private, there is no public `Clone`, and provenance
182/// cannot be extracted outside camel-api (short of `unsafe`). Crate internals
183/// duplicate the handle via `OpaqueErrorSource::clone_handle` when cloning a
184/// [`CamelError`].
185///
186/// # Examples
187///
188/// The inner handle cannot be destructured out of the wrapper (private field):
189///
190/// ```compile_fail
191/// use camel_api::OpaqueErrorSource;
192///
193/// #[derive(Debug)]
194/// struct MyError;
195///
196/// impl std::fmt::Display for MyError {
197///     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
198///         f.write_str("my error")
199///     }
200/// }
201///
202/// impl std::error::Error for MyError {}
203///
204/// let OpaqueErrorSource(inner) = OpaqueErrorSource::new(std::sync::Arc::new(MyError));
205/// ```
206///
207/// The wrapper is deliberately not `Clone`, so callers cannot copy the handle
208/// out of camel-api:
209///
210/// ```compile_fail
211/// use camel_api::OpaqueErrorSource;
212///
213/// #[derive(Debug)]
214/// struct MyError;
215///
216/// impl std::fmt::Display for MyError {
217///     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
218///         f.write_str("my error")
219///     }
220/// }
221///
222/// impl std::error::Error for MyError {}
223///
224/// let s = OpaqueErrorSource::new(std::sync::Arc::new(MyError));
225/// let _ = s.clone();
226/// ```
227#[derive(Debug)]
228pub struct OpaqueErrorSource(Arc<dyn std::error::Error + Send + Sync>);
229
230impl OpaqueErrorSource {
231    /// Wrap an existing error as an opaque source.
232    pub fn new(source: Arc<dyn std::error::Error + Send + Sync>) -> Self {
233        Self(source)
234    }
235
236    /// Duplicate the inner handle for the manual `Clone` impl on
237    /// [`CamelError`]. Crate-private by design: the wrapper itself is not
238    /// `Clone`, so external code cannot duplicate provenance out of camel-api.
239    fn clone_handle(&self) -> Self {
240        Self(Arc::clone(&self.0))
241    }
242}
243
244impl fmt::Display for OpaqueErrorSource {
245    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
246        self.0.fmt(f)
247    }
248}
249
250impl std::error::Error for OpaqueErrorSource {
251    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
252        // Pointee directly — NO Arc wrapper hop, so `downcast_ref` on the
253        // returned trait object reaches the wrapped error itself.
254        Some(self.0.as_ref())
255    }
256}
257
258/// Structured diagnostics payload whose `Debug` never prints its contents.
259///
260/// Wraps a [`serde_json::Value`] while redacting it from every `Debug`
261/// rendering, so accidental structured logging of a [`CamelError::Business`]
262/// cannot leak exchange data. Structural comparison (`PartialEq`/`Eq`) and
263/// cloning still go through the wrapped value; the payload is reachable only
264/// through the explicit [`RedactedJson::as_value`] accessor.
265///
266/// # Examples
267///
268/// ```
269/// use camel_api::RedactedJson;
270///
271/// let data = RedactedJson::new(serde_json::json!({"secret": "hunter2"}));
272/// assert_eq!(format!("{data:?}"), "[redacted]");
273/// assert_eq!(data.as_value()["secret"], "hunter2");
274/// ```
275#[derive(Clone, PartialEq, Eq)]
276pub struct RedactedJson(serde_json::Value);
277
278impl RedactedJson {
279    /// Wrap a JSON value as redacted diagnostics.
280    pub fn new(value: serde_json::Value) -> Self {
281        Self(value)
282    }
283
284    /// Borrow the wrapped value for internal consumers (Simple evaluator,
285    /// HTTP error mapping), which must not render it through `Debug`.
286    pub fn as_value(&self) -> &serde_json::Value {
287        &self.0
288    }
289}
290
291impl fmt::Debug for RedactedJson {
292    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
293        f.write_str("[redacted]")
294    }
295}
296
297/// Core error type for the Camel framework.
298#[derive(Debug, Error)]
299#[non_exhaustive]
300pub enum CamelError {
301    #[error("Component not found: {0}")]
302    ComponentNotFound(String),
303
304    #[error("Endpoint creation failed: {0}")]
305    EndpointCreationFailed(String),
306
307    /// Like `EndpointCreationFailed` but preserves the source error chain
308    /// for downstream inspection (e.g. typed gate-rejection classification).
309    #[error("Endpoint creation failed: {0}")]
310    EndpointCreationFailedWithSource(String, #[source] OpaqueErrorSource),
311
312    #[error("Processor error: {0}")]
313    ProcessorError(String),
314
315    /// Like `ProcessorError` but preserves the source error chain
316    /// for downstream inspection (e.g. via `std::error::Error::source()`).
317    #[error("Processor error: {0}")]
318    ProcessorErrorWithSource(String, #[source] Arc<dyn std::error::Error + Send + Sync>),
319
320    #[error("Type conversion failed: {0}")]
321    TypeConversionFailed(String),
322
323    #[error("Invalid URI: {0}")]
324    InvalidUri(String),
325
326    #[error("Channel closed")]
327    ChannelClosed,
328
329    #[error("Route error: {0}")]
330    RouteError(String),
331
332    #[error("IO error: {0}")]
333    Io(String),
334
335    #[error("Dead letter channel failed: {0}")]
336    DeadLetterChannelFailed(String),
337
338    #[error("Circuit breaker open: {0}")]
339    CircuitOpen(String),
340
341    #[error("HTTP {method} {url} failed: {status_code} {status_text}")]
342    HttpOperationFailed {
343        method: String,
344        url: String,
345        status_code: u16,
346        status_text: String,
347        response_body: Option<String>,
348    },
349
350    /// Producer `call()` failed on a shutdown signal — the consumer/semaphore
351    /// is closing and the producer cannot acquire a permit. Distinct from Stop EIP
352    /// (which is successful control flow). Used by JMS/OpenSearch producers. See ADR-0024.
353    #[error("Consumer stopping: semaphore closed during call")]
354    ConsumerStopping,
355
356    #[error("Configuration error: {0}")]
357    Config(String),
358
359    /// Typed security-validation error (ADR-0033). Promotes Batch 1+ config/startup
360    /// failure modes from stringly-typed `Config(_)` to a matchable enum so
361    /// operators can discriminate programmatically.
362    #[error("Configuration validation error: {0}")]
363    ConfigValidation(ConfigValidationError),
364
365    #[error("Body stream has already been consumed")]
366    AlreadyConsumed,
367
368    #[error("Stream size exceeded limit: {0}")]
369    StreamLimitExceeded(usize),
370
371    #[error("Unauthenticated: {0}")]
372    Unauthenticated(String),
373
374    #[error("Unauthorized: {0}")]
375    Unauthorized(String),
376
377    /// Auth provider (JWKS/introspection/token endpoint) is unreachable or failing.
378    /// Promotes the auth-provider-down signal from a stringly-typed ProcessorError to
379    /// a matchable variant; WebSocket and gRPC transports map it to 503 / UNAVAILABLE.
380    #[error("Auth provider unavailable: {0}")]
381    AuthProviderUnavailable(String),
382
383    #[error("Validation failed: {0}")]
384    ValidationError(String),
385
386    #[error("Template reload failed: {0}")]
387    TemplateReload(String),
388
389    /// Typed endpoint-URI construction error (see [`EndpointUriError`]). Promotes the
390    /// fail-closed `EndpointUri` merge failures from stringly-typed errors to a matchable
391    /// variant so operators can discriminate programmatically.
392    #[error("Endpoint URI error: {0}")]
393    EndpointUri(EndpointUriError),
394
395    /// The request body media type does not match the declared/consumed type
396    /// (REST DSL default-strict content negotiation, HTTP 415).
397    #[error("Unsupported media type: consumed {consumed}, declared {declared}")]
398    UnsupportedMediaType { consumed: String, declared: String },
399
400    /// The response representation cannot satisfy the client's Accept header
401    /// (REST DSL default-strict content negotiation, HTTP 406).
402    #[error("Not acceptable: accept {accept}, produced {produced}")]
403    NotAcceptable { accept: String, produced: String },
404
405    /// Evaluation of a language expression failed during a route step
406    /// (language-value-boundary spec). All fields are route metadata and typed
407    /// diagnostics — no exchange data enters any field or the Display output.
408    #[error(
409        "expression failed: {class} in {language} `{verb}` step `{step_id}` (route `{route_id}`){}{}",
410        expression_position_suffix(.position),
411        expression_conversion_suffix(.conversion),
412    )]
413    ExpressionFailed {
414        /// Language the failing expression was written in (e.g. `rhai`).
415        language: String,
416        /// Id of the route that owned the failing step.
417        route_id: String,
418        /// Id of the failing step.
419        step_id: String,
420        /// DSL verb that evaluated the expression (e.g. `set_property`).
421        verb: String,
422        /// Typed failure classification.
423        class: ExpressionErrorClass,
424        /// Position inside the expression source, when the engine reports one.
425        position: Option<ErrorPosition>,
426        /// Failed result-conversion detail, when the failure was a conversion.
427        conversion: Option<ConversionDetail>,
428        /// Chained underlying error, when the failure wraps another
429        /// [`CamelError`] (e.g. a catch predicate failure chaining the
430        /// original route error).
431        #[source]
432        cause: Option<Box<CamelError>>,
433    },
434
435    /// Business (domain) failure raised by the `throw` step or a component that
436    /// classifies a failure as a client/domain fault.
437    ///
438    /// # Constructor contract
439    ///
440    /// - `code` and `kind` must be non-blank. Validation happens at the
441    ///   builders' boundaries (route load for the `throw` step); the variant
442    ///   itself makes no runtime guarantee.
443    /// - `message` is log-and-diagnostics only: it never reaches a client
444    ///   through any mapping, disposition, or configuration, and it is
445    ///   deliberately absent from the `Display` rendering.
446    /// - `data` holds optional structured diagnostics as a [`RedactedJson`]:
447    ///   its `Debug` prints `[redacted]`, so accidental structured logging
448    ///   cannot leak the payload.
449    #[error("business error {code} ({kind})")]
450    Business {
451        /// Stable machine-readable error code (e.g. `ORDER_NOT_FOUND`).
452        code: String,
453        /// Business kind used by `on_exceptions` / catch matchers (default
454        /// `failed` at the `throw` boundary).
455        kind: String,
456        /// Human-readable log-only summary; never sent to a client.
457        message: String,
458        /// Redacted structured diagnostics; never rendered by `Debug`.
459        data: Option<RedactedJson>,
460    },
461
462    /// Typed transaction failure from the `transacted { datasource }` port
463    /// (sql-transactions capability). Carries the offender and datasource so
464    /// operators can discriminate programmatically.
465    #[error(transparent)]
466    Transaction(#[from] crate::transaction::TransactionError),
467}
468
469/// Manual `Clone` impl: every arm clones its fields normally, except
470/// `EndpointCreationFailedWithSource`, which duplicates the opaque source
471/// handle via the crate-private `OpaqueErrorSource::clone_handle` (the wrapper
472/// itself is deliberately not `Clone`). Exhaustive like `variant_name()` — a
473/// new variant without an arm fails compilation.
474impl Clone for CamelError {
475    fn clone(&self) -> Self {
476        match self {
477            Self::ComponentNotFound(msg) => Self::ComponentNotFound(msg.clone()),
478            Self::EndpointCreationFailed(msg) => Self::EndpointCreationFailed(msg.clone()),
479            Self::EndpointCreationFailedWithSource(msg, source) => {
480                Self::EndpointCreationFailedWithSource(msg.clone(), source.clone_handle())
481            }
482            Self::ProcessorError(msg) => Self::ProcessorError(msg.clone()),
483            Self::ProcessorErrorWithSource(msg, source) => {
484                Self::ProcessorErrorWithSource(msg.clone(), Arc::clone(source))
485            }
486            Self::TypeConversionFailed(msg) => Self::TypeConversionFailed(msg.clone()),
487            Self::InvalidUri(msg) => Self::InvalidUri(msg.clone()),
488            Self::ChannelClosed => Self::ChannelClosed,
489            Self::RouteError(msg) => Self::RouteError(msg.clone()),
490            Self::Io(msg) => Self::Io(msg.clone()),
491            Self::DeadLetterChannelFailed(msg) => Self::DeadLetterChannelFailed(msg.clone()),
492            Self::CircuitOpen(msg) => Self::CircuitOpen(msg.clone()),
493            Self::HttpOperationFailed {
494                method,
495                url,
496                status_code,
497                status_text,
498                response_body,
499            } => Self::HttpOperationFailed {
500                method: method.clone(),
501                url: url.clone(),
502                status_code: *status_code,
503                status_text: status_text.clone(),
504                response_body: response_body.clone(),
505            },
506            Self::ConsumerStopping => Self::ConsumerStopping,
507            Self::Config(msg) => Self::Config(msg.clone()),
508            Self::ConfigValidation(e) => Self::ConfigValidation(e.clone()),
509            Self::AlreadyConsumed => Self::AlreadyConsumed,
510            Self::StreamLimitExceeded(limit) => Self::StreamLimitExceeded(*limit),
511            Self::Unauthenticated(msg) => Self::Unauthenticated(msg.clone()),
512            Self::Unauthorized(msg) => Self::Unauthorized(msg.clone()),
513            Self::AuthProviderUnavailable(msg) => Self::AuthProviderUnavailable(msg.clone()),
514            Self::ValidationError(msg) => Self::ValidationError(msg.clone()),
515            Self::TemplateReload(msg) => Self::TemplateReload(msg.clone()),
516            Self::EndpointUri(e) => Self::EndpointUri(e.clone()),
517            Self::UnsupportedMediaType { consumed, declared } => Self::UnsupportedMediaType {
518                consumed: consumed.clone(),
519                declared: declared.clone(),
520            },
521            Self::NotAcceptable { accept, produced } => Self::NotAcceptable {
522                accept: accept.clone(),
523                produced: produced.clone(),
524            },
525            Self::ExpressionFailed {
526                language,
527                route_id,
528                step_id,
529                verb,
530                class,
531                position,
532                conversion,
533                cause,
534            } => Self::ExpressionFailed {
535                language: language.clone(),
536                route_id: route_id.clone(),
537                step_id: step_id.clone(),
538                verb: verb.clone(),
539                class: *class,
540                position: *position,
541                conversion: conversion.clone(),
542                cause: cause.clone(),
543            },
544            Self::Business {
545                code,
546                kind,
547                message,
548                data,
549            } => Self::Business {
550                code: code.clone(),
551                kind: kind.clone(),
552                message: message.clone(),
553                data: data.clone(),
554            },
555            Self::Transaction(e) => Self::Transaction(e.clone()),
556        }
557    }
558}
559
560/// Classification marker for `CamelError::CircuitOpen`.
561///
562/// Shared named constant so the pipeline tracer's circuit-open exclusion
563/// (skip `increment_errors` — the breaker already recorded the rejection)
564/// and `classify` itself cannot drift apart (dashboard-observability D2).
565pub const CIRCUIT_OPEN: &str = "circuit_open";
566
567impl CamelError {
568    pub fn classify(&self) -> &'static str {
569        #[allow(unreachable_patterns)]
570        match self {
571            Self::ComponentNotFound(_) => "component",
572            Self::EndpointCreationFailed(_)
573            | Self::EndpointCreationFailedWithSource(_, _)
574            | Self::InvalidUri(_)
575            | Self::EndpointUri(_) => "endpoint",
576            Self::ProcessorError(_)
577            | Self::ProcessorErrorWithSource(_, _)
578            | Self::AuthProviderUnavailable(_) => "processor",
579            Self::TypeConversionFailed(_) | Self::AlreadyConsumed => "type_conversion",
580            Self::Io(_) => "io",
581            Self::RouteError(_) => "route",
582            Self::CircuitOpen(_) => CIRCUIT_OPEN,
583            Self::HttpOperationFailed { .. } => "http",
584            Self::Config(_) | Self::ConfigValidation(_) => "config",
585            Self::DeadLetterChannelFailed(_) => "dead_letter",
586            Self::ConsumerStopping => "consumer_stop",
587            Self::StreamLimitExceeded(_) => "stream",
588            Self::ChannelClosed => "channel",
589            Self::Unauthenticated(_) => "unauthenticated",
590            Self::Unauthorized(_) => "unauthorized",
591            Self::ValidationError(_) => "validation",
592            Self::TemplateReload(_) => "template",
593            Self::UnsupportedMediaType { .. } => "unsupported_media_type",
594            Self::NotAcceptable { .. } => "not_acceptable",
595            Self::Business { .. } => "business",
596            Self::Transaction(_) => "transaction",
597            _ => "unknown",
598        }
599    }
600
601    /// Stable variant name used by `doTry` catch-by-variant matchers.
602    ///
603    /// `ProcessorErrorWithSource` and `AuthProviderUnavailable` alias to
604    /// `"ProcessorError"`, and `EndpointCreationFailedWithSource` aliases to
605    /// `"EndpointCreationFailed"` — the aliased variants are not distinguishable
606    /// by name in MVP (see spec §5.4), so existing `doTry` catch handlers keep
607    /// matching.
608    ///
609    /// The enum is `#[non_exhaustive]`; this match lives in the defining crate (camel-api),
610    /// so internal exhaustive matching is allowed. Adding a new variant without updating
611    /// this method will fail to compile, surfaced by `variant_name_tests`.
612    pub fn variant_name(&self) -> &'static str {
613        match self {
614            Self::ComponentNotFound(_) => "ComponentNotFound",
615            Self::EndpointCreationFailed(_) => "EndpointCreationFailed",
616            Self::EndpointCreationFailedWithSource(_, _) => "EndpointCreationFailed",
617            Self::ProcessorError(_) => "ProcessorError",
618            Self::ProcessorErrorWithSource(_, _) => "ProcessorError",
619            Self::AuthProviderUnavailable(_) => "ProcessorError",
620            Self::TypeConversionFailed(_) => "TypeConversionFailed",
621            Self::InvalidUri(_) => "InvalidUri",
622            Self::ChannelClosed => "ChannelClosed",
623            Self::RouteError(_) => "RouteError",
624            Self::Io(_) => "Io",
625            Self::DeadLetterChannelFailed(_) => "DeadLetterChannelFailed",
626            Self::CircuitOpen(_) => "CircuitOpen",
627            Self::HttpOperationFailed { .. } => "HttpOperationFailed",
628            Self::ConsumerStopping => "ConsumerStopping",
629            Self::Config(_) => "Config",
630            Self::ConfigValidation(_) => "ConfigValidation",
631            Self::AlreadyConsumed => "AlreadyConsumed",
632            Self::StreamLimitExceeded(_) => "StreamLimitExceeded",
633            Self::Unauthenticated(_) => "Unauthenticated",
634            Self::Unauthorized(_) => "Unauthorized",
635            Self::ValidationError(_) => "ValidationError",
636            Self::TemplateReload(_) => "TemplateReload",
637            Self::EndpointUri(_) => "EndpointUri",
638            Self::UnsupportedMediaType { .. } => "UnsupportedMediaType",
639            Self::NotAcceptable { .. } => "NotAcceptable",
640            Self::ExpressionFailed { .. } => "ExpressionFailed",
641            Self::Business { .. } => "Business",
642            Self::Transaction(_) => "Transaction",
643        }
644    }
645}
646
647impl From<std::io::Error> for CamelError {
648    fn from(err: std::io::Error) -> Self {
649        CamelError::Io(err.to_string())
650    }
651}
652
653impl From<crate::template::TemplateError> for CamelError {
654    fn from(err: crate::template::TemplateError) -> Self {
655        CamelError::Config(err.to_string())
656    }
657}
658
659impl From<ConfigValidationError> for CamelError {
660    fn from(e: ConfigValidationError) -> Self {
661        CamelError::ConfigValidation(e)
662    }
663}
664
665impl From<EndpointUriError> for CamelError {
666    fn from(e: EndpointUriError) -> Self {
667        CamelError::EndpointUri(e)
668    }
669}
670
671/// Boxed trait-object error used by Tower middleware (`Service::Error`).
672pub type BoxError = std::boxed::Box<dyn std::error::Error + Send + Sync + 'static>;
673
674/// Returns `true` when an [`tower::timeout::error::Elapsed`] appears anywhere
675/// in the source chain rooted at `err`.
676///
677/// The walk starts at `err` itself: `TimeoutLayer` boxes a bare `Elapsed` with
678/// no wrapper, so skipping the root would miss the common timeout case.
679fn source_chain_contains_elapsed(err: &(dyn std::error::Error + 'static)) -> bool {
680    let mut current = Some(err);
681    while let Some(source) = current {
682        if source
683            .downcast_ref::<tower::timeout::error::Elapsed>()
684            .is_some()
685        {
686            return true;
687        }
688        current = std::error::Error::source(source);
689    }
690    false
691}
692
693/// Converts a boxed middleware error into a [`CamelError`].
694///
695/// A boxed [`CamelError`] passes through unchanged. This keeps native exception
696/// matching and fault classification intact after a middleware hop instead of
697/// double-wrapping it as a processor error.
698///
699/// Any other boxed error becomes [`CamelError::ProcessorErrorWithSource`] with
700/// the original error preserved as the source, so the chain stays inspectable.
701/// A Tower timeout anywhere in the chain (not only at its root) is reported as
702/// a middleware timeout.
703///
704/// The payload is an [`OpaqueErrorSource`] around the `Arc`, not a bare `Arc`.
705/// With a bare `Arc` the chain would skip the pointee: thiserror's generated
706/// `source()` delegates through std's forwarding `Error for Arc<T>` impl to the
707/// pointee's own `source()`. The wrapper instead returns the pointee DIRECTLY
708/// from its own `source()`, with no `Arc` hop, so the concrete error is the
709/// FIRST node of the public chain — `err.source()` already yields it, and
710/// `downcast_ref` reaches it at hop 1 (e.g.
711/// `tower::timeout::error::Elapsed`).
712///
713/// # Examples
714///
715/// A boxed [`CamelError`] is returned unchanged:
716///
717/// ```
718/// use std::error::Error;
719///
720/// use camel_api::error::CamelError;
721///
722/// let boxed: Box<dyn Error + Send + Sync> = Box::new(CamelError::InvalidUri("u".into()));
723/// match CamelError::from(boxed) {
724///     CamelError::InvalidUri(uri) => assert_eq!(uri, "u"),
725///     other => panic!("expected pass-through, got {other:?}"),
726/// }
727/// ```
728///
729/// A timeout nested in the source chain is classified as a middleware timeout,
730/// and the source is preserved:
731///
732/// ```
733/// use std::error::Error;
734///
735/// use camel_api::error::CamelError;
736/// use tower::timeout::error::Elapsed;
737///
738/// #[derive(Debug)]
739/// struct TimedOut(Elapsed);
740///
741/// impl std::fmt::Display for TimedOut {
742///     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
743///         f.write_str("middleware call timed out")
744///     }
745/// }
746///
747/// impl Error for TimedOut {
748///     fn source(&self) -> Option<&(dyn Error + 'static)> {
749///         Some(&self.0)
750///     }
751/// }
752///
753/// let boxed: Box<dyn Error + Send + Sync> = Box::new(TimedOut(Elapsed::new()));
754/// let err = CamelError::from(boxed);
755/// assert!(err.to_string().contains("middleware timeout elapsed"));
756///
757/// let mut source = err.source();
758/// let mut reached_elapsed = false;
759/// while let Some(inner) = source {
760///     if inner.downcast_ref::<Elapsed>().is_some() {
761///         reached_elapsed = true;
762///         break;
763///     }
764///     source = inner.source();
765/// }
766/// assert!(reached_elapsed, "source chain must reach the original Elapsed");
767/// ```
768impl From<BoxError> for CamelError {
769    fn from(err: BoxError) -> Self {
770        // Pass a native CamelError through untouched: double-wrapping it would
771        // break doTry catch-by-variant matching and fault classification.
772        match err.downcast::<CamelError>() {
773            Ok(camel_error) => *camel_error,
774            Err(err) => {
775                let message = if source_chain_contains_elapsed(err.as_ref()) {
776                    "middleware timeout elapsed"
777                } else {
778                    "middleware error"
779                };
780                CamelError::ProcessorErrorWithSource(
781                    message.to_string(),
782                    Arc::new(OpaqueErrorSource::new(Arc::from(err))),
783                )
784            }
785        }
786    }
787}
788
789#[cfg(test)]
790mod tests {
791    use super::*;
792    // `super::*` brings in thiserror's `Error` derive macro; import the trait
793    // anonymously so `source()` is callable in tests.
794    use std::error::Error as _;
795
796    /// Minimal source error for opaque-provenance tests.
797    #[derive(Debug)]
798    struct SampleSource;
799
800    impl fmt::Display for SampleSource {
801        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
802            f.write_str("sample source")
803        }
804    }
805
806    impl std::error::Error for SampleSource {}
807
808    /// Wrapper whose only source is a tower timeout [`Elapsed`], used to prove
809    /// the `BoxError` conversion walks the whole source chain.
810    ///
811    /// [`Elapsed`]: tower::timeout::error::Elapsed
812    #[derive(Debug)]
813    struct ElapsedSourcedError(tower::timeout::error::Elapsed);
814
815    impl fmt::Display for ElapsedSourcedError {
816        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
817            f.write_str("wrapped middleware failure")
818        }
819    }
820
821    impl std::error::Error for ElapsedSourcedError {
822        fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
823            Some(&self.0)
824        }
825    }
826
827    #[test]
828    fn boxed_camel_error_passthrough_unchanged() {
829        let boxed: Box<dyn std::error::Error + Send + Sync> =
830            Box::<dyn std::error::Error + Send + Sync>::from(CamelError::InvalidUri(
831                "u".to_string(),
832            ));
833        let err = CamelError::from(boxed);
834        match err {
835            CamelError::InvalidUri(uri) => assert_eq!(uri, "u"),
836            other => panic!("expected InvalidUri passthrough, got {other:?}"),
837        }
838    }
839
840    /// Asserts a tower [`Elapsed`] is reachable through the public
841    /// [`std::error::Error::source`] chain within `max_hops` hops.
842    ///
843    /// This is the real consumer path: the `ProcessorErrorWithSource` payload is
844    /// opaque, so callers can only walk `source()` and `downcast_ref`.
845    ///
846    /// [`Elapsed`]: tower::timeout::error::Elapsed
847    fn assert_elapsed_within_source_hops(err: &CamelError, max_hops: usize) {
848        let mut current = err.source();
849        for _ in 0..max_hops {
850            let Some(node) = current else { break };
851            if node
852                .downcast_ref::<tower::timeout::error::Elapsed>()
853                .is_some()
854            {
855                return;
856            }
857            current = node.source();
858        }
859        panic!("source chain does not reach tower Elapsed within {max_hops} hops: {err:?}");
860    }
861
862    #[test]
863    fn timeout_error_classified_through_source_chain() {
864        let boxed: Box<dyn std::error::Error + Send + Sync> =
865            Box::new(ElapsedSourcedError(tower::timeout::error::Elapsed::new()));
866        let err = CamelError::from(boxed);
867        assert!(
868            err.to_string().contains("middleware timeout elapsed"),
869            "unexpected display: {err}"
870        );
871        assert_elapsed_within_source_hops(&err, 3);
872    }
873
874    #[test]
875    fn bare_elapsed_root_error_classified_as_timeout() {
876        // Mirrors probe P4: `TimeoutLayer` boxes a bare `Elapsed` at the chain
877        // root, with no wrapper error to walk through. The `OpaqueErrorSource`
878        // payload still surfaces it as a downcastable chain node (hop 1).
879        let boxed: Box<dyn std::error::Error + Send + Sync> =
880            Box::new(tower::timeout::error::Elapsed::new());
881        let err = CamelError::from(boxed);
882        assert!(
883            err.to_string().contains("middleware timeout elapsed"),
884            "unexpected display: {err}"
885        );
886        assert_elapsed_within_source_hops(&err, 3);
887    }
888
889    #[test]
890    #[allow(clippy::io_other_error)]
891    fn plain_box_error_preserves_source() {
892        let boxed: Box<dyn std::error::Error + Send + Sync> =
893            Box::new(std::io::Error::new(std::io::ErrorKind::Other, "boom"));
894        let err = CamelError::from(boxed);
895        match &err {
896            CamelError::ProcessorErrorWithSource(message, _) => {
897                assert!(
898                    message.contains("middleware error"),
899                    "unexpected message: {message}"
900                );
901            }
902            other => panic!("expected ProcessorErrorWithSource, got {other:?}"),
903        }
904        let source = err
905            .source()
906            .expect("ProcessorErrorWithSource carries a source");
907        assert_eq!(source.to_string(), "boom");
908    }
909
910    fn all_error_samples() -> Vec<CamelError> {
911        vec![
912            CamelError::ComponentNotFound("x".to_string()),
913            CamelError::EndpointCreationFailed("x".to_string()),
914            CamelError::EndpointCreationFailedWithSource(
915                "x".to_string(),
916                OpaqueErrorSource::new(Arc::new(SampleSource)),
917            ),
918            CamelError::ProcessorError("x".to_string()),
919            CamelError::ProcessorErrorWithSource(
920                "x".to_string(),
921                Arc::new(std::io::Error::other("inner")),
922            ),
923            CamelError::TypeConversionFailed("x".to_string()),
924            CamelError::InvalidUri("x".to_string()),
925            CamelError::ChannelClosed,
926            CamelError::RouteError("x".to_string()),
927            CamelError::Io("x".to_string()),
928            CamelError::DeadLetterChannelFailed("x".to_string()),
929            CamelError::CircuitOpen("x".to_string()),
930            CamelError::HttpOperationFailed {
931                method: "GET".to_string(),
932                url: "https://example.com".to_string(),
933                status_code: 500,
934                status_text: "Internal Server Error".to_string(),
935                response_body: Some("error".to_string()),
936            },
937            CamelError::ConsumerStopping,
938            CamelError::Config("x".to_string()),
939            CamelError::ConfigValidation(ConfigValidationError::ThrottlerMaxRequestsZero),
940            CamelError::AlreadyConsumed,
941            CamelError::StreamLimitExceeded(42),
942            CamelError::Unauthenticated("token expired".to_string()),
943            CamelError::Unauthorized("missing admin role".to_string()),
944            CamelError::AuthProviderUnavailable("jwks down".to_string()),
945            CamelError::ValidationError("body does not match schema".to_string()),
946            CamelError::TemplateReload("reload failed".to_string()),
947            CamelError::EndpointUri(EndpointUriError::MissingScheme),
948            CamelError::UnsupportedMediaType {
949                consumed: "text/plain".to_string(),
950                declared: "application/json".to_string(),
951            },
952            CamelError::NotAcceptable {
953                accept: "application/xml".to_string(),
954                produced: "application/json".to_string(),
955            },
956        ]
957    }
958
959    #[test]
960    fn test_http_operation_failed_display() {
961        let err = CamelError::HttpOperationFailed {
962            method: "GET".to_string(),
963            url: "https://example.com/test".to_string(),
964            status_code: 404,
965            status_text: "Not Found".to_string(),
966            response_body: Some("page not found".to_string()),
967        };
968        let msg = format!("{err}");
969        assert!(msg.contains("404"));
970        assert!(msg.contains("Not Found"));
971    }
972
973    #[test]
974    fn test_http_operation_failed_clone() {
975        let err = CamelError::HttpOperationFailed {
976            method: "POST".to_string(),
977            url: "https://api.example.com/users".to_string(),
978            status_code: 500,
979            status_text: "Internal Server Error".to_string(),
980            response_body: None,
981        };
982        let cloned = err.clone();
983        assert!(matches!(
984            cloned,
985            CamelError::HttpOperationFailed {
986                status_code: 500,
987                ..
988            }
989        ));
990    }
991
992    #[test]
993    fn test_classify_maps_all_variants() {
994        assert_eq!(
995            CamelError::ComponentNotFound("x".to_string()).classify(),
996            "component"
997        );
998        assert_eq!(
999            CamelError::EndpointCreationFailed("x".to_string()).classify(),
1000            "endpoint"
1001        );
1002        assert_eq!(
1003            CamelError::ProcessorError("x".to_string()).classify(),
1004            "processor"
1005        );
1006        assert_eq!(
1007            CamelError::TypeConversionFailed("x".to_string()).classify(),
1008            "type_conversion"
1009        );
1010        assert_eq!(
1011            CamelError::InvalidUri("x".to_string()).classify(),
1012            "endpoint"
1013        );
1014        assert_eq!(CamelError::ChannelClosed.classify(), "channel");
1015        assert_eq!(CamelError::RouteError("x".to_string()).classify(), "route");
1016        assert_eq!(CamelError::Io("x".to_string()).classify(), "io");
1017        assert_eq!(
1018            CamelError::DeadLetterChannelFailed("x".to_string()).classify(),
1019            "dead_letter"
1020        );
1021        assert_eq!(
1022            CamelError::CircuitOpen("x".to_string()).classify(),
1023            "circuit_open"
1024        );
1025        assert_eq!(
1026            CamelError::HttpOperationFailed {
1027                method: "GET".to_string(),
1028                url: "https://example.com".to_string(),
1029                status_code: 500,
1030                status_text: "Internal Server Error".to_string(),
1031                response_body: None,
1032            }
1033            .classify(),
1034            "http"
1035        );
1036        assert_eq!(CamelError::Config("x".to_string()).classify(), "config");
1037        assert_eq!(
1038            CamelError::ConfigValidation(ConfigValidationError::ThrottlerMaxRequestsZero)
1039                .classify(),
1040            "config"
1041        );
1042        assert_eq!(CamelError::AlreadyConsumed.classify(), "type_conversion");
1043        assert_eq!(CamelError::StreamLimitExceeded(42).classify(), "stream");
1044        assert_eq!(
1045            CamelError::ValidationError("bad".to_string()).classify(),
1046            "validation"
1047        );
1048    }
1049
1050    #[test]
1051    fn test_classify_output_is_ascii_and_short() {
1052        for error in all_error_samples() {
1053            let class = error.classify();
1054            assert!(class.is_ascii());
1055            // "unsupported_media_type" (REST negotiation, L2) sets the floor at 22
1056            assert!(class.len() <= 22, "class too long: {class}");
1057        }
1058    }
1059
1060    #[test]
1061    fn test_auth_variants_classify() {
1062        assert_eq!(
1063            CamelError::Unauthenticated("x".to_string()).classify(),
1064            "unauthenticated"
1065        );
1066        assert_eq!(
1067            CamelError::Unauthorized("x".to_string()).classify(),
1068            "unauthorized"
1069        );
1070    }
1071
1072    #[test]
1073    fn test_validation_error_classify() {
1074        assert_eq!(
1075            CamelError::ValidationError("bad".to_string()).classify(),
1076            "validation"
1077        );
1078    }
1079
1080    #[test]
1081    fn template_reload_classifies_as_template() {
1082        let err = CamelError::TemplateReload("boom".into());
1083        assert_eq!(err.classify(), "template");
1084    }
1085
1086    #[test]
1087    fn template_reload_variant_name() {
1088        let err = CamelError::TemplateReload("boom".into());
1089        assert_eq!(err.variant_name(), "TemplateReload");
1090    }
1091
1092    #[test]
1093    fn test_auth_variants_are_clone() {
1094        let err = CamelError::Unauthenticated("test".to_string());
1095        let cloned = err.clone();
1096        assert!(matches!(cloned, CamelError::Unauthenticated(_)));
1097
1098        let err2 = CamelError::Unauthorized("test".to_string());
1099        let cloned2 = err2.clone();
1100        assert!(matches!(cloned2, CamelError::Unauthorized(_)));
1101    }
1102
1103    #[test]
1104    fn classification_unchanged_for_callers() {
1105        // Pins the contract the pipeline-tracer circuit_open exclusion
1106        // relies on (dashboard-observability D2): CircuitOpen must keep
1107        // classifying as "circuit_open" — callers and the tracer skip
1108        // branch match on exactly this literal.
1109        assert_eq!(
1110            CamelError::CircuitOpen("breaker open".into()).classify(),
1111            "circuit_open"
1112        );
1113    }
1114
1115    #[test]
1116    fn auth_provider_unavailable_display_carries_detail() {
1117        let err = CamelError::AuthProviderUnavailable("conn refused".into());
1118        let msg = err.to_string();
1119        assert!(msg.contains("conn refused"));
1120        assert!(
1121            msg.starts_with("Auth provider unavailable"),
1122            "display should start with 'Auth provider unavailable', got: {msg}"
1123        );
1124    }
1125
1126    #[test]
1127    fn classify_negotiation_errors() {
1128        let unsupported = CamelError::UnsupportedMediaType {
1129            consumed: "text/plain".into(),
1130            declared: "application/json".into(),
1131        };
1132        let not_acceptable = CamelError::NotAcceptable {
1133            accept: "application/xml".into(),
1134            produced: "application/json".into(),
1135        };
1136        assert_eq!(unsupported.classify(), "unsupported_media_type");
1137        assert_eq!(not_acceptable.classify(), "not_acceptable");
1138    }
1139
1140    #[test]
1141    fn variant_names_negotiation_errors() {
1142        let unsupported = CamelError::UnsupportedMediaType {
1143            consumed: "text/plain".into(),
1144            declared: "application/json".into(),
1145        };
1146        let not_acceptable = CamelError::NotAcceptable {
1147            accept: "application/xml".into(),
1148            produced: "application/json".into(),
1149        };
1150        assert_eq!(unsupported.variant_name(), "UnsupportedMediaType");
1151        assert_eq!(not_acceptable.variant_name(), "NotAcceptable");
1152    }
1153
1154    #[test]
1155    fn error_classification_label_is_pinned() {
1156        // Pins `classify()` labels for every variant the ADR-0096 fault-blame
1157        // change touches, so a silent label move fails here first.
1158        let type_conversion = CamelError::TypeConversionFailed(String::new());
1159        let validation = CamelError::ValidationError(String::new());
1160        let unsupported = CamelError::UnsupportedMediaType {
1161            consumed: String::new(),
1162            declared: String::new(),
1163        };
1164        let not_acceptable = CamelError::NotAcceptable {
1165            accept: String::new(),
1166            produced: String::new(),
1167        };
1168        let unauthenticated = CamelError::Unauthenticated(String::new());
1169        let unauthorized = CamelError::Unauthorized(String::new());
1170        let processor_with_source = CamelError::ProcessorErrorWithSource(
1171            String::new(),
1172            Arc::new(std::io::Error::other("inner")),
1173        );
1174        let consumer_stopping = CamelError::ConsumerStopping;
1175
1176        assert_eq!(
1177            type_conversion.classify(),
1178            "type_conversion",
1179            "TypeConversionFailed must classify as type_conversion (ADR-0096)"
1180        );
1181        assert_eq!(
1182            validation.classify(),
1183            "validation",
1184            "ValidationError must classify as validation"
1185        );
1186        assert_eq!(
1187            unsupported.classify(),
1188            "unsupported_media_type",
1189            "UnsupportedMediaType must classify as unsupported_media_type"
1190        );
1191        assert_eq!(
1192            not_acceptable.classify(),
1193            "not_acceptable",
1194            "NotAcceptable must classify as not_acceptable"
1195        );
1196        assert_eq!(
1197            unauthenticated.classify(),
1198            "unauthenticated",
1199            "Unauthenticated must classify as unauthenticated"
1200        );
1201        assert_eq!(
1202            unauthorized.classify(),
1203            "unauthorized",
1204            "Unauthorized must classify as unauthorized"
1205        );
1206        assert_eq!(
1207            processor_with_source.classify(),
1208            "processor",
1209            "ProcessorErrorWithSource must classify as processor"
1210        );
1211        assert_eq!(
1212            consumer_stopping.classify(),
1213            "consumer_stop",
1214            "ConsumerStopping must classify as consumer_stop"
1215        );
1216    }
1217
1218    #[test]
1219    fn display_negotiation_errors() {
1220        let unsupported = CamelError::UnsupportedMediaType {
1221            consumed: "text/plain".into(),
1222            declared: "application/json".into(),
1223        };
1224        let not_acceptable = CamelError::NotAcceptable {
1225            accept: "application/xml".into(),
1226            produced: "application/json".into(),
1227        };
1228        let unsupported_msg = unsupported.to_string();
1229        assert!(unsupported_msg.contains("text/plain"));
1230        assert!(unsupported_msg.contains("application/json"));
1231        let not_acceptable_msg = not_acceptable.to_string();
1232        assert!(not_acceptable_msg.contains("application/xml"));
1233        assert!(not_acceptable_msg.contains("application/json"));
1234    }
1235
1236    #[test]
1237    fn expression_failed_display_has_no_exchange_data() {
1238        let err = CamelError::ExpressionFailed {
1239            language: "rhai".to_string(),
1240            route_id: "r1".to_string(),
1241            step_id: "set_property#0".to_string(),
1242            verb: "set_property".to_string(),
1243            class: ExpressionErrorClass::Arithmetic,
1244            position: Some(ErrorPosition { line: 3, column: 8 }),
1245            conversion: None,
1246            cause: None,
1247        };
1248        let msg = err.to_string();
1249        assert!(msg.contains("arithmetic"), "missing class: {msg}");
1250        assert!(msg.contains("rhai"), "missing language: {msg}");
1251        assert!(msg.contains("set_property"), "missing verb/step: {msg}");
1252        assert!(msg.contains("3:8"), "missing position: {msg}");
1253        // Nothing beyond the metadata fields: the full rendering is pinned.
1254        assert_eq!(
1255            msg,
1256            "expression failed: arithmetic in rhai `set_property` step \
1257             `set_property#0` (route `r1`) at 3:8"
1258        );
1259    }
1260
1261    #[test]
1262    fn expression_failed_variant_name() {
1263        let err = CamelError::ExpressionFailed {
1264            language: "rhai".to_string(),
1265            route_id: "r1".to_string(),
1266            step_id: "set_property#0".to_string(),
1267            verb: "set_property".to_string(),
1268            class: ExpressionErrorClass::Runtime,
1269            position: None,
1270            conversion: None,
1271            cause: None,
1272        };
1273        assert_eq!(err.variant_name(), "ExpressionFailed");
1274    }
1275
1276    #[test]
1277    fn config_validation_error_on_exception_conflict_display() {
1278        let err = ConfigValidationError::OnExceptionStepsHandledByConflict;
1279        let msg = format!("{err}");
1280        assert!(msg.contains("steps"));
1281        assert!(msg.contains("handled_by"));
1282        assert!(msg.contains("exclusive"));
1283    }
1284
1285    #[test]
1286    fn opaque_error_source_exposes_only_pointee() {
1287        let src = OpaqueErrorSource::new(Arc::new(SampleSource));
1288        let pointee = src.source().unwrap();
1289        assert!(pointee.downcast_ref::<SampleSource>().is_some());
1290    }
1291
1292    #[test]
1293    fn endpoint_creation_failed_with_source_aliases_to_plain() {
1294        let e = CamelError::EndpointCreationFailedWithSource(
1295            "d".to_string(),
1296            OpaqueErrorSource::new(Arc::new(SampleSource)),
1297        );
1298        assert_eq!(e.variant_name(), "EndpointCreationFailed");
1299        assert_eq!(e.classify(), "endpoint");
1300        assert_eq!(e.to_string(), "Endpoint creation failed: d");
1301    }
1302
1303    #[test]
1304    fn clone_preserves_variant_identity_for_all_error_samples() {
1305        for e in all_error_samples() {
1306            let c = e.clone();
1307            assert_eq!(c.variant_name(), e.variant_name());
1308            assert_eq!(c.classify(), e.classify());
1309            assert_eq!(c.to_string(), e.to_string());
1310        }
1311    }
1312
1313    #[test]
1314    fn camel_error_clone_preserves_source_provenance() {
1315        let e = CamelError::EndpointCreationFailedWithSource(
1316            "d".to_string(),
1317            OpaqueErrorSource::new(Arc::new(SampleSource)),
1318        );
1319        let c = e.clone();
1320        // `CamelError::source()` (thiserror #[source]) yields the wrapper
1321        // itself; the pointee is one more `source()` hop away — that hop is
1322        // the pointee-only mechanism under test (no Arc wrapper in between).
1323        let wrapper = c.source().unwrap();
1324        let pointee = wrapper.source().unwrap();
1325        assert!(pointee.downcast_ref::<SampleSource>().is_some());
1326    }
1327}
1328
1329#[cfg(test)]
1330mod variant_name_tests {
1331    use super::{
1332        CamelError, ConfigValidationError, EndpointUriError, ExpressionErrorClass,
1333        OpaqueErrorSource, RedactedJson,
1334    };
1335    use std::sync::Arc;
1336
1337    /// Representative value for each enum variant. This test fails to compile
1338    /// when a new variant is added to CamelError without updating variant_name().
1339    /// The enum is `#[non_exhaustive]` but this match lives in the same crate, so internal
1340    /// exhaustive matching is allowed.
1341    ///
1342    /// The table must list every variant exactly once (`cases.len()` is asserted
1343    /// below). When adding a CamelError variant, also update
1344    /// `test_exception_kind_vocabulary_classification_guard` in
1345    /// crates/camel-dsl/src/compile.rs and make the register-or-document
1346    /// decision (bd rc-5u8co).
1347    #[test]
1348    fn variant_name_covers_all_variants() {
1349        let cases: Vec<(CamelError, &str)> = vec![
1350            (
1351                CamelError::ComponentNotFound("x".into()),
1352                "ComponentNotFound",
1353            ),
1354            (
1355                CamelError::EndpointCreationFailed("x".into()),
1356                "EndpointCreationFailed",
1357            ),
1358            (
1359                CamelError::EndpointCreationFailedWithSource(
1360                    "x".into(),
1361                    OpaqueErrorSource::new(Arc::new(std::io::Error::other("y"))),
1362                ),
1363                "EndpointCreationFailed", // aliased
1364            ),
1365            (CamelError::ProcessorError("x".into()), "ProcessorError"),
1366            (
1367                CamelError::ProcessorErrorWithSource(
1368                    "x".into(),
1369                    Arc::new(std::io::Error::other("y")),
1370                ),
1371                "ProcessorError", // aliased
1372            ),
1373            (
1374                CamelError::TypeConversionFailed("x".into()),
1375                "TypeConversionFailed",
1376            ),
1377            (CamelError::InvalidUri("x".into()), "InvalidUri"),
1378            (CamelError::ChannelClosed, "ChannelClosed"),
1379            (CamelError::RouteError("x".into()), "RouteError"),
1380            (CamelError::Io("x".into()), "Io"),
1381            (
1382                CamelError::DeadLetterChannelFailed("x".into()),
1383                "DeadLetterChannelFailed",
1384            ),
1385            (CamelError::CircuitOpen("x".into()), "CircuitOpen"),
1386            (
1387                CamelError::HttpOperationFailed {
1388                    method: "GET".into(),
1389                    url: "https://example.com".into(),
1390                    status_code: 500,
1391                    status_text: "Internal Server Error".into(),
1392                    response_body: None,
1393                },
1394                "HttpOperationFailed",
1395            ),
1396            (CamelError::ConsumerStopping, "ConsumerStopping"),
1397            (CamelError::Config("x".into()), "Config"),
1398            (
1399                CamelError::ConfigValidation(ConfigValidationError::ThrottlerMaxRequestsZero),
1400                "ConfigValidation",
1401            ),
1402            (CamelError::AlreadyConsumed, "AlreadyConsumed"),
1403            (CamelError::StreamLimitExceeded(42), "StreamLimitExceeded"),
1404            (CamelError::Unauthenticated("x".into()), "Unauthenticated"),
1405            (CamelError::Unauthorized("x".into()), "Unauthorized"),
1406            (CamelError::ValidationError("bad".into()), "ValidationError"),
1407            (CamelError::TemplateReload("x".into()), "TemplateReload"),
1408            (
1409                CamelError::EndpointUri(EndpointUriError::MissingScheme),
1410                "EndpointUri",
1411            ),
1412            (
1413                CamelError::UnsupportedMediaType {
1414                    consumed: "text/plain".into(),
1415                    declared: "application/json".into(),
1416                },
1417                "UnsupportedMediaType",
1418            ),
1419            (
1420                CamelError::NotAcceptable {
1421                    accept: "application/xml".into(),
1422                    produced: "application/json".into(),
1423                },
1424                "NotAcceptable",
1425            ),
1426            (
1427                CamelError::ExpressionFailed {
1428                    language: "rhai".into(),
1429                    route_id: "r1".into(),
1430                    step_id: "set_property#0".into(),
1431                    verb: "set_property".into(),
1432                    class: ExpressionErrorClass::Runtime,
1433                    position: None,
1434                    conversion: None,
1435                    cause: None,
1436                },
1437                "ExpressionFailed",
1438            ),
1439            (
1440                CamelError::AuthProviderUnavailable("x".into()),
1441                "ProcessorError",
1442            ),
1443            (
1444                CamelError::Business {
1445                    code: "ORDER_NOT_FOUND".into(),
1446                    kind: "not-found".into(),
1447                    message: "m".into(),
1448                    data: None,
1449                },
1450                "Business",
1451            ),
1452            (
1453                CamelError::Transaction(crate::transaction::TransactionError::ManagerMissing {
1454                    datasource: "pg".into(),
1455                }),
1456                "Transaction",
1457            ),
1458        ];
1459
1460        assert_eq!(
1461            cases.len(),
1462            29,
1463            "variant_name_covers_all_variants must cover every CamelError variant; \
1464             extend this table and the camel-dsl classification guard"
1465        );
1466
1467        for (err, expected) in cases {
1468            assert_eq!(
1469                err.variant_name(),
1470                expected,
1471                "variant_name mismatch for {:?}",
1472                err
1473            );
1474        }
1475    }
1476
1477    #[test]
1478    fn classify_and_variant_name_business() {
1479        let err = CamelError::Business {
1480            code: "ORDER_NOT_FOUND".to_string(),
1481            kind: "not-found".to_string(),
1482            message: "m".to_string(),
1483            data: None,
1484        };
1485
1486        assert_eq!(err.classify(), "business");
1487        assert_eq!(err.variant_name(), "Business");
1488    }
1489
1490    #[test]
1491    fn debug_on_data_newtype_redacts() {
1492        let data = RedactedJson::new(serde_json::json!({"secret": "hunter2"}));
1493        let err = CamelError::Business {
1494            code: "ORDER_NOT_FOUND".to_string(),
1495            kind: "not-found".to_string(),
1496            message: "m".to_string(),
1497            data: Some(data.clone()),
1498        };
1499
1500        let rendered = format!("{err:?}");
1501        assert!(
1502            rendered.contains("[redacted]"),
1503            "missing redaction marker: {rendered}"
1504        );
1505        assert!(!rendered.contains("hunter2"), "data leaked: {rendered}");
1506        assert_eq!(format!("{data:?}"), "[redacted]");
1507        // Redaction must not weaken structural equality of the payload.
1508        assert_eq!(
1509            data,
1510            RedactedJson::new(serde_json::json!({"secret": "hunter2"}))
1511        );
1512    }
1513
1514    #[test]
1515    fn display_includes_code_and_kind_but_redacts_message_and_data() {
1516        let err = CamelError::Business {
1517            code: "ORDER_NOT_FOUND".to_string(),
1518            kind: "not-found".to_string(),
1519            message: "secret-message".to_string(),
1520            data: Some(RedactedJson::new(serde_json::json!({"secret": "hunter2"}))),
1521        };
1522
1523        let rendered = format!("{err}");
1524        assert!(
1525            rendered.contains("ORDER_NOT_FOUND"),
1526            "Display must include the code: {rendered}"
1527        );
1528        assert!(
1529            rendered.contains("not-found"),
1530            "Display must include the kind: {rendered}"
1531        );
1532        assert!(
1533            !rendered.contains("secret-message"),
1534            "Display leaked the log-only message: {rendered}"
1535        );
1536        assert!(
1537            !rendered.contains("hunter2"),
1538            "Display leaked the data payload: {rendered}"
1539        );
1540    }
1541
1542    #[test]
1543    fn auth_provider_unavailable_classifies_as_processor() {
1544        let err = CamelError::AuthProviderUnavailable("jwks down".into());
1545        assert_eq!(err.classify(), "processor");
1546    }
1547
1548    #[test]
1549    fn auth_provider_unavailable_variant_name_aliases_processor_error() {
1550        let err = CamelError::AuthProviderUnavailable("jwks down".into());
1551        assert_eq!(err.variant_name(), "ProcessorError");
1552    }
1553}