Skip to main content

kardia_core/
registry.rs

1use std::collections::HashSet;
2use std::future::Future;
3use std::sync::{Arc, Weak};
4
5use serde::Serialize;
6use serde_json::Value;
7
8use crate::context::Context;
9use crate::effect::{Disposer, EffectCell};
10use crate::error::{Error, KardiaError, Result};
11use crate::events::{PluginInserted, PluginRemoved, Replaced};
12use crate::fiber::Fiber;
13use crate::key::FiberId;
14use crate::logger::Level;
15use crate::plugin::{Inject, Plugin, PluginDef, RuntimeKey};
16use crate::root::RootInner;
17use crate::scope::{Scope, ScopeKind};
18use crate::state::{FiberData, RuntimeData, State, Target};
19
20impl Context {
21    /// Instantiates a typed plugin as a child fiber of the current fiber.
22    pub fn plugin<P: Plugin>(&self, config: P::Config) -> Result<Fiber>
23    where
24        P::Config: Serialize,
25    {
26        self.plugin_def(&PluginDef::of::<P>(), serde_json::to_value(config)?)
27    }
28
29    /// Instantiates a typed plugin from a raw configuration value.
30    pub fn plugin_value<P: Plugin>(&self, config: Value) -> Result<Fiber> {
31        self.plugin_def(&PluginDef::of::<P>(), config)
32    }
33
34    /// Instantiates a plugin definition (O-Insert). The instantiation is an
35    /// effect of the current fiber, whose inverse retires the new fiber.
36    pub fn plugin_def(&self, def: &PluginDef, config: Value) -> Result<Fiber> {
37        Ok(self.root.run(|st| st.insert_fiber(&self.root, self, def, config))?)
38    }
39
40    /// Instantiates an anonymous closure plugin with the given dependencies.
41    pub fn inject<F, Fut>(&self, inject: impl Into<Inject>, apply: F) -> Result<Fiber>
42    where
43        F: Fn(Context) -> Fut + Send + Sync + 'static,
44        Fut: Future<Output = Result<()>> + Send + 'static,
45    {
46        let def = PluginDef::new(move |ctx, _| apply(ctx)).inject(inject);
47        self.plugin_def(&def, Value::Null)
48    }
49
50    pub fn registry(&self) -> Registry {
51        Registry { ctx: self.clone() }
52    }
53}
54
55/// Registry operations of a root.
56pub struct Registry {
57    ctx: Context,
58}
59
60impl Registry {
61    /// Number of plugins with at least one fiber.
62    pub fn size(&self) -> usize {
63        self.ctx.root.with(|st| st.runtimes.len())
64    }
65
66    /// Keys of the registered plugins, in registration order.
67    pub fn keys(&self) -> Vec<RuntimeKey> {
68        self.ctx.root.with(|st| st.runtimes.keys().copied().collect())
69    }
70
71    /// The registry key a plugin resolves to, following replacements.
72    pub fn get(&self, def: &PluginDef) -> Option<RuntimeKey> {
73        self.ctx.root.with(|st| {
74            let (key, _) = st.forward(def);
75            st.runtimes.contains_key(&key).then_some(key)
76        })
77    }
78
79    pub fn has(&self, def: &PluginDef) -> bool {
80        self.get(def).is_some()
81    }
82
83    /// The fibers of a plugin, in instantiation order.
84    pub fn fibers(&self, def: &PluginDef) -> Vec<Fiber> {
85        let ids = self.ctx.root.with(|st| {
86            let (key, _) = st.forward(def);
87            st.runtimes.get(&key).map(|runtime| runtime.fibers.clone()).unwrap_or_default()
88        });
89        ids.into_iter().map(|id| Fiber::of(&self.ctx.root, id)).collect()
90    }
91
92    /// Swaps the implementation behind every fiber of `old` in place, and
93    /// forwards future instantiations of `old` to `new`. Returns the moved
94    /// fibers; each reloads with the new implementation.
95    pub fn replace(&self, old: &PluginDef, new: &PluginDef) -> Vec<Fiber> {
96        let ids = self.ctx.root.run(|st| st.replace(old, new));
97        ids.into_iter().map(|id| Fiber::of(&self.ctx.root, id)).collect()
98    }
99}
100
101impl State {
102    pub(crate) fn forward(&self, def: &PluginDef) -> (RuntimeKey, PluginDef) {
103        let mut def = def.clone();
104        while let Some(next) = self.aliases.get(&def.key()) {
105            def = next.clone();
106        }
107        (def.key(), def)
108    }
109
110    pub(crate) fn insert_fiber(
111        &mut self,
112        root: &Arc<RootInner>,
113        parent: &Context,
114        def: &PluginDef,
115        config: Value,
116    ) -> Result<Fiber, KardiaError> {
117        self.assert_active(parent.fiber)?;
118        let (key, def) = self.forward(def);
119        self.runtimes.entry(key).or_insert_with(|| RuntimeData { def: def.clone(), fibers: Vec::new() });
120        let id = self.next_fiber_id();
121        let scope = Scope::child(&parent.scope, ScopeKind::Fiber(id));
122        let inject = def.inject_spec().clone();
123        let keys: Vec<_> = inject.keys().cloned().collect();
124        self.fibers.insert(id, FiberData::new(parent.fiber, scope.clone(), Some(key), inject, config));
125        let event_scope = scope.clone();
126        self.emit(move |root| PluginInserted { fiber: Fiber::from_parts(root, id, event_scope) });
127        for name in &keys {
128            self.check_impl(id, name);
129        }
130        self.runtimes[&key].fibers.push(id);
131        self.refresh(id);
132        let cell = EffectCell::new("ctx.plugin()", parent.fiber);
133        cell.push_disposer(retire(Arc::downgrade(root), id));
134        self.attach_effect(parent.fiber, &cell);
135        self.fibers.get_mut(&id).expect("just inserted").retire = Some(cell);
136        self.warn_cycle(id);
137        Ok(Fiber::from_parts(root, id, scope))
138    }
139
140    /// The synchronous part of O-Retire.
141    fn retire_fiber(&mut self, id: FiberId) {
142        let Some(fiber) = self.fibers.get_mut(&id) else { return };
143        if fiber.removed {
144            return;
145        }
146        fiber.removed = true;
147        let recovery = fiber.recovery.take();
148        let (scope, runtime) = (fiber.scope.clone(), fiber.runtime);
149        self.drop_later(recovery);
150        self.emit(move |root| PluginRemoved { fiber: Fiber::from_parts(root, id, scope) });
151        if let Some(key) = runtime
152            && let Some(runtime) = self.runtimes.get_mut(&key)
153        {
154            runtime.fibers.retain(|fiber| *fiber != id);
155            if runtime.fibers.is_empty()
156                && let Some(runtime) = self.runtimes.shift_remove(&key)
157            {
158                self.drop_later(runtime.def);
159            }
160        }
161        // A retired provider's bindings stop occupying their realms at once,
162        // so a successor can provide there while old consumers still drain
163        // (they read through their committed views).
164        let provisions = self.fibers[&id].provisions.clone();
165        for impl_id in provisions {
166            self.unbind(impl_id);
167        }
168        self.set_target(id, Target::Inactive);
169        self.collect_removed(id);
170    }
171
172    fn replace(&mut self, old: &PluginDef, new: &PluginDef) -> Vec<FiberId> {
173        let (old_key, _) = self.forward(old);
174        let key = new.key();
175        // `new` is an implementation of its own again
176        self.aliases.remove(&key);
177        let fibers = match self.runtimes.get(&old_key) {
178            Some(runtime) => runtime.fibers.clone(),
179            None => Vec::new(),
180        };
181        if old_key != key {
182            self.runtimes.shift_remove(&old_key);
183            self.aliases.insert(old_key, new.clone());
184        }
185        if fibers.is_empty() {
186            return fibers;
187        }
188        self.runtimes.entry(key).or_insert_with(|| RuntimeData { def: new.clone(), fibers: Vec::new() });
189        for id in &fibers {
190            self.replace_fiber(*id, key, new.inject_spec().clone());
191        }
192        fibers
193    }
194
195    fn replace_fiber(&mut self, id: FiberId, key: RuntimeKey, inject: Inject) {
196        let fiber = self.fibers.get_mut(&id).expect("registered fiber exists");
197        if fiber.runtime != Some(key) {
198            fiber.runtime = Some(key);
199            self.runtimes[&key].fibers.push(id);
200        }
201        let fiber = self.fibers.get_mut(&id).expect("registered fiber exists");
202        let keys: Vec<_> = inject.keys().cloned().collect();
203        fiber.inject = inject;
204        fiber.resolved.clear();
205        let scope = fiber.scope.clone();
206        self.emit(move |root| Replaced { fiber: Fiber::from_parts(root, id, scope) });
207        for name in &keys {
208            self.check_impl(id, name);
209        }
210        let fiber = self.fibers.get_mut(&id).expect("registered fiber exists");
211        fiber.error = None;
212        fiber.revision += 1;
213        self.refresh(id);
214    }
215
216    /// Warns when the declared provisions and dependencies of live fibers
217    /// form a cycle through the new fiber (paper ยง6.5); such a fiber stays pending.
218    fn warn_cycle(&mut self, start: FiberId) {
219        let mut path = vec![start];
220        let mut visited = HashSet::new();
221        if self.find_cycle(start, start, &mut path, &mut visited) {
222            let names: Vec<String> = path.iter().map(|id| self.fiber_name(*id)).collect();
223            let error = Error::msg(format!("dependency cycle: {}", names.join(" -> ")));
224            self.log(start, Level::Warn, error);
225        }
226    }
227
228    /// Depth-first search along "depends on a declared provider" edges.
229    fn find_cycle(&self, start: FiberId, at: FiberId, path: &mut Vec<FiberId>, visited: &mut HashSet<FiberId>) -> bool {
230        let consumer = &self.fibers[&at];
231        for key in consumer.inject.keys() {
232            let realm = self.realm_of(&consumer.scope, key);
233            for runtime in self.runtimes.values() {
234                if !runtime.def.provide_spec().contains(key) {
235                    continue;
236                }
237                for provider in &runtime.fibers {
238                    let Some(data) = self.fiber(*provider) else { continue };
239                    if data.removed || self.realm_of(&data.scope, key) != realm {
240                        continue;
241                    }
242                    if *provider == start {
243                        path.push(start);
244                        return true;
245                    }
246                    if visited.insert(*provider) {
247                        path.push(*provider);
248                        if self.find_cycle(start, *provider, path, visited) {
249                            return true;
250                        }
251                        path.pop();
252                    }
253                }
254            }
255        }
256        false
257    }
258}
259
260/// The inverse of an instantiation: retire the fiber, then wait for its
261/// transitions to settle.
262fn retire(root: Weak<RootInner>, id: FiberId) -> Disposer {
263    Disposer::future(move || {
264        let root = root.upgrade();
265        if let Some(root) = &root {
266            root.run(|st| st.retire_fiber(id));
267        }
268        async move {
269            let Some(root) = root else { return };
270            root.wait_until(|st| st.fiber(id).is_none_or(|fiber| !fiber.inertia)).await;
271            root.run(|st| st.collect_removed(id));
272        }
273    })
274}