toolkit_contract/runtime/
canonical.rs1use 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 TransportError::Overloaded => CanonicalError::service_unavailable()
47 .with_detail("client concurrency limit reached (request shed before send)")
48 .create(),
49 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 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 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 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 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 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 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 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}