helios-persistence 0.1.47

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
//! Tests for FHIR bundle transaction operations.
//!
//! This module tests FHIR transaction bundles including the various
//! HTTP method equivalents and conditional operations.

use serde_json::json;

use helios_persistence::core::{ResourceStorage, TransactionProvider};
use helios_persistence::tenant::{TenantContext, TenantId, TenantPermissions};
use helios_persistence::types::{BundleEntry, BundleRequest, TransactionBundle};

#[cfg(feature = "sqlite")]
use helios_persistence::backends::sqlite::SqliteBackend;

#[cfg(feature = "sqlite")]
fn create_sqlite_backend() -> SqliteBackend {
    let backend = SqliteBackend::in_memory().expect("Failed to create SQLite backend");
    backend.init_schema().expect("Failed to initialize schema");
    backend
}

fn create_tenant() -> TenantContext {
    TenantContext::new(TenantId::new("test-tenant"), TenantPermissions::full_access())
}

// ============================================================================
// Basic Bundle Tests
// ============================================================================

/// Test executing a simple transaction bundle with creates.
#[cfg(feature = "sqlite")]
#[tokio::test]
async fn test_bundle_create_entries() {
    let backend = create_sqlite_backend();
    let tenant = create_tenant();

    let bundle = TransactionBundle::new(vec![
        BundleEntry {
            full_url: Some("urn:uuid:patient-1".to_string()),
            resource: Some(json!({
                "resourceType": "Patient",
                "name": [{"family": "BundlePatient1"}]
            })),
            request: BundleRequest {
                method: "POST".to_string(),
                url: "Patient".to_string(),
                if_match: None,
                if_none_match: None,
                if_none_exist: None,
            },
        },
        BundleEntry {
            full_url: Some("urn:uuid:patient-2".to_string()),
            resource: Some(json!({
                "resourceType": "Patient",
                "name": [{"family": "BundlePatient2"}]
            })),
            request: BundleRequest {
                method: "POST".to_string(),
                url: "Patient".to_string(),
                if_match: None,
                if_none_match: None,
                if_none_exist: None,
            },
        },
    ]);

    let result = backend.execute_transaction(&tenant, bundle).await.unwrap();

    // Should have 2 response entries
    assert_eq!(result.entries.len(), 2);

    // Both should be successful creates
    for entry in &result.entries {
        assert_eq!(entry.response.status, "201 Created");
        assert!(entry.response.location.is_some());
    }

    // Verify resources exist
    let count = backend.count(&tenant, Some("Patient")).await.unwrap();
    assert_eq!(count, 2);
}

/// Test bundle with PUT (create or update).
#[cfg(feature = "sqlite")]
#[tokio::test]
async fn test_bundle_put_entries() {
    let backend = create_sqlite_backend();
    let tenant = create_tenant();

    let bundle = TransactionBundle::new(vec![BundleEntry {
        full_url: Some("urn:uuid:patient-put".to_string()),
        resource: Some(json!({
            "resourceType": "Patient",
            "id": "patient-123",
            "name": [{"family": "PutPatient"}]
        })),
        request: BundleRequest {
            method: "PUT".to_string(),
            url: "Patient/patient-123".to_string(),
            if_match: None,
            if_none_match: None,
            if_none_exist: None,
        },
    }]);

    let result = backend.execute_transaction(&tenant, bundle).await.unwrap();

    assert_eq!(result.entries.len(), 1);
    assert!(
        result.entries[0].response.status == "201 Created"
            || result.entries[0].response.status == "200 OK"
    );

    // Verify resource
    let read = backend
        .read(&tenant, "Patient", "patient-123")
        .await
        .unwrap();
    assert!(read.is_some());
    assert_eq!(read.unwrap().content()["name"][0]["family"], "PutPatient");
}

/// Test bundle with DELETE.
#[cfg(feature = "sqlite")]
#[tokio::test]
async fn test_bundle_delete_entries() {
    let backend = create_sqlite_backend();
    let tenant = create_tenant();

    // First create a resource
    backend
        .create_or_update(
            &tenant,
            "Patient",
            "to-delete",
            json!({"resourceType": "Patient"}),
        )
        .await
        .unwrap();

    let bundle = TransactionBundle::new(vec![BundleEntry {
        full_url: None,
        resource: None,
        request: BundleRequest {
            method: "DELETE".to_string(),
            url: "Patient/to-delete".to_string(),
            if_match: None,
            if_none_match: None,
            if_none_exist: None,
        },
    }]);

    let result = backend.execute_transaction(&tenant, bundle).await.unwrap();

    assert_eq!(result.entries.len(), 1);
    assert!(
        result.entries[0].response.status == "200 OK"
            || result.entries[0].response.status == "204 No Content"
    );

    // Verify deleted
    assert!(!backend.exists(&tenant, "Patient", "to-delete").await.unwrap());
}

// ============================================================================
// Mixed Operation Bundle Tests
// ============================================================================

/// Test bundle with mixed operations (CREATE, UPDATE, DELETE).
#[cfg(feature = "sqlite")]
#[tokio::test]
async fn test_bundle_mixed_operations() {
    let backend = create_sqlite_backend();
    let tenant = create_tenant();

    // Pre-create resources for update and delete
    backend
        .create_or_update(
            &tenant,
            "Patient",
            "update-me",
            json!({"resourceType": "Patient", "name": [{"family": "Original"}]}),
        )
        .await
        .unwrap();
    backend
        .create_or_update(
            &tenant,
            "Patient",
            "delete-me",
            json!({"resourceType": "Patient"}),
        )
        .await
        .unwrap();

    let bundle = TransactionBundle::new(vec![
        // CREATE
        BundleEntry {
            full_url: Some("urn:uuid:new-patient".to_string()),
            resource: Some(json!({
                "resourceType": "Patient",
                "name": [{"family": "NewPatient"}]
            })),
            request: BundleRequest {
                method: "POST".to_string(),
                url: "Patient".to_string(),
                if_match: None,
                if_none_match: None,
                if_none_exist: None,
            },
        },
        // UPDATE
        BundleEntry {
            full_url: None,
            resource: Some(json!({
                "resourceType": "Patient",
                "id": "update-me",
                "name": [{"family": "Updated"}]
            })),
            request: BundleRequest {
                method: "PUT".to_string(),
                url: "Patient/update-me".to_string(),
                if_match: None,
                if_none_match: None,
                if_none_exist: None,
            },
        },
        // DELETE
        BundleEntry {
            full_url: None,
            resource: None,
            request: BundleRequest {
                method: "DELETE".to_string(),
                url: "Patient/delete-me".to_string(),
                if_match: None,
                if_none_match: None,
                if_none_exist: None,
            },
        },
    ]);

    let result = backend.execute_transaction(&tenant, bundle).await.unwrap();

    assert_eq!(result.entries.len(), 3);

    // Verify all operations succeeded
    let count = backend.count(&tenant, Some("Patient")).await.unwrap();
    assert_eq!(count, 2); // 1 pre-existing + 1 new - 1 deleted

    // Verify update
    let updated = backend
        .read(&tenant, "Patient", "update-me")
        .await
        .unwrap()
        .unwrap();
    assert_eq!(updated.content()["name"][0]["family"], "Updated");

    // Verify delete
    assert!(!backend.exists(&tenant, "Patient", "delete-me").await.unwrap());
}

// ============================================================================
// Reference Resolution Tests
// ============================================================================

/// Test bundle with internal references (urn:uuid).
#[cfg(feature = "sqlite")]
#[tokio::test]
async fn test_bundle_internal_references() {
    let backend = create_sqlite_backend();
    let tenant = create_tenant();

    let bundle = TransactionBundle::new(vec![
        // Create patient first
        BundleEntry {
            full_url: Some("urn:uuid:new-patient".to_string()),
            resource: Some(json!({
                "resourceType": "Patient",
                "name": [{"family": "ReferencedPatient"}]
            })),
            request: BundleRequest {
                method: "POST".to_string(),
                url: "Patient".to_string(),
                if_match: None,
                if_none_match: None,
                if_none_exist: None,
            },
        },
        // Create observation referencing patient by urn:uuid
        BundleEntry {
            full_url: Some("urn:uuid:new-observation".to_string()),
            resource: Some(json!({
                "resourceType": "Observation",
                "status": "final",
                "code": {"coding": [{"code": "test"}]},
                "subject": {"reference": "urn:uuid:new-patient"}
            })),
            request: BundleRequest {
                method: "POST".to_string(),
                url: "Observation".to_string(),
                if_match: None,
                if_none_match: None,
                if_none_exist: None,
            },
        },
    ]);

    let result = backend.execute_transaction(&tenant, bundle).await.unwrap();

    assert_eq!(result.entries.len(), 2);

    // Get the patient's assigned ID from the response
    let patient_location = result.entries[0].response.location.as_ref().unwrap();
    let patient_id = patient_location.split('/').last().unwrap();

    // Find the observation and verify reference was resolved
    let obs_location = result.entries[1].response.location.as_ref().unwrap();
    let obs_id = obs_location.split('/').last().unwrap();

    let observation = backend
        .read(&tenant, "Observation", obs_id)
        .await
        .unwrap()
        .unwrap();

    // Reference should be resolved to actual Patient ID
    let subject_ref = observation.content()["subject"]["reference"].as_str().unwrap();
    assert!(
        subject_ref.contains(patient_id),
        "Reference should be resolved to actual patient ID"
    );
}

// ============================================================================
// Conditional Bundle Tests
// ============================================================================

/// Test bundle with conditional create (if-none-exist).
#[cfg(feature = "sqlite")]
#[tokio::test]
async fn test_bundle_conditional_create() {
    let backend = create_sqlite_backend();
    let tenant = create_tenant();

    // First bundle - should create
    let bundle1 = TransactionBundle::new(vec![BundleEntry {
        full_url: Some("urn:uuid:conditional".to_string()),
        resource: Some(json!({
            "resourceType": "Patient",
            "identifier": [{"system": "http://example.org", "value": "12345"}],
            "name": [{"family": "Conditional"}]
        })),
        request: BundleRequest {
            method: "POST".to_string(),
            url: "Patient".to_string(),
            if_match: None,
            if_none_match: None,
            if_none_exist: Some("identifier=http://example.org|12345".to_string()),
        },
    }]);

    let result1 = backend.execute_transaction(&tenant, bundle1).await.unwrap();
    assert_eq!(result1.entries[0].response.status, "201 Created");

    // Second bundle with same condition - should return existing
    let bundle2 = TransactionBundle::new(vec![BundleEntry {
        full_url: Some("urn:uuid:conditional".to_string()),
        resource: Some(json!({
            "resourceType": "Patient",
            "identifier": [{"system": "http://example.org", "value": "12345"}],
            "name": [{"family": "ShouldNotCreate"}]
        })),
        request: BundleRequest {
            method: "POST".to_string(),
            url: "Patient".to_string(),
            if_match: None,
            if_none_match: None,
            if_none_exist: Some("identifier=http://example.org|12345".to_string()),
        },
    }]);

    let result2 = backend.execute_transaction(&tenant, bundle2).await.unwrap();

    // Should not create duplicate
    assert_ne!(result2.entries[0].response.status, "201 Created");

    // Only one patient should exist
    let count = backend.count(&tenant, Some("Patient")).await.unwrap();
    assert_eq!(count, 1);
}

/// Test bundle with conditional update (if-match).
#[cfg(feature = "sqlite")]
#[tokio::test]
async fn test_bundle_conditional_update_if_match() {
    let backend = create_sqlite_backend();
    let tenant = create_tenant();

    // Create initial resource
    let created = backend
        .create_or_update(
            &tenant,
            "Patient",
            "conditional-update",
            json!({"resourceType": "Patient", "name": [{"family": "Original"}]}),
        )
        .await
        .unwrap();

    let etag = format!("W/\"{}\"", created.version());

    // Update with correct ETag
    let bundle = TransactionBundle::new(vec![BundleEntry {
        full_url: None,
        resource: Some(json!({
            "resourceType": "Patient",
            "id": "conditional-update",
            "name": [{"family": "UpdatedWithMatch"}]
        })),
        request: BundleRequest {
            method: "PUT".to_string(),
            url: "Patient/conditional-update".to_string(),
            if_match: Some(etag),
            if_none_match: None,
            if_none_exist: None,
        },
    }]);

    let result = backend.execute_transaction(&tenant, bundle).await.unwrap();
    assert_eq!(result.entries[0].response.status, "200 OK");

    // Verify update
    let read = backend
        .read(&tenant, "Patient", "conditional-update")
        .await
        .unwrap()
        .unwrap();
    assert_eq!(read.content()["name"][0]["family"], "UpdatedWithMatch");
}

/// Test bundle with if-match failure.
#[cfg(feature = "sqlite")]
#[tokio::test]
async fn test_bundle_if_match_failure() {
    let backend = create_sqlite_backend();
    let tenant = create_tenant();

    // Create initial resource
    backend
        .create_or_update(
            &tenant,
            "Patient",
            "version-conflict",
            json!({"resourceType": "Patient"}),
        )
        .await
        .unwrap();

    // Update with wrong ETag
    let bundle = TransactionBundle::new(vec![BundleEntry {
        full_url: None,
        resource: Some(json!({
            "resourceType": "Patient",
            "id": "version-conflict",
            "name": [{"family": "ShouldFail"}]
        })),
        request: BundleRequest {
            method: "PUT".to_string(),
            url: "Patient/version-conflict".to_string(),
            if_match: Some("W/\"wrong-version\"".to_string()),
            if_none_match: None,
            if_none_exist: None,
        },
    }]);

    let result = backend.execute_transaction(&tenant, bundle).await;

    // Should fail due to version mismatch
    assert!(result.is_err() || result.unwrap().entries[0].response.status.contains("409"));
}

// ============================================================================
// Bundle Atomicity Tests
// ============================================================================

/// Test that bundle is atomic - all succeed or all fail.
#[cfg(feature = "sqlite")]
#[tokio::test]
async fn test_bundle_atomicity() {
    let backend = create_sqlite_backend();
    let tenant = create_tenant();

    // Bundle with valid operation and invalid operation
    let bundle = TransactionBundle::new(vec![
        // Valid create
        BundleEntry {
            full_url: Some("urn:uuid:valid".to_string()),
            resource: Some(json!({
                "resourceType": "Patient",
                "name": [{"family": "Valid"}]
            })),
            request: BundleRequest {
                method: "POST".to_string(),
                url: "Patient".to_string(),
                if_match: None,
                if_none_match: None,
                if_none_exist: None,
            },
        },
        // Invalid - delete non-existent
        BundleEntry {
            full_url: None,
            resource: None,
            request: BundleRequest {
                method: "DELETE".to_string(),
                url: "Patient/non-existent-id".to_string(),
                if_match: None,
                if_none_match: None,
                if_none_exist: None,
            },
        },
    ]);

    let result = backend.execute_transaction(&tenant, bundle).await;

    // If transaction failed, no resources should be created
    if result.is_err() {
        let count = backend.count(&tenant, Some("Patient")).await.unwrap();
        assert_eq!(count, 0, "Transaction should be atomic - no partial commits");
    }
}

// ============================================================================
// Bundle Edge Cases
// ============================================================================

/// Test empty bundle.
#[cfg(feature = "sqlite")]
#[tokio::test]
async fn test_bundle_empty() {
    let backend = create_sqlite_backend();
    let tenant = create_tenant();

    let bundle = TransactionBundle::new(vec![]);
    let result = backend.execute_transaction(&tenant, bundle).await;

    // Empty bundle should succeed with empty response
    assert!(result.is_ok());
    assert!(result.unwrap().entries.is_empty());
}

/// Test bundle with single entry.
#[cfg(feature = "sqlite")]
#[tokio::test]
async fn test_bundle_single_entry() {
    let backend = create_sqlite_backend();
    let tenant = create_tenant();

    let bundle = TransactionBundle::new(vec![BundleEntry {
        full_url: Some("urn:uuid:single".to_string()),
        resource: Some(json!({"resourceType": "Patient"})),
        request: BundleRequest {
            method: "POST".to_string(),
            url: "Patient".to_string(),
            if_match: None,
            if_none_match: None,
            if_none_exist: None,
        },
    }]);

    let result = backend.execute_transaction(&tenant, bundle).await.unwrap();
    assert_eq!(result.entries.len(), 1);
    assert_eq!(result.entries[0].response.status, "201 Created");
}

/// Test bundle respects tenant isolation.
#[cfg(feature = "sqlite")]
#[tokio::test]
async fn test_bundle_tenant_isolation() {
    let backend = create_sqlite_backend();
    let tenant_a = TenantContext::new(TenantId::new("tenant-a"), TenantPermissions::full_access());
    let tenant_b = TenantContext::new(TenantId::new("tenant-b"), TenantPermissions::full_access());

    let bundle = TransactionBundle::new(vec![BundleEntry {
        full_url: Some("urn:uuid:tenant-patient".to_string()),
        resource: Some(json!({
            "resourceType": "Patient",
            "name": [{"family": "TenantA"}]
        })),
        request: BundleRequest {
            method: "POST".to_string(),
            url: "Patient".to_string(),
            if_match: None,
            if_none_match: None,
            if_none_exist: None,
        },
    }]);

    let result = backend.execute_transaction(&tenant_a, bundle).await.unwrap();
    let location = result.entries[0].response.location.as_ref().unwrap();
    let patient_id = location.split('/').last().unwrap();

    // Tenant A can see it
    assert!(backend.exists(&tenant_a, "Patient", patient_id).await.unwrap());

    // Tenant B cannot
    assert!(!backend.exists(&tenant_b, "Patient", patient_id).await.unwrap());
}