bistun-lms 2.1.1

A thread-safe capability engine for resolving BCP 47 language tags into actionable rendering and parsing properties (directionality, morphology, segmentation). Features a wait-free, lock-free memory pool (ArcSwap) enabling zero-downtime registry hot-swaps for high-throughput NLP and UI pipelines.
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
// Bistun Linguistic Metadata Service (LMS)
// Copyright (C) 2026  Francis Xavier Wazeter IV
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

//! # The Linguistic Manager (SDK Orchestrator)
//! Crate: `bistun-lms`
//! Ref: [001-LMS-CORE], [010-LMS-MEM], [007-LMS-OPS]
//! Location: `crates/bistun-lms/src/manager.rs`
//!
//! **Why**: This module serves as the primary ``SDK`` interface for external consumers. It abstracts away the complex ``5-Phase`` resolution pipeline and manages the thread-safe dynamic memory pool.
//! **Impact**: If this module fails, external services cannot interface with the capability engine or will fail to boot due to hydration errors.
//!
//! ### Glossary
//! * **Circuit Breaker**: A design pattern that prevents the system from executing a failing operation (like querying an empty memory pool), instead instantly returning a safe default.
//! * **SdkState**: The operational health of the manager (``Bootstrapping``, ``Ready``, ``Degraded``).

use crate::core::pipeline::generate_manifest;
use crate::data::repository::{ISnapshotProvider, hydrate_snapshot};
use crate::data::swap::RegistryState;
use bistun_core::{
    CapabilityManifest, Direction, LmsError, LmsRule, MorphType, NormRule, ResolutionMetrics,
    SdkState, SegType, SyncMetrics, TraitKey, TraitValue, TransRule,
};
use std::sync::{Arc, RwLock};
use web_time::{SystemTime, UNIX_EPOCH};

#[cfg(feature = "async-worker")]
use std::time::Duration;
#[cfg(feature = "async-worker")]
use tokio::time;

use tracing::{error, info};

/// The primary interface for generating Linguistic Capability Manifests.
///
/// Time: `O(1)` reads | Space: `O(1)` pointer allocations
#[derive(Debug, Clone)]
pub struct LinguisticManager {
    /// The thread-safe dynamic memory state protecting the Flyweight pool.
    state: RegistryState,
    /// The current operational status of the engine. Protected by an ``RwLock``
    /// so the background worker can update it across threads.
    status: Arc<RwLock<SdkState>>,
    /// Thread-safe tracking of background sync health and errors.
    pub metrics: Arc<RwLock<SyncMetrics>>,
    /// Thread-safe tracking of atomic runtime execution telemetry (``V2.0.0``).
    pub resolution_metrics: Arc<RwLock<ResolutionMetrics>>,
}

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

impl LinguisticManager {
    /// Initializes a new, empty manager instance in the ``Bootstrapping`` state.
    ///
    /// Time: `O(1)` | Space: `O(1)`
    ///
    /// # Logic Trace (Internal)
    /// 1. Instantiates a default [`RegistryState`].
    /// 2. Wraps the [`SdkState::Bootstrapping`] enum in a thread-safe ``Arc<RwLock>``.
    /// 3. Initializes metrics containers for sync and resolution telemetry.
    /// 4. Returns the prepared struct.
    ///
    /// # Returns
    /// * `Self`: A newly instantiated [`LinguisticManager`] ready for async initialization.
    #[must_use]
    pub fn new() -> Self {
        Self {
            state: RegistryState::new(),
            status: Arc::new(RwLock::new(SdkState::Bootstrapping)),
            metrics: Arc::new(RwLock::new(SyncMetrics::default())),
            resolution_metrics: Arc::new(RwLock::new(ResolutionMetrics::default())),
        }
    }

    /// Internal helper to get the current ``Unix`` timestamp in seconds safely.
    ///
    /// Time: `O(1)` | Space: `O(1)`
    ///
    /// # Panics
    /// * **Panics**: Panics if the system clock moved backwards from the ``UNIX_EPOCH``.
    #[must_use]
    fn now_secs() -> u64 {
        // web_time acts as a drop-in replacement.
        // On native targets, it uses std::time. On WASM, it uses JS Date.now().
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("LMS-OPS: System clock moved backwards")
            .as_secs()
    }

    /// Performs the initial async ``WORM`` snapshot hydration via Dependency Injection.
    ///
    /// Time: `O(M)` where M is the number of locales | Space: `O(M)` memory pool allocation
    ///
    /// # Logic Trace (Internal)
    /// 1. Record the start of the sync attempt in [`SyncMetrics`].
    /// 2. Await the repository hydrator with the injected ``provider`` and ``public_key_b64``.
    /// 3. On success, hot-swap the registry and set status to ``Ready``.
    /// 4. On failure, activate Circuit Breaker mode (``Degraded``).
    ///
    /// # Arguments
    /// * `provider` (&impl [`ISnapshotProvider`]): The authoritative data source.
    /// * `public_key_b64` (&str): The ``Base64`` encoded public key for signature verification.
    ///
    /// # Panics
    /// * Panics if the internal ``metrics`` or ``status`` locks are poisoned.
    pub async fn initialize(&self, provider: &impl ISnapshotProvider, public_key_b64: &str) {
        // [STEP 1]: Record the start of the sync attempt.
        self.metrics.write().expect("LMS-OPS: Sync metrics lock poisoned").last_attempted_sync =
            Self::now_secs();

        // [STEP 2]: Await the repository hydrator.
        match hydrate_snapshot(provider, public_key_b64).await {
            Ok(store) => {
                // [STEP 3a]: On success, hot-swap the registry and set status to Ready.
                self.state.swap_registry(store);
                *self.status.write().expect("LMS-OPS: Status lock poisoned") = SdkState::Ready;
                self.metrics
                    .write()
                    .expect("LMS-OPS: Sync metrics lock poisoned")
                    .last_successful_sync = Self::now_secs();
                info!("LinguisticManager initialized successfully.");
            }
            Err(e) => {
                // [STEP 3b]: On failure, activate Circuit Breaker mode.
                *self.status.write().expect("LMS-OPS: Status lock poisoned") = SdkState::Degraded;
                self.metrics
                    .write()
                    .expect("LMS-OPS: Sync metrics lock poisoned")
                    .sync_error_count += 1;
                error!(
                    "LinguisticManager failed to initialize. Triggering Circuit Breaker. Reason: {e}"
                );
            }
        }
    }

    /// Forces an immediate, real-time hydration of the capability engine's memory pool.
    ///
    /// Time: `O(M)` where M is the number of locales | Space: `O(M)` memory pool allocation
    ///
    /// # Logic Trace (Internal)
    /// 1. Record the manual sync attempt timestamp in [`SyncMetrics`].
    /// 2. Await the repository hydrator with the injected `provider` and `public_key_b64`.
    /// 3. On success, perform a wait-free hot-swap of the registry state and log the telemetry.
    /// 4. On failure, bubble up the stringified error for the HTTP handler to return as a 500 response.
    ///
    /// # Arguments
    /// * `provider` (&impl [`ISnapshotProvider`]): The authoritative WORM data source.
    /// * `public_key_b64` (&str): The `Base64` encoded public key for signature verification.
    ///
    /// # Returns
    /// * `Result<(), String>`: Yields success or a descriptive error message on failure.
    ///
    /// # Errors
    /// * Returns an `Err(String)` if the provider fails to fetch, parse, or cryptographically verify the snapshot.
    ///
    /// # Panics
    /// * Panics if internal metrics locks are poisoned.
    ///
    /// # Safety
    /// * Fully safe asynchronous execution utilizing `ArcSwap` for wait-free pointer rotation.
    ///
    /// # Side Effects
    /// * Mutates the internal `RegistryState` pointer by hot-swapping the active memory pool.
    /// * Mutates `SyncMetrics` to record success or failure counts.
    pub async fn force_sync(
        &self,
        provider: &impl ISnapshotProvider,
        public_key_b64: &str,
    ) -> Result<(), String> {
        // [STEP 1]: Record manual sync attempt
        self.metrics.write().expect("LMS-OPS: Sync metrics lock poisoned").last_attempted_sync =
            Self::now_secs();

        // [STEP 2]: Execute immediate hydration bypass
        match hydrate_snapshot(provider, public_key_b64).await {
            Ok(store) => {
                // [STEP 3]: Wait-free atomic swap
                self.state.swap_registry(store);
                let mut s = self.status.write().expect("LMS-OPS: Status lock poisoned");
                if *s != SdkState::Ready {
                    *s = SdkState::Ready;
                }
                self.metrics
                    .write()
                    .expect("LMS-OPS: Sync metrics lock poisoned")
                    .last_successful_sync = Self::now_secs();
                info!("LMS-OPS: Real-time force_sync successful. Registry hot-swapped.");
                Ok(())
            }
            Err(e) => {
                // [STEP 4]: Yield degradation
                self.metrics
                    .write()
                    .expect("LMS-OPS: Sync metrics lock poisoned")
                    .sync_error_count += 1;
                error!("LMS-OPS: Real-time force_sync failed: {}", e);
                Err(e.to_string())
            }
        }
    }

    /// Spawns a ``Tokio`` background worker that periodically polls for registry updates.
    ///
    /// # Logic Trace (Internal)
    /// 1. Clone atomic state and locks for the background thread.
    /// 2. Spawn the detached ``Tokio`` task.
    /// 3. Loop at the specified ``interval_secs``, attempting to fetch and hydrate a new snapshot.
    /// 4. Hot-swap the registry on success, or increment error counts on failure.
    ///
    /// # Arguments
    /// * `interval_secs` (u64): The polling frequency for the background worker.
    /// * `provider` (P): The snapshot provider implementation.
    /// * `public_key_b64` (String): The ``Base64`` public key for validation.
    ///
    /// # Panics
    /// * Panics if the internal ``status`` or ``metrics`` locks are poisoned during background execution.
    #[cfg(feature = "async-worker")]
    pub fn spawn_background_sync<P>(&self, interval_secs: u64, provider: P, public_key_b64: String)
    where
        P: ISnapshotProvider + 'static,
    {
        // [STEP 1]: Clone atomic state and locks for the background thread.
        let state = self.state.clone();
        let status = self.status.clone();
        let metrics = self.metrics.clone();

        // [STEP 2]: Spawn the detached Tokio task
        tokio::spawn(async move {
            info!("Background sync worker started (Interval: {interval_secs}s)");
            let mut interval_timer = time::interval(Duration::from_secs(interval_secs));

            loop {
                // [STEP 3]: Sleep for the requested interval.
                interval_timer.tick().await;

                // [STEP 4]: Attempt to fetch and hydrate a new snapshot.
                match hydrate_snapshot(&provider, &public_key_b64).await {
                    Ok(store) => {
                        state.swap_registry(store);
                        let mut s =
                            status.write().expect("LMS-OPS: Background status lock poisoned");
                        if *s != SdkState::Ready {
                            *s = SdkState::Ready;
                        }
                        info!("Background sync successful. Registry hot-swapped.");
                    }
                    Err(e) => {
                        // CRITICAL: We do NOT set SdkState::Degraded here.
                        // If a background update fails, we keep using the last known good memory pool!
                        metrics
                            .write()
                            .expect("LMS-OPS: Background metrics lock poisoned")
                            .sync_error_count += 1;
                        error!(
                            "Background sync failed. Retaining current registry state. Reason: {e}"
                        );
                    }
                }
            }
        });
    }

    /// Returns the current health status of the ``SDK``.
    ///
    /// Time: `O(1)` | Space: `O(1)`
    ///
    /// # Returns
    /// * [`SdkState`]: The current operational health status.
    ///
    /// # Panics
    /// * **Panics**: Panics if the internal ``status`` lock is poisoned.
    #[must_use]
    pub fn status(&self) -> SdkState {
        *self.status.read().expect("LMS-OPS: Status lock poisoned")
    }

    /// Returns a copy of the current sync metrics.
    ///
    /// Time: `O(1)` | Space: `O(1)`
    ///
    /// # Returns
    /// * [`SyncMetrics`]: Thread-safe copy of background sync telemetry.
    ///
    /// # Panics
    /// * **Panics**: Panics if the internal ``metrics`` lock is poisoned.
    #[must_use]
    pub fn metrics(&self) -> SyncMetrics {
        self.metrics.read().expect("LMS-OPS: Metrics lock poisoned").clone()
    }

    /// Returns a copy of the current resolution metrics.
    ///
    /// Time: `O(1)` | Space: `O(1)`
    ///
    /// # Returns
    /// * [`ResolutionMetrics`]: Thread-safe copy of runtime resolution telemetry.
    ///
    /// # Panics
    /// * **Panics**: Panics if the internal ``resolution_metrics`` lock is poisoned.
    #[must_use]
    pub fn resolution_metrics(&self) -> ResolutionMetrics {
        self.resolution_metrics.read().expect("LMS-OPS: Resolution metrics lock poisoned").clone()
    }

    /// Resolves a raw ``BCP 47`` tag dynamically into an immutable [`CapabilityManifest`].
    ///
    /// Time: `O(N)` based on tag truncation length | Space: `O(1)` beyond returned allocations
    ///
    /// # Logic Trace (Internal)
    /// 1. Increment the atomic global metrics counter.
    /// 2. Check health status; if ``Degraded``, yield the hardcoded ``V2.0.0`` fallback.
    /// 3. Delegate valid requests to the ``5-Phase`` pipeline via [`generate_manifest`].
    /// 4. Return the generated manifest or bubble up architectural errors.
    ///
    /// # Arguments
    /// * `tag` (&str): The raw language tag to resolve.
    ///
    /// # Returns
    /// * `Result<CapabilityManifest, LmsError>`: The resolved manifest or a resolution error.
    ///
    /// # Errors
    /// * Returns [`LmsError`] if the pipeline fails during resolution steps.
    ///
    /// # Panics
    /// * Panics if the internal ``resolution_metrics`` lock is poisoned.
    pub fn resolve_capabilities(&self, tag: &str) -> Result<CapabilityManifest, LmsError> {
        // [STEP 1]: Increment operational telemetry
        self.resolution_metrics
            .write()
            .expect("LMS-OPS: Resolution metrics lock poisoned")
            .total_manifests_resolved += 1;

        // [STEP 2]: Check health status; trigger Circuit Breaker if Degraded.
        if self.status() == SdkState::Degraded {
            return Ok(Self::generate_circuit_breaker_manifest());
        }

        // [STEP 3 & 4]: Delegate to the 5-Phase pipeline and return.
        generate_manifest(tag, &self.state)
    }

    /// Generates a guaranteed-safe fallback manifest when the memory pool is unreachable.
    ///
    /// Time: `O(1)` | Space: `O(1)`
    ///
    /// # Logic Trace (Internal)
    /// 1. Instantiate a default ``en-US`` manifest.
    /// 2. Inject immutable Linguistic ``DNA`` traits.
    /// 3. Inject algorithmic execution rules (Mandatory for Phase 4 Integrity).
    /// 4. Inject telemetry metadata including the ``circuit_breaker: "true"`` flag.
    /// 5. Return the hardcoded fallback manifest.
    ///
    /// # Returns
    /// * [`CapabilityManifest`]: The hardcoded system default manifest.
    #[must_use]
    fn generate_circuit_breaker_manifest() -> CapabilityManifest {
        // [STEP 1]: Instantiate default "en-US" manifest.
        let mut manifest = CapabilityManifest::new("en-US".to_string());

        // [STEP 2]: Inject V2.0.0 Domain 1 (Traits)
        manifest.traits.insert(TraitKey::PrimaryDirection, TraitValue::Direction(Direction::LTR));
        manifest.traits.insert(TraitKey::HasBidiElements, TraitValue::Boolean(false));
        manifest.traits.insert(TraitKey::RequiresShaping, TraitValue::Boolean(false));
        manifest.traits.insert(TraitKey::SegmentationStrategy, TraitValue::SegType(SegType::SPACE));
        manifest
            .traits
            .insert(TraitKey::MorphologyType, TraitValue::MorphType(MorphType::FUSIONAL));

        // [STEP 3]: Inject V2.0.0 Domain 2 (Rules) - Required by Phase 4 Integrity!
        manifest.rules.insert("NORMALIZATION_DEFAULT".to_string(), LmsRule::Norm(NormRule::NFC));
        manifest
            .rules
            .insert("TRANSLITERATION_DEFAULT".to_string(), LmsRule::Trans(TransRule::NONE));

        // [STEP 4]: Inject telemetry metadata.
        manifest.metadata.insert("registry_version".to_string(), "CIRCUIT_BREAKER".to_string());
        manifest.metadata.insert("resolution_path".to_string(), "DEGRADED_FALLBACK".to_string());
        manifest.metadata.insert("resolution_time_ms".to_string(), "0.0000".to_string());
        manifest.metadata.insert("circuit_breaker".to_string(), "true".to_string());

        // [STEP 5]: Return fallback manifest.
        manifest
    }
}

#[cfg(all(test, feature = "simulation"))]
mod tests {
    use super::*;
    use crate::data::repository::SimulatedSnapshotProvider;

    #[test]
    fn test_manager_starts_in_bootstrapping_state() {
        let manager = LinguisticManager::new();
        assert_eq!(manager.status(), SdkState::Bootstrapping);
    }

    #[tokio::test]
    async fn test_manager_initializes_into_ready_state() {
        let manager = LinguisticManager::new();
        let provider = SimulatedSnapshotProvider::new();
        // Dynamically inject the key generated by the simulated provider
        manager.initialize(&provider, &provider.public_key).await;

        assert_eq!(manager.status(), SdkState::Ready);

        let metrics = manager.metrics();
        assert!(metrics.last_successful_sync > 0);
        assert_eq!(metrics.sync_error_count, 0);
    }

    #[tokio::test]
    async fn test_manager_delegates_to_dynamic_pipeline() {
        let manager = LinguisticManager::new();
        let provider = SimulatedSnapshotProvider::new();
        manager.initialize(&provider, &provider.public_key).await;

        let manifest =
            manager.resolve_capabilities("th-TH").expect("LMS-TEST: SDK delegation failed");

        assert_eq!(manifest.resolved_locale, "th-TH");
        assert!(!manifest.traits.is_empty());
        assert_eq!(manager.resolution_metrics().total_manifests_resolved, 1);
    }

    #[tokio::test]
    async fn test_circuit_breaker_intercepts_requests() {
        let manager = LinguisticManager::new();

        // Force the degraded state manually
        *manager.status.write().expect("LMS-TEST: Status lock poisoned") = SdkState::Degraded;

        let manifest =
            manager.resolve_capabilities("ar-EG").expect("LMS-TEST: Circuit breaker failed");

        // Verify V2.0.0 fallback structure
        assert_eq!(manifest.resolved_locale, "en-US");
        assert_eq!(
            manifest.metadata.get("registry_version").expect("LMS-TEST: Missing key"),
            "CIRCUIT_BREAKER"
        );
        assert_eq!(
            manifest.metadata.get("circuit_breaker").expect("LMS-TEST: Missing key"),
            "true"
        );

        // Verify Integrity bypass safety
        assert!(manifest.rules.contains_key("NORMALIZATION_DEFAULT"));
    }
}