lenso-native-adapter 0.3.0

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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
//! Native Rust Execution Adapter for statically linked Plugin packages.

mod managed_tasks;

use std::{collections::BTreeMap, rc::Rc};

#[doc(hidden)]
pub use inventory as __inventory;
use lenso_app_plan::{
    ExecutionClassId, ResolvedAppPlan,
    authoring::{HostCatalog, HostDefaultPlugin, HostPluginRelease, HostSlot, PluginDescriptor},
};
use lenso_kernel::{ActivateContext, DeactivateContext, PrepareContext};
pub use lenso_kernel::{CancellationToken, RuntimeFailure};
pub use lenso_native_adapter_macros::{PluginConfig, plugin, provides};
pub use managed_tasks::{ManagedTasks, ManagedTasksError};

/// Optional convention-based lifecycle hooks for a struct-level Plugin.
///
/// Add `#[plugin(lifecycle)]`, implement this trait, and override only the
/// phases that own real work. The generated Adapter lifecycle still connects
/// declared Capability ports before `activate`.
#[allow(async_fn_in_trait)]
pub trait Lifecycle: Clone + 'static {
    async fn prepare(&self, _context: PrepareContext) -> Result<(), RuntimeFailure> {
        Ok(())
    }

    async fn activate(&self, _context: ActivateContext) -> Result<(), RuntimeFailure> {
        Ok(())
    }

    async fn deactivate(&self, _context: DeactivateContext) -> Result<(), RuntimeFailure> {
        Ok(())
    }
}

/// Implementation details referenced by generated Plugin glue.
#[doc(hidden)]
pub mod __private {
    pub use crate::{
        __inventory, Lifecycle, LinkedNativePluginFactory, NativePluginFactory,
        NativePluginFactoryContext, NativePluginInstance, RuntimeFailure,
    };
    pub use futures;
    pub use futures::future::LocalBoxFuture;
    pub use lenso_kernel::{
        ActivateContext, DeactivateContext, InvocationContext, NativeEventEndpoint,
        NativeRequestEndpoint, NativeRequestFuture, NativeStreamEndpoint, NativeStreamSession,
        PluginFuture, PluginLifecycle, PrepareContext,
    };
    pub use serde_json;
}

use lenso_kernel::{
    NativeEndpointSet, NativeEventEndpoint, NativeExecutionAdapter, NativeRequestEndpoint,
    NativeStreamEndpoint, NoopPluginLifecycle, PluginLifecycle, PreparedBinding,
    PreparedEventBinding, PreparedNativeApp, PreparedNativePlugin, PreparedStreamBinding,
};

/// One native Plugin factory contributed to the Host's link-time catalog.
#[derive(Clone, Copy, Debug)]
#[doc(hidden)]
pub struct LinkedNativePluginFactory {
    constructor: fn() -> Rc<dyn NativePluginFactory>,
    descriptor: &'static str,
}

impl LinkedNativePluginFactory {
    /// Creates a link-time catalog record. Intended for generated authoring glue.
    #[doc(hidden)]
    pub const fn new(
        constructor: fn() -> Rc<dyn NativePluginFactory>,
        descriptor: &'static str,
    ) -> Self {
        Self {
            constructor,
            descriptor,
        }
    }
}

inventory::collect!(LinkedNativePluginFactory);

/// Endpoints created for one statically linked Plugin Instance generation.
#[derive(Debug)]
pub struct NativePluginInstance {
    endpoints: NativeEndpointSet,
    lifecycle: Rc<dyn PluginLifecycle>,
}

impl NativePluginInstance {
    /// Creates a generation from its exact declared endpoint set.
    pub fn new(endpoints: Vec<Rc<dyn NativeRequestEndpoint>>) -> Self {
        Self::with_lifecycle(endpoints, NoopPluginLifecycle)
    }

    /// Creates a generation with its exact endpoints and lifecycle Interface.
    pub fn with_lifecycle(
        endpoints: Vec<Rc<dyn NativeRequestEndpoint>>,
        lifecycle: impl PluginLifecycle,
    ) -> Self {
        Self {
            endpoints: NativeEndpointSet::new(endpoints, Vec::new(), Vec::new()),
            lifecycle: Rc::new(lifecycle),
        }
    }

    /// Creates a generation with request and bidirectional stream endpoints.
    pub fn with_endpoints(
        endpoints: Vec<Rc<dyn NativeRequestEndpoint>>,
        stream_endpoints: Vec<Rc<dyn NativeStreamEndpoint>>,
        lifecycle: impl PluginLifecycle,
    ) -> Self {
        Self {
            endpoints: NativeEndpointSet::new(endpoints, stream_endpoints, Vec::new()),
            lifecycle: Rc::new(lifecycle),
        }
    }

    /// Creates a generation containing only bidirectional stream endpoints.
    pub fn with_stream_endpoints(
        stream_endpoints: Vec<Rc<dyn NativeStreamEndpoint>>,
        lifecycle: impl PluginLifecycle,
    ) -> Self {
        Self::with_endpoints(Vec::new(), stream_endpoints, lifecycle)
    }

    /// Creates a generation containing only ephemeral Event endpoints.
    pub fn with_event_endpoints(
        event_endpoints: Vec<Rc<dyn NativeEventEndpoint>>,
        lifecycle: impl PluginLifecycle,
    ) -> Self {
        Self {
            endpoints: NativeEndpointSet::new(Vec::new(), Vec::new(), event_endpoints),
            lifecycle: Rc::new(lifecycle),
        }
    }

    /// Creates a generation with request, stream, and ephemeral Event endpoints.
    pub fn with_all_endpoints(
        endpoints: Vec<Rc<dyn NativeRequestEndpoint>>,
        stream_endpoints: Vec<Rc<dyn NativeStreamEndpoint>>,
        event_endpoints: Vec<Rc<dyn NativeEventEndpoint>>,
        lifecycle: impl PluginLifecycle,
    ) -> Self {
        Self {
            endpoints: NativeEndpointSet::new(endpoints, stream_endpoints, event_endpoints),
            lifecycle: Rc::new(lifecycle),
        }
    }

    /// Returns the lifecycle Interface for this generation.
    pub fn lifecycle(&self) -> Rc<dyn PluginLifecycle> {
        self.lifecycle.clone()
    }

    /// Returns the exact endpoint set created for this generation.
    pub fn endpoints(&self) -> &[Rc<dyn NativeRequestEndpoint>] {
        self.endpoints.request()
    }

    /// Returns the exact bidirectional stream endpoint set created for this generation.
    pub fn stream_endpoints(&self) -> &[Rc<dyn NativeStreamEndpoint>] {
        self.endpoints.stream()
    }

    /// Returns the exact ephemeral Event endpoint set created for this Instance.
    pub fn event_endpoints(&self) -> &[Rc<dyn NativeEventEndpoint>] {
        self.endpoints.event()
    }
}

impl Default for NativePluginInstance {
    fn default() -> Self {
        Self::new(Vec::new())
    }
}

/// Adapter-specific factory for a statically linked native Rust Plugin.
pub trait NativePluginFactory: std::fmt::Debug + 'static {
    /// Package identity selected by the Resolved App Plan.
    fn package_id(&self) -> &'static str;
    /// Exact statically linked Cargo package version.
    fn package_version(&self) -> &'static str {
        ""
    }
    /// Immutable factory identity advertised by the exact Host Build Manifest.
    ///
    /// Plugin-resolved Plans carry this value as their package revision. The
    /// default keeps ordinary statically linked factories unique by package and
    /// version while allowing a factory to override the identity when its build
    /// authority is more specific than a Cargo package version.
    fn factory_identity(&self) -> String {
        let version = self.package_version();
        if version.is_empty() {
            self.package_id().to_owned()
        } else {
            format!("{}@{version}", self.package_id())
        }
    }
    /// Creates a fresh Plugin Instance generation.
    fn instantiate(
        &self,
        context: NativePluginFactoryContext<'_>,
    ) -> Result<NativePluginInstance, RuntimeFailure>;
}

/// Immutable Plan input supplied when a native factory creates one generation.
#[derive(Clone, Copy, Debug)]
pub struct NativePluginFactoryContext<'a> {
    instance_key: &'a str,
    entrypoint: &'a str,
    configuration: &'a str,
}

impl<'a> NativePluginFactoryContext<'a> {
    fn from_plan(instance: &'a lenso_app_plan::PluginInstancePlan) -> Self {
        Self {
            instance_key: instance.instance_key(),
            entrypoint: instance.entrypoint(),
            configuration: instance.configuration(),
        }
    }

    /// Returns the App-local Plugin Instance key.
    pub const fn instance_key(self) -> &'a str {
        self.instance_key
    }

    /// Returns the exact package entrypoint selected before boot.
    pub const fn entrypoint(self) -> &'a str {
        self.entrypoint
    }

    /// Returns opaque Plugin-owned configuration selected before boot.
    pub const fn configuration(self) -> &'a str {
        self.configuration
    }
}

/// Statically linked native Plugin factories available to an App binary.
#[derive(Debug, Default)]
pub struct NativePluginRegistry {
    factories: Vec<Rc<dyn NativePluginFactory>>,
}

type NativeInstances = BTreeMap<String, NativePluginInstance>;
type PreparedGenerations = BTreeMap<String, PreparedNativePlugin>;
type NativeBindings = (
    Vec<PreparedBinding>,
    Vec<PreparedStreamBinding>,
    Vec<PreparedEventBinding>,
);

fn factory_matches(
    factory: &dyn NativePluginFactory,
    expected: &lenso_app_plan::PluginInstancePlan,
) -> bool {
    factory.package_id() == expected.package_id()
        && (expected.package_revision().is_empty()
            || factory.package_version() == expected.package_revision()
            || factory.factory_identity() == expected.package_revision())
}

impl NativePluginRegistry {
    /// Creates an empty linked-factory registry.
    pub fn new() -> Self {
        Self::default()
    }

    /// Adds every Plugin factory contributed to this Host at link time.
    ///
    /// This catalog describes code available in the binary. The Resolved App
    /// Plan remains the sole authority that selects and binds Plugin Instances.
    #[must_use]
    pub fn with_linked_factories(mut self) -> Self {
        self.factories.extend(
            inventory::iter::<LinkedNativePluginFactory>
                .into_iter()
                .map(|linked| (linked.constructor)()),
        );
        self.factories
            .sort_by_key(|factory| factory.factory_identity());
        self
    }

    /// Returns the exact native factories available to this registry.
    pub fn factories(&self) -> impl Iterator<Item = &dyn NativePluginFactory> {
        self.factories.iter().map(std::convert::AsRef::as_ref)
    }

    /// Builds the immutable Host Catalog declared by this binary and Host policy.
    pub fn host_catalog(
        slots: impl IntoIterator<Item = HostSlot>,
        defaults: impl IntoIterator<Item = HostDefaultPlugin>,
    ) -> Result<HostCatalog, RuntimeFailure> {
        let plugins = inventory::iter::<LinkedNativePluginFactory>
            .into_iter()
            .map(|linked| {
                serde_json::from_str::<PluginDescriptor>(linked.descriptor)
                    .map(HostPluginRelease::new)
                    .map_err(|error| RuntimeFailure::InvalidResolvedPlan {
                        detail: format!("invalid linked Plugin Descriptor: {error}"),
                    })
            })
            .collect::<Result<Vec<_>, _>>()?;
        Ok(HostCatalog::new(slots, plugins, defaults))
    }
    /// Adds one statically linked factory.
    #[must_use]
    pub fn with_factory(mut self, factory: impl NativePluginFactory) -> Self {
        self.factories.push(Rc::new(factory));
        self
    }

    fn prepare_instances(
        &self,
        plan: &ResolvedAppPlan,
    ) -> Result<(NativeInstances, PreparedGenerations), RuntimeFailure> {
        let mut instances = BTreeMap::new();
        let mut generations = BTreeMap::new();
        for expected in plan
            .plugin_instances()
            .iter()
            .filter(|instance| instance.execution_class() == &ExecutionClassId::native_rust())
        {
            let matching_factories: Vec<_> = self
                .factories
                .iter()
                .filter(|factory| factory_matches(factory.as_ref(), expected))
                .collect();
            let factory = match matching_factories.as_slice() {
                [] => {
                    return Err(RuntimeFailure::MissingPluginFactory {
                        instance: expected.instance_key().to_owned(),
                        package_id: expected.package_id().to_owned(),
                    });
                }
                [factory] => *factory,
                _ => {
                    return invalid(format!(
                        "multiple statically linked factories declare package `{}`",
                        expected.package_id()
                    ));
                }
            };
            let generation =
                factory.instantiate(NativePluginFactoryContext::from_plan(expected))?;
            generations.insert(
                expected.instance_key().to_owned(),
                PreparedNativePlugin::with_endpoint_set_lifecycle(
                    generation.endpoints.clone(),
                    generation.lifecycle(),
                ),
            );
            if instances
                .insert(expected.instance_key().to_owned(), generation)
                .is_some()
            {
                return invalid(format!(
                    "duplicate Plugin Instance `{}`",
                    expected.instance_key()
                ));
            }
        }
        Ok((instances, generations))
    }
}

impl NativeExecutionAdapter for NativePluginRegistry {
    fn prepare(&self, plan: &ResolvedAppPlan) -> Result<PreparedNativeApp, RuntimeFailure> {
        plan.validate()
            .map_err(|error| RuntimeFailure::InvalidResolvedPlan {
                detail: error.to_string(),
            })?;

        let (instances, generations) = self.prepare_instances(plan)?;
        let (bindings, stream_bindings, event_bindings) = prepare_bindings(plan, &instances)?;
        Ok(PreparedNativeApp::new(bindings, generations)
            .with_stream_bindings(stream_bindings)
            .with_event_bindings(event_bindings))
    }

    fn recreate(
        &self,
        plan: &ResolvedAppPlan,
        instance_key: &str,
    ) -> Result<PreparedNativePlugin, RuntimeFailure> {
        let expected = plan
            .plugin_instances()
            .iter()
            .find(|instance| instance.instance_key() == instance_key)
            .ok_or_else(|| RuntimeFailure::InvalidResolvedPlan {
                detail: format!("unknown Plugin Instance `{instance_key}`"),
            })?;
        let matching_factories: Vec<_> = self
            .factories
            .iter()
            .filter(|factory| factory_matches(factory.as_ref(), expected))
            .collect();
        let factory = match matching_factories.as_slice() {
            [] => {
                return Err(RuntimeFailure::MissingPluginFactory {
                    instance: expected.instance_key().to_owned(),
                    package_id: expected.package_id().to_owned(),
                });
            }
            [factory] => *factory,
            _ => {
                return invalid(format!(
                    "multiple statically linked factories declare package `{}`",
                    expected.package_id()
                ));
            }
        };
        let generation = factory.instantiate(NativePluginFactoryContext::from_plan(expected))?;
        Ok(PreparedNativePlugin::with_endpoint_set_lifecycle(
            generation.endpoints.clone(),
            generation.lifecycle(),
        ))
    }
}

fn prepare_bindings(
    plan: &ResolvedAppPlan,
    instances: &NativeInstances,
) -> Result<NativeBindings, RuntimeFailure> {
    let mut bindings = Vec::new();
    let mut stream_bindings = Vec::new();
    let mut event_bindings = Vec::new();
    for binding in plan.capability_bindings() {
        if !instances.contains_key(binding.provider_instance()) {
            continue;
        }
        let provider = plan
            .plugin_instance(binding.provider_instance())
            .expect("validated binding provider should exist");
        let descriptor = provider
            .provided_capabilities()
            .iter()
            .find(|descriptor| descriptor.capability_id() == binding.capability_id())
            .expect("validated binding descriptor should exist");
        if !descriptor.request_operations().is_empty() {
            let endpoint = instances
                .get(binding.provider_instance())
                .and_then(|instance| {
                    instance.endpoints.request().iter().find(|endpoint| {
                        endpoint.capability_id() == binding.capability_id()
                            && endpoint.descriptor_version() == binding.descriptor_version()
                    })
                })
                .cloned()
                .ok_or_else(|| RuntimeFailure::InvalidResolvedPlan {
                    detail: format!(
                        "Capability `{}` version `{}` has no request endpoint on provider `{}`",
                        binding.capability_id(),
                        binding.descriptor_version(),
                        binding.provider_instance()
                    ),
                })?;
            bindings.push(PreparedBinding::new(
                binding.consumer_instance(),
                binding.provider_instance(),
                endpoint,
            ));
        }
        if !descriptor.stream_operations().is_empty() {
            let endpoint = instances
                .get(binding.provider_instance())
                .and_then(|instance| {
                    instance.endpoints.stream().iter().find(|endpoint| {
                        endpoint.capability_id() == binding.capability_id()
                            && endpoint.descriptor_version() == binding.descriptor_version()
                    })
                })
                .cloned()
                .ok_or_else(|| RuntimeFailure::InvalidResolvedPlan {
                    detail: format!(
                        "Capability `{}` version `{}` has no stream endpoint on provider `{}`",
                        binding.capability_id(),
                        binding.descriptor_version(),
                        binding.provider_instance()
                    ),
                })?;
            stream_bindings.push(PreparedStreamBinding::new(
                binding.consumer_instance(),
                binding.provider_instance(),
                endpoint,
            ));
        }
        if !descriptor.event_operations().is_empty() {
            let endpoint = instances
                .get(binding.provider_instance())
                .and_then(|instance| {
                    instance.endpoints.event().iter().find(|endpoint| {
                        endpoint.capability_id() == binding.capability_id()
                            && endpoint.descriptor_version() == binding.descriptor_version()
                    })
                })
                .cloned()
                .ok_or_else(|| RuntimeFailure::InvalidResolvedPlan {
                    detail: format!(
                        "Capability `{}` version `{}` has no Event endpoint on provider `{}`",
                        binding.capability_id(),
                        binding.descriptor_version(),
                        binding.provider_instance()
                    ),
                })?;
            event_bindings.push(PreparedEventBinding::new(
                binding.consumer_instance(),
                binding.provider_instance(),
                endpoint,
            ));
        }
    }
    Ok((bindings, stream_bindings, event_bindings))
}

fn invalid<T>(detail: String) -> Result<T, RuntimeFailure> {
    Err(RuntimeFailure::InvalidResolvedPlan { detail })
}