helios-persistence 0.1.39

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
//! SearchParameter Registry.
//!
//! The registry maintains an in-memory cache of all active SearchParameters,
//! indexed by both (resource_type, param_code) and canonical URL.

use std::collections::HashMap;
use std::sync::Arc;

use serde::{Deserialize, Serialize};
use tokio::sync::broadcast;

use crate::types::SearchParamType;

use super::errors::RegistryError;
use super::loader::SearchParameterLoader;

/// Status of a SearchParameter.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum SearchParameterStatus {
    /// Active - can be used in searches.
    #[default]
    Active,
    /// Draft - informational, not yet active.
    Draft,
    /// Retired - disabled, not usable.
    Retired,
}

impl SearchParameterStatus {
    /// Parse from FHIR status string.
    pub fn from_fhir_status(s: &str) -> Option<Self> {
        match s.to_lowercase().as_str() {
            "active" => Some(SearchParameterStatus::Active),
            "draft" => Some(SearchParameterStatus::Draft),
            "retired" => Some(SearchParameterStatus::Retired),
            _ => None,
        }
    }

    /// Convert to FHIR status string.
    pub fn to_fhir_status(&self) -> &'static str {
        match self {
            SearchParameterStatus::Active => "active",
            SearchParameterStatus::Draft => "draft",
            SearchParameterStatus::Retired => "retired",
        }
    }

    /// Returns true if this status allows the parameter to be used in searches.
    pub fn is_usable(&self) -> bool {
        *self == SearchParameterStatus::Active
    }
}

/// Source of a SearchParameter definition.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum SearchParameterSource {
    /// Built-in standard parameters (bundled at compile time).
    #[default]
    Embedded,
    /// POSTed SearchParameter resources (persisted in database).
    Stored,
    /// Runtime configuration file.
    Config,
}

/// Component of a composite search parameter.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CompositeComponentDef {
    /// Definition URL of the component parameter.
    pub definition: String,
    /// FHIRPath expression for extracting this component.
    pub expression: String,
}

/// Complete definition of a SearchParameter.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SearchParameterDefinition {
    /// Canonical URL (unique identifier).
    pub url: String,

    /// Parameter code (the URL param name, e.g., "name", "identifier").
    pub code: String,

    /// Human-readable name.
    pub name: Option<String>,

    /// Description of the parameter.
    pub description: Option<String>,

    /// The parameter type.
    pub param_type: SearchParamType,

    /// FHIRPath expression for extracting values.
    pub expression: String,

    /// Resource types this parameter applies to.
    pub base: Vec<String>,

    /// Target resource types (for reference parameters).
    pub target: Option<Vec<String>>,

    /// Components (for composite parameters).
    pub component: Option<Vec<CompositeComponentDef>>,

    /// Current status.
    pub status: SearchParameterStatus,

    /// Source of this definition.
    pub source: SearchParameterSource,

    /// Supported modifiers.
    pub modifier: Option<Vec<String>>,

    /// Whether multiple values should use AND or OR logic.
    pub multiple_or: Option<bool>,
    /// Whether multiple parameters should use AND or OR logic.
    pub multiple_and: Option<bool>,

    /// Comparators supported (for number/date/quantity).
    pub comparator: Option<Vec<String>>,

    /// XPath expression (legacy, for reference).
    pub xpath: Option<String>,
}

impl SearchParameterDefinition {
    /// Creates a new SearchParameter definition.
    pub fn new(
        url: impl Into<String>,
        code: impl Into<String>,
        param_type: SearchParamType,
        expression: impl Into<String>,
    ) -> Self {
        Self {
            url: url.into(),
            code: code.into(),
            name: None,
            description: None,
            param_type,
            expression: expression.into(),
            base: Vec::new(),
            target: None,
            component: None,
            status: SearchParameterStatus::Active,
            source: SearchParameterSource::Embedded,
            modifier: None,
            multiple_or: None,
            multiple_and: None,
            comparator: None,
            xpath: None,
        }
    }

    /// Sets the base resource types.
    pub fn with_base<I, S>(mut self, base: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.base = base.into_iter().map(Into::into).collect();
        self
    }

    /// Sets target types for reference parameters.
    pub fn with_targets<I, S>(mut self, targets: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.target = Some(targets.into_iter().map(Into::into).collect());
        self
    }

    /// Sets the source.
    pub fn with_source(mut self, source: SearchParameterSource) -> Self {
        self.source = source;
        self
    }

    /// Sets the status.
    pub fn with_status(mut self, status: SearchParameterStatus) -> Self {
        self.status = status;
        self
    }

    /// Returns whether this is a composite parameter.
    pub fn is_composite(&self) -> bool {
        self.param_type == SearchParamType::Composite
            && self
                .component
                .as_ref()
                .map(|c| !c.is_empty())
                .unwrap_or(false)
    }

    /// Returns whether this parameter applies to the given resource type.
    pub fn applies_to(&self, resource_type: &str) -> bool {
        self.base
            .iter()
            .any(|b| b == resource_type || b == "Resource" || b == "DomainResource")
    }
}

/// Update notification for registry changes.
#[derive(Debug, Clone)]
pub enum RegistryUpdate {
    /// A parameter was added.
    Added(String),
    /// A parameter was removed.
    Removed(String),
    /// A parameter's status changed.
    StatusChanged(String, SearchParameterStatus),
    /// Registry was bulk-reloaded.
    Reloaded,
}

/// In-memory registry of SearchParameter definitions.
///
/// Provides fast lookup by (resource_type, param_code) and by URL.
/// Notifies subscribers when parameters are added, removed, or changed.
pub struct SearchParameterRegistry {
    /// Parameters indexed by (resource_type, param_code).
    params_by_type: HashMap<String, HashMap<String, Arc<SearchParameterDefinition>>>,

    /// Parameters indexed by canonical URL.
    params_by_url: HashMap<String, Arc<SearchParameterDefinition>>,

    /// Notification channel for registry updates.
    update_tx: broadcast::Sender<RegistryUpdate>,
}

impl SearchParameterRegistry {
    /// Creates a new empty registry.
    pub fn new() -> Self {
        let (update_tx, _) = broadcast::channel(64);
        Self {
            params_by_type: HashMap::new(),
            params_by_url: HashMap::new(),
            update_tx,
        }
    }

    /// Returns the number of registered parameters.
    pub fn len(&self) -> usize {
        self.params_by_url.len()
    }

    /// Returns true if the registry is empty.
    pub fn is_empty(&self) -> bool {
        self.params_by_url.is_empty()
    }

    /// Loads all parameters from a loader.
    pub async fn load_all(
        &mut self,
        loader: &SearchParameterLoader,
    ) -> Result<usize, super::errors::LoaderError> {
        let params = loader.load_embedded()?;
        let count = params.len();

        for param in params {
            // Skip duplicates silently during bulk load
            if !self.params_by_url.contains_key(&param.url) {
                self.register_internal(param);
            }
        }

        let _ = self.update_tx.send(RegistryUpdate::Reloaded);
        Ok(count)
    }

    /// Gets all active parameters for a resource type.
    pub fn get_active_params(&self, resource_type: &str) -> Vec<Arc<SearchParameterDefinition>> {
        self.params_by_type
            .get(resource_type)
            .map(|params| {
                params
                    .values()
                    .filter(|p| p.status.is_usable())
                    .cloned()
                    .collect()
            })
            .unwrap_or_default()
    }

    /// Gets all parameters for a resource type (including inactive).
    pub fn get_all_params(&self, resource_type: &str) -> Vec<Arc<SearchParameterDefinition>> {
        self.params_by_type
            .get(resource_type)
            .map(|params| params.values().cloned().collect())
            .unwrap_or_default()
    }

    /// Gets a specific parameter by resource type and code.
    pub fn get_param(
        &self,
        resource_type: &str,
        code: &str,
    ) -> Option<Arc<SearchParameterDefinition>> {
        self.params_by_type
            .get(resource_type)
            .and_then(|params| params.get(code))
            .cloned()
    }

    /// Gets a parameter by its canonical URL.
    pub fn get_by_url(&self, url: &str) -> Option<Arc<SearchParameterDefinition>> {
        self.params_by_url.get(url).cloned()
    }

    /// Registers a new parameter.
    pub fn register(&mut self, param: SearchParameterDefinition) -> Result<(), RegistryError> {
        if self.params_by_url.contains_key(&param.url) {
            return Err(RegistryError::DuplicateUrl { url: param.url });
        }

        let url = param.url.clone();
        self.register_internal(param);
        let _ = self.update_tx.send(RegistryUpdate::Added(url));

        Ok(())
    }

    /// Internal registration without duplicate checking.
    fn register_internal(&mut self, param: SearchParameterDefinition) {
        let param = Arc::new(param);

        // Index by URL
        self.params_by_url
            .insert(param.url.clone(), Arc::clone(&param));

        // Index by (resource_type, code) for each base type
        for base in &param.base {
            self.params_by_type
                .entry(base.clone())
                .or_default()
                .insert(param.code.clone(), Arc::clone(&param));
        }
    }

    /// Updates a parameter's status.
    pub fn update_status(
        &mut self,
        url: &str,
        status: SearchParameterStatus,
    ) -> Result<(), RegistryError> {
        // We need to create a new Arc with the updated status
        let old_param = self
            .params_by_url
            .get(url)
            .ok_or_else(|| RegistryError::NotFound {
                identifier: url.to_string(),
            })?;

        // Create updated definition
        let mut new_def = (**old_param).clone();
        new_def.status = status;
        let new_param = Arc::new(new_def);

        // Update URL index
        self.params_by_url
            .insert(url.to_string(), Arc::clone(&new_param));

        // Update type indexes
        for base in &new_param.base {
            if let Some(type_params) = self.params_by_type.get_mut(base) {
                type_params.insert(new_param.code.clone(), Arc::clone(&new_param));
            }
        }

        let _ = self
            .update_tx
            .send(RegistryUpdate::StatusChanged(url.to_string(), status));

        Ok(())
    }

    /// Removes a parameter from the registry.
    pub fn unregister(&mut self, url: &str) -> Result<(), RegistryError> {
        let param = self
            .params_by_url
            .remove(url)
            .ok_or_else(|| RegistryError::NotFound {
                identifier: url.to_string(),
            })?;

        // Remove from type indexes
        for base in &param.base {
            if let Some(type_params) = self.params_by_type.get_mut(base) {
                type_params.remove(&param.code);
                if type_params.is_empty() {
                    self.params_by_type.remove(base);
                }
            }
        }

        let _ = self
            .update_tx
            .send(RegistryUpdate::Removed(url.to_string()));

        Ok(())
    }

    /// Subscribes to registry updates.
    pub fn subscribe(&self) -> broadcast::Receiver<RegistryUpdate> {
        self.update_tx.subscribe()
    }

    /// Returns all resource types that have registered parameters.
    pub fn resource_types(&self) -> Vec<String> {
        self.params_by_type.keys().cloned().collect()
    }

    /// Returns all registered parameter URLs.
    pub fn all_urls(&self) -> Vec<String> {
        self.params_by_url.keys().cloned().collect()
    }
}

impl Default for SearchParameterRegistry {
    fn default() -> Self {
        Self::new()
    }
}

impl std::fmt::Debug for SearchParameterRegistry {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("SearchParameterRegistry")
            .field("params_count", &self.params_by_url.len())
            .field(
                "resource_types",
                &self.params_by_type.keys().collect::<Vec<_>>(),
            )
            .finish()
    }
}

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

    #[test]
    fn test_search_parameter_status() {
        assert!(SearchParameterStatus::Active.is_usable());
        assert!(!SearchParameterStatus::Draft.is_usable());
        assert!(!SearchParameterStatus::Retired.is_usable());

        assert_eq!(
            SearchParameterStatus::from_fhir_status("active"),
            Some(SearchParameterStatus::Active)
        );
        assert_eq!(SearchParameterStatus::Active.to_fhir_status(), "active");
    }

    #[test]
    fn test_search_parameter_definition() {
        let def = SearchParameterDefinition::new(
            "http://hl7.org/fhir/SearchParameter/Patient-name",
            "name",
            SearchParamType::String,
            "Patient.name",
        )
        .with_base(vec!["Patient"]);

        assert_eq!(def.code, "name");
        assert!(def.applies_to("Patient"));
        assert!(!def.applies_to("Observation"));
    }

    #[test]
    fn test_registry_operations() {
        let mut registry = SearchParameterRegistry::new();

        let def = SearchParameterDefinition::new(
            "http://example.org/sp/test",
            "test",
            SearchParamType::String,
            "Patient.test",
        )
        .with_base(vec!["Patient"]);

        // Register
        registry.register(def.clone()).unwrap();
        assert_eq!(registry.len(), 1);

        // Get by URL
        let found = registry.get_by_url("http://example.org/sp/test");
        assert!(found.is_some());

        // Get by type and code
        let found = registry.get_param("Patient", "test");
        assert!(found.is_some());
        assert_eq!(found.unwrap().code, "test");

        // Get active params
        let active = registry.get_active_params("Patient");
        assert_eq!(active.len(), 1);

        // Update status
        registry
            .update_status("http://example.org/sp/test", SearchParameterStatus::Retired)
            .unwrap();
        let active = registry.get_active_params("Patient");
        assert_eq!(active.len(), 0);

        // Unregister
        registry.unregister("http://example.org/sp/test").unwrap();
        assert_eq!(registry.len(), 0);
    }

    #[test]
    fn test_duplicate_url_error() {
        let mut registry = SearchParameterRegistry::new();

        let def = SearchParameterDefinition::new(
            "http://example.org/sp/test",
            "test",
            SearchParamType::String,
            "Patient.test",
        )
        .with_base(vec!["Patient"]);

        registry.register(def.clone()).unwrap();

        let result = registry.register(def);
        assert!(matches!(result, Err(RegistryError::DuplicateUrl { .. })));
    }
}