coven_storage/error.rs
1use crate::CloudProvider;
2
3/// Failures the app can distinguish and act on (Appendix F.5).
4#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
5pub enum StorageFailure {
6 /// The platform or OS version cannot use this built-in provider.
7 ProviderUnavailable,
8 /// The app did not register the access required by this operation.
9 AccessNotRegistered {
10 /// Access the app must register before this operation is available.
11 required: crate::OAuthAccess,
12 },
13 /// The authorization did not grant the required access.
14 AccessNotGranted {
15 /// Access the account must authorize.
16 required: crate::OAuthAccess,
17 },
18 /// An App-folder store cannot be shared without relocating it.
19 DropboxAppFolderNotShareable,
20 /// The installation must complete membership and key-copy catch-up before sending.
21 CatchUpRequired,
22 /// No route to the provider, a timeout, an interrupted response, or a
23 /// server failure the provider answered with (§6.7).
24 Network,
25 /// Two complete reads of one immutable object returned different bytes:
26 /// a fault on the way to the device changed one of them (§19.1).
27 Corrupted,
28 /// Credentials were refused or must be refreshed.
29 Authentication,
30 /// The account is signed in but cannot perform this operation.
31 PermissionDenied,
32 /// The requested object is absent.
33 NotFound,
34 /// A create-once path is occupied.
35 AlreadyExists,
36 /// A concurrent storage mutation defeated a conditional request.
37 Conflict,
38 /// The bucket, folder or zone is absent.
39 ContainerNotFound,
40 /// The S3 endpoint or signing region is wrong.
41 RegionMismatch,
42 /// Setting up a store that never had storage found another installation's
43 /// creation slot: another installation of the store claimed this
44 /// location first (§10.3). Restore or join it instead.
45 StoreExists,
46 /// S3 rejected the device clock after one retry with the offset its
47 /// response stated (§20.7).
48 ClockSkew,
49 /// Every member reaches the whole location (a Dropbox shared folder, a
50 /// OneDrive folder, or an S3 bucket), so a store there needs it to
51 /// itself, and it holds something besides this store (§20.3). At first
52 /// setup: an object or folder outside the store's own, or a location
53 /// marker that doesn't name it. At a reconnect, restore or join: a marker
54 /// that is missing, malformed or names another store.
55 OwnLocationRequired,
56 /// The provider has no space left.
57 QuotaExceeded,
58 /// The provider requests a later retry.
59 RateLimited,
60 /// The request's configuration is invalid.
61 InvalidConfiguration,
62 /// The provider refused the request for another reason.
63 Refused,
64 /// The response or recorded session is malformed.
65 Protocol,
66 /// An object path is outside the store's layout.
67 InvalidPath,
68 /// A range is empty, reversed or beyond the object's end.
69 InvalidRange,
70 /// Coven changes sharing only from the account holding the store. That is
71 /// coven's rule, not every provider's limit (§13.2).
72 NotStoreOwner,
73 /// The invited account is the one holding the store (§13.2).
74 InviteeIsStoreOwner,
75 /// The provider refused to share the store for a reason only a person
76 /// can fix, the invited address's or the inviting account's, so no retry
77 /// changes the answer (§13.2).
78 SharingRefused(coven_foundation::sharing::SharingRefusal),
79 /// Dropbox cannot upgrade a pending viewer without the recipient's account id.
80 AccountIdUnavailable,
81 /// The invite belongs to another provider location.
82 InvitationMismatch,
83 /// The session belongs to another provider or location.
84 SessionMismatch,
85 /// The recorded upload expired or a publication conflict invalidated it.
86 SessionExpired,
87 /// A part disagrees with the session's offset, size or alignment.
88 InvalidPart,
89 /// A floor pointer replacement exceeds this provider's single-request
90 /// limit. The pointer is small, so it never goes up in parts.
91 SingleRequestTooLarge {
92 /// Encrypted body length in bytes.
93 size: u64,
94 /// The adapter's single-request limit in bytes.
95 limit: u64,
96 },
97 /// An S3 object published by `CopyObject` exceeds its single-copy limit,
98 /// so this profile refuses it (§20.6 says why).
99 CopyTooLarge {
100 /// Encrypted body length in bytes.
101 size: u64,
102 /// The single-copy limit in bytes.
103 limit: u64,
104 },
105 /// Parsing recorded provider data failed.
106 Encoding,
107 /// Local file access or persisting provider settings or upload progress failed.
108 File,
109 /// This installation has no member keys in custody.
110 MemberKeysMissing,
111 /// Coven's work for the request panicked: a bug, which the caller
112 /// reports (E15). `StorageError::Bug` carries it.
113 Bug,
114}
115
116/// A storage error preserves its cause without converting it into text.
117#[derive(Debug, thiserror::Error)]
118pub enum StorageError {
119 /// A classified failure with no underlying native error.
120 #[error("{0:?}")]
121 Failure(StorageFailure),
122 /// A classified local failure with its diagnostic or native cause.
123 #[error("{failure:?}: {source}")]
124 Caused {
125 /// The failure the app can act on.
126 failure: StorageFailure,
127 /// The diagnostic or original error.
128 #[source]
129 source: Box<dyn std::error::Error + Send + Sync>,
130 },
131 /// A provider failure, classified for the app, with its original cause.
132 #[error("{provider:?}: {failure:?}: {source}")]
133 Provider {
134 /// Provider that failed.
135 provider: CloudProvider,
136 /// Actionable classification.
137 failure: StorageFailure,
138 /// Original transport, SDK or framework error.
139 #[source]
140 source: Box<dyn std::error::Error + Send + Sync>,
141 },
142 /// Cleanup failed too; neither cause is hidden.
143 #[error("{operation}; cleanup also failed: {cleanup}")]
144 Cleanup {
145 /// The original failure.
146 #[source]
147 operation: Box<StorageError>,
148 /// Failure removing temporary data or recording the failed upload state.
149 cleanup: Box<StorageError>,
150 },
151 /// Coven's work for the request panicked: a bug, which the caller
152 /// reports (E15). Its failure is `StorageFailure::Bug`.
153 #[error(transparent)]
154 Bug(#[from] coven_foundation::task::Bug),
155}
156
157impl coven_foundation::task::CarriesBug for StorageError {
158 fn bug(&self) -> Option<&coven_foundation::task::Bug> {
159 match self {
160 Self::Bug(bug) => Some(bug),
161 Self::Cleanup { operation, cleanup } => operation.bug().or_else(|| cleanup.bug()),
162 Self::Failure(_) | Self::Caused { .. } | Self::Provider { .. } => None,
163 }
164 }
165}
166
167impl StorageError {
168 /// Native destination conflicts mean a failed condition during replacement.
169 pub(crate) fn replacement(mut self) -> Self {
170 match &mut self {
171 Self::Failure(failure)
172 | Self::Caused { failure, .. }
173 | Self::Provider { failure, .. }
174 if *failure == StorageFailure::AlreadyExists =>
175 {
176 *failure = StorageFailure::Conflict
177 }
178 _ => {}
179 }
180 self
181 }
182
183 /// What the app can do about this failure.
184 pub fn failure(&self) -> StorageFailure {
185 match self {
186 Self::Provider { failure, .. } => *failure,
187 Self::Failure(failure) | Self::Caused { failure, .. } => *failure,
188 Self::Cleanup { operation, .. } => operation.failure(),
189 Self::Bug(_) => StorageFailure::Bug,
190 }
191 }
192
193 /// The failure when the request alone failed: none when its cleanup
194 /// failed too, which leaves state behind that a caller handling the
195 /// failure itself, such as an occupied path or a throttled request,
196 /// doesn't know of.
197 pub fn own_failure(&self) -> Option<StorageFailure> {
198 match self {
199 Self::Cleanup { .. } => None,
200 _ => Some(self.failure()),
201 }
202 }
203
204 /// Whether the provider answered the request behind this failure, even
205 /// with an error (E5). `Network` alone cannot say: a server's error
206 /// response is an answer; a refused connection or a timeout is not.
207 pub fn answered(&self) -> bool {
208 match self {
209 Self::Provider { source, .. } => crate::providers::response_arrived(source.as_ref()),
210 Self::Cleanup { operation, .. } => operation.answered(),
211 Self::Failure(_) | Self::Caused { .. } | Self::Bug(_) => false,
212 }
213 }
214
215 /// Whether the provider answered this request with a refusal, so it
216 /// stored nothing. A timeout, or a lost, malformed or server-failure
217 /// reply, leaves the outcome unknown. The clients resend a request only
218 /// after a refusal (a rejected token, a skewed clock), so no earlier
219 /// attempt of it stored anything either.
220 pub fn refused(&self) -> bool {
221 self.answered()
222 && !matches!(self.failure(), StorageFailure::Network | StorageFailure::Protocol)
223 }
224
225 /// The wait a provider response asked every consumer to observe, from
226 /// its `Retry-After`, Dropbox's `retry_after` or CloudKit's
227 /// `CKErrorRetryAfterKey`.
228 pub(crate) fn retry_after(&self) -> Option<crate::RetryAfter> {
229 match self {
230 Self::Provider { provider, source, .. } => {
231 crate::providers::retry_after(*provider, source.as_ref())
232 }
233 Self::Cleanup { operation, .. } => operation.retry_after(),
234 Self::Failure(_) | Self::Caused { .. } | Self::Bug(_) => None,
235 }
236 }
237
238 /// Transport interruptions and provider throttling invite retry.
239 pub fn retryable(&self) -> bool {
240 matches!(self.failure(), StorageFailure::Network | StorageFailure::RateLimited)
241 }
242}
243
244/// The provider operation checked before setup commits anything (E5).
245#[derive(Clone, Copy, Debug, PartialEq, Eq)]
246pub enum StorageCheck {
247 /// Create a fresh sealed object.
248 Create,
249 /// Refuse a second create at the same path.
250 CreateOnce,
251 /// Replace the observed object and refuse its stale revision without changing bytes.
252 ConditionalReplace,
253 /// Read the original bytes in full.
254 Read,
255 /// Read exactly an interior byte range.
256 ReadRange,
257 /// Run the scoped query and check returned probe metadata; fresh objects may be omitted.
258 List,
259 /// Delete the object and confirm it is absent.
260 Delete,
261 /// S3: multipart publication refuses an occupied name with its bytes and
262 /// time unchanged, and conditional completion hides unfinished uploads.
263 MultipartCreateOnce,
264 /// S3: multipart objects are dated by complete publication, as recorded.
265 PublicationTime,
266 /// S3: another setting agrees with the service's observed behavior.
267 Behavior,
268}
269
270/// A provider or S3 settings check refused the location (§20.7, §20.8).
271#[derive(Debug, thiserror::Error)]
272pub enum StorageCheckError {
273 /// This profile has no certification with bucket versioning enabled.
274 #[error("S3 bucket versioning {state:?} is not certified for this profile")]
275 S3VersioningUnsupported {
276 /// The bucket's observed versioning state.
277 state: crate::S3BucketVersioning,
278 },
279 /// The bucket state is unknown and this profile has no versioning certification.
280 #[error("S3 bucket versioning is unknown; this profile requires a successful GetBucketVersioning (s3:GetBucketVersioning; GCS storage.buckets.get): {source}")]
281 S3VersioningUnknown {
282 /// The refused versioning read, retaining its native cause.
283 #[source]
284 source: std::sync::Arc<StorageError>,
285 },
286 /// A provider check failed; cleanup failures retain both causes.
287 #[error("storage check {check:?}: {source}")]
288 ProviderCheck {
289 /// The operation that failed.
290 check: StorageCheck,
291 /// The original failure, including cleanup if that also failed.
292 #[source]
293 source: StorageError,
294 },
295 /// A classified storage failure.
296 #[error(transparent)]
297 Storage(StorageError),
298}
299
300impl coven_foundation::task::CarriesBug for StorageCheckError {
301 fn bug(&self) -> Option<&coven_foundation::task::Bug> {
302 match self {
303 Self::Storage(error) | Self::ProviderCheck { source: error, .. } => error.bug(),
304 Self::S3VersioningUnknown { source } => source.bug(),
305 Self::S3VersioningUnsupported { .. } => None,
306 }
307 }
308}
309
310impl From<StorageError> for StorageCheckError {
311 fn from(error: StorageError) -> Self {
312 Self::Storage(error)
313 }
314}
315
316impl StorageFailure {
317 /// Whether the provider answered that the signed-in account may not use
318 /// the shared location, or that the location is gone: the access an
319 /// invite shared is no longer there. A sign-in the provider rejects
320 /// (`Authentication`) is not: signing in again can mend it.
321 pub fn access_ended(self) -> bool {
322 matches!(self, Self::PermissionDenied | Self::ContainerNotFound)
323 }
324
325 /// Whether the provider answered, to accepting an invite's share, that the
326 /// account may not use the location or that the share or location is gone.
327 /// A refused sign-in (`Authentication`) is not: signing in again can mend
328 /// it.
329 pub fn share_refused(self) -> bool {
330 matches!(self, Self::PermissionDenied | Self::NotFound | Self::ContainerNotFound)
331 }
332
333 /// Retain the diagnostic or native cause alongside this classification.
334 pub fn with_source(
335 self,
336 source: impl Into<Box<dyn std::error::Error + Send + Sync>>,
337 ) -> StorageError {
338 StorageError::Caused { failure: self, source: source.into() }
339 }
340}
341
342impl From<StorageFailure> for StorageError {
343 fn from(failure: StorageFailure) -> Self {
344 Self::Failure(failure)
345 }
346}
347
348impl From<coven_foundation::files::FileError> for StorageError {
349 fn from(error: coven_foundation::files::FileError) -> Self {
350 match error {
351 coven_foundation::files::FileError::Bug(bug) => Self::Bug(bug),
352 error => StorageFailure::File.with_source(error),
353 }
354 }
355}
356
357#[cfg(test)]
358#[path = "error_tests.rs"]
359mod tests;
360
361/// A code's storage part that the format's primitives refuse: truncated,
362/// trailing bytes, an unknown tag or a length past its bound (format.md D13).
363impl From<coven_format::Error> for StorageError {
364 fn from(error: coven_format::Error) -> Self {
365 StorageFailure::Encoding.with_source(error)
366 }
367}
368
369impl From<coven_format::path::PathError> for StorageError {
370 fn from(error: coven_format::path::PathError) -> Self {
371 StorageFailure::InvalidPath.with_source(error)
372 }
373}