helios-persistence 0.1.46

Polyglot persistence layer for Helios FHIR Server
Documentation
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
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
//! Error types for the persistence layer.
//!
//! This module defines all error types used throughout the persistence layer,
//! following a hierarchy that separates storage errors, tenant errors, search errors,
//! and transaction errors.

// Error enum variant fields are self-documenting via their #[error(...)] messages
#![allow(missing_docs)]

use std::fmt;

use thiserror::Error;

use crate::tenant::TenantId;

/// The primary error type for all storage operations.
///
/// This enum encompasses all possible errors that can occur during persistence
/// operations, organized by category.
#[derive(Error, Debug)]
pub enum StorageError {
    /// Resource state errors
    #[error(transparent)]
    Resource(#[from] ResourceError),

    /// Concurrency and versioning errors
    #[error(transparent)]
    Concurrency(#[from] ConcurrencyError),

    /// Tenant isolation errors
    #[error(transparent)]
    Tenant(#[from] TenantError),

    /// Validation errors
    #[error(transparent)]
    Validation(#[from] ValidationError),

    /// Search operation errors
    #[error(transparent)]
    Search(#[from] SearchError),

    /// Transaction errors
    #[error(transparent)]
    Transaction(#[from] TransactionError),

    /// Backend-specific errors
    #[error(transparent)]
    Backend(#[from] BackendError),

    /// Bulk export errors
    #[error(transparent)]
    BulkExport(#[from] BulkExportError),

    /// Bulk submit errors
    #[error(transparent)]
    BulkSubmit(#[from] BulkSubmitError),
}

/// Errors related to resource state.
#[derive(Error, Debug)]
pub enum ResourceError {
    /// The requested resource was not found.
    #[error("resource not found: {resource_type}/{id}")]
    NotFound { resource_type: String, id: String },

    /// A resource with the given ID already exists.
    #[error("resource already exists: {resource_type}/{id}")]
    AlreadyExists { resource_type: String, id: String },

    /// The resource has been deleted (HTTP 410 Gone).
    #[error("resource deleted: {resource_type}/{id}")]
    Gone {
        resource_type: String,
        id: String,
        deleted_at: Option<chrono::DateTime<chrono::Utc>>,
    },

    /// The requested version of the resource was not found.
    #[error("version not found: {resource_type}/{id}/_history/{version_id}")]
    VersionNotFound {
        resource_type: String,
        id: String,
        version_id: String,
    },
}

/// Errors related to concurrency control.
#[derive(Error, Debug)]
pub enum ConcurrencyError {
    /// Version conflict detected during optimistic locking.
    #[error("version conflict: expected {expected_version}, found {actual_version}")]
    VersionConflict {
        resource_type: String,
        id: String,
        expected_version: String,
        actual_version: String,
    },

    /// Optimistic lock failure (If-Match precondition failed).
    #[error("optimistic lock failure: resource {resource_type}/{id} has been modified")]
    OptimisticLockFailure {
        resource_type: String,
        id: String,
        expected_etag: String,
        actual_etag: Option<String>,
    },

    /// Deadlock detected during pessimistic locking.
    #[error("deadlock detected while accessing {resource_type}/{id}")]
    Deadlock { resource_type: String, id: String },

    /// Lock acquisition timed out.
    #[error("lock timeout after {timeout_ms}ms for {resource_type}/{id}")]
    LockTimeout {
        resource_type: String,
        id: String,
        timeout_ms: u64,
    },
}

/// Errors related to tenant isolation.
#[derive(Error, Debug)]
pub enum TenantError {
    /// Access to resource denied for the current tenant.
    #[error("access denied: tenant {tenant_id} cannot access {resource_type}/{resource_id}")]
    AccessDenied {
        tenant_id: TenantId,
        resource_type: String,
        resource_id: String,
    },

    /// The specified tenant does not exist or is invalid.
    #[error("invalid tenant: {tenant_id}")]
    InvalidTenant { tenant_id: TenantId },

    /// Tenant is suspended and cannot perform operations.
    #[error("tenant suspended: {tenant_id}")]
    TenantSuspended { tenant_id: TenantId },

    /// Cross-tenant reference not allowed.
    #[error(
        "cross-tenant reference not allowed: resource in tenant {source_tenant} references resource in tenant {target_tenant}"
    )]
    CrossTenantReference {
        source_tenant: TenantId,
        target_tenant: TenantId,
        reference: String,
    },

    /// Operation not permitted for tenant.
    #[error("operation {operation} not permitted for tenant {tenant_id}")]
    OperationNotPermitted {
        tenant_id: TenantId,
        operation: String,
    },
}

/// Errors related to resource validation.
#[derive(Error, Debug)]
pub enum ValidationError {
    /// The resource failed validation.
    #[error("invalid resource: {message}")]
    InvalidResource {
        message: String,
        details: Vec<ValidationDetail>,
    },

    /// The search parameter is invalid.
    #[error("invalid search parameter: {parameter}")]
    InvalidSearchParameter { parameter: String, message: String },

    /// The resource type is not supported.
    #[error("unsupported resource type: {resource_type}")]
    UnsupportedResourceType { resource_type: String },

    /// Missing required field.
    #[error("missing required field: {field}")]
    MissingRequiredField { field: String },

    /// Invalid reference format.
    #[error("invalid reference: {reference}")]
    InvalidReference { reference: String, message: String },
}

/// Detailed validation error information.
#[derive(Debug, Clone)]
pub struct ValidationDetail {
    /// The path to the field with the error (FHIRPath expression).
    pub path: String,
    /// A human-readable error message.
    pub message: String,
    /// The type of validation error.
    pub severity: ValidationSeverity,
}

/// Severity level for validation errors.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ValidationSeverity {
    /// Fatal error - operation cannot proceed.
    Error,
    /// Warning - operation can proceed but with concerns.
    Warning,
    /// Informational - no action required.
    Information,
}

impl fmt::Display for ValidationSeverity {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ValidationSeverity::Error => write!(f, "error"),
            ValidationSeverity::Warning => write!(f, "warning"),
            ValidationSeverity::Information => write!(f, "information"),
        }
    }
}

/// Errors related to search operations.
#[derive(Error, Debug)]
pub enum SearchError {
    /// The search parameter type is not supported.
    #[error("unsupported search parameter type: {param_type}")]
    UnsupportedParameterType { param_type: String },

    /// The search modifier is not supported for this parameter type.
    #[error("unsupported modifier '{modifier}' for parameter type '{param_type}'")]
    UnsupportedModifier {
        modifier: String,
        param_type: String,
    },

    /// Chained search is not supported by this backend.
    #[error("chained search not supported: {chain}")]
    ChainedSearchNotSupported { chain: String },

    /// Reverse chaining (_has) is not supported by this backend.
    #[error("reverse chaining (_has) not supported")]
    ReverseChainNotSupported,

    /// Include/revinclude not supported.
    #[error("{operation} not supported by this backend")]
    IncludeNotSupported { operation: String },

    /// Too many results to return.
    #[error("search result limit exceeded: found {count}, maximum is {max}")]
    TooManyResults { count: usize, max: usize },

    /// Invalid cursor for pagination.
    #[error("invalid pagination cursor: {cursor}")]
    InvalidCursor { cursor: String },

    /// Search query parsing failed.
    #[error("failed to parse search query: {message}")]
    QueryParseError { message: String },

    /// Composite search parameter error.
    #[error("invalid composite search parameter: {message}")]
    InvalidComposite { message: String },

    /// Text search not available.
    #[error("full-text search not available")]
    TextSearchNotAvailable,
}

/// Errors related to transactions.
#[derive(Error, Debug)]
pub enum TransactionError {
    /// Transaction timed out.
    #[error("transaction timed out after {timeout_ms}ms")]
    Timeout { timeout_ms: u64 },

    /// Transaction was rolled back.
    #[error("transaction rolled back: {reason}")]
    RolledBack { reason: String },

    /// Transaction is no longer valid (already committed or rolled back).
    #[error("transaction no longer valid")]
    InvalidTransaction,

    /// Nested transactions not supported.
    #[error("nested transactions not supported")]
    NestedNotSupported,

    /// Bundle processing error.
    #[error("bundle processing error at entry {index}: {message}")]
    BundleError { index: usize, message: String },

    /// Conditional operation matched multiple resources.
    #[error("conditional {operation} matched {count} resources, expected at most 1")]
    MultipleMatches { operation: String, count: usize },

    /// Isolation level not supported.
    #[error("isolation level {level} not supported by this backend")]
    UnsupportedIsolationLevel { level: String },
}

/// Errors originating from the database backend.
#[derive(Error, Debug)]
pub enum BackendError {
    /// The backend is currently unavailable.
    #[error("backend unavailable: {backend_name}")]
    Unavailable {
        backend_name: String,
        message: String,
    },

    /// Connection to the backend failed.
    #[error("connection failed to {backend_name}: {message}")]
    ConnectionFailed {
        backend_name: String,
        message: String,
    },

    /// Connection pool exhausted.
    #[error("connection pool exhausted for {backend_name}")]
    PoolExhausted { backend_name: String },

    /// The requested capability is not supported by this backend.
    #[error("capability '{capability}' not supported by {backend_name}")]
    UnsupportedCapability {
        backend_name: String,
        capability: String,
    },

    /// Schema migration error.
    #[error("schema migration failed: {message}")]
    MigrationError { message: String },

    /// Internal backend error.
    #[error("internal error in {backend_name}: {message}")]
    Internal {
        backend_name: String,
        message: String,
        #[source]
        source: Option<Box<dyn std::error::Error + Send + Sync>>,
    },

    /// Query execution error.
    #[error("query execution failed: {message}")]
    QueryError { message: String },

    /// Serialization/deserialization error.
    #[error("serialization error: {message}")]
    SerializationError { message: String },
}

/// Errors related to bulk export operations.
#[derive(Error, Debug)]
pub enum BulkExportError {
    /// The export job was not found.
    #[error("export job not found: {job_id}")]
    JobNotFound { job_id: String },

    /// The job is in an invalid state for the requested operation.
    #[error("invalid job state: job {job_id} is {actual}, expected {expected}")]
    InvalidJobState {
        job_id: String,
        expected: String,
        actual: String,
    },

    /// The resource type cannot be exported.
    #[error("resource type '{resource_type}' is not exportable")]
    TypeNotExportable { resource_type: String },

    /// Invalid export request.
    #[error("invalid export request: {message}")]
    InvalidRequest { message: String },

    /// The specified group was not found.
    #[error("group not found: {group_id}")]
    GroupNotFound { group_id: String },

    /// The output format is not supported.
    #[error("unsupported export format: {format}")]
    UnsupportedFormat { format: String },

    /// Invalid type filter.
    #[error("invalid type filter for {resource_type}: {message}")]
    InvalidTypeFilter {
        resource_type: String,
        message: String,
    },

    /// The export was cancelled.
    #[error("export job {job_id} was cancelled")]
    Cancelled { job_id: String },

    /// Error writing export output.
    #[error("export write error: {message}")]
    WriteError { message: String },

    /// Too many concurrent exports.
    #[error("too many concurrent exports (maximum: {max_concurrent})")]
    TooManyConcurrentExports { max_concurrent: u32 },
}

/// Errors related to bulk submit operations.
#[derive(Error, Debug)]
pub enum BulkSubmitError {
    /// The submission was not found.
    #[error("submission not found: {submitter}/{submission_id}")]
    SubmissionNotFound {
        submitter: String,
        submission_id: String,
    },

    /// The manifest was not found.
    #[error("manifest not found: {submission_id}/{manifest_id}")]
    ManifestNotFound {
        submission_id: String,
        manifest_id: String,
    },

    /// The submission is in an invalid state for the requested operation.
    #[error("invalid submission state: {submission_id} is {actual}, expected {expected}")]
    InvalidState {
        submission_id: String,
        expected: String,
        actual: String,
    },

    /// The submission is already complete.
    #[error("submission {submission_id} is already complete")]
    AlreadyComplete { submission_id: String },

    /// The submission was aborted.
    #[error("submission {submission_id} was aborted: {reason}")]
    Aborted {
        submission_id: String,
        reason: String,
    },

    /// Maximum errors exceeded.
    #[error("submission {submission_id} exceeded maximum errors ({max_errors})")]
    MaxErrorsExceeded {
        submission_id: String,
        max_errors: u32,
    },

    /// Error parsing NDJSON entry.
    #[error("parse error at line {line}: {message}")]
    ParseError { line: u64, message: String },

    /// Invalid resource in submission.
    #[error("invalid resource at line {line}: {message}")]
    InvalidResource { line: u64, message: String },

    /// Duplicate submission ID.
    #[error("duplicate submission: {submitter}/{submission_id}")]
    DuplicateSubmission {
        submitter: String,
        submission_id: String,
    },

    /// Error replacing manifest.
    #[error("cannot replace manifest {manifest_url}: {reason}")]
    ManifestReplacementError {
        manifest_url: String,
        reason: String,
    },

    /// Rollback failed.
    #[error("rollback failed for submission {submission_id}: {message}")]
    RollbackFailed {
        submission_id: String,
        message: String,
    },
}

/// Result type alias for storage operations.
pub type StorageResult<T> = Result<T, StorageError>;

/// Result type alias for search operations.
pub type SearchResult<T> = Result<T, SearchError>;

/// Result type alias for transaction operations.
pub type TransactionResult<T> = Result<T, TransactionError>;

// Implement conversions from common error types

impl From<serde_json::Error> for StorageError {
    fn from(err: serde_json::Error) -> Self {
        StorageError::Backend(BackendError::SerializationError {
            message: err.to_string(),
        })
    }
}

impl From<std::io::Error> for BackendError {
    fn from(err: std::io::Error) -> Self {
        BackendError::Internal {
            backend_name: "unknown".to_string(),
            message: err.to_string(),
            source: Some(Box::new(err)),
        }
    }
}

#[cfg(feature = "sqlite")]
impl From<rusqlite::Error> for StorageError {
    fn from(err: rusqlite::Error) -> Self {
        StorageError::Backend(BackendError::Internal {
            backend_name: "sqlite".to_string(),
            message: err.to_string(),
            source: Some(Box::new(err)),
        })
    }
}

#[cfg(feature = "sqlite")]
impl From<r2d2::Error> for StorageError {
    fn from(_err: r2d2::Error) -> Self {
        StorageError::Backend(BackendError::PoolExhausted {
            backend_name: "sqlite".to_string(),
        })
    }
}

#[cfg(feature = "postgres")]
impl From<tokio_postgres::Error> for StorageError {
    fn from(err: tokio_postgres::Error) -> Self {
        StorageError::Backend(BackendError::Internal {
            backend_name: "postgres".to_string(),
            message: err.to_string(),
            source: Some(Box::new(err)),
        })
    }
}

#[cfg(feature = "mongodb")]
impl From<mongodb::error::Error> for StorageError {
    fn from(err: mongodb::error::Error) -> Self {
        StorageError::Backend(BackendError::Internal {
            backend_name: "mongodb".to_string(),
            message: err.to_string(),
            source: Some(Box::new(err)),
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_storage_error_display() {
        let err = StorageError::Resource(ResourceError::NotFound {
            resource_type: "Patient".to_string(),
            id: "123".to_string(),
        });
        assert_eq!(err.to_string(), "resource not found: Patient/123");
    }

    #[test]
    fn test_concurrency_error_display() {
        let err = ConcurrencyError::VersionConflict {
            resource_type: "Patient".to_string(),
            id: "123".to_string(),
            expected_version: "1".to_string(),
            actual_version: "2".to_string(),
        };
        assert_eq!(err.to_string(), "version conflict: expected 1, found 2");
    }

    #[test]
    fn test_tenant_error_display() {
        let err = TenantError::AccessDenied {
            tenant_id: TenantId::new("tenant-a"),
            resource_type: "Patient".to_string(),
            resource_id: "123".to_string(),
        };
        assert!(err.to_string().contains("access denied"));
    }

    #[test]
    fn test_search_error_display() {
        let err = SearchError::UnsupportedModifier {
            modifier: "contains".to_string(),
            param_type: "token".to_string(),
        };
        assert!(err.to_string().contains("unsupported modifier"));
    }

    #[test]
    fn test_validation_severity_display() {
        assert_eq!(ValidationSeverity::Error.to_string(), "error");
        assert_eq!(ValidationSeverity::Warning.to_string(), "warning");
        assert_eq!(ValidationSeverity::Information.to_string(), "information");
    }

    #[test]
    fn test_bulk_export_error_display() {
        let err = BulkExportError::JobNotFound {
            job_id: "abc-123".to_string(),
        };
        assert_eq!(err.to_string(), "export job not found: abc-123");

        let err = BulkExportError::InvalidJobState {
            job_id: "abc-123".to_string(),
            expected: "in-progress".to_string(),
            actual: "complete".to_string(),
        };
        assert!(err.to_string().contains("invalid job state"));
    }

    #[test]
    fn test_bulk_submit_error_display() {
        let err = BulkSubmitError::SubmissionNotFound {
            submitter: "test-system".to_string(),
            submission_id: "sub-123".to_string(),
        };
        assert_eq!(err.to_string(), "submission not found: test-system/sub-123");

        let err = BulkSubmitError::ParseError {
            line: 42,
            message: "invalid JSON".to_string(),
        };
        assert!(err.to_string().contains("line 42"));
    }

    #[test]
    fn test_storage_error_from_bulk_errors() {
        let export_err = BulkExportError::JobNotFound {
            job_id: "test".to_string(),
        };
        let storage_err: StorageError = export_err.into();
        assert!(matches!(storage_err, StorageError::BulkExport(_)));

        let submit_err = BulkSubmitError::SubmissionNotFound {
            submitter: "test".to_string(),
            submission_id: "123".to_string(),
        };
        let storage_err: StorageError = submit_err.into();
        assert!(matches!(storage_err, StorageError::BulkSubmit(_)));
    }
}