lenso-native-adapter 0.3.19

Native Rust Execution Adapter for Lenso vNext.
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
use std::{
    any::{Any, TypeId},
    cell::{Cell, OnceCell},
    fmt,
    future::Future,
    rc::Rc,
    time::Duration,
};

use lenso_kernel::{
    ActivateContext, CancellationToken, DeactivateContext, ManagedTask, ManagedTaskScope,
    PluginDependencies, PluginFuture, PluginLifecycle, ReadinessContext, RuntimeFailure,
};

/// Bounded cooperative context available to complete-object construction and cleanup.
#[derive(Clone, Debug)]
pub struct LifecycleContext {
    cancellation: CancellationToken,
    remaining_budget: Option<Duration>,
    readiness: Option<ReadinessContext>,
    tasks: Option<ManagedTaskScope>,
}

impl LifecycleContext {
    fn constructing(context: &ActivateContext) -> Self {
        Self {
            cancellation: context.cancellation(),
            remaining_budget: None,
            readiness: Some(context.readiness()),
            tasks: Some(context.tasks().clone()),
        }
    }

    fn stopping(context: &DeactivateContext) -> Self {
        Self {
            cancellation: context.cancellation(),
            remaining_budget: context.remaining_budget(),
            readiness: None,
            tasks: None,
        }
    }

    /// Returns the cooperative cancellation signal for this lifecycle phase.
    pub fn cancellation(&self) -> CancellationToken {
        self.cancellation.clone()
    }

    /// Returns the Host cleanup budget remaining when one is configured.
    pub const fn remaining_budget(&self) -> Option<Duration> {
        self.remaining_budget
    }

    /// Returns this generation's Ready Gate and declared dependencies during construction.
    ///
    /// Pass this context to managed work and wait there. Waiting inside the constructor
    /// would prevent the App from completing activation and opening its Ready Gate.
    pub fn readiness(&self) -> Result<ReadinessContext, RuntimeFailure> {
        self.readiness
            .clone()
            .ok_or(RuntimeFailure::AdmissionClosed)
    }

    /// Spawns work in the constructing Plugin generation's existing task scope.
    ///
    /// Cleanup contexts reject new tasks. Retained construction contexts also reject
    /// tasks once the Kernel closes their generation scope.
    pub fn spawn_local(
        &self,
        task: impl Future<Output = ()> + 'static,
    ) -> Result<ManagedTask, crate::ManagedTasksError> {
        self.tasks
            .as_ref()
            .ok_or(crate::ManagedTasksError::Inactive)?
            .spawn_local(Box::pin(task))
            .map_err(crate::ManagedTasksError::Scope)
    }
}

/// Exact inputs admitted before one complete Plugin object is constructed.
#[derive(Clone, Debug)]
pub struct ConstructionContext {
    configuration: String,
    dependencies: PluginDependencies,
    lifecycle: LifecycleContext,
    facilities: crate::NativeFacilities,
}

impl ConstructionContext {
    fn new(
        configuration: String,
        context: &ActivateContext,
        facilities: crate::NativeFacilities,
    ) -> Self {
        Self {
            configuration,
            dependencies: context.dependencies().clone(),
            lifecycle: LifecycleContext::constructing(context),
            facilities,
        }
    }

    /// Returns validated, defaulted Plugin configuration JSON.
    pub fn configuration(&self) -> &str {
        &self.configuration
    }

    /// Returns only the dependencies declared for this Plugin instance.
    pub const fn dependencies(&self) -> &PluginDependencies {
        &self.dependencies
    }

    /// Returns the construction cancellation context.
    pub const fn lifecycle(&self) -> &LifecycleContext {
        &self.lifecycle
    }

    /// Clones one typed owner attachment selected by the Host before activation.
    pub fn facility<T: Any + Clone>(&self, name: &str) -> Result<T, RuntimeFailure> {
        self.facilities.require(name)
    }

    /// Clones an optional typed owner attachment without searching for another resource.
    pub fn optional_facility<T: Any + Clone>(
        &self,
        name: &str,
    ) -> Result<Option<T>, RuntimeFailure> {
        self.facilities.optional(name)
    }
}

/// Future returned by one generated complete-object constructor.
pub type ConstructionFuture<T> =
    futures::future::LocalBoxFuture<'static, Result<Rc<T>, RuntimeFailure>>;

/// Type-erased future contributed by generated constructor glue.
pub type ErasedConstructionFuture =
    futures::future::LocalBoxFuture<'static, Result<Rc<dyn Any>, RuntimeFailure>>;
/// Type-erased stop hook contributed by generated Plugin glue.
pub type ErasedStop = fn(Rc<dyn Any>, LifecycleContext) -> PluginFuture;

/// One link-time constructor and stop pair for a complete-object Plugin type.
#[derive(Clone, Copy)]
pub struct LinkedPluginConstruction {
    plugin_type: fn() -> TypeId,
    custom: bool,
    construct: fn(ConstructionContext) -> ErasedConstructionFuture,
    stop: Option<ErasedStop>,
}

impl LinkedPluginConstruction {
    /// Creates generated link-time construction metadata.
    #[doc(hidden)]
    pub const fn new(
        plugin_type: fn() -> TypeId,
        custom: bool,
        construct: fn(ConstructionContext) -> ErasedConstructionFuture,
        stop: Option<ErasedStop>,
    ) -> Self {
        Self {
            plugin_type,
            custom,
            construct,
            stop,
        }
    }
}

impl fmt::Debug for LinkedPluginConstruction {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("LinkedPluginConstruction")
            .field("custom", &self.custom)
            .finish_non_exhaustive()
    }
}

inventory::collect!(LinkedPluginConstruction);

type Constructor<T> = Rc<dyn Fn(ConstructionContext) -> ConstructionFuture<T>>;
type Initializer<T> = Rc<dyn Fn(&mut T) -> Result<(), RuntimeFailure>>;
type Stopper<T> = Rc<dyn Fn(Rc<T>, LifecycleContext) -> PluginFuture>;

/// Shared reference to the one object owned by a Plugin instance generation.
pub struct PluginObject<T> {
    value: Rc<OnceCell<Rc<T>>>,
}

impl<T> PluginObject<T> {
    /// Creates an inert provider handle before construction begins.
    pub fn empty() -> Self {
        Self {
            value: Rc::new(OnceCell::new()),
        }
    }

    /// Creates a provider handle around an already constructed legacy object.
    pub fn from_value(value: Rc<T>) -> Self {
        let object = Self::empty();
        assert!(
            object.value.set(value).is_ok(),
            "a new Plugin object cell is empty"
        );
        object
    }

    fn install(&self, value: Rc<T>) -> Result<(), RuntimeFailure> {
        self.value
            .set(value)
            .map_err(|_| RuntimeFailure::InvalidResolvedPlan {
                detail: "Plugin object was constructed more than once".to_owned(),
            })
    }

    /// Returns the constructed object or fails closed before readiness.
    pub fn get(&self) -> Result<Rc<T>, RuntimeFailure> {
        self.value
            .get()
            .cloned()
            .ok_or(RuntimeFailure::AdmissionClosed)
    }
}

impl<T> Clone for PluginObject<T> {
    fn clone(&self) -> Self {
        Self {
            value: self.value.clone(),
        }
    }
}

impl<T> fmt::Debug for PluginObject<T> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("PluginObject")
            .field("constructed", &self.value.get().is_some())
            .finish()
    }
}

/// Adapter lifecycle that owns exactly one complete Plugin object.
pub struct CompleteObjectLifecycle<T> {
    object: PluginObject<T>,
    configuration: String,
    facilities: crate::NativeFacilities,
    constructor: Constructor<T>,
    initializer: Option<Initializer<T>>,
    stopper: Option<Stopper<T>>,
    construction_started: Cell<bool>,
    stop_attempted: Cell<bool>,
}

impl<T> CompleteObjectLifecycle<T> {
    /// Creates a lifecycle around generated constructor and optional stop glue.
    pub fn new(
        object: PluginObject<T>,
        configuration: impl Into<String>,
        constructor: impl Fn(ConstructionContext) -> ConstructionFuture<T> + 'static,
    ) -> Self {
        Self {
            object,
            configuration: configuration.into(),
            facilities: crate::NativeFacilities::new(),
            constructor: Rc::new(constructor),
            initializer: None,
            stopper: None,
            construction_started: Cell::new(false),
            stop_attempted: Cell::new(false),
        }
    }

    #[must_use]
    pub fn with_facilities(mut self, facilities: crate::NativeFacilities) -> Self {
        self.facilities = facilities;
        self
    }

    /// Selects the unique generated constructor for this exact Plugin type.
    pub fn linked(
        object: PluginObject<T>,
        configuration: impl Into<String>,
    ) -> Result<Self, RuntimeFailure>
    where
        T: Any,
    {
        let mut defaults = Vec::new();
        let mut customs = Vec::new();
        for linked in inventory::iter::<LinkedPluginConstruction> {
            if (linked.plugin_type)() == TypeId::of::<T>() {
                if linked.custom {
                    customs.push(linked);
                } else {
                    defaults.push(linked);
                }
            }
        }
        let selected = match (customs.as_slice(), defaults.as_slice()) {
            ([custom], _) => *custom,
            ([], [default]) => *default,
            ([], []) => {
                return Err(RuntimeFailure::InvalidResolvedPlan {
                    detail: "Plugin type has no linked constructor".to_owned(),
                });
            }
            (customs, _) if customs.len() > 1 => {
                return Err(RuntimeFailure::InvalidResolvedPlan {
                    detail: "Plugin type has multiple custom constructors".to_owned(),
                });
            }
            _ => {
                return Err(RuntimeFailure::InvalidResolvedPlan {
                    detail: "Plugin type has multiple default constructors".to_owned(),
                });
            }
        };
        let constructor = selected.construct;
        let lifecycle = Self::new(object, configuration, move |context| {
            let erased = constructor(context);
            Box::pin(async move {
                erased
                    .await?
                    .downcast::<T>()
                    .map_err(|_| RuntimeFailure::InvalidResolvedPlan {
                        detail: "linked Plugin constructor returned the wrong type".to_owned(),
                    })
            })
        });
        Ok(if let Some(stop) = selected.stop {
            lifecycle.with_stop(move |object, context| {
                let object: Rc<dyn Any> = object;
                stop(object, context)
            })
        } else {
            lifecycle
        })
    }

    /// Adds the generated stop hook for the same complete object.
    #[must_use]
    pub fn with_stop(
        mut self,
        stopper: impl Fn(Rc<T>, LifecycleContext) -> PluginFuture + 'static,
    ) -> Self {
        self.stopper = Some(Rc::new(stopper));
        self
    }

    /// Applies one Host-private binding to the complete object before it is
    /// published to providers or declared ready.
    #[must_use]
    pub fn with_initialize(
        mut self,
        initialize: impl Fn(&mut T) -> Result<(), RuntimeFailure> + 'static,
    ) -> Self {
        self.initializer = Some(Rc::new(initialize));
        self
    }
}

impl<T> fmt::Debug for CompleteObjectLifecycle<T> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("CompleteObjectLifecycle")
            .field("object", &self.object)
            .field("has_stop", &self.stopper.is_some())
            .finish_non_exhaustive()
    }
}

impl<T: 'static> PluginLifecycle for CompleteObjectLifecycle<T> {
    fn construct(&self, context: ActivateContext) -> PluginFuture {
        if self.construction_started.replace(true) {
            return Box::pin(futures::future::ready(Err(
                RuntimeFailure::InvalidResolvedPlan {
                    detail: "Plugin construction was attempted more than once".to_owned(),
                },
            )));
        }
        let object = self.object.clone();
        let initializer = self.initializer.clone();
        let construction = (self.constructor)(ConstructionContext::new(
            self.configuration.clone(),
            &context,
            self.facilities.clone(),
        ));
        let cancellation = context.cancellation();
        Box::pin(async move {
            if cancellation.is_cancelled() {
                return Err(RuntimeFailure::AdmissionClosed);
            }
            let mut value = construction.await?;
            if let Some(initialize) = initializer {
                let unique =
                    Rc::get_mut(&mut value).ok_or_else(|| RuntimeFailure::InvalidResolvedPlan {
                        detail: "Host binding requires an exclusively constructed Plugin object"
                            .to_owned(),
                    })?;
                initialize(unique)?;
            }
            object.install(value)?;
            if cancellation.is_cancelled() {
                return Err(RuntimeFailure::AdmissionClosed);
            }
            Ok(())
        })
    }

    fn deactivate(&self, context: DeactivateContext) -> PluginFuture {
        if self.stop_attempted.replace(true) {
            return Box::pin(futures::future::ready(Ok(())));
        }
        let Some(stopper) = self.stopper.clone() else {
            return Box::pin(futures::future::ready(Ok(())));
        };
        let Ok(object) = self.object.get() else {
            return Box::pin(futures::future::ready(Ok(())));
        };
        stopper(object, LifecycleContext::stopping(&context))
    }
}