1use std::time::Duration;
4
5use khive_storage::error::{SqliteWriteFailure, SqliteWriteStage};
6use khive_storage::{StorageCapability, StorageError, WriterTaskRequestState};
7use thiserror::Error;
8
9pub(crate) fn native_write_failure(
12 error: &(dyn std::error::Error + 'static),
13 stage: SqliteWriteStage,
14) -> Option<SqliteWriteFailure> {
15 if let Some(error) = error.downcast_ref::<StorageError>() {
16 return match error {
17 StorageError::SqliteWrite { failure, .. } => Some(*failure),
18 StorageError::Driver { source, .. } => native_write_failure(source.as_ref(), stage),
19 StorageError::WriterTaskRequestFailed { source, .. } => {
20 native_write_failure(source.as_ref(), stage)
21 }
22 _ => None,
23 };
24 }
25 if let Some(error) = error.downcast_ref::<SqliteError>() {
26 return match error {
27 SqliteError::Write { stage, source } => native_write_failure(source, *stage),
28 SqliteError::WriteSettlementUnknown { failure } => Some(*failure),
29 SqliteError::Rusqlite(source) => native_write_failure(source, stage),
30 _ => None,
31 };
32 }
33 if let Some(
34 rusqlite::Error::SqliteFailure(code, _)
35 | rusqlite::Error::SqlInputError { error: code, .. },
36 ) = error.downcast_ref::<rusqlite::Error>()
37 {
38 return Some(SqliteWriteFailure {
39 stage,
40 primary_code: code.extended_code & 0xff,
41 extended_code: code.extended_code,
42 settlement_unknown: false,
43 });
44 }
45 None
46}
47
48pub(crate) fn with_write_stage(error: StorageError, stage: SqliteWriteStage) -> StorageError {
49 match native_write_failure(&error, stage) {
50 Some(failure) => error.with_sqlite_write_failure(failure),
51 None => error,
52 }
53}
54
55pub(crate) fn statement_failure(error: StorageError) -> StorageError {
56 with_write_stage(error, SqliteWriteStage::Statement)
57}
58
59pub(crate) fn unknown_write_settlement(mut error: StorageError) -> StorageError {
60 if let StorageError::SqliteWrite { failure, .. } = &mut error {
61 failure.settlement_unknown = true;
62 }
63 error
64}
65
66pub const SQLITE_WAL_CAPACITY_REFUSED_STAGE: &str = "sqlite_wal_capacity_refused";
69pub const SQLITE_WAL_CAPACITY_UNAVAILABLE_STAGE: &str = "sqlite_wal_capacity_unavailable";
70
71#[derive(Debug, Error)]
73pub enum SqliteError {
74 #[error("strict writer routing refused a direct logical write: {operation}")]
75 WriterRouteViolation { operation: &'static str },
76
77 #[error("sqlite error: {source}")]
78 Write {
79 stage: SqliteWriteStage,
80 #[source]
81 source: rusqlite::Error,
82 },
83 #[error(transparent)]
85 RequestReadStopped(khive_storage::StorageError),
86
87 #[error("sqlite error: {0}")]
89 Rusqlite(#[from] rusqlite::Error),
90
91 #[error("invalid data: {0}")]
93 InvalidData(String),
94
95 #[error("pooled writer contains an inherited transaction; prior side effects are unknown")]
98 InheritedWriterTransaction,
99
100 #[error("writer transaction settlement is unknown; connection retired")]
102 WriterSettlementUnknown,
103
104 #[error("writer transaction settlement is unknown; connection retired")]
106 WriteSettlementUnknown { failure: SqliteWriteFailure },
107
108 #[error("writer refused: an earlier write's settlement is unknown; this write did not start")]
112 WriterPoisoned,
113
114 #[error("invalid data: timed out after {timeout:?} waiting for sqlite writer connection")]
123 WriterPoolCheckoutTimeout {
124 timeout: Duration,
126 },
127
128 #[error(
131 "refusing sqlite write on {volume}: {available_bytes} bytes available, \
132 at or below the {floor_bytes}-byte free-space floor plus \
133 {required_headroom_bytes} bytes of operation headroom"
134 )]
135 CapacityFloor {
136 volume: String,
137 available_bytes: u64,
138 floor_bytes: u64,
139 required_headroom_bytes: u64,
140 },
141
142 #[error("sqlite capacity admission unavailable in {phase} phase: {message}")]
145 CapacityUnavailable {
146 phase: khive_storage::CapacityUnavailablePhase,
147 message: String,
148 },
149
150 #[error(
154 "volume lease re-entry: this thread already holds the lease for this volume \
155 (held at {holder_site}, requested again at {requester_site})"
156 )]
157 VolumeLeaseReentry {
158 holder_site: String,
159 requester_site: String,
160 },
161
162 #[error("invalid WAL ceiling {bytes} bytes: exceeds supported SQLite file offsets")]
165 WalCeilingOffsetOverflow { bytes: u64 },
166
167 #[error("invalid WAL ceiling {bytes} bytes: {backend_kind} does not support WAL enforcement")]
169 WalCeilingUnsupported {
170 bytes: u64,
171 backend_kind: &'static str,
172 },
173
174 #[error(
176 "invalid WAL ceiling {bytes} bytes: page size {page_size} requires at least {minimum_bytes} bytes for one WAL frame"
177 )]
178 WalCeilingBelowMinimum {
179 bytes: u64,
180 page_size: u64,
181 minimum_bytes: u64,
182 },
183
184 #[error(
186 "{stage}: WAL ceiling {bytes} bytes cannot be enforced: missing {capability}",
187 stage = SQLITE_WAL_CAPACITY_UNAVAILABLE_STAGE
188 )]
189 WalCapacityUnavailable {
190 bytes: u64,
191 capability: &'static str,
192 },
193
194 #[error("invalid config: {0}")]
199 InvalidConfig(String),
200
201 #[error("io error: {0}")]
203 Io(#[from] std::io::Error),
204
205 #[error("migration v{version} failed: {error}")]
207 Migration {
208 version: u32,
210 error: String,
212 #[source]
216 source: Option<Box<SqliteError>>,
217 },
218}
219
220impl SqliteError {
221 pub fn write(error: rusqlite::Error, stage: SqliteWriteStage) -> Self {
223 if matches!(
224 error,
225 rusqlite::Error::SqliteFailure(..) | rusqlite::Error::SqlInputError { .. }
226 ) {
227 Self::Write {
228 stage,
229 source: error,
230 }
231 } else {
232 Self::Rusqlite(error)
233 }
234 }
235
236 pub(crate) fn settlement_with_cause(
237 error: &(dyn std::error::Error + 'static),
238 stage: SqliteWriteStage,
239 ) -> Self {
240 match native_write_failure(error, stage) {
241 Some(mut failure) => {
242 failure.settlement_unknown = true;
243 Self::WriteSettlementUnknown { failure }
244 }
245 None => Self::WriterSettlementUnknown,
246 }
247 }
248
249 pub fn write_failure(&self) -> Option<SqliteWriteFailure> {
250 match self {
251 Self::Write { stage, source } => native_write_failure(source, *stage),
252 Self::WriteSettlementUnknown { failure } => Some(*failure),
253 _ => None,
254 }
255 }
256 pub fn migration(version: u32, cause: impl std::fmt::Display + Into<SqliteError>) -> Self {
263 let error = cause.to_string();
264 Self::Migration {
265 version,
266 error,
267 source: Some(Box::new(cause.into())),
268 }
269 }
270
271 pub fn migration_with_cause(
274 version: u32,
275 message: impl Into<String>,
276 cause: impl Into<SqliteError>,
277 ) -> Self {
278 Self::Migration {
279 version,
280 error: message.into(),
281 source: Some(Box::new(cause.into())),
282 }
283 }
284
285 pub fn migration_message(version: u32, message: impl Into<String>) -> Self {
287 Self::Migration {
288 version,
289 error: message.into(),
290 source: None,
291 }
292 }
293
294 pub fn migration_cause(&self) -> Option<&SqliteError> {
296 match self {
297 Self::Migration { source, .. } => source.as_deref(),
298 _ => None,
299 }
300 }
301
302 pub fn native_extended_code(&self) -> Option<i32> {
308 match self {
309 Self::Rusqlite(source) | Self::Write { source, .. } => {
310 Self::driver_extended_code(source)
311 }
312 Self::WriteSettlementUnknown { failure } => Some(failure.extended_code),
313 Self::Migration { source, .. } => source
314 .as_deref()
315 .and_then(|cause| cause.native_extended_code()),
316 _ => None,
317 }
318 }
319
320 fn driver_extended_code(error: &rusqlite::Error) -> Option<i32> {
321 match error {
322 rusqlite::Error::SqliteFailure(code, _)
323 | rusqlite::Error::SqlInputError { error: code, .. } => Some(code.extended_code),
324 _ => None,
325 }
326 }
327
328 pub fn wal_capacity_stage(&self) -> Option<&'static str> {
330 match self {
331 Self::WalCapacityUnavailable { .. } => Some(SQLITE_WAL_CAPACITY_UNAVAILABLE_STAGE),
332 _ => None,
333 }
334 }
335
336 pub fn into_storage_error(
342 self,
343 capability: StorageCapability,
344 operation: &'static str,
345 ) -> StorageError {
346 match self {
347 Self::WriterRouteViolation { operation } => StorageError::WriterRouteViolation {
348 operation: operation.into(),
349 },
350 error @ Self::Write { stage, .. } => {
351 with_write_stage(StorageError::driver(capability, operation, error), stage)
352 }
353 Self::CapacityFloor {
354 volume,
355 available_bytes,
356 floor_bytes,
357 required_headroom_bytes,
358 } => StorageError::CapacityFloor {
359 capability: StorageCapability::Sql,
360 volume,
361 available_bytes,
362 floor_bytes,
363 required_headroom_bytes,
364 },
365 Self::CapacityUnavailable { phase, message } => StorageError::CapacityUnavailable {
366 capability: StorageCapability::Sql,
367 phase,
368 message,
369 },
370 Self::WriteSettlementUnknown { failure } => {
371 StorageError::writer_task_terminated(WriterTaskRequestState::SideEffectsUnknown)
372 .with_sqlite_write_failure(failure)
373 }
374 Self::InheritedWriterTransaction | Self::WriterSettlementUnknown => {
375 StorageError::writer_task_terminated(WriterTaskRequestState::SideEffectsUnknown)
376 }
377 Self::WriterPoisoned => {
378 StorageError::writer_task_terminated(WriterTaskRequestState::NotStarted)
379 }
380 other => StorageError::driver(capability, operation, other),
381 }
382 }
383}
384
385#[cfg(test)]
386mod tests {
387 use super::*;
388 use khive_storage::CapacityUnavailablePhase;
389
390 #[test]
391 fn capacity_and_settlement_errors_keep_their_meaning_from_any_store() {
392 for capability in [StorageCapability::Entities, StorageCapability::Sql] {
393 let refused = SqliteError::CapacityFloor {
394 volume: "/volume".to_string(),
395 available_bytes: 99,
396 floor_bytes: 100,
397 required_headroom_bytes: 12,
398 }
399 .into_storage_error(capability, "write");
400 assert!(
401 matches!(
402 refused,
403 StorageError::CapacityFloor {
404 capability: StorageCapability::Sql,
405 available_bytes: 99,
406 floor_bytes: 100,
407 required_headroom_bytes: 12,
408 ..
409 }
410 ),
411 "{capability:?}: {refused:?}"
412 );
413
414 let unavailable = SqliteError::CapacityUnavailable {
415 phase: CapacityUnavailablePhase::LockContended,
416 message: "lease timed out".to_string(),
417 }
418 .into_storage_error(capability, "write");
419 assert!(
420 matches!(
421 unavailable,
422 StorageError::CapacityUnavailable {
423 capability: StorageCapability::Sql,
424 phase: CapacityUnavailablePhase::LockContended,
425 ..
426 }
427 ),
428 "{capability:?}: {unavailable:?}"
429 );
430
431 for unsettled in [
432 SqliteError::InheritedWriterTransaction,
433 SqliteError::WriterSettlementUnknown,
434 ] {
435 let mapped = unsettled.into_storage_error(capability, "write");
436 assert!(
437 matches!(
438 mapped,
439 StorageError::WriterTaskTerminated {
440 request_state: WriterTaskRequestState::SideEffectsUnknown,
441 ..
442 }
443 ),
444 "{capability:?}: {mapped:?}"
445 );
446 }
447
448 let refused = SqliteError::WriterPoisoned.into_storage_error(capability, "write");
449 assert!(
450 matches!(
451 refused,
452 StorageError::WriterTaskTerminated {
453 request_state: WriterTaskRequestState::NotStarted,
454 ..
455 }
456 ),
457 "{capability:?}: {refused:?}"
458 );
459 }
460 }
461}