Skip to main content

appcore_gateway/
failure_diagnostic.rs

1// =============================================================================
2//        #######
3//     ###       ###     F: failure_diagnostic.rs
4//    ##   ## ##   ##    P: AppCore-Runtime
5//         ## ##
6//                       C: 2026/10/12 00:00:00 by dnettoRaw
7//    ##   ## ##   ##    U: 2026/10/12 00:00:00 by dnettoRaw
8//      ###########      S: 1.0.2-rc
9// =============================================================================
10
11//! Controlled Gateway route evidence without raw provider/authentication detail.
12use crate::{GatewayError, WorkerSelectionError};
13use serde::Serialize;
14
15/// Stable local Gateway failure categories; no route or protocol alias is added.
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
17#[serde(rename_all = "snake_case")]
18#[non_exhaustive]
19pub enum GatewayFailureCodeV1 {
20    /// Invalid deployment configuration.
21    Configuration,
22    /// Authentication rejected; sensitive cause remains local.
23    Authentication,
24    /// Authenticated caller lacks authorization.
25    Authorization,
26    /// Authenticated partition identity does not match.
27    TenantMismatch,
28    /// Coarse routing evidence does not distinguish absent/unhealthy workers.
29    WorkerUnavailable,
30    /// No worker advertises the selected capability.
31    WorkerAbsent,
32    /// Known workers are disconnected or unhealthy.
33    WorkerUnhealthy,
34    /// Healthy workers are at their explicit capacity limit.
35    CapacityExceeded,
36    /// Route transport is unavailable; acknowledgement may be ambiguous.
37    TransportUnavailable,
38    /// Bounded request serialization failed.
39    InvalidPayload,
40    /// Selected protocol or envelope is invalid.
41    Protocol,
42    /// Underlying Runtime rejected the operation; inspect local typed evidence.
43    Runtime,
44}
45/// Safe route diagnostic. Tenant authorization remains the exporter's boundary.
46#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
47pub struct GatewayFailureDiagnosticV1 {
48    schema_version: u16,
49    code: GatewayFailureCodeV1,
50    correlation_id: Option<String>,
51    retryable: bool,
52}
53impl GatewayFailureDiagnosticV1 {
54    /// Preserves a typed worker selection outcome before it is flattened to text.
55    /// A retry hint never permits replay of an ambiguously acknowledged command.
56    pub fn from_selection(error: &WorkerSelectionError, correlation: Option<&str>) -> Self {
57        use GatewayFailureCodeV1 as Code;
58        let code = match error {
59            WorkerSelectionError::CapabilityUnavailable => Code::WorkerAbsent,
60            WorkerSelectionError::NoHealthyWorker => Code::WorkerUnhealthy,
61            WorkerSelectionError::AtCapacity => Code::CapacityExceeded,
62            WorkerSelectionError::InvalidAffinity | WorkerSelectionError::InvalidLimits => {
63                Code::Configuration
64            }
65        };
66        Self::new(code, correlation)
67    }
68    fn new(code: GatewayFailureCodeV1, correlation: Option<&str>) -> Self {
69        Self {
70            schema_version: 1,
71            code,
72            correlation_id: correlation
73                .filter(|id| {
74                    !id.is_empty()
75                        && id.len() <= 128
76                        && id.bytes().all(|byte| {
77                            byte.is_ascii_alphanumeric()
78                                || matches!(byte, b'.' | b'_' | b'-' | b':')
79                        })
80                })
81                .map(str::to_owned),
82            retryable: matches!(
83                code,
84                GatewayFailureCodeV1::WorkerUnhealthy
85                    | GatewayFailureCodeV1::CapacityExceeded
86                    | GatewayFailureCodeV1::TransportUnavailable
87            ),
88        }
89    }
90    /// Stable code, suitable for operational projection/UI classification.
91    pub fn code(&self) -> GatewayFailureCodeV1 {
92        self.code
93    }
94    /// Whether an independently safe higher-level operation may retry under a budget.
95    pub fn retryable(&self) -> bool {
96        self.retryable
97    }
98}
99impl GatewayError {
100    /// Produces controlled evidence without parsing or exporting raw error strings.
101    pub fn diagnostic_v1(&self, correlation: Option<&str>) -> GatewayFailureDiagnosticV1 {
102        use GatewayFailureCodeV1 as Code;
103        let code = match self {
104            Self::Config(_) => Code::Configuration,
105            Self::Authentication(_) => Code::Authentication,
106            Self::Forbidden(_) => Code::Authorization,
107            Self::TenantMismatch(_) => Code::TenantMismatch,
108            Self::WorkerUnavailable(_) => Code::WorkerUnavailable,
109            Self::Transport(_) => Code::TransportUnavailable,
110            Self::Serialization(_) => Code::InvalidPayload,
111            Self::Protocol(_) => Code::Protocol,
112            Self::Runtime(_) => Code::Runtime,
113        };
114        GatewayFailureDiagnosticV1::new(code, correlation)
115    }
116}
117#[cfg(test)]
118mod tests {
119    use super::*;
120    #[test]
121    fn preserves_selection_and_correlation_without_raw_error_detail() {
122        let absent = GatewayFailureDiagnosticV1::from_selection(
123            &WorkerSelectionError::CapabilityUnavailable,
124            Some("request-a"),
125        );
126        assert_eq!(absent.code(), GatewayFailureCodeV1::WorkerAbsent);
127        assert!(!absent.retryable());
128        let busy =
129            GatewayFailureDiagnosticV1::from_selection(&WorkerSelectionError::AtCapacity, None);
130        assert!(busy.retryable());
131        let diagnostic =
132            GatewayError::Authentication("private-marker".into()).diagnostic_v1(Some("request-a"));
133        let encoded = serde_json::to_string(&diagnostic).unwrap();
134        assert!(encoded.contains("request-a"));
135        assert!(!encoded.contains("private-marker"));
136    }
137}