inklog 0.3.0-rc.2

Enterprise-grade Rust logging infrastructure
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
// Copyright (c) 2026 Kirky.X
// SPDX-License-Identifier: MIT
//! `InklogModule` — trait-kit 0.4 `AsyncKit` integration for inklog.
//!
//! Wires inklog's `Database` abstraction into the `AsyncKit` dependency
//! injection framework, depending on `DbNexusModule` for the database
//! pool capability.
//!
//! `InklogModule::build` retrieves `Arc<dyn ConnectionPool + Send + Sync>`
//! from `DbNexusModule`, wraps it in `DbNexusAdapter` (which implements
//! `Database`), and returns it as `Arc<dyn Database + Send + Sync>`.
//! Consumers can inject this directly into `DatabaseSink` via
//! `LoggerBuilder::with_database(...)`.

use std::any::TypeId;
use std::future::Future;
use std::pin::Pin;
use std::sync::{Arc, OnceLock};

use trait_kit::AsyncReady;
use trait_kit::prelude::*;

use dbnexus::DbNexusModule;

use crate::InklogError;
use crate::integrations::infra::Database;
use crate::integrations::infra::database::DbNexusAdapter;

/// trait-kit `AsyncKit` module that constructs an inklog `Database` impl.
///
/// Depends on `DbNexusModule` (registered first via topological sort).
/// Register with `AsyncKit::register::<InklogModule>()`, then
/// `kit.build().await` and retrieve the capability with
/// `kit.require::<InklogModule>()`.
///
/// The returned `Arc<dyn Database + Send + Sync>` wraps a `DbNexusAdapter`
/// that proxies `insert_batch` / `is_healthy` through the dbnexus
/// `ConnectionPool`. This capability can be injected directly into
/// `LoggerBuilder::with_database(...)`.
///
/// # Lifecycle
///
/// Implements `AsyncLifecycle`:
/// - `on_ready`: verifies `DbNexusModule` capability is accessible in the built kit.
/// - `on_shutdown`: logs inklog module shutdown (connection pool is owned by dbnexus).
///
/// # Health
///
/// Implements `AsyncHealthCheck`:
/// - `check`: returns `Healthy` when the database capability is present in the kit.
///   For detailed async runtime connectivity checks, use `Database::is_healthy()` directly.
pub struct InklogModule;

impl ModuleMeta for InklogModule {
    const NAME: &'static str = "inklog";

    fn dependencies() -> &'static [(&'static str, TypeId)] {
        static DEPS: OnceLock<Vec<(&'static str, TypeId)>> = OnceLock::new();
        DEPS.get_or_init(|| vec![("dbnexus", TypeId::of::<DbNexusModule>())])
            .as_slice()
    }
}

impl AsyncAutoBuilder for InklogModule {
    type Capability = Arc<dyn Database + Send + Sync>;
    type Error = InklogError;

    fn build<'a>(
        kit: &'a AsyncKit,
    ) -> Pin<Box<dyn Future<Output = Result<Self::Capability, Self::Error>> + Send + 'a>> {
        Box::pin(async move {
            // 1. Require DbNexusModule capability (Arc<dyn ConnectionPool + Send + Sync>).
            let pool = kit.require::<DbNexusModule>().map_err(|e| {
                let mut args = fluent_bundle::FluentArgs::new();
                args.set("err", e.to_string());
                InklogError::database_error(crate::i18n::tr_args("config-require_dbnexus", args))
            })?;

            // 2. Wrap in DbNexusAdapter — adapts ConnectionPool to Database.
            let adapter = DbNexusAdapter::from_connection_pool(
                pool,
                crate::support::io::sink::entity::TABLE_NAME,
            )?;

            // 3. Return as Arc<dyn Database + Send + Sync>.
            Ok(Arc::new(adapter) as Arc<dyn Database + Send + Sync>)
        })
    }
}

impl AsyncLifecycle for InklogModule {
    fn on_ready<'a>(
        kit: &'a AsyncKit<AsyncReady>,
    ) -> Pin<Box<dyn Future<Output = Result<(), Self::Error>> + Send + 'a>> {
        Box::pin(async move {
            // Verify DbNexusModule capability is accessible after all modules are built.
            // This catches missing or failed database dependencies early.
            kit.require::<DbNexusModule>().map_err(|e| {
                let mut args = fluent_bundle::FluentArgs::new();
                args.set("err", e.to_string());
                InklogError::database_error(crate::i18n::tr_args("config-db_not_available", args))
            })?;
            tracing::debug!("InklogModule: on_ready — database dependency verified");
            Ok(())
        })
    }

    fn on_shutdown<'a>(
        _cap: &'a Self::Capability,
    ) -> Pin<Box<dyn Future<Output = ()> + Send + 'a>> {
        Box::pin(async {
            // Connection pool lifecycle is managed by DbNexusModule.
            // InklogModule only releases its adapter wrapper here.
            tracing::debug!("InklogModule: on_shutdown — releasing database adapter");
        })
    }
}

impl AsyncHealthCheck for InklogModule {
    fn check(_cap: &Self::Capability) -> HealthStatus {
        // Capability presence confirms the database adapter was successfully built
        // and the underlying connection pool was established during build().
        //
        // Detailed async runtime connectivity checks should use
        // `Database::is_healthy()` directly (e.g. from the HTTP health endpoint).
        HealthStatus::Healthy
    }
}

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

    /// R-inklog-module-003 #1: `InklogModule::NAME == "inklog"`.
    #[test]
    fn inklog_module_meta_name() {
        assert_eq!(InklogModule::NAME, "inklog");
    }

    /// R-inklog-module-003 #2: `InklogModule::dependencies()` declares
    /// a dependency on `DbNexusModule`.
    #[test]
    fn inklog_module_meta_dependencies() {
        let deps = InklogModule::dependencies();
        assert_eq!(deps.len(), 1, "InklogModule should depend on 1 module");
        assert_eq!(deps[0].0, "dbnexus", "dep name should be 'dbnexus'");
        assert_eq!(
            deps[0].1,
            TypeId::of::<DbNexusModule>(),
            "dep TypeId should match DbNexusModule"
        );
    }

    /// R-inklog-module-003 #3: `InklogModule` satisfies `AsyncAutoBuilder`
    /// trait bounds — `Capability: Clone + Send + Sync + 'static` and
    /// `Error: std::error::Error + Send + 'static`.
    #[test]
    fn inklog_module_satisfies_async_auto_builder_bounds() {
        fn assert_cap<T: Clone + Send + Sync + 'static>() {}
        assert_cap::<Arc<dyn Database + Send + Sync>>();
        fn assert_err<T: std::error::Error + Send + 'static>() {}
        assert_err::<InklogError>();
    }

    /// R-inklog-module-003 #4: Full integration — register OxcacheModule +
    /// DbNexusModule + InklogModule, set configs, build, require
    /// InklogModule → get a working `Arc<dyn Database + Send + Sync>`.
    #[cfg(feature = "sqlite")]
    #[tokio::test]
    async fn inklog_module_build_returns_database() {
        use dbnexus::foundation::config::DbConfig;
        use oxcache::integrations::kit::{OxcacheConfig, OxcacheModule};

        let mut kit = AsyncKit::new();
        kit.set_config(OxcacheConfig::default());
        kit.set_config(DbConfig {
            url: "sqlite::memory:".to_string(),
            pool_config: dbnexus::foundation::config::PoolConfig {
                max_connections: 5,
                min_connections: 1,
                ..Default::default()
            },
            ..Default::default()
        });
        kit.register::<OxcacheModule>()
            .expect("register OxcacheModule");
        kit.register::<DbNexusModule>()
            .expect("register DbNexusModule");
        kit.register::<InklogModule>()
            .expect("register InklogModule");
        let kit = kit.build().await.expect("AsyncKit::build");

        let db: Arc<dyn Database + Send + Sync> =
            kit.require::<InklogModule>().expect("require InklogModule");

        // Verify the database is usable — health check should pass.
        assert!(db.is_healthy().await);
    }

    /// R-inklog-module-003 #5: build fails with a clear error if
    /// DbNexusModule is not registered (dependency missing).
    #[cfg(feature = "sqlite")]
    #[tokio::test]
    async fn inklog_module_build_fails_without_dbnexus() {
        let mut kit = AsyncKit::new();
        // Register only InklogModule — DbNexusModule is missing.
        kit.register::<InklogModule>()
            .expect("register InklogModule");
        let err = kit.build().await.expect_err("build should fail");
        let msg = err.to_string();
        assert!(
            msg.contains("dbnexus"),
            "error should mention dbnexus dependency, got: {msg}"
        );
    }

    // ========================================================================
    // AsyncHealthCheck tests
    // ========================================================================

    /// AsyncHealthCheck::check returns Healthy for a valid database capability.
    #[cfg(feature = "sqlite")]
    #[tokio::test]
    async fn inklog_module_health_check_returns_healthy() {
        use dbnexus::foundation::config::DbConfig;
        use oxcache::integrations::kit::{OxcacheConfig, OxcacheModule};

        let mut kit = AsyncKit::new();
        kit.set_config(OxcacheConfig::default());
        kit.set_config(DbConfig {
            url: "sqlite::memory:".to_string(),
            pool_config: dbnexus::foundation::config::PoolConfig {
                max_connections: 5,
                min_connections: 1,
                ..Default::default()
            },
            ..Default::default()
        });
        kit.register::<OxcacheModule>()
            .expect("register OxcacheModule");
        kit.register::<DbNexusModule>()
            .expect("register DbNexusModule");
        kit.register::<InklogModule>()
            .expect("register InklogModule");
        let built = kit.build().await.expect("AsyncKit::build");

        let db: Arc<dyn Database + Send + Sync> = built
            .require::<InklogModule>()
            .expect("require InklogModule");
        let status = InklogModule::check(&db);
        assert_eq!(status, HealthStatus::Healthy);
    }

    // ========================================================================
    // AsyncLifecycle tests
    // ========================================================================

    /// on_ready succeeds when DbNexusModule is registered and accessible.
    #[cfg(feature = "sqlite")]
    #[tokio::test]
    async fn inklog_module_lifecycle_on_ready_succeeds() {
        use dbnexus::foundation::config::DbConfig;
        use oxcache::integrations::kit::{OxcacheConfig, OxcacheModule};

        let mut kit = AsyncKit::new();
        kit.set_config(OxcacheConfig::default());
        kit.set_config(DbConfig {
            url: "sqlite::memory:".to_string(),
            pool_config: dbnexus::foundation::config::PoolConfig {
                max_connections: 5,
                min_connections: 1,
                ..Default::default()
            },
            ..Default::default()
        });
        kit.register::<OxcacheModule>()
            .expect("register OxcacheModule");
        kit.register::<DbNexusModule>()
            .expect("register DbNexusModule");
        kit.register::<InklogModule>()
            .expect("register InklogModule");
        // register_lifecycle enables on_ready/on_shutdown hooks
        kit.register_lifecycle::<InklogModule>();
        // build() invokes on_ready internally — should not error
        let built = kit
            .build()
            .await
            .expect("build with lifecycle should succeed");
        drop(built);
    }

    /// on_shutdown completes without panic after a successful build.
    #[cfg(feature = "sqlite")]
    #[tokio::test]
    async fn inklog_module_lifecycle_shutdown_completes() {
        use dbnexus::foundation::config::DbConfig;
        use oxcache::integrations::kit::{OxcacheConfig, OxcacheModule};

        let mut kit = AsyncKit::new();
        kit.set_config(OxcacheConfig::default());
        kit.set_config(DbConfig {
            url: "sqlite::memory:".to_string(),
            pool_config: dbnexus::foundation::config::PoolConfig {
                max_connections: 5,
                min_connections: 1,
                ..Default::default()
            },
            ..Default::default()
        });
        kit.register::<OxcacheModule>()
            .expect("register OxcacheModule");
        kit.register::<DbNexusModule>()
            .expect("register DbNexusModule");
        kit.register::<InklogModule>()
            .expect("register InklogModule");
        kit.register_lifecycle::<InklogModule>();
        let built = kit.build().await.expect("build");
        // shutdown() invokes on_shutdown for each lifecycle-registered module
        built.shutdown();
    }

    /// Full integration: lifecycle + health check working together.
    #[cfg(feature = "sqlite")]
    #[tokio::test]
    async fn inklog_module_lifecycle_and_health_full_integration() {
        use dbnexus::foundation::config::DbConfig;
        use oxcache::integrations::kit::{OxcacheConfig, OxcacheModule};

        let mut kit = AsyncKit::new();
        kit.set_config(OxcacheConfig::default());
        kit.set_config(DbConfig {
            url: "sqlite::memory:".to_string(),
            pool_config: dbnexus::foundation::config::PoolConfig {
                max_connections: 5,
                min_connections: 1,
                ..Default::default()
            },
            ..Default::default()
        });
        kit.register::<OxcacheModule>()
            .expect("register OxcacheModule");
        kit.register::<DbNexusModule>()
            .expect("register DbNexusModule");
        kit.register::<InklogModule>()
            .expect("register InklogModule");
        kit.register_lifecycle::<InklogModule>();
        kit.register_health_check::<InklogModule>();
        let built = kit.build().await.expect("build");

        // Health check via kit
        let status = built
            .health_check::<InklogModule>()
            .expect("health_check should succeed");
        assert_eq!(status, HealthStatus::Healthy);

        // Shutdown
        built.shutdown();
    }

    // ========================================================================
    // BuildObserver integration tests
    // ========================================================================

    /// Build with InklogBuildObserver — observer receives build events.
    #[cfg(feature = "sqlite")]
    #[tokio::test]
    async fn inklog_module_build_with_observer() {
        use dbnexus::foundation::config::DbConfig;
        use oxcache::integrations::kit::{OxcacheConfig, OxcacheModule};

        use super::super::InklogBuildObserver;

        let mut kit = AsyncKit::new();
        kit.with_observer(Arc::new(InklogBuildObserver));
        kit.set_config(OxcacheConfig::default());
        kit.set_config(DbConfig {
            url: "sqlite::memory:".to_string(),
            pool_config: dbnexus::foundation::config::PoolConfig {
                max_connections: 5,
                min_connections: 1,
                ..Default::default()
            },
            ..Default::default()
        });
        kit.register::<OxcacheModule>()
            .expect("register OxcacheModule");
        kit.register::<DbNexusModule>()
            .expect("register DbNexusModule");
        kit.register::<InklogModule>()
            .expect("register InklogModule");
        let built = kit.build().await.expect("build with observer");
        let db: Arc<dyn Database + Send + Sync> =
            built.require::<InklogModule>().expect("require db");
        assert!(db.is_healthy().await);
    }

    // ========================================================================
    // AsyncScope integration tests
    // ========================================================================

    /// create_inklog_scope + populate + require round-trip.
    #[cfg(feature = "sqlite")]
    #[tokio::test]
    async fn inklog_scope_insert_require_roundtrip() {
        use dbnexus::foundation::config::DbConfig;
        use oxcache::integrations::kit::{OxcacheConfig, OxcacheModule};

        use super::super::{create_inklog_scope, populate_inklog_scope};

        // Build with main kit first
        let mut kit = AsyncKit::new();
        kit.set_config(OxcacheConfig::default());
        kit.set_config(DbConfig {
            url: "sqlite::memory:".to_string(),
            pool_config: dbnexus::foundation::config::PoolConfig {
                max_connections: 2,
                min_connections: 1,
                ..Default::default()
            },
            ..Default::default()
        });
        kit.register::<OxcacheModule>()
            .expect("register OxcacheModule");
        kit.register::<DbNexusModule>()
            .expect("register DbNexusModule");
        kit.register::<InklogModule>()
            .expect("register InklogModule");
        let built = kit.build().await.expect("build");
        let db = built.require::<InklogModule>().expect("require from kit");

        // Insert into scope and retrieve
        let scope = create_inklog_scope();
        populate_inklog_scope(&scope, db);
        let retrieved = scope.require::<InklogModule>().expect("require from scope");
        assert!(retrieved.is_healthy().await);
    }
}