coven_database/error.rs
1//! Typed database call and authorization failures; opening's and
2//! migrations' are `open_error`'s, and the schema rules `schema_error`'s.
3
4use coven_foundation::files::StoreLockError;
5use coven_foundation::task::{Bug, CarriesBug};
6
7impl CarriesBug for DbError {
8 fn bug(&self) -> Option<&Bug> {
9 match self {
10 Self::Bug(bug) => Some(bug),
11 Self::Disk(error) => error.bug(),
12 Self::Lock(error) => error.bug(),
13 Self::StatePersistence(cause)
14 | Self::CheckpointFailed(cause)
15 | Self::StatisticsFailed(cause) => cause.bug(),
16 Self::Rollback { operation, .. } => operation.bug(),
17 Self::FileCleanup { write, failures } => write
18 .as_ref()
19 .err()
20 .and_then(|write| write.bug())
21 .or_else(|| failures.iter().find_map(DbError::bug)),
22 Self::StagingCleanup { operation, cleanup } => {
23 operation.bug().or_else(|| cleanup.bug())
24 }
25 Self::Closing { failures } => failures.iter().find_map(DbError::bug),
26 // An earlier bug, which reached its one reporter as it happened.
27 Self::StoreFailed(_) => None,
28 _ => None,
29 }
30 }
31}
32
33/// A failed database call or a write the database refuses (§4, §9, §15, §17).
34#[derive(Debug, thiserror::Error)]
35pub enum DbError {
36 /// Another claim must settle before this device reserves a new number.
37 #[error("a claim is already pending")]
38 ClaimPending,
39 /// No current claim exists for this operation.
40 #[error("there is no current claim")]
41 NoClaim,
42 /// A request to a provider account is between its target being fixed and
43 /// its reply, so a revocation queued now could precede the grants it
44 /// must follow (§20.9). The call is made again once the request ends.
45 #[error("a request to a provider account is running")]
46 ProviderRequestRunning,
47 /// Uncertain publication cannot be abandoned or resealed; a landed writes
48 /// batch cannot finish until its consumed state has committed.
49 #[error("the current claim has not settled or its writes have not applied")]
50 ClaimUnsettled,
51 /// The installation has exhausted its claim-number representation.
52 #[error("claim numbers exhausted")]
53 ClaimNumberExhausted,
54 /// This installation has exhausted its positive original-write identities.
55 #[error("write numbers exhausted")]
56 WriteNumberExhausted,
57 /// The supplied floor evidence does not cover the attempted slot.
58 #[error("floor evidence does not cover the claim")]
59 InvalidClaimCoverage,
60 /// Slot application must extend the previously committed prefix.
61 #[error("slot {received:?} does not follow applied slot {applied}")]
62 SequenceGap {
63 /// Previously committed coverage.
64 applied: u64,
65 /// The received slot.
66 received: coven_merge::Slot,
67 },
68 /// A slot's readable original awaits an external prerequisite.
69 #[error("write awaits {0:?}")]
70 WriteWaiting(crate::WriteWait),
71 /// A pending record, its subject, the sync status or an operation's
72 /// data could not be encoded, or a stored pending record could not be
73 /// decoded as the requested record type (E5).
74 #[error("invalid sync state data: {0}")]
75 StateEncoding(#[source] serde_json::Error),
76 /// Saving pending state or the sync status failed. The call that lost
77 /// the update and every later call and live query fail with this same
78 /// cause until reopened (E5).
79 #[error("saving sync state failed: {0}")]
80 StatePersistence(#[source] std::sync::Arc<DbError>),
81 /// An earlier call's rollback failed, so a connection may still be inside
82 /// that transaction, holding its uncommitted changes or its old snapshot;
83 /// this handle, read-only or not, refuses calls until reopened (§4).
84 #[error("an earlier rollback failed; reopen the store")]
85 RollbackFailed,
86 /// One of coven's own WAL checkpoints failed with this cause, other than
87 /// on a busy or locked database, so the store's checkpointing stopped.
88 /// Rather than stay open while its WAL grows without bound, this handle
89 /// and every live query fail with this same cause until reopened (§4).
90 #[error("a WAL checkpoint failed: {0}")]
91 CheckpointFailed(#[source] std::sync::Arc<DbError>),
92 /// Checking or gathering the query planner's statistics while the store
93 /// stays open failed with this cause, other than on a busy or locked
94 /// database, so keeping them stopped. Rather than stay open while the
95 /// planner plans with statistics that no longer hold, this handle and
96 /// every live query fail with this same cause until reopened (§4).
97 #[error("gathering the planner's statistics failed: {0}")]
98 StatisticsFailed(#[source] std::sync::Arc<DbError>),
99 /// The handle's clock could not wait for an open invite's expiry, so
100 /// the invite would outlive its lifetime. Rather than stay open
101 /// without writing expiries, this handle and every live query fail with
102 /// this same cause until reopened, and opening writes each expiry
103 /// already past (§13.2).
104 #[error(transparent)]
105 WallTimer(coven_foundation::clock::WallTimerError),
106 /// The system refused a thread of coven's upkeep, the one that
107 /// checkpoints a WAL or the one that keeps the planner's statistics, so
108 /// the store did not open (§4).
109 #[error("an upkeep thread could not start: {0}")]
110 UpkeepThread(#[source] std::io::Error),
111 /// Reading a claim's sealed bytes to retain them failed, and the claim's
112 /// transaction did not commit (§11).
113 #[error("reading a claim's bytes failed: {0}")]
114 ClaimRead(#[source] std::io::Error),
115 /// This handle or a clone has closed the store (E1).
116 #[error("store is closed")]
117 StoreClosed,
118 /// The call's runtime is shutting down and dropped its work (E15). A
119 /// call the blocking pool dropped unstarted changed nothing
120 /// (`ShutdownOutcome::NotRun`); closing, which runs as its own task, may
121 /// have closed some connections (`ShutdownOutcome::Unknown`).
122 #[error(transparent)]
123 Shutdown(#[from] coven_foundation::task::Shutdown),
124 /// The call's work panicked: a bug in coven or in the app's callback,
125 /// which the caller reports (E15). A write that panicked rolled back,
126 /// and the bytes it released or staged are removed as after any failed
127 /// write.
128 #[error(transparent)]
129 Bug(#[from] coven_foundation::task::Bug),
130 /// An earlier bug may have left this handle's state wrong, so the
131 /// handle failed with it, and every call and live query fails with it
132 /// until the store is reopened (E15). The call whose work hit the bug
133 /// returned it as `Bug`, or the store's bug sink heard it, so the app
134 /// shows this and doesn't report it again.
135 #[error("the store's handle failed on an earlier bug; reopen the store: {0}")]
136 StoreFailed(coven_foundation::task::Bug),
137 /// SQLite refused or failed a statement, preserving its error.
138 #[error(transparent)]
139 Sqlite(sqlive::rusqlite::Error),
140 /// A statement met damage SQLite reports (`SQLITE_CORRUPT`,
141 /// `SQLITE_NOTADB`), decoding stored facts found damage (§19.3), or a
142 /// snapshot's staged records differ from a second staging's (§19.1).
143 #[error("damaged database")]
144 DamagedDatabase,
145 /// Coven's own code broke a rule it relies on, such as a caller's
146 /// contract or a step its state machine cannot reach: a bug, not damage.
147 /// Sync reports it as `Failed(LocalFailure::Bug)` (§19.1).
148 #[error("coven invariant failed: {what}")]
149 Invariant {
150 /// The broken rule.
151 what: &'static str,
152 },
153 /// Directory settings disagree with a store's creation entry (§10).
154 #[error("store settings disagree with creation of {store}")]
155 StoreSettingsMismatch {
156 /// The id in the creation entry.
157 store: coven_foundation::id_source::StoreId,
158 },
159 /// A synced table declaration or schema is invalid.
160 #[error(transparent)]
161 Schema(#[from] crate::SchemaError),
162 /// A write was given files staged, or a pin prepared, in another open
163 /// store, or in this one before it closed: the copies they name aren't
164 /// reserved here (§17.3, §17.8).
165 #[error("these files were not prepared in this open store")]
166 PreparedElsewhere,
167 /// A write made a file device-only and also removed its last reference,
168 /// so the copy kept as its original would name no file (§17.3). Nothing
169 /// committed.
170 #[error("file {file} made device-only has no reference left in the same write")]
171 DeviceOnlyUnreferenced {
172 /// The file.
173 file: coven_foundation::id_source::FileId,
174 },
175 /// A pin prepared over a whole copy already kept found that copy gone
176 /// when its write committed it, evicted or unpinned since: nothing was pinned, and
177 /// preparing again downloads it. A prepare whose partial download the
178 /// app's unpin ended meanwhile fails with it too (§17.8).
179 #[error("the kept copy of file {file} changed since its pin was prepared")]
180 PinChanged {
181 /// The file.
182 file: coven_foundation::id_source::FileId,
183 },
184 /// One of coven's steps in this write failed, and the write's closure
185 /// went on to return success: the write rolls back, since a failed step
186 /// may have made only part of its change (§4).
187 #[error("a step of this write failed")]
188 StepFailed,
189 /// One of the app's statements in this write failed, and the write's
190 /// closure went on to return success: the write rolls back, since SQLite
191 /// may have kept part of the statement's change or undone rows coven saw
192 /// it change (§4).
193 #[error("a statement of this write failed")]
194 StatementFailed,
195 /// App SQL read, changed or defined one of coven's internal objects (§4).
196 #[error("app SQL cannot access internal object {table}")]
197 InternalTable {
198 /// The reserved object.
199 table: String,
200 },
201 /// A local trigger wrote a synced table or a shared trigger a local one (§9.4).
202 #[error("trigger {trigger} cannot write table {table}")]
203 TriggerTarget {
204 /// The trigger doing the write.
205 trigger: String,
206 /// The target table.
207 table: String,
208 },
209 /// A bulk write's statement, or a trigger or foreign-key action it would
210 /// run, writes a synced table (§4, E3). Nothing committed.
211 #[error("a bulk write cannot write synced table {table}")]
212 SyncedTableInBulkWrite {
213 /// The synced table.
214 table: String,
215 },
216 /// A statement of the app's before-commit function, or a trigger or
217 /// foreign-key action it would run, writes a synced table (§9.4, E1).
218 /// Nothing committed.
219 #[error("the app's before-commit function cannot write synced table {table}")]
220 SyncedTableBeforeCommit {
221 /// The synced table.
222 table: String,
223 },
224 /// SQLite rolled the owned transaction back itself, so it can't go on (E3, E13).
225 #[error("SQLite ended the owned transaction")]
226 TransactionEnded,
227 /// App SQL tried transaction control, a PRAGMA, ATTACH, loading an
228 /// extension, changing a hidden rowid, or changing the schema outside a
229 /// migration (§4, E13).
230 #[error("app SQL cannot perform {operation}")]
231 StatementForbidden {
232 /// The refused operation.
233 operation: &'static str,
234 },
235 /// SQLite kept another journal mode instead of WAL (§4).
236 #[error("SQLite kept journal mode {mode} instead of WAL")]
237 WalUnavailable {
238 /// The journal mode SQLite selected.
239 mode: String,
240 },
241 /// An app's SQLite setting is larger than SQLite can hold (api.md E1).
242 #[error("SQLite setting {setting} exceeds {maximum}")]
243 SqliteSettingOutOfRange {
244 /// The setting's PRAGMA name.
245 setting: &'static str,
246 /// The largest value SQLite holds for it.
247 maximum: u64,
248 },
249 /// An app collation has the name of one of SQLite's own (api.md E1).
250 #[error("collation {name} is SQLite's own")]
251 ReservedCollation {
252 /// The name as the app gave it.
253 name: String,
254 },
255 /// The app gave two collations one name, which SQLite compares without
256 /// regard to ASCII case (api.md E1).
257 #[error("collation {name} is registered twice")]
258 DuplicateCollation {
259 /// The second registration's name.
260 name: String,
261 },
262 /// An app function has the name of one SQLite or coven already has, or
263 /// coven's reserved prefix (api.md E1).
264 #[error("function {name} is SQLite's or coven's own")]
265 ReservedFunction {
266 /// The name as the app gave it.
267 name: String,
268 },
269 /// The app gave two functions one name, which SQLite compares without
270 /// regard to ASCII case (api.md E1).
271 #[error("function {name} is registered twice")]
272 DuplicateFunction {
273 /// The second registration's name.
274 name: String,
275 },
276 /// An app function is deterministic and takes no arguments, which SQLite
277 /// evaluates while planning in a way coven can't receive (api.md E1).
278 #[error("function {name} is deterministic and takes no arguments")]
279 ConstantFunction {
280 /// The function's name.
281 name: String,
282 },
283 /// A writable open found a new version of an app collation or function
284 /// that a CHECK or generated column uses. Coven rebuilds only indexes,
285 /// so the open changed nothing (§4).
286 #[error("{name} has a new version, and a CHECK or generated column of {table} uses it")]
287 VersionChangeRefused {
288 /// The collation's or function's name, ASCII lowercase.
289 name: String,
290 /// The table whose CHECK or generated column uses it.
291 table: String,
292 },
293 /// A read-only open found the store's indexes built with another
294 /// version of an app collation or function than the one registered.
295 /// Only a writable open rebuilds them (§4).
296 #[error("the store's indexes use version {built} of {name}, not {registered}")]
297 VersionNotRebuilt {
298 /// The collation's or function's name, ASCII lowercase.
299 name: String,
300 /// The version the store's indexes were built with.
301 built: u32,
302 /// The version this open registered.
303 registered: u32,
304 },
305 /// The wall clock or next timestamp exceeds its representation (§7.2).
306 #[error("clock is outside the timestamp range")]
307 ClockOutOfRange,
308 /// Protected remote input fills the configured disk budget. No input or
309 /// budget change was committed; increase the budget or finish pending work.
310 #[error("retained input requires {required} bytes within a {maximum} byte budget")]
311 InputBudgetExceeded {
312 /// Bytes required after evicting every eligible range.
313 required: u64,
314 /// Configured encrypted-input limit.
315 maximum: u64,
316 },
317 /// A value or row exceeds the format (format.md D1, D2, D5), or a write's
318 /// plaintext and sealing key ids cannot fit in its SQLite queue row (§6.3).
319 #[error("{field} length {actual} exceeds {maximum}")]
320 TooLarge {
321 /// The bounded field or collection.
322 field: &'static str,
323 /// Its actual length.
324 actual: u64,
325 /// Its maximum length.
326 maximum: u64,
327 },
328 /// A sum of sizes passes `u64::MAX`, so no total exists to report.
329 #[error("{field} total {total} plus {addend} exceeds {}", u64::MAX)]
330 TotalTooLarge {
331 /// The summed quantity.
332 field: &'static str,
333 /// The sum so far.
334 total: u64,
335 /// The next term, which did not fit.
336 addend: u64,
337 },
338 /// A reference reaches an audience the source row's readers cannot read (§15.3).
339 #[error("reference {table}.{column} at {key:?} reaches another audience")]
340 ReferenceAudience {
341 /// The referencing table.
342 table: String,
343 /// Its row's primary key.
344 key: crate::RowKey,
345 /// The referencing column.
346 column: String,
347 },
348 /// A write targets a circle whose deletion has been applied (§15.9).
349 #[error("circle {0} has been deleted")]
350 DeletedCircle(coven_foundation::id_source::CircleId),
351 /// A local write targets a circle this member is not in or the store does not have (§15).
352 #[error("not a member of circle {0}")]
353 NotInCircle(coven_foundation::id_source::CircleId),
354 /// A write with a synced change on a store a join published, before the
355 /// state its device has applied registers the device (§7.1, §13.4).
356 #[error("this device is not registered yet")]
357 NotRegistered,
358 /// This audience still exposes its previous data while its selected boundary reloads (§16.5).
359 #[error("audience {0:?} is reloading")]
360 AudienceReloading(coven_merge::Audience),
361 /// The write directly changed another member's row of an `owner_only()`
362 /// table: a statement, a shared trigger, or coven copying or dismissing
363 /// it for the app (§9.6). The transaction, including its upload record,
364 /// did not commit.
365 #[error("{table} row {key:?} belongs to member {owner:?}")]
366 NotOwner {
367 /// The owned row's table.
368 table: String,
369 /// Its primary key, in declared key order.
370 key: crate::RowKey,
371 /// The member who originally created it.
372 owner: coven_foundation::id_source::MemberId,
373 },
374 /// The write directly changed a row of an `admin_only()` table, and this
375 /// device's member isn't an admin in the state it has applied: a
376 /// statement, a shared trigger, or coven copying or dismissing it for
377 /// the app (§9.6). The transaction, including its upload record, did
378 /// not commit.
379 #[error("{table} row {key:?} can be changed only by an admin")]
380 NotAdmin {
381 /// The row's table.
382 table: String,
383 /// Its primary key, in declared key order.
384 key: crate::RowKey,
385 },
386 /// The write's foreign-key actions on this row are not the schema's exact
387 /// consequence of its direct changes, so every receiver would refuse
388 /// them (§9.6). The transaction, including its upload record, did not
389 /// commit.
390 #[error("{table} row {key:?} is not an exact foreign-key effect")]
391 InvalidForeignKeyEffect {
392 /// The row's table.
393 table: String,
394 /// Its primary key, in declared key order.
395 key: crate::RowKey,
396 },
397 /// An inserted row's independent key holds no UUID (§9.2).
398 #[error("independent key {key:?} of {table} does not contain a canonical lowercase UUIDv4 or UUIDv7")]
399 KeyNotUuid {
400 /// The inserted row's table.
401 table: String,
402 /// Its primary key, in declared key order.
403 key: crate::RowKey,
404 },
405 /// A root row's audience cell is neither `store` nor a circle id in
406 /// canonical lowercase form (§15).
407 #[error("audience cell of {table} at {key:?} is neither `store` nor a canonical lowercase circle id")]
408 InvalidAudience {
409 /// The written row's table.
410 table: String,
411 /// Its primary key, in declared key order.
412 key: crate::RowKey,
413 },
414 /// A downloaded write fails the merge's checks and is never applied (§19.1).
415 #[error("invalid write {write:?}: {error}")]
416 InvalidWrite {
417 /// The refused write's device and write number.
418 write: coven_merge::WriteId,
419 /// The merge rule it broke.
420 #[source]
421 error: coven_merge::MergeError,
422 },
423 /// Original row-change evidence is unavailable. Receipt waits without
424 /// consuming the position; local authoring rolls back instead of guessing.
425 #[error("missing original write sources: {0:?}")]
426 MissingWriteSources(Vec<coven_format::write_sources::ChangeId>),
427 /// A waiting record or its conversion violates the write format (E13).
428 #[error(transparent)]
429 WriteFormat(coven_format::Error),
430 /// A migration's declared kind disagrees with its runtime classification.
431 #[error("migration {version} declared the wrong kind")]
432 MigrationKindMismatch {
433 /// The refused migration's version.
434 version: u32,
435 },
436 /// A breaking run's rows of a table in an audience differ from the same
437 /// migrations run over only that audience's rows and the store's: they
438 /// came from another circle, a local table or this device's own state.
439 #[error("a migration's {table} rows in {audience} depend on rows outside it")]
440 MigrationReadsAcross {
441 /// A table whose rows differ.
442 table: String,
443 /// The audience whose rows differ.
444 audience: coven_merge::Audience,
445 },
446 /// A rebuild's migration write was given a header that is not the one the
447 /// rebuild's store can make: it must be a migration at the store's newest
448 /// version, this device's next write, read through the slot the store has
449 /// applied (§18.3).
450 #[error("a rebuild's migration write header: {reason}")]
451 RebuildHeader {
452 /// What about the header the store refused.
453 reason: &'static str,
454 },
455 /// A synced row of a table that synced before a breaking run has no merge
456 /// record, so the check of what the run reads can't tell its audience:
457 /// the database is damaged.
458 #[error("a synced row of {table} has no merge record")]
459 UnrecordedRow {
460 /// The table holding the row.
461 table: String,
462 },
463 /// A conversion changed or introduced a reference whose generation it cannot know (E13).
464 #[error("conversion cannot change reference {table}.{column}")]
465 MigrationReference {
466 /// The referencing table in the converted change.
467 table: String,
468 /// The referencing column in the converted change.
469 column: String,
470 },
471 /// A converted row names the same column twice.
472 #[error("migration conversion repeats {table}.{column}")]
473 MigrationDuplicateColumn {
474 /// The converted table.
475 table: String,
476 /// The repeated column.
477 column: String,
478 },
479 /// A converted column is absent from the target schema.
480 #[error("converted column {table}.{column} is absent from the schema")]
481 MigrationColumnMissing {
482 /// The converted table.
483 table: String,
484 /// The absent column.
485 column: String,
486 },
487 /// A converted table has no primary index.
488 #[error("converted table {table} has no primary index")]
489 MigrationPrimaryKeyMissing {
490 /// The converted table.
491 table: String,
492 },
493 /// A converted key has the wrong number of values.
494 #[error("converted key of {table} has {actual} values, expected {expected}")]
495 MigrationKeyArity {
496 /// The converted table.
497 table: String,
498 /// The primary index width.
499 expected: usize,
500 /// The supplied key width.
501 actual: usize,
502 },
503 /// A converted row or reference names an absent table.
504 #[error("converted table {table} is absent from the schema")]
505 MigrationTableMissing {
506 /// The absent table.
507 table: String,
508 },
509 /// Distinct original references became the same converted reference.
510 #[error("converted references of {table} collide at {reference:?}")]
511 MigrationReferenceCollision {
512 /// The original referencing table.
513 table: String,
514 /// The repeated converted reference.
515 reference: coven_merge::ForeignKey,
516 },
517 /// A write dismissed a removed row, deleting it for good, and also
518 /// changed that row or one its delete cascades to (§8.4).
519 #[error("a write dismissing {table} at {key:?} also changes it")]
520 DismissedRowChanged {
521 /// The declared table.
522 table: String,
523 /// The row's key.
524 key: crate::RowKey,
525 },
526 /// A write changed a write-once file reference that named a file (§17.2).
527 #[error("file reference on {table} at {key:?} cannot change")]
528 FileWriteOnce {
529 /// The declared table.
530 table: String,
531 /// The row's key.
532 key: crate::RowKey,
533 },
534 /// The user's original disappeared.
535 #[error("user file is missing: {}", path.display())]
536 UserFileMissing {
537 /// The original path.
538 path: std::path::PathBuf,
539 },
540 /// The user's original changed during preparation or since it was prepared.
541 #[error("user file changed: {}", path.display())]
542 UserFileChanged {
543 /// The original path.
544 path: std::path::PathBuf,
545 },
546 /// No namespace of this name was declared when the store opened (E1).
547 #[error("file namespace {namespace} is not declared")]
548 UndeclaredNamespace {
549 /// The supplied namespace.
550 namespace: String,
551 },
552 /// A file was staged into a namespace of the other kind: app bytes into a
553 /// user namespace, or a user's original into an app one (§17.1); or a
554 /// bound reference names a user's file (§17.4).
555 #[error("file namespace {namespace} holds {kind:?} files")]
556 NamespaceKind {
557 /// The supplied namespace.
558 namespace: String,
559 /// The kind the namespace was declared with.
560 kind: crate::Provenance,
561 },
562 /// The id source reused the physical name of a kept file: a cache
563 /// file's name, a staged copy's `<folder>/<copy>`, or a staging's folder
564 /// (Appendix C.3).
565 #[error("file name {name:?} is already kept by this device")]
566 FileNameReused {
567 /// The refused physical name, as this device's records hold it.
568 name: String,
569 },
570 /// A file the write staged is referenced by none of its rows (§17.2).
571 #[error("no row references staged file {file} in {namespace}")]
572 FileUnreferenced {
573 /// The staged file's namespace.
574 namespace: String,
575 /// The staged file's id.
576 file: coven_foundation::id_source::FileId,
577 },
578 /// A reference names no file this device has a record of in its row's
579 /// audience (§17.2).
580 #[error("{table}.{column} names {file}, which is no file of its row's audience")]
581 FileUnknown {
582 /// The referencing table.
583 table: String,
584 /// The reference column.
585 column: String,
586 /// The value the column holds.
587 file: String,
588 },
589 /// This device has no record of the file (§17.2): one to move, to make
590 /// device-only, or to stage a new file over.
591 #[error("no file {file} here")]
592 FileAbsent {
593 /// The requested file.
594 file: coven_foundation::id_source::FileId,
595 },
596 /// The file is on another device only, and only that device has its
597 /// bytes: one to move to the cloud (§17.3), or one a write makes a new
598 /// file over (§17.2).
599 #[error("file {file} is on another device")]
600 NotThisDevice {
601 /// The file.
602 file: coven_foundation::id_source::FileId,
603 },
604 /// The file to move is in the cloud already (§17.3).
605 #[error("file {file} is not on this device only")]
606 NotDeviceOnlyHere {
607 /// The file.
608 file: coven_foundation::id_source::FileId,
609 },
610 /// The file to move is in a move already, moving or failed: a file is in
611 /// one move at a time, and the app cancels a failed one to move its files
612 /// again (§17.3).
613 #[error("file {file} is in move {id:?}")]
614 FileInMove {
615 /// The file.
616 file: coven_foundation::id_source::FileId,
617 /// The move that holds it.
618 id: crate::MoveId,
619 },
620 /// A bound reference names a file larger than its limit (§17.4).
621 #[error("{table}.{column} names a file of {size} bytes, over its limit of {limit}")]
622 BoundFileTooLarge {
623 /// The referencing table.
624 table: String,
625 /// The bound reference column.
626 column: String,
627 /// The file's size in bytes.
628 size: u64,
629 /// The column's limit in bytes.
630 limit: u64,
631 },
632 /// A bound reference names a file on one device only that no bound
633 /// upload stores (§17.4).
634 #[error("file {file} is on one device only, with no bound upload")]
635 DeviceOnly {
636 /// The file.
637 file: coven_foundation::id_source::FileId,
638 },
639 /// This device never made the move (§17.3).
640 #[error("no move {id:?} here")]
641 MoveUnknown {
642 /// The move.
643 id: crate::MoveId,
644 },
645 /// The move finished: its files are in the cloud (§17.3).
646 #[error("move {id:?} finished")]
647 MoveFinished {
648 /// The move.
649 id: crate::MoveId,
650 },
651 /// The move is a bound file's: its upload holds a write until the file
652 /// is stored, so it can't be cancelled (§17.4).
653 #[error("move {id:?} stores a bound file")]
654 MoveBound {
655 /// The move.
656 id: crate::MoveId,
657 },
658 /// The file to make device-only is on one device only already, so
659 /// storage holds no bytes of it to download (§17.3).
660 #[error("file {file} is not in the cloud")]
661 NotInCloud {
662 /// The file.
663 file: coven_foundation::id_source::FileId,
664 },
665 /// No record here names the stored bytes a file reference was taken
666 /// over any more: the record went, or a switch took it off them, as
667 /// making the file device-only does. The cache keeps bytes only while a
668 /// record names them, so a pin fetching them keeps nothing (§17.8).
669 #[error("file {file} is no longer stored where its reference names")]
670 NoLongerStored {
671 /// The file.
672 file: coven_foundation::id_source::FileId,
673 },
674 /// Another call making files device-only is writing a copy at this path
675 /// (§17.3).
676 #[error("a copy is being written at {}", path.display())]
677 CopyPathTaken {
678 /// The copy's path.
679 path: std::path::PathBuf,
680 },
681 /// Reading or keeping file bytes failed.
682 #[error(transparent)]
683 Disk(coven_foundation::files::FileError),
684 /// A write queueing a file's upload, as staging for the cloud or a move
685 /// does, could not create the file's random key (§17.3).
686 #[error("creating a file key failed: {0}")]
687 FileKey(#[source] coven_crypto::CryptoError),
688 /// Retaining the store while staging file bytes failed.
689 #[error(transparent)]
690 Lock(StoreLockError),
691 /// File cleanup failed, retaining every failure: on opening (`Ok`), or
692 /// after a failed write, whose error it keeps (Appendix C.3).
693 #[error("file cleanup failed: {failures:?}; write outcome: {write:?}")]
694 FileCleanup {
695 /// `Ok` on opening; otherwise the failed write's error.
696 write: Result<(), Box<DbError>>,
697 /// Each failed byte removal or pending-record update.
698 failures: Vec<DbError>,
699 },
700 /// A snapshot load or file check failed, and so did removing the records
701 /// it staged, which its failure ends (§16.2); both failures are kept,
702 /// and sync judges the load's or check's own as it would alone (§19.1).
703 #[error("removing staged snapshot records failed: {cleanup}; after: {operation}")]
704 StagingCleanup {
705 /// The load's or check's own failure.
706 operation: Box<DbError>,
707 /// Removing the staged records' tables.
708 cleanup: Box<DbError>,
709 },
710 /// An operation no longer has the state expected by its caller.
711 #[error("operation {0:?} changed or is absent")]
712 OperationChanged(crate::OperationId),
713 /// The operation the app acknowledges is still running: it has no
714 /// outcome yet (§11.4).
715 #[error("operation {0:?} is still running")]
716 OperationRunning(crate::OperationId),
717 /// `coven_operations` lists no operation with this id: the app's writes
718 /// never journaled it, or its outcome was acknowledged already (§11.4).
719 #[error("no operation {0:?} is listed")]
720 OperationUnknown(crate::OperationId),
721 /// Self-replacement has paused app writes while queued objects settle
722 /// and the new binding and custody are installed (§12.3, E9).
723 #[error("member keys are changing; app writes are paused")]
724 MemberKeysChanging,
725 /// The prepared raise no longer names the current counted prefix.
726 #[error("raise capture changed before snapshot creation")]
727 CaptureChanged,
728 /// An ordinary snapshot of an audience whose raise this device captured
729 /// and has not published: it would carry a schema version the history
730 /// doesn't hold yet (§16.2).
731 #[error("this device's raise of the audience has not landed")]
732 RaiseWaiting,
733 /// Loading plaintext supplied by sync failed without changing the database.
734 #[error(transparent)]
735 Snapshot(#[from] crate::SnapshotError),
736 /// Closing failed for these connections, after every one was tried (E1).
737 #[error("closing database connections failed: {failures:?}")]
738 Closing {
739 /// Failures in connection-close order.
740 failures: Vec<DbError>,
741 },
742 /// A transaction failed and rolling it back failed too. Later calls fail
743 /// with `RollbackFailed` until the store is reopened (§4).
744 #[error("{operation}; rollback failed: {rollback}")]
745 Rollback {
746 /// The operation that required rollback.
747 operation: Box<DbError>,
748 /// SQLite's rollback failure.
749 #[source]
750 rollback: sqlive::rusqlite::Error,
751 },
752}
753
754impl DbError {
755 /// Whether the disk under the store caused this failure: its files
756 /// could not be read or kept, or SQLite found the disk full, failing,
757 /// read-only or damaged. A failure of any other kind, and one that
758 /// names no disk error, is not the disk's.
759 pub fn is_disk(&self) -> bool {
760 match self {
761 Self::Disk(_) => true,
762 Self::Sqlite(error) => sqlite_error_is_disk(error),
763 Self::Rollback { operation, .. } => operation.is_disk(),
764 _ => false,
765 }
766 }
767}
768
769/// Whether SQLite failed because of the disk under it: full, failing, gone
770/// read-only, or damaged.
771pub fn sqlite_error_is_disk(error: &sqlive::rusqlite::Error) -> bool {
772 matches!(
773 error.sqlite_error_code(),
774 Some(
775 sqlive::rusqlite::ErrorCode::DiskFull
776 | sqlive::rusqlite::ErrorCode::SystemIoFailure
777 | sqlive::rusqlite::ErrorCode::CannotOpen
778 | sqlive::rusqlite::ErrorCode::ReadOnly
779 | sqlive::rusqlite::ErrorCode::DatabaseCorrupt
780 | sqlive::rusqlite::ErrorCode::NotADatabase
781 )
782 )
783}
784
785impl From<coven_foundation::task::TaskFailed> for DbError {
786 fn from(failed: coven_foundation::task::TaskFailed) -> Self {
787 failed.into_error()
788 }
789}
790
791impl From<coven_foundation::files::FileError> for DbError {
792 fn from(error: coven_foundation::files::FileError) -> Self {
793 match error {
794 coven_foundation::files::FileError::Bug(bug) => Self::Bug(bug),
795 error => Self::Disk(error),
796 }
797 }
798}
799
800impl From<StoreLockError> for DbError {
801 fn from(error: StoreLockError) -> Self {
802 match error {
803 StoreLockError::Bug(bug) => Self::Bug(bug),
804 error => Self::Lock(error),
805 }
806 }
807}
808
809impl From<coven_foundation::files::WriterError> for DbError {
810 fn from(error: coven_foundation::files::WriterError) -> Self {
811 match error {
812 coven_foundation::files::WriterError::Lock(error) => error.into(),
813 coven_foundation::files::WriterError::File(error) => error.into(),
814 }
815 }
816}
817
818impl From<coven_foundation::files::StagingFolderError> for DbError {
819 fn from(error: coven_foundation::files::StagingFolderError) -> Self {
820 match error {
821 coven_foundation::files::StagingFolderError::Taken(folder) => {
822 Self::FileNameReused { name: folder.as_str().to_owned() }
823 }
824 coven_foundation::files::StagingFolderError::Writer(error) => error.into(),
825 }
826 }
827}
828
829impl From<coven_format::Error> for DbError {
830 fn from(error: coven_format::Error) -> Self {
831 match error {
832 coven_format::Error::Limit { field, actual, maximum } => {
833 Self::TooLarge { field, actual: actual as u64, maximum: maximum as u64 }
834 }
835 error => Self::WriteFormat(error),
836 }
837 }
838}
839
840impl From<sqlive::rusqlite::Error> for DbError {
841 fn from(error: sqlive::rusqlite::Error) -> Self {
842 match error {
843 sqlive::rusqlite::Error::UserFunctionError(source) => {
844 match crate::reported_engine_errors::raised(source) {
845 Ok(error) => error,
846 Err(source) => Self::Sqlite(sqlive::rusqlite::Error::UserFunctionError(source)),
847 }
848 }
849 // A column coven reads into one of its types, such as a `RowKey`,
850 // fails with what that type found.
851 sqlive::rusqlite::Error::FromSqlConversionFailure(index, kind, source) => {
852 match crate::reported_engine_errors::raised(source) {
853 Ok(error) => error,
854 Err(source) => Self::Sqlite(sqlive::rusqlite::Error::FromSqlConversionFailure(
855 index, kind, source,
856 )),
857 }
858 }
859 // SQLite found a page it can't read as what it should hold, or a
860 // file that isn't a database: the damage, wherever a statement
861 // met it, is the store's, not the statement's (§19.3).
862 sqlive::rusqlite::Error::SqliteFailure(failure, _)
863 if matches!(
864 failure.code,
865 sqlive::rusqlite::ErrorCode::DatabaseCorrupt
866 | sqlive::rusqlite::ErrorCode::NotADatabase
867 ) =>
868 {
869 Self::DamagedDatabase
870 }
871 error => Self::Sqlite(error),
872 }
873 }
874}
875
876#[cfg(test)]
877#[path = "error_tests.rs"]
878mod tests;