You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@maka.apache.org by wy...@apache.org on 2026/10/15 17:05:16 UTC
(maka) branch rust-preview updated: perf(runtime): reuse prepared deployment snapshots during startup
This is an automated email from the ASF dual-hosted git repository.
M4n5ter pushed a commit to branch rust-preview
in repository https://gitbox.apache.org/repos/asf/maka.git
The following commit(s) were added to refs/heads/rust-preview by this push:
new 457e6220e9 perf(runtime): reuse prepared deployment snapshots during startup
457e6220e9 is described below
commit 457e6220e93f474b5ad05c71383583078f2addde
Author: Wang <m4...@gmail.com>
AuthorDate: Fri Oct 16 01:05:02 2026 +0800
perf(runtime): reuse prepared deployment snapshots during startup
Carry checked package selections and plans from product authoring through definite commits into Host and UI startup. Keep disk recovery validation, exact original revision comparisons, current head selection, Root ownership checks, and per-source document budgets.
Validated with 341 affected nextest tests, all-target clippy, formatting, and real PTY initialization and partial-commit recovery. Five alternating default debug TUI runs reduced fresh Root median startup from 26.20s to 15.36s (before 26.17-26.51s, after 15.29-15.48s), with valid frames and clean Root release.
Generated-by: Codex
---
platform/event-log/src/applications.rs | 115 +++++++-
platform/event-log/src/applications/tests.rs | 194 +++++++++++++
platform/host-runtime/src/application.rs | 17 +-
platform/host-runtime/src/application/host.rs | 26 +-
platform/transport/src/connections.rs | 33 ++-
platform/transport/tests/owners.rs | 94 ++++++
products/maka/cli/src/application.rs | 19 +-
products/maka/cli/src/application/product.rs | 38 ++-
.../maka/cli/src/application/product/headless.rs | 161 +++++++++--
.../maka/cli/src/application/product/launch.rs | 319 ++++++++++++---------
.../cli/src/application/product/launch/tests.rs | 56 +++-
.../cli/src/application/product/test_public.rs | 8 +-
12 files changed, 863 insertions(+), 217 deletions(-)
diff --git a/platform/event-log/src/applications.rs b/platform/event-log/src/applications.rs
index 70f7f10824..896374b7f9 100644
--- a/platform/event-log/src/applications.rs
+++ b/platform/event-log/src/applications.rs
@@ -47,7 +47,45 @@ use uuid::Uuid;
const MAX_JSON: usize = MAX_DOCUMENT_BYTES;
-/// One read transaction captures the source and every immutable byte it selects.
+/// Immutable source, bytes and plan checked together before persistence.
+/// This value carries no Root authority and is not evidence of a committed revision.
+pub struct PreparedApplication {
+ input: Input,
+ observations: Vec<RemoteObservation>,
+ packages: Vec<Package>,
+ plan: Plan,
+}
+impl PreparedApplication {
+ pub fn new(
+ input: Input,
+ observations: Vec<RemoteObservation>,
+ packages: Vec<Package>,
+ ) -> Result<Self, StoreError> {
+ check_document(
+ &input,
+ &observations,
+ packages.iter().map(Package::application_ref).collect(),
+ )?;
+ let plan = validate(&input, &observations, &packages)?;
+ Ok(Self {
+ input,
+ observations,
+ packages,
+ plan,
+ })
+ }
+ pub fn input(&self) -> &Input {
+ &self.input
+ }
+ pub fn remote_exports(&self) -> &[RemoteObservation] {
+ &self.observations
+ }
+ pub fn packages(&self) -> &[Package] {
+ &self.packages
+ }
+}
+
+/// Exact committed source and immutable bytes, checked together with its plan.
pub struct LoadedDeployment {
source: Deployment,
packages: Vec<Package>,
@@ -181,19 +219,43 @@ pub fn validate_application(
}
/// Check several sources against the same immutable package set. Each source
-/// keeps its own document budget, remote observations and resulting plan.
-pub fn validate_applications(
+/// keeps its own document budget, selected packages, observations and plan.
+pub fn prepare_applications(
sources: &[(&Input, &[RemoteObservation])],
bytes: &[Package],
-) -> Result<Vec<Plan>, StoreError> {
- let references: Vec<_> = bytes.iter().map(Package::application_ref).collect();
+) -> Result<Vec<PreparedApplication>, StoreError> {
for (input, observations) in sources {
- check_document(input, observations, references.clone())?;
+ // Reject oversized source data before planning. Package references are
+ // counted after selection: other sources' packages are not persisted here.
+ check_document(input, observations, Vec::new())?;
}
let packages = validate_packages(bytes)?;
sources
.iter()
- .map(|(input, observations)| validate_plan(input, observations, &packages))
+ .map(|(input, observations)| {
+ let plan = validate_plan(input, observations, &packages)?;
+ let required: BTreeSet<_> = plan
+ .instances()
+ .values()
+ .map(|instance| &instance.package)
+ .collect();
+ let selected: Vec<_> = bytes
+ .iter()
+ .filter(|package| required.contains(&package.application_ref()))
+ .cloned()
+ .collect();
+ check_document(
+ input,
+ observations,
+ selected.iter().map(Package::application_ref).collect(),
+ )?;
+ Ok(PreparedApplication {
+ input: (*input).clone(),
+ observations: observations.to_vec(),
+ packages: selected,
+ plan,
+ })
+ })
.collect()
}
impl EventLog {
@@ -214,18 +276,36 @@ impl EventLog {
observations: Vec<RemoteObservation>,
bytes: Vec<Package>,
) -> Result<DeploymentRef, StoreError> {
+ let prepared = PreparedApplication::new(input, observations, bytes)?;
+ Ok(self
+ .commit_prepared_application(deployment, expected_revision, prepared)
+ .await?
+ .source
+ .reference)
+ }
+
+ /// A successful COMMIT binds the checked source to this exact live Root owner.
+ /// An unknown COMMIT outcome returns no executable snapshot; callers recover
+ /// using the original durable pending operation and normal storage validation.
+ pub async fn commit_prepared_application(
+ &self,
+ deployment: Uuid,
+ expected_revision: u64,
+ prepared: PreparedApplication,
+ ) -> Result<LoadedDeployment, StoreError> {
let domain = self.application_domain()?;
if deployment.is_nil() || expected_revision >= 9_007_199_254_740_991 {
return Err(invalid("invalid deployment or exhausted revision"));
}
- check_document(
- &input,
- &observations,
- bytes.iter().map(Package::application_ref).collect(),
- )?;
+ let PreparedApplication {
+ input,
+ observations,
+ packages: bytes,
+ plan,
+ } = prepared;
let encoded = encode(&input, MAX_JSON)?;
let remote = encode(&observations, MAX_JSON - encoded.len())?;
- validate(&input, &observations, &bytes)?;
+ let owner = std::sync::Arc::downgrade(self.root_owner.as_ref().expect("owned source Root"));
let commits = self.commits.clone();
self.connection.run(move |connection| Box::pin(async move {
let mut tx = connection.begin_with("BEGIN IMMEDIATE").await?;
@@ -241,7 +321,7 @@ impl EventLog {
.bind(&id).bind(revision as i64).bind(encoded).bind(remote).execute(&mut *tx).await?;
sqlx::query("INSERT INTO application_deployments VALUES (?, ?) ON CONFLICT(id) DO UPDATE SET revision=excluded.revision")
.bind(&id).bind(revision as i64).execute(&mut *tx).await?;
- for package in bytes {
+ for package in &bytes {
let reference = package.application_ref();
// Existing immutable content must match as well; never repair corruption by an overwrite.
let exists: bool = sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM application_packages WHERE id = ? AND revision = ?)")
@@ -262,7 +342,12 @@ impl EventLog {
}
tx.commit().await.map_err(StoreError::CommitUnknown)?;
commits.send_modify(|_| {});
- Ok(DeploymentRef { state_domain: domain, deployment, revision })
+ let reference = DeploymentRef { state_domain: domain, deployment, revision };
+ let snapshot = SourceSnapshot::new(owner, reference.clone(), input.environment.location, &plan);
+ Ok(LoadedDeployment {
+ source: Deployment { reference, input, remote_exports: observations },
+ packages: bytes, plan, snapshot,
+ })
})).await
}
diff --git a/platform/event-log/src/applications/tests.rs b/platform/event-log/src/applications/tests.rs
index c161d878df..31fd4ca73c 100644
--- a/platform/event-log/src/applications/tests.rs
+++ b/platform/event-log/src/applications/tests.rs
@@ -552,3 +552,197 @@ async fn checked_deployment_cannot_cross_root_owners() {
);
other.drain().await;
}
+
+#[tokio::test]
+async fn prepared_commit_preserves_exact_source_and_cas() {
+ let (_directory, store) = store().await;
+ let selected_package = package("export const value = 'selected';");
+ let extra_package = package("export const value = 'unused';");
+ let original = selected(&selected_package);
+ let prepared = prepare_applications(
+ &[(&original, &[])],
+ &[selected_package.clone(), extra_package],
+ )
+ .unwrap()
+ .pop()
+ .unwrap();
+ assert_eq!(prepared.packages().len(), 1);
+ assert_eq!(prepared.packages()[0].files(), selected_package.files());
+ let id = Uuid::new_v4();
+ let committed = store
+ .commit_prepared_application(id, 0, prepared)
+ .await
+ .unwrap();
+ committed.check_store(&store).unwrap();
+ assert_eq!(committed.source().reference.revision, 1);
+ assert_eq!(
+ serde_json::to_value(&committed.source().input).unwrap(),
+ serde_json::to_value(&original).unwrap()
+ );
+ let persisted = store.load_application(id).await.unwrap().unwrap();
+ assert_eq!(persisted.source().reference, committed.source().reference);
+ assert_eq!(
+ persisted.packages()[0].files(),
+ committed.packages()[0].files()
+ );
+ assert_eq!(
+ persisted.plan().instances().len(),
+ committed.plan().instances().len()
+ );
+ let stale = PreparedApplication::new(original, vec![], vec![selected_package]).unwrap();
+ assert!(matches!(
+ store.commit_prepared_application(id, 0, stale).await,
+ Err(StoreError::RevisionConflict { .. })
+ ));
+ assert_eq!(
+ store
+ .read_application_metadata(id)
+ .await
+ .unwrap()
+ .unwrap()
+ .source
+ .reference
+ .revision,
+ 1
+ );
+ store.drain().await;
+}
+
+#[tokio::test]
+async fn prepared_commit_snapshot_cannot_cross_reopened_root_lease() {
+ let (directory, original) = store().await;
+ let id = Uuid::new_v4();
+ let prepared = PreparedApplication::new(input(), vec![], vec![]).unwrap();
+ let loaded = original
+ .commit_prepared_application(id, 0, prepared)
+ .await
+ .unwrap();
+ loaded.check_store(&original).unwrap();
+ original.drain().await;
+ drop(original);
+ let namespaces = RootNamespaces {
+ ownership: directory.path().join("owners"),
+ control: directory.path().join("control"),
+ };
+ let reopened = EventLog::for_root(Arc::new(
+ RootOwner::open(&directory.path().join("root"), &namespaces).unwrap(),
+ ))
+ .await
+ .unwrap();
+ assert_eq!(
+ reopened.owned_root().unwrap().root_id(),
+ loaded.source().reference.state_domain
+ );
+ assert!(loaded.check_store(&reopened).is_err());
+ reopened
+ .load_application(id)
+ .await
+ .unwrap()
+ .unwrap()
+ .check_store(&reopened)
+ .unwrap();
+ reopened.drain().await;
+}
+
+#[tokio::test]
+async fn batch_budget_counts_each_sources_selected_packages() {
+ let (_directory, store) = store().await;
+ let first = package("export default 'first';");
+ let second = package("export default 'second';");
+ let mut source = selected(&first);
+ source
+ .instances
+ .get_mut("view")
+ .unwrap()
+ .configuration
+ .values
+ .insert("padding".into(), serde_json::json!(""));
+ let selected_refs = vec![first.application_ref()];
+ let overhead = serde_json::to_vec(&DeploymentDocument {
+ input: source.clone(),
+ remote_exports: vec![],
+ packages: selected_refs.clone(),
+ })
+ .unwrap()
+ .len();
+ source
+ .instances
+ .get_mut("view")
+ .unwrap()
+ .configuration
+ .values
+ .insert(
+ "padding".into(),
+ serde_json::json!("x".repeat(MAX_JSON - overhead)),
+ );
+ assert_eq!(
+ serde_json::to_vec(&DeploymentDocument {
+ input: source.clone(),
+ remote_exports: vec![],
+ packages: selected_refs,
+ })
+ .unwrap()
+ .len(),
+ MAX_JSON
+ );
+ validate_application(&source, &[], std::slice::from_ref(&first)).unwrap();
+ let pool = vec![first.clone(), second.clone()];
+ // An ordinary commit still counts every explicitly supplied package.
+ assert!(PreparedApplication::new(source.clone(), vec![], pool.clone()).is_err());
+ let other = selected(&second);
+ let mut prepared = prepare_applications(&[(&source, &[]), (&other, &[])], &pool).unwrap();
+ assert_eq!(prepared[0].packages().len(), 1);
+ assert_eq!(
+ prepared[0].packages()[0].application_ref(),
+ first.application_ref()
+ );
+ assert_eq!(
+ prepared[1].packages()[0].application_ref(),
+ second.application_ref()
+ );
+ let id = Uuid::new_v4();
+ let committed = store
+ .commit_prepared_application(id, 0, prepared.remove(0))
+ .await
+ .unwrap();
+ let loaded = store.load_application(id).await.unwrap().unwrap();
+ assert_eq!(loaded.source().reference, committed.source().reference);
+ assert_eq!(loaded.source().input, source);
+ assert_eq!(loaded.packages().len(), 1);
+ // Recovery decodes all immutable bytes again, then applies the same budget
+ // to each selected source instead of the union written in the pending record.
+ let recovered_pool: Vec<_> = pool
+ .iter()
+ .map(|package| Package::from_bundle(&package.to_bundle()).unwrap())
+ .collect();
+ let recovered =
+ prepare_applications(&[(&source, &[]), (&other, &[])], &recovered_pool).unwrap();
+ assert_eq!(
+ recovered[0].packages()[0].files(),
+ loaded.packages()[0].files()
+ );
+ let mut oversized = source;
+ let padding = oversized
+ .instances
+ .get_mut("view")
+ .unwrap()
+ .configuration
+ .values
+ .get_mut("padding")
+ .unwrap();
+ *padding = serde_json::json!(format!("{}x", padding.as_str().unwrap()));
+ assert!(validate_application(&oversized, &[], std::slice::from_ref(&first)).is_err());
+ assert!(prepare_applications(&[(&oversized, &[])], &pool).is_err());
+ assert_eq!(
+ store
+ .read_application_metadata(id)
+ .await
+ .unwrap()
+ .unwrap()
+ .source
+ .reference
+ .revision,
+ 1
+ );
+ store.drain().await;
+}
diff --git a/platform/host-runtime/src/application.rs b/platform/host-runtime/src/application.rs
index 9d82d99747..ac06b19ece 100644
--- a/platform/host-runtime/src/application.rs
+++ b/platform/host-runtime/src/application.rs
@@ -698,7 +698,7 @@ impl Application {
pub async fn start_from_store(
store: Arc<maka_event_log::EventLog>,
deployment: Uuid,
- mut native: NativeRegistry,
+ native: NativeRegistry,
issuer: Issuer,
policy: Arc<dyn Policy>,
scripts: Option<Arc<dyn backend::Factory>>,
@@ -708,6 +708,21 @@ impl Application {
.await
.map_err(|e| e.to_string())?
.ok_or("deployment not found")?;
+ Self::start_loaded(store, loaded, native, issuer, policy, scripts)
+ }
+
+ /// Start a committed snapshot belonging to the same live original Root.
+ pub fn start_loaded(
+ store: Arc<maka_event_log::EventLog>,
+ loaded: maka_event_log::applications::LoadedDeployment,
+ mut native: NativeRegistry,
+ issuer: Issuer,
+ policy: Arc<dyn Policy>,
+ scripts: Option<Arc<dyn backend::Factory>>,
+ ) -> Result<Self> {
+ loaded
+ .check_store(&store)
+ .map_err(|error| error.to_string())?;
// Persisted remote declarations are compatibility observations. This
// executor has no trusted remote transport and cannot turn them into grants.
if !loaded.source().remote_exports.is_empty() {
diff --git a/platform/host-runtime/src/application/host.rs b/platform/host-runtime/src/application/host.rs
index 9bda734bfd..e0cf22a635 100644
--- a/platform/host-runtime/src/application/host.rs
+++ b/platform/host-runtime/src/application/host.rs
@@ -124,6 +124,25 @@ impl Host {
selections: BTreeMap<String, HostEndpoint>,
grants: Vec<NativeGrant>,
options: Options,
+ ) -> Result<Arc<Self>> {
+ let loaded = store
+ .load_application(deployment)
+ .await
+ .map_err(|error| error.to_string())?
+ .ok_or("deployment not found")?;
+ Self::open_loaded_with_options(store, loaded, native, scripts, selections, grants, options)
+ .await
+ }
+
+ /// Open a checked committed source without rereading its immutable packages.
+ pub async fn open_loaded_with_options(
+ store: Arc<EventLog>,
+ loaded: maka_event_log::applications::LoadedDeployment,
+ native: NativeRegistry,
+ scripts: Option<Arc<dyn super::backend::Factory>>,
+ selections: BTreeMap<String, HostEndpoint>,
+ grants: Vec<NativeGrant>,
+ options: Options,
) -> Result<Arc<Self>> {
if options.handshake_timeout.is_zero()
|| options.handshake_timeout > Duration::from_secs(300)
@@ -136,15 +155,14 @@ impl Host {
}
let root = store.owned_root().map_err(|error| error.to_string())?;
let policy = Arc::new(PeerPolicy::with_native_grants(grants)?);
- let application = Application::start_from_store(
+ let application = Application::start_loaded(
store.clone(),
- deployment,
+ loaded,
with_gateway(native)?,
policy.issuer(),
policy.clone(),
scripts,
- )
- .await?;
+ )?;
if let Err(error) = Endpoints::start(&application.client(), &selections).await {
application.shutdown().await?;
return Err(error);
diff --git a/platform/transport/src/connections.rs b/platform/transport/src/connections.rs
index 6b8e19226e..10b82484ec 100644
--- a/platform/transport/src/connections.rs
+++ b/platform/transport/src/connections.rs
@@ -192,15 +192,44 @@ impl Connections {
configuration: Configuration,
namespaces: RootNamespaces,
helper: PathBuf,
- mut cohost_native: maka_host_runtime::application::NativeRegistry,
+ cohost_native: maka_host_runtime::application::NativeRegistry,
cohost_scripts: Option<Arc<dyn maka_host_runtime::application::backend::Factory>>,
) -> Result<Self> {
- configuration.validate()?;
let loaded = store
.load_application(deployment)
.await
.map_err(|e| e.to_string())?
.ok_or("UI deployment not found")?;
+ Self::prepare_loaded(
+ store,
+ loaded,
+ target,
+ configuration,
+ namespaces,
+ helper,
+ cohost_native,
+ cohost_scripts,
+ )
+ .await
+ }
+
+ /// Adopt one checked UI snapshot from the same live original Root owner.
+ #[allow(clippy::too_many_arguments)]
+ pub async fn prepare_loaded(
+ store: Arc<EventLog>,
+ loaded: maka_event_log::applications::LoadedDeployment,
+ target: PresentationTarget,
+ configuration: Configuration,
+ namespaces: RootNamespaces,
+ helper: PathBuf,
+ mut cohost_native: maka_host_runtime::application::NativeRegistry,
+ cohost_scripts: Option<Arc<dyn maka_host_runtime::application::backend::Factory>>,
+ ) -> Result<Self> {
+ loaded
+ .check_store(&store)
+ .map_err(|error| error.to_string())?;
+ configuration.validate()?;
+ let deployment = loaded.source().reference.deployment;
if loaded.source().input.environment.location != ExecutionLocation::Ui
|| loaded.source().input.environment.presentation != Some(target)
{
diff --git a/platform/transport/tests/owners.rs b/platform/transport/tests/owners.rs
index 00f08f52b8..d57f48d86d 100644
--- a/platform/transport/tests/owners.rs
+++ b/platform/transport/tests/owners.rs
@@ -387,3 +387,97 @@ Some(maka_host_js::factory(Default::default())),).await.unwrap();
drop(RootOwner::open(&root, &namespaces).unwrap());
}).await.unwrap();
}
+
+#[tokio::test]
+async fn loaded_ui_requires_its_live_original_root_owner() {
+ use maka_plugin_core::composition::PresentationTarget;
+ use maka_transport::Connections;
+ let directory = tempfile::tempdir().unwrap();
+ let namespaces = RootNamespaces {
+ ownership: directory.path().join("owners"),
+ control: directory.path().join("control"),
+ };
+ let path = directory.path().join("ui");
+ let original = Arc::new(
+ EventLog::for_root(Arc::new(RootOwner::create(&path, &namespaces).unwrap()))
+ .await
+ .unwrap(),
+ );
+ let other = Arc::new(
+ EventLog::for_root(Arc::new(
+ RootOwner::create(&directory.path().join("other"), &namespaces).unwrap(),
+ ))
+ .await
+ .unwrap(),
+ );
+ let input = serde_json::from_value(json!({
+ "environment":{"location":"ui","presentation":"tui"},"instances":{}
+ }))
+ .unwrap();
+ let id = uuid::Uuid::new_v4();
+ let reference = original
+ .commit_application(id, 0, input, vec![], vec![])
+ .await
+ .unwrap();
+ let foreign = original.load_application(id).await.unwrap().unwrap();
+ let error = Connections::prepare_loaded(
+ other.clone(),
+ foreign,
+ PresentationTarget::Tui,
+ Configuration::default(),
+ namespaces.clone(),
+ "unused-startup-helper".into(),
+ NativeRegistry::default(),
+ None,
+ )
+ .await
+ .err()
+ .unwrap();
+ assert!(error.contains("foreign original source Root"), "{error}");
+ let expired = original.load_application(id).await.unwrap().unwrap();
+ original.drain().await;
+ drop(original);
+ let reopened = Arc::new(
+ EventLog::for_root(Arc::new(RootOwner::open(&path, &namespaces).unwrap()))
+ .await
+ .unwrap(),
+ );
+ assert_eq!(
+ reopened.owned_root().unwrap().root_id(),
+ reference.state_domain
+ );
+ let error = Connections::prepare_loaded(
+ reopened.clone(),
+ expired,
+ PresentationTarget::Tui,
+ Configuration::default(),
+ namespaces.clone(),
+ "unused-startup-helper".into(),
+ NativeRegistry::default(),
+ None,
+ )
+ .await
+ .err()
+ .unwrap();
+ assert!(error.contains("original source Root has closed"), "{error}");
+ let current = reopened.load_application(id).await.unwrap().unwrap();
+ let mut connections = Connections::prepare_loaded(
+ reopened.clone(),
+ current,
+ PresentationTarget::Tui,
+ Configuration::default(),
+ namespaces,
+ "unused-startup-helper".into(),
+ NativeRegistry::default(),
+ None,
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ connections.take_initial().unwrap().source().reference,
+ reference
+ );
+ connections.drain().await;
+ reopened.drain().await;
+ other.drain().await;
+}
diff --git a/products/maka/cli/src/application.rs b/products/maka/cli/src/application.rs
index e92a85b987..44eb26b174 100644
--- a/products/maka/cli/src/application.rs
+++ b/products/maka/cli/src/application.rs
@@ -210,7 +210,18 @@ impl Command {
.transpose()?
.unwrap_or_default();
let store = Arc::new(open_store(args.root).await?);
- run_tui(store, args.deployment, configuration, None, Vec::new()).await?;
+ let loaded = match store.load_application(args.deployment).await {
+ Ok(Some(loaded)) => loaded,
+ Ok(None) => {
+ store.drain().await;
+ return Err("UI deployment not found".into());
+ }
+ Err(error) => {
+ store.drain().await;
+ return Err(error.into());
+ }
+ };
+ run_tui(store, loaded, configuration, None, Vec::new()).await?;
}
}
Ok(())
@@ -288,7 +299,7 @@ async fn open_store(root: PathBuf) -> Result<maka_event_log::EventLog, HostError
async fn run_tui(
store: Arc<maka_event_log::EventLog>,
- deployment: uuid::Uuid,
+ loaded: maka_event_log::applications::LoadedDeployment,
configuration: maka_transport::Configuration,
startup: Option<maka_render_terminal::startup::Startup>,
anchors: Vec<maka_host_runtime::application::host::Client>,
@@ -309,9 +320,9 @@ async fn run_tui(
return Err(error);
}
};
- let mut connections = match maka_transport::Connections::prepare(
+ let mut connections = match maka_transport::Connections::prepare_loaded(
store.clone(),
- deployment,
+ loaded,
PresentationTarget::Tui,
configuration,
namespaces,
diff --git a/products/maka/cli/src/application/product.rs b/products/maka/cli/src/application/product.rs
index d9e39e90ad..2bd31f240f 100644
--- a/products/maka/cli/src/application/product.rs
+++ b/products/maka/cli/src/application/product.rs
@@ -19,8 +19,8 @@
//! Product authoring loads checked packages from development output or release assets.
use super::{HostError, Input, Package, RemoteObservation, read_json};
use clap::{Args, ValueEnum};
+use maka_event_log::applications::PreparedApplication;
use maka_js_runtime::plugin::Vm;
-use maka_plugin_core::plan::Plan;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::{collections::BTreeMap, io::Write, path::PathBuf};
@@ -233,7 +233,7 @@ async fn author(
product: Product,
configuration: Value,
packages: &BTreeMap<String, Package>,
-) -> Result<(Sources, Value, Plan), HostError> {
+) -> Result<(Sources, Value, [PreparedApplication; 3]), HostError> {
let source = authoring()?;
verified_fingerprint(&source, packages, &bundle_fingerprint()?)?;
author_with_source(product, configuration, packages, &source).await
@@ -243,7 +243,7 @@ async fn author_with_source(
mut configuration: Value,
packages: &BTreeMap<String, Package>,
source: &str,
-) -> Result<(Sources, Value, Plan), HostError> {
+) -> Result<(Sources, Value, [PreparedApplication; 3]), HostError> {
let values = configuration
.as_object_mut()
.ok_or("installation configuration must be an object")?;
@@ -302,22 +302,12 @@ async fn author_with_source(
vm.shutdown().await;
let sources: Sources = serde_json::from_value(result?)?;
let checked: Vec<_> = packages.values().cloned().collect();
- let host_plan = maka_event_log::applications::validate_applications(
- &[
- (&sources.host, &[][..]),
- (&sources.management_host, &[][..]),
- (&sources.ui, sources.remote_exports.as_slice()),
- ],
- &checked,
- )?
- .into_iter()
- .next()
- .expect("validated Host plan");
+ let prepared = prepare_sources(&sources, &checked)?;
let connections: maka_transport::Configuration =
serde_json::from_value(sources.connections.clone())?;
connections.validate().map_err(HostError::from)?;
values.remove("packages");
- Ok((sources, configuration, host_plan))
+ Ok((sources, configuration, prepared))
}
fn export(
@@ -420,3 +410,21 @@ fn selected(
.cloned()
.collect())
}
+
+fn prepare_sources(
+ sources: &Sources,
+ packages: &[Package],
+) -> Result<[PreparedApplication; 3], HostError> {
+ let prepared = maka_event_log::applications::prepare_applications(
+ &[
+ (&sources.host, &[][..]),
+ (&sources.management_host, &[][..]),
+ (&sources.ui, sources.remote_exports.as_slice()),
+ ],
+ packages,
+ )?;
+ let prepared: [PreparedApplication; 3] = prepared
+ .try_into()
+ .unwrap_or_else(|_| unreachable!("three prepared product sources"));
+ Ok(prepared)
+}
diff --git a/products/maka/cli/src/application/product/headless.rs b/products/maka/cli/src/application/product/headless.rs
index 50ead7b80c..b6d732b50e 100644
--- a/products/maka/cli/src/application/product/headless.rs
+++ b/products/maka/cli/src/application/product/headless.rs
@@ -19,7 +19,11 @@
//! A public Host opens the same persisted product source across process restarts.
use super::{HostError, Input, Product, author, installation, launch, packages};
use base64::{Engine, engine::general_purpose::STANDARD};
-use maka_event_log::{EventLog, applications::launch::Launch, root::RootOwner};
+use maka_event_log::{
+ EventLog,
+ applications::{LoadedDeployment, PreparedApplication, launch::Launch},
+ root::RootOwner,
+};
use maka_host_runtime::{
DirectoryRootSpec,
application::{
@@ -61,22 +65,28 @@ struct Preparation {
pub(super) async fn save_product(
store: &EventLog,
deployment: Uuid,
- input: &Input,
- packages: &[super::Package],
+ prepared: PreparedApplication,
endpoints: BTreeMap<String, HostEndpoint>,
native: Vec<NativeGrant>,
) -> Result<(), HostError> {
+ if !prepared.remote_exports().is_empty() {
+ return Err("public Host cannot use remote observations".into());
+ }
let selection = serde_json::to_value(Selection::PublicHost { endpoints, native })?;
match store.application_launch().await? {
Some(record) => {
if record.deployment != deployment || record.configuration != selection {
return Err("original public Host selection changed".into());
}
+ // Existing pending bytes remain authoritative and must recover first.
+ prepare(store, Roots::Saved).await?;
+ launch::ensure_prepared(store, deployment, prepared).await?;
}
None => {
let preparation = Preparation {
- input: input.clone(),
- packages: packages
+ input: prepared.input().clone(),
+ packages: prepared
+ .packages()
.iter()
.map(|package| {
package
@@ -94,10 +104,12 @@ pub(super) async fn save_product(
pending: Some(serde_json::to_vec(&preparation)?),
})
.await?;
+ // The pending record is durable; keep the exact already checked bytes.
+ launch::ensure_prepared(store, deployment, prepared).await?;
+ store.complete_application_launch(deployment).await?;
}
}
- prepare(store, Roots::Saved).await?;
- launch::ensure(store, deployment, input, &[], packages).await
+ Ok(())
}
/// Bind an explicitly committed generic Host without reauthoring its source.
@@ -143,11 +155,10 @@ pub(crate) async fn open_host(
) -> Result<Arc<Host>, HostError> {
let store = Arc::new(maka_transport::open_store(Arc::new(owner)).await?);
let result = async {
- let (deployment, Selection::PublicHost { endpoints, native }) =
- prepare(&store, roots).await?;
- Ok(Host::open_with_options(
+ let (loaded, Selection::PublicHost { endpoints, native }) = prepare(&store, roots).await?;
+ Ok(Host::open_loaded_with_options(
store.clone(),
- deployment,
+ loaded,
crate::application::serve::native()?,
Some(maka_host_js::factory(Default::default())),
endpoints,
@@ -162,13 +173,21 @@ pub(crate) async fn open_host(
}
result
}
-async fn prepare(store: &EventLog, roots: Roots) -> Result<(Uuid, Selection), HostError> {
+async fn prepare(
+ store: &EventLog,
+ roots: Roots,
+) -> Result<(LoadedDeployment, Selection), HostError> {
if store.application_launch().await?.is_none() {
let initial = match &roots {
Roots::Saved => None,
Roots::Configured(roots) => roots.clone(),
};
- begin(store, initial).await?;
+ let (deployment, selection, prepared) = begin(store, initial).await?;
+ let loaded = store
+ .commit_prepared_application(deployment, 0, prepared)
+ .await?;
+ store.complete_application_launch(deployment).await?;
+ return Ok((loaded, selection));
}
let record = store
.application_launch()
@@ -185,9 +204,16 @@ async fn prepare(store: &EventLog, roots: Roots) -> Result<(Uuid, Selection), Ho
if let Roots::Configured(roots) = roots {
apply_directories(store, record.deployment, directories(roots)?).await?;
}
- Ok((record.deployment, selection))
+ let loaded = store
+ .load_application(record.deployment)
+ .await?
+ .ok_or("public Host source missing")?;
+ Ok((loaded, selection))
}
-async fn begin(store: &EventLog, roots: Option<Vec<DirectoryRootSpec>>) -> Result<(), HostError> {
+async fn begin(
+ store: &EventLog,
+ roots: Option<Vec<DirectoryRootSpec>>,
+) -> Result<(Uuid, Selection, PreparedApplication), HostError> {
let home = crate::serve::home_directory()?;
let roots = directories(roots)?;
let root = store.owned_root()?;
@@ -206,29 +232,21 @@ async fn begin(store: &EventLog, roots: Option<Vec<DirectoryRootSpec>>) -> Resul
.collect(),
);
let packages = tokio::task::spawn_blocking(packages).await??;
- let (sources, _, host_plan) = author(Product::Agent, configuration, &packages).await?;
+ let (sources, _, [prepared, _, _]) = author(Product::Agent, configuration, &packages).await?;
let connections: maka_transport::Configuration = serde_json::from_value(sources.connections)?;
let connection = connections
.hosts
.into_iter()
.find(|host| host.name == "local")
.ok_or("product public Host missing")?;
- let required: std::collections::BTreeSet<_> = host_plan
- .instances()
- .values()
- .map(|instance| &instance.package)
- .collect();
- let packages: Vec<_> = packages
- .into_values()
- .filter(|package| required.contains(&package.application_ref()))
- .collect();
let selection = Selection::PublicHost {
endpoints: connection.endpoints,
native: connection.native,
};
let preparation = Preparation {
- input: sources.host,
- packages: packages
+ input: prepared.input().clone(),
+ packages: prepared
+ .packages()
.iter()
.map(|package| {
package
@@ -242,11 +260,11 @@ async fn begin(store: &EventLog, roots: Option<Vec<DirectoryRootSpec>>) -> Resul
store
.begin_application_launch(Launch {
deployment: connection.deployment,
- configuration: serde_json::to_value(selection)?,
+ configuration: serde_json::to_value(&selection)?,
pending: Some(serde_json::to_vec(&preparation)?),
})
.await?;
- Ok(())
+ Ok((connection.deployment, selection, prepared))
}
async fn apply_directories(
@@ -356,6 +374,87 @@ fn configuration_values<'a>(
#[cfg(test)]
mod tests {
use super::*;
+ #[tokio::test]
+ async fn saved_product_checks_original_source_before_accepting_prepared_input() {
+ let directory = tempfile::tempdir().unwrap();
+ let store = launch::open(directory.path().join("host"), true, None)
+ .await
+ .unwrap();
+ let deployment = Uuid::new_v4();
+ let source: Input = serde_json::from_value(json!({
+ "environment":{"location":"host"},"instances":{}
+ }))
+ .unwrap();
+ let pending = Preparation {
+ input: source.clone(),
+ packages: vec![],
+ };
+ let configuration = serde_json::to_value(Selection::PublicHost {
+ endpoints: BTreeMap::new(),
+ native: vec![],
+ })
+ .unwrap();
+ store
+ .begin_application_launch(Launch {
+ deployment,
+ configuration: configuration.clone(),
+ pending: Some(serde_json::to_vec(&pending).unwrap()),
+ })
+ .await
+ .unwrap();
+ let mut changed = source.clone();
+ changed.environment.location = maka_plugin_core::composition::ExecutionLocation::Ui;
+ changed.environment.presentation =
+ Some(maka_plugin_core::composition::PresentationTarget::Tui);
+ let error = save_product(
+ &store,
+ deployment,
+ PreparedApplication::new(changed, vec![], vec![]).unwrap(),
+ BTreeMap::new(),
+ vec![],
+ )
+ .await
+ .err()
+ .unwrap();
+ assert!(error.to_string().contains("conflicts"), "{error}");
+ let stored = store.load_application(deployment).await.unwrap().unwrap();
+ assert_eq!(stored.source().reference.revision, 1);
+ assert_eq!(
+ serde_json::to_value(&stored.source().input).unwrap(),
+ serde_json::to_value(&source).unwrap()
+ );
+ assert_eq!(
+ store
+ .application_launch()
+ .await
+ .unwrap()
+ .unwrap()
+ .configuration,
+ configuration
+ );
+ save_product(
+ &store,
+ deployment,
+ PreparedApplication::new(source, vec![], vec![]).unwrap(),
+ BTreeMap::new(),
+ vec![],
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ store
+ .read_application_metadata(deployment)
+ .await
+ .unwrap()
+ .unwrap()
+ .source
+ .reference
+ .revision,
+ 1
+ );
+ store.drain().await;
+ }
+
#[tokio::test]
async fn public_host_resumes_original_source_and_starts_with_read_only_permissions() {
let directory = tempfile::tempdir().unwrap();
@@ -377,8 +476,9 @@ mod tests {
let record = store.application_launch().await.unwrap().unwrap();
assert!(record.pending.is_some());
let selected_id = record.deployment;
- let (deployment, Selection::PublicHost { endpoints, .. }) =
+ let (loaded, Selection::PublicHost { endpoints, .. }) =
prepare(&store, Roots::Saved).await.unwrap();
+ let deployment = loaded.source().reference.deployment;
assert_eq!(deployment, selected_id);
assert!(endpoints.contains_key("agent"));
assert!(
@@ -412,6 +512,7 @@ mod tests {
}));
let revision = original.source().reference.revision;
let (reopened, _) = prepare(&store, Roots::Saved).await.unwrap();
+ let reopened = reopened.source().reference.deployment;
assert_eq!(reopened, deployment);
assert_eq!(
store
diff --git a/products/maka/cli/src/application/product/launch.rs b/products/maka/cli/src/application/product/launch.rs
index 5b4fdff65b..7f3d095235 100644
--- a/products/maka/cli/src/application/product/launch.rs
+++ b/products/maka/cli/src/application/product/launch.rs
@@ -24,7 +24,7 @@ use base64::{Engine, engine::general_purpose::STANDARD};
use clap::Args;
use maka_event_log::{
EventLog,
- applications::launch::Launch as Record,
+ applications::{LoadedDeployment, PreparedApplication, launch::Launch as Record},
root::{RootNamespaces, RootOwner},
};
use maka_packages::Package;
@@ -81,6 +81,13 @@ pub(super) struct Preparation {
pub(super) packages: Vec<BTreeMap<String, String>>,
}
+struct PreparedLaunch {
+ deployment: Uuid,
+ configuration: Value,
+ preparation: Preparation,
+ applications: [PreparedApplication; 3],
+}
+
impl Launch {
pub(crate) async fn run(self) -> Result<(), HostError> {
if self.configuration.is_none()
@@ -117,7 +124,7 @@ impl Launch {
Ok(Some(selected))
}
}.await;
- let (deployment, configuration, anchors) = match result {
+ let (loaded, configuration, anchors) = match result {
Ok(Some(value)) => value,
Ok(None) => {
store.drain().await;
@@ -128,7 +135,7 @@ impl Launch {
return Err(error);
}
};
- run_tui(store, deployment, configuration, startup, anchors).await
+ run_tui(store, loaded, configuration, startup, anchors).await
}
}
async fn standard_configuration(
@@ -226,7 +233,7 @@ pub(super) async fn prepare(
product: Product,
) -> Result<
(
- Uuid,
+ LoadedDeployment,
Configuration,
Vec<maka_host_runtime::application::host::Client>,
),
@@ -241,126 +248,136 @@ pub(super) async fn prepare(
}
None => {
let configuration = configuration.ok_or("first launch requires --configuration")?;
- begin(store, configuration, product).await?;
- store
- .application_launch()
- .await?
- .ok_or("launcher record missing after commit")?
+ return finish(store, begin(store, configuration, product).await?).await;
}
};
- let mut connections: Configuration = serde_json::from_value(record.configuration.clone())?;
- let (root, domain, host, management) = targets(&connections)?;
+ let connections: Configuration = serde_json::from_value(record.configuration.clone())?;
+ let (root, domain, host, _) = targets(&connections)?;
if let Some(bytes) = record.pending {
- let preparation: Preparation = serde_json::from_slice(&bytes)?;
- if preparation
- .previous_connections
- .as_ref()
- .unwrap_or(&preparation.sources.connections)
- != &record.configuration
- {
- return Err("original launcher connection input changed".into());
- }
- let packages = decode_packages(preparation.packages)?;
- let host_packages = super::selected(&preparation.sources.host, &[], &packages)?;
- let management_packages =
- super::selected(&preparation.sources.management_host, &[], &packages)?;
- let ui_packages = super::selected(
- &preparation.sources.ui,
- &preparation.sources.remote_exports,
- &packages,
- )?;
+ let mut preparation: Preparation = serde_json::from_slice(&bytes)?;
+ let packages = decode_packages(std::mem::take(&mut preparation.packages))?;
+ let applications = super::prepare_sources(&preparation.sources, &packages)?;
+ return finish(
+ store,
+ PreparedLaunch {
+ deployment: record.deployment,
+ configuration: record.configuration,
+ preparation,
+ applications,
+ },
+ )
+ .await;
+ }
+ let public = super::public::Host::connect(root, domain, host).await?;
+ let loaded = store
+ .load_application(record.deployment)
+ .await?
+ .ok_or("UI source missing")?;
+ Ok((loaded, connections, vec![public.into_client()]))
+}
+
+async fn finish(
+ store: &EventLog,
+ prepared: PreparedLaunch,
+) -> Result<
+ (
+ LoadedDeployment,
+ Configuration,
+ Vec<maka_host_runtime::application::host::Client>,
+ ),
+ HostError,
+> {
+ let PreparedLaunch {
+ deployment,
+ configuration,
+ preparation,
+ applications: [host_source, management_source, ui_source],
+ } = prepared;
+ if preparation
+ .previous_connections
+ .as_ref()
+ .unwrap_or(&preparation.sources.connections)
+ != &configuration
+ {
+ return Err("original launcher connection input changed".into());
+ }
+ let mut connections: Configuration = serde_json::from_value(configuration)?;
+ let (root, domain, host, management) = targets(&connections)?;
+ let host_input = host_source.input().clone();
+ let host_packages = host_source.packages().to_vec();
+ if preparation.restore.is_empty() {
+ bootstrap_host(&root, &domain, host, &connections, host_source).await?;
+ }
+ let public = super::public::Host::connect(root.clone(), domain.clone(), host).await?;
+ let result = async {
if preparation.restore.is_empty() {
- bootstrap_host(
- &root,
- &domain,
- host,
- &connections,
- &preparation.sources.host,
- &host_packages,
- )
- .await?;
- }
- let public = super::public::Host::connect(root.clone(), domain.clone(), host).await?;
- let result = async {
- if preparation.restore.is_empty() {
- public
- .ensure_initial(&preparation.sources.host, &[], &host_packages)
- .await?;
- } else {
- let previous = host_configuration(&connections)?;
- let desired = host_configuration(&serde_json::from_value(
- preparation.sources.connections.clone(),
- )?)?;
- let configuration =
- if serde_json::to_value(&previous)? == serde_json::to_value(&desired)? {
- None
- } else {
- Some((previous, desired))
- };
- public
- .ensure_restore(
- *preparation
- .restore
- .get(&host)
- .ok_or("restore revision missing")?,
- &preparation.sources.host,
- &[],
- &host_packages,
- configuration,
- )
- .await?;
- }
- for (deployment, input, observations, packages) in [
- (
- management,
- &preparation.sources.management_host,
- &[][..],
- management_packages.as_slice(),
- ),
- (
- record.deployment,
- &preparation.sources.ui,
- preparation.sources.remote_exports.as_slice(),
- ui_packages.as_slice(),
- ),
- ] {
- if preparation.restore.is_empty() {
- ensure(store, deployment, input, observations, packages).await?;
+ public
+ .ensure_initial(&host_input, &[], &host_packages)
+ .await?;
+ } else {
+ let previous = host_configuration(&connections)?;
+ let desired = host_configuration(&serde_json::from_value(
+ preparation.sources.connections.clone(),
+ )?)?;
+ let configuration =
+ if serde_json::to_value(&previous)? == serde_json::to_value(&desired)? {
+ None
} else {
- super::restore::ensure(
- store,
- deployment,
- *preparation
- .restore
- .get(&deployment)
- .ok_or("restore revision missing")?,
- input,
- observations,
- packages,
- )
- .await?;
- }
- }
- if let Some(baseline) = preparation.product {
- store
- .complete_application_product(
- record.deployment,
- preparation.sources.connections.clone(),
- serde_json::to_value(baseline)?,
- )
- .await?;
- connections = serde_json::from_value(preparation.sources.connections.clone())?;
- } else {
- store.complete_application_launch(record.deployment).await?;
+ Some((previous, desired))
+ };
+ public
+ .ensure_restore(
+ *preparation
+ .restore
+ .get(&host)
+ .ok_or("restore revision missing")?,
+ &host_input,
+ &[],
+ &host_packages,
+ configuration,
+ )
+ .await?;
+ }
+ let loaded = if preparation.restore.is_empty() {
+ ensure_prepared(store, management, management_source).await?;
+ ensure_prepared(store, deployment, ui_source).await?
+ } else {
+ for (deployment, source) in [(management, management_source), (deployment, ui_source)] {
+ super::restore::ensure(
+ store,
+ deployment,
+ *preparation
+ .restore
+ .get(&deployment)
+ .ok_or("restore revision missing")?,
+ source.input(),
+ source.remote_exports(),
+ source.packages(),
+ )
+ .await?;
}
- Ok::<_, HostError>(())
+ store
+ .load_application(deployment)
+ .await?
+ .ok_or("UI source missing")?
+ };
+ if let Some(baseline) = preparation.product {
+ store
+ .complete_application_product(
+ deployment,
+ preparation.sources.connections.clone(),
+ serde_json::to_value(baseline)?,
+ )
+ .await?;
+ connections = serde_json::from_value(preparation.sources.connections.clone())?;
+ } else {
+ store.complete_application_launch(deployment).await?;
}
- .await;
- result?;
- return Ok((record.deployment, connections, vec![public.into_client()]));
+ Ok::<_, HostError>(loaded)
}
- let public = super::public::Host::connect(root, domain, host).await?;
- Ok((record.deployment, connections, vec![public.into_client()]))
+ .await;
+ let loaded = result?;
+ Ok((loaded, connections, vec![public.into_client()]))
}
fn host_configuration(
configuration: &Configuration,
@@ -383,8 +400,7 @@ async fn bootstrap_host(
domain: &str,
deployment: Uuid,
connections: &Configuration,
- input: &Input,
- packages: &[Package],
+ prepared: PreparedApplication,
) -> Result<(), HostError> {
let host_store = match open(root.into(), false, Some(domain.into())).await {
Ok(store) => store,
@@ -405,8 +421,7 @@ async fn bootstrap_host(
let result = super::headless::save_product(
&host_store,
deployment,
- input,
- packages,
+ prepared,
connection.endpoints.clone(),
connection.native.clone(),
)
@@ -417,7 +432,11 @@ async fn bootstrap_host(
result
}
-async fn begin(store: &EventLog, input: Installation, product: Product) -> Result<(), HostError> {
+async fn begin(
+ store: &EventLog,
+ input: Installation,
+ product: Product,
+) -> Result<PreparedLaunch, HostError> {
let version = super::bundle_fingerprint()?;
let authoring = super::authoring()?;
let (mut configuration, mut default_options) = match input {
@@ -454,7 +473,7 @@ async fn begin(store: &EventLog, input: Installation, product: Product) -> Resul
}
let packages = tokio::task::spawn_blocking(packages).await??;
let version = super::verified_fingerprint(&authoring, &packages, &version)?;
- let (mut sources, installation, _) = super::author_with_source(product, configuration, &packages, &authoring).await?;
+ let (mut sources, installation, applications) = super::author_with_source(product, configuration, &packages, &authoring).await?;
for host in sources.connections["hosts"].as_array_mut().ok_or("product connections missing")? {
if host["location"]["kind"] == "public" {
host["location"]["stateDomain"] = Value::String(owner.root_id().into());
@@ -468,18 +487,23 @@ async fn begin(store: &EventLog, input: Installation, product: Product) -> Resul
return Err("installation deployment already exists; use its original launcher or application run".into());
}
let selection = sources.connections.clone();
- let preparation = Preparation {
+ let mut preparation = Preparation {
product: Some(super::update::Baseline { product, installation, default_options, sources: sources.clone(), version: Some(version) }),
previous_connections: None,
restore: BTreeMap::new(),
sources,
packages: packages.values().map(|package| package.files().iter().map(|(path, bytes)| (path.clone(), STANDARD.encode(bytes))).collect()).collect(),
};
+ let deployment = Uuid::new_v4();
store.begin_application_launch(Record {
- deployment: Uuid::new_v4(), configuration: selection,
+ deployment, configuration: selection.clone(),
pending: Some(serde_json::to_vec(&preparation)?),
}).await?;
- Ok::<_, HostError>(())
+ preparation.packages.clear();
+ Ok::<_, HostError>(PreparedLaunch {
+ deployment, configuration: selection, preparation,
+ applications,
+ })
}.await;
host_store.drain().await;
result
@@ -508,6 +532,23 @@ pub(super) async fn ensure(
observations: &[RemoteObservation],
packages: &[Package],
) -> Result<(), HostError> {
+ ensure_prepared(
+ store,
+ deployment,
+ PreparedApplication::new(input.clone(), observations.to_vec(), packages.to_vec())?,
+ )
+ .await
+ .map(|_| ())
+}
+
+pub(super) async fn ensure_prepared(
+ store: &EventLog,
+ deployment: Uuid,
+ prepared: PreparedApplication,
+) -> Result<LoadedDeployment, HostError> {
+ let input = prepared.input();
+ let observations = prepared.remote_exports();
+ let packages = prepared.packages();
let reference = DeploymentRef {
state_domain: store.owned_root()?.root_id().into(),
deployment,
@@ -531,20 +572,24 @@ pub(super) async fn ensure(
"original product initialization source conflicts with stored revision 1".into(),
);
}
- // Reading validated every original byte against its immutable revision.
- // A newer user-authored head is deliberately preserved.
- } else {
+ // Initialization compares revision one, but execution selects the current
+ // head. Reuse the original only while it remains the observed head.
+ let head = store
+ .read_application_metadata(deployment)
+ .await?
+ .ok_or("UI source missing")?;
+ if head.source.reference == original.source().reference {
+ return Ok(original);
+ }
store
- .commit_application(
- deployment,
- 0,
- input.clone(),
- observations.to_vec(),
- packages.to_vec(),
- )
- .await?;
+ .load_application_at(&head.source.reference)
+ .await?
+ .ok_or_else(|| "UI source missing".into())
+ } else {
+ Ok(store
+ .commit_prepared_application(deployment, 0, prepared)
+ .await?)
}
- Ok(())
}
#[cfg(test)]
diff --git a/products/maka/cli/src/application/product/launch/tests.rs b/products/maka/cli/src/application/product/launch/tests.rs
index 22152ed3d8..e7b1f035ce 100644
--- a/products/maka/cli/src/application/product/launch/tests.rs
+++ b/products/maka/cli/src/application/product/launch/tests.rs
@@ -70,12 +70,36 @@ async fn pending(store: &EventLog, host: &EventLog) -> (Uuid, Uuid, Uuid) {
#[tokio::test]
async fn partial_initialization_resumes_original_inputs_and_preserves_new_heads() {
+ check_partial_initialization(false).await;
+}
+
+#[tokio::test]
+async fn checked_launch_finishes_partial_initialization_and_preserves_new_heads() {
+ check_partial_initialization(true).await;
+}
+
+async fn check_partial_initialization(checked: bool) {
let directory = tempfile::tempdir().unwrap();
let ui_path = directory.path().join("ui");
let host_path = directory.path().join("host");
let store = open(ui_path.clone(), true, None).await.unwrap();
let host = Arc::new(open(host_path.clone(), true, None).await.unwrap());
let (ui, host_id, management) = pending(&store, &host).await;
+ // The small fixture supplies the same checked value that authoring retains
+ // on a first launch; the other case reconstructs it through disk recovery.
+ let prepared = if checked {
+ let record = store.application_launch().await.unwrap().unwrap();
+ let preparation: Preparation =
+ serde_json::from_slice(record.pending.as_ref().unwrap()).unwrap();
+ Some(PreparedLaunch {
+ deployment: record.deployment,
+ configuration: record.configuration,
+ applications: super::super::prepare_sources(&preparation.sources, &[]).unwrap(),
+ preparation,
+ })
+ } else {
+ None
+ };
ensure(&host, host_id, &input(), &[], &[]).await.unwrap();
let mut edited = input();
edited.environment = Environment {
@@ -88,12 +112,28 @@ async fn partial_initialization_resumes_original_inputs_and_preserves_new_heads(
ensure(&store, management, &input(), &[], &[])
.await
.unwrap();
+ ensure(&store, ui, &input(), &[], &[]).await.unwrap();
+ let mut newer_ui = input();
+ newer_ui.environment = Environment {
+ location: ExecutionLocation::Ui,
+ presentation: Some(PresentationTarget::Tui),
+ };
+ store
+ .commit_application(ui, 1, newer_ui.clone(), vec![], vec![])
+ .await
+ .unwrap();
let serving = PublishedHost::start(host.clone(), host_id).await;
store.drain().await;
drop(store);
let store = open(ui_path.clone(), false, None).await.unwrap();
- let (selected, _, clients) = prepare(&store, None, Product::Studio).await.unwrap();
- assert_eq!(selected, ui);
+ let (selected, _, clients) = match prepared {
+ Some(prepared) => finish(&store, prepared).await.unwrap(),
+ None => prepare(&store, None, Product::Studio).await.unwrap(),
+ };
+ selected.check_store(&store).unwrap();
+ assert_eq!(selected.source().reference.deployment, ui);
+ assert_eq!(selected.source().reference.revision, 2);
+ assert_eq!(selected.source().input, newer_ui);
assert!(
store
.application_launch()
@@ -112,7 +152,7 @@ async fn partial_initialization_resumes_original_inputs_and_preserves_new_heads(
.source()
.reference
.revision,
- 1
+ 2
);
assert_eq!(
store
@@ -137,7 +177,7 @@ async fn partial_initialization_resumes_original_inputs_and_preserves_new_heads(
);
drop(clients);
store
- .commit_application(ui, 1, input(), vec![], vec![])
+ .commit_application(ui, 2, input(), vec![], vec![])
.await
.unwrap();
assert!(
@@ -149,7 +189,8 @@ async fn partial_initialization_resumes_original_inputs_and_preserves_new_heads(
.await
.is_err()
);
- prepare(&store, None, Product::Agent).await.unwrap();
+ let (current, _, _) = prepare(&store, None, Product::Agent).await.unwrap();
+ assert_eq!(current.source().reference.revision, 3);
assert_eq!(
store
.load_application(ui)
@@ -159,7 +200,7 @@ async fn partial_initialization_resumes_original_inputs_and_preserves_new_heads(
.source()
.reference
.revision,
- 2
+ 3
);
serving.stop().await;
drop(host);
@@ -247,7 +288,8 @@ async fn invalid_presentation_is_rejected_before_host_initialization() {
Product::Agent,
)
.await
- .unwrap_err();
+ .err()
+ .unwrap();
assert!(error.to_string().contains("requires tui"));
assert!(!host.exists());
assert!(store.application_launch().await.unwrap().is_none());
diff --git a/products/maka/cli/src/application/product/test_public.rs b/products/maka/cli/src/application/product/test_public.rs
index 136c1f4aed..ad7c33ad38 100644
--- a/products/maka/cli/src/application/product/test_public.rs
+++ b/products/maka/cli/src/application/product/test_public.rs
@@ -123,8 +123,12 @@ impl PublishedHost {
super::headless::save_product(
&store,
deployment,
- &original.source().input,
- original.packages(),
+ maka_event_log::applications::PreparedApplication::new(
+ original.source().input.clone(),
+ original.source().remote_exports.clone(),
+ original.packages().to_vec(),
+ )
+ .unwrap(),
endpoints.clone(),
native.clone(),
)
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org