1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
//! Error types for the TUS client.
use std::time::Duration;
/// Result type returned by the client.
pub type Result<T> = std::result::Result<T, Error>;
/// Boxed error type carried by [`Error::Transport`].
///
/// On native targets the boxed error must be `Send + Sync` so client futures
/// stay `Send`; on `wasm32` (where futures are not `Send`) the bounds are
/// relaxed, mirroring the rest of the crate.
#[cfg(not(target_arch = "wasm32"))]
pub type BoxError = Box<dyn std::error::Error + Send + Sync + 'static>;
/// Boxed error type carried by [`Error::Transport`].
///
/// On native targets the boxed error must be `Send + Sync` so client futures
/// stay `Send`; on `wasm32` (where futures are not `Send`) the bounds are
/// relaxed, mirroring the rest of the crate.
#[cfg(target_arch = "wasm32")]
pub type BoxError = Box<dyn std::error::Error + 'static>;
/// Errors returned by the client.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
/// Local file I/O error.
#[error("io failed: {0}")]
Io(#[from] std::io::Error),
/// URL parsing/joining error.
#[error("invalid upload url: {0}")]
Url(#[from] url::ParseError),
/// The server did not send a required response header.
#[error("missing required `{header}` header")]
#[non_exhaustive]
MissingHeader {
/// Name of the missing response header.
header: &'static str,
},
/// The server sent a response header the client could not parse: a
/// non-UTF-8 value, a non-numeric `Upload-Offset`/`Upload-Length`, or a
/// malformed `Upload-Metadata`. Returned only while decoding a server
/// response; client-built request headers surface as
/// [`InvalidRequestHeader`](Error::InvalidRequestHeader).
#[error("invalid `{header}` header value `{value}`")]
#[non_exhaustive]
InvalidHeader {
/// Name of the offending response header.
header: &'static str,
/// The malformed value the server sent.
value: String,
},
/// A request header the client constructs could not be built: a
/// protocol header (`Upload-Offset`, `Upload-Length`, `Upload-Concat`),
/// the encoded `Upload-Metadata`, or the `Upload-Checksum` value. This
/// is a client-side construction failure (e.g. a metadata key or value
/// that cannot form a valid header), never a response the server sent.
#[error("invalid `{name}` header: {value}")]
#[non_exhaustive]
InvalidRequestHeader {
/// Name of the header.
name: String,
/// The invalid value.
value: String,
},
/// The remote offset is beyond the local source size.
#[error("server offset {offset} exceeds local source size {source_len}")]
#[non_exhaustive]
OffsetBeyondSource {
/// Offset reported by the server.
offset: u64,
/// Size of the local upload source.
source_len: u64,
},
/// The remote upload length does not match the local source size.
#[error("server length {remote} does not match local source size {local}")]
#[non_exhaustive]
LengthMismatch {
/// Upload length reported by the server.
remote: u64,
/// Size of the local upload source.
local: u64,
},
/// The server acknowledged an offset inconsistent with what the client
/// sent, either behind the previous offset or beyond the bytes actually
/// transmitted, which indicates a protocol bug on one side rather than
/// a transient network failure. Never retried.
#[error("server offset {actual} does not match expected offset {expected}")]
#[non_exhaustive]
OffsetDesync {
/// Offset the client expected after the write.
expected: u64,
/// Offset the server acknowledged.
actual: u64,
},
/// The upload source misbehaved (for example a short or oversized read,
/// or content that changed underneath the client). Deterministic and
/// never retried.
///
/// Custom [`UploadSource`](crate::UploadSource) implementations should
/// build this variant through [`Error::source`] rather than constructing
/// it directly; the underlying failure is preserved as the error
/// [`source`](std::error::Error::source).
#[error("upload source failed: {source}")]
#[non_exhaustive]
Source {
/// The underlying source failure.
#[source]
source: BoxError,
},
/// A [`HeaderProvider`](crate::HeaderProvider) failed to produce the
/// dynamic request headers for an attempt: for example a token refresh
/// that could not reach the auth server, or a credential that is no
/// longer valid.
///
/// `retryable` reports whether producing the headers could plausibly
/// succeed on a later attempt (a transient refresh failure) or is
/// deterministic (a permanently bad credential). The retry loop
/// re-invokes the provider on each attempt, so a retryable failure gives
/// a transient refresh another chance after backoff. Custom providers
/// should build this variant through [`Error::header_provider`] or
/// [`Error::header_provider_permanent`] rather than constructing it
/// directly; the underlying failure is preserved as the error
/// [`source`](std::error::Error::source).
#[error("{}: {source}", header_provider_failure_message(.retryable))]
#[non_exhaustive]
HeaderProvider {
/// The underlying header-provider failure.
#[source]
source: BoxError,
/// Whether producing the headers could plausibly succeed on retry.
retryable: bool,
},
/// The server returned an unexpected HTTP response.
#[error("unexpected {operation} response: status {}, body `{body}`", .status.as_u16())]
#[non_exhaustive]
UnexpectedResponse {
/// The client operation that received the response.
operation: &'static str,
/// HTTP status code of the response.
status: http::StatusCode,
/// Response body, for diagnostics. Bodies are truncated to a few
/// KiB; a truncated body ends with `...[truncated]`.
body: String,
/// The delay requested by a valid `Retry-After` response header, if
/// present. Populated for every response but only meaningful on
/// retryable statuses (429/503/408), where the client honors it in
/// place of its computed backoff.
retry_after: Option<Duration>,
},
/// A transport failed to execute a request.
///
/// `retryable` reports whether retrying could plausibly succeed
/// (connection reset, DNS hiccup) or whether the failure is
/// deterministic (request construction bug, redirect-policy violation).
/// Custom transports should build this variant through
/// [`Error::transport`] or [`Error::transport_permanent`] rather than
/// constructing it directly; the underlying failure is preserved as the
/// error [`source`](std::error::Error::source).
#[error("{}", transport_failure_message(.retryable))]
#[non_exhaustive]
Transport {
/// The underlying transport failure.
#[source]
source: BoxError,
/// Whether retrying the request could plausibly succeed.
retryable: bool,
},
/// The server directed the client to an upload URL on a different origin
/// than the endpoint, and cross-origin upload locations are restricted.
///
/// Only returned when [`Client::with_endpoint_origin_restriction`] is
/// enabled. It exists to stop a malicious or compromised server from
/// redirecting credentialed requests (an `Authorization` header, cookies)
/// to an attacker-controlled host.
///
/// [`Client::with_endpoint_origin_restriction`]: crate::Client::with_endpoint_origin_restriction
#[error("server upload location `{location}` is not on the endpoint origin `{endpoint}`")]
#[non_exhaustive]
CrossOriginLocation {
/// The endpoint origin the client trusts.
endpoint: String,
/// The cross-origin upload location the server returned.
location: String,
},
/// The server does not advertise a TUS extension required by the
/// requested operation.
#[error("server does not advertise the `{extension}` tus extension")]
#[non_exhaustive]
UnsupportedExtension {
/// Name of the required-but-unadvertised extension.
extension: &'static str,
},
/// An internal client error, such as a panicked upload task.
#[error("internal client error: {message}")]
#[non_exhaustive]
Internal {
/// Description of the internal failure.
message: String,
},
}
impl Error {
/// Wraps a transport failure that may succeed on retry (connection
/// reset, DNS hiccup, timeout).
///
/// Custom [`Transport`](crate::Transport) implementations should use
/// this for transient failures and [`Error::transport_permanent`] for
/// deterministic ones. Accepts any error type (or a plain message
/// string):
///
/// ```
/// use tus_uploader::Error;
///
/// let io = std::io::Error::other("connection reset");
/// let error = Error::transport(io);
/// assert!(error.is_retryable());
/// ```
pub fn transport(source: impl Into<BoxError>) -> Self {
Error::Transport {
source: source.into(),
retryable: true,
}
}
/// Wraps a deterministic transport failure that is never retried, such
/// as a request that cannot be constructed.
pub fn transport_permanent(source: impl Into<BoxError>) -> Self {
Error::Transport {
source: source.into(),
retryable: false,
}
}
/// Wraps a failure from a custom [`UploadSource`](crate::UploadSource),
/// such as a short or oversized read or content that changed underneath
/// the client. Always permanent; the local source is authoritative, so
/// the failure is never retried. Accepts any error type (or a plain
/// message string):
///
/// ```
/// use tus_uploader::Error;
///
/// let error = Error::source("read returned fewer bytes than requested");
/// assert!(!error.is_retryable());
/// ```
pub fn source(source: impl Into<BoxError>) -> Self {
Error::Source {
source: source.into(),
}
}
/// Wraps a [`HeaderProvider`](crate::HeaderProvider) failure that may
/// succeed on retry, such as a token refresh that could not reach the
/// auth server. The retry loop re-invokes the provider, so a retryable
/// failure gets another attempt after backoff. Use
/// [`Error::header_provider_permanent`] for deterministic failures such
/// as a permanently invalid credential.
pub fn header_provider(source: impl Into<BoxError>) -> Self {
Error::HeaderProvider {
source: source.into(),
retryable: true,
}
}
/// Wraps a deterministic [`HeaderProvider`](crate::HeaderProvider)
/// failure that is never retried, such as a permanently invalid
/// credential or a misconfigured provider.
pub fn header_provider_permanent(source: impl Into<BoxError>) -> Self {
Error::HeaderProvider {
source: source.into(),
retryable: false,
}
}
/// Reports whether retrying the failed operation could plausibly
/// succeed.
///
/// Transient failures (the transient `5xx` responses `500`/`502`/`503`/`504`,
/// plus `408`/`409`/`429`/`460`, retryable [`Error::Transport`] failures,
/// and retryable [`Error::HeaderProvider`] failures) are retryable.
/// Deterministic failures (source misbehavior, offset desync, request
/// construction errors, permanent transport failures, and permanent
/// header-provider failures) are not.
///
/// Only the transient `5xx` codes are retried. Deterministic server-side
/// codes such as `501 Not Implemented` and `505 HTTP Version Not Supported`
/// will not succeed on retry, so they are treated as permanent even though
/// they are `5xx`.
///
/// A 460 (Checksum Mismatch, TUS checksum extension) is retryable
/// because in-transit corruption of a chunk is exactly the transient
/// failure the extension exists to detect: the server discarded the
/// chunk, so resending it is safe and likely to succeed.
#[must_use]
pub fn is_retryable(&self) -> bool {
match self {
Error::UnexpectedResponse { status, .. } => {
matches!(
status.as_u16(),
500 | 502 | 503 | 504 | 408 | 409 | 429 | 460
)
}
Error::Transport { retryable, .. } => *retryable,
Error::HeaderProvider { retryable, .. } => *retryable,
_ => false,
}
}
/// Returns the delay a server requested via a valid `Retry-After`
/// response header, when the error carries one. Only
/// [`UnexpectedResponse`](Error::UnexpectedResponse) can; every other
/// variant returns `None`. The client uses this to honor server-driven
/// backoff on retryable responses instead of its own jittered delay.
///
/// Exposed so a custom [`RetryHook`](crate::RetryHook) can honor the same
/// server-driven backoff the built-in retry loop uses.
#[must_use]
pub fn retry_after(&self) -> Option<Duration> {
match self {
Error::UnexpectedResponse { retry_after, .. } => *retry_after,
_ => None,
}
}
}
// Takes `&bool` because thiserror's `.retryable` format shorthand expands to
// `&self.retryable`.
fn transport_failure_message(retryable: &bool) -> &'static str {
if *retryable {
"transport failed"
} else {
"transport failed permanently"
}
}
// Takes `&bool` because thiserror's `.retryable` format shorthand expands to
// `&self.retryable`.
fn header_provider_failure_message(retryable: &bool) -> &'static str {
if *retryable {
"header provider failed"
} else {
"header provider failed permanently"
}
}
#[cfg(test)]
mod tests {
use super::*;
use http::StatusCode;
#[cfg_attr(not(target_arch = "wasm32"), test)]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
fn offset_beyond_source_error_uses_public_client_error_name() {
let error = Error::OffsetBeyondSource {
offset: 5,
source_len: 4,
};
assert_eq!(
error.to_string(),
"server offset 5 exceeds local source size 4"
);
}
#[cfg_attr(not(target_arch = "wasm32"), test)]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
fn transport_errors_preserve_the_source_chain() {
let inner = std::io::Error::other("connection reset");
let error = Error::transport(inner);
assert_eq!(error.to_string(), "transport failed");
let source = std::error::Error::source(&error).expect("source must be preserved");
assert_eq!(source.to_string(), "connection reset");
let permanent = Error::transport_permanent("bad request line");
assert_eq!(permanent.to_string(), "transport failed permanently");
let source = std::error::Error::source(&permanent).expect("source must be preserved");
assert_eq!(source.to_string(), "bad request line");
}
#[cfg_attr(not(target_arch = "wasm32"), test)]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
fn source_and_header_provider_errors_preserve_the_source_chain() {
let inner = std::io::Error::other("file changed length after open");
let error = Error::source(inner);
assert_eq!(
error.to_string(),
"upload source failed: file changed length after open"
);
assert!(!error.is_retryable());
let source = std::error::Error::source(&error).expect("source must be preserved");
assert_eq!(source.to_string(), "file changed length after open");
let retryable = Error::header_provider("token refresh timed out");
assert_eq!(
retryable.to_string(),
"header provider failed: token refresh timed out"
);
assert!(retryable.is_retryable());
let source = std::error::Error::source(&retryable).expect("source must be preserved");
assert_eq!(source.to_string(), "token refresh timed out");
let permanent = Error::header_provider_permanent("invalid refresh token");
assert_eq!(
permanent.to_string(),
"header provider failed permanently: invalid refresh token"
);
assert!(!permanent.is_retryable());
}
#[cfg_attr(not(target_arch = "wasm32"), test)]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
fn retryability_is_a_typed_property() {
let retryable = [
Error::transport("connection reset"),
Error::header_provider("token refresh timed out"),
Error::UnexpectedResponse {
operation: "patch upload",
status: StatusCode::SERVICE_UNAVAILABLE,
body: String::new(),
retry_after: None,
},
Error::UnexpectedResponse {
operation: "patch upload",
status: StatusCode::TOO_MANY_REQUESTS,
body: String::new(),
retry_after: None,
},
Error::UnexpectedResponse {
operation: "patch upload",
status: StatusCode::REQUEST_TIMEOUT,
body: String::new(),
retry_after: None,
},
Error::UnexpectedResponse {
operation: "patch upload",
status: StatusCode::CONFLICT,
body: String::new(),
retry_after: None,
},
Error::UnexpectedResponse {
operation: "patch upload",
status: StatusCode::from_u16(460).unwrap(),
body: String::new(),
retry_after: None,
},
Error::UnexpectedResponse {
operation: "patch upload",
status: StatusCode::INTERNAL_SERVER_ERROR,
body: String::new(),
retry_after: None,
},
Error::UnexpectedResponse {
operation: "patch upload",
status: StatusCode::BAD_GATEWAY,
body: String::new(),
retry_after: None,
},
Error::UnexpectedResponse {
operation: "patch upload",
status: StatusCode::GATEWAY_TIMEOUT,
body: String::new(),
retry_after: None,
},
];
for error in retryable {
assert!(error.is_retryable(), "expected retryable: {error}");
}
let permanent = [
Error::transport_permanent("bad credentials"),
Error::source("short read"),
Error::header_provider_permanent("invalid refresh token"),
Error::OffsetDesync {
expected: 4,
actual: 2,
},
Error::OffsetBeyondSource {
offset: 5,
source_len: 4,
},
Error::UnexpectedResponse {
operation: "patch upload",
status: StatusCode::BAD_REQUEST,
body: String::new(),
retry_after: None,
},
// Deterministic 5xx codes are permanent even though they are 5xx:
// retrying `501 Not Implemented` or `505 HTTP Version Not Supported`
// cannot succeed.
Error::UnexpectedResponse {
operation: "patch upload",
status: StatusCode::NOT_IMPLEMENTED,
body: String::new(),
retry_after: None,
},
Error::UnexpectedResponse {
operation: "patch upload",
status: StatusCode::HTTP_VERSION_NOT_SUPPORTED,
body: String::new(),
retry_after: None,
},
Error::UnsupportedExtension {
extension: "concatenation",
},
Error::Internal {
message: "task panicked".into(),
},
];
for error in permanent {
assert!(!error.is_retryable(), "expected permanent: {error}");
}
}
#[cfg_attr(not(target_arch = "wasm32"), test)]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
fn retry_after_is_carried_only_by_unexpected_response() {
let with_hint = Error::UnexpectedResponse {
operation: "patch upload",
status: StatusCode::SERVICE_UNAVAILABLE,
body: String::new(),
retry_after: Some(Duration::from_secs(7)),
};
assert_eq!(with_hint.retry_after(), Some(Duration::from_secs(7)));
let without_hint = Error::UnexpectedResponse {
operation: "patch upload",
status: StatusCode::SERVICE_UNAVAILABLE,
body: String::new(),
retry_after: None,
};
assert_eq!(without_hint.retry_after(), None);
assert_eq!(Error::transport("connection reset").retry_after(), None);
}
}