lenso-plugin-authoring 0.2.0

Runtime-neutral typed dependency and error primitives for Lenso 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
//! Runtime-neutral authoring primitives for strongly typed Lenso Plugins.

use std::{cell::OnceCell, marker::PhantomData, ops::Deref, rc::Rc};

/// Generated exact Capability reference used by dependency declarations.
///
/// It carries contract identity and a zero-sized client type witness without
/// selecting a provider or depending on any product-specific SDK.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct CapabilityReference<C> {
    capability_id: &'static str,
    descriptor_version: &'static str,
    descriptor_digest: &'static str,
    client: PhantomData<fn() -> C>,
}

impl<C> CapabilityReference<C> {
    #[must_use]
    pub const fn new(
        capability_id: &'static str,
        descriptor_version: &'static str,
        descriptor_digest: &'static str,
    ) -> Self {
        Self {
            capability_id,
            descriptor_version,
            descriptor_digest,
            client: PhantomData,
        }
    }

    #[must_use]
    pub const fn capability_id(&self) -> &'static str {
        self.capability_id
    }

    #[must_use]
    pub const fn descriptor_version(&self) -> &'static str {
        self.descriptor_version
    }

    #[must_use]
    pub const fn descriptor_digest(&self) -> &'static str {
        self.descriptor_digest
    }
}

/// One Plugin operation failure with an explicit Domain/Runtime split.
///
/// Ordinary operations can return `Result<T, DomainError>` directly. Use this
/// type only when Plugin code must deliberately surface an Adapter-specific
/// runtime failure in addition to its Capability-defined Domain Errors.
#[derive(Clone, Debug, PartialEq)]
pub enum PluginError<DomainError, RuntimeError> {
    /// An expected Capability-defined business rejection.
    Domain(DomainError),
    /// An infrastructure or execution failure outside the Capability contract.
    Runtime(RuntimeError),
}

impl<DomainError, RuntimeError> PluginError<DomainError, RuntimeError> {
    /// Creates a Capability-defined Domain Error.
    pub const fn domain(error: DomainError) -> Self {
        Self::Domain(error)
    }

    /// Creates an Adapter-specific Runtime Error.
    pub const fn runtime(error: RuntimeError) -> Self {
        Self::Runtime(error)
    }

    /// Maps the Domain Error while preserving the Runtime Error.
    pub fn map_domain<Other>(
        self,
        map: impl FnOnce(DomainError) -> Other,
    ) -> PluginError<Other, RuntimeError> {
        match self {
            Self::Domain(error) => PluginError::Domain(map(error)),
            Self::Runtime(error) => PluginError::Runtime(error),
        }
    }
}

/// A generated, strongly typed client for one required Capability.
///
/// Capability binding generators implement this trait for their client type so
/// Plugin authoring frontends can connect typed Ports without knowing the
/// Capability's operation kinds or handle layout. Implementations must use only
/// the supplied Plan-owned dependencies; they must not perform discovery.
pub trait CapabilityClient: Sized + 'static {
    /// Adapter-owned dependency view used to connect this client.
    type Dependencies: ?Sized;
    /// Adapter-owned failure returned when connection cannot complete.
    type Error;

    /// Stable Capability identity required by this client.
    const CAPABILITY_ID: &'static str;
    /// Exact Descriptor version understood by this generated client.
    const DESCRIPTOR_VERSION: &'static str;

    /// Connects this client to one Plugin Instance's resolved dependencies.
    fn from_dependencies(dependencies: &Self::Dependencies) -> Result<Self, Self::Error>;

    /// Connects this client to one source-named requirement.
    ///
    /// Generated clients override this method to narrow the dependency view by
    /// exact requirement identity. The default preserves older projections.
    fn from_requirement(
        dependencies: &Self::Dependencies,
        _requirement_id: &str,
    ) -> Result<Self, Self::Error> {
        Self::from_dependencies(dependencies)
    }

    /// Creates the adapter failure for an invalid second connection attempt.
    fn already_connected() -> Self::Error;
}

/// A generated Capability client that can be connected to every explicitly
/// bound provider in deterministic Resolved App Plan order.
pub trait CapabilityClientMany: CapabilityClient {
    /// Connects one typed client per bound provider without performing discovery.
    fn many_from_dependencies(
        dependencies: &Self::Dependencies,
    ) -> Result<Vec<BoundCapabilityClient<Self>>, Self::Error>;

    /// Connects every provider bound to one source-named requirement.
    fn many_from_requirement(
        dependencies: &Self::Dependencies,
        _requirement_id: &str,
    ) -> Result<Vec<BoundCapabilityClient<Self>>, Self::Error> {
        Self::many_from_dependencies(dependencies)
    }
}

/// One typed Capability client paired with its App-local provider Instance key.
#[derive(Debug)]
pub struct BoundCapabilityClient<C> {
    provider_instance: String,
    client: C,
}

impl<C> BoundCapabilityClient<C> {
    /// Creates one Plan-bound client entry.
    #[must_use]
    pub fn new(provider_instance: impl Into<String>, client: C) -> Self {
        Self {
            provider_instance: provider_instance.into(),
            client,
        }
    }

    /// Returns the App-local provider Instance key selected by Composition.
    #[must_use]
    pub fn provider_instance(&self) -> &str {
        &self.provider_instance
    }

    /// Returns the generated typed client.
    #[must_use]
    pub const fn client(&self) -> &C {
        &self.client
    }
}

impl<C> Deref for BoundCapabilityClient<C> {
    type Target = C;

    fn deref(&self) -> &Self::Target {
        &self.client
    }
}

/// A typed, lifecycle-bound Capability requirement declared by a Plugin.
///
/// Generated Plugin glue connects the Port during activation. Plugin behavior
/// can then call the generated Capability client directly through `Deref`.
/// A fresh Plugin generation owns fresh Ports; reconnecting one Port is an
/// invalid lifecycle transition.
pub struct Port<C: CapabilityClient> {
    client: Rc<OnceCell<C>>,
}

impl<C: CapabilityClient> Port<C> {
    /// Creates a disconnected typed Port.
    #[must_use]
    pub fn new() -> Self {
        Self {
            client: Rc::new(OnceCell::new()),
        }
    }

    /// Connects the Port from this Plugin Instance's resolved dependencies.
    pub fn connect(&self, dependencies: &C::Dependencies) -> Result<(), C::Error> {
        let client = C::from_dependencies(dependencies)?;
        self.client.set(client).map_err(|_| C::already_connected())
    }

    /// Connects the Port through one exact source declaration.
    pub fn connect_requirement(
        &self,
        dependencies: &C::Dependencies,
        requirement_id: &str,
    ) -> Result<(), C::Error> {
        let client = C::from_requirement(dependencies, requirement_id)?;
        self.client.set(client).map_err(|_| C::already_connected())
    }

    /// Returns whether lifecycle activation connected this Port.
    #[must_use]
    pub fn is_connected(&self) -> bool {
        self.client.get().is_some()
    }
}

impl<C: CapabilityClient> Clone for Port<C> {
    fn clone(&self) -> Self {
        Self {
            client: Rc::clone(&self.client),
        }
    }
}

impl<C: CapabilityClient> std::fmt::Debug for Port<C> {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("Port")
            .field("capability_id", &C::CAPABILITY_ID)
            .field("descriptor_version", &C::DESCRIPTOR_VERSION)
            .field("connected", &self.is_connected())
            .finish()
    }
}

impl<C: CapabilityClient> Default for Port<C> {
    fn default() -> Self {
        Self::new()
    }
}

impl<C: CapabilityClient> Deref for Port<C> {
    type Target = C;

    fn deref(&self) -> &Self::Target {
        self.client.get().unwrap_or_else(|| {
            panic!(
                "Capability Port {} was used before Plugin activation",
                C::CAPABILITY_ID
            )
        })
    }
}

/// A typed, lifecycle-bound `many` Capability requirement declared by a Plugin.
///
/// Generated Plugin glue connects one client per explicitly bound provider during
/// activation. Entries retain their provider Instance keys and resolved order.
pub struct ManyPort<C: CapabilityClientMany> {
    clients: Rc<OnceCell<Vec<BoundCapabilityClient<C>>>>,
}

impl<C: CapabilityClientMany> ManyPort<C> {
    /// Creates a disconnected typed `many` Port.
    #[must_use]
    pub fn new() -> Self {
        Self {
            clients: Rc::new(OnceCell::new()),
        }
    }

    /// Connects the Port from this Plugin Instance's resolved dependencies.
    pub fn connect(&self, dependencies: &C::Dependencies) -> Result<(), C::Error> {
        let clients = C::many_from_dependencies(dependencies)?;
        self.clients
            .set(clients)
            .map_err(|_| C::already_connected())
    }

    /// Connects only providers selected for one exact source declaration.
    pub fn connect_requirement(
        &self,
        dependencies: &C::Dependencies,
        requirement_id: &str,
    ) -> Result<(), C::Error> {
        let clients = C::many_from_requirement(dependencies, requirement_id)?;
        self.clients
            .set(clients)
            .map_err(|_| C::already_connected())
    }

    /// Returns whether lifecycle activation connected this Port.
    #[must_use]
    pub fn is_connected(&self) -> bool {
        self.clients.get().is_some()
    }
}

impl<C: CapabilityClientMany> Clone for ManyPort<C> {
    fn clone(&self) -> Self {
        Self {
            clients: Rc::clone(&self.clients),
        }
    }
}

impl<C: CapabilityClientMany> std::fmt::Debug for ManyPort<C> {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("ManyPort")
            .field("capability_id", &C::CAPABILITY_ID)
            .field("descriptor_version", &C::DESCRIPTOR_VERSION)
            .field("connected", &self.is_connected())
            .field("provider_count", &self.clients.get().map(Vec::len))
            .finish()
    }
}

impl<C: CapabilityClientMany> Default for ManyPort<C> {
    fn default() -> Self {
        Self::new()
    }
}

impl<C: CapabilityClientMany> Deref for ManyPort<C> {
    type Target = [BoundCapabilityClient<C>];

    fn deref(&self) -> &Self::Target {
        self.clients.get().map_or_else(
            || {
                panic!(
                    "Capability ManyPort {} was used before Plugin activation",
                    C::CAPABILITY_ID
                )
            },
            Vec::as_slice,
        )
    }
}

/// Common imports for a Plugin authoring frontend.
pub mod prelude {
    pub use crate::{
        BoundCapabilityClient, CapabilityClient, CapabilityClientMany, CapabilityReference,
        ManyPort, PluginError, Port,
    };
}

#[cfg(test)]
mod tests {
    use super::*;

    #[derive(Debug, Eq, PartialEq)]
    struct ExampleClient(u64);

    #[derive(Debug, Eq, PartialEq)]
    enum ExampleError {
        AlreadyConnected,
    }

    impl CapabilityClient for ExampleClient {
        type Dependencies = ();
        type Error = ExampleError;

        const CAPABILITY_ID: &'static str = "example.echo@1";
        const DESCRIPTOR_VERSION: &'static str = "1.0.0";

        fn from_dependencies(_dependencies: &Self::Dependencies) -> Result<Self, Self::Error> {
            Ok(Self(42))
        }

        fn already_connected() -> Self::Error {
            ExampleError::AlreadyConnected
        }
    }

    impl CapabilityClientMany for ExampleClient {
        fn many_from_dependencies(
            _dependencies: &Self::Dependencies,
        ) -> Result<Vec<BoundCapabilityClient<Self>>, Self::Error> {
            Ok(vec![
                BoundCapabilityClient::new("alpha", Self(1)),
                BoundCapabilityClient::new("beta", Self(2)),
            ])
        }
    }

    #[test]
    fn port_connects_once_and_is_shared_by_plugin_clones() {
        let port = Port::<ExampleClient>::new();
        let plugin_clone = port.clone();
        assert!(!port.is_connected());

        port.connect(&())
            .expect("the generated client should connect");

        assert!(plugin_clone.is_connected());
        assert_eq!(plugin_clone.0, 42);
        assert_eq!(port.connect(&()), Err(ExampleError::AlreadyConnected));
    }

    #[test]
    fn many_port_preserves_provider_identity_and_resolved_order() {
        let port = ManyPort::<ExampleClient>::new();
        let plugin_clone = port.clone();
        assert!(!port.is_connected());

        port.connect(&())
            .expect("the generated clients should connect");

        assert!(plugin_clone.is_connected());
        assert_eq!(plugin_clone[0].provider_instance(), "alpha");
        assert_eq!(plugin_clone[0].client().0, 1);
        assert_eq!(plugin_clone[1].provider_instance(), "beta");
        assert_eq!(plugin_clone[1].client().0, 2);
        assert_eq!(port.connect(&()), Err(ExampleError::AlreadyConnected));
    }

    #[test]
    fn plugin_error_preserves_runtime_failures_while_mapping_domain_errors() {
        let domain = PluginError::<_, &str>::domain("missing").map_domain(str::len);
        assert_eq!(domain, PluginError::Domain(7));

        let runtime = PluginError::<&str, _>::runtime("cancelled").map_domain(str::len);
        assert_eq!(runtime, PluginError::Runtime("cancelled"));
    }

    #[derive(Debug, Eq, PartialEq)]
    struct NamedClient(String);

    impl CapabilityClient for NamedClient {
        type Dependencies = ();
        type Error = ExampleError;

        const CAPABILITY_ID: &'static str = "example.store@1";
        const DESCRIPTOR_VERSION: &'static str = "1.0.0";

        fn from_dependencies(_dependencies: &Self::Dependencies) -> Result<Self, Self::Error> {
            Ok(Self("legacy".to_owned()))
        }

        fn from_requirement(
            _dependencies: &Self::Dependencies,
            requirement_id: &str,
        ) -> Result<Self, Self::Error> {
            Ok(Self(requirement_id.to_owned()))
        }

        fn already_connected() -> Self::Error {
            ExampleError::AlreadyConnected
        }
    }

    impl CapabilityClientMany for NamedClient {
        fn many_from_dependencies(
            _dependencies: &Self::Dependencies,
        ) -> Result<Vec<BoundCapabilityClient<Self>>, Self::Error> {
            Ok(Vec::new())
        }

        fn many_from_requirement(
            _dependencies: &Self::Dependencies,
            requirement_id: &str,
        ) -> Result<Vec<BoundCapabilityClient<Self>>, Self::Error> {
            Ok(vec![BoundCapabilityClient::new(
                format!("{requirement_id}-provider"),
                Self(requirement_id.to_owned()),
            )])
        }
    }

    #[test]
    fn named_ports_pass_the_exact_source_requirement_to_generated_clients() {
        let source = Port::<NamedClient>::new();
        let destination = Port::<NamedClient>::new();
        source.connect_requirement(&(), "source").unwrap();
        destination.connect_requirement(&(), "destination").unwrap();
        assert_eq!(source.0, "source");
        assert_eq!(destination.0, "destination");

        let stores = ManyPort::<NamedClient>::new();
        stores.connect_requirement(&(), "stores").unwrap();
        assert_eq!(stores[0].provider_instance(), "stores-provider");
        assert_eq!(stores[0].0, "stores");
    }

    #[test]
    fn generated_capability_reference_is_typed_and_provider_free() {
        let reference = CapabilityReference::<NamedClient>::new(
            "example.store@1",
            "1.0.0",
            "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
        );
        assert_eq!(reference.capability_id(), "example.store@1");
        assert_eq!(reference.descriptor_version(), "1.0.0");
        assert_eq!(
            reference.descriptor_digest(),
            "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
        );
    }
}