lenso 0.5.30

Rust authoring and Host facade for Lenso applications and Plugins.
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
523
524
525
526
527
528
529
530
531
532
533
534
#![allow(dead_code)]

use std::cell::Cell;

use lenso::prelude::*;
use lenso_app_plan::{
    AppComposition, CapabilityBinding, CapabilityEndpointPlan, CapabilityRequirementPlan,
    PluginInstancePlan,
};
use lenso_kernel::{DeterministicDriver, Kernel, NativeExecutionAdapter, RuntimeDriver};
use lenso_native_adapter::{
    CompleteObjectLifecycle, NativePluginFactory, NativePluginFactoryContext, NativePluginInstance,
    NativePluginRegistry, PluginObject,
};

#[derive(Debug)]
struct ConsumerFactory;

#[derive(Debug)]
struct BoundConsumer {
    health: lenso_kernel::NativeRequestHandle<health::Health>,
}

#[derive(Debug)]
struct BoundConsumerFactory {
    object: PluginObject<BoundConsumer>,
}

#[derive(Debug)]
struct PreparingConsumerFactory {
    fail: bool,
}

#[derive(Debug)]
struct PreparingConsumer {
    fail: bool,
}

impl lenso_kernel::PluginLifecycle for PreparingConsumer {
    fn prepare(&self, context: lenso_kernel::PrepareContext) -> lenso_kernel::PluginFuture {
        let fail = self.fail;
        Box::pin(async move {
            assert!(context.admission().is_closed());
            let health = context.dependencies().one::<health::Health>()?;
            assert_eq!(health.invoke("check", ()).await?, Ok(1));
            if fail {
                return Err(lenso_kernel::RuntimeFailure::PluginFailure {
                    detail: "dependent preparation failed after reading its provider".into(),
                });
            }
            Ok(())
        })
    }
}

impl NativePluginFactory for PreparingConsumerFactory {
    fn package_id(&self) -> &'static str {
        "fixture.preparing-consumer"
    }

    fn instantiate(
        &self,
        _context: NativePluginFactoryContext<'_>,
    ) -> Result<NativePluginInstance, lenso_kernel::RuntimeFailure> {
        Ok(NativePluginInstance::with_lifecycle(
            vec![],
            PreparingConsumer { fail: self.fail },
        ))
    }
}

impl NativePluginFactory for BoundConsumerFactory {
    fn package_id(&self) -> &'static str {
        "fixture.bound-consumer"
    }

    fn runtime_profile(&self) -> &'static str {
        "lenso.native-authoring@2"
    }

    fn instantiate(
        &self,
        context: NativePluginFactoryContext<'_>,
    ) -> Result<NativePluginInstance, lenso_kernel::RuntimeFailure> {
        let lifecycle =
            CompleteObjectLifecycle::new(self.object.clone(), context.configuration(), |context| {
                Box::pin(async move {
                    let health = context.dependencies().requirement("health")?.one()?;
                    Ok(std::rc::Rc::new(BoundConsumer { health }))
                })
            });
        Ok(NativePluginInstance::with_lifecycle(vec![], lifecycle))
    }
}

impl NativePluginFactory for ConsumerFactory {
    fn package_id(&self) -> &'static str {
        "fixture.consumer"
    }

    fn runtime_profile(&self) -> &'static str {
        "lenso.native-authoring@2"
    }

    fn instantiate(
        &self,
        _context: NativePluginFactoryContext<'_>,
    ) -> Result<NativePluginInstance, lenso_kernel::RuntimeFailure> {
        Ok(NativePluginInstance::default())
    }
}

#[derive(Clone, Debug, PluginConfig)]
struct PluginSettings {
    enabled: bool,
}

#[doc(hidden)]
pub mod __lenso_native_support {
    pub use lenso::__private::{
        NativeEventEndpoint, NativePluginInstance, NativeRequestEndpoint, NativeStreamEndpoint,
    };
}

mod health {
    use std::any::Any;

    use lenso::__private::{
        InvocationContext, LocalBoxFuture, NativeRequestEndpoint, NativeRequestFuture,
        RuntimeFailure,
    };
    use lenso_kernel::RequestCapability;

    #[derive(Debug)]
    pub struct HealthEndpoint {
        provider: std::rc::Rc<dyn HealthProvider>,
    }

    impl HealthEndpoint {
        pub(crate) fn new(provider: impl HealthProvider) -> Self {
            Self {
                provider: std::rc::Rc::new(provider),
            }
        }
    }

    impl NativeRequestEndpoint for HealthEndpoint {
        fn capability_id(&self) -> &'static str {
            "example.health@1"
        }

        fn descriptor_version(&self) -> &'static str {
            "1.0.0"
        }

        fn operations(&self) -> &'static [&'static str] {
            &["check"]
        }

        fn invoke(
            &self,
            _operation: &str,
            request: Box<dyn Any>,
            context: InvocationContext,
        ) -> LocalBoxFuture<'static, Result<Result<Box<dyn Any>, Box<dyn Any>>, RuntimeFailure>>
        {
            let Ok(request) = request.downcast::<()>() else {
                return Box::pin(async {
                    Err(RuntimeFailure::ProtocolViolation {
                        capability: "example.health@1",
                    })
                });
            };
            let _: () = *request;
            let invocation = self.provider.check(context, ());
            Box::pin(async move {
                invocation.await.map(|result| {
                    result
                        .map(|value| Box::new(value) as Box<dyn Any>)
                        .map_err(|error| Box::new(error) as Box<dyn Any>)
                })
            })
        }
    }

    #[macro_export]
    macro_rules! __test_lenso_provided_health {
        () => {
            r#"{"capability_id":"example.health@1","descriptor_version":"1.0.0","operations":["check"],"operation_kinds":{},"default_admission":{"queue_capacity":0,"max_concurrency":1},"operation_admissions":{},"event_admission":null,"cross_lane_transfer":false}"#
        };
    }
    pub use crate::__test_lenso_provided_health as __lenso_provided_health;

    #[macro_export]
    macro_rules! __test_lenso_native_endpoints_health {
        ($provider:expr, $support:path) => {{
            use $support as __LensoNativeSupport;
            (
                vec![
                    std::rc::Rc::new($crate::health::HealthEndpoint::new($provider))
                        as std::rc::Rc<dyn __LensoNativeSupport::NativeRequestEndpoint>,
                ],
                Vec::<std::rc::Rc<dyn __LensoNativeSupport::NativeStreamEndpoint>>::new(),
                Vec::<std::rc::Rc<dyn __LensoNativeSupport::NativeEventEndpoint>>::new(),
            )
        }};
    }
    pub use crate::__test_lenso_native_endpoints_health as __lenso_native_endpoints_health;

    #[macro_export]
    macro_rules! __test_lenso_native_lower_health {
        ($plugin:ty, $support:path) => {
            use $support as __LensoNativeSupportHealth;
            impl $crate::health::HealthProvider for $plugin {
                fn check(
                    &self,
                    context: __LensoNativeSupportHealth::InvocationContext,
                    request: (),
                ) -> __LensoNativeSupportHealth::NativeRequestFuture<$crate::health::Health> {
                    let plugin = self.clone();
                    Box::pin(async move { Ok(<$plugin>::check(&plugin, context, request).await) })
                }
            }
        };
    }
    pub use crate::__test_lenso_native_lower_health as __lenso_native_lower_health;

    #[macro_export]
    macro_rules! __test_lenso_native_lower_object_health {
        ($object:ty, $plugin:ty, $support:path) => {
            use $support as __LensoNativeObjectSupportHealth;
            impl $crate::health::HealthProvider for $object {
                fn check(
                    &self,
                    context: __LensoNativeObjectSupportHealth::InvocationContext,
                    request: (),
                ) -> __LensoNativeObjectSupportHealth::NativeRequestFuture<$crate::health::Health>
                {
                    let object = self.clone();
                    Box::pin(async move {
                        let plugin = object.get()?;
                        Ok(<$plugin>::check(plugin.as_ref(), context, request).await)
                    })
                }
            }
        };
    }
    pub use crate::__test_lenso_native_lower_object_health as __lenso_native_lower_object_health;

    #[derive(Debug)]
    pub struct Health;

    impl RequestCapability for Health {
        type Request = ();
        type Response = usize;
        type DomainError = ();

        const ID: &'static str = "example.health@1";
        const DESCRIPTOR_VERSION: &'static str = "1.0.0";
    }

    pub trait HealthProvider: std::fmt::Debug + 'static {
        fn check(&self, context: InvocationContext, request: ()) -> NativeRequestFuture<Health>;
    }
}

#[plugin]
#[derive(Clone, Debug, Default)]
struct StatelessHealthPlugin {
    calls: Cell<usize>,
    stops: std::rc::Rc<Cell<usize>>,
}

#[lenso::plugin_impl]
impl StatelessHealthPlugin {
    #[stop]
    fn stop(&self) {
        self.stops.set(self.stops.get() + 1);
    }
}

#[provides(health::Health)]
impl StatelessHealthPlugin {
    async fn check(
        &self,
        _context: lenso::__private::InvocationContext,
        (): (),
    ) -> Result<usize, ()> {
        let calls = self.calls.get() + 1;
        self.calls.set(calls);
        Ok(calls)
    }
}

#[test]
fn stateless_plugin_derives_empty_configuration() {
    let descriptor: lenso::__private::serde_json::Value =
        lenso::__private::serde_json::from_str(PLUGIN_DESCRIPTOR_JSON)
            .expect("generated Descriptor should be valid JSON");
    assert_eq!(
        descriptor["configuration_schema"],
        lenso::__private::serde_json::json!({
            "$schema": "https://json-schema.org/draft/2020-12/schema",
            "type": "object",
            "additionalProperties": false,
            "required": [],
            "properties": {},
        })
    );
    assert_eq!(descriptor["authoring_version"], 2);
    assert_eq!(descriptor["runtime_profile"], "lenso.native-authoring@2");

    let provider = PluginInstancePlan::new("health", "lenso")
        .with_authoring(2, "lenso.native-authoring@2")
        .with_configuration("{}")
        .with_capability(CapabilityEndpointPlan::new(
            "example.health@1",
            "1.0.0",
            ["check"],
        ));
    let plan = AppComposition::new(vec![provider], vec![])
        .resolve()
        .expect("stateless plan should resolve");
    NativeExecutionAdapter::prepare(&NativePluginRegistry::new().with_linked_factories(), &plan)
        .expect("stateless Plugin should accept empty configuration");
}

#[test]
fn authoring_v2_provider_invokes_the_one_constructed_object() {
    let provider = PluginInstancePlan::new("health", "lenso")
        .with_authoring(2, "lenso.native-authoring@2")
        .with_configuration("{}")
        .with_capability(CapabilityEndpointPlan::new(
            "example.health@1",
            "1.0.0",
            ["check"],
        ));
    let consumer = PluginInstancePlan::new("consumer", "fixture.consumer")
        .with_authoring(2, "lenso.native-authoring@2")
        .with_requirement(
            CapabilityRequirementPlan::one("example.health@1", "1.0.0")
                .with_requirement_id("health"),
        );
    let plan = AppComposition::new(
        vec![consumer, provider],
        vec![
            CapabilityBinding::new("consumer", "example.health@1", "1.0.0", "health")
                .with_requirement_id("health"),
        ],
    )
    .resolve()
    .expect("complete-object provider plan should resolve");
    let driver = DeterministicDriver::new();
    let app = driver
        .run(Kernel::start_native(
            plan,
            driver.clone(),
            NativePluginRegistry::new()
                .with_linked_factories()
                .with_factory(ConsumerFactory),
        ))
        .expect("authoring v2 provider should construct");

    assert_eq!(
        driver
            .run(app.invoke::<health::Health>("consumer", "check", ()))
            .expect("first request should reach the provider"),
        Ok(1)
    );
    assert_eq!(
        driver
            .run(app.invoke::<health::Health>("consumer", "check", ()))
            .expect("second request should reach the provider"),
        Ok(2)
    );
}

#[test]
fn complete_object_consumer_materializes_its_named_provider_during_construction() {
    let provider = PluginInstancePlan::new("health", "lenso")
        .with_authoring(2, "lenso.native-authoring@2")
        .with_capability(CapabilityEndpointPlan::new(
            "example.health@1",
            "1.0.0",
            ["check"],
        ));
    let consumer = PluginInstancePlan::new("consumer", "fixture.bound-consumer")
        .with_authoring(2, "lenso.native-authoring@2")
        .with_requirement(
            CapabilityRequirementPlan::one("example.health@1", "1.0.0")
                .with_requirement_id("health"),
        );
    let plan = AppComposition::new(
        vec![consumer, provider],
        vec![
            CapabilityBinding::new("consumer", "example.health@1", "1.0.0", "health")
                .with_requirement_id("health"),
        ],
    )
    .resolve()
    .expect("named complete-object dependency should resolve");
    let object = PluginObject::empty();
    let driver = DeterministicDriver::new();
    let app = driver
        .run(Kernel::start_native(
            plan,
            driver.clone(),
            NativePluginRegistry::new()
                .with_linked_factories()
                .with_factory(BoundConsumerFactory {
                    object: object.clone(),
                }),
        ))
        .expect("constructor should materialize a dependency while public admission is closed");
    let consumer = object.get().expect("consumer should construct once");
    assert_eq!(
        driver.run(consumer.health.invoke("check", ())).unwrap(),
        Ok(1)
    );
    assert_eq!(
        driver.run(app.shutdown(std::time::Duration::from_secs(1))),
        lenso_kernel::ShutdownOutcome::Clean
    );
}

#[test]
fn legacy_prepare_calls_its_constructed_complete_object_provider() {
    let plan = mixed_authoring_plan();
    let driver = DeterministicDriver::new();
    let app = driver
        .run(Kernel::start_native(
            plan,
            driver.clone(),
            NativePluginRegistry::new()
                .with_linked_factories()
                .with_factory(PreparingConsumerFactory { fail: false }),
        ))
        .expect("legacy prepare must be able to use its already-constructed v2 dependency");
    assert_eq!(
        driver
            .run(app.invoke::<health::Health>("consumer", "check", ()))
            .unwrap(),
        Ok(2)
    );
    assert_eq!(
        driver.run(app.shutdown(std::time::Duration::from_secs(1))),
        lenso_kernel::ShutdownOutcome::Clean
    );
}

fn mixed_authoring_plan() -> lenso_app_plan::ResolvedAppPlan {
    let provider = PluginInstancePlan::new("health", "lenso")
        .with_authoring(2, "lenso.native-authoring@2")
        .with_capability(CapabilityEndpointPlan::new(
            "example.health@1",
            "1.0.0",
            ["check"],
        ));
    let consumer = PluginInstancePlan::new("consumer", "fixture.preparing-consumer")
        .with_requirement(CapabilityRequirementPlan::one("example.health@1", "1.0.0"));
    AppComposition::new(
        vec![consumer, provider],
        vec![CapabilityBinding::new(
            "consumer",
            "example.health@1",
            "1.0.0",
            "health",
        )],
    )
    .resolve()
    .expect("mixed-authoring dependency should resolve")
}

#[test]
fn later_prepare_failure_stops_the_constructed_provider_once_without_ready() {
    let stops = std::rc::Rc::new(Cell::new(0));
    let recorded_stops = stops.clone();
    let registry = NativePluginRegistry::new()
        .with_linked_factories()
        .with_factory_override(lenso_native_adapter::ConfiguredPluginFactory::<
            StatelessHealthPlugin,
            _,
        >::new(move |plugin| {
            plugin.stops = recorded_stops.clone();
            Ok(())
        }))
        .unwrap()
        .with_factory(PreparingConsumerFactory { fail: true });
    let driver = DeterministicDriver::new();
    let diagnostics = lenso_kernel::RuntimeDiagnostics::new();
    let observer = diagnostics.subscribe_all(64).unwrap();
    let result = driver.run(Kernel::start_native_with_diagnostics(
        mixed_authoring_plan(),
        driver.clone(),
        registry,
        diagnostics,
    ));
    assert!(
        matches!(result, Err(lenso_kernel::RuntimeFailure::PluginFailure { detail }) if detail == "dependent preparation failed after reading its provider")
    );
    assert_eq!(stops.get(), 1);
    while let Some(record) = observer.try_recv() {
        assert!(!matches!(
            record.event,
            lenso_kernel::DiagnosticEvent::AppReady
        ));
    }
    driver.run(driver.yield_now());
    assert_eq!(stops.get(), 1);
}

#[test]
fn stateless_plugin_rejects_non_empty_configuration() {
    let provider = PluginInstancePlan::new("health", "lenso")
        .with_authoring(2, "lenso.native-authoring@2")
        .with_configuration(r#"{"unexpected":true}"#)
        .with_capability(CapabilityEndpointPlan::new(
            "example.health@1",
            "1.0.0",
            ["check"],
        ));
    let plan = AppComposition::new(vec![provider], vec![])
        .resolve()
        .expect("composition resolution defers Plugin-owned configuration validation");
    let driver = DeterministicDriver::new();
    let error = driver
        .run(Kernel::start_native(
            plan,
            driver.clone(),
            NativePluginRegistry::new().with_linked_factories(),
        ))
        .expect_err("stateless Plugin must reject non-empty configuration");
    assert!(format!("{error:?}").contains("does not accept configuration"));
}