saddle-framework 0.3.6

The single business-facing facade for Saddle applications
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
//! The only Saddle crate that business applications directly depend on.
//!
//! Pool construction and Service registry assembly remain framework-owned:
//!
//! ```compile_fail
//! let _ = saddle::db::Database::connect;
//! ```
//!
//! ```compile_fail
//! let _ = saddle::service::ServiceRegistryBuilder::new();
//! ```
//!
//! The old static/three-argument launcher is not a public surface:
//!
//! ```compile_fail
//! let _ = saddle::Saddle::run;
//! ```

mod application;
#[cfg(all(target_arch = "x86_64", target_os = "linux"))]
mod http1;
mod process;
mod profusegw_http;
mod profusegw_response;
mod programming;
mod startup_candidate;
mod testing_harness;

pub use application::ProductionLauncher;
pub use application::SaddleConfig;
pub use application::{
    ApprovedBundleNonceReservation, ApprovedExternalBundle,
    ApprovedExternalBundleApplicabilityFailure, ApprovedExternalBundleSeal,
    ApprovedExternalBundleVerification, ListenerAuthorityProvider, ListenerAuthoritySeal,
    VerifiedListenerAuthority,
};
#[doc(hidden)]
pub use application::{
    GeneratedApplicationBindingError, GeneratedApplicationConsumer, GeneratedApplicationOwner,
    GeneratedApplicationParts, GeneratedApplicationSeal, GeneratedBoundApplicationParts,
    GeneratedProductionBootstrap,
};
/// Framework/Skill assembly handshake. This is not a business API.
#[doc(hidden)]
#[cfg(all(target_arch = "x86_64", target_os = "linux"))]
pub mod internal {
    pub use crate::http1::bootstrap::{
        ApprovedGeneratedHttp1Facts, GeneratedApplicationBootstrap, GeneratedBootstrapError,
        GeneratedBootstrapToken, GeneratedCompiledAdapter, GeneratedContextFactory,
        GeneratedHttp1StaticFacts, GeneratedRoute, generated_bootstrap_type_identity,
        generated_http1_framing_identity,
    };
}

pub use process::{BusinessConfig, ProcessConfig};
pub use saddle_core::{ErrorKind, Result, SaddleError};

// Macro plumbing for `business_types!`. These names are not a supported
// general-purpose protobuf API; generated message implementations require
// exactly this trait/encoding surface.
#[doc(hidden)]
pub use prost::{DecodeError, Message, alloc, bytes, encoding};

#[doc(hidden)]
pub mod __private {
    pub use crate::process::{
        coordinate_profusegw_process, process_bootstrap_error, process_contract_error,
        process_dispatch_error,
    };
    pub use crate::profusegw_http::encode_profusegw_http1;
    pub use crate::profusegw_response::assert_unique_code_registries;
    pub use crate::programming::{
        ProfuseContractDeployment, ProfuseGwDispatchError, decode_accepted_profusegw,
        ingress_matches_contract,
    };
    pub use crate::testing_harness::{accept_test_request, dispatch_error, execution};
    pub use prost;
    pub use prost::Message;
    pub use saddle_boundary::ingress::{AcceptedIngress, ProfuseGwListenerAdapter};
    pub use saddle_core::{BootstrapRendezvousIssuer, GeneratedApplicationFreezeSource};
    pub use saddle_macros::contract_dir;
    pub use serde;
    pub use serde::Serializer;
    pub use serde::{Deserialize, Serialize};
    pub use serde_json;
}

/// Declares application-owned protobuf and JSON carrier types without adding
/// serde or prost as direct application dependencies.
///
/// The macro deliberately exposes only declarations. Encoding, decoding and
/// the test runtime remain controlled by the generated application surface.
#[macro_export]
macro_rules! business_types {
    ($($item:item)*) => {
        #[allow(unused_extern_crates)]
        extern crate saddle as prost;
        #[doc(hidden)]
        mod serde {
            pub use $crate::__private::serde::*;
        }
        #[allow(unused_imports)]
        use $crate::__private::{Deserialize, Message, Serialize};
        $($item)*
    };
}

/// Fixed profusegw handler context.
pub mod ingress {
    pub use crate::profusegw_response::{
        FailureMessage, FailureMessageError, MAX_FAILURE_MESSAGE_BYTES, ProfuseGwCode,
        ProfuseGwFailure, ProfuseGwResponse,
    };
    pub use crate::programming::{
        LdcInfo, MAX_PROFUSE_GW_USER_ID_BYTES, ProfuseGwContext, ProfuseGwDispatchError, TraceInfo,
    };
}

/// Business-facing tests that exercise the same generated Profusegw dispatch.
pub mod testing {
    pub use crate::programming::{
        FakeExecutionCertainty, FakeProfuseContractBoundary, FakeStep, FakeTechnicalCode,
    };
    pub use crate::testing_harness::{
        PROFUSEGW_MEDIA_TYPE, PROFUSEGW_METHOD, PROFUSEGW_PATH, ProfuseGwTestAttempt,
        ProfuseGwTestError, ProfuseGwTestExecution, ProfuseGwTestHarness, ProfuseGwTestRequest,
        TestIngressIdentity,
    };
}

/// Application-facing, strongly typed profusecontract programming surface.
pub mod profusecontract {
    #[doc(hidden)]
    pub use crate::programming::ApplicationContractSeal;
    pub use crate::programming::{
        DeclaredExternalFunctionCall, ExecutionCertainty, ExternalFunctionResult, TechnicalFailure,
        TechnicalFailureCode,
    };

    /// Deterministic alpha.1 consumer harness. Production assembly does not
    /// consume this harness, and Transport's raw boundary types remain hidden.
    pub mod testing {
        pub use crate::programming::{
            FakeApplicationBinding, FakeAttempt, FakeExecutionCertainty,
            FakeProfuseContractBoundary, FakeStep, FakeTechnicalCode,
        };
    }
}

/// The complete stable set of business-owned values accepted by generated
/// Saddle 0.2 handlers.
pub mod managed {
    pub use saddle_db::internal::ManagedWriteResult as WriteResult;
    pub use saddle_service::internal::{
        ManagedBool as Bool, ManagedPair as Pair, ManagedU64 as U64,
    };

    /// A fixed optional value delivered to a `query_optional` handler.
    #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
    pub struct Optional<T>(Option<T>);

    impl<T> Optional<T> {
        #[doc(hidden)]
        pub const fn from_generated(value: Option<T>) -> Self {
            Self(value)
        }

        pub fn into_option(self) -> Option<T> {
            self.0
        }

        pub const fn as_ref(&self) -> Option<&T> {
            self.0.as_ref()
        }
    }
}

/// Declares the sole generated Saddle application in a business crate.
///
/// The Skill emits a private `__saddle_generated` module beside this
/// invocation. Only the generated application marker can move that module's
/// bootstrap owner into the facade.
#[doc(hidden)]
#[macro_export]
macro_rules! __saddle_business_config_type {
    () => {
        ()
    };
    ($business_config:ty) => {
        $business_config
    };
}

#[macro_export]
macro_rules! application {
    (
        schema "saddle-application/1";
        application $application:ident;
        $($declaration:tt)*
    ) => {
        pub struct $application;
    };
    (
        schema "saddle-application/2";
        application $application:ident;
        deployment_app $deployment_app:literal;
        business_config $business_config:ty;
        profusecontract {
            contract_dir $contract_dir:literal;
            capability $capability:ident;
            response_code $result_code:ty;
            functions {
                $(
                    $function:ident => $method:ident {
                        business_unit $business_unit:literal;
                        function $function_name:literal;
                    } (
                        $function_request:ty
                    ) -> $function_result:ty;
                )+
            }
        }
        $(
            service $service:ident {
                ingress profusegw;
                operation_type $operation_type:literal;
                request $request:ty;
                response $response:ty;
                handler $handler:path;
                $(uses $uses:ident;)+
            }
        )+
    ) => {
        const __SADDLE_ONLY_APPLICATION: () = ();
        $crate::__private::contract_dir!(
            $contract_dir;
            declarations {
                $(($function, $business_unit, $function_name, $function_request, $function_result);)+
            }
            uses {
                $($($uses;)+)+
            }
        );

        pub struct $application;

        trait __SaddleDeclaredExternalFunction {}

        $(
            pub struct $function;
            impl __SaddleDeclaredExternalFunction for $function {}
        )+

        pub struct $capability {
            __seal: $crate::profusecontract::ApplicationContractSeal,
        }

        impl $capability {
            #[doc(hidden)]
            pub fn __from_framework(
                seal: $crate::profusecontract::ApplicationContractSeal,
            ) -> Self {
                Self { __seal: seal }
            }

            $(
                pub fn $method(
                    &self,
                    request: $function_request,
                ) -> $crate::profusecontract::DeclaredExternalFunctionCall<
                    $application,
                    $function,
                    $function_request,
                    $function_result,
                > {
                    $crate::profusecontract::DeclaredExternalFunctionCall::from_declared(
                        request,
                        &self.__seal,
                        $business_unit,
                        $function_name,
                    )
                }
            )+
        }

        impl $application {
            pub const PROFUSECONTRACT_DIR: &'static str = $contract_dir;

            #[doc(hidden)]
            pub const __PROFUSECONTRACT_DESCRIPTOR: &'static [u8] =
                __SADDLE_CONTRACT_DESCRIPTOR;

            /// Starts the sole generated application process. Configuration,
            /// listener, Runtime and shutdown ownership remain in the facade.
            pub fn run() -> $crate::Result<()> {
                let (application_half, listener_issuer) =
                    $crate::__private::BootstrapRendezvousIssuer::issue()
                        .freeze_application(
                            $crate::__private::GeneratedApplicationFreezeSource::new(
                                $deployment_app,
                                Self::__PROFUSECONTRACT_DESCRIPTOR,
                                &[
                                    $(concat!(
                                        $operation_type,
                                        "|",
                                        stringify!($request),
                                        "|",
                                        stringify!($response),
                                        "|",
                                        stringify!($handler)
                                    ),)+
                                ],
                            ),
                        )
                        .map_err(|_| $crate::__private::process_bootstrap_error())?;
                let config = $crate::ProcessConfig::<$business_config>::from_args()?;
                $crate::__private::coordinate_profusegw_process(
                    config,
                    Self::__profusegw_listener_adapter(),
                    application_half,
                    listener_issuer,
                    |authority_template| async move {
                        Ok($crate::__private::ProfuseContractDeployment::routed(
                            authority_template,
                        ))
                    },
                    |accepted, deployment, _business| async move {
                        let capability = Self::__bind_profusecontract(&deployment, &accepted);
                        Self::__dispatch_accepted_profusegw(
                            accepted,
                            capability,
                            _business,
                        )
                            .await
                            .map_err(|_| $crate::__private::process_dispatch_error())?
                            .__encode_profusegw_http1()
                            .map_err(|_| $crate::__private::process_dispatch_error())
                    },
                )
            }

            /// Resolves the MobileGW operation name against the sole static
            /// application graph. Business handlers never perform dispatch.
            pub fn dispatch_profusegw_operation(
                operation_type: &str,
            ) -> Option<ProfuseGwDispatch> {
                match operation_type {
                    $(
                        $operation_type => Some(ProfuseGwDispatch::$service),
                    )+
                    _ => None,
                }
            }

            #[doc(hidden)]
            pub fn __profusegw_listener_adapter(
            ) -> $crate::__private::ProfuseGwListenerAdapter {
                $crate::__private::ProfuseGwListenerAdapter::new($deployment_app)
                    .expect("generated deployment application identity is valid")
            }

            #[doc(hidden)]
            pub fn __bind_profusecontract(
                deployment: &$crate::__private::ProfuseContractDeployment,
                accepted: &$crate::__private::AcceptedIngress,
            ) -> $capability {
                $capability::__from_framework(deployment.bind_accepted(accepted))
            }

            /// Runs the generated Profusegw ingress and handler graph through
            /// the controlled framework fake without exposing hidden ingress.
            pub fn profusegw_test_harness(
                fake: $crate::testing::FakeProfuseContractBoundary,
                business: $crate::BusinessConfig<$business_config>,
            ) -> $crate::testing::ProfuseGwTestHarness<ProfuseGwResponse> {
                $crate::testing::ProfuseGwTestHarness::from_executor(move |request| {
                    ::std::boxed::Box::pin(async move {
                        let observed = fake.clone();
                        let accepted = $crate::__private::accept_test_request(
                            &Self::__profusegw_listener_adapter(),
                            request,
                        )?;
                        let binding = fake
                            .bind_accepted(&accepted)
                            .map_err($crate::__private::dispatch_error)?;
                        let response = Self::__dispatch_accepted_profusegw(
                            accepted,
                            $capability::__from_framework(binding.into_contract_seal()),
                            business.clone(),
                        )
                        .await
                        .map_err($crate::__private::dispatch_error)?;
                        Ok($crate::__private::execution(response, &observed))
                    })
                })
            }

            #[doc(hidden)]
            pub async fn __dispatch_accepted_profusegw(
                accepted: $crate::__private::AcceptedIngress,
                contract: $capability,
                business: $crate::BusinessConfig<$business_config>,
            ) -> ::core::result::Result<ProfuseGwResponse, $crate::__private::ProfuseGwDispatchError> {
                if !$crate::__private::ingress_matches_contract(&accepted, &contract.__seal) {
                    return Err($crate::__private::ProfuseGwDispatchError::IdentityMismatch);
                }
                match accepted.interface_id.as_str() {
                    $(
                        $operation_type => {
                            let (request, context) =
                                $crate::__private::decode_accepted_profusegw::<$request>(accepted)?;
                            Ok(ProfuseGwResponse::$service(
                                $handler(request, context, contract, business.clone()).await,
                            ))
                        }
                    )+
                    _ => Err($crate::__private::ProfuseGwDispatchError::InterfaceNotFound),
                }
            }
        }

        pub enum ProfuseGwResponse {
            $($service($crate::ingress::ProfuseGwResponse<$response, $result_code>)),+
        }

        impl $crate::__private::Serialize for ProfuseGwResponse {
            fn serialize<S>(&self, serializer: S) -> ::core::result::Result<S::Ok, S::Error>
            where
                S: $crate::__private::Serializer,
            {
                match self {
                    $(Self::$service(response) => $crate::__private::Serialize::serialize(response, serializer)),+
                }
            }
        }

        impl ProfuseGwResponse {
            /// The sole production HTTP adapter projection. The core response
            /// remains transport-independent and supplies only `Serialize`.
            #[doc(hidden)]
            pub fn __encode_profusegw_http1(
                &self,
            ) -> ::core::result::Result<
                ::std::vec::Vec<u8>,
                $crate::__private::serde_json::Error,
            > {
                match self {
                    $(Self::$service(response) => $crate::__private::encode_profusegw_http1(response)),+
                }
            }
        }

        const _: () = $crate::__private::assert_unique_code_registries(&[
            <$result_code as $crate::ingress::ProfuseGwCode>::REGISTERED_CODES,
        ]);

        #[derive(Clone, Copy, Debug, Eq, PartialEq)]
        pub enum ProfuseGwDispatch {
            $($service),+
        }

        $(
            pub struct $service;
            impl $service {
                pub const OPERATION_TYPE: &'static str = $operation_type;
            }

            const _: fn() = || {
                fn handler_shape<F, Fut>(_: F)
                where
                    F: Fn(
                        $request,
                        $crate::ingress::ProfuseGwContext,
                        $capability,
                        $crate::BusinessConfig<$business_config>,
                    ) -> Fut,
                    Fut: ::core::future::Future<
                        Output = $crate::ingress::ProfuseGwResponse<$response, $result_code>,
                    >,
                {}
                handler_shape($handler);

                fn declared_use<F>()
                where
                    F: __SaddleDeclaredExternalFunction,
                {}
                $(declared_use::<$uses>();)+
            };
        )+
    };
    ($($invalid:tt)*) => {
        compile_error!("skill.schema.unsupported");
    };
}