Skip to main content

kian_plugin/
ctx.rs

1//! `Ctx` typed service registry, `Plugin`, activation, `Disposer`
2//! (DESIGN §6.1, ADR-004).
3//!
4//! Mapping from Cordis (ADR-004):
5//! - **Stable service keys**: a service is registered *by trait-object type*
6//!   (`ctx.provide::<dyn ModelProvider>(impl)` / `ctx.resolve::<dyn
7//!   ModelProvider>`); one implementation per key — a second registration
8//!   is a named error.
9//! - **Reversible registration**: `trait Plugin { fn apply(self, ctx: &mut
10//!   Ctx) -> Result<Disposer, PluginError> }` — everything `apply` installs
11//!   (services, event handlers) is unwound by the returned [`Disposer`].
12//! - **inject → topology**: plugins declare dependencies by name;
13//!   [`PluginSet::activate`] runs them in a deterministic topological order
14//!   (ties broken by declaration order); cycles are a named error.
15//! - **Disposers unwind in reverse order exactly once**, on explicit
16//!   `dispose()` or on drop.
17//!
18//! Static (compile-time) plugins only — [`crate::kian_plugins!`] assembles a
19//! [`PluginSet`]; dynamic loading (dylib/wasm) is deferred.
20
21use std::any::{Any, TypeId};
22use std::cmp::Reverse;
23use std::collections::{BinaryHeap, HashMap, HashSet};
24use std::fmt;
25use std::sync::{Arc, RwLock};
26
27use crate::dispatch::Events;
28
29/// Marker bound for services stored in [`Ctx`]: any `'static` `Send + Sync`
30/// type (trait object or concrete) can occupy a service key.
31pub trait Service: Any + Send + Sync {}
32
33impl<T: ?Sized + Any + Send + Sync> Service for T {}
34
35/// Named errors for the plugin subsystem (acceptance criteria).
36#[derive(Debug, thiserror::Error)]
37pub enum PluginError {
38    /// A second registration for an already-occupied stable service key.
39    #[error(
40        "service key `{key}` is already provided (service keys are stable: one impl per trait)"
41    )]
42    DuplicateService { key: &'static str },
43
44    /// Two plugins registered under the same name.
45    #[error("plugin name `{name}` is registered twice")]
46    DuplicatePlugin { name: String },
47
48    /// A plugin declared a dependency that no registered plugin carries.
49    #[error("plugin `{plugin}` declares unknown dependency `{dependency}`")]
50    UnknownDependency { plugin: String, dependency: String },
51
52    /// The declared dependency graph contains a cycle; `cycle` lists its
53    /// members in walk order.
54    #[error("dependency cycle detected among plugins: [{}]", cycle.join(" -> "))]
55    DependencyCycle { cycle: Vec<String> },
56
57    /// A plugin's `apply` failed; already-activated plugins were unwound in
58    /// reverse activation order.
59    #[error("plugin `{plugin}` failed to apply: {source}")]
60    Apply {
61        plugin: String,
62        source: Box<dyn std::error::Error + Send + Sync>,
63    },
64}
65
66/// Reversible side effect (Cordis disposer). Callbacks run in reverse
67/// insertion order, exactly once — on explicit [`Disposer::dispose`] or on
68/// drop. Registration and disposal are paired.
69#[must_use = "a Disposer holds teardown; dropping it runs teardown immediately — dispose explicitly or pass it on"]
70pub struct Disposer {
71    callbacks: Vec<Box<dyn FnOnce() + Send + Sync>>,
72}
73
74impl Disposer {
75    pub const fn new() -> Self {
76        Self {
77            callbacks: Vec::new(),
78        }
79    }
80
81    /// A disposer from a single teardown callback.
82    pub fn from_fn<F: FnOnce() + Send + Sync + 'static>(callback: F) -> Self {
83        Self {
84            callbacks: vec![Box::new(callback)],
85        }
86    }
87
88    /// Appends `later`'s callbacks after `self`'s; disposal unwinds in
89    /// reverse insertion order, so `later`'s teardown runs first — matching
90    /// reverse activation order when later-registered disposers are merged in.
91    pub fn extend(mut self, mut later: Disposer) -> Self {
92        self.callbacks.extend(std::mem::take(&mut later.callbacks));
93        self
94    }
95
96    pub fn is_empty(&self) -> bool {
97        self.callbacks.is_empty()
98    }
99
100    /// Runs all callbacks now, in reverse insertion order, exactly once.
101    pub fn dispose(mut self) {
102        for callback in self.callbacks.drain(..).rev() {
103            callback();
104        }
105    }
106}
107
108impl Default for Disposer {
109    fn default() -> Self {
110        Self::new()
111    }
112}
113
114impl fmt::Debug for Disposer {
115    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
116        f.debug_struct("Disposer")
117            .field("callbacks", &self.callbacks.len())
118            .finish()
119    }
120}
121
122impl Drop for Disposer {
123    fn drop(&mut self) {
124        // `dispose()` drains first, so an explicitly disposed Disposer drops
125        // empty — callbacks can never run twice.
126        for callback in self.callbacks.drain(..).rev() {
127            callback();
128        }
129    }
130}
131
132pub(crate) struct Inner {
133    pub(crate) services: RwLock<HashMap<TypeId, Slot>>,
134    pub(crate) events: Events,
135}
136
137pub(crate) struct Slot {
138    // Concrete type is `Arc<S>` for the key's `S`: trait-object-to-`dyn Any`
139    // coercion needs a sized inner, hence the double `Arc`.
140    value: Arc<dyn Any + Send + Sync>,
141}
142
143/// Typed service registry (Cordis `ctx` container). Service keys are stable:
144/// the key is the [`TypeId`] of the trait-object type (`dyn Greeter`) or of a
145/// concrete type; values are `Arc<dyn Any + Send + Sync>` wrappers around
146/// `Arc<S>`.
147///
148/// Also carries the typed-event handler registry (see [`crate::dispatch`]):
149/// `ctx.on*` registers handlers, `ctx.emit`/`parallel`/`serial`/`waterfall`/
150/// `bail` dispatch them.
151pub struct Ctx {
152    pub(crate) inner: Arc<Inner>,
153}
154
155impl Ctx {
156    pub fn new() -> Self {
157        Self {
158            inner: Arc::new(Inner {
159                services: RwLock::new(HashMap::new()),
160                events: Events::default(),
161            }),
162        }
163    }
164
165    /// Registers `svc` under the stable service key `S` and returns the
166    /// [`Disposer`] that removes exactly this registration.
167    pub fn provide<S: ?Sized + Service>(&self, svc: Arc<S>) -> Result<Disposer, PluginError> {
168        let key = TypeId::of::<S>();
169        // The slot stores `Arc<S>` itself as the concrete type behind
170        // `dyn Any` (trait-object-to-`dyn Any` coercion needs a sized
171        // value, and `Arc<S>` is sized even for `S:?Sized`).
172        let slot_value: Arc<dyn Any + Send + Sync> = Arc::new(svc);
173        {
174            let mut services = self
175                .inner
176                .services
177                .write()
178                .expect("kian-plugin: services lock poisoned");
179            if services.contains_key(&key) {
180                return Err(PluginError::DuplicateService {
181                    key: std::any::type_name::<S>(),
182                });
183            }
184            services.insert(
185                key,
186                Slot {
187                    value: slot_value.clone(),
188                },
189            );
190        }
191        let inner = Arc::clone(&self.inner);
192        Ok(Disposer::from_fn(move || {
193            let mut services = inner
194                .services
195                .write()
196                .expect("kian-plugin: services lock poisoned");
197            // Remove only if the slot is still ours — a re-registered
198            // service must survive a stale disposer.
199            let ours = services
200                .get(&key)
201                .is_some_and(|slot| Arc::ptr_eq(&slot.value, &slot_value));
202            if ours {
203                services.remove(&key);
204            }
205        }))
206    }
207
208    /// Looks the service for key `S` up by trait type; `None` if absent.
209    pub fn resolve<S: ?Sized + Service>(&self) -> Option<Arc<S>> {
210        let services = self
211            .inner
212            .services
213            .read()
214            .expect("kian-plugin: services lock poisoned");
215        let slot = services.get(&TypeId::of::<S>())?;
216        let erased = Arc::clone(&slot.value);
217        drop(services);
218        erased
219            .downcast::<Arc<S>>()
220            .ok()
221            .map(|wrapped| (*wrapped).clone())
222    }
223
224    /// Whether a service currently occupies the key `S`.
225    pub fn contains_service<S: ?Sized + Service>(&self) -> bool {
226        self.inner
227            .services
228            .read()
229            .expect("kian-plugin: services lock poisoned")
230            .contains_key(&TypeId::of::<S>())
231    }
232}
233
234impl Default for Ctx {
235    fn default() -> Self {
236        Self::new()
237    }
238}
239
240/// A statically-registered capability unit (ADR-004). `apply` installs
241/// services and event handlers into [`Ctx`] and returns the [`Disposer`]
242/// that unwinds them; dependencies are declared by plugin *name* and
243/// resolved by topological activation (the static equivalent of Cordis
244/// `inject`).
245pub trait Plugin: Send + Sync + 'static {
246    /// Unique plugin name (the dependency-graph node).
247    fn name(&self) -> String;
248
249    /// Names of plugins that must be activated before this one.
250    fn dependencies(&self) -> Vec<String> {
251        Vec::new()
252    }
253
254    fn apply(self, ctx: &mut Ctx) -> Result<Disposer, PluginError>;
255}
256
257type ApplyFn = Box<dyn FnOnce(&mut Ctx) -> Result<Disposer, PluginError> + Send>;
258
259struct PluginEntry {
260    name: String,
261    dependencies: Vec<String>,
262    // `Option` so activation (which consumes the entry's apply closure)
263    // can run exactly once even on error paths.
264    apply: Option<ApplyFn>,
265}
266
267/// The compile-time plugin set assembled by [`crate::kian_plugins!`].
268/// Activation order is derived from declared dependencies, not listing
269/// order.
270pub struct PluginSet {
271    entries: Vec<PluginEntry>,
272}
273
274impl PluginSet {
275    pub const fn new() -> Self {
276        Self {
277            entries: Vec::new(),
278        }
279    }
280
281    /// Registers a plugin (name and dependencies are read immediately).
282    pub fn register<P: Plugin>(&mut self, plugin: P) {
283        let name = plugin.name();
284        let dependencies = plugin.dependencies();
285        self.entries.push(PluginEntry {
286            name,
287            dependencies,
288            apply: Some(Box::new(move |ctx| plugin.apply(ctx))),
289        });
290    }
291
292    /// Registered plugin names, in declaration order.
293    pub fn names(&self) -> Vec<String> {
294        self.entries.iter().map(|e| e.name.clone()).collect()
295    }
296
297    /// Activates every plugin in deterministic topological order. On the
298    /// first failure, already-activated plugins are unwound in reverse
299    /// activation order exactly once and the error is returned. On success,
300    /// the returned [`Disposer`] unwinds the whole set in reverse activation
301    /// order.
302    pub fn activate(mut self, ctx: &mut Ctx) -> Result<Disposer, PluginError> {
303        let order = topological_order(&self.entries)?;
304        let mut activated: Vec<Disposer> = Vec::with_capacity(order.len());
305        for index in order {
306            let entry = &mut self.entries[index];
307            let apply = entry
308                .apply
309                .take()
310                .expect("a plugin entry is activated exactly once");
311            match apply(ctx) {
312                Ok(disposer) => activated.push(disposer),
313                Err(source) => {
314                    // Unwind exactly what was activated, reverse order, once.
315                    for disposer in activated.drain(..).rev() {
316                        disposer.dispose();
317                    }
318                    return Err(PluginError::Apply {
319                        plugin: entry.name.clone(),
320                        source: Box::new(source),
321                    });
322                }
323            }
324        }
325        Ok(activated
326            .into_iter()
327            .fold(Disposer::new(), |earlier, later| earlier.extend(later)))
328    }
329}
330
331impl Default for PluginSet {
332    fn default() -> Self {
333        Self::new()
334    }
335}
336
337/// Deterministic topological order over the declared dependency graph:
338/// Kahn's algorithm with declaration-index tiebreaking (the smallest
339/// original index among ready nodes wins). Rejects duplicate names, unknown
340/// dependencies, and cycles (with the cycle's members named).
341fn topological_order(entries: &[PluginEntry]) -> Result<Vec<usize>, PluginError> {
342    let mut index_by_name: HashMap<&str, usize> = HashMap::new();
343    for (index, entry) in entries.iter().enumerate() {
344        if index_by_name.insert(entry.name.as_str(), index).is_some() {
345            return Err(PluginError::DuplicatePlugin {
346                name: entry.name.clone(),
347            });
348        }
349    }
350
351    for entry in entries {
352        for dep in &entry.dependencies {
353            if !index_by_name.contains_key(dep.as_str()) {
354                return Err(PluginError::UnknownDependency {
355                    plugin: entry.name.clone(),
356                    dependency: dep.clone(),
357                });
358            }
359        }
360    }
361
362    let mut unresolved: Vec<usize> = entries.iter().map(|e| e.dependencies.len()).collect();
363    let mut dependents: Vec<Vec<usize>> = vec![Vec::new(); entries.len()];
364    for (index, entry) in entries.iter().enumerate() {
365        for dep in &entry.dependencies {
366            dependents[index_by_name[dep.as_str()]].push(index);
367        }
368    }
369
370    let mut ready: BinaryHeap<Reverse<usize>> = unresolved
371        .iter()
372        .enumerate()
373        .filter(|(_, count)| **count == 0)
374        .map(|(index, _)| Reverse(index))
375        .collect();
376    let mut order = Vec::with_capacity(entries.len());
377    while let Some(Reverse(current)) = ready.pop() {
378        order.push(current);
379        for &dependent in &dependents[current] {
380            unresolved[dependent] -= 1;
381            if unresolved[dependent] == 0 {
382                ready.push(Reverse(dependent));
383            }
384        }
385    }
386
387    if order.len() == entries.len() {
388        return Ok(order);
389    }
390
391    // Everything not in `order` is stuck behind a cycle. Walk dependencies
392    // among the stuck set until a node repeats; the path from the first
393    // occurrence of the repeated node is the cycle.
394    let processed: HashSet<usize> = order.iter().copied().collect();
395    let mut current = (0..entries.len())
396        .find(|i| !processed.contains(i))
397        .expect("unprocessed nodes exist whenever a cycle exists");
398    let mut seen: HashMap<usize, usize> = HashMap::new();
399    let mut path: Vec<usize> = Vec::new();
400    loop {
401        if let Some(position) = seen.get(&current) {
402            let cycle = path[*position..]
403                .iter()
404                .map(|&i| entries[i].name.clone())
405                .collect();
406            return Err(PluginError::DependencyCycle { cycle });
407        }
408        seen.insert(current, path.len());
409        path.push(current);
410        current = entries[current]
411            .dependencies
412            .iter()
413            .map(|dep| index_by_name[dep.as_str()])
414            .find(|dep_index| !processed.contains(dep_index))
415            .expect("every unprocessed node has an unprocessed dependency");
416    }
417}
418
419#[cfg(test)]
420mod tests {
421    use super::*;
422    use std::sync::Mutex;
423
424    trait Greeter: Service {
425        fn greet(&self) -> String;
426    }
427
428    struct EngGreeter;
429
430    impl Greeter for EngGreeter {
431        fn greet(&self) -> String {
432            "hello".into()
433        }
434    }
435
436    #[allow(dead_code)] // only the key's TypeId is exercised, not the methods
437    trait Counter: Service {
438        fn bump(&self);
439    }
440
441    /// Test plugin recording apply/dispose into a shared log; optionally
442    /// provides `dyn Greeter`, and can fail to exercise partial unwinding.
443    struct TestPlugin {
444        name: String,
445        deps: Vec<String>,
446        fail: bool,
447        provide_greeter: bool,
448        log: Arc<Mutex<Vec<String>>>,
449    }
450
451    impl Plugin for TestPlugin {
452        fn name(&self) -> String {
453            self.name.clone()
454        }
455
456        fn dependencies(&self) -> Vec<String> {
457            self.deps.clone()
458        }
459
460        fn apply(self, ctx: &mut Ctx) -> Result<Disposer, PluginError> {
461            self.log
462                .lock()
463                .unwrap()
464                .push(format!("apply:{}", self.name));
465            if self.fail {
466                return Err(PluginError::Apply {
467                    plugin: self.name,
468                    source: "boom".into(),
469                });
470            }
471            // Registrations must survive `apply` returning: the service
472            // disposer is merged into the plugin's own disposer, not dropped.
473            let mut disposer = Disposer::new();
474            if self.provide_greeter {
475                disposer = disposer.extend(ctx.provide::<dyn Greeter>(Arc::new(EngGreeter))?);
476            }
477            let name = self.name.clone();
478            let log = Arc::clone(&self.log);
479            Ok(disposer.extend(Disposer::from_fn(move || {
480                log.lock().unwrap().push(format!("dispose:{name}"));
481            })))
482        }
483    }
484
485    fn plugin(name: &str, deps: &[&str], log: &Arc<Mutex<Vec<String>>>) -> TestPlugin {
486        TestPlugin {
487            name: name.to_string(),
488            deps: deps.iter().map(|d| d.to_string()).collect(),
489            fail: false,
490            provide_greeter: false,
491            log: Arc::clone(log),
492        }
493    }
494
495    #[test]
496    fn register_and_resolve_service_by_trait_type() {
497        let ctx = Ctx::new();
498        let _keep = ctx
499            .provide::<dyn Greeter>(Arc::new(EngGreeter))
500            .expect("first registration succeeds");
501        assert!(ctx.contains_service::<dyn Greeter>());
502        assert!(!ctx.contains_service::<dyn Counter>());
503
504        let svc = ctx
505            .resolve::<dyn Greeter>()
506            .expect("registered service resolves by trait type");
507        assert_eq!(svc.greet(), "hello");
508
509        assert!(
510            ctx.resolve::<dyn Counter>().is_none(),
511            "an unregistered trait type must not resolve"
512        );
513    }
514
515    #[test]
516    fn duplicate_service_registration_is_rejected() {
517        let ctx = Ctx::new();
518        let _first = ctx.provide::<dyn Greeter>(Arc::new(EngGreeter)).unwrap();
519        let err = ctx
520            .provide::<dyn Greeter>(Arc::new(EngGreeter))
521            .expect_err("a stable service key may only be provided once");
522        assert!(matches!(err, PluginError::DuplicateService { .. }));
523        // The original registration survives the rejected duplicate.
524        assert!(ctx.resolve::<dyn Greeter>().is_some());
525    }
526
527    #[test]
528    fn service_disposer_removes_only_its_own_registration() {
529        let ctx = Ctx::new();
530        let disposer = ctx.provide::<dyn Greeter>(Arc::new(EngGreeter)).unwrap();
531        assert!(ctx.resolve::<dyn Greeter>().is_some());
532        disposer.dispose();
533        assert!(ctx.resolve::<dyn Greeter>().is_none());
534    }
535
536    #[test]
537    fn disposer_unwinds_in_reverse_order_exactly_once() {
538        let log = Arc::new(Mutex::new(Vec::new()));
539        let step = |tag: &'static str, log: &Arc<Mutex<Vec<String>>>| {
540            let log = Arc::clone(log);
541            Disposer::from_fn(move || log.lock().unwrap().push(format!("dispose:{tag}")))
542        };
543        let disposer = step("a", &log)
544            .extend(step("b", &log))
545            .extend(step("c", &log));
546        disposer.dispose();
547        assert_eq!(
548            *log.lock().unwrap(),
549            vec![
550                "dispose:c".to_string(),
551                "dispose:b".to_string(),
552                "dispose:a".to_string()
553            ],
554            "teardown must unwind in reverse insertion order"
555        );
556
557        assert!(Disposer::new().is_empty());
558        assert!(!Disposer::from_fn(|| ()).is_empty());
559    }
560
561    #[test]
562    fn disposer_runs_each_callback_exactly_once_on_drop() {
563        let counts = Arc::new(Mutex::new([0u32; 3]));
564        let mut disposer = Disposer::new();
565        for index in 0..3 {
566            let counts = Arc::clone(&counts);
567            disposer = disposer.extend(Disposer::from_fn(move || {
568                counts.lock().unwrap()[index] += 1;
569            }));
570        }
571        drop(disposer);
572        assert_eq!(*counts.lock().unwrap(), [1, 1, 1]);
573    }
574
575    #[test]
576    fn activation_is_topological_and_deterministic() {
577        let log = Arc::new(Mutex::new(Vec::new()));
578        for _round in 0..2 {
579            let mut set = PluginSet::new();
580            set.register(plugin("p0", &["p2"], &log));
581            set.register(plugin("p1", &[], &log));
582            set.register(plugin("p2", &[], &log));
583
584            let mut ctx = Ctx::new();
585            let disposer = set.activate(&mut ctx).expect("activation succeeds");
586            // Ready set is {p1, p2}; declaration-index tiebreak picks p1
587            // first, then p2 unblocks p0 — not declaration order.
588            assert_eq!(
589                *log.lock().unwrap(),
590                [
591                    "apply:p1".to_string(),
592                    "apply:p2".to_string(),
593                    "apply:p0".to_string()
594                ],
595                "round {_round}: order must be topological and stable"
596            );
597            log.lock().unwrap().clear();
598
599            disposer.dispose();
600            // Disposal unwinds in reverse activation order.
601            assert_eq!(
602                *log.lock().unwrap(),
603                [
604                    "dispose:p0".to_string(),
605                    "dispose:p2".to_string(),
606                    "dispose:p1".to_string()
607                ],
608                "round {_round}: disposal must unwind in reverse activation order"
609            );
610            log.lock().unwrap().clear();
611        }
612    }
613
614    #[test]
615    fn dependency_cycle_is_rejected_with_named_error() {
616        let log = Arc::new(Mutex::new(Vec::new()));
617        let mut set = PluginSet::new();
618        set.register(plugin("a", &["b"], &log));
619        set.register(plugin("b", &["c"], &log));
620        set.register(plugin("c", &["a"], &log));
621        // d hangs off the cycle without being part of it.
622        set.register(plugin("d", &["a"], &log));
623
624        let mut ctx = Ctx::new();
625        let err = set.activate(&mut ctx).expect_err("cycle must be rejected");
626        match err {
627            PluginError::DependencyCycle { cycle } => {
628                let joined = cycle.join(",");
629                for member in ["a", "b", "c"] {
630                    assert!(
631                        joined.contains(member),
632                        "cycle must name {member}: {cycle:?}"
633                    );
634                }
635                assert!(
636                    !joined.contains('d'),
637                    "cycle must not list non-member d: {cycle:?}"
638                );
639            }
640            other => panic!("expected DependencyCycle, got: {other}"),
641        }
642        // Nothing was activated, so nothing was disposed either.
643        assert!(log.lock().unwrap().is_empty());
644    }
645
646    #[test]
647    fn unknown_dependency_is_rejected_with_named_error() {
648        let log = Arc::new(Mutex::new(Vec::new()));
649        let mut set = PluginSet::new();
650        set.register(plugin("a", &["ghost"], &log));
651        let mut ctx = Ctx::new();
652        let err = set
653            .activate(&mut ctx)
654            .expect_err("unknown dependency must be rejected");
655        match err {
656            PluginError::UnknownDependency { plugin, dependency } => {
657                assert_eq!(plugin, "a");
658                assert_eq!(dependency, "ghost");
659            }
660            other => panic!("expected UnknownDependency, got: {other}"),
661        }
662    }
663
664    #[test]
665    fn duplicate_plugin_name_is_rejected() {
666        let log = Arc::new(Mutex::new(Vec::new()));
667        let mut set = PluginSet::new();
668        set.register(plugin("twin", &[], &log));
669        set.register(plugin("twin", &[], &log));
670        let mut ctx = Ctx::new();
671        assert!(matches!(
672            set.activate(&mut ctx),
673            Err(PluginError::DuplicatePlugin { .. })
674        ));
675    }
676
677    #[test]
678    fn partial_activation_failure_unwinds_in_reverse_exactly_once() {
679        let log = Arc::new(Mutex::new(Vec::new()));
680        let mut set = PluginSet::new();
681        set.register(plugin("p1", &[], &log));
682        set.register(plugin("p2", &["p1"], &log));
683        let mut failing = plugin("pfail", &["p2"], &log);
684        failing.fail = true;
685        set.register(failing);
686
687        let mut ctx = Ctx::new();
688        let err = set
689            .activate(&mut ctx)
690            .expect_err("failing plugin aborts activation");
691        match err {
692            PluginError::Apply { plugin, .. } => assert_eq!(plugin, "pfail"),
693            other => panic!("expected Apply, got: {other}"),
694        }
695        assert_eq!(
696            *log.lock().unwrap(),
697            [
698                "apply:p1".to_string(),
699                "apply:p2".to_string(),
700                "apply:pfail".to_string(),
701                "dispose:p2".to_string(),
702                "dispose:p1".to_string(),
703            ],
704            "activated plugins must unwind in reverse order, exactly once"
705        );
706    }
707
708    #[test]
709    fn kian_plugins_macro_registers_and_activates() {
710        let log = Arc::new(Mutex::new(Vec::new()));
711        let mut greeter_provider = plugin("gp", &[], &log);
712        greeter_provider.provide_greeter = true;
713        let consumer = plugin("consumer", &["gp"], &log);
714
715        let set = crate::kian_plugins![greeter_provider, consumer];
716        assert_eq!(set.names(), vec!["gp".to_string(), "consumer".to_string()]);
717
718        let mut ctx = Ctx::new();
719        let disposer = set.activate(&mut ctx).expect("activation succeeds");
720        assert_eq!(
721            *log.lock().unwrap(),
722            ["apply:gp".to_string(), "apply:consumer".to_string()]
723        );
724        assert!(ctx.resolve::<dyn Greeter>().is_some());
725
726        disposer.dispose();
727        assert!(
728            ctx.resolve::<dyn Greeter>().is_none(),
729            "service disposers wired into the plugin disposer must unwind services"
730        );
731        assert_eq!(
732            *log.lock().unwrap(),
733            [
734                "apply:gp".to_string(),
735                "apply:consumer".to_string(),
736                "dispose:consumer".to_string(),
737                "dispose:gp".to_string(),
738            ]
739        );
740    }
741}