1use 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
35pub 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 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 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 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 pub fn effective_application_manifest(&self) -> &ApplicationManifestV1 {
97 &self.application_manifest
98 }
99
100 pub fn effective_deployment_manifest(&self) -> &DeploymentManifestV1 {
102 &self.deployment_manifest
103 }
104
105 pub fn id(&self) -> &AppId {
107 &self.id
108 }
109
110 pub fn logging(mut self, config: LoggerConfig) -> AppResult<Self> {
115 self.logger = config.build()?;
116 Ok(self)
117 }
118
119 pub fn log(&self, message: &str) {
124 self.logger().info(message);
125 }
126
127 pub fn logger(&self) -> LogBuilder<'_> {
132 self.logger
133 .dispatcher()
134 .event(now_ms(), self.logger_component.as_str())
135 }
136
137 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 #[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 pub fn dump_crash_log(&self) -> AppResult<usize> {
203 Ok(self.logger.dump_crash()?)
204 }
205
206 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
245pub 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}