cf-modkit 0.6.4

Core ModKit library
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
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
use serde::de::DeserializeOwned;
use std::sync::Arc;
use tokio_util::sync::CancellationToken;
use uuid::Uuid;

// Import configuration types from the config module
use crate::{
    config::{ConfigError, ConfigProvider, module_config_or_default},
    module_config_required,
};

// Note: runtime-dependent features are conditionally compiled

// DB types are available only when feature "db" is enabled.
// We keep local aliases so the rest of this file can compile without importing `modkit_db`.
#[cfg(feature = "db")]
pub(crate) type DbManager = modkit_db::DbManager;
#[cfg(feature = "db")]
pub(crate) type DbProvider = modkit_db::DBProvider<modkit_db::DbError>;

// Stub types for no-db builds (never exposed; methods that would use them are cfg'd out).
#[cfg(not(feature = "db"))]
#[derive(Clone, Debug)]
pub struct DbManager;
#[cfg(not(feature = "db"))]
#[derive(Clone, Debug)]
pub struct DbProvider;

#[derive(Clone)]
#[must_use]
pub struct ModuleCtx {
    module_name: Arc<str>,
    instance_id: Uuid,
    config_provider: Arc<dyn ConfigProvider>,
    client_hub: Arc<crate::client_hub::ClientHub>,
    cancellation_token: CancellationToken,
    db: Option<DbProvider>,
}

/// Builder for creating module-scoped contexts with resolved database handles.
///
/// This builder internally uses `DbManager` to resolve per-module `Db` instances
/// at build time, ensuring `ModuleCtx` contains only the final, ready-to-use entrypoint.
pub struct ModuleContextBuilder {
    instance_id: Uuid,
    config_provider: Arc<dyn ConfigProvider>,
    client_hub: Arc<crate::client_hub::ClientHub>,
    root_token: CancellationToken,
    db_manager: Option<Arc<DbManager>>, // internal only, never exposed to modules
}

impl ModuleContextBuilder {
    pub fn new(
        instance_id: Uuid,
        config_provider: Arc<dyn ConfigProvider>,
        client_hub: Arc<crate::client_hub::ClientHub>,
        root_token: CancellationToken,
        db_manager: Option<Arc<DbManager>>,
    ) -> Self {
        Self {
            instance_id,
            config_provider,
            client_hub,
            root_token,
            db_manager,
        }
    }

    /// Returns the process-level instance ID.
    #[must_use]
    pub fn instance_id(&self) -> Uuid {
        self.instance_id
    }

    /// Build a module-scoped context, resolving the `DbHandle` for the given module.
    ///
    /// # Errors
    /// Returns an error if database resolution fails.
    pub async fn for_module(&self, module_name: &str) -> anyhow::Result<ModuleCtx> {
        let db: Option<DbProvider> = {
            #[cfg(feature = "db")]
            {
                if let Some(mgr) = &self.db_manager {
                    mgr.get(module_name).await?.map(modkit_db::DBProvider::new)
                } else {
                    None
                }
            }
            #[cfg(not(feature = "db"))]
            {
                let _ = module_name; // avoid unused in no-db builds
                None
            }
        };

        Ok(ModuleCtx::new(
            Arc::<str>::from(module_name),
            self.instance_id,
            self.config_provider.clone(),
            self.client_hub.clone(),
            self.root_token.child_token(),
            db,
        ))
    }
}

impl ModuleCtx {
    /// Create a new module-scoped context with all required fields.
    pub fn new(
        module_name: impl Into<Arc<str>>,
        instance_id: Uuid,
        config_provider: Arc<dyn ConfigProvider>,
        client_hub: Arc<crate::client_hub::ClientHub>,
        cancellation_token: CancellationToken,
        db: Option<DbProvider>,
    ) -> Self {
        Self {
            module_name: module_name.into(),
            instance_id,
            config_provider,
            client_hub,
            cancellation_token,
            db,
        }
    }

    // ---- public read-only API for modules ----

    #[inline]
    #[must_use]
    pub fn module_name(&self) -> &str {
        &self.module_name
    }

    /// Returns the process-level instance ID.
    ///
    /// This is a unique identifier for this process instance, shared by all modules
    /// in the same process. It is generated once at bootstrap.
    #[inline]
    #[must_use]
    pub fn instance_id(&self) -> Uuid {
        self.instance_id
    }

    #[inline]
    #[must_use]
    pub fn config_provider(&self) -> &dyn ConfigProvider {
        &*self.config_provider
    }

    /// Get the `ClientHub` for dependency resolution.
    #[inline]
    #[must_use]
    pub fn client_hub(&self) -> Arc<crate::client_hub::ClientHub> {
        self.client_hub.clone()
    }

    #[inline]
    #[must_use]
    pub fn cancellation_token(&self) -> &CancellationToken {
        &self.cancellation_token
    }

    /// Get a module-scoped DB entrypoint for secure database operations.
    ///
    /// Returns `None` if no database is configured for this module.
    ///
    /// # Security
    ///
    /// The returned `DBProvider<modkit_db::DbError>`:
    /// - Is cheap to clone (shares an internal `Db`)
    /// - Provides `conn()` for non-transactional access (fails inside tx via guard)
    /// - Provides `transaction(..)` for transactional operations
    ///
    /// # Example
    ///
    /// ```ignore
    /// let db = ctx.db().ok_or_else(|| anyhow!("no db"))?;
    /// let conn = db.conn()?;
    /// let user = svc.get_user(&conn, &scope, id).await?;
    /// ```
    #[must_use]
    #[cfg(feature = "db")]
    pub fn db(&self) -> Option<modkit_db::DBProvider<modkit_db::DbError>> {
        self.db.clone()
    }

    /// Get a database handle, returning an error if not configured.
    ///
    /// This is a convenience method that combines `db()` with an error for
    /// modules that require database access.
    ///
    /// # Errors
    ///
    /// Returns an error if the database is not configured for this module.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let db = ctx.db_required()?;
    /// let conn = db.conn()?;
    /// let user = svc.get_user(&conn, &scope, id).await?;
    /// ```
    #[cfg(feature = "db")]
    pub fn db_required(&self) -> anyhow::Result<modkit_db::DBProvider<modkit_db::DbError>> {
        self.db().ok_or_else(|| {
            anyhow::anyhow!(
                "Database is not configured for module '{}'",
                self.module_name
            )
        })
    }

    /// Deserialize the module's config section into `T`.
    ///
    /// This reads the `modules.<name>.config` object for the current module and
    /// deserializes it into the requested type.
    ///
    /// # Errors
    /// Returns `ConfigError` if the module config is missing or deserialization fails.
    pub fn config<T: DeserializeOwned>(&self) -> Result<T, ConfigError> {
        module_config_required(self.config_provider.as_ref(), &self.module_name)
    }

    /// Deserialize the module's config section into T, or use defaults if missing.
    ///
    /// This method uses lenient configuration loading: if the module is not present in config,
    /// has no config section, or the module entry is not an object, it returns `T::default()`.
    /// This allows modules to exist without configuration sections in the main config file.
    ///
    /// It extracts the 'config' field from: `modules.<name> = { database: ..., config: ... }`
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// #[derive(serde::Deserialize, Default)]
    /// struct MyConfig {
    ///     api_key: String,
    ///     timeout_ms: u64,
    /// }
    ///
    /// let config: MyConfig = ctx.config_or_default()?;
    /// ```
    ///
    /// # Errors
    /// Returns `ConfigError` if deserialization fails.
    pub fn config_or_default<T: DeserializeOwned + Default>(&self) -> Result<T, ConfigError> {
        module_config_or_default(self.config_provider.as_ref(), &self.module_name)
    }

    /// Like [`config()`](Self::config), but additionally expands `${VAR}` placeholders
    /// in fields marked with `#[expand_vars]`.
    ///
    /// # Errors
    /// Returns `ConfigError` if the module config is missing, deserialization fails,
    /// or environment variable expansion fails.
    pub fn config_expanded<T>(&self) -> Result<T, ConfigError>
    where
        T: DeserializeOwned + crate::var_expand::ExpandVars,
    {
        let mut cfg: T = self.config()?;
        cfg.expand_vars().map_err(|e| ConfigError::VarExpand {
            module: self.module_name.to_string(),
            source: e,
        })?;
        Ok(cfg)
    }

    /// Like [`config_or_default()`](Self::config_or_default), but additionally expands `${VAR}`
    /// placeholders
    /// in fields marked with `#[expand_vars]` (requires `#[derive(ExpandVars)]` on the config
    /// struct).
    ///
    /// Modules that do not need environment variable expansion should use
    /// [`config_or_default()`](Self::config_or_default).
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// #[derive(serde::Deserialize, Default, ExpandVars)]
    /// struct MyConfig {
    ///     #[expand_vars]
    ///     api_key: String,
    ///     timeout_ms: u64,
    /// }
    ///
    /// let config: MyConfig = ctx.config_expanded_or_default()?;
    /// ```
    ///
    /// # Errors
    /// Returns `ConfigError` if deserialization fails or if environment variable expansion fails.
    pub fn config_expanded_or_default<T>(&self) -> Result<T, ConfigError>
    where
        T: DeserializeOwned + Default + crate::var_expand::ExpandVars,
    {
        let mut cfg: T = self.config_or_default()?;
        cfg.expand_vars().map_err(|e| ConfigError::VarExpand {
            module: self.module_name.to_string(),
            source: e,
        })?;
        Ok(cfg)
    }

    /// Get the raw JSON value of the module's config section.
    /// Returns the 'config' field from: modules.<name> = { database: ..., config: ... }
    #[must_use]
    pub fn raw_config(&self) -> &serde_json::Value {
        use std::sync::LazyLock;

        static EMPTY: LazyLock<serde_json::Value> =
            LazyLock::new(|| serde_json::Value::Object(serde_json::Map::new()));

        if let Some(module_raw) = self.config_provider.get_module_config(&self.module_name) {
            // Try new structure first: modules.<name> = { database: ..., config: ... }
            if let Some(obj) = module_raw.as_object()
                && let Some(config_section) = obj.get("config")
            {
                return config_section;
            }
        }
        &EMPTY
    }

    /// Create a derivative context with the same references but no DB handle.
    /// Useful for modules that don't require database access.
    pub fn without_db(&self) -> ModuleCtx {
        ModuleCtx {
            module_name: self.module_name.clone(),
            instance_id: self.instance_id,
            config_provider: self.config_provider.clone(),
            client_hub: self.client_hub.clone(),
            cancellation_token: self.cancellation_token.clone(),
            db: None,
        }
    }
}

#[cfg(test)]
#[cfg_attr(coverage_nightly, coverage(off))]
mod tests {
    use super::*;
    use serde::Deserialize;
    use serde_json::json;
    use std::collections::HashMap;

    #[derive(Debug, PartialEq, Deserialize, Default)]
    struct TestConfig {
        #[serde(default)]
        api_key: String,
        #[serde(default)]
        timeout_ms: u64,
        #[serde(default)]
        enabled: bool,
    }

    struct MockConfigProvider {
        modules: HashMap<String, serde_json::Value>,
    }

    impl MockConfigProvider {
        fn new() -> Self {
            let mut modules = HashMap::new();

            // Valid module config
            modules.insert(
                "test_module".to_owned(),
                json!({
                    "database": {
                        "url": "postgres://localhost/test"
                    },
                    "config": {
                        "api_key": "secret123",
                        "timeout_ms": 5000,
                        "enabled": true
                    }
                }),
            );

            Self { modules }
        }
    }

    impl ConfigProvider for MockConfigProvider {
        fn get_module_config(&self, module_name: &str) -> Option<&serde_json::Value> {
            self.modules.get(module_name)
        }
    }

    #[test]
    fn test_module_ctx_config_with_valid_config() {
        let provider = Arc::new(MockConfigProvider::new());
        let ctx = ModuleCtx::new(
            "test_module",
            Uuid::new_v4(),
            provider,
            Arc::new(crate::client_hub::ClientHub::default()),
            CancellationToken::new(),
            None,
        );

        let result: Result<TestConfig, ConfigError> = ctx.config();
        assert!(result.is_ok());

        let config = result.unwrap();
        assert_eq!(config.api_key, "secret123");
        assert_eq!(config.timeout_ms, 5000);
        assert!(config.enabled);
    }

    #[test]
    fn test_module_ctx_config_returns_error_for_missing_module() {
        let provider = Arc::new(MockConfigProvider::new());
        let ctx = ModuleCtx::new(
            "nonexistent_module",
            Uuid::new_v4(),
            provider,
            Arc::new(crate::client_hub::ClientHub::default()),
            CancellationToken::new(),
            None,
        );

        let result: Result<TestConfig, ConfigError> = ctx.config();
        assert!(matches!(
            result,
            Err(ConfigError::ModuleNotFound { ref module }) if module == "nonexistent_module"
        ));
    }

    #[test]
    fn test_module_ctx_config_or_default_returns_default_for_missing_module() {
        let provider = Arc::new(MockConfigProvider::new());
        let ctx = ModuleCtx::new(
            "nonexistent_module",
            Uuid::new_v4(),
            provider,
            Arc::new(crate::client_hub::ClientHub::default()),
            CancellationToken::new(),
            None,
        );

        let result: Result<TestConfig, ConfigError> = ctx.config_or_default();
        assert!(result.is_ok());

        let config = result.unwrap();
        assert_eq!(config, TestConfig::default());
    }

    #[test]
    fn test_module_ctx_instance_id() {
        let provider = Arc::new(MockConfigProvider::new());
        let instance_id = Uuid::new_v4();
        let ctx = ModuleCtx::new(
            "test_module",
            instance_id,
            provider,
            Arc::new(crate::client_hub::ClientHub::default()),
            CancellationToken::new(),
            None,
        );

        assert_eq!(ctx.instance_id(), instance_id);
    }

    // --- config_expanded tests ---

    #[derive(Debug, PartialEq, Deserialize, Default, modkit_macros::ExpandVars)]
    struct ExpandableConfig {
        #[expand_vars]
        #[serde(default)]
        api_key: String,
        #[expand_vars]
        #[serde(default)]
        endpoint: Option<String>,
        #[serde(default)]
        retries: u32,
    }

    fn make_ctx(module_name: &str, config_json: serde_json::Value) -> ModuleCtx {
        let mut modules = HashMap::new();
        modules.insert(module_name.to_owned(), config_json);
        let provider = Arc::new(MockConfigProvider { modules });
        ModuleCtx::new(
            module_name,
            Uuid::new_v4(),
            provider,
            Arc::new(crate::client_hub::ClientHub::default()),
            CancellationToken::new(),
            None,
        )
    }

    #[test]
    fn config_expanded_resolves_env_vars() {
        let ctx = make_ctx(
            "expand_mod",
            json!({
                "config": {
                    "api_key": "${MODKIT_TEST_KEY}",
                    "endpoint": "https://${MODKIT_TEST_HOST}/api",
                    "retries": 3
                }
            }),
        );

        temp_env::with_vars(
            [
                ("MODKIT_TEST_KEY", Some("secret-42")),
                ("MODKIT_TEST_HOST", Some("example.com")),
            ],
            || {
                let cfg: ExpandableConfig = ctx.config_expanded().unwrap();
                assert_eq!(cfg.api_key, "secret-42");
                assert_eq!(cfg.endpoint.as_deref(), Some("https://example.com/api"));
                assert_eq!(cfg.retries, 3);
            },
        );
    }

    #[test]
    fn config_expanded_returns_error_on_missing_var() {
        let ctx = make_ctx(
            "expand_mod",
            json!({
                "config": {
                    "api_key": "${MODKIT_TEST_MISSING_VAR_XYZ}"
                }
            }),
        );

        temp_env::with_vars([("MODKIT_TEST_MISSING_VAR_XYZ", None::<&str>)], || {
            let err = ctx.config_expanded::<ExpandableConfig>().unwrap_err();
            assert!(
                matches!(err, ConfigError::VarExpand { ref module, .. } if module == "expand_mod"),
                "expected EnvExpand error, got: {err:?}"
            );
        });
    }

    #[test]
    fn config_expanded_skips_none_option_fields() {
        let ctx = make_ctx(
            "expand_mod",
            json!({
                "config": {
                    "api_key": "literal-key",
                    "retries": 5
                }
            }),
        );

        let cfg: ExpandableConfig = ctx.config_expanded().unwrap();
        assert_eq!(cfg.api_key, "literal-key");
        assert_eq!(cfg.endpoint, None);
        assert_eq!(cfg.retries, 5);
    }

    #[test]
    fn config_expanded_returns_error_when_missing() {
        let ctx = make_ctx("missing_mod", json!({}));
        let err = ctx.config_expanded::<ExpandableConfig>().unwrap_err();
        assert!(matches!(
            err,
            ConfigError::MissingConfigSection { ref module } if module == "missing_mod"
        ));
    }

    #[test]
    fn config_expanded_or_default_falls_back_to_default_when_missing() {
        let ctx = make_ctx("missing_mod", json!({}));
        let cfg: ExpandableConfig = ctx.config_expanded_or_default().unwrap();
        assert_eq!(cfg, ExpandableConfig::default());
    }

    // --- nested struct expansion ---

    #[derive(Debug, PartialEq, Deserialize, Default, modkit_macros::ExpandVars)]
    struct NestedProvider {
        #[expand_vars]
        #[serde(default)]
        host: String,
        #[expand_vars]
        #[serde(default)]
        token: Option<String>,
        #[expand_vars]
        #[serde(default)]
        auth_config: Option<HashMap<String, String>>,
        #[serde(default)]
        port: u16,
    }

    #[derive(Debug, PartialEq, Deserialize, Default, modkit_macros::ExpandVars)]
    struct NestedConfig {
        #[expand_vars]
        #[serde(default)]
        name: String,
        #[expand_vars]
        #[serde(default)]
        providers: HashMap<String, NestedProvider>,
        #[expand_vars]
        #[serde(default)]
        tags: Vec<String>,
    }

    #[test]
    fn config_expanded_resolves_nested_structs() {
        let ctx = make_ctx(
            "nested_mod",
            json!({
                "config": {
                    "name": "${MODKIT_NESTED_NAME}",
                    "providers": {
                        "primary": {
                            "host": "${MODKIT_NESTED_HOST}",
                            "token": "${MODKIT_NESTED_TOKEN}",
                            "auth_config": {
                                "header": "X-Api-Key",
                                "secret_ref": "${MODKIT_NESTED_SECRET}"
                            },
                            "port": 443
                        }
                    },
                    "tags": ["${MODKIT_NESTED_TAG}", "literal"]
                }
            }),
        );

        temp_env::with_vars(
            [
                ("MODKIT_NESTED_NAME", Some("my-service")),
                ("MODKIT_NESTED_HOST", Some("api.example.com")),
                ("MODKIT_NESTED_TOKEN", Some("sk-secret")),
                ("MODKIT_NESTED_SECRET", Some("key-12345")),
                ("MODKIT_NESTED_TAG", Some("production")),
            ],
            || {
                let cfg: NestedConfig = ctx.config_expanded().unwrap();
                assert_eq!(cfg.name, "my-service");
                assert_eq!(cfg.tags, vec!["production", "literal"]);

                let primary = cfg.providers.get("primary").expect("primary provider");
                assert_eq!(primary.host, "api.example.com");
                assert_eq!(primary.token.as_deref(), Some("sk-secret"));
                assert_eq!(primary.port, 443);

                let auth = primary.auth_config.as_ref().expect("auth_config present");
                assert_eq!(auth.get("header").map(String::as_str), Some("X-Api-Key"));
                assert_eq!(
                    auth.get("secret_ref").map(String::as_str),
                    Some("key-12345")
                );
            },
        );
    }

    #[test]
    fn config_expanded_nested_missing_var_returns_error() {
        let ctx = make_ctx(
            "nested_mod",
            json!({
                "config": {
                    "name": "ok",
                    "providers": {
                        "bad": { "host": "${MODKIT_NESTED_GONE}", "port": 80 }
                    }
                }
            }),
        );

        temp_env::with_vars([("MODKIT_NESTED_GONE", None::<&str>)], || {
            let err = ctx.config_expanded::<NestedConfig>().unwrap_err();
            assert!(
                matches!(err, ConfigError::VarExpand { ref module, .. } if module == "nested_mod"),
                "expected EnvExpand, got: {err:?}"
            );
        });
    }
}