Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(tauri): autoupdate on app resume (#2822)

Sean Ayea01f52f55340
diff --git a/js/app/justfile b/js/app/justfile
index 814383f244..1186c719f2 100644
--- a/js/app/justfile
+++ b/js/app/justfile
@@ -37,6 +37,20 @@ build-prod:
build-tauri:
cd packages/app && MODE=production NODE_ENV=production bun run --bun build:tauri
+# Build the web bundle for `platform` (default: ios), zip it, and install it at
+# rust/cloud-storage/tools/native_app_server/app-archive.zip for the bundle
+# updater test server. The server hashes the archive at request time, so no
+# checksum wiring is needed.
+dist-archive platform='ios':
+ #!/usr/bin/env bash
+ set -euo pipefail
+ cd packages/app
+ MODE=production NODE_ENV=production bun run --bun build:{{platform}}
+ TARGET="$(cd {{ justfile_directory() }}/../../rust/cloud-storage/tools/native_app_server && pwd)/app-archive.zip"
+ rm -f "$TARGET"
+ (cd dist && zip -qr "$TARGET" .)
+ echo "Archive: $TARGET"
+
test-watch:
bunx --bun vitest
diff --git a/js/app/tauri/input_accessory_plugin/src/lib.rs b/js/app/tauri/input_accessory_plugin/src/lib.rs
index e7474c1ef5..73d9f5a3b4 100644
--- a/js/app/tauri/input_accessory_plugin/src/lib.rs
+++ b/js/app/tauri/input_accessory_plugin/src/lib.rs
@@ -1,6 +1,6 @@
use tauri::{
- plugin::{Builder, TauriPlugin},
Runtime,
+ plugin::{Builder, TauriPlugin},
};
#[cfg(target_os = "ios")]
diff --git a/js/app/tauri/macro_bundle_updater_plugin/src/domain/models.rs b/js/app/tauri/macro_bundle_updater_plugin/src/domain/models.rs
index caae4cf018..5e3e8d0832 100644
--- a/js/app/tauri/macro_bundle_updater_plugin/src/domain/models.rs
+++ b/js/app/tauri/macro_bundle_updater_plugin/src/domain/models.rs
@@ -64,7 +64,8 @@ impl BundleRoot {
match self.0.as_ref() {
Some(root) => {
tracing::info!("Persisting bundle root {root:?} to {persist_path:?}");
- fs.write(&persist_path, root.to_string_lossy().as_bytes()).await
+ fs.write(&persist_path, root.to_string_lossy().as_bytes())
+ .await
}
None => fs.remove_file(&persist_path).await,
}
@@ -75,11 +76,6 @@ impl BundleRoot {
self.0.as_deref()
}
- /// Set the bundle root to a new path.
- pub(crate) fn set(&mut self, path: PathBuf) {
- self.0 = Some(path);
- }
-
/// Clear the bundle root, reverting to the built-in assets.
pub(crate) fn clear(&mut self) {
self.0 = None;
@@ -332,27 +328,13 @@ pub enum UpdateError {
}
/// denotes that an update was approved
-#[derive(Debug, Clone)]
+#[derive(Debug, Clone, Default)]
pub struct UpdateGranted(());
-impl UpdateGranted {
- /// Create a new granted token.
- pub fn new() -> Self {
- UpdateGranted(())
- }
-}
-
/// denotes that an update was denied
-#[derive(Debug, Clone, Copy)]
+#[derive(Debug, Clone, Copy, Default)]
pub struct UpdateDenied(());
-impl UpdateDenied {
- /// Create a new denied token.
- pub fn new() -> Self {
- UpdateDenied(())
- }
-}
-
/// Whether the user approved or denied a pending update.
#[derive(Debug, Clone)]
pub enum UpdateApproval {
diff --git a/js/app/tauri/macro_bundle_updater_plugin/src/domain/service.rs b/js/app/tauri/macro_bundle_updater_plugin/src/domain/service.rs
index 2633f090f8..38b47cbc83 100644
--- a/js/app/tauri/macro_bundle_updater_plugin/src/domain/service.rs
+++ b/js/app/tauri/macro_bundle_updater_plugin/src/domain/service.rs
@@ -1,7 +1,7 @@
use crate::domain::{
models::{
- BundleRoot, CompletedStatus, ProgressPercentage, UnzipRequest, UnzipStatus,
- UpdateApproval, UpdateDownloadingStatus, UpdateError, UpdateFoundStatus, UpdateStatus,
+ BundleRoot, CompletedStatus, ProgressPercentage, UnzipRequest, UnzipStatus, UpdateApproval,
+ UpdateDownloadingStatus, UpdateError, UpdateFoundStatus, UpdateStatus,
},
ports::{AutoUpdateService, FsRepo, SystemQuery, UpdateRepo},
};
@@ -123,14 +123,12 @@ impl<U: UpdateRepo, Fs: FsRepo, Q: SystemQuery> Worker<U, Fs, Q> {
match res {
Some(update) => {
// Check if this version was already downloaded in a previous session.
- if let Ok(update_dir) = self.system_query.get_update_dir().await {
- if let Some(entrypoint) =
- find_cached_bundle(&self.fs_repo, &update_dir, &update.version).await
- {
- return Ok(UpdateStatus::Completed(CompletedStatus {
- entrypoint,
- }));
- }
+ if let Ok(update_dir) = self.system_query.get_update_dir().await
+ && let Some(entrypoint) =
+ find_cached_bundle(&self.fs_repo, &update_dir, &update.version)
+ .await
+ {
+ return Ok(UpdateStatus::Completed(CompletedStatus { entrypoint }));
}
Ok(UpdateStatus::UpdateFound(UpdateFoundStatus {
bundle: update,
@@ -291,7 +289,6 @@ async fn find_cached_bundle(
None
}
-
/// helper function which pipes the progress of an event from one channel into another
/// returning true if the value in the sender channel was modified
async fn glue_channels<F>(
@@ -334,10 +331,43 @@ impl<Fs: FsRepo> Service<Fs> {
self.bundle_root.path()
}
+ /// Apply the update by modifying the bundle root and resetting the worker thread to the initial state.
+ ///
+ /// Returns `Ok(false)` when there is no pending update or another caller
+ /// is already applying one.
+ pub async fn apply_update(&mut self, cache_dir: &Path) -> Result<bool, Report> {
+ let entrypoint = {
+ let status = self.status().borrow();
+ match status.as_ref() {
+ Ok(UpdateStatus::Completed(bundle_location)) => bundle_location.entrypoint.clone(),
+ _ => return Ok(false),
+ }
+ };
+
+ // Claim the worker restart slot before doing any work. If the channel
+ // is full another apply_update is already in flight — short-circuit.
+ if self.start().is_err() {
+ return Ok(false);
+ }
+
+ let bundle_dir = entrypoint
+ .parent()
+ .ok_or_else(|| report!("entrypoint {entrypoint:?} has no parent directory"))?
+ .to_path_buf();
+
+ tracing::info!("Setting bundle root to {bundle_dir:?}");
+ self.set_bundle_root(bundle_dir.clone(), cache_dir).await?;
+
+ // Remove old bundle directories now that we've switched to the new one
+ self.cleanup_old_bundles(cache_dir, &bundle_dir).await;
+
+ Ok(true)
+ }
+
/// Set the bundle root to a new directory and persist it.
///
/// The in-memory state is only updated after persistence succeeds.
- pub async fn set_bundle_root(
+ async fn set_bundle_root(
&mut self,
path: PathBuf,
cache_dir: &Path,
@@ -366,7 +396,7 @@ impl<Fs: FsRepo> Service<Fs> {
}
/// Remove all numeric bundle subdirectories under `dir` except `keep`.
- pub async fn cleanup_old_bundles(&self, dir: &Path, keep: &Path) {
+ async fn cleanup_old_bundles(&self, dir: &Path, keep: &Path) {
for name in self.fs_repo.list_dir_names(dir).await {
if name.parse::<u64>().is_err() {
continue;
diff --git a/js/app/tauri/macro_bundle_updater_plugin/src/inbound/plugin.rs b/js/app/tauri/macro_bundle_updater_plugin/src/inbound/plugin.rs
index 19c0b32bcb..5f4bf8bd16 100644
--- a/js/app/tauri/macro_bundle_updater_plugin/src/inbound/plugin.rs
+++ b/js/app/tauri/macro_bundle_updater_plugin/src/inbound/plugin.rs
@@ -100,59 +100,59 @@ pub async fn grant_bundle_update(
let mut service = service.lock().await;
let grant_tx = service.try_recv_grant_sender().map_err(|e| e.to_string())?;
let approval = if approved {
- UpdateApproval::Granted(UpdateGranted::new())
+ UpdateApproval::Granted(UpdateGranted::default())
} else {
- UpdateApproval::Denied(UpdateDenied::new())
+ UpdateApproval::Denied(UpdateDenied::default())
};
grant_tx
.send(approval)
.map_err(|_| "Worker dropped the grant receiver".to_string())
}
-/// Apply a completed bundle update: set the bundle root and navigate to it.
-#[tauri::command]
-#[tracing::instrument(err, skip(service, app_handle))]
-pub async fn perform_update<R: Runtime>(
- service: tauri::State<'_, Mutex<PluginService>>,
- app_handle: tauri::AppHandle<R>,
-) -> Result<(), String> {
- let mut service = service.lock().await;
- let entrypoint = {
- let status = service.status().borrow();
- match status.as_ref() {
- Ok(UpdateStatus::Completed(bundle_location)) => bundle_location.entrypoint.clone(),
- _ => return Err("No pending update".into()),
- }
- };
-
- let bundle_dir = entrypoint
- .parent()
- .ok_or_else(|| format!("entrypoint {entrypoint:?} has no parent directory"))?
- .to_path_buf();
+/// Apply a completed bundle update to the live webview.
+///
+/// Returns `Ok(true)` if an update was applied, `Ok(false)` if the service is
+/// not in the `Completed` state (no pending update to commit).
+pub async fn apply_completed_update<R: Runtime>(
+ app_handle: &tauri::AppHandle<R>,
+) -> Result<bool, String> {
+ let service_state = app_handle
+ .try_state::<Mutex<PluginService>>()
+ .ok_or_else(|| "Bundle updater plugin not initialized".to_string())?;
let cache_dir = app_handle
.path()
.app_cache_dir()
.map_err(|e| e.to_string())?;
- tracing::info!("Setting bundle root to {bundle_dir:?}");
- service
- .set_bundle_root(bundle_dir.clone(), &cache_dir)
+ let mut service = service_state.lock().await;
+
+ let applied = service
+ .apply_update(&cache_dir)
.await
.map_err(|e| e.to_string())?;
- // Remove old bundle directories now that we've switched to the new one
- service.cleanup_old_bundles(&cache_dir, &bundle_dir).await;
-
drop(service);
- // Reload to pick up the new bundle. Using location.reload() instead of
- // navigating to a new URL preserves WKWebView's cookie store.
- if let Some(webview) = app_handle.webview_windows().values().next() {
- tracing::info!("Bundle update complete, reloading to pick up new assets");
- let _ = webview.eval("window.location.reload();");
+ if applied {
+ // Reload to pick up the new bundle. Using location.reload() instead of
+ // navigating to a new URL preserves WKWebView's cookie store.
+ if let Some(webview) = app_handle.webview_windows().values().next() {
+ tracing::info!("Bundle update complete, reloading to pick up new assets");
+ let _ = webview.eval("window.location.reload();");
+ }
+ }
+ Ok(applied)
+}
+
+/// Apply a completed bundle update: set the bundle root and navigate to it.
+#[tauri::command]
+#[tracing::instrument(err, skip(app_handle))]
+pub async fn perform_update<R: Runtime>(app_handle: tauri::AppHandle<R>) -> Result<(), String> {
+ match apply_completed_update(&app_handle).await? {
+ true => Ok(()),
+ false => Err("No pending update".into()),
}
- Ok(())
}
/// Trigger a manual check for bundle updates.
diff --git a/js/app/tauri/src-tauri/src/lib.rs b/js/app/tauri/src-tauri/src/lib.rs
index d4602ab395..af3c08d3aa 100644
--- a/js/app/tauri/src-tauri/src/lib.rs
+++ b/js/app/tauri/src-tauri/src/lib.rs
@@ -1,5 +1,5 @@
use logger::Logger;
-use macro_bundle_updater_plugin::inbound::plugin::PluginService;
+use macro_bundle_updater_plugin::inbound::plugin::{PluginService, apply_completed_update};
use navigation_plugin::MacroNavigationPlugin;
use navigation_plugin::scheme::MacroScheme;
use reqwest::cookie::CookieStore;
@@ -7,7 +7,7 @@ use reqwest::header::{COOKIE, ORIGIN};
use rootcause::{Report, report};
use serde::Serialize;
use tauri::http::{HeaderMap, HeaderValue};
-use tauri::{AppHandle, Emitter, Manager, Runtime};
+use tauri::{AppHandle, Emitter, Manager, RunEvent, Runtime};
mod tauri_protocol;
use tauri_plugin_deep_link::{DeepLinkExt, OpenUrlEvent};
@@ -180,17 +180,17 @@ pub fn run() {
])
.setup(|app| {
// Restore persisted bundle root on startup
- if let Ok(cache_dir) = app.path().app_cache_dir() {
- if let Some(s) = app.try_state::<tokio::sync::Mutex<PluginService>>() {
- tauri::async_runtime::block_on(async {
- let mut service = s.lock().await;
- service.load_bundle_root(&cache_dir).await;
- tracing::info!(
- "Setup: restored bundle root to {:?}",
- service.bundle_root_path()
- );
- });
- }
+ if let Ok(cache_dir) = app.path().app_cache_dir()
+ && let Some(s) = app.try_state::<tokio::sync::Mutex<PluginService>>()
+ {
+ tauri::async_runtime::block_on(async {
+ let mut service = s.lock().await;
+ service.load_bundle_root(&cache_dir).await;
+ tracing::info!(
+ "Setup: restored bundle root to {:?}",
+ service.bundle_root_path()
+ );
+ });
}
#[cfg(any(target_os = "linux", all(windows, debug_assertions)))]
@@ -206,8 +206,24 @@ pub fn run() {
Ok(())
})
- .run(tauri::generate_context!())
- .expect("error while running tauri application");
+ .build(tauri::generate_context!())
+ .expect("error while building tauri application")
+ .run(|app_handle, event| {
+ if let RunEvent::Resumed = event {
+ let app = app_handle.clone();
+ tauri::async_runtime::spawn(async move {
+ match apply_completed_update(&app).await {
+ Ok(true) => {
+ tracing::info!("auto-applied pending bundle update on foreground");
+ }
+ Ok(false) => {}
+ Err(e) => {
+ tracing::error!("failed to auto-apply bundle update: {e}");
+ }
+ }
+ });
+ }
+ });
}
/// fn to merge the headers from the http cookie store into the initial
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index 72c632a2b8..340d975ada 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -7079,7 +7079,9 @@ version = "0.1.0"
dependencies = [
"axum",
"native_app_service",
+ "rootcause",
"semver",
+ "sha2",
"tokio",
"tower-http",
"tracing",
@@ -7091,10 +7093,11 @@ dependencies = [
name = "native_app_service"
version = "0.1.0"
dependencies = [
- "anyhow",
"axum",
"cool_asserts",
+ "futures",
"reqwest",
+ "rootcause",
"semver",
"serde",
"serde_json",
diff --git a/rust/cloud-storage/native_app_service/Cargo.toml b/rust/cloud-storage/native_app_service/Cargo.toml
index d7767d9ec2..c2c63a8640 100644
--- a/rust/cloud-storage/native_app_service/Cargo.toml
+++ b/rust/cloud-storage/native_app_service/Cargo.toml
@@ -5,13 +5,14 @@ publish = false
version = "0.1.0"
[dependencies]
-anyhow = { workspace = true }
axum = { workspace = true, features = ["macros"] }
-reqwest = { workspace = true }
+reqwest = { workspace = true, features = ["stream"] }
+futures = { workspace = true }
+rootcause = { workspace = true }
semver = { workspace = true }
-sha2 = { workspace = true }
serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true }
+sha2 = { workspace = true }
thiserror = { workspace = true }
tokio = { workspace = true }
tracing = { workspace = true }
diff --git a/rust/cloud-storage/native_app_service/src/domain/models.rs b/rust/cloud-storage/native_app_service/src/domain/models.rs
index 6ad80604f6..e9eeb9671a 100644
--- a/rust/cloud-storage/native_app_service/src/domain/models.rs
+++ b/rust/cloud-storage/native_app_service/src/domain/models.rs
@@ -100,11 +100,11 @@ pub static BUNDLE_ARCHIVE_NAME: &str = "/app/app-archive.zip";
#[derive(Debug, Error)]
pub enum UpdateErr {
/// a network error has occirred
- #[error("A network error occurred: {0:?}")]
- Network(#[from] anyhow::Error),
+ #[error("A network error occurred")]
+ Network,
/// failed to parse a semver string
- #[error("Failed to parse semver {0}")]
- Semver(#[from] semver::Error),
+ #[error("Failed to parse semver")]
+ Semver,
}
/// contains information about bundle ids for various app platforms
diff --git a/rust/cloud-storage/native_app_service/src/domain/ports.rs b/rust/cloud-storage/native_app_service/src/domain/ports.rs
index bb6ace30bc..b233685de8 100644
--- a/rust/cloud-storage/native_app_service/src/domain/ports.rs
+++ b/rust/cloud-storage/native_app_service/src/domain/ports.rs
@@ -1,17 +1,20 @@
use crate::domain::models::{BundleUpdate, BundleUpdateRequest, PlatformVerifier, UpdateErr};
+use rootcause::Report;
use url::Url;
/// outbound trait for sending network requests to query the bundle state
pub trait GetJsBundleSemver: Send + Sync + 'static {
/// fetch the semver of the current app over the network
- fn get_app_semver(&self) -> impl Future<Output = Result<semver::Version, UpdateErr>> + Send;
+ fn get_app_semver(
+ &self,
+ ) -> impl Future<Output = Result<semver::Version, Report<UpdateErr>>> + Send;
/// get the Url of the bundle
fn get_app_bundle_path(&self) -> Url;
/// get the SHA-256 hex digest of the bundle archive for the given version
fn get_app_bundle_checksum(
&self,
version: &semver::Version,
- ) -> impl Future<Output = Result<String, UpdateErr>> + Send;
+ ) -> impl Future<Output = Result<String, Report<UpdateErr>>> + Send;
}
/// the service level trait for dealing with tauri app integration
@@ -21,7 +24,7 @@ pub trait NativeAppService: Send + Sync + 'static {
fn get_bundle_update(
&self,
req: BundleUpdateRequest,
- ) -> impl Future<Output = Result<Option<BundleUpdate>, UpdateErr>> + Send;
+ ) -> impl Future<Output = Result<Option<BundleUpdate>, Report<UpdateErr>>> + Send;
/// retrieve the verification payload for some platform T
fn verification_data<T: PlatformVerifier>(&self, req: T) -> T::VerifierPayload;
diff --git a/rust/cloud-storage/native_app_service/src/domain/service.rs b/rust/cloud-storage/native_app_service/src/domain/service.rs
index ba1fa693f9..1c9adb5ccf 100644
--- a/rust/cloud-storage/native_app_service/src/domain/service.rs
+++ b/rust/cloud-storage/native_app_service/src/domain/service.rs
@@ -2,6 +2,7 @@ use crate::domain::{
models::{BundleUpdate, BundleUpdateRequest, PlatformData, PlatformVerifier, UpdateErr},
ports::{GetJsBundleSemver, NativeAppService},
};
+use rootcause::Report;
/// the concrete struct which implements [NativeAppService]
pub struct NativeAppServiceImpl<T> {
@@ -19,7 +20,7 @@ where
async fn get_bundle_update(
&self,
req: BundleUpdateRequest,
- ) -> Result<Option<BundleUpdate>, UpdateErr> {
+ ) -> Result<Option<BundleUpdate>, Report<UpdateErr>> {
let BundleUpdateRequest {
target: _,
arch: _,
diff --git a/rust/cloud-storage/native_app_service/src/outbound.rs b/rust/cloud-storage/native_app_service/src/outbound.rs
index fe9a0d4801..97722c77e6 100644
--- a/rust/cloud-storage/native_app_service/src/outbound.rs
+++ b/rust/cloud-storage/native_app_service/src/outbound.rs
@@ -2,6 +2,8 @@ use crate::domain::{
models::{BUNDLE_ARCHIVE_NAME, SEMVER_FILE_NAME, UpdateErr},
ports::GetJsBundleSemver,
};
+use futures::StreamExt;
+use rootcause::{Report, prelude::ResultExt};
use sha2::{Digest, Sha256};
use std::str::FromStr;
use tokio::sync::RwLock;
@@ -31,35 +33,36 @@ impl DefaultBundleFetcher {
}
}
- /// Download the bundle and compute its SHA-256 hex digest
- async fn compute_checksum(&self) -> Result<String, UpdateErr> {
- let url = self.get_app_bundle_path();
- let bytes = reqwest::get(url)
- .await
- .map_err(anyhow::Error::from)?
- .error_for_status()
- .map_err(anyhow::Error::from)?
- .bytes()
- .await
- .map_err(anyhow::Error::from)?;
- let hash = Sha256::digest(&bytes);
- Ok(format!("{:x}", hash))
+ /// Download the bundle and compute its SHA-256 hex digest by streaming
+ async fn compute_checksum(&self) -> Result<String, Report<UpdateErr>> {
+ async move {
+ let url = self.get_app_bundle_path();
+ let response = reqwest::get(url).await?.error_for_status()?;
+ let mut stream = response.bytes_stream();
+ let mut hasher = Sha256::new();
+ while let Some(chunk) = stream.next().await {
+ hasher.update(&chunk?);
+ }
+ Result::<_, Report>::Ok(format!("{:x}", hasher.finalize()))
+ }
+ .await
+ .context(UpdateErr::Network)
}
}
impl GetJsBundleSemver for DefaultBundleFetcher {
#[tracing::instrument(skip(self), ret, err)]
- async fn get_app_semver(&self) -> Result<semver::Version, UpdateErr> {
+ async fn get_app_semver(&self) -> Result<semver::Version, Report<UpdateErr>> {
let url = self.base_url.join(self.semver_file_name).unwrap();
let res = reqwest::get(url)
.await
- .map_err(anyhow::Error::from)?
+ .context(UpdateErr::Network)?
.error_for_status()
- .map_err(anyhow::Error::from)?
+ .context(UpdateErr::Network)?
.text()
.await
- .map_err(anyhow::Error::from)?;
- let cur_ver = semver::Version::from_str(res.trim())?;
+ .context(UpdateErr::Network)?;
+ let cur_ver = semver::Version::from_str(res.trim()).context(UpdateErr::Semver)?;
Ok(cur_ver)
}
@@ -71,7 +74,7 @@ impl GetJsBundleSemver for DefaultBundleFetcher {
async fn get_app_bundle_checksum(
&self,
version: &semver::Version,
- ) -> Result<String, UpdateErr> {
+ ) -> Result<String, Report<UpdateErr>> {
// return cached checksum if version matches
if let Some((cached_ver, cached_checksum)) = self.checksum_cache.read().await.as_ref()
&& cached_ver == version
diff --git a/rust/cloud-storage/native_app_service/src/tests.rs b/rust/cloud-storage/native_app_service/src/tests.rs
index 719733f1f2..8919457a07 100644
--- a/rust/cloud-storage/native_app_service/src/tests.rs
+++ b/rust/cloud-storage/native_app_service/src/tests.rs
@@ -10,6 +10,7 @@ use crate::{
outbound::DefaultBundleFetcher,
};
use reqwest::Url;
+use rootcause::Report;
use cool_asserts::assert_matches;
use semver::Version;
@@ -25,7 +26,7 @@ fn all_urls_work() {
struct MockBundleFetcher;
impl GetJsBundleSemver for MockBundleFetcher {
- async fn get_app_semver(&self) -> Result<semver::Version, UpdateErr> {
+ async fn get_app_semver(&self) -> Result<semver::Version, Report<UpdateErr>> {
Ok("1.1.1".parse().unwrap())
}
@@ -36,7 +37,7 @@ impl GetJsBundleSemver for MockBundleFetcher {
async fn get_app_bundle_checksum(
&self,
_version: &semver::Version,
- ) -> Result<String, UpdateErr> {
+ ) -> Result<String, Report<UpdateErr>> {
Ok("abc123".to_string())
}
}
@@ -221,7 +222,7 @@ fn needs_update_should_not_downgrade() {
struct MockBundleFetcherWithBuild;
impl GetJsBundleSemver for MockBundleFetcherWithBuild {
- async fn get_app_semver(&self) -> Result<semver::Version, UpdateErr> {
+ async fn get_app_semver(&self) -> Result<semver::Version, Report<UpdateErr>> {
Ok("1.1.1+abc1234".parse().unwrap())
}
@@ -232,7 +233,7 @@ impl GetJsBundleSemver for MockBundleFetcherWithBuild {
async fn get_app_bundle_checksum(
&self,
_version: &semver::Version,
- ) -> Result<String, UpdateErr> {
+ ) -> Result<String, Report<UpdateErr>> {
Ok("abc123".to_string())
}
}
diff --git a/rust/cloud-storage/tools/native_app_server/Cargo.toml b/rust/cloud-storage/tools/native_app_server/Cargo.toml
index 239464b067..3264704c29 100644
--- a/rust/cloud-storage/tools/native_app_server/Cargo.toml
+++ b/rust/cloud-storage/tools/native_app_server/Cargo.toml
@@ -1,13 +1,15 @@
[package]
-name = "native_app_server"
-version = "0.1.0"
edition = "2024"
+name = "native_app_server"
publish = false
+version = "0.1.0"
[dependencies]
axum = { workspace = true }
native_app_service = { path = "../../native_app_service" }
+rootcause = { workspace = true }
semver = { workspace = true }
+sha2 = { workspace = true }
tokio = { workspace = true }
tower-http = { workspace = true, features = ["fs"] }
tracing = { workspace = true }
diff --git a/rust/cloud-storage/tools/native_app_server/src/main.rs b/rust/cloud-storage/tools/native_app_server/src/main.rs
index 56fab75a99..ba5bf5cc0d 100644
--- a/rust/cloud-storage/tools/native_app_server/src/main.rs
+++ b/rust/cloud-storage/tools/native_app_server/src/main.rs
@@ -1,3 +1,4 @@
+use std::path::{Path, PathBuf};
use std::sync::Arc;
use native_app_service::{
@@ -8,17 +9,22 @@ use native_app_service::{
},
inbound::{RouterState, native_app_router},
};
+use rootcause::{Report, report};
+use sha2::{Digest, Sha256};
+use tokio::io::AsyncReadExt;
use tower_http::services::ServeFile;
use url::Url;
/// Bundle fetcher that always reports a very high version, forcing an update.
+/// The checksum is recomputed from the archive on disk each time it is
+/// requested, so rebuilding the archive doesn't require restarting the server.
struct AlwaysUpdateFetcher {
bundle_url: Url,
- checksum: String,
+ archive_path: PathBuf,
}
impl GetJsBundleSemver for AlwaysUpdateFetcher {
- async fn get_app_semver(&self) -> Result<semver::Version, UpdateErr> {
+ async fn get_app_semver(&self) -> Result<semver::Version, Report<UpdateErr>> {
Ok(semver::Version::new(999, 0, 0))
}
@@ -29,11 +35,28 @@ impl GetJsBundleSemver for AlwaysUpdateFetcher {
async fn get_app_bundle_checksum(
&self,
_version: &semver::Version,
- ) -> Result<String, UpdateErr> {
- Ok(self.checksum.clone())
+ ) -> Result<String, Report<UpdateErr>> {
+ sha256_hex(&self.archive_path).await.map_err(|e| {
+ tracing::error!(error=?e, path=?self.archive_path, "failed to hash bundle archive");
+ report!(e).context(UpdateErr::Network)
+ })
}
}
+async fn sha256_hex(path: &Path) -> std::io::Result<String> {
+ let mut file = tokio::fs::File::open(path).await?;
+ let mut hasher = Sha256::new();
+ let mut buf = [0u8; 8192];
+ loop {
+ let n = file.read(&mut buf).await?;
+ if n == 0 {
+ break;
+ }
+ hasher.update(&buf[..n]);
+ }
+ Ok(format!("{:x}", hasher.finalize()))
+}
+
const ADDR: &str = "127.0.0.1:3001";
const ARCHIVE_PATH: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/app-archive.zip");
@@ -46,14 +69,10 @@ async fn main() {
.parse()
.expect("BUNDLE_URL must be a valid URL");
- let checksum = std::env::var("BUNDLE_CHECKSUM").unwrap_or_else(|_| {
- "1be759e3b1befdd6639cd89f93e9aa79857ca5c06c06e71de9b3702a9cd8af29".to_string()
- });
-
let service = NativeAppServiceImpl {
bundle_fetcher: AlwaysUpdateFetcher {
bundle_url,
- checksum,
+ archive_path: PathBuf::from(ARCHIVE_PATH),
},
platform_data: PlatformData {
ios_development_team_id: String::new(),