limiteron 0.3.0-rc.7

Unified flow control framework for Rust
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
// Copyright (c) 2026 Kirky.X🌠
// SPDX-License-Identifier: MIT
//! `LimiteronModule` — trait-kit `AsyncKit` integration for limiteron.
//!
//! Wires limiteron's [`Governor`] into the `AsyncKit` dependency
//! injection framework as a leaf module (no upstream dependencies).
//!
//! # Design divergence from `design.md` / `spec.md` (Rule 7: expose, don't
//! paper over)
//!
//! `design.md` Decision 3 (lines 417-439) and `limiteron-module/spec.md`
//! R-001 wrote the capability type as `Arc<dyn Limiter + Send + Sync>`, the
//! error type as `LimiteronError`, and the config type as `LimiteronConfig`.
//! limiteron v0.2.1's actual API does not match this pseudo-code on **three**
//! independent points, all surfaced here rather than papered over:
//!
//! 1. **`Governor` does NOT implement `Limiter`** — `Governor::check` takes
//!    `&RequestContext` and returns `Decision`; `Limiter::allow` takes `u64`
//!    cost and returns `bool`. `Governor` is the *controller* (orchestrates
//!    a `DecisionChain` of `Limiter`s), not itself a `Limiter`. We therefore
//!    expose the capability as `Arc<Governor>` (concrete type) instead of
//!    `Arc<dyn Limiter>`. This mirrors oxcache's approach (using
//!    `CacheBackend` instead of non-object-safe `UnifiedCache`).
//!
//! 2. **`LimiteronError` does NOT exist** — limiteron's error type is
//!    [`LimiteronError`] (thiserror-based, implements `std::error::Error +
//!    Send + 'static`). We use `LimiteronError` as `AsyncAutoBuilder::Error`.
//!
//! 3. **`LimiteronConfig` does NOT exist** — per spec Constraints line 43
//!    ("LimiteronConfig 类型从 limiteron 现有配置类型复用"), we reuse
//!    limiteron's existing [`FlowControlConfig`] directly.
//!
//! **Follow-up**: if the spec owner requires
//! the literal `Arc<dyn Limiter>` form, `Governor` must be made to implement
//! `Limiter` (or a new `RateLimiter` trait introduced). That change affects
//! limiteron's public API and is deferred to its own change spec.

use crate::config::FlowControlConfig;
use crate::error::LimiteronError;
use crate::governor::Governor;
use crate::storage::{BanStorage, MemoryBanStorage, MemoryStorage, Storage};
use std::any::TypeId;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;

use oxcache::integrations::kit::OxcacheModule;
use trait_kit::prelude::*;

/// 存储覆盖配置 — 通过 `AsyncKit::set_config(LimiteronStorageConfig::...)`
/// 向 [`LimiteronModule`] 注入自定义 `Storage` / `BanStorage` 实例。
///
/// 未设置(或不调用任何 builder 方法)时,`LimiteronModule` 保持默认行为:
/// 使用进程内 `MemoryStorage` / `MemoryBanStorage`(向后兼容)。
#[derive(Default, Clone)]
pub struct LimiteronStorageConfig {
    storage: Option<Arc<dyn Storage>>,
    ban_storage: Option<Arc<dyn BanStorage>>,
}

impl LimiteronStorageConfig {
    /// 创建空覆盖配置(全部使用默认实现)。
    pub fn new() -> Self {
        Self::default()
    }

    /// 注入存储实例。
    pub fn with_storage(mut self, storage: Arc<dyn Storage>) -> Self {
        self.storage = Some(storage);
        self
    }

    /// 注入封禁存储实例。
    pub fn with_ban_storage(mut self, ban_storage: Arc<dyn BanStorage>) -> Self {
        self.ban_storage = Some(ban_storage);
        self
    }

    /// 已注入的存储(`None` = 使用默认 `MemoryStorage`)。
    pub fn storage(&self) -> Option<Arc<dyn Storage>> {
        self.storage.clone()
    }

    /// 已注入的封禁存储(`None` = 使用默认 `MemoryBanStorage`)。
    pub fn ban_storage(&self) -> Option<Arc<dyn BanStorage>> {
        self.ban_storage.clone()
    }
}

/// trait-kit `AsyncKit` module that constructs a limiteron `Governor`.
///
/// Leaf module (no upstream dependencies). Register with
/// `AsyncKit::register::<LimiteronModule>()`, configure via
/// `kit.set_config(FlowControlConfig::default())`, then `kit.build().await`
/// and retrieve the capability with `kit.require::<LimiteronModule>()`.
///
/// The returned `Arc<Governor>` is the concrete controller type — see the
/// module-level docs for the design-divergence rationale (spec.md wrote
/// `Arc<dyn Limiter>`, but `Governor` does not implement `Limiter`).
pub struct LimiteronModule;

impl ModuleMeta for LimiteronModule {
    const NAME: &'static str = "limiteron";

    /// 依赖 `OxcacheModule`(dbnexus `DbNexusModule` 同款范式)——
    /// 上游 oxcache 先构建缓存后端,limiteron 构建期经 `require` 注入并做
    /// 探活写读(缓存链路故障快速失败;未注入/不可用时降级为内存,不阻断)。
    fn dependencies() -> &'static [(&'static str, TypeId)] {
        static DEPS: std::sync::OnceLock<Vec<(&'static str, TypeId)>> = std::sync::OnceLock::new();
        DEPS.get_or_init(|| vec![("oxcache", TypeId::of::<OxcacheModule>())])
    }
}

impl AsyncAutoBuilder for LimiteronModule {
    type Capability = Arc<Governor>;
    type Error = LimiteronError;

    fn build<'a>(
        kit: &'a AsyncKit,
    ) -> Pin<Box<dyn Future<Output = Result<Self::Capability, Self::Error>> + Send + 'a>> {
        Box::pin(async move {
            let config: FlowControlConfig = kit.config().map_err(|e| {
                LimiteronError::ConfigError(format!("LimiteronModule: read config: {e}"))
            })?;
            // 存储注入钩子:`kit.set_config(LimiteronStorageConfig::...)` 注入
            // 自定义存储;未设置时使用 in-memory 实现(leaf module 不依赖
            // postgres/redis 后端;生产调用方可用 Governor 的 builder 直连持久化
            // 存储,kit 集成面向 wiring/测试场景)。
            let storage_override: Option<LimiteronStorageConfig> = kit.config().ok();
            let storage: Arc<dyn Storage> = storage_override
                .as_ref()
                .and_then(|o| o.storage())
                .unwrap_or_else(|| Arc::new(MemoryStorage::new()) as Arc<dyn Storage>);
            let ban_storage: Arc<dyn BanStorage> = storage_override
                .as_ref()
                .and_then(|o| o.ban_storage())
                .unwrap_or_else(|| Arc::new(MemoryBanStorage::new()) as Arc<dyn BanStorage>);
            // 经 OxcacheModule 注入缓存——上游缓存后端可用时执行
            // set/get/delete 探活写读(验证 kit 缓存链路);探测失败仅告警
            // 并继续(Governor 自带内存 兜底,缓存故障不阻断限流主链路)。
            if let Ok(cache) = kit.require::<OxcacheModule>() {
                const PROBE_KEY: &str = "limiteron:kit:probe";
                let payload: Arc<Vec<u8>> = Arc::new(b"limiteron-cache-probe".to_vec());
                let probe_ok = async {
                    cache
                        .set(Arc::from(PROBE_KEY), payload.clone(), None)
                        .await
                        .ok()?;
                    let got = cache.get(PROBE_KEY).await.ok().flatten()?;
                    cache.delete(PROBE_KEY).await.ok()?;
                    (got.as_slice() == payload.as_slice()).then_some(())
                }
                .await;
                if probe_ok.is_none() {
                    log::warn!(
                        "LimiteronModule: OxcacheModule cache probe failed; continuing with in-memory L1"
                    );
                }
            }
            let governor = Governor::builder()
                .with_config(config)
                .with_storage(storage)
                .with_ban_storage(ban_storage)
                .build()
                .await?;
            Ok(Arc::new(governor))
        })
    }
}

/// trait-kit 健康端口——`AsyncHealthCheck` 经
/// [`Governor::health_status`](crate::governor::Governor::health_status)
/// 汇报存储/封禁存储/缓存/后台任务健康(`/healthz` 同一数据源)。
impl trait_kit::core::health::AsyncHealthCheck for LimiteronModule {
    fn check(cap: &Self::Capability) -> trait_kit::core::health::HealthStatus {
        use trait_kit::core::health::HealthStatus;
        // health_status 含快速 IO 探针;与 OxcacheModule 同款 block_on 方案
        let hs = futures::executor::block_on(cap.health_status());
        if hs.healthy() {
            HealthStatus::Healthy
        } else {
            let mut detail = Vec::new();
            if !hs.storage_healthy {
                detail.push("storage");
            }
            if !hs.ban_storage_healthy {
                detail.push("ban-storage");
            }
            if !hs.cache_healthy {
                detail.push("l1-cache");
            }
            if !hs.background_tasks_alive {
                detail.push("background-tasks");
            }
            HealthStatus::unhealthy(format!("unhealthy components: {}", detail.join(",")))
        }
    }
}

/// trait-kit 生命周期端口——`AsyncLifecycle::on_shutdown` 优雅停机
/// Governor(停止接新 + 停后台任务,与 admin API 停机路径一致)。
impl trait_kit::core::lifecycle::AsyncLifecycle for LimiteronModule {
    fn on_ready<'a>(
        kit: &'a trait_kit::kit::AsyncKit<trait_kit::kit::async_kit::Ready>,
    ) -> Pin<Box<dyn Future<Output = Result<(), Self::Error>> + Send + 'a>> {
        Box::pin(async move {
            // 能力已就绪:经 require 取回 Governor 确认链路完整(依赖
            // OxcacheModule 已在前序层级构建完成)
            let _governor: Arc<Governor> = kit.require::<LimiteronModule>().map_err(|e| {
                LimiteronError::ConfigError(format!("LimiteronModule on_ready: {e}"))
            })?;
            Ok(())
        })
    }

    fn on_shutdown<'a>(cap: &'a Self::Capability) -> Pin<Box<dyn Future<Output = ()> + Send + 'a>> {
        Box::pin(async move {
            if let Err(e) = cap.shutdown().await {
                log::warn!("LimiteronModule shutdown error: {e}");
            }
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::FlowControlConfig;
    #[cfg(feature = "ban-manager")]
    use crate::error::StorageError;
    use crate::governor::Governor;
    #[cfg(feature = "ban-manager")]
    use crate::matchers::Identifier;
    #[cfg(feature = "ban-manager")]
    use crate::storage::{BanHistory, BanRecord, BanTarget};
    use oxcache::integrations::kit::OxcacheConfig;
    #[cfg(feature = "ban-manager")]
    use std::any::Any;
    use std::any::TypeId;
    use std::sync::Arc;
    #[cfg(feature = "ban-manager")]
    use std::sync::atomic::{AtomicUsize, Ordering};

    /// 可观测的封禁存储替身:委托给真实 `MemoryBanStorage`,同时计数
    /// `save`/`is_banned` 调用,用于验证注入实例确实被路由使用
    /// (单元层测试替身,符合净化规范)。
    #[cfg(feature = "ban-manager")]
    struct RecordingBanStorage {
        inner: MemoryBanStorage,
        saves: AtomicUsize,
    }

    #[cfg(feature = "ban-manager")]
    impl RecordingBanStorage {
        fn new() -> Self {
            Self {
                inner: MemoryBanStorage::new(),
                saves: AtomicUsize::new(0),
            }
        }

        fn save_count(&self) -> usize {
            self.saves.load(Ordering::SeqCst)
        }
    }

    #[cfg(feature = "ban-manager")]
    #[async_trait::async_trait]
    impl BanStorage for RecordingBanStorage {
        async fn is_banned(&self, target: &BanTarget) -> Result<Option<BanRecord>, StorageError> {
            self.inner.is_banned(target).await
        }

        async fn save(&self, record: &BanRecord) -> Result<(), StorageError> {
            self.saves.fetch_add(1, Ordering::SeqCst);
            self.inner.save(record).await
        }

        async fn get_history(
            &self,
            target: &BanTarget,
        ) -> Result<Option<BanHistory>, StorageError> {
            self.inner.get_history(target).await
        }

        async fn increment_ban_times(&self, target: &BanTarget) -> Result<u64, StorageError> {
            self.inner.increment_ban_times(target).await
        }

        async fn get_ban_times(&self, target: &BanTarget) -> Result<u64, StorageError> {
            self.inner.get_ban_times(target).await
        }

        async fn remove_ban(&self, target: &BanTarget) -> Result<(), StorageError> {
            self.inner.remove_ban(target).await
        }

        async fn cleanup_expired_bans(&self) -> Result<u64, StorageError> {
            self.inner.cleanup_expired_bans().await
        }

        async fn list_bans(
            &self,
            active_only: bool,
            offset: u64,
            limit: u64,
        ) -> Result<Vec<BanRecord>, StorageError> {
            self.inner.list_bans(active_only, offset, limit).await
        }

        fn as_any(&self) -> &dyn Any {
            self
        }
    }

    /// Build a minimal valid `FlowControlConfig` (1 rule, 1 matcher, 1
    /// limiter). `FlowControlConfig::default()` has an empty rules vec, which
    /// fails `validate()` with "至少需要一个规则" — Governor::builder().build()
    /// calls validate() and returns Err. The kit integration must surface that
    /// Err, not paper over it (Rule 12), so tests use a valid config.
    fn make_minimal_valid_config() -> FlowControlConfig {
        use crate::config::{Action, ActionConfig, LimiterConfig, Matcher, Rule};
        let mut config = FlowControlConfig::default();
        config.rules.push(Rule {
            id: "default".to_string(),
            name: "default rule".to_string(),
            priority: 0,
            matchers: vec![Matcher::User {
                user_ids: vec!["user1".to_string()],
            }],
            limiters: vec![LimiterConfig::TokenBucket {
                capacity: 100,
                refill_rate: 10,
            }],
            action: ActionConfig {
                on_exceed: Action::Reject,
                ban: None,
            },
        });
        config
    }

    /// `LimiteronModule::NAME == "limiteron"`.
    #[test]
    fn limiteron_module_meta_name() {
        assert_eq!(LimiteronModule::NAME, "limiteron");
    }

    /// `LimiteronModule` 依赖 `OxcacheModule`(dbnexus 范式——
    /// 缓存经上游 OxcacheModule 注入)
    #[test]
    fn limiteron_module_meta_dependencies_declare_oxcache() {
        let deps = LimiteronModule::dependencies();
        assert_eq!(deps.len(), 1, "single upstream dep: oxcache");
        assert_eq!(deps[0].0, "oxcache");
        assert_eq!(deps[0].1, TypeId::of::<OxcacheModule>());
    }

    /// register `LimiteronModule` + `set_config` +
    /// `build()` + `require::<LimiteronModule>()` returns an `Arc<Governor>`
    /// capability that was constructed from the kit's config.
    /// 带 OxcacheModule 的标准 kit 组装(dbnexus 同款范式)
    fn register_modules(kit: &mut AsyncKit) {
        kit.set_config(OxcacheConfig::default());
        kit.register::<OxcacheModule>()
            .expect("register OxcacheModule");
    }

    #[tokio::test]
    async fn limiteron_module_build_returns_governor_capability() {
        let mut kit = AsyncKit::new();
        register_modules(&mut kit);
        kit.set_config(make_minimal_valid_config());
        kit.register::<LimiteronModule>()
            .expect("register LimiteronModule");
        let kit = kit.build().await.expect("AsyncKit::build");
        let governor: Arc<Governor> = kit
            .require::<LimiteronModule>()
            .expect("require LimiteronModule");
        // Smoke-test the capability type-checks as Arc<Governor> and was
        // actually constructed (register+build+require succeeded).
        let _ = governor;
    }

    /// build reads `FlowControlConfig` from
    /// `kit.config::<FlowControlConfig>()` — verifies the config we set is
    /// honored by the constructed Governor (build returns Err on missing
    /// config).
    #[tokio::test]
    async fn limiteron_module_build_reads_config_from_kit() {
        let mut kit = AsyncKit::new();
        register_modules(&mut kit);
        kit.set_config(make_minimal_valid_config());
        kit.register::<LimiteronModule>()
            .expect("register LimiteronModule");
        let kit = kit.build().await.expect("AsyncKit::build");
        let _governor: Arc<Governor> = kit
            .require::<LimiteronModule>()
            .expect("require LimiteronModule");
        // If build succeeded, config was read (build() returns Err on
        // missing config).
    }

    /// `LimiteronModule::build` returns a
    /// `Pin<Box<dyn Future + Send>>` (async build), not a sync `Result`.
    /// Verified by calling `AsyncAutoBuilder::build` directly on an unbuilt
    /// kit and awaiting the returned future.
    #[tokio::test]
    async fn limiteron_module_build_is_async() {
        let kit = AsyncKit::new();
        kit.set_config(make_minimal_valid_config());
        // Call AsyncAutoBuilder::build directly (bypassing AsyncKit::build's
        // topological pipeline). The return type is Pin<Box<dyn Future + Send>>;
        // awaiting it must yield the capability.
        let fut = <LimiteronModule as AsyncAutoBuilder>::build(&kit);
        let _governor: Arc<Governor> = fut.await.expect("build future resolves");
        // Capability satisfies Send + Sync (AsyncAutoBuilder bound).
        fn assert_send_sync<T: Send + Sync>() {}
        assert_send_sync::<Arc<Governor>>();
    }

    #[cfg(feature = "ban-manager")]
    /// 存储注入钩子:`kit.set_config(LimiteronStorageConfig::new()
    /// .with_ban_storage(recording))` 后,Governor 的封禁操作必须路由到注入
    /// 实例(通过替身计数验证),而非默认 `MemoryBanStorage`。
    #[tokio::test]
    async fn limiteron_module_routes_to_injected_ban_storage() {
        let recording = Arc::new(RecordingBanStorage::new());
        let recording_for_assert = recording.clone();

        let mut kit = AsyncKit::new();
        register_modules(&mut kit);
        kit.set_config(make_minimal_valid_config());
        kit.set_config(
            LimiteronStorageConfig::new()
                .with_ban_storage(recording.clone() as Arc<dyn BanStorage>),
        );
        kit.register::<LimiteronModule>()
            .expect("register LimiteronModule");
        let kit = kit.build().await.expect("AsyncKit::build");
        let governor: Arc<Governor> = kit
            .require::<LimiteronModule>()
            .expect("require LimiteronModule");

        // 触发封禁:create_ban → save + is_banned 由注入替身承接
        let identifier = Identifier::UserId("injected-route-user".to_string());
        governor
            .ban_identifier(&identifier, "test ban", None)
            .await
            .expect("ban via injected storage");

        assert!(
            recording_for_assert.save_count() > 0,
            "the injected BanStorage must be routed by Governor (save)"
        );
        // 解封路径同样路由到注入实例(委托 inner 真实实现,不抛错)
        governor
            .unban_identifier(&identifier)
            .await
            .expect("unban via injected storage");
    }

    #[cfg(feature = "ban-manager")]
    /// 存储注入钩子:未设置 `LimiteronStorageConfig` 时保持默认
    /// `MemoryStorage`/`MemoryBanStorage`(向后兼容),build + 封禁正常。
    #[tokio::test]
    async fn limiteron_module_defaults_to_memory_storage() {
        let mut kit = AsyncKit::new();
        register_modules(&mut kit);
        kit.set_config(make_minimal_valid_config());
        kit.register::<LimiteronModule>()
            .expect("register LimiteronModule");
        let kit = kit.build().await.expect("AsyncKit::build");
        let governor: Arc<Governor> = kit
            .require::<LimiteronModule>()
            .expect("require LimiteronModule");

        let identifier = Identifier::UserId("default-memory-user".to_string());
        governor
            .ban_identifier(&identifier, "test ban", None)
            .await
            .expect("ban with default MemoryBanStorage");
    }

    /// 存储注入钩子:`with_storage` 注入的 `Storage` 同样被路由(通过
    /// `LimiteronStorageConfig` 的 getter 往返验证配置保留)。
    #[test]
    fn limiteron_storage_config_builders_roundtrip() {
        let storage: Arc<dyn Storage> = Arc::new(MemoryStorage::new());
        let ban_storage: Arc<dyn BanStorage> = Arc::new(MemoryBanStorage::new());
        let config = LimiteronStorageConfig::new()
            .with_storage(storage.clone())
            .with_ban_storage(ban_storage.clone());
        assert!(config.storage().is_some());
        assert!(config.ban_storage().is_some());
        let empty = LimiteronStorageConfig::new();
        assert!(empty.storage().is_none());
        assert!(empty.ban_storage().is_none());
    }
    // ========================================================================
    // 健康/生命周期端口 + OxcacheModule 缓存注入
    // ========================================================================

    /// AsyncHealthCheck:健康 Governor → Healthy
    #[tokio::test]
    async fn t617_health_check_reports_healthy() {
        use trait_kit::core::health::AsyncHealthCheck;
        let mut kit = AsyncKit::new();
        register_modules(&mut kit);
        kit.set_config(make_minimal_valid_config());
        kit.register::<LimiteronModule>().unwrap();
        let kit = kit.build().await.unwrap();
        let governor: Arc<Governor> = kit.require::<LimiteronModule>().unwrap();
        let status = <LimiteronModule as AsyncHealthCheck>::check(&governor);
        assert!(
            matches!(status, trait_kit::core::health::HealthStatus::Healthy),
            "the in-memory storage Governor should be Healthy, got: {status:?}"
        );
    }

    /// AsyncLifecycle:on_shutdown 优雅停机 Governor
    #[tokio::test]
    async fn t617_lifecycle_on_shutdown_stops_governor() {
        use trait_kit::core::lifecycle::AsyncLifecycle;
        let mut kit = AsyncKit::new();
        register_modules(&mut kit);
        kit.set_config(make_minimal_valid_config());
        kit.register::<LimiteronModule>().unwrap();
        let kit = kit.build().await.unwrap();
        let governor: Arc<Governor> = kit.require::<LimiteronModule>().unwrap();
        assert!(!governor.is_shutdown());
        <LimiteronModule as AsyncLifecycle>::on_shutdown(&governor).await;
        assert!(
            governor.is_shutdown(),
            "on_shutdown must stop the Governor (background task exit)"
        );
    }

    /// 缓存注入探活:注册 OxcacheModule 后 build 走缓存探活路径(成功不告警不阻断)
    #[tokio::test]
    async fn t617_cache_probe_via_oxcache_module() {
        let mut kit = AsyncKit::new();
        register_modules(&mut kit);
        kit.set_config(make_minimal_valid_config());
        kit.register::<LimiteronModule>().unwrap();
        let kit = kit.build().await.unwrap();
        // 上游缓存能力可取回(拓扑序保证先于 limiteron 构建)
        let cache = kit
            .require::<OxcacheModule>()
            .expect("OxcacheModule capability");
        let health = cache.health_check().await;
        assert!(
            health.is_ok(),
            "the injected cache backend should be healthy"
        );
    }
}