helios-persistence 0.2.0

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
//! AWS S3 backend — struct definition, capability matrix, and Backend trait
//! implementation.
use std::any::Any;
use std::future::Future;
use std::sync::Arc;

use async_trait::async_trait;

use crate::core::{Backend, BackendCapability, BackendKind};
use crate::error::{BackendError, StorageError, StorageResult};
use crate::tenant::{TenantContext, TenantId};

use super::client::{AwsS3Client, AwsS3ClientOptions, S3Api, S3ClientError};
use super::config::{S3BackendConfig, S3TenancyMode};
use super::keyspace::S3Keyspace;

/// AWS S3 backend for object-storage persistence.
#[derive(Clone)]
pub struct S3Backend {
    pub(crate) config: S3BackendConfig,
    pub(crate) client: Arc<dyn S3Api>,
}

impl std::fmt::Debug for S3Backend {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("S3Backend")
            .field("config", &self.config)
            .finish_non_exhaustive()
    }
}

/// Opaque connection handle for the S3 backend.
///
/// S3 is stateless from the client's perspective — there is no persistent TCP
/// connection to acquire per-request. This marker type satisfies the `Backend`
/// trait's associated `Connection` type without holding any resources.
#[derive(Debug)]
pub struct S3Connection;

/// Resolved bucket name and key hierarchy for a single tenant.
///
/// Computed once per storage operation from the `TenantContext` and the
/// backend configuration, then passed through the call stack within that
/// operation.
#[derive(Debug, Clone)]
pub(crate) struct TenantLocation {
    /// S3 bucket that holds this tenant's data.
    pub bucket: String,
    /// Keyspace builder scoped to this tenant's prefix hierarchy.
    pub keyspace: S3Keyspace,
}

impl S3Backend {
    /// Returns the backend-level capability declarations for S3.
    ///
    /// Kept independent of client construction so reporting/tests do not need
    /// AWS SDK initialization.
    pub fn declared_capabilities() -> Vec<BackendCapability> {
        vec![
            BackendCapability::Crud,
            BackendCapability::Versioning,
            BackendCapability::InstanceHistory,
            BackendCapability::TypeHistory,
            BackendCapability::SystemHistory,
            BackendCapability::OptimisticLocking,
            BackendCapability::CursorPagination,
            BackendCapability::BulkExport,
            BackendCapability::BulkSubmitIngest,
            BackendCapability::SharedSchema,
            BackendCapability::DatabasePerTenant,
        ]
    }

    /// Creates a new S3 backend using AWS standard credential provider chain.
    pub fn new(config: S3BackendConfig) -> StorageResult<Self> {
        Self::from_env(config)
    }

    /// Creates a new S3 backend using environment/provider chain credentials.
    ///
    /// The region is resolved in priority order: `config.region`, then the
    /// `AWS_REGION` environment variable, then the standard AWS SDK provider
    /// chain (shared config file, EC2 instance metadata, etc.).
    ///
    /// If `validate_buckets_on_startup` is set, every configured bucket is
    /// verified with a `HeadBucket` call before this function returns.
    pub fn from_env(config: S3BackendConfig) -> StorageResult<Self> {
        block_on(Self::from_env_async(config))?
    }

    /// Async constructor for S3 backend using environment/provider chain credentials.
    pub async fn from_env_async(mut config: S3BackendConfig) -> StorageResult<Self> {
        config.validate()?;

        if config.region.is_none() {
            config.region = std::env::var("AWS_REGION").ok();
        }

        apply_s3_compatible_endpoint_defaults(&mut config);

        let sdk_config = AwsS3Client::load_sdk_config(config.region.as_deref()).await;
        let endpoint_url = config
            .endpoint_url
            .as_deref()
            .map(str::trim)
            .filter(|url| !url.is_empty())
            .map(str::to_string);

        let client = Arc::new(AwsS3Client::from_sdk_config_with_options(
            &sdk_config,
            AwsS3ClientOptions {
                endpoint_url,
                force_path_style: config.force_path_style,
            },
        ));

        let backend = Self { config, client };

        if backend.config.validate_buckets_on_startup {
            backend.validate_buckets().await?;
        }

        Ok(backend)
    }
    /// Creates a backend with an injected `S3Api` implementation.
    ///
    /// Intended exclusively for unit tests that supply a mock client.
    /// Not compiled into non-test builds.
    #[cfg(test)]
    pub(crate) fn with_client(
        config: S3BackendConfig,
        client: Arc<dyn S3Api>,
    ) -> StorageResult<Self> {
        config.validate()?;
        Ok(Self { config, client })
    }

    /// Verifies that every bucket referenced in the configuration exists and
    /// is accessible to the current credentials.
    ///
    /// Issues a `HeadBucket` request for each distinct bucket. Returns the
    /// first error encountered; does not attempt to create missing buckets.
    pub(crate) async fn validate_buckets(&self) -> StorageResult<()> {
        for bucket in self.config.configured_buckets() {
            self.client
                .head_bucket(&bucket)
                .await
                .map_err(|e| self.map_client_error(e))?;
        }
        Ok(())
    }

    /// Resolves the bucket and keyspace for the given tenant.
    ///
    /// In `PrefixPerTenant` mode all tenants share one bucket and are separated
    /// by a key prefix derived from the tenant ID. In `BucketPerTenant` mode
    /// each tenant maps to a dedicated bucket looked up from the config map.
    ///
    /// Returns a `TenantError` if the tenant has no bucket assignment in the
    /// `BucketPerTenant` mapping.
    pub(crate) fn tenant_location(&self, tenant: &TenantContext) -> StorageResult<TenantLocation> {
        let global_prefix = self
            .config
            .prefix
            .as_ref()
            .map(|p| p.trim_matches('/').to_string())
            .filter(|p| !p.is_empty());

        match &self.config.tenancy_mode {
            S3TenancyMode::PrefixPerTenant { bucket } => Ok(TenantLocation {
                bucket: bucket.clone(),
                keyspace: S3Keyspace::new(global_prefix)
                    .with_tenant_prefix(tenant.tenant_id().as_str()),
            }),
            S3TenancyMode::BucketPerTenant {
                tenant_bucket_map,
                default_system_bucket,
            } => {
                let tenant_id = tenant.tenant_id().as_str();
                let bucket = tenant_bucket_map
                    .get(tenant_id)
                    .cloned()
                    .or_else(|| {
                        if tenant.tenant_id().is_system() {
                            default_system_bucket.clone()
                        } else {
                            None
                        }
                    })
                    .ok_or_else(|| {
                        StorageError::Tenant(crate::error::TenantError::InvalidTenant {
                            tenant_id: TenantId::new(tenant_id),
                        })
                    })?;

                Ok(TenantLocation {
                    bucket,
                    keyspace: S3Keyspace::new(global_prefix),
                })
            }
        }
    }

    /// Maps a low-level `S3ClientError` to the shared `StorageError` taxonomy.
    ///
    /// This is the error boundary between the S3 SDK layer and the storage
    /// trait layer. Keeping the translation here ensures all storage operations
    /// return consistent error variants regardless of the underlying transport.
    pub(crate) fn map_client_error(&self, error: S3ClientError) -> StorageError {
        match error {
            S3ClientError::NotFound => StorageError::Backend(BackendError::Unavailable {
                backend_name: "s3".to_string(),
                message: "resource not found in S3".to_string(),
            }),
            S3ClientError::PreconditionFailed => StorageError::Backend(BackendError::QueryError {
                message: "S3 precondition failed".to_string(),
            }),
            S3ClientError::Throttled(message) => StorageError::Backend(BackendError::Unavailable {
                backend_name: "s3".to_string(),
                message,
            }),
            S3ClientError::Unavailable(message) => {
                StorageError::Backend(BackendError::Unavailable {
                    backend_name: "s3".to_string(),
                    message,
                })
            }
            S3ClientError::InvalidInput(message) => {
                StorageError::Validation(crate::error::ValidationError::InvalidResource {
                    message,
                    details: Vec::new(),
                })
            }
            S3ClientError::Internal(message) => StorageError::Backend(BackendError::Internal {
                backend_name: "s3".to_string(),
                message,
                source: None,
            }),
        }
    }
}

#[async_trait]
impl Backend for S3Backend {
    type Connection = S3Connection;

    fn kind(&self) -> BackendKind {
        BackendKind::S3
    }

    fn name(&self) -> &'static str {
        "s3"
    }

    fn supports(&self, capability: BackendCapability) -> bool {
        Self::declared_capabilities().contains(&capability)
    }

    fn capabilities(&self) -> Vec<BackendCapability> {
        Self::declared_capabilities()
    }

    async fn acquire(&self) -> Result<Self::Connection, BackendError> {
        Ok(S3Connection)
    }

    async fn release(&self, _conn: Self::Connection) {}

    async fn health_check(&self) -> Result<(), BackendError> {
        self.validate_buckets().await.map_err(|err| match err {
            StorageError::Backend(backend_err) => backend_err,
            other => BackendError::Internal {
                backend_name: "s3".to_string(),
                message: other.to_string(),
                source: None,
            },
        })
    }

    async fn initialize(&self) -> Result<(), BackendError> {
        self.health_check().await
    }

    async fn migrate(&self) -> Result<(), BackendError> {
        // No schema migrations for object storage.
        self.health_check().await
    }
}

/// Applies endpoint-mode defaults without changing standard AWS mode behavior.
fn apply_s3_compatible_endpoint_defaults(config: &mut S3BackendConfig) {
    let has_endpoint_url = config
        .endpoint_url
        .as_deref()
        .map(str::trim)
        .filter(|url| !url.is_empty())
        .is_some();

    if !has_endpoint_url {
        return;
    }

    if !config.force_path_style {
        config.force_path_style = true;
    }

    if config.region.is_none() {
        config.region = Some("us-east-1".to_string());
    }
}

/// Drives an async future to completion from synchronous code.
///
/// If a Tokio runtime is already active, the future is driven on a detached
/// thread to avoid nesting runtimes. Otherwise a temporary single-threaded
/// runtime is created for the duration of the call.
fn block_on<F>(future: F) -> StorageResult<F::Output>
where
    F: Future + Send + 'static,
    F::Output: Send + 'static,
{
    if tokio::runtime::Handle::try_current().is_ok() {
        std::thread::spawn(move || {
            let rt = tokio::runtime::Builder::new_current_thread()
                .enable_all()
                .build()
                .map_err(|e| {
                    StorageError::Backend(BackendError::Internal {
                        backend_name: "s3".to_string(),
                        message: format!("failed to create runtime: {e}"),
                        source: None,
                    })
                })?;
            Ok(rt.block_on(future))
        })
        .join()
        .map_err(|panic_payload| {
            StorageError::Backend(BackendError::Internal {
                backend_name: "s3".to_string(),
                message: format!(
                    "failed to join detached runtime thread: {}",
                    panic_payload_to_message(panic_payload)
                ),
                source: None,
            })
        })?
    } else {
        let rt = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .map_err(|e| {
                StorageError::Backend(BackendError::Internal {
                    backend_name: "s3".to_string(),
                    message: format!("failed to create runtime: {e}"),
                    source: None,
                })
            })?;
        Ok(rt.block_on(future))
    }
}

fn panic_payload_to_message(payload: Box<dyn Any + Send + 'static>) -> String {
    if let Some(message) = payload.downcast_ref::<&str>() {
        (*message).to_string()
    } else if let Some(message) = payload.downcast_ref::<String>() {
        message.clone()
    } else {
        "unknown panic payload".to_string()
    }
}

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

    fn base_config() -> S3BackendConfig {
        S3BackendConfig {
            tenancy_mode: S3TenancyMode::PrefixPerTenant {
                bucket: "test-bucket".to_string(),
            },
            ..Default::default()
        }
    }

    #[test]
    fn endpoint_defaults_not_applied_in_aws_mode() {
        let mut config = base_config();
        config.endpoint_url = None;
        config.region = None;
        config.force_path_style = false;

        apply_s3_compatible_endpoint_defaults(&mut config);

        assert!(config.region.is_none());
        assert!(!config.force_path_style);
    }

    #[test]
    fn endpoint_defaults_applied_when_endpoint_is_set() {
        let mut config = base_config();
        config.endpoint_url = Some("http://127.0.0.1:9000".to_string());
        config.region = None;
        config.force_path_style = false;

        apply_s3_compatible_endpoint_defaults(&mut config);

        assert_eq!(config.region.as_deref(), Some("us-east-1"));
        assert!(config.force_path_style);
    }

    #[test]
    fn block_on_works_inside_current_thread_runtime() {
        let rt = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .expect("build test runtime");

        rt.block_on(async {
            let value = block_on(async { 7usize }).expect("block_on should work");
            assert_eq!(value, 7);
        });
    }
}