rutis 0.3.0

Cordis core paradigms in idiomatic Rust: plugin assembly, fiber lifecycle, typed service registry, dependency-driven reload
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
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
use std::future::Future;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex, Weak};
use std::time::{Duration, Instant};

use tokio::runtime::Handle;
use tokio_util::sync::CancellationToken;

use crate::bus::EventBus;
use crate::diagnostics::{
    DependencyDiagnostics, DependencyStatus, PluginDiagnostics, ResolvedDependency,
    RuntimeDiagnostics, ServiceAccess,
};
use crate::effect::{Disposer, Effect, EffectRecord};
use crate::error::{default_sink, CordisError, ErrorSink};
use crate::fiber::{
    join_task, spawn_fiber, DisposeWaitError, FiberInner, FiberState, FiberView, Intent,
    TransitionTask,
};
use crate::key::{InstanceId, ScopeId, TypeKey};
use crate::registry::{Binding, CheckFn, Registry, StoredValue};
use crate::Plugin;
use crate::PluginFactory;

pub(crate) struct Shared {
    pub admission: Mutex<()>,
    pub handle: Handle,
    pub bus: EventBus,
    pub registry: Registry,
    pub error_sink: ErrorSink,
    pub next_plugin_id: AtomicU64,
    pub closing: AtomicBool,
    pub shutdown_task: Mutex<Option<Arc<TransitionTask>>>,
}

pub(crate) struct CtxInner {
    pub(crate) shared: Arc<Shared>,
    pub(crate) parent: Option<Ctx>,
    pub(crate) fiber: Weak<FiberInner>,
    pub(crate) isolate: Option<(TypeKey, ScopeId)>,
    pub(crate) instance: InstanceId,
}

/// 上下文 = `Arc<CtxInner>`(所有权模型:Clone 廉价;isolate/plugin 返回共享内核的新 Ctx)。
#[derive(Clone)]
pub struct Ctx(Arc<CtxInner>);

struct EffectFactoryLease(Arc<FiberInner>);

impl Drop for EffectFactoryLease {
    fn drop(&mut self) {
        self.0.finish_event();
    }
}

impl Ctx {
    pub(crate) fn new_child(
        shared: Arc<Shared>,
        parent: &Ctx,
        fiber: Weak<FiberInner>,
        isolate: Option<(TypeKey, ScopeId)>,
        instance: InstanceId,
    ) -> Self {
        Self(Arc::new(CtxInner {
            shared,
            parent: Some(parent.clone()),
            fiber,
            isolate,
            instance,
        }))
    }

    pub(crate) fn new_root(
        shared: Arc<Shared>,
        fiber: Weak<FiberInner>,
        instance: InstanceId,
    ) -> Self {
        Self(Arc::new(CtxInner {
            shared,
            parent: None,
            fiber,
            isolate: None,
            instance,
        }))
    }

    pub(crate) fn weak_fiber(&self) -> Weak<FiberInner> {
        self.0.fiber.clone()
    }

    pub(crate) fn shared(&self) -> &Arc<Shared> {
        &self.0.shared
    }

    /// Identity of the fiber owning this context. Isolated contexts retain it.
    pub fn instance(&self) -> InstanceId {
        self.0.instance
    }

    /// True only while a live ancestor fiber owns this identity.
    pub(crate) fn in_instance(&self, id: InstanceId) -> bool {
        let mut current = self.0.fiber.upgrade();
        while let Some(fiber) = current {
            if fiber.instance == id {
                return true;
            }
            current = fiber.parent_fiber.as_ref().and_then(Weak::upgrade);
        }
        false
    }

    pub(crate) fn instance_owner(&self, id: InstanceId) -> Option<Arc<FiberInner>> {
        let mut current = self.0.fiber.upgrade();
        while let Some(fiber) = current {
            if fiber.instance == id {
                return Some(fiber);
            }
            current = fiber.parent_fiber.as_ref().and_then(Weak::upgrade);
        }
        None
    }

    pub(crate) fn check_instance(&self, key: &TypeKey) -> Result<(), CordisError> {
        if let Some(id) = key.instance_id() {
            if !self.in_instance(id) {
                return Err(CordisError::InstanceOutOfScope { instance: id });
            }
        }
        Ok(())
    }

    pub(crate) fn in_instance_key(&self, key: &TypeKey) -> bool {
        key.instance_id().is_none_or(|id| self.in_instance(id))
    }

    pub(crate) fn subtree_closing(&self) -> bool {
        let mut current = self.0.fiber.upgrade();
        while let Some(fiber) = current {
            if fiber.closing.load(Ordering::SeqCst) {
                return true;
            }
            current = fiber.parent_fiber.as_ref().and_then(Weak::upgrade);
        }
        false
    }

    pub(crate) fn registration_open(&self) -> Result<(), CordisError> {
        if self.0.shared.closing.load(Ordering::SeqCst) || self.subtree_closing() {
            Err(CordisError::Closed)
        } else {
            Ok(())
        }
    }

    pub fn handle(&self) -> &Handle {
        &self.0.shared.handle
    }

    /// 错误路由:插件运行期(apply 之外)的异步错误经此上报,不崩 root。
    /// 供外部插件在 turn 边界兜底(如 session 落盘失败),与框架内部
    /// 路由同一 sink——可观测,不静默。
    pub fn error_sink(&self) -> ErrorSink {
        self.0.shared.error_sink.clone()
    }

    /// 自动路径:`Handle::try_current()` 失败返回明确错误,绝不隐式建 runtime(D8)。
    pub fn root() -> Result<Ctx, CordisError> {
        let handle = Handle::try_current().map_err(|_| {
            CordisError::PluginFailed(
                "no tokio runtime in scope; construct inside #[tokio::test]/runtime, or use Ctx::root_with(handle)".into(),
            )
        })?;
        Ok(Self::root_with_sink(handle, default_sink()))
    }

    /// 注入构造(优先路径,D8)。
    pub fn root_with(handle: Handle) -> Ctx {
        Self::root_with_sink(handle, default_sink())
    }

    /// 注入构造 + 自定义 ErrorSink。
    pub fn root_with_sink(handle: Handle, sink: ErrorSink) -> Ctx {
        let shared = Arc::new(Shared {
            admission: Mutex::new(()),
            handle,
            bus: EventBus::new(),
            registry: Registry::new(),
            error_sink: sink,
            next_plugin_id: AtomicU64::new(1),
            closing: AtomicBool::new(false),
            shutdown_task: Mutex::new(None),
        });
        let root_fiber = spawn_fiber(&shared, None, None, true);
        root_fiber.ctx.clone()
    }

    /// root fiber 句柄(root dispose 清子树 / root restart,§五 root_restart)。
    /// 最终 shutdown 并释放所有 `FiberView` 后返回 None。
    pub fn root_view(&self) -> Option<FiberView> {
        let mut current = self.clone();
        while let Some(parent) = current.0.parent.clone() {
            current = parent;
        }
        current.0.fiber.upgrade().map(FiberView::from_inner)
    }

    /// Read-only snapshot of live fibers and services; no plugin callback runs.
    pub fn diagnostics(&self) -> RuntimeDiagnostics {
        let mut plugins = Vec::new();
        if let Some(root) = self.root_view() {
            let mut pending = vec![root.inner];
            while let Some(fiber) = pending.pop() {
                pending.extend(
                    fiber
                        .children
                        .lock()
                        .unwrap()
                        .iter()
                        .filter_map(Weak::upgrade),
                );
                let snapshot = fiber.state_snapshot();
                let injects = fiber
                    .declared_injects
                    .iter()
                    .map(|key| {
                        let scope = fiber.ctx.scope_for(key);
                        let status = if !fiber.ctx.in_instance_key(key) {
                            DependencyStatus::OutOfScope
                        } else {
                            self.0
                                .shared
                                .registry
                                .dependency_status(key, scope.as_ref())
                        };
                        DependencyDiagnostics {
                            key: key.clone(),
                            scope: scope.as_ref().map(|s| s.to_string()),
                            status,
                        }
                    })
                    .collect();
                let resolved_dependencies = fiber
                    .last_deps
                    .lock()
                    .unwrap()
                    .as_ref()
                    .map(|deps| {
                        deps.iter()
                            .map(|(provider, generation, key, scope)| ResolvedDependency {
                                key: key.clone(),
                                scope: scope.as_ref().map(|s| s.to_string()),
                                provider: *provider,
                                generation: *generation,
                            })
                            .collect()
                    })
                    .unwrap_or_default();
                plugins.push(PluginDiagnostics {
                    id: fiber.id,
                    instance: fiber.instance,
                    parent: fiber
                        .parent_fiber
                        .as_ref()
                        .and_then(Weak::upgrade)
                        .map(|p| p.id),
                    name: fiber.name.clone(),
                    state: snapshot.state,
                    generation: snapshot.generation,
                    error: snapshot.error,
                    injects,
                    resolved_dependencies,
                    accesses: fiber.accesses.lock().unwrap().clone(),
                });
            }
        }
        RuntimeDiagnostics {
            shutting_down: self.0.shared.closing.load(Ordering::SeqCst),
            plugins,
            bindings: self.0.shared.registry.bindings_snapshot(),
        }
    }

    /// 最终关闭 root。重复或并发调用共享同一完成结果;现有 `dispose`
    /// 仍可 `restart`。关闭会拒绝新注册并等待当前装载、子树与清理完成。
    /// 不协作的代码可能使等待无限延长,可用 `shutdown_with_timeout` 限制等待。
    pub fn shutdown(&self) -> crate::BoxFuture<'static, Result<(), Arc<CordisError>>> {
        let _admission = self.0.shared.admission.lock().unwrap();
        let task = {
            let mut slot = self.0.shared.shutdown_task.lock().unwrap();
            if let Some(task) = slot.as_ref() {
                task.clone()
            } else {
                let task = TransitionTask::new();
                *slot = Some(task.clone());
                self.0.shared.closing.store(true, Ordering::SeqCst);
                if let Some(root) = self.root_view() {
                    root.inner.cancel_current();
                    root.inner.post(Intent::Shutdown(task.clone()));
                } else {
                    task.complete(Some(Arc::new(CordisError::Closed)));
                }
                task
            }
        };
        Box::pin(async move { join_task(&task).await })
    }

    /// 限制等待最终关闭的时间。超时后关闭仍在后台进行,重复调用
    /// `shutdown()` 可继续 join 同一结果。
    pub fn shutdown_with_timeout(
        &self,
        limit: Duration,
    ) -> crate::BoxFuture<'static, Result<(), DisposeWaitError>> {
        let root = self.root_view();
        let pending = self.shutdown();
        let Some(root) = root else {
            // No root view remains only after its driver has exited; the
            // cached shutdown result is already available without a deadline.
            return Box::pin(async move { pending.await.map_err(DisposeWaitError::Failed) });
        };
        Box::pin(async move {
            let started = Instant::now();
            match tokio::time::timeout(limit, pending).await {
                Ok(Ok(())) => Ok(()),
                Ok(Err(error)) => Err(DisposeWaitError::Failed(error)),
                Err(_) => {
                    let snapshot = root.state();
                    Err(DisposeWaitError::TimedOut {
                        plugin_id: root.id,
                        generation: snapshot.generation,
                        state: snapshot.state,
                        elapsed: started.elapsed(),
                    })
                }
            }
        })
    }

    /// 事件总线(全局唯一;事件分发不跨 isolate 过滤,D29)。
    pub fn events(&self) -> &EventBus {
        &self.0.shared.bus
    }

    /// scope 解析:沿 Ctx 父链回溯,取该键最近的 isolate 覆盖(§四:保留父链查找)。
    pub(crate) fn scope_for(&self, key: &TypeKey) -> Option<ScopeId> {
        let mut current = Some(self.clone());
        while let Some(ctx) = current {
            if let Some((k, scope)) = &ctx.0.isolate {
                if k == key {
                    return Some(scope.clone());
                }
            }
            current = ctx.0.parent.clone();
        }
        None
    }

    /// isolate 作用域(支柱 3):按 ServiceKey 隔离,同 label 合并(TS 语义,D21);
    /// 返回的 Ctx 保留原 fiber 所有权(D28)。
    pub fn isolate(&self, key: impl Into<TypeKey>, label: &str) -> Ctx {
        Ctx::new_child(
            self.0.shared.clone(),
            self,
            self.0.fiber.clone(),
            Some((key.into(), Arc::from(label))),
            self.instance(),
        )
    }

    /// 类型键读取(显式定位器,D13):沿父链解析作用域;
    /// provider 非 Active 时不可见,但其子树内自访问除外(清理期自访问,§四)。
    /// 访问方自身失活(Unloading/Disposed)时同样不可见——TS inactive context
    /// 语义(reflect.spec 'service inject leak' 的语言无关内核;provider 子树
    /// 内自访问豁免,与清理期自访问同一条规则)。
    pub fn get<T: Send + Sync + 'static>(&self) -> Option<Arc<T>> {
        self.get_as::<T>(TypeKey::of::<T>())
    }

    /// 带显式 key 的读取(多实例,shaku Keyed 模式)。
    pub fn get_as<T: ?Sized + Send + Sync + 'static>(
        &self,
        key: impl Into<TypeKey>,
    ) -> Option<Arc<T>> {
        let key = key.into();
        let scope = self.scope_for(&key);
        let out_of_scope = !self.in_instance_key(&key);
        let mut found = None;
        let result = (|| {
            if out_of_scope {
                return None;
            }
            let binding = self.0.shared.registry.lookup(&key, scope.as_ref())?;
            let provider = binding.provider.upgrade()?;
            let self_access = self.in_subtree_of(&provider);
            found = Some((binding.provider_id, binding.provider_gen, !self_access));
            if !self_access {
                match self.0.fiber.upgrade() {
                    None => return None,
                    Some(accessor)
                        if matches!(
                            accessor.state(),
                            FiberState::Unloading | FiberState::Disposed
                        ) =>
                    {
                        return None
                    }
                    _ => {}
                }
                let visible = provider.state() == FiberState::Active
                    && !binding.removing.load(std::sync::atomic::Ordering::SeqCst);
                if !visible {
                    return None;
                }
            }
            binding.value.downcast::<T>()
        })();
        if let Some(fiber) = self.0.fiber.upgrade() {
            if fiber.state() == FiberState::Loading {
                let (provider, generation, external) = found
                    .map(|(p, g, x)| (Some(p), Some(g), x))
                    .unwrap_or((None, None, false));
                let access = ServiceAccess {
                    key: key.clone(),
                    scope: scope.as_ref().map(|s| s.to_string()),
                    provider,
                    generation,
                    declared: fiber.declared_injects.contains(&key),
                    external,
                    out_of_scope,
                };
                let mut accesses = fiber.accesses.lock().unwrap();
                if !accesses.contains(&access) {
                    accesses.push(access);
                }
            }
        }
        result
    }

    fn in_subtree_of(&self, other: &Arc<FiberInner>) -> bool {
        let mut current = self.0.fiber.upgrade();
        while let Some(fiber) = current {
            if Arc::ptr_eq(&fiber, other) {
                return true;
            }
            current = fiber.parent_fiber.as_ref().and_then(|w| w.upgrade());
        }
        false
    }

    /// 值语义注册便捷入口(D13)。
    pub fn provide<T: Send + Sync + 'static>(&self, value: T) -> Result<Disposer, CordisError> {
        self.provide_as::<T>(TypeKey::of::<T>(), Arc::new(value))
    }

    /// trait 对象 / 共享实例注册入口。
    pub fn provide_as<T: ?Sized + Send + Sync + 'static>(
        &self,
        key: impl Into<TypeKey>,
        value: Arc<T>,
    ) -> Result<Disposer, CordisError> {
        self.provide_inner(key.into(), value, None)
    }

    /// 带 `check()` 谓词的注册(§四:check 门控保留)。
    pub fn provide_as_with_check<T: ?Sized + Send + Sync + 'static>(
        &self,
        key: impl Into<TypeKey>,
        value: Arc<T>,
        check: impl Fn() -> bool + Send + Sync + 'static,
    ) -> Result<Disposer, CordisError> {
        self.provide_inner(key.into(), value, Some(Arc::new(check)))
    }

    fn provide_inner<T: ?Sized + Send + Sync + 'static>(
        &self,
        key: TypeKey,
        value: Arc<T>,
        check: Option<CheckFn>,
    ) -> Result<Disposer, CordisError> {
        self.check_instance(&key)?;
        if !key.has_type::<T>() {
            return Err(CordisError::Validation {
                issues: vec![format!(
                    "service key {} expects value of type {}, got {}",
                    key.describe(),
                    key.type_name(),
                    std::any::type_name::<T>()
                )],
            });
        }
        let scope = self.scope_for(&key);
        let shared = self.0.shared.clone();
        self.register_internal_effect(move |fiber, provider_gen, state| {
            // Admission and the fiber transition lock cover both the binding and
            // its cleanup record, so shutdown cannot miss a committed service.
            shared.registry.insert_binding(
                key.clone(),
                scope.clone(),
                Binding {
                    value: StoredValue::new(value),
                    provider: Arc::downgrade(fiber),
                    provider_id: fiber.id,
                    provider_gen,
                    check,
                    check_status: Mutex::new(None),
                    removing: AtomicBool::new(false),
                },
            )?;
            fiber
                .provided
                .lock()
                .unwrap()
                .push((key.clone(), scope.clone()));
            let cleanup_shared = shared.clone();
            let provider = Arc::downgrade(fiber);
            let pid = fiber.id;
            let evict_scope = scope.clone();
            let evict_key = key.clone();
            if state == FiberState::Active {
                shared.registry.notify_key_changed(&key);
            }
            Ok(Effect::AsyncDisposer(Box::new(move || {
                let shared = cleanup_shared.clone();
                let provider = provider.clone();
                let scope = evict_scope.clone();
                Box::pin(async move {
                    evict_and_finalize(&shared, provider, pid, provider_gen, evict_key, scope).await
                })
            })))
        })
    }

    /// 注册清理效应(D23):`f` 立即执行,返回的清理在卸载时 LIFO 执行。
    /// fiber 已 Disposed/Unloading 时返回 `InactiveEffect`(§四:重入报错)。
    pub fn effect(&self, f: impl FnOnce() -> Effect) -> Result<Disposer, CordisError> {
        let record = self.register_effect(f)?;
        let handle = self.handle().clone();
        Ok(Disposer::new(Box::new(move || {
            let record = record.clone();
            let handle = handle.clone();
            Box::pin(async move { record.drain(&handle).await })
        })))
    }

    /// Framework-owned registration: admission, state check, insertion and
    /// cleanup ownership commit at one synchronous point. `f` must not call
    /// user code or try to acquire the admission lock again.
    pub(crate) fn register_internal_effect(
        &self,
        f: impl FnOnce(&Arc<FiberInner>, u64, FiberState) -> Result<Effect, CordisError>,
    ) -> Result<Disposer, CordisError> {
        let _admission = self.0.shared.admission.lock().unwrap();
        self.registration_open()?;
        let fiber = self.0.fiber.upgrade().ok_or(CordisError::InactiveEffect)?;
        let tr = fiber.transition.lock().unwrap();
        if matches!(tr.state, FiberState::Unloading | FiberState::Disposed) {
            return Err(CordisError::InactiveEffect);
        }
        let effect = f(&fiber, tr.generation, tr.state)?;
        let record = EffectRecord::new(effect, self.0.fiber.clone());
        fiber.effects.lock().unwrap().push(record.clone());
        drop(tr);
        let handle = self.handle().clone();
        Ok(Disposer::new(Box::new(move || {
            let record = record.clone();
            let handle = handle.clone();
            Box::pin(async move { record.drain(&handle).await })
        })))
    }

    fn register_mount_effect(
        &self,
        child: &Arc<FiberInner>,
        make: impl FnOnce() -> Effect,
    ) -> Result<Arc<EffectRecord>, CordisError> {
        let _admission = self.0.shared.admission.lock().unwrap();
        self.registration_open()?;
        if child.closing.load(Ordering::SeqCst) || !child.alive.load(Ordering::SeqCst) {
            return Err(CordisError::Closed);
        }
        let parent = self.0.fiber.upgrade().ok_or(CordisError::InactiveEffect)?;
        let tr = parent.transition.lock().unwrap();
        if matches!(tr.state, FiberState::Unloading | FiberState::Disposed) {
            return Err(CordisError::InactiveEffect);
        }
        let record = EffectRecord::new(make(), self.0.fiber.clone());
        parent.effects.lock().unwrap().push(record.clone());
        *child.mount.lock().unwrap() = Some(record.clone());
        Ok(record)
    }

    /// `effect` 的内部形态:返回记录本体,供 mount 登记等持有引用。
    /// Disposer 语义不变:drop 不触发清理,fiber 卸载仍兜底(D28)。
    pub(crate) fn register_effect(
        &self,
        f: impl FnOnce() -> Effect,
    ) -> Result<Arc<EffectRecord>, CordisError> {
        let fiber = self.0.fiber.upgrade().ok_or(CordisError::InactiveEffect)?;
        let lease = {
            let _admission = self.0.shared.admission.lock().unwrap();
            let tr = fiber.transition.lock().unwrap();
            if self.0.shared.closing.load(Ordering::SeqCst)
                || (self.subtree_closing() && tr.state != FiberState::Loading)
            {
                return Err(CordisError::Closed);
            }
            if matches!(tr.state, FiberState::Unloading | FiberState::Disposed) {
                return Err(CordisError::InactiveEffect);
            }
            fiber.begin_event();
            EffectFactoryLease(fiber.clone())
        };
        // factory 锁外执行;但"状态检查 + effects 入队"必须在同一临界区
        //(transition → effects 嵌套,锁序无反向):否则检查通过后驱动恰好
        // 卸载取走 effects,新记录漏掉本轮清理而泄漏(评审 P1)
        let record = EffectRecord::new(f(), self.0.fiber.clone());
        let handle = self.handle().clone();
        {
            let tr = fiber.transition.lock().unwrap();
            if matches!(tr.state, FiberState::Unloading | FiberState::Disposed) {
                drop(tr);
                // 生命周期已越过登记点:f() 可能已有副作用(如插入了监听器),
                // 立即排干该记录的清理并返失败
                let sink = self.error_sink();
                let drain_handle = handle.clone();
                handle.spawn(async move {
                    if let Err(e) = record.drain(&drain_handle).await {
                        sink(e);
                    }
                    drop(lease);
                });
                return Err(CordisError::InactiveEffect);
            }
            fiber.effects.lock().unwrap().push(record.clone());
        }
        drop(lease);
        Ok(record)
    }

    /// 装载插件(支柱 1)。返回 FiberView;级联卸载:child dispose 注册为
    /// parent fiber 的 effect(D28:child plugin 自动归 parent fiber 所有)。
    pub fn plugin(&self, p: impl Plugin) -> FiberView {
        let fiber = spawn_fiber(&self.0.shared, Some(self), Some(Arc::new(p)), false);
        self.mount_fiber(fiber)
    }

    /// 工厂模式装载(D32:配置热更新):依赖门控声明从 config 派生,
    /// 每代装载用当前 config 构造实例;返回的 FiberView 可 `update(config)`。
    pub fn plugin_with<C: Send + Sync + 'static>(
        &self,
        factory: impl PluginFactory<C>,
        config: C,
    ) -> FiberView {
        let fiber =
            crate::fiber::spawn_factory_fiber(&self.0.shared, Some(self), factory, config, false);
        self.mount_fiber(fiber)
    }

    /// 工厂模式装载的闭包便捷形态(D32):零依赖声明的单方法工厂。
    /// 需要声明 `injects`/`validate_config` 时实现 [`PluginFactory`]。
    pub fn plugin_from<C: Send + Sync + 'static>(
        &self,
        build: impl Fn(&C) -> Result<Box<dyn Plugin>, CordisError> + Send + Sync + 'static,
        config: C,
    ) -> FiberView {
        struct ClosureFactory<F> {
            build: F,
        }
        impl<C, F> PluginFactory<C> for ClosureFactory<F>
        where
            C: Send + Sync + 'static,
            F: Fn(&C) -> Result<Box<dyn Plugin>, CordisError> + Send + Sync + 'static,
        {
            fn build(&self, config: &C) -> Result<Box<dyn Plugin>, CordisError> {
                (self.build)(config)
            }
        }
        self.plugin_with(ClosureFactory { build }, config)
    }

    /// 装配收尾:级联卸载 effect + 初始装载意图(评审 #10:parent 失活时
    /// 处置子 fiber,不再触发装载)。
    fn mount_fiber(&self, fiber: std::sync::Arc<crate::fiber::FiberInner>) -> FiberView {
        let view = FiberView::from_inner(fiber.clone());
        if !fiber.alive.load(Ordering::SeqCst) {
            return view;
        }
        let child = view.clone();
        let sink = self.error_sink();
        let registered = self.register_mount_effect(&fiber, move || {
            Effect::AsyncDisposer(Box::new(move || {
                let child = child.clone();
                let sink = sink.clone();
                Box::pin(async move {
                    let closing_task = {
                        let _admission = child.inner.ctx.shared().admission.lock().unwrap();
                        child.inner.shutdown_inner.lock().unwrap().clone()
                    };
                    if let Some(task) = closing_task {
                        // Wait for the child's own cleanup, not its public
                        // shutdown result: the latter waits for this mount to
                        // detach and would form a parent/child cycle.
                        let _ = join_task(&task).await;
                        return Ok(());
                    }
                    // 级联 dispose:parent 卸载时子尚未处置,错误仅经 sink 可见;
                    // 子已 Disposed(调用方已从 dispose() 收到同一错误)则不再
                    // 重复上报——0.2.1 子终态退出也会 drain 本记录
                    let delivered = matches!(child.state().state, FiberState::Disposed);
                    if let Err(e) = child.dispose().await {
                        if !delivered {
                            sink(e);
                        }
                    }
                    Ok(())
                })
            }))
        });
        match registered {
            Ok(record) => {
                // Mount ownership was committed under the admission lock.
                drop(record);
                fiber.post(Intent::RefreshDeps);
            }
            Err(_) => {
                // parent 已失活:处置子 fiber,且不再触发装载(评审 #10:
                // 避免 Dispose 之后入队的重载意图无人处理)
                if fiber.closing.load(Ordering::SeqCst) {
                    // The subtree coordinator already owns the terminal intent.
                } else if self.0.shared.closing.load(Ordering::SeqCst) {
                    // Keep the orphan's terminal result available to its
                    // FiberView, even when root shutdown won the mount race.
                    drop(view.shutdown());
                } else {
                    fiber.post(Intent::Dispose);
                }
            }
        }
        view
    }

    /// 当前 fiber 代的取消 token(D27:每代独立 token,卸载第②步取消)。
    pub fn cancellation_token(&self) -> CancellationToken {
        match self.0.fiber.upgrade() {
            Some(fiber) => fiber.current_token(),
            // fiber 已析构 ≡ 代已结束:返回预取消 token,cancelled() 不永等(评审 P2)
            None => {
                let token = CancellationToken::new();
                token.cancel();
                token
            }
        }
    }

    /// 等待当前 fiber 代被取消(协作取消;不观察则 dispose 无限等待,D27 限制)。
    pub fn cancelled(&self) -> impl Future<Output = ()> + Send + 'static {
        let token = self.cancellation_token();
        async move { token.cancelled().await }
    }

    /// 触发依赖重查(check() 谓词结果变更等场景)。
    pub fn refresh(&self) {
        self.0.shared.registry.refresh_all();
    }
}

/// 服务摘除(D14):①捕获本次绑定并标记摘除(严格解析立即失败,绑定保留供
/// 清理期自访问)→ ②预取消 + 可 join 的依赖重查(驱动已退出的消费者任务即刻
/// 完成,不 join 永等,评审 #3)→ ③并发排干后按 Arc 身份最终摘除——
/// 摘除窗口内被新 provide 替换过的槽位不动(TS dispose 同步释放槽位语义,
/// 对拍 fiber.spec inertia lock 2)→ ④摘除 provider 的 `provided` 记账
/// (0.2.1:长寿 root 上反复 provide/dispose 不累积)。
async fn evict_and_finalize(
    shared: &Arc<Shared>,
    provider: Weak<FiberInner>,
    pid: crate::PluginId,
    provider_gen: u64,
    key: TypeKey,
    scope: Option<crate::key::ScopeId>,
) -> Result<(), CordisError> {
    let old = shared
        .registry
        .lookup(&key, scope.as_ref())
        .filter(|b| b.provider_id == pid && b.provider_gen == provider_gen);
    if let Some(binding) = &old {
        binding
            .removing
            .store(true, std::sync::atomic::Ordering::SeqCst);
    }
    let consumers: Vec<Arc<FiberInner>> = shared
        .registry
        .consumers_of(&key, (pid, provider_gen, key.clone(), scope.clone()));
    let mut tasks = Vec::new();
    for fiber in &consumers {
        if fiber.id == pid {
            continue;
        }
        fiber.cancel_current();
        if fiber.closing.load(Ordering::SeqCst) {
            let task = {
                let _admission = shared.admission.lock().unwrap();
                fiber.shutdown_inner.lock().unwrap().clone()
            };
            if let Some(task) = task {
                tasks.push(task);
            }
            continue;
        }
        let task = TransitionTask::new();
        // post_join 返回 false 时任务已在 post 内即刻完成(评审 #3)
        fiber.post_join(task.clone(), Intent::RefreshDepsJoin);
        tasks.push(task);
    }
    // 其它注入该键的 fiber(Pending 者)也重查(不取消:可能是等值合并)
    shared.registry.notify_key_changed(&key);
    for task in tasks {
        let _ = join_task(&task).await;
    }
    // 清理期自访问结束,最终摘除(仅当槽位未被替换)
    if let Some(binding) = old {
        shared
            .registry
            .finalize_binding_if(key.clone(), scope.clone(), &binding);
    }
    // ④摘除 provider 的 provided 记账:仅移除本键本作用域的一条(同键
    // 新 provide 的条目保留;fiber 卸载整表清空后此处自然 no-op)
    if let Some(fiber) = provider.upgrade() {
        let mut provided = fiber.provided.lock().unwrap();
        if let Some(pos) = provided.iter().position(|(k, s)| *k == key && *s == scope) {
            provided.swap_remove(pos);
        }
        // 稀疏即收缩(0.2.5):长寿 root 的瞬态记账容量不随历史 provide 滞留
        //(常驻键使表永不为空,按浪费率收缩)。
        if provided.capacity() > 64 && provided.len() * 4 < provided.capacity() {
            provided.shrink_to_fit();
        }
    }
    Ok(())
}