lenso-capability-http-endpoint 0.2.8

Portable HTTP Endpoint Capability contract for Lenso backend 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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
// @generated by lenso-contract-codegen; do not edit.
use std::{fmt, rc::Rc};
use futures::future::LocalBoxFuture;
use lenso_kernel::{InvocationContext, NativeRequestEndpoint, NativeRequestFuture, NativeRequestHandle, PluginDependencies, RequestCapability, RuntimeFailure};

use lenso_plugin_authoring::{BoundCapabilityClient, CapabilityClient, CapabilityClientMany};
pub const CAPABILITY_ID: &str = "lenso.http.endpoint@1";
pub const DESCRIPTOR_VERSION: &str = "1.1.0";
pub const PORTABLE: bool = true;
pub const CROSS_LANE_TRANSFER: bool = true;
pub const ENDPOINT_CAPABILITY_ID: &str = CAPABILITY_ID;
pub const ENDPOINT_DESCRIPTOR_VERSION: &str = DESCRIPTOR_VERSION;

#[doc(hidden)]
#[macro_export]
macro_rules! __lenso_provided_endpoint { () => { "{\"capability_id\":\"lenso.http.endpoint@1\",\"descriptor_version\":\"1.1.0\",\"operations\":[\"describe\",\"handle\"],\"operation_kinds\":{},\"default_admission\":{\"queue_capacity\":0,\"max_concurrency\":1},\"operation_admissions\":{},\"event_admission\":null,\"cross_lane_transfer\":true}" }; }

#[doc(hidden)]
#[macro_export]
macro_rules! __lenso_required_endpoint_client { () => { "{\"capability_id\":\"lenso.http.endpoint@1\",\"descriptor_version\":\"1.1.0\",\"cardinality\":\"one\"}" }; }

#[doc(hidden)]
#[macro_export]
macro_rules! __lenso_required_many_endpoint_client { () => { "{\"capability_id\":\"lenso.http.endpoint@1\",\"descriptor_version\":\"1.1.0\",\"cardinality\":\"many\"}" }; }

pub const DESCRIBE_OPERATION: &str = "describe";
pub const HANDLE_OPERATION: &str = "handle";

pub use lenso_contract_runtime::{Bytes, UnknownDomainError};
use lenso_contract_runtime::{decode_portable_json, encode_portable_json};

#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct DescribeRequest {

}

#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct DescribeResponse {
    #[serde(rename = "routes")]
    #[serde(deserialize_with = "lenso_contract_runtime::serde::deserialize_required")]
    pub routes: Vec<DescribeResponseRoutesItem>,
}

#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct DescribeResponseRoutesItem {
    #[serde(rename = "method")]
    #[serde(deserialize_with = "lenso_contract_runtime::serde::deserialize_required")]
    pub method: String,
    #[serde(rename = "openapi")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub openapi: Option<std::collections::BTreeMap<String, serde_json::Value>>,
    #[serde(rename = "path")]
    #[serde(deserialize_with = "lenso_contract_runtime::serde::deserialize_required")]
    pub path: String,
    #[serde(rename = "route_id")]
    #[serde(deserialize_with = "lenso_contract_runtime::serde::deserialize_required")]
    pub route_id: String,
}

#[derive(Clone, Debug, PartialEq)]
pub enum DescribeError {
    InvalidConfiguration,
    Unknown(UnknownDomainError),
}

#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct HandleRequest {
    #[serde(rename = "body")]
    #[serde(deserialize_with = "lenso_contract_runtime::serde::deserialize_required")]
    pub body: Bytes,
    #[serde(rename = "credential")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub credential: Option<HandleRequestCredential>,
    #[serde(rename = "headers")]
    #[serde(deserialize_with = "lenso_contract_runtime::serde::deserialize_required")]
    pub headers: Vec<HandleRequestHeadersItem>,
    #[serde(rename = "method")]
    #[serde(deserialize_with = "lenso_contract_runtime::serde::deserialize_required")]
    pub method: String,
    #[serde(rename = "path")]
    #[serde(deserialize_with = "lenso_contract_runtime::serde::deserialize_required")]
    pub path: String,
    #[serde(rename = "path_parameters")]
    #[serde(deserialize_with = "lenso_contract_runtime::serde::deserialize_required")]
    pub path_parameters: Vec<HandleRequestPathParametersItem>,
    #[serde(rename = "query")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub query: Option<String>,
    #[serde(rename = "request_id")]
    #[serde(deserialize_with = "lenso_contract_runtime::serde::deserialize_required")]
    pub request_id: String,
    #[serde(rename = "route_id")]
    #[serde(deserialize_with = "lenso_contract_runtime::serde::deserialize_required")]
    pub route_id: String,
}

#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct HandleRequestCredential {
    #[serde(rename = "scheme")]
    #[serde(deserialize_with = "lenso_contract_runtime::serde::deserialize_required")]
    pub scheme: String,
    #[serde(rename = "value")]
    #[serde(deserialize_with = "lenso_contract_runtime::serde::deserialize_required")]
    pub value: String,
}

#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct HandleRequestHeadersItem {
    #[serde(rename = "name")]
    #[serde(deserialize_with = "lenso_contract_runtime::serde::deserialize_required")]
    pub name: String,
    #[serde(rename = "value")]
    #[serde(deserialize_with = "lenso_contract_runtime::serde::deserialize_required")]
    pub value: String,
}

#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct HandleRequestPathParametersItem {
    #[serde(rename = "name")]
    #[serde(deserialize_with = "lenso_contract_runtime::serde::deserialize_required")]
    pub name: String,
    #[serde(rename = "value")]
    #[serde(deserialize_with = "lenso_contract_runtime::serde::deserialize_required")]
    pub value: String,
}

#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct HandleResponse {
    #[serde(rename = "body")]
    #[serde(deserialize_with = "lenso_contract_runtime::serde::deserialize_required")]
    pub body: Bytes,
    #[serde(rename = "headers")]
    #[serde(deserialize_with = "lenso_contract_runtime::serde::deserialize_required")]
    pub headers: Vec<HandleResponseHeadersItem>,
    #[serde(rename = "status")]
    #[serde(deserialize_with = "lenso_contract_runtime::serde::deserialize_required")]
    pub status: i64,
}

#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct HandleResponseHeadersItem {
    #[serde(rename = "name")]
    #[serde(deserialize_with = "lenso_contract_runtime::serde::deserialize_required")]
    pub name: String,
    #[serde(rename = "value")]
    #[serde(deserialize_with = "lenso_contract_runtime::serde::deserialize_required")]
    pub value: String,
}

#[derive(Clone, Debug, PartialEq)]
pub enum HandleError {
    Rejected,
    Unknown(UnknownDomainError),
}

#[derive(Debug)]
pub struct EndpointDescribe;
impl RequestCapability for EndpointDescribe {
    type Request = DescribeRequest;
    type Response = DescribeResponse;
    type DomainError = DescribeError;
    const ID: &'static str = CAPABILITY_ID;
    const DESCRIPTOR_VERSION: &'static str = DESCRIPTOR_VERSION;

    fn invoke_native(endpoint: &dyn NativeRequestEndpoint, operation: &str, request: Self::Request, context: InvocationContext) -> NativeRequestFuture<Self> {
        if operation != DESCRIBE_OPERATION {
            return lenso_kernel::invoke_typed_or_erased_native_request::<Self>(endpoint, operation, request, context);
        }
        let Some(typed_endpoint) = endpoint
            .typed_endpoint()
            .and_then(|endpoint| endpoint.downcast_ref::<EndpointRequestEndpoint>())
        else {
            return lenso_kernel::invoke_typed_or_erased_native_request::<Self>(endpoint, operation, request, context);
        };
        Rc::clone(&typed_endpoint.provider).describe(context, request)
    }
}

#[derive(Debug)]
pub struct EndpointHandle;
impl RequestCapability for EndpointHandle {
    type Request = HandleRequest;
    type Response = HandleResponse;
    type DomainError = HandleError;
    const ID: &'static str = CAPABILITY_ID;
    const DESCRIPTOR_VERSION: &'static str = DESCRIPTOR_VERSION;

    fn invoke_native(endpoint: &dyn NativeRequestEndpoint, operation: &str, request: Self::Request, context: InvocationContext) -> NativeRequestFuture<Self> {
        if operation != HANDLE_OPERATION {
            return lenso_kernel::invoke_typed_or_erased_native_request::<Self>(endpoint, operation, request, context);
        }
        let Some(typed_endpoint) = endpoint
            .typed_endpoint()
            .and_then(|endpoint| endpoint.downcast_ref::<EndpointRequestEndpoint>())
        else {
            return lenso_kernel::invoke_typed_or_erased_native_request::<Self>(endpoint, operation, request, context);
        };
        Rc::clone(&typed_endpoint.provider).handle(context, request)
    }
}

impl serde::Serialize for DescribeError {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        use serde::ser::SerializeMap;
        match self {
            Self::InvalidConfiguration => serializer.serialize_str("invalid_configuration"),
            Self::Unknown(value) => {
                let mut map = serializer.serialize_map(Some(1 + usize::from(value.payload.is_some()) + value.extra.len()))?;
                map.serialize_entry("code", &value.code)?;
                if let Some(payload) = &value.payload {
                    map.serialize_entry("payload", payload)?;
                }
                for (key, extra) in &value.extra {
                    map.serialize_entry(key, extra)?;
                }
                map.end()
            },
        }
    }
}

impl<'de> serde::Deserialize<'de> for DescribeError {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let value = <serde_json::Value as serde::Deserialize>::deserialize(deserializer)?;
        match value {
            serde_json::Value::String(code) => match code.as_str() {
                "invalid_configuration" => Ok(Self::InvalidConfiguration),
                _ => Ok(Self::Unknown(UnknownDomainError { code, payload: None, extra: std::collections::BTreeMap::new() })),
            },
            serde_json::Value::Object(mut object) => {
                let Some(code) = object.remove("code").and_then(|value| value.as_str().map(ToOwned::to_owned)) else {
                    return Err(serde::de::Error::custom("Domain Error object is missing a string code"));
                };
                let payload = object.remove("payload");
                let extra = object.into_iter().collect::<std::collections::BTreeMap<_, _>>();
                Ok(Self::Unknown(UnknownDomainError { code, payload, extra }))
            }
            other => Err(serde::de::Error::custom(format!("Domain Error must be a string or object, got {other}"))),
        }
    }
}

impl serde::Serialize for HandleError {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        use serde::ser::SerializeMap;
        match self {
            Self::Rejected => serializer.serialize_str("rejected"),
            Self::Unknown(value) => {
                let mut map = serializer.serialize_map(Some(1 + usize::from(value.payload.is_some()) + value.extra.len()))?;
                map.serialize_entry("code", &value.code)?;
                if let Some(payload) = &value.payload {
                    map.serialize_entry("payload", payload)?;
                }
                for (key, extra) in &value.extra {
                    map.serialize_entry(key, extra)?;
                }
                map.end()
            },
        }
    }
}

impl<'de> serde::Deserialize<'de> for HandleError {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let value = <serde_json::Value as serde::Deserialize>::deserialize(deserializer)?;
        match value {
            serde_json::Value::String(code) => match code.as_str() {
                "rejected" => Ok(Self::Rejected),
                _ => Ok(Self::Unknown(UnknownDomainError { code, payload: None, extra: std::collections::BTreeMap::new() })),
            },
            serde_json::Value::Object(mut object) => {
                let Some(code) = object.remove("code").and_then(|value| value.as_str().map(ToOwned::to_owned)) else {
                    return Err(serde::de::Error::custom("Domain Error object is missing a string code"));
                };
                let payload = object.remove("payload");
                let extra = object.into_iter().collect::<std::collections::BTreeMap<_, _>>();
                Ok(Self::Unknown(UnknownDomainError { code, payload, extra }))
            }
            other => Err(serde::de::Error::custom(format!("Domain Error must be a string or object, got {other}"))),
        }
    }
}

pub fn encode_describe_request(value: &DescribeRequest) -> Result<String, serde_json::Error> { encode_portable_json(value) }
pub fn decode_describe_request(wire: &str) -> Result<DescribeRequest, serde_json::Error> { decode_portable_json(wire) }
pub fn encode_describe_response(value: &DescribeResponse) -> Result<String, serde_json::Error> { encode_portable_json(value) }
pub fn decode_describe_response(wire: &str) -> Result<DescribeResponse, serde_json::Error> { decode_portable_json(wire) }
pub fn encode_describe_error(value: &DescribeError) -> Result<String, serde_json::Error> { encode_portable_json(value) }
pub fn decode_describe_error(wire: &str) -> Result<DescribeError, serde_json::Error> { decode_portable_json(wire) }

pub fn encode_handle_request(value: &HandleRequest) -> Result<String, serde_json::Error> { encode_portable_json(value) }
pub fn decode_handle_request(wire: &str) -> Result<HandleRequest, serde_json::Error> { decode_portable_json(wire) }
pub fn encode_handle_response(value: &HandleResponse) -> Result<String, serde_json::Error> { encode_portable_json(value) }
pub fn decode_handle_response(wire: &str) -> Result<HandleResponse, serde_json::Error> { decode_portable_json(wire) }
pub fn encode_handle_error(value: &HandleError) -> Result<String, serde_json::Error> { encode_portable_json(value) }
pub fn decode_handle_error(wire: &str) -> Result<HandleError, serde_json::Error> { decode_portable_json(wire) }

#[doc(hidden)]
pub trait __LensoIntoEndpointDescribeResult {
    fn __lenso_into_result(self) -> Result<Result<DescribeResponse, DescribeError>, RuntimeFailure>;
}
impl __LensoIntoEndpointDescribeResult for Result<DescribeResponse, DescribeError> {
    fn __lenso_into_result(self) -> Result<Result<DescribeResponse, DescribeError>, RuntimeFailure> { Ok(self) }
}
impl __LensoIntoEndpointDescribeResult for Result<Result<DescribeResponse, DescribeError>, RuntimeFailure> {
    fn __lenso_into_result(self) -> Result<Result<DescribeResponse, DescribeError>, RuntimeFailure> { self }
}
impl __LensoIntoEndpointDescribeResult for Result<DescribeResponse, lenso_plugin_authoring::PluginError<DescribeError, RuntimeFailure>> {
    fn __lenso_into_result(self) -> Result<Result<DescribeResponse, DescribeError>, RuntimeFailure> {
        match self {
            Ok(value) => Ok(Ok(value)),
            Err(lenso_plugin_authoring::PluginError::Domain(error)) => Ok(Err(error)),
            Err(lenso_plugin_authoring::PluginError::Runtime(error)) => Err(error),
        }
    }
}
impl __LensoIntoEndpointDescribeResult for Result<DescribeResponse, EndpointDescribeInvocationError> {
    fn __lenso_into_result(self) -> Result<Result<DescribeResponse, DescribeError>, RuntimeFailure> {
        match self {
            Ok(value) => Ok(Ok(value)),
            Err(EndpointDescribeInvocationError::Domain(error)) => Ok(Err(error)),
            Err(EndpointDescribeInvocationError::Runtime(error)) => Err(error),
        }
    }
}

#[doc(hidden)]
pub trait __LensoIntoEndpointHandleResult {
    fn __lenso_into_result(self) -> Result<Result<HandleResponse, HandleError>, RuntimeFailure>;
}
impl __LensoIntoEndpointHandleResult for Result<HandleResponse, HandleError> {
    fn __lenso_into_result(self) -> Result<Result<HandleResponse, HandleError>, RuntimeFailure> { Ok(self) }
}
impl __LensoIntoEndpointHandleResult for Result<Result<HandleResponse, HandleError>, RuntimeFailure> {
    fn __lenso_into_result(self) -> Result<Result<HandleResponse, HandleError>, RuntimeFailure> { self }
}
impl __LensoIntoEndpointHandleResult for Result<HandleResponse, lenso_plugin_authoring::PluginError<HandleError, RuntimeFailure>> {
    fn __lenso_into_result(self) -> Result<Result<HandleResponse, HandleError>, RuntimeFailure> {
        match self {
            Ok(value) => Ok(Ok(value)),
            Err(lenso_plugin_authoring::PluginError::Domain(error)) => Ok(Err(error)),
            Err(lenso_plugin_authoring::PluginError::Runtime(error)) => Err(error),
        }
    }
}
impl __LensoIntoEndpointHandleResult for Result<HandleResponse, EndpointHandleInvocationError> {
    fn __lenso_into_result(self) -> Result<Result<HandleResponse, HandleError>, RuntimeFailure> {
        match self {
            Ok(value) => Ok(Ok(value)),
            Err(EndpointHandleInvocationError::Domain(error)) => Ok(Err(error)),
            Err(EndpointHandleInvocationError::Runtime(error)) => Err(error),
        }
    }
}

pub trait EndpointProvider: fmt::Debug + 'static {
    fn describe(&self, context: InvocationContext, request: DescribeRequest) -> NativeRequestFuture<EndpointDescribe>;
    fn handle(&self, context: InvocationContext, request: HandleRequest) -> NativeRequestFuture<EndpointHandle>;
}

#[doc(hidden)]
#[macro_export]
macro_rules! __lenso_native_lower_endpoint {
    ($plugin:ty, $support:path) => {
        use $support as __LensoNativeSupportEndpoint;
        impl $crate::EndpointProvider for $plugin {
        fn describe(&self, context: __LensoNativeSupportEndpoint::InvocationContext, request: $crate::DescribeRequest) -> __LensoNativeSupportEndpoint::NativeRequestFuture<$crate::EndpointDescribe> {
            let plugin = self.clone();
            ::std::boxed::Box::pin(async move {
                let result = <$plugin>::describe(&plugin, context, request).await;
                $crate::__LensoIntoEndpointDescribeResult::__lenso_into_result(result)
            })
        }
        fn handle(&self, context: __LensoNativeSupportEndpoint::InvocationContext, request: $crate::HandleRequest) -> __LensoNativeSupportEndpoint::NativeRequestFuture<$crate::EndpointHandle> {
            let plugin = self.clone();
            ::std::boxed::Box::pin(async move {
                let result = <$plugin>::handle(&plugin, context, request).await;
                $crate::__LensoIntoEndpointHandleResult::__lenso_into_result(result)
            })
        }
        }
    };
}

#[derive(Debug)]
struct EndpointRequestEndpoint { provider: Rc<dyn EndpointProvider> }

#[derive(Debug)]
pub struct EndpointEndpoint<P: EndpointProvider> { provider: Rc<P>, request_endpoint: EndpointRequestEndpoint }
impl<P: EndpointProvider> EndpointEndpoint<P> {
    pub fn new(provider: P) -> Self {
        let provider = Rc::new(provider);
        let request_provider: Rc<dyn EndpointProvider> = provider.clone();
        Self { provider, request_endpoint: EndpointRequestEndpoint { provider: request_provider } }
    }
}

impl<P: EndpointProvider> NativeRequestEndpoint for EndpointEndpoint<P> {
    fn capability_id(&self) -> &'static str { CAPABILITY_ID }
    fn descriptor_version(&self) -> &'static str { DESCRIPTOR_VERSION }
    fn operations(&self) -> &'static [&'static str] { &[
        DESCRIBE_OPERATION,
        HANDLE_OPERATION,
    ] }
    fn typed_endpoint(&self) -> Option<&dyn std::any::Any> { Some(&self.request_endpoint) }
    fn invoke(&self, operation: &str, request: Box<dyn std::any::Any>, context: InvocationContext) -> LocalBoxFuture<'static, Result<Result<Box<dyn std::any::Any>, Box<dyn std::any::Any>>, RuntimeFailure>> {
        match operation {
            DESCRIBE_OPERATION => {
                let Ok(request) = request.downcast::<DescribeRequest>() else {
                    return Box::pin(futures::future::ready(Err(RuntimeFailure::ProtocolViolation { capability: CAPABILITY_ID })));
                };
                let invocation = Rc::clone(&self.provider).describe(context, *request);
                Box::pin(async move {
                    invocation.await.map(|result| {
                        result
                            .map(|value| Box::new(value) as Box<dyn std::any::Any>)
                            .map_err(|error| Box::new(error) as Box<dyn std::any::Any>)
                    })
                })
            },
            HANDLE_OPERATION => {
                let Ok(request) = request.downcast::<HandleRequest>() else {
                    return Box::pin(futures::future::ready(Err(RuntimeFailure::ProtocolViolation { capability: CAPABILITY_ID })));
                };
                let invocation = Rc::clone(&self.provider).handle(context, *request);
                Box::pin(async move {
                    invocation.await.map(|result| {
                        result
                            .map(|value| Box::new(value) as Box<dyn std::any::Any>)
                            .map_err(|error| Box::new(error) as Box<dyn std::any::Any>)
                    })
                })
            }
            _ => Box::pin(futures::future::ready(Err(RuntimeFailure::UnknownOperation { capability: CAPABILITY_ID, operation: operation.to_owned() }))),
        }
    }
}

#[doc(hidden)]
#[macro_export]
macro_rules! __lenso_native_endpoints_endpoint {
    ($provider:expr, $support:path) => {{
        use $support as __LensoNativeSupport;
        let endpoint = ::std::rc::Rc::new($crate::EndpointEndpoint::new($provider));
        (
            vec![endpoint.clone() as ::std::rc::Rc<dyn __LensoNativeSupport::NativeRequestEndpoint>],
            vec![],
            vec![],
        )
    }};
}

#[doc(hidden)]
#[macro_export]
macro_rules! __lenso_native_provide_endpoint {
    ($provider:expr, $lifecycle:expr, $support:path) => {{
        use $support as __LensoNativeSupport;
        let (request_endpoints, stream_endpoints, event_endpoints) =
            $crate::__lenso_native_endpoints_endpoint!($provider, $support);
        __LensoNativeSupport::NativePluginInstance::with_all_endpoints(
            request_endpoints,
            stream_endpoints,
            event_endpoints,
            $lifecycle,
        )
    }};
}

#[derive(Debug)]
pub struct EndpointClient {
    describe: NativeRequestHandle<EndpointDescribe>,
    handle: NativeRequestHandle<EndpointHandle>,
}
impl EndpointClient {
    pub fn from_dependencies(dependencies: &PluginDependencies) -> Result<Self, RuntimeFailure> {
        <Self as CapabilityClient>::from_dependencies(dependencies)
    }

    pub async fn describe(&self, request: DescribeRequest) -> Result<DescribeResponse, EndpointDescribeInvocationError> {
        self.describe.invoke(DESCRIBE_OPERATION, request).await
            .map_err(EndpointDescribeInvocationError::Runtime)?
            .map_err(EndpointDescribeInvocationError::Domain)
    }

    pub async fn describe_with_context(&self, context: InvocationContext, request: DescribeRequest) -> Result<DescribeResponse, EndpointDescribeInvocationError> {
        self.describe.invoke_with_context(DESCRIBE_OPERATION, context, request).await
            .map_err(EndpointDescribeInvocationError::Runtime)?
            .map_err(EndpointDescribeInvocationError::Domain)
    }

    pub async fn handle(&self, request: HandleRequest) -> Result<HandleResponse, EndpointHandleInvocationError> {
        self.handle.invoke(HANDLE_OPERATION, request).await
            .map_err(EndpointHandleInvocationError::Runtime)?
            .map_err(EndpointHandleInvocationError::Domain)
    }

    pub async fn handle_with_context(&self, context: InvocationContext, request: HandleRequest) -> Result<HandleResponse, EndpointHandleInvocationError> {
        self.handle.invoke_with_context(HANDLE_OPERATION, context, request).await
            .map_err(EndpointHandleInvocationError::Runtime)?
            .map_err(EndpointHandleInvocationError::Domain)
    }
}

impl CapabilityClient for EndpointClient {
    type Dependencies = PluginDependencies;
    type Error = RuntimeFailure;

    const CAPABILITY_ID: &'static str = CAPABILITY_ID;
    const DESCRIPTOR_VERSION: &'static str = DESCRIPTOR_VERSION;

    fn from_dependencies(dependencies: &PluginDependencies) -> Result<Self, RuntimeFailure> {
        Ok(Self {
            describe: dependencies.one::<EndpointDescribe>()?,
            handle: dependencies.one::<EndpointHandle>()?,
        })
    }

    fn already_connected() -> RuntimeFailure {
        RuntimeFailure::PluginFailure {
            detail: format!("Capability Port {CAPABILITY_ID} was connected more than once"),
        }
    }
}

impl CapabilityClientMany for EndpointClient {
    fn many_from_dependencies(
        dependencies: &PluginDependencies,
    ) -> Result<Vec<BoundCapabilityClient<Self>>, RuntimeFailure> {
        dependencies
            .bindings()
            .iter()
            .filter(|binding| binding.capability_id() == CAPABILITY_ID)
            .map(|binding| {
                Ok(BoundCapabilityClient::new(
                    binding.provider_instance(),
                    Self {
                    describe: binding.handle().ok_or(RuntimeFailure::Unavailable { capability: CAPABILITY_ID })?.typed::<EndpointDescribe>()?,
                    handle: binding.handle().ok_or(RuntimeFailure::Unavailable { capability: CAPABILITY_ID })?.typed::<EndpointHandle>()?,
                    },
                ))
            })
            .collect()
    }
}

#[derive(Clone, Debug, PartialEq)]
pub enum EndpointDescribeInvocationError {
    Domain(DescribeError),
    Runtime(RuntimeFailure),
}
#[derive(Clone, Debug, PartialEq)]
pub enum EndpointHandleInvocationError {
    Domain(HandleError),
    Runtime(RuntimeFailure),
}