Skip to main content

appcore_sdk/
prepared.rs

1// =============================================================================
2//        #######
3//     ###       ###     F: prepared.rs
4//    ##   ## ##   ##    P: AppCore-Runtime
5//         ## ##
6//                       C: 2026/09/04 00:00:00 by dnettoRaw
7//    ##   ## ##   ##    U: 2026/09/04 00:00:00 by dnettoRaw
8//      ###########      S: 1.0.0-rc.1
9// =============================================================================
10
11//! Validated bridge from application-owned behavior to Runtime registries.
12//!
13//! Use this module after manifests and any deployment bindings have been
14//! validated, but before a deployment starts providers or workers. The value
15//! owns registries and callbacks, is intentionally not cloneable, and performs
16//! no I/O. `appcore-sdk` implements the bridge over `appcore-core`; a host may
17//! consume its parts without making Core depend on the SDK.
18
19#[cfg(feature = "scheduler")]
20use crate::ApplicationTaskRegistry;
21use crate::{AppResult, Application};
22#[cfg(feature = "api")]
23use appcore_api::ApiRouter;
24use appcore_contracts::{ApplicationManifestV1, DeploymentManifestV1};
25use appcore_core::{
26    AppFamily, AppId, AppPlugin, CommandBus, CommandRegistry, DecisionEngine, DecisionRegistry,
27    EventRegistry, NodeId, RuntimeBuilder, RuntimeContractVersion, RuntimeIdentity,
28    RuntimeInstance, RuntimeResult, StateRegistry, SyncGroup,
29};
30
31/// Application behavior prepared for an explicit deployment boundary.
32///
33/// This value owns only in-memory registries and callbacks. It does not own a
34/// listener, provider, worker or process lifecycle. Deployments may inspect the
35/// registrations and then connect the independently owned capability crates.
36pub struct PreparedApplication {
37    runtime: RuntimeInstance,
38    #[cfg(feature = "api")]
39    queries: ApiRouter,
40    #[cfg(feature = "scheduler")]
41    tasks: ApplicationTaskRegistry,
42}
43
44impl std::fmt::Debug for PreparedApplication {
45    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
46        formatter
47            .debug_struct("PreparedApplication")
48            .field("runtime", &self.runtime)
49            .finish_non_exhaustive()
50    }
51}
52
53impl PreparedApplication {
54    pub(crate) fn new<A>(
55        manifest: ApplicationManifestV1,
56        deployment: &DeploymentManifestV1,
57        application: &A,
58        node_id: NodeId,
59    ) -> AppResult<Self>
60    where
61        A: Application + ?Sized,
62    {
63        let adapter = ApplicationPlugin::new(manifest, deployment, application)?;
64        let mut builder = RuntimeBuilder::new();
65        builder.with_plugin(&adapter, node_id)?;
66        let runtime = builder.build()?;
67
68        #[cfg(feature = "api")]
69        let queries = {
70            let mut router = ApiRouter::new();
71            application.register_queries(&mut router)?;
72            router.freeze_queries();
73            router
74        };
75
76        #[cfg(feature = "scheduler")]
77        let tasks = {
78            let mut registry = ApplicationTaskRegistry::new();
79            application.register_tasks(&mut registry)?;
80            registry
81        };
82
83        Ok(Self {
84            runtime,
85            #[cfg(feature = "api")]
86            queries,
87            #[cfg(feature = "scheduler")]
88            tasks,
89        })
90    }
91
92    /// Returns the immutable Core runtime and its registered behavior.
93    pub fn runtime(&self) -> &RuntimeInstance {
94        &self.runtime
95    }
96
97    /// Returns the frozen query router prepared for an API host.
98    #[cfg(feature = "api")]
99    pub fn queries(&self) -> &ApiRouter {
100        &self.queries
101    }
102
103    /// Returns the bounded task definitions prepared for a scheduler integration.
104    #[cfg(feature = "scheduler")]
105    pub fn tasks(&self) -> &ApplicationTaskRegistry {
106        &self.tasks
107    }
108
109    /// Transfers every prepared registry to a composition root.
110    #[cfg(not(any(feature = "api", feature = "scheduler")))]
111    pub fn into_parts(self) -> RuntimeInstance {
112        self.runtime
113    }
114
115    /// Transfers every prepared registry to a composition root.
116    #[cfg(all(feature = "api", not(feature = "scheduler")))]
117    pub fn into_parts(self) -> (RuntimeInstance, ApiRouter) {
118        (self.runtime, self.queries)
119    }
120
121    /// Transfers every prepared registry to a composition root.
122    #[cfg(all(not(feature = "api"), feature = "scheduler"))]
123    pub fn into_parts(self) -> (RuntimeInstance, ApplicationTaskRegistry) {
124        (self.runtime, self.tasks)
125    }
126
127    /// Transfers every prepared registry to a composition root.
128    #[cfg(all(feature = "api", feature = "scheduler"))]
129    pub fn into_parts(self) -> (RuntimeInstance, ApiRouter, ApplicationTaskRegistry) {
130        (self.runtime, self.queries, self.tasks)
131    }
132}
133
134struct ApplicationPlugin<'a, A: Application + ?Sized> {
135    application: &'a A,
136    manifest: ApplicationManifestV1,
137    app_id: AppId,
138    app_family: AppFamily,
139    sync_group: SyncGroup,
140    runtime_contract: RuntimeContractVersion,
141}
142
143impl<'a, A: Application + ?Sized> ApplicationPlugin<'a, A> {
144    fn new(
145        manifest: ApplicationManifestV1,
146        deployment: &DeploymentManifestV1,
147        application: &'a A,
148    ) -> RuntimeResult<Self> {
149        let application_id = manifest.application_id().as_str();
150        let protocol = manifest
151            .runtime_requirements()
152            .protocol_version()
153            .parse::<u16>()
154            .map_err(|_| appcore_core::RuntimeError::IncompatibleRuntimeContract)?;
155        Ok(Self {
156            application,
157            app_id: AppId::new(application_id)?,
158            app_family: AppFamily::new(application_id)?,
159            sync_group: SyncGroup::new(deployment.installation_id().as_str())?,
160            runtime_contract: RuntimeContractVersion::new(protocol),
161            manifest,
162        })
163    }
164}
165
166impl<A: Application + ?Sized> AppPlugin for ApplicationPlugin<'_, A> {
167    fn application_manifest(&self) -> ApplicationManifestV1 {
168        self.manifest.clone()
169    }
170
171    fn identity(&self, node_id: NodeId) -> RuntimeIdentity {
172        RuntimeIdentity {
173            app_id: self.app_id.clone(),
174            app_family: self.app_family.clone(),
175            sync_group: self.sync_group.clone(),
176            runtime_contract: self.runtime_contract,
177            node_id,
178        }
179    }
180
181    fn register_commands(&self, registry: &mut CommandRegistry) -> RuntimeResult<()> {
182        self.application.register_commands(registry)
183    }
184
185    fn register_events(&self, registry: &mut EventRegistry) -> RuntimeResult<()> {
186        self.application.register_events(registry)
187    }
188
189    fn register_states(&self, registry: &mut StateRegistry) -> RuntimeResult<()> {
190        self.application.register_states(registry)
191    }
192
193    fn register_decisions(&self, registry: &mut DecisionRegistry) -> RuntimeResult<()> {
194        self.application.register_decisions(registry)
195    }
196
197    fn register_decision_nodes(&self, engine: &mut DecisionEngine) -> RuntimeResult<()> {
198        self.application.register_decision_nodes(engine)
199    }
200
201    fn register_handlers(&self, bus: &mut CommandBus) -> RuntimeResult<()> {
202        self.application.register_handlers(bus)
203    }
204}
205
206#[cfg(test)]
207mod tests {
208    use super::*;
209    use crate::application::{CommandName, CommandRegistry};
210    use crate::App;
211
212    struct DuplicateCommands;
213
214    impl Application for DuplicateCommands {
215        fn register_commands(&self, registry: &mut CommandRegistry) -> RuntimeResult<()> {
216            registry.register(CommandName::new("duplicate.command")?)?;
217            registry.register(CommandName::new("duplicate.command")?)
218        }
219    }
220
221    #[test]
222    fn registration_failure_is_preserved() {
223        let app = App::new("duplicate-app").expect("application defaults");
224        let error = app
225            .prepare(
226                &DuplicateCommands,
227                NodeId::new("duplicate-node").expect("node identity"),
228            )
229            .expect_err("duplicate registration must fail");
230        assert!(matches!(error, crate::AppError::Runtime(_)));
231    }
232}