Skip to main content

appcore_sdk/
simple_app.rs

1// =============================================================================
2//        #######
3//     ###       ###     F: simple_app.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//! Minimal local application context and canonical zero-config manifests.
12//!
13//! A manifest is always part of an `AppCore` application contract. Files are not
14//! required for the smallest local program: this module constructs the same V1
15//! contract values that a manifest reader validates, then exposes them for
16//! inspection or replacement before execution.
17
18use crate::{AppError, AppResult, Application, PreparedApplication};
19use appcore_contracts::{
20    ApplicationId, ApplicationManifestV1, DeploymentManifestV1, InstallationId, NetworkConfig,
21    ProviderConfig, ProviderId, RuntimeMode, RuntimeRequirements, ServiceId,
22};
23use appcore_core::AppId;
24use appcore_core::NodeId;
25use appcore_log::{ConfiguredLogger, LogBuilder, LoggerConfig};
26use std::time::{SystemTime, UNIX_EPOCH};
27
28const DEFAULT_APPLICATION_VERSION: &str = "0.1.0";
29const DEFAULT_RUNTIME_VERSION: &str = "1.0.0";
30const DEFAULT_PROTOCOL_VERSION: &str = "1";
31const DEFAULT_VENDOR: &str = "local";
32const DEFAULT_STORAGE_PROVIDER: &str = "file";
33const DEFAULT_TRANSPORT_PROVIDER: &str = "http";
34
35/// A small local application context with effective validated manifests.
36///
37/// `App::new` creates a standalone, local-only deployment: no listener,
38/// cluster, gateway, peer RPC, AI, storage path or external service is started
39/// implicitly. The default storage and transport provider identifiers exist in
40/// the deployment contract only; an application-owned deployment selects their
41/// implementation when it later opts into explicit manifest execution.
42pub struct App {
43    id: AppId,
44    application_manifest: ApplicationManifestV1,
45    deployment_manifest: DeploymentManifestV1,
46    logger: ConfiguredLogger,
47    logger_component: String,
48}
49
50impl std::fmt::Debug for App {
51    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
52        formatter
53            .debug_struct("App")
54            .field("id", &self.id)
55            .field("application_manifest", &self.application_manifest)
56            .field("deployment_manifest", &self.deployment_manifest)
57            .finish_non_exhaustive()
58    }
59}
60
61impl App {
62    /// Creates a local application with validated V1 standalone defaults.
63    ///
64    /// The resulting manifests are equivalent to the minimal canonical
65    /// contracts, not a second `SDK`-specific configuration format.
66    pub fn new(name: &str) -> AppResult<Self> {
67        let id = AppId::new(name)?;
68        let application_manifest = default_application_manifest(name)?;
69        let deployment_manifest = default_deployment_manifest(name)?;
70        Self::from_manifests(id, application_manifest, deployment_manifest)
71    }
72
73    /// Replaces the application manifest after normal contract validation.
74    ///
75    /// Explicit configuration always wins over `SDK` defaults. Invalid input is
76    /// returned unchanged as an error and is never silently replaced.
77    pub fn application_manifest(mut self, manifest: ApplicationManifestV1) -> AppResult<Self> {
78        manifest.validate()?;
79        self.application_manifest = manifest;
80        self.ensure_manifest_identity()?;
81        Ok(self)
82    }
83
84    /// Replaces the deployment manifest after normal contract validation.
85    ///
86    /// An explicit deployment never inherits cluster, provider or networking
87    /// values from the `SDK` default; it entirely owns installation policy.
88    pub fn deployment_manifest(mut self, manifest: DeploymentManifestV1) -> AppResult<Self> {
89        manifest.validate()?;
90        self.deployment_manifest = manifest;
91        self.ensure_manifest_identity()?;
92        Ok(self)
93    }
94
95    /// Returns the validated application-owned manifest currently in effect.
96    pub fn effective_application_manifest(&self) -> &ApplicationManifestV1 {
97        &self.application_manifest
98    }
99
100    /// Returns the validated installation-owned manifest currently in effect.
101    pub fn effective_deployment_manifest(&self) -> &DeploymentManifestV1 {
102        &self.deployment_manifest
103    }
104
105    /// Returns the validated application identifier.
106    pub fn id(&self) -> &AppId {
107        &self.id
108    }
109
110    /// Selects explicit bounded logging destinations for this application.
111    ///
112    /// File, terminal, combined, disabled and crash-only modes are provided by
113    /// [`crate::logging::LoggerConfig`]. Invalid limits fail during setup.
114    pub fn logging(mut self, config: LoggerConfig) -> AppResult<Self> {
115        self.logger = config.build()?;
116        Ok(self)
117    }
118
119    /// Emits one informational message through `AppCore`'s redacting logger.
120    ///
121    /// Logging is an observability side effect; setup and business failures
122    /// must still be returned by the caller's callback.
123    pub fn log(&self, message: &str) {
124        self.logger().info(message);
125    }
126
127    /// Returns a fluent logger scoped to this application.
128    ///
129    /// Use `app.logger().info("started")` for an explicit severity, or add
130    /// `.component("sync").verbosity(7)` before the final severity method.
131    pub fn logger(&self) -> LogBuilder<'_> {
132        self.logger
133            .dispatcher()
134            .event(now_ms(), self.logger_component.as_str())
135    }
136
137    /// Collects an [`Application`]'s behavior into executable Core registries.
138    ///
139    /// Preparation performs no I/O and starts no service. It validates and
140    /// freezes registrations so an explicit deployment can inspect or execute
141    /// them without importing `RuntimeBuilder`.
142    ///
143    /// # Errors
144    ///
145    /// Returns the exact controlled Runtime error produced by a registration
146    /// hook, an invalid node identity or inconsistent decision registration.
147    ///
148    /// # Examples
149    ///
150    /// ```
151    /// use appcore_sdk::application::NodeId;
152    /// use appcore_sdk::{App, Application, AppResult};
153    ///
154    /// struct Business;
155    /// impl Application for Business {}
156    ///
157    /// # fn example() -> AppResult<()> {
158    /// let app = App::new("prepared-example")?;
159    /// let prepared = app.prepare(&Business, NodeId::new("local-node")?)?;
160    /// assert!(prepared.runtime().commands().is_empty());
161    /// # Ok(())
162    /// # }
163    /// ```
164    pub fn prepare<A>(&self, application: &A, node_id: NodeId) -> AppResult<PreparedApplication>
165    where
166        A: Application + ?Sized,
167    {
168        PreparedApplication::new(
169            self.application_manifest.clone(),
170            &self.deployment_manifest,
171            application,
172            node_id,
173        )
174    }
175
176    /// Applies resolved deployment bindings and then prepares application behavior.
177    ///
178    /// This is the integration boundary for an explicit deployment. The SDK
179    /// neither resolves the supplied bindings nor retains their secret values.
180    ///
181    /// # Errors
182    ///
183    /// Returns the controlled error from `Application::configure` or from any
184    /// subsequent registration hook.
185    #[cfg(feature = "deployment")]
186    pub fn prepare_with_deployment<A>(
187        &self,
188        application: &A,
189        node_id: NodeId,
190        deployment: &crate::DeploymentContext,
191    ) -> AppResult<PreparedApplication>
192    where
193        A: Application + ?Sized,
194    {
195        application.configure(deployment)?;
196        self.prepare(application, node_id)
197    }
198
199    /// Persists the bounded crash ring when crash-only logging is configured.
200    ///
201    /// Other output modes return zero without creating a file.
202    pub fn dump_crash_log(&self) -> AppResult<usize> {
203        Ok(self.logger.dump_crash()?)
204    }
205
206    /// Runs a local callback using the effective validated manifests.
207    ///
208    /// This deliberately does not create a hidden host. When an application
209    /// needs provider composition or long-running services, it owns an explicit
210    /// deployment process; the same manifest values can then be serialized.
211    pub fn run<F>(self, configure: F) -> AppResult<()>
212    where
213        F: FnOnce(&App) -> AppResult<()>,
214    {
215        configure(&self)
216    }
217
218    fn from_manifests(
219        id: AppId,
220        application_manifest: ApplicationManifestV1,
221        deployment_manifest: DeploymentManifestV1,
222    ) -> AppResult<Self> {
223        let logger_component = format!("application.{}", id.as_str());
224        let app = Self {
225            id,
226            application_manifest,
227            deployment_manifest,
228            logger: LoggerConfig::default().build()?,
229            logger_component,
230        };
231        app.ensure_manifest_identity()?;
232        Ok(app)
233    }
234
235    fn ensure_manifest_identity(&self) -> AppResult<()> {
236        if self.application_manifest.application_id() != self.deployment_manifest.application_id()
237            || self.application_manifest.application_id().as_str() != self.id.as_str()
238        {
239            return Err(AppError::ManifestIdentityMismatch);
240        }
241        Ok(())
242    }
243}
244
245/// Runs a local application callback with canonical standalone defaults.
246///
247/// # Errors
248///
249/// Returns identifier or manifest-validation errors, and preserves the exact
250/// error from `configure`. It never starts background services or suppresses
251/// failures.
252pub fn run<F>(name: &str, configure: F) -> AppResult<()>
253where
254    F: FnOnce(&App) -> AppResult<()>,
255{
256    App::new(name)?.run(configure)
257}
258
259fn default_application_manifest(name: &str) -> AppResult<ApplicationManifestV1> {
260    Ok(ApplicationManifestV1::new(
261        ApplicationId::new(name)?,
262        DEFAULT_APPLICATION_VERSION,
263        name,
264        DEFAULT_VENDOR,
265        ServiceId::new(format!("{name}.local"))?,
266        RuntimeRequirements::new(DEFAULT_RUNTIME_VERSION, DEFAULT_PROTOCOL_VERSION)?,
267    )?)
268}
269
270fn default_deployment_manifest(name: &str) -> AppResult<DeploymentManifestV1> {
271    Ok(DeploymentManifestV1::builder(
272        InstallationId::new(format!("{name}-local"))?,
273        ApplicationId::new(name)?,
274        RuntimeMode::Standalone,
275        ProviderConfig::new(ProviderId::new(DEFAULT_STORAGE_PROVIDER)?),
276        NetworkConfig::new(
277            ProviderId::new(DEFAULT_TRANSPORT_PROVIDER)?,
278            ProviderId::new(DEFAULT_TRANSPORT_PROVIDER)?,
279        ),
280    )
281    .build()?)
282}
283
284fn now_ms() -> u64 {
285    SystemTime::now()
286        .duration_since(UNIX_EPOCH)
287        .map(|duration| duration.as_millis().try_into().unwrap_or(u64::MAX))
288        .unwrap_or_default()
289}
290
291#[cfg(test)]
292mod tests {
293    use super::*;
294
295    #[test]
296    fn zero_config_uses_validated_standalone_manifests() {
297        let app = App::new("hello-sdk").expect("defaults are valid");
298        assert_eq!(
299            app.effective_deployment_manifest().mode(),
300            RuntimeMode::Standalone
301        );
302        app.effective_application_manifest()
303            .validate()
304            .expect("application manifest validates");
305        app.effective_deployment_manifest()
306            .validate()
307            .expect("deployment manifest validates");
308    }
309
310    #[test]
311    fn application_accepts_disabled_logging_without_a_sink() {
312        let app = App::new("quiet-sdk")
313            .unwrap()
314            .logging(LoggerConfig {
315                output: appcore_log::LogOutputMode::Disabled,
316                ..LoggerConfig::default()
317            })
318            .unwrap();
319
320        app.log("this performs no sink work");
321        assert!(app.logger.dump_crash().is_ok_and(|written| written == 0));
322    }
323
324    #[test]
325    fn callback_receives_validated_identity() {
326        run("hello-sdk", |app| {
327            assert_eq!(app.id().as_str(), "hello-sdk");
328            Ok(())
329        })
330        .expect("run succeeds");
331    }
332
333    #[test]
334    fn invalid_identity_is_returned() {
335        assert!(run("", |_| Ok(())).is_err());
336    }
337
338    #[test]
339    fn explicit_manifest_identity_mismatch_is_not_masked_by_defaults() {
340        let other = App::new("other-sdk").expect("other defaults");
341        let error = App::new("hello-sdk")
342            .expect("hello defaults")
343            .application_manifest(other.effective_application_manifest().clone())
344            .expect_err("explicit application identity must win and fail");
345        assert_eq!(error, AppError::ManifestIdentityMismatch);
346    }
347
348    #[test]
349    fn explicit_deployment_replaces_the_standalone_default() {
350        let deployment = DeploymentManifestV1::builder(
351            InstallationId::new("hello-sdk-explicit").expect("installation identity"),
352            ApplicationId::new("hello-sdk").expect("application identity"),
353            RuntimeMode::Standalone,
354            ProviderConfig::new(ProviderId::new("memory").expect("storage provider")),
355            NetworkConfig::new(
356                ProviderId::new("loopback").expect("peer transport"),
357                ProviderId::new("loopback").expect("command transport"),
358            ),
359        )
360        .build()
361        .expect("explicit deployment");
362        let app = App::new("hello-sdk")
363            .expect("target defaults")
364            .deployment_manifest(deployment)
365            .expect("matching explicit deployment");
366        assert_eq!(
367            app.effective_deployment_manifest()
368                .installation_id()
369                .as_str(),
370            "hello-sdk-explicit"
371        );
372        assert_eq!(
373            app.effective_deployment_manifest().mode(),
374            RuntimeMode::Standalone
375        );
376    }
377}