Skip to main content

kardia_core/
fiber.rs

1use std::fmt;
2use std::sync::Arc;
3
4use futures::FutureExt;
5use futures::future::BoxFuture;
6use serde_json::Value;
7
8use crate::context::Context;
9use crate::effect::{Disposal, EffectHandle, EffectMeta};
10use crate::error::{Error, Interrupted, Result};
11use crate::events::ConfigCommitted;
12use crate::key::FiberId;
13use crate::lifecycle::resolve_config;
14use crate::plugin::{Inject, PluginDef, RuntimeKey};
15use crate::root::RootInner;
16use crate::scope::Scope;
17use crate::state::{FiberData, Target};
18
19/// The paper's θ.
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
21pub enum FiberState {
22    /// Waiting for its dependencies.
23    Pending,
24    Loading,
25    Active,
26    Unloading,
27    /// Its last load failed; only `update` and `registry().replace` recover it.
28    Failed,
29    Disposed,
30}
31
32/// Resolves when a fiber has no transition in flight, with its failure if any.
33pub type Settle = BoxFuture<'static, Result<()>>;
34
35/// A handle to a fiber (one instantiation of a plugin).
36#[derive(Clone)]
37pub struct Fiber {
38    pub(crate) ctx: Context,
39}
40
41impl Fiber {
42    pub(crate) fn from_parts(root: &Arc<RootInner>, id: FiberId, scope: Arc<Scope>) -> Self {
43        Self { ctx: Context { root: root.clone(), fiber: id, scope } }
44    }
45
46    pub(crate) fn of(root: &Arc<RootInner>, id: FiberId) -> Self {
47        let scope = root.with(|st| st.fiber(id).map(|fiber| fiber.scope.clone()));
48        Self::from_parts(root, id, scope.unwrap_or_else(Scope::root))
49    }
50
51    pub fn id(&self) -> FiberId {
52        self.ctx.fiber
53    }
54
55    /// The fiber's own context.
56    pub fn context(&self) -> &Context {
57        &self.ctx
58    }
59
60    pub fn state(&self) -> FiberState {
61        self.read(|fiber| fiber.state).unwrap_or(FiberState::Disposed)
62    }
63
64    /// Whether the fiber has been retired (its instantiation reverted).
65    pub fn is_removed(&self) -> bool {
66        self.read(|fiber| fiber.removed).unwrap_or(true)
67    }
68
69    pub fn is_root(&self) -> bool {
70        self.ctx.fiber == FiberId::ROOT
71    }
72
73    /// The source configuration, as last given.
74    pub fn config(&self) -> Value {
75        self.read(|fiber| fiber.config.clone()).unwrap_or_default()
76    }
77
78    pub fn inject(&self) -> Inject {
79        self.read(|fiber| fiber.inject.clone()).unwrap_or_default()
80    }
81
82    pub fn error(&self) -> Option<Error> {
83        self.read(|fiber| fiber.error.clone()).flatten()
84    }
85
86    pub fn runtime(&self) -> Option<RuntimeKey> {
87        self.read(|fiber| fiber.runtime).flatten()
88    }
89
90    /// The plugin definition currently behind the fiber.
91    pub fn def(&self) -> Option<PluginDef> {
92        self.ctx.root.with(|st| st.def_of(self.ctx.fiber))
93    }
94
95    /// The plugin name of the fiber or its nearest named ancestor.
96    pub fn name(&self) -> String {
97        self.ctx.root.with(|st| st.fiber_name(self.ctx.fiber))
98    }
99
100    /// The fiber this one was instantiated from (the root is its own parent).
101    pub fn parent(&self) -> Option<Fiber> {
102        let parent = self.read(|fiber| fiber.parent)?;
103        Some(Fiber::of(&self.ctx.root, parent))
104    }
105
106    /// The effect on the parent that instantiated this fiber.
107    pub fn effect_handle(&self) -> Option<EffectHandle> {
108        let cell = self.read(|fiber| fiber.retire.clone()).flatten()?;
109        Some(EffectHandle::new(&self.ctx.root, cell))
110    }
111
112    /// The effects currently registered on the fiber, in insertion order.
113    pub fn effects(&self) -> Vec<EffectMeta> {
114        let cells = self.read(|fiber| fiber.disposables.values().cloned().collect::<Vec<_>>()).unwrap_or_default();
115        cells.iter().map(|cell| cell.meta()).collect()
116    }
117
118    /// Number of effects in the fiber's accumulator.
119    pub fn effect_count(&self) -> usize {
120        self.read(|fiber| fiber.disposables.len()).unwrap_or(0)
121    }
122
123    /// Waits until no transition is in flight; fails with the fiber's error.
124    pub fn settled(&self) -> Settle {
125        let root = self.ctx.root.clone();
126        let id = self.ctx.fiber;
127        async move {
128            root.wait_until(|st| st.fiber(id).is_none_or(|fiber| !fiber.inertia)).await;
129            match root.with(|st| st.fiber(id).and_then(|fiber| fiber.error.clone())) {
130                Some(error) => Err(error),
131                None => Ok(()),
132            }
133        }
134        .boxed()
135    }
136
137    /// Retires the fiber. For the root fiber this restarts it, reverting
138    /// everything registered on it.
139    pub fn dispose(&self) -> Disposal {
140        if self.is_root() {
141            let restart = self.restart();
142            return Disposal::spawn(async move {
143                let _ = restart.await;
144                Ok(())
145            });
146        }
147        match self.effect_handle() {
148            Some(handle) => handle.dispose(),
149            None => Disposal::ready(Ok(())),
150        }
151    }
152
153    /// Bumps the revision, so the fiber unloads and loads again. A failed
154    /// fiber stays failed: only `update` and `registry().replace` clear its error.
155    pub fn restart(&self) -> Settle {
156        let id = self.ctx.fiber;
157        let started = self.ctx.root.run(|st| {
158            st.assert_active(id)?;
159            st.fiber_mut(id).expect("active fiber exists").revision += 1;
160            st.refresh(id);
161            Ok::<_, Error>(())
162        });
163        match started {
164            Ok(()) => self.settled(),
165            Err(error) => futures::future::ready(Err(error)).boxed(),
166        }
167    }
168
169    /// Fails the fiber from outside, as a load returning `error` would: it
170    /// unloads, reverting its effects and provisions, and settles as
171    /// `Failed` until `update` or `registry().replace` clears the error. A
172    /// load in flight finishes first. A fiber that has already failed keeps
173    /// its first error.
174    pub fn fail(&self, error: Error) -> Settle {
175        let id = self.ctx.fiber;
176        let started = self.ctx.root.run(|st| {
177            st.assert_active(id)?;
178            st.fail(id, error);
179            Ok::<_, Error>(())
180        });
181        match started {
182            Ok(()) => self.settled(),
183            Err(error) => futures::future::ready(Err(error)).boxed(),
184        }
185    }
186
187    /// Replaces the configuration. If the fiber is loaded, the new config is
188    /// validated first (a rejected config leaves the running instance
189    /// untouched) and offered to the fiber's update hooks; if none takes it
190    /// over, the fiber restarts.
191    pub fn update(&self, config: Value) -> Result<Settle> {
192        self.update_with(config, false)
193    }
194
195    /// Like [`Fiber::update`]; `no_save` suppresses [`ConfigCommitted`].
196    pub fn update_with(&self, config: Value, no_save: bool) -> Result<Settle> {
197        let id = self.ctx.fiber;
198        let (loaded, def, hooks) = self.ctx.root.with(|st| {
199            st.assert_active(id)?;
200            let fiber = st.fiber(id).expect("active fiber exists");
201            let hooks: Vec<_> = fiber.update_hooks.values().cloned().collect();
202            Ok::<_, Error>((fiber.target != Target::Inactive, st.def_of(id), hooks))
203        })?;
204        let resolved = match (&def, loaded) {
205            (Some(def), true) => Some(resolve_config(self, def, config.clone())?),
206            _ => None,
207        };
208        if !no_save {
209            self.ctx.root().emit(&ConfigCommitted { fiber: self.clone(), config: config.clone() });
210        }
211        self.ctx.root.run(|st| {
212            if let Some(fiber) = st.fiber_mut(id) {
213                fiber.config = config;
214                fiber.error = None;
215            }
216        });
217        if let Some(resolved) = resolved
218            && let Some(handled) = hooks.iter().find_map(|hook| hook.offer(&resolved))
219        {
220            return Ok(handled);
221        }
222        Ok(self.restart())
223    }
224
225    fn read<T>(&self, f: impl FnOnce(&FiberData) -> T) -> Option<T> {
226        self.ctx.root.with(|st| st.fiber(self.ctx.fiber).map(f))
227    }
228}
229
230impl PartialEq for Fiber {
231    fn eq(&self, other: &Self) -> bool {
232        self.ctx.same_root(&other.ctx) && self.ctx.fiber == other.ctx.fiber
233    }
234}
235
236impl Eq for Fiber {}
237
238impl fmt::Debug for Fiber {
239    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
240        write!(f, "Fiber({:?}, {:?})", self.ctx.fiber, self.state())
241    }
242}
243
244impl From<&Fiber> for EffectHandle {
245    fn from(fiber: &Fiber) -> Self {
246        fiber.effect_handle().expect("only a live, non-root fiber has an instantiation effect")
247    }
248}
249
250impl From<Fiber> for EffectHandle {
251    fn from(fiber: Fiber) -> Self {
252        (&fiber).into()
253    }
254}
255
256impl Context {
257    /// The fiber this context belongs to.
258    pub fn fiber(&self) -> Fiber {
259        Fiber::of(&self.root, self.fiber)
260    }
261
262    /// An iteration boundary of the fiber's own load (L-Divert): fails with
263    /// [`Interrupted`] once the load has been superseded or the fiber retired.
264    /// Returning that error from `apply` is not a failure.
265    pub fn checkpoint(&self) -> Result<(), Interrupted> {
266        self.root.with(|st| match st.fiber(self.fiber) {
267            Some(fiber) if !fiber.removed && fiber.episode.as_ref().is_none_or(|episode| *episode == fiber.target) => {
268                Ok(())
269            }
270            _ => Err(Interrupted),
271        })
272    }
273}