Skip to main content

toolkit_contract/runtime/
canonical.rs

1//! Conversion from [`TransportError`] into [`toolkit_canonical_errors::CanonicalError`].
2//!
3//! Lives in `toolkit-contract` (not in `toolkit-canonical-errors`) so the
4//! canonical-errors crate stays a leaf in the workspace dep graph. Gated
5//! behind the `canonical-errors` feature.
6//!
7//! # Mapping policy
8//!
9//! When the peer participates in the canonical-errors envelope (RFC 9457
10//! `Problem` with a `gts://...` `type` URI, either inline on the HTTP
11//! response body or attached as the `x-toolkit-problem-bin` gRPC trailer),
12//! the typed `CanonicalError::*` variant is recovered via
13//! [`toolkit_canonical_errors::CanonicalError::try_from(Problem)`]. Resource
14//! info (`resource_type`, `resource_name`) is pulled out of
15//! `Problem.context` so callers can `matches!(err, CanonicalError::NotFound
16//! { .. })` after the conversion.
17//!
18//! Fallbacks for peers that don't speak the envelope:
19//! - [`TransportError::HttpStatus`]: resource-scoped statuses (404 / 409 /
20//!   403) construct the matching variant with `resource_type = "unknown"`
21//!   and `resource_name = "unknown"` via a synthetic `Problem`.
22//! - [`TransportError::Grpc`]: resource-scoped codes (`NotFound`,
23//!   `AlreadyExists`, `PermissionDenied`) likewise construct the matching
24//!   variant with synthetic "unknown" resource info.
25//! - Other categories (Internal, Unavailable, Unauthenticated, ...) map
26//!   directly via the canonical category mapping.
27
28use toolkit_canonical_errors::{CanonicalError, Problem, ProblemCategory};
29
30use crate::runtime::transport_error::TransportError;
31
32impl From<TransportError> for CanonicalError {
33    fn from(err: TransportError) -> Self {
34        match err {
35            TransportError::Problem { problem, .. } => problem_to_canonical(*problem),
36            TransportError::HttpStatus { status, body, .. } => {
37                http_status_to_canonical(status, &body)
38            }
39            #[cfg(feature = "grpc-client")]
40            TransportError::Grpc { code, message } => grpc_code_to_canonical(code, message),
41            TransportError::Network(_msg) => CanonicalError::service_unavailable().create(),
42            // The client's own concurrency limiter shed this request before it
43            // was sent: the local client is saturated. Surfaced as
44            // service-unavailable (the caller's dependency is momentarily
45            // overloaded), with the cause named in the detail.
46            TransportError::Overloaded => CanonicalError::service_unavailable()
47                .with_detail("client concurrency limit reached (request shed before send)")
48                .create(),
49            // Provider not registered / no live instance: same canonical shape
50            // as a network failure — retryable service-unavailable. Keep the
51            // gear name in the detail so operators can triage which dependency
52            // failed to resolve.
53            TransportError::Unresolved { gear } => CanonicalError::service_unavailable()
54                .with_detail(format!("provider `{gear}` is not resolvable"))
55                .create(),
56            TransportError::CircuitOpen { retry_after } => CanonicalError::service_unavailable()
57                .with_retry_after_seconds(retry_after.as_secs().max(1))
58                .with_detail("circuit breaker open: recent calls to the provider failed")
59                .create(),
60            TransportError::Timeout(d) => {
61                CanonicalError::internal(format!("timeout after {d:?}")).create()
62            }
63            TransportError::Serialization(msg) => {
64                CanonicalError::internal(format!("serialization error: {msg}")).create()
65            }
66            // A peer that does not conform to the wire framing is an internal
67            // fault; naming the framing is what makes the detail actionable.
68            TransportError::Framing { framing, source } => CanonicalError::internal(format!(
69                "{} framing error: {source}",
70                framing.media_type()
71            ))
72            .create(),
73            TransportError::UrlBuild(msg) => {
74                CanonicalError::internal(format!("URL build error: {msg}")).create()
75            }
76        }
77    }
78}
79
80fn problem_to_canonical(problem: Problem) -> CanonicalError {
81    // Falls back to 500 if `try_from` fails on a Problem with no status at
82    // all (only reachable from an SSE error event) - the safest guess when
83    // nothing else is known.
84    let status = problem.status.unwrap_or(500);
85    let title = problem.title.clone();
86    let detail = problem.detail.clone();
87    match CanonicalError::try_from(problem) {
88        Ok(err) => err,
89        Err(_) => http_status_to_canonical(status, &format!("{title}: {detail}")),
90    }
91}
92
93fn synth_problem(category: ProblemCategory, detail: &str) -> Problem {
94    Problem {
95        problem_type: format!("gts://{}", category.gts_fragment()),
96        title: category.title().to_owned(),
97        status: Some(category.http_status()),
98        detail: detail.to_owned(),
99        instance: None,
100        trace_id: None,
101        // Carry every field any synthesizable category's context needs.
102        // serde ignores unknown fields, so categories that don't use a given
103        // key (e.g. NotFound ignores `reason`, PermissionDenied ignores the
104        // resource fields) deserialize fine. `reason` is required by
105        // `PermissionDeniedV1`; omitting it made `synth_to_canonical` panic for
106        // 403 / gRPC PermissionDenied.
107        context: serde_json::json!({
108            "resource_type": "unknown",
109            "resource_name": "unknown",
110            "reason": detail,
111        }),
112        error_code: None,
113        error_domain: None,
114    }
115}
116
117#[allow(
118    clippy::expect_used,
119    reason = "synth_problem unconditionally constructs problem_type from ProblemCategory::canonical_type(), which is the canonical GTS URI registry — CanonicalError::try_from cannot fail for any input synth_problem can produce."
120)]
121fn synth_to_canonical(category: ProblemCategory, detail: &str) -> CanonicalError {
122    CanonicalError::try_from(synth_problem(category, detail))
123        .expect("synthetic problem_type is always a known canonical GTS URI")
124}
125
126fn http_status_to_canonical(status: u16, body: &str) -> CanonicalError {
127    // `body` is peer-controlled (arbitrary UTF-8); a raw `&body[..200]` byte
128    // slice panics if 200 lands inside a multi-byte character. Floor to the
129    // nearest char boundary at or below 200.
130    let preview: &str = if body.len() > 200 {
131        let cut = (0..=200)
132            .rev()
133            .find(|&i| body.is_char_boundary(i))
134            .unwrap_or(0);
135        &body[..cut]
136    } else {
137        body
138    };
139    match status {
140        401 => CanonicalError::unauthenticated()
141            .with_reason(preview.to_owned())
142            .create(),
143        403 => synth_to_canonical(ProblemCategory::PermissionDenied, preview),
144        404 => synth_to_canonical(ProblemCategory::NotFound, preview),
145        409 => synth_to_canonical(ProblemCategory::AlreadyExists, preview),
146        503 => CanonicalError::service_unavailable().create(),
147        s => CanonicalError::internal(format!("HTTP {s}: {preview}")).create(),
148    }
149}
150
151#[cfg(feature = "grpc-client")]
152fn grpc_code_to_canonical(code: tonic::Code, message: String) -> CanonicalError {
153    use tonic::Code;
154    match code {
155        Code::Unauthenticated => CanonicalError::unauthenticated()
156            .with_reason(message)
157            .create(),
158        Code::Unavailable => CanonicalError::service_unavailable().create(),
159        Code::NotFound => synth_to_canonical(ProblemCategory::NotFound, &message),
160        Code::AlreadyExists => synth_to_canonical(ProblemCategory::AlreadyExists, &message),
161        Code::PermissionDenied => synth_to_canonical(ProblemCategory::PermissionDenied, &message),
162        // The provider does not serve this RPC. Within one major version that
163        // means it runs an older minor release that predates the method.
164        Code::Unimplemented => synth_to_canonical(
165            ProblemCategory::Unimplemented,
166            &format!(
167                "provider does not implement this RPC; it may run an older minor version \
168                 of the contract ({message})"
169            ),
170        ),
171        other => CanonicalError::internal(format!("gRPC {other:?}: {message}")).create(),
172    }
173}
174
175#[cfg(test)]
176#[cfg_attr(coverage_nightly, coverage(off))]
177mod tests {
178    use super::*;
179
180    #[test]
181    fn problem_not_found_preserves_category() {
182        let original = toolkit_canonical_errors::Problem::from_error(
183            &CanonicalError::try_from(synth_problem(ProblemCategory::NotFound, "missing")).unwrap(),
184        )
185        .unwrap();
186        let err: CanonicalError = TransportError::problem(original).into();
187        assert!(matches!(err, CanonicalError::NotFound { .. }));
188    }
189
190    #[test]
191    fn http_404_fallback_yields_not_found() {
192        let err: CanonicalError = TransportError::HttpStatus {
193            status: 404,
194            body: "missing".into(),
195            retry_after: None,
196        }
197        .into();
198        assert!(matches!(err, CanonicalError::NotFound { .. }));
199    }
200
201    #[test]
202    fn http_status_to_canonical_does_not_panic_on_multibyte_char_at_boundary() {
203        // 199 ASCII bytes + a 3-byte UTF-8 char straddling byte 200 — a raw
204        // `&body[..200]` slice would panic since byte 200 falls inside it.
205        let body = format!("{}€", "a".repeat(199));
206        assert_eq!(body.len(), 202);
207        let err: CanonicalError = TransportError::HttpStatus {
208            status: 403,
209            body,
210            retry_after: None,
211        }
212        .into();
213        assert!(matches!(err, CanonicalError::PermissionDenied { .. }));
214    }
215
216    #[test]
217    fn overloaded_maps_to_service_unavailable_with_detail() {
218        // A locally-shed request (concurrency limiter) is surfaced as a
219        // retryable service-unavailable, with the shed named in the detail so
220        // operators can tell it apart from an upstream 503.
221        let err: CanonicalError = TransportError::Overloaded.into();
222        let problem = Problem::from_error(&err).expect("problem from overloaded");
223        assert_eq!(problem.status, Some(503));
224        assert!(
225            problem.detail.contains("concurrency limit reached"),
226            "detail names the shed: {}",
227            problem.detail
228        );
229    }
230
231    #[test]
232    fn http_403_fallback_yields_permission_denied() {
233        let err: CanonicalError = TransportError::HttpStatus {
234            status: 403,
235            body: "nope".into(),
236            retry_after: None,
237        }
238        .into();
239        assert!(matches!(err, CanonicalError::PermissionDenied { .. }));
240    }
241
242    #[test]
243    fn http_409_fallback_yields_already_exists() {
244        let err: CanonicalError = TransportError::HttpStatus {
245            status: 409,
246            body: "dup".into(),
247            retry_after: None,
248        }
249        .into();
250        assert!(matches!(err, CanonicalError::AlreadyExists { .. }));
251    }
252
253    #[cfg(feature = "grpc-client")]
254    #[test]
255    fn grpc_not_found_preserves_category() {
256        let err: CanonicalError = TransportError::Grpc {
257            code: tonic::Code::NotFound,
258            message: "missing".into(),
259        }
260        .into();
261        assert!(matches!(err, CanonicalError::NotFound { .. }));
262    }
263
264    #[cfg(feature = "grpc-client")]
265    #[test]
266    fn grpc_already_exists_preserves_category() {
267        let err: CanonicalError = TransportError::Grpc {
268            code: tonic::Code::AlreadyExists,
269            message: "dup".into(),
270        }
271        .into();
272        assert!(matches!(err, CanonicalError::AlreadyExists { .. }));
273    }
274
275    #[cfg(feature = "grpc-client")]
276    #[test]
277    fn grpc_permission_denied_preserves_category() {
278        let err: CanonicalError = TransportError::Grpc {
279            code: tonic::Code::PermissionDenied,
280            message: "nope".into(),
281        }
282        .into();
283        assert!(matches!(err, CanonicalError::PermissionDenied { .. }));
284    }
285}