bistun-core 2.0.3

The authoritative Linguistic DNA models and DTOs for the Bistun LMS. Provides a high-performance, immutable contract layer for BCP 47 locale resolution, typographic traits, and linguistic metadata.
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
// Copyright (C) 2026 Francis Xavier Wazeter IV
// SPDX-License-Identifier: GPL-3.0-or-later
//
// This file is part of the Bistun Linguistic Metadata Service (LMS).
// See the LICENSE file in the workspace root for full license information.

#![cfg(feature = "persistence")]

//! # Registry Persistence Models
//! **Crate**: `bistun-core`
//! **Ref**: `[010-LMS-MEM]`, `[002-LMS-DATA]`
//! **Domain**: `Persistence`
//! **Location**: `crates/bistun-core/src/registry.rs`
//!
//! **Why**: This module defines the fundamental `Linguistic Metadata Schema` used to store linguistic profiles in the `WORM Storage (Write-Once, Read-Many)` registry and manage them in memory.
//! **Impact**: These structures represent the authoritative `System of Record (SoR)`. Any changes here dictate how the `Cryptographic Payload` is deserialized and injected into the `Resolution Pipeline`.
//!
//! ### Architectural Topology
//! * **Tier**: `0`
//! * **Dependencies**: `crate::traits::LmsRule`, `crate::TraitKey`, `crate::TraitValue`, `hashbrown`, `serde`, `std::sync::Arc`
//! * **Consumers**: Data `Ingestion` pipelines, `Delivery` state injection.
//! * **State Model**: `Shared-State (Arc/RwLock)`
//! * **Design Patterns**: `Repository Pattern`, `Flyweight Pattern`
//!
//! ### Local Definitions
//! * **WORM Storage (Write-Once, Read-Many)**: A data retention philosophy where registry records are never mutated in place; new versions are appended to create a verifiable audit trail.
//! * **Flyweight Pattern**: A memory optimization strategy that shares immutable instances of common language/script definitions across requests, reducing the `SDK`'s memory footprint by over 80%.

use crate::traits::LmsRule;
use crate::{TraitKey, TraitValue};
use hashbrown::HashMap;
use serde::{Deserialize, Serialize};
use std::sync::Arc;

/// Authoritative identity and audit metadata for a specific registry build.
///
/// ### `OpenAPI` Schema
/// ```yaml
/// schema: RegistryMetadata
/// description: Authoritative identity and audit metadata for a specific registry build.
/// ```
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct RegistryMetadata {
    /// Semantic version of the data (e.g., "v1.2.3").
    pub version: String,
    /// `ISO 8601` timestamp of when the curator compiled this snapshot.
    pub build_date: String,
    /// `SHA-256` hash or similar unique identifier for data integrity.
    pub checksum: String,
}

impl Default for RegistryMetadata {
    /// Provides a safe "Phase 0" default identity for bootstrapping.
    ///
    /// **Time**: `O(1)` | **Space**: `O(1)`
    /// **SLI Target**: `< 1ms`
    ///
    /// # Algorithmic Execution Trace (Internal)
    /// 1. Instantiate the metadata with zeroed-out default dates and checksums.
    /// 2. Return the safe bootstrap instance.
    ///
    /// # Arguments
    /// This function accepts no arguments.
    ///
    /// # Returns
    /// * `Self`: A default metadata struct for early lifecycle states.
    ///
    /// # Golden Master Tests
    /// * **Input**: None
    /// * **Output**: A valid `RegistryMetadata` struct with version `"v0.0.0-default"`.
    ///
    /// # Errors
    /// This function cannot fail and does not return an error variant.
    ///
    /// # Panics
    /// This function does not panic.
    ///
    /// # Safety
    /// This function does not contain unsafe blocks.
    ///
    /// # Side Effects
    /// This function does not produce external side effects.
    ///
    /// # Observability & Security
    /// * **Spans**: None.
    /// * **Metrics**: None.
    /// * **Auth Required**: None.
    fn default() -> Self {
        // [STEP 1]: Instantiate the metadata with zeroed-out default dates and checksums.
        let metadata = Self {
            version: "v0.0.0-default".to_string(),
            build_date: "1970-01-01T00:00:00Z".to_string(),
            checksum: "00000000000000000000000000000000".to_string(),
        };

        // [STEP 2]: Return the safe bootstrap instance.
        metadata
    }
}

/// An aggregated representation of a locale's Typological and Orthographic rules.
///
/// ### `OpenAPI` Schema
/// ```yaml
/// schema: LocaleProfile
/// description: The foundational, immutable data model representing the structural properties of a language.
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LocaleProfile {
    /// The canonical `BCP 47` identifier (e.g., "ar-EG").
    #[serde(rename = "ID")]
    pub id: String,
    /// The collection of `Linguistic Metadata Schema` traits (`Typology` & `Orthography`).
    #[serde(default)]
    pub traits: HashMap<TraitKey, TraitValue>,
    /// Logical directives for algorithmic execution.
    #[serde(default)]
    pub rules: HashMap<String, LmsRule>,
    /// Mappings of Logical Resource IDs to Physical Paths.
    #[serde(default)]
    pub resources: HashMap<String, String>,
}

/// The top-level persistence contract for the entire `WORM Storage (Write-Once, Read-Many)` `JSON` registry.
///
/// ### `OpenAPI` Schema
/// ```yaml
/// schema: WormPayload
/// description: The fully packaged, versioned snapshot of the database exported by the persistence layer.
/// ```
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct WormPayload {
    /// Authoritative build identity.
    pub metadata: RegistryMetadata,
    /// The array of fully inflated `Linguistic Metadata Schema` profiles.
    pub profiles: Vec<LocaleProfile>,
    /// Deprecated or macro language tag mappings.
    #[serde(default)]
    pub aliases: HashMap<String, String>,
}

/// The high-performance, in-memory data store for linguistic profiles and dynamic routing mappings.
///
/// ### `OpenAPI` Schema
/// ```yaml
/// schema: RegistryStore
/// description: The high-performance, in-memory data store using the Flyweight Pattern.
/// ```
#[derive(Debug, Default)]
pub struct RegistryStore {
    /// Authoritative identity of this specific data set.
    pub metadata: Arc<RegistryMetadata>,
    /// Environment-specific base `URI` for resolving binary data blobs.
    pub base_resource_uri: Arc<String>,
    /// Maps a canonical Locale `ID` (e.g., "ar-EG") to its `Flyweight Pattern` profile.
    pools: HashMap<String, Arc<LocaleProfile>>,
    /// Maps a deprecated or macro language tag (e.g., "in") to its canonical `ID` (e.g., "id").
    aliases: HashMap<String, String>,
}

impl RegistryStore {
    /// Initializes a new, empty `RegistryStore`.
    ///
    /// **Time**: `O(1)` | **Space**: `O(1)`
    /// **SLI Target**: `< 1ms`
    ///
    /// # Algorithmic Execution Trace (Internal)
    /// 1. Instantiate the high-throughput `HashMap` containers for pools and aliases.
    /// 2. Inject default metadata and a fallback resource `URI`.
    /// 3. Return the empty store structure.
    ///
    /// # Examples
    /// ```rust
    /// # use bistun_core::registry::RegistryStore;
    /// let store = RegistryStore::new();
    /// ```
    ///
    /// # Arguments
    /// This function accepts no arguments.
    ///
    /// # Returns
    /// * `Self`: A newly instantiated, empty `RegistryStore`.
    ///
    /// # Golden Master Tests
    /// * **Input**: None
    /// * **Output**: An initialized `RegistryStore` instance.
    ///
    /// # Errors
    /// This function cannot fail and does not return an error variant.
    ///
    /// # Panics
    /// This function does not panic.
    ///
    /// # Safety
    /// This function does not contain unsafe blocks.
    ///
    /// # Side Effects
    /// Allocates empty `HashMap` data structures on the heap.
    ///
    /// # Observability & Security
    /// * **Spans**: None.
    /// * **Metrics**: None.
    /// * **Auth Required**: None.
    #[must_use]
    pub fn new() -> Self {
        // [STEP 1]: Instantiate the high-throughput `HashMap` containers for pools and aliases.
        // [STEP 2]: Inject default metadata and a fallback resource `URI`.
        // [STEP 3]: Return the empty store structure.
        Self {
            metadata: Arc::new(RegistryMetadata::default()),
            base_resource_uri: Arc::new(String::new()),
            pools: HashMap::new(),
            aliases: HashMap::new(),
        }
    }

    /// Sets the authoritative metadata for this store.
    ///
    /// **Time**: `O(1)` | **Space**: `O(1)`
    /// **SLI Target**: `< 1ms`
    ///
    /// # Algorithmic Execution Trace (Internal)
    /// 1. Wrap the raw metadata struct in a thread-safe `Arc`.
    /// 2. Update the internal metadata pointer via mutation.
    ///
    /// # Arguments
    /// * `metadata` (`RegistryMetadata`): The new identity header extracted during hydration.
    ///
    /// # Returns
    /// * This function does not return a value.
    ///
    /// # Golden Master Tests
    /// * **Input**: A valid `RegistryMetadata` object.
    /// * **Output**: None.
    ///
    /// # Errors
    /// This function cannot fail and does not return an error variant.
    ///
    /// # Panics
    /// This function does not panic.
    ///
    /// # Safety
    /// This function does not contain unsafe blocks.
    ///
    /// # Side Effects
    /// Mutates the internal state of the `RegistryStore` in-place.
    ///
    /// # Observability & Security
    /// * **Spans**: None.
    /// * **Metrics**: None.
    /// * **Auth Required**: None.
    pub fn set_metadata(&mut self, metadata: RegistryMetadata) {
        // [STEP 1]: Wrap the raw metadata struct in a thread-safe `Arc`.
        // [STEP 2]: Update the internal metadata pointer via mutation.
        self.metadata = Arc::new(metadata);
    }

    /// Sets the environment-specific base `URI` for resource resolution.
    ///
    /// **Time**: `O(1)` | **Space**: `O(1)`
    /// **SLI Target**: `< 1ms`
    ///
    /// # Algorithmic Execution Trace (Internal)
    /// 1. Wrap the raw string `URI` in a thread-safe `Arc`.
    /// 2. Update the internal base resource `URI` pointer via mutation.
    ///
    /// # Arguments
    /// * `uri` (`String`): The fully qualified base `URI` (e.g., `https://cdn.example.com/v1/icu/`).
    ///
    /// # Returns
    /// * This function does not return a value.
    ///
    /// # Golden Master Tests
    /// * **Input**: `"https://cdn.example.com/v1/icu/"`
    /// * **Output**: None.
    ///
    /// # Errors
    /// This function cannot fail and does not return an error variant.
    ///
    /// # Panics
    /// This function does not panic.
    ///
    /// # Safety
    /// This function does not contain unsafe blocks.
    ///
    /// # Side Effects
    /// Mutates the internal state of the `RegistryStore` in-place.
    ///
    /// # Observability & Security
    /// * **Spans**: None.
    /// * **Metrics**: None.
    /// * **Auth Required**: None.
    pub fn set_base_resource_uri(&mut self, uri: String) {
        // [STEP 1]: Wrap the raw string `URI` in a thread-safe `Arc`.
        // [STEP 2]: Update the internal base resource `URI` pointer via mutation.
        self.base_resource_uri = Arc::new(uri);
    }

    /// Retrieves an atomic reference to a `LocaleProfile` if it exists.
    ///
    /// **Time**: `O(1)` | **Space**: `O(1)`
    /// **SLI Target**: `< 1ms`
    ///
    /// # Algorithmic Execution Trace (Internal)
    /// 1. Query the internal `pools` map using the provided locale `ID`.
    /// 2. If found, clone the `Arc` (bumping the reference count) and return it.
    /// 3. If missing, return `None`.
    ///
    /// # Examples
    /// ```rust
    /// # use bistun_core::registry::RegistryStore;
    /// let store = RegistryStore::new();
    /// assert!(store.get_profile("ar-EG").is_none());
    /// ```
    ///
    /// # Arguments
    /// * `id` (`&str`): The canonical `BCP 47` locale `ID` to retrieve.
    ///
    /// # Returns
    /// * `Option<Arc<LocaleProfile>>`: An atomic reference to the immutable profile, or `None` if absent.
    ///
    /// # Golden Master Tests
    /// * **Input**: `"ar-EG"`
    /// * **Output**: `None` (if empty) or `Some(Arc<LocaleProfile>)`
    ///
    /// # Errors
    /// This function cannot fail and does not return an error variant.
    ///
    /// # Panics
    /// This function does not panic.
    ///
    /// # Safety
    /// This function does not contain unsafe blocks.
    ///
    /// # Side Effects
    /// This function does not produce external side effects.
    ///
    /// # Observability & Security
    /// * **Spans**: None.
    /// * **Metrics**: None.
    /// * **Auth Required**: None.
    #[must_use]
    pub fn get_profile(&self, id: &str) -> Option<Arc<LocaleProfile>> {
        // [STEP 1]: Query the internal `pools` map using the provided locale `ID`.
        // [STEP 2]: If found, clone the `Arc` (bumping the reference count) and return it.
        // [STEP 3]: If missing, return `None`.
        self.pools.get(id).cloned()
    }

    /// Retrieves the canonical target for a known alias or macrolanguage tag.
    ///
    /// **Time**: `O(1)` | **Space**: `O(1)`
    /// **SLI Target**: `< 1ms`
    ///
    /// # Algorithmic Execution Trace (Internal)
    /// 1. Query the internal `aliases` map using the provided tag.
    /// 2. If an alias is found, clone the canonical string and return it.
    /// 3. If missing, return `None`.
    ///
    /// # Arguments
    /// * `tag` (`&str`): The legacy or macrolanguage `BCP 47` tag.
    ///
    /// # Returns
    /// * `Option<String>`: The canonical `BCP 47` `ID`.
    ///
    /// # Golden Master Tests
    /// * **Input**: `"in"`
    /// * **Output**: `Some("id")` (assuming seeded).
    ///
    /// # Errors
    /// This function cannot fail and does not return an error variant.
    ///
    /// # Panics
    /// This function does not panic.
    ///
    /// # Safety
    /// This function does not contain unsafe blocks.
    ///
    /// # Side Effects
    /// This function does not produce external side effects.
    ///
    /// # Observability & Security
    /// * **Spans**: None.
    /// * **Metrics**: None.
    /// * **Auth Required**: None.
    #[must_use]
    pub fn resolve_alias(&self, tag: &str) -> Option<String> {
        // [STEP 1]: Query the internal `aliases` map using the provided tag.
        // [STEP 2]: If an alias is found, clone the canonical string and return it.
        // [STEP 3]: If missing, return `None`.
        self.aliases.get(tag).cloned()
    }

    /// Inserts a profile directly into the pool.
    ///
    /// **Time**: `O(1)` | **Space**: `O(1)`
    /// **SLI Target**: `< 1ms`
    ///
    /// # Algorithmic Execution Trace (Internal)
    /// 1. Wrap the owned `LocaleProfile` in an `Arc` to establish the `Flyweight Pattern`.
    /// 2. Insert the `Arc` into the `pools` `HashMap`, keyed by the profile's `ID`.
    ///
    /// # Arguments
    /// * `profile` (`LocaleProfile`): The fully hydrated linguistic profile.
    ///
    /// # Returns
    /// * This function does not return a value.
    ///
    /// # Golden Master Tests
    /// * **Input**: A valid `LocaleProfile` instance.
    /// * **Output**: None.
    ///
    /// # Errors
    /// This function cannot fail and does not return an error variant.
    ///
    /// # Panics
    /// This function does not panic.
    ///
    /// # Safety
    /// This function does not contain unsafe blocks.
    ///
    /// # Side Effects
    /// Mutates the internal state of the `RegistryStore` by allocating and inserting a new map entry.
    ///
    /// # Observability & Security
    /// * **Spans**: None.
    /// * **Metrics**: None.
    /// * **Auth Required**: None.
    pub fn insert_stub(&mut self, profile: LocaleProfile) {
        // [STEP 1]: Wrap the owned `LocaleProfile` in an `Arc` to establish the `Flyweight Pattern`.
        // [STEP 2]: Insert the `Arc` into the `pools` `HashMap`, keyed by the profile's `ID`.
        self.pools.insert(profile.id.clone(), Arc::new(profile));
    }

    /// Inserts an alias mapping directly into the dynamic routing table.
    ///
    /// **Time**: `O(1)` | **Space**: `O(1)`
    /// **SLI Target**: `< 1ms`
    ///
    /// # Algorithmic Execution Trace (Internal)
    /// 1. Insert the raw string mapping directly into the `aliases` `HashMap`.
    ///
    /// # Arguments
    /// * `alias` (`String`): The deprecated or macrolanguage tag.
    /// * `canonical` (`String`): The correct operational `ID`.
    ///
    /// # Returns
    /// * This function does not return a value.
    ///
    /// # Golden Master Tests
    /// * **Input**: `"in"`, `"id"`
    /// * **Output**: None.
    ///
    /// # Errors
    /// This function cannot fail and does not return an error variant.
    ///
    /// # Panics
    /// This function does not panic.
    ///
    /// # Safety
    /// This function does not contain unsafe blocks.
    ///
    /// # Side Effects
    /// Mutates the internal state of the `RegistryStore` by allocating and inserting a new map entry.
    ///
    /// # Observability & Security
    /// * **Spans**: None.
    /// * **Metrics**: None.
    /// * **Auth Required**: None.
    pub fn insert_alias(&mut self, alias: String, canonical: String) {
        // [STEP 1]: Insert the raw string mapping directly into the `aliases` `HashMap`.
        self.aliases.insert(alias, canonical);
    }
}