toolkit_contract/runtime/transport_error.rs
1//! `TransportError` — uniform transport-layer error surfaced by generated
2//! REST clients.
3//!
4//! The wire envelope is `toolkit_canonical_errors::Problem` (RFC 9457) when
5//! the peer participates in the canonical error system. Older peers may
6//! return raw HTTP status codes without a Problem body — those land in
7//! [`TransportError::HttpStatus`].
8
9#[cfg(feature = "canonical-errors")]
10use toolkit_canonical_errors::Problem;
11
12/// Errors produced by the generated REST client transport layer.
13#[derive(Debug, thiserror::Error)]
14#[non_exhaustive]
15pub enum TransportError {
16 /// The server returned a structured RFC 9457 `Problem` payload.
17 #[cfg(feature = "canonical-errors")]
18 #[error("server returned problem: {} ({})", .problem.title, .problem.status.map_or_else(|| "unknown".to_owned(), |s| s.to_string()))]
19 Problem {
20 /// The structured RFC 9457 problem payload. Boxed: `Problem` itself is
21 /// large enough (several `String`/`Value` fields) that an unboxed copy
22 /// here would make `TransportError` — and therefore every
23 /// `Result<_, TransportError>` return type across the crate — bloat
24 /// past clippy's `result_large_err` threshold.
25 problem: Box<Problem>,
26 /// Server-advised minimum wait before retry, parsed from the
27 /// `Retry-After` response header (delta-seconds), when present. Carried
28 /// alongside the `Problem` so in-mesh peers that speak canonical errors
29 /// still get their advised backoff honored by the retry loop.
30 retry_after: Option<std::time::Duration>,
31 },
32
33 /// The server returned a non-success status with a non-Problem body.
34 #[error("HTTP {status}: {body}")]
35 HttpStatus {
36 /// Numeric HTTP status code.
37 status: u16,
38 /// Body excerpt suitable for diagnostics. Truncated at the call site.
39 body: String,
40 /// Server-advised minimum wait before retry, parsed from the
41 /// `Retry-After` response header (delta-seconds), when present. The
42 /// retry loop honors this in preference to computed backoff.
43 retry_after: Option<std::time::Duration>,
44 },
45
46 /// The gRPC server returned a non-OK status. Preserves the original
47 /// `tonic::Code` so callers can map it back to canonical categories
48 /// without losing information through an HTTP-status detour.
49 #[cfg(feature = "grpc-client")]
50 #[error("gRPC {code:?}: {message}")]
51 Grpc {
52 /// The raw gRPC status code as returned by the server.
53 code: tonic::Code,
54 /// Human-readable detail copied from `tonic::Status::message`.
55 message: String,
56 },
57
58 /// Low-level network failure (DNS, connect, TLS, mid-flight reset).
59 #[error("network error: {0}")]
60 Network(#[source] Box<dyn std::error::Error + Send + Sync + 'static>),
61
62 /// The client-side concurrency limiter shed this request before it left the
63 /// process: more than `max_concurrent_requests`
64 /// ([`ClientConfig::max_concurrent_requests`](crate::runtime::config::ClientConfig::max_concurrent_requests))
65 /// were already in flight.
66 ///
67 /// Deliberately **not** transient (see [`Self::is_transient`]): the request
68 /// never reached the network, so re-issuing it — especially with backoff on
69 /// an already-saturated client — would only add load. Distinct from
70 /// [`Network`](Self::Network) so a caller can tell a locally-shed request
71 /// (never sent) apart from a mid-flight reset (maybe sent).
72 #[error("client concurrency limit reached (request shed before send)")]
73 Overloaded,
74
75 /// The total deadline elapsed before the response was complete.
76 #[error("timeout after {0:?}")]
77 Timeout(std::time::Duration),
78
79 /// Request or response (de)serialization failure.
80 #[error("serialization error: {0}")]
81 Serialization(#[source] Box<dyn std::error::Error + Send + Sync + 'static>),
82
83 /// Streaming framing-protocol error: the peer's bytes do not conform to
84 /// the wire framing in use — a malformed SSE frame, a bad multipart
85 /// delimiter or part header, a part length that overruns its delimiter, an
86 /// accumulation guard trip.
87 ///
88 /// Distinct from [`TransportError::Serialization`], which is a
89 /// well-framed frame or part whose *payload* would not decode.
90 ///
91 /// Replaces an earlier SSE-only variant: naming the framing is what keeps
92 /// a fault attributable once more than one framing exists, so there is
93 /// deliberately no framing-specific variant to reach for instead.
94 #[error("{} framing error: {source}", framing.media_type())]
95 Framing {
96 /// Which wire framing produced the fault.
97 framing: crate::ir::binding::StreamFraming,
98 /// Underlying cause.
99 #[source]
100 source: Box<dyn std::error::Error + Send + Sync + 'static>,
101 },
102
103 /// URL construction error (missing path parameter, invalid template).
104 #[error("URL build error: {0}")]
105 UrlBuild(String),
106
107 /// The providing gear could not be resolved to a live endpoint via the
108 /// service directory: it has not registered yet, or every instance was
109 /// evicted (e.g., the provider pod went away). Treated as transient — the
110 /// directory-resolving client re-resolves on the next call and recovers
111 /// once a live instance reappears.
112 #[error("provider `{gear}` is not resolvable (not ready or no live instance)")]
113 Unresolved {
114 /// Logical gear name that could not be resolved to an endpoint.
115 gear: String,
116 },
117
118 /// The client's circuit breaker is open for this endpoint: recent calls
119 /// failed at the transport level, so this one was refused without being
120 /// sent. Not transient within one call — retrying it at once would only be
121 /// refused again; callers see `service_unavailable` with `retry_after`.
122 #[error("circuit breaker open; retry after {} ms", retry_after.as_millis())]
123 CircuitOpen {
124 /// Time until the breaker lets a probe through.
125 retry_after: std::time::Duration,
126 },
127}
128
129impl TransportError {
130 /// Convenience constructor for [`TransportError::Network`] from any
131 /// boxable error. Preserves the source via `Error::source()`.
132 pub fn network<E>(err: E) -> Self
133 where
134 E: Into<Box<dyn std::error::Error + Send + Sync + 'static>>,
135 {
136 Self::Network(err.into())
137 }
138
139 /// Convenience constructor for [`TransportError::Serialization`] from any
140 /// boxable error. Preserves the source via `Error::source()`.
141 pub fn serialization<E>(err: E) -> Self
142 where
143 E: Into<Box<dyn std::error::Error + Send + Sync + 'static>>,
144 {
145 Self::Serialization(err.into())
146 }
147
148 /// Convenience constructor for [`TransportError::Framing`] from any
149 /// boxable error. Preserves the source via `Error::source()`.
150 pub fn framing<E>(framing: crate::ir::binding::StreamFraming, err: E) -> Self
151 where
152 E: Into<Box<dyn std::error::Error + Send + Sync + 'static>>,
153 {
154 Self::Framing {
155 framing,
156 source: err.into(),
157 }
158 }
159
160 /// Convenience constructor for [`TransportError::Unresolved`].
161 pub fn unresolved(gear: impl Into<String>) -> Self {
162 Self::Unresolved { gear: gear.into() }
163 }
164
165 /// Convenience constructor for [`TransportError::Problem`] with no
166 /// server-advised `Retry-After`.
167 #[cfg(feature = "canonical-errors")]
168 #[must_use]
169 pub fn problem(problem: Problem) -> Self {
170 Self::Problem {
171 problem: Box::new(problem),
172 retry_after: None,
173 }
174 }
175
176 /// Server-advised retry delay (`Retry-After`), when the error carries one.
177 ///
178 /// Carried by both [`TransportError::HttpStatus`] (non-`Problem` peers) and
179 /// [`TransportError::Problem`] (canonical-error peers), parsed from the
180 /// response header. Returns `None` for all other error classes.
181 #[must_use]
182 pub fn retry_after(&self) -> Option<std::time::Duration> {
183 match self {
184 TransportError::HttpStatus { retry_after, .. } => *retry_after,
185 #[cfg(feature = "canonical-errors")]
186 TransportError::Problem { retry_after, .. } => *retry_after,
187 _ => None,
188 }
189 }
190
191 /// Whether this error class is generally safe to retry without a higher-level
192 /// idempotency strategy. Used by [`crate::runtime::retry`] when a method is
193 /// declared `#[retryable]`.
194 #[must_use]
195 pub fn is_transient(&self) -> bool {
196 match self {
197 // `Framing` is transient deliberately: that classification is
198 // what makes a mid-stream framing fault reconnect-eligible.
199 TransportError::Network(_)
200 | TransportError::Timeout(_)
201 | TransportError::Framing { .. }
202 | TransportError::Unresolved { .. } => true,
203 TransportError::HttpStatus { status, .. } => is_retryable_status(*status),
204 #[cfg(feature = "canonical-errors")]
205 TransportError::Problem { problem, .. } => {
206 problem.status.is_some_and(is_retryable_status)
207 }
208 #[cfg(feature = "grpc-client")]
209 TransportError::Grpc { code, .. } => matches!(
210 code,
211 tonic::Code::Unavailable
212 | tonic::Code::DeadlineExceeded
213 | tonic::Code::Cancelled
214 | tonic::Code::Aborted
215 | tonic::Code::ResourceExhausted
216 ),
217 // `Overloaded` is a local shed, not a network condition: retrying it
218 // adds load to an already-saturated client, so it fails fast.
219 // `CircuitOpen` fails fast for the same reason, and so the breaker
220 // also stops an in-call retry loop or stream reconnect at once.
221 TransportError::Serialization(_)
222 | TransportError::UrlBuild(_)
223 | TransportError::Overloaded
224 | TransportError::CircuitOpen { .. } => false,
225 }
226 }
227}
228
229fn is_retryable_status(status: u16) -> bool {
230 // PRD §5.7 retryable set: throttling + gateway/upstream transient failures.
231 // Deliberately excludes 408 and 500 — a bare 500 is often a deterministic
232 // server-side failure and blindly retrying it (especially a write) risks
233 // duplicate side effects.
234 matches!(status, 429 | 502 | 503 | 504)
235}
236
237#[cfg(test)]
238#[cfg_attr(coverage_nightly, coverage(off))]
239mod tests {
240 use super::*;
241
242 #[test]
243 fn network_and_timeout_are_transient() {
244 assert!(TransportError::network("dns").is_transient());
245 assert!(TransportError::Timeout(std::time::Duration::from_secs(1)).is_transient());
246 }
247
248 #[test]
249 fn serialization_is_not_transient() {
250 assert!(!TransportError::serialization("bad json").is_transient());
251 assert!(!TransportError::UrlBuild("missing path param".into()).is_transient());
252 }
253
254 #[test]
255 fn overloaded_is_not_transient() {
256 // A locally-shed request never left the process; retrying it only adds
257 // load to an already-saturated client, so it must fail fast.
258 assert!(!TransportError::Overloaded.is_transient());
259 }
260
261 #[test]
262 fn unresolved_is_transient() {
263 assert!(TransportError::unresolved("billing").is_transient());
264 }
265
266 #[test]
267 fn framing_is_transient_for_every_framing() {
268 // Q9: a framing fault is transient on purpose — that classification is
269 // what makes it reconnect-eligible, and it must not depend on which
270 // framing faulted.
271 for framing in [
272 crate::ir::binding::StreamFraming::ServerSentEvents,
273 crate::ir::binding::StreamFraming::MultipartMixed,
274 ] {
275 assert!(
276 TransportError::framing(framing, "bad frame").is_transient(),
277 "expected {framing:?} framing errors to be transient"
278 );
279 }
280 }
281
282 #[test]
283 fn framing_display_names_the_media_type() {
284 assert_eq!(
285 TransportError::framing(
286 crate::ir::binding::StreamFraming::MultipartMixed,
287 "bad delimiter",
288 )
289 .to_string(),
290 "multipart/mixed framing error: bad delimiter"
291 );
292 assert_eq!(
293 TransportError::framing(
294 crate::ir::binding::StreamFraming::ServerSentEvents,
295 "bad frame",
296 )
297 .to_string(),
298 "text/event-stream framing error: bad frame"
299 );
300 }
301
302 #[cfg(feature = "grpc-client")]
303 #[test]
304 fn grpc_transient_codes() {
305 for code in [
306 tonic::Code::Unavailable,
307 tonic::Code::DeadlineExceeded,
308 tonic::Code::Cancelled,
309 tonic::Code::Aborted,
310 tonic::Code::ResourceExhausted,
311 ] {
312 assert!(
313 TransportError::Grpc {
314 code,
315 message: String::new(),
316 }
317 .is_transient(),
318 "expected {code:?} to be transient"
319 );
320 }
321 for code in [
322 tonic::Code::NotFound,
323 tonic::Code::InvalidArgument,
324 tonic::Code::PermissionDenied,
325 tonic::Code::Internal,
326 ] {
327 assert!(
328 !TransportError::Grpc {
329 code,
330 message: String::new(),
331 }
332 .is_transient(),
333 "expected {code:?} not to be transient"
334 );
335 }
336 }
337
338 #[test]
339 fn five_xx_is_transient_but_4xx_mostly_is_not() {
340 assert!(
341 TransportError::HttpStatus {
342 status: 503,
343 body: String::new(),
344 retry_after: None,
345 }
346 .is_transient()
347 );
348 assert!(
349 !TransportError::HttpStatus {
350 status: 404,
351 body: String::new(),
352 retry_after: None,
353 }
354 .is_transient()
355 );
356 assert!(
357 TransportError::HttpStatus {
358 status: 429,
359 body: String::new(),
360 retry_after: None,
361 }
362 .is_transient()
363 );
364 }
365
366 #[test]
367 fn bare_500_and_408_are_not_retried() {
368 // PRD §5.7: 500 and 408 are deliberately excluded from the retryable set.
369 for status in [500u16, 408] {
370 assert!(
371 !TransportError::HttpStatus {
372 status,
373 body: String::new(),
374 retry_after: None,
375 }
376 .is_transient(),
377 "status {status} must not be retryable"
378 );
379 }
380 }
381
382 #[test]
383 fn retry_after_accessor_reads_http_status_field() {
384 let err = TransportError::HttpStatus {
385 status: 429,
386 body: String::new(),
387 retry_after: Some(std::time::Duration::from_secs(2)),
388 };
389 assert_eq!(err.retry_after(), Some(std::time::Duration::from_secs(2)));
390 assert_eq!(TransportError::network("x").retry_after(), None);
391 }
392}