Skip to main content

kardia_core/
plugin.rs

1use std::any::TypeId;
2use std::fmt;
3use std::future::Future;
4use std::sync::Arc;
5use std::sync::atomic::{AtomicU64, Ordering};
6
7use futures::FutureExt;
8use futures::future::BoxFuture;
9use indexmap::IndexMap;
10use serde::de::DeserializeOwned;
11use serde_json::Value;
12
13use crate::config::{ErasedConfig, ValidationError, decode};
14use crate::context::Context;
15use crate::error::Result;
16use crate::key::Key;
17
18/// A statically typed plugin (the paper's component (d, p, e)).
19pub trait Plugin: Send + Sync + 'static {
20    const NAME: &'static str;
21    type Config: DeserializeOwned + Send + Sync + 'static;
22
23    /// Declared dependencies (d), with optional interception metadata.
24    fn inject() -> Inject {
25        Inject::new()
26    }
27
28    /// Declared provisions (p). Metadata only: used for tooling and the
29    /// dependency-cycle check.
30    fn provide() -> Vec<Key> {
31        Vec::new()
32    }
33
34    fn apply(ctx: Context, config: Arc<Self::Config>) -> impl Future<Output = Result<()>> + Send;
35}
36
37/// Declared dependencies: ordered keys, each with optional interception metadata.
38#[derive(Debug, Clone, Default, PartialEq)]
39pub struct Inject {
40    entries: IndexMap<Key, Option<Value>>,
41}
42
43impl Inject {
44    pub fn new() -> Self {
45        Self::default()
46    }
47
48    pub fn with(mut self, key: impl Into<Key>) -> Self {
49        self.entries.insert(key.into(), None);
50        self
51    }
52
53    pub fn with_meta(mut self, key: impl Into<Key>, meta: Value) -> Self {
54        self.entries.insert(key.into(), Some(meta));
55        self
56    }
57
58    pub fn keys(&self) -> impl Iterator<Item = &Key> {
59        self.entries.keys()
60    }
61
62    pub fn contains(&self, key: &str) -> bool {
63        self.entries.contains_key(key)
64    }
65
66    pub fn meta(&self, key: &str) -> Option<&Value> {
67        self.entries.get(key).and_then(Option::as_ref)
68    }
69
70    pub fn len(&self) -> usize {
71        self.entries.len()
72    }
73
74    pub fn is_empty(&self) -> bool {
75        self.entries.is_empty()
76    }
77}
78
79impl<K: Into<Key>, const N: usize> From<[K; N]> for Inject {
80    fn from(keys: [K; N]) -> Self {
81        keys.into_iter().fold(Inject::new(), Inject::with)
82    }
83}
84
85impl<K: Into<Key>> From<Vec<K>> for Inject {
86    fn from(keys: Vec<K>) -> Self {
87        keys.into_iter().fold(Inject::new(), Inject::with)
88    }
89}
90
91/// Identity of a plugin in the registry: the plugin type, or the identity
92/// of a closure-based definition.
93#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
94pub enum RuntimeKey {
95    Type(TypeId),
96    Def(u64),
97}
98
99type ApplyFn = Arc<dyn Fn(Context, ErasedConfig) -> BoxFuture<'static, Result<()>> + Send + Sync>;
100type DecodeFn = Arc<dyn Fn(&Value) -> Result<ErasedConfig, ValidationError> + Send + Sync>;
101
102/// A type-erased plugin definition, as stored in the registry.
103#[derive(Clone)]
104pub struct PluginDef(Arc<PluginDefInner>);
105
106#[derive(Clone)]
107struct PluginDefInner {
108    key: RuntimeKey,
109    name: Option<String>,
110    inject: Inject,
111    provide: Vec<Key>,
112    tags: Vec<&'static str>,
113    decode: DecodeFn,
114    apply: ApplyFn,
115}
116
117static DEF_COUNTER: AtomicU64 = AtomicU64::new(0);
118
119impl PluginDef {
120    /// The definition of a typed plugin. Every call yields the same registry identity.
121    pub fn of<P: Plugin>() -> Self {
122        Self(Arc::new(PluginDefInner {
123            key: RuntimeKey::Type(TypeId::of::<P>()),
124            name: Some(P::NAME.into()),
125            inject: P::inject(),
126            provide: P::provide(),
127            tags: Vec::new(),
128            decode: typed_decoder::<P::Config>(),
129            apply: Arc::new(|ctx, config| {
130                let config = config.downcast::<P::Config>().expect("config decoded by this plugin");
131                P::apply(ctx, config).boxed()
132            }),
133        }))
134    }
135
136    /// A closure plugin receiving its configuration as raw JSON. Every call
137    /// creates a new registry identity.
138    pub fn new<F, Fut>(apply: F) -> Self
139    where
140        F: Fn(Context, Value) -> Fut + Send + Sync + 'static,
141        Fut: Future<Output = Result<()>> + Send + 'static,
142    {
143        Self::erased(
144            Arc::new(|value: &Value| Ok(Arc::new(value.clone()) as ErasedConfig)),
145            Arc::new(move |ctx, config| {
146                let config = config.downcast_ref::<Value>().cloned().unwrap_or_default();
147                apply(ctx, config).boxed()
148            }),
149        )
150    }
151
152    /// A closure plugin with a typed, deserialized configuration.
153    pub fn typed<C, F, Fut>(apply: F) -> Self
154    where
155        C: DeserializeOwned + Send + Sync + 'static,
156        F: Fn(Context, Arc<C>) -> Fut + Send + Sync + 'static,
157        Fut: Future<Output = Result<()>> + Send + 'static,
158    {
159        Self::erased(
160            typed_decoder::<C>(),
161            Arc::new(move |ctx, config| {
162                let config = config.downcast::<C>().expect("config decoded by this plugin");
163                apply(ctx, config).boxed()
164            }),
165        )
166    }
167
168    fn erased(decode: DecodeFn, apply: ApplyFn) -> Self {
169        let key = RuntimeKey::Def(DEF_COUNTER.fetch_add(1, Ordering::Relaxed) + 1);
170        Self(Arc::new(PluginDefInner {
171            key,
172            name: None,
173            inject: Inject::new(),
174            provide: Vec::new(),
175            tags: Vec::new(),
176            decode,
177            apply,
178        }))
179    }
180
181    pub fn name(mut self, name: impl Into<String>) -> Self {
182        Arc::make_mut(&mut self.0).name = Some(name.into());
183        self
184    }
185
186    pub fn inject(mut self, inject: impl Into<Inject>) -> Self {
187        Arc::make_mut(&mut self.0).inject = inject.into();
188        self
189    }
190
191    pub fn provides(mut self, keys: impl IntoIterator<Item = impl Into<Key>>) -> Self {
192        Arc::make_mut(&mut self.0).provide = keys.into_iter().map(Into::into).collect();
193        self
194    }
195
196    /// Marks the definition, so that hosts (e.g. the loader) can recognise it.
197    pub fn tag(mut self, tag: &'static str) -> Self {
198        Arc::make_mut(&mut self.0).tags.push(tag);
199        self
200    }
201
202    /// Validates or transforms the raw configuration before it is decoded.
203    pub fn validate_with(
204        mut self,
205        validate: impl Fn(&Value) -> Result<Value, ValidationError> + Send + Sync + 'static,
206    ) -> Self {
207        let inner = Arc::make_mut(&mut self.0);
208        let decode = inner.decode.clone();
209        inner.decode = Arc::new(move |value| decode(&validate(value)?));
210        self
211    }
212
213    pub fn key(&self) -> RuntimeKey {
214        self.0.key
215    }
216
217    pub fn plugin_name(&self) -> Option<&str> {
218        self.0.name.as_deref()
219    }
220
221    pub fn inject_spec(&self) -> &Inject {
222        &self.0.inject
223    }
224
225    pub fn provide_spec(&self) -> &[Key] {
226        &self.0.provide
227    }
228
229    pub fn has_tag(&self, tag: &str) -> bool {
230        self.0.tags.contains(&tag)
231    }
232
233    pub fn decode(&self, value: &Value) -> Result<ErasedConfig, ValidationError> {
234        (self.0.decode)(value)
235    }
236
237    pub(crate) fn apply(&self, ctx: Context, config: ErasedConfig) -> BoxFuture<'static, Result<()>> {
238        (self.0.apply)(ctx, config)
239    }
240}
241
242impl fmt::Debug for PluginDef {
243    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
244        f.debug_struct("PluginDef").field("key", &self.0.key).field("name", &self.0.name).finish()
245    }
246}
247
248fn typed_decoder<C: DeserializeOwned + Send + Sync + 'static>() -> DecodeFn {
249    Arc::new(|value| decode::<C>(value).map(|config| Arc::new(config) as ErasedConfig))
250}