updater: require the one-token probe (force the load of a lazy server), keep the test start's engine log, report what was installed when a step fails

This commit is contained in:
Niko1221 committed 2026-10-15 17:33:47 +02:00
1 parent d3c4bba4ca
commit 4868f3234d
7 files changed
+301 -11

No files matched your search

+1
View File
@@ -12,6 +12,7 @@ tauri-build = { version = "2", features = [] }
[dependencies]
tauri = { version = "2", features = [] }
tauri-plugin-shell = "2"
tauri-plugin-updater = "2"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
+6
View File
@@ -24,6 +24,8 @@ use std::time::{Duration, Instant};
use tauri::{Manager, WebviewUrl, WebviewWindowBuilder};
mod updater;
/// The running App Host, kept so it can be stopped on exit.
struct HostProcess(Mutex<Option<Child>>);
@@ -275,6 +277,9 @@ fn start_host(app: &tauri::AppHandle) -> Result<u16, String> {
.stdout(Stdio::inherit())
.stderr(Stdio::inherit());
apply_runtime_policy(&mut cmd, &res);
// The signed app updater (Tauri) is reached by the host through a token-protected loopback bridge.
let bridge = updater::start(app, random_token());
updater::apply_env(&mut cmd, app, bridge.as_ref());
let token = random_token();
cmd.env("STRATA_SHUTDOWN_TOKEN", &token);
*app.state::<ShutdownToken>().0.lock().unwrap() = Some(token);
@@ -591,6 +596,7 @@ fn main() {
tauri::Builder::default()
.plugin(tauri_plugin_shell::init())
.plugin(tauri_plugin_updater::Builder::new().build())
.manage(HostProcess(Mutex::new(None)))
.manage(HostPort(Mutex::new(None)))
.manage(ShutdownToken(Mutex::new(None)))
+202
View File
@@ -0,0 +1,202 @@
//! The shell's half of the app update: Tauri's signed updater behind a loopback bridge for the App Host.
//!
//! The UI is served by the App Host, so it cannot call Tauri's updater plugin; and the host is Node, which has no updater.
//! The shell therefore opens one loopback listener, protected by a random token it hands only to the host it started
//! (`STRATA_SHELL_BRIDGE`, `STRATA_SHELL_TOKEN`), and the host's `app-updater.mjs` talks to it:
//!
//! GET /app-update/check -> { available, version, current, notes } (signature-verified metadata from the feed)
//! POST /app-update/install -> starts download + install in the background
//! GET /app-update/status -> { state: idle|downloading|installing|done|error, downloaded, total, version, error }
//!
//! The update itself is Tauri's: it downloads the installer, checks its minisign signature against the public key in
//! `tauri.conf.json` (`plugins.updater.pubkey`, the owner's separate updater key) and installs. A check or an install happens
//! only when the user presses "Check for updates" / "Update Strata"; nothing here runs on start, and nothing here touches
//! engines or models (those are Control's component updater: `strata update`).
use std::io::{Read, Write};
use std::net::{TcpListener, TcpStream};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use tauri::AppHandle;
use tauri_plugin_updater::UpdaterExt;
/// Where an endpoint other than the one in `tauri.conf.json` may come from: a local test feed. Only loopback or https.
const ENDPOINT_ENV: &str = "STRATA_UPDATE_APP_ENDPOINT";
#[derive(Clone, Default)]
struct Progress {
state: &'static str,
downloaded: u64,
total: u64,
version: Option<String>,
error: Option<String>,
}
impl Progress {
fn json(&self) -> serde_json::Value {
serde_json::json!({
"state": if self.state.is_empty() { "idle" } else { self.state },
"downloaded": self.downloaded, "total": self.total, "version": self.version, "error": self.error,
})
}
}
/// What the host needs to find the bridge.
pub struct Bridge {
pub url: String,
pub token: String,
}
fn endpoint_override() -> Option<String> {
let url = std::env::var(ENDPOINT_ENV).ok()?;
if url.starts_with("https://") || url.starts_with("http://127.0.0.1:") || url.starts_with("http://localhost:") {
Some(url)
} else {
None
}
}
fn updater_for(app: &AppHandle) -> Result<tauri_plugin_updater::Updater, String> {
match endpoint_override() {
Some(url) => {
let url: tauri::Url = url.parse().map_err(|e| format!("bad update endpoint: {e}"))?;
app.updater_builder().endpoints(vec![url]).map_err(|e| e.to_string())?.build().map_err(|e| e.to_string())
}
None => app.updater().map_err(|e| e.to_string()),
}
}
async fn check(app: &AppHandle) -> Result<serde_json::Value, String> {
let updater = updater_for(app)?;
match updater.check().await.map_err(|e| e.to_string())? {
Some(update) => Ok(serde_json::json!({
"available": true, "version": update.version, "current": update.current_version, "notes": update.body,
})),
None => Ok(serde_json::json!({ "available": false, "current": app.package_info().version.to_string() })),
}
}
async fn install(app: AppHandle, progress: Arc<Mutex<Progress>>) {
let fail = |message: String| {
let mut p = progress.lock().unwrap();
p.state = "error";
p.error = Some(message);
};
let updater = match updater_for(&app) {
Ok(u) => u,
Err(e) => return fail(e),
};
let update = match updater.check().await {
Ok(Some(update)) => update,
Ok(None) => return fail("There is no newer version of the Strata app.".into()),
Err(e) => return fail(e.to_string()),
};
{
let mut p = progress.lock().unwrap();
*p = Progress { state: "downloading", version: Some(update.version.clone()), ..Default::default() };
}
let on_chunk = {
let progress = progress.clone();
move |chunk: usize, total: Option<u64>| {
let mut p = progress.lock().unwrap();
p.downloaded += chunk as u64;
p.total = total.unwrap_or(p.total);
}
};
let on_finish = {
let progress = progress.clone();
move || progress.lock().unwrap().state = "installing"
};
// Tauri checks the installer's minisign signature before it runs anything. On Windows the plugin ends this process
// when the installer starts; elsewhere the app restarts itself once the update is in place.
match update.download_and_install(on_chunk, on_finish).await {
Ok(()) => {
progress.lock().unwrap().state = "done";
app.restart();
}
Err(e) => fail(e.to_string()),
}
}
fn respond(stream: &mut TcpStream, status: &str, body: &serde_json::Value) {
let text = body.to_string();
let _ = stream.write_all(
format!(
"HTTP/1.1 {status}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{text}",
text.len()
)
.as_bytes(),
);
}
fn same(a: &str, b: &str) -> bool {
a.len() == b.len() && a.bytes().zip(b.bytes()).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
}
fn handle(mut stream: TcpStream, app: &AppHandle, token: &str, progress: &Arc<Mutex<Progress>>) {
let _ = stream.set_read_timeout(Some(Duration::from_secs(5)));
let mut buf = Vec::new();
let mut chunk = [0u8; 1024];
while !buf.windows(4).any(|w| w == b"\r\n\r\n") && buf.len() < 8192 {
match stream.read(&mut chunk) {
Ok(0) | Err(_) => break,
Ok(n) => buf.extend_from_slice(&chunk[..n]),
}
}
let head = String::from_utf8_lossy(&buf).to_string();
let mut lines = head.lines();
let request = lines.next().unwrap_or_default().to_string();
let supplied = lines
.find_map(|l| l.strip_prefix("authorization: ").or_else(|| l.strip_prefix("Authorization: ")))
.map(|v| v.trim().trim_start_matches("Bearer ").to_string())
.unwrap_or_default();
if !same(&supplied, token) {
return respond(&mut stream, "401 Unauthorized", &serde_json::json!({ "error": "not allowed" }));
}
let mut parts = request.split_whitespace();
let (method, path) = (parts.next().unwrap_or(""), parts.next().unwrap_or(""));
match (method, path) {
("GET", "/app-update/check") => match tauri::async_runtime::block_on(check(app)) {
Ok(value) => respond(&mut stream, "200 OK", &value),
Err(e) => respond(&mut stream, "502 Bad Gateway", &serde_json::json!({ "error": e })),
},
("POST", "/app-update/install") => {
{
let mut p = progress.lock().unwrap();
if p.state == "downloading" || p.state == "installing" {
return respond(&mut stream, "409 Conflict", &serde_json::json!({ "error": "An app update is already running." }));
}
*p = Progress { state: "downloading", ..Default::default() };
}
tauri::async_runtime::spawn(install(app.clone(), progress.clone()));
respond(&mut stream, "202 Accepted", &progress.lock().unwrap().json());
}
("GET", "/app-update/status") => respond(&mut stream, "200 OK", &progress.lock().unwrap().json()),
_ => respond(&mut stream, "404 Not Found", &serde_json::json!({ "error": "unknown route" })),
}
}
/// Open the bridge on a free loopback port. Returns None if the listener cannot be bound (the app then simply has no
/// in-app update; the Terminal's `strata update --app` still works).
pub fn start(app: &AppHandle, token: String) -> Option<Bridge> {
let listener = TcpListener::bind(("127.0.0.1", 0)).ok()?;
let port = listener.local_addr().ok()?.port();
let progress = Arc::new(Mutex::new(Progress::default()));
let app = app.clone();
let secret = token.clone();
std::thread::spawn(move || {
for stream in listener.incoming().flatten() {
handle(stream, &app, &secret, &progress);
}
});
Some(Bridge { url: format!("http://127.0.0.1:{port}"), token })
}
/// Environment for the App Host: where the bridge is, which app version this is.
pub fn apply_env(cmd: &mut std::process::Command, app: &AppHandle, bridge: Option<&Bridge>) {
cmd.env("STRATA_APP_VERSION", app.package_info().version.to_string());
if let Some(bridge) = bridge {
cmd.env("STRATA_SHELL_BRIDGE", &bridge.url).env("STRATA_SHELL_TOKEN", &bridge.token);
}
}
+11 -1
View File
@@ -51,5 +51,15 @@
}
}
},
"plugins": {}
"plugins": {
"updater": {
"pubkey": "REPLACE-WITH-THE-OWNERS-TAURI-UPDATER-PUBLIC-KEY",
"endpoints": [
"https://github.com/Niko1221/Strata/releases/latest/download/latest.json"
],
"windows": {
"installMode": "passive"
}
}
}
}
+7 -2
View File
@@ -117,8 +117,10 @@ def _line(name: str, result: dict) -> str:
return f"{name:<8}{result.get('installed_before') or '?'} -> {result.get('installed_after')} updated (takes effect on the next start)"
if status == "current":
return f"{name:<8}{result.get('installed_before')} up to date"
if status == "not-in-feed":
return f"{name:<8}not part of this feed"
if status == "failed":
return f"{name:<8}NOT changed: {result.get('error')}"
return f"{name:<8}{result.get('installed_before') or '?'} NOT changed: {result.get('error')}"
return f"{name:<8}{status}"
if status == "downloaded":
return f"{name:<8}{result.get('version')} downloaded and verified: {result.get('path')}\n{'':<8}{result.get('note')}"
@@ -141,7 +143,10 @@ def _print_check(report: dict) -> None:
print(f" - {reason}")
if eng.get("note"):
print(f" {eng['note']}")
print(f" Control {ctl['installed'] or '?'}: {ctl['status']}" + (f" ({ctl['offered']})" if ctl["offered"] else ""))
if ctl["status"] == "not-in-feed":
print(" Control not part of this feed")
else:
print(f" Control {ctl['installed'] or '?'}: {ctl['status']}" + (f" ({ctl['offered']})" if ctl["offered"] else ""))
if app["status"] != "not-in-feed":
print(f" App {app['installed'] or 'unknown'} -> {app['offered']}: {app['status']}")
if report.get("serving"):
+48 -8
View File
@@ -539,6 +539,30 @@ def binary_smoke(component: ec.EngineComponent, timeout: float = 60) -> dict:
"output": done.stdout.strip()[:200]}
def _log_tail(sandbox: Path, component: ec.EngineComponent) -> str:
log = sandbox / "engine.log"
try:
lines = log.read_text(errors="replace").splitlines()[-3:]
except OSError:
return ""
return " | " + " ".join(lines)[:300] if lines else ""
def _keep_log(sandbox: Path, component: ec.EngineComponent, ctx: Context) -> None:
"""The engine's log from the test start (the last 64 KiB), kept in ``.updates/logs`` so a failed update can be read afterwards."""
log = sandbox / "engine.log"
try:
data = log.read_bytes()[-65536:]
target = updates_dir(ctx.components) / "logs"
target.mkdir(parents=True, exist_ok=True)
(target / f"test-start-{component.version}.log").write_bytes(data)
logs = sorted(target.glob("test-start-*.log"), key=lambda p: p.stat().st_mtime)
for old in logs[:-5]:
old.unlink(missing_ok=True)
except OSError:
pass
def default_test_start(stage_root: Path, component: ec.EngineComponent, ctx: Context) -> dict:
"""Start the staged engine through the real start path (owner runtime, `component:strata-engine`, a saved model), wait for
the one-token generation probe, and stop it. Everything runs in an isolated runtime, profile and component folder, so a
@@ -570,16 +594,19 @@ def default_test_start(stage_root: Path, component: ec.EngineComponent, ctx: Con
started = None
try:
started = runtime.start(name, wait=min(ctx.test_timeout, 600), shutdown_timeout=20)
if not started.get("ok") or started.get("state") != "ready":
log = Path(sandbox / "engine.log")
tail = ""
if log.exists():
tail = " | " + " ".join(log.read_text(errors="replace").splitlines()[-3:])[:300]
if started.get("ok") and started.get("state") == "ready" and started.get("generation_ready") is not True:
# a server that loads its model on the first request is "ready" without having generated anything:
# force the load and the one-token probe, because that is what the new engine has to be able to do
started = {**started, **runtime.verify(name, timeout=min(ctx.test_timeout, 600), load=True)}
if not started.get("ok") or started.get("state") != "ready" or started.get("generation_ready") is not True:
raise TestStartFailed(component.version,
f"it did not become ready ({started.get('error') or started.get('state')}){tail}")
f"it did not answer a one-token probe ({started.get('error') or started.get('state')})"
+ _log_tail(sandbox, component))
_keep_log(sandbox, component, ctx)
return {"mode": "full", "model": cfg.get("model_name") or source.stem, "state": started["state"],
"detail": "started, answered a one-token probe, stopped"}
"generation_ready": True, "detail": "started, answered a one-token probe, stopped"}
except TestStartFailed:
_keep_log(sandbox, component, ctx)
raise
except Exception as exc: # noqa: BLE001
raise TestStartFailed(component.version, f"{type(exc).__name__}: {exc}") from None
@@ -911,6 +938,18 @@ def update_app(ctx: Context, feed: feedmod.Feed) -> dict:
# ---------------------------------------------------------------------------------------------- the one command
def _installed_before(name: str, ctx: Context):
"""What was installed when a step failed, for the report: the engine's view, Control's version, or nothing."""
try:
if name == "engine":
return _engine_view(installed_engine(ctx.components, ctx.hardware)[0])
if name == "control":
return (active_control(ctx.components) or {}).get("version") or ec.runtime_version()
except Exception: # noqa: BLE001 - reporting only
pass
return None
def run_update(ctx: Context, *, engine: bool = True, control: bool = True, app: bool = False) -> dict:
"""`strata update`: the feed once, then the engine, Control and (if asked) the app installer, each reported separately.
A component that fails does not undo one that succeeded; the exit code is the worst one."""
@@ -927,7 +966,8 @@ def run_update(ctx: Context, *, engine: bool = True, control: bool = True, app:
try:
results.append(step())
except UpdateError as exc:
results.append({"component": name, "status": "failed", "changed": False, "error": str(exc), "exit_code": exc.exit_code})
results.append({"component": name, "status": "failed", "changed": False, "error": str(exc), "exit_code": exc.exit_code,
"installed_before": _installed_before(name, ctx)})
failure = failure or exc
if any(r.get("component") == "engine" and r.get("status") == "updated" for r in results):
state.data.get("last_check", {}).pop("engine", None)
+26
View File
@@ -406,6 +406,32 @@ class EngineUpdate(UpdaterCase):
self.assertEqual(done.stdout.strip(), "[]")
class LazyModel(UpdaterCase):
"""A server that is "ready" with its model unloaded has not generated anything yet; the test start forces the load and the probe."""
def run_default(self, started, verified):
from strata_control import runtime
self.install_current()
folder = fx.build_package(self.root / "lazy", "0.1.46", key=self.key)
stage = self.root / "stage"
(stage / "engine").mkdir(parents=True)
shutil.copytree(folder, stage / "engine" / folder.name)
component = ec.read_manifest(stage / "engine" / folder.name)
with mock.patch.object(runtime, "start", return_value=started), mock.patch.object(runtime, "verify", return_value=verified) as verify, mock.patch.object(runtime, "stop", return_value={}):
result = updater.default_test_start(stage, component, self.ctx())
return result, verify
def test_an_unloaded_ready_server_is_made_to_answer_before_the_engine_passes(self):
result, verify = self.run_default({"ok": True, "state": "ready", "generation_ready": False},
{"ok": True, "state": "ready", "generation_ready": True})
self.assertEqual(result["generation_ready"], True)
self.assertEqual(verify.call_args.kwargs["load"], True)
def test_an_engine_that_cannot_answer_does_not_pass(self):
with self.assertRaisesRegex(updater.TestStartFailed, "one-token probe"):
self.run_default({"ok": True, "state": "ready", "generation_ready": False}, {"ok": False, "state": "failed", "error": "probe_generation_no_tokens"})
class OtherComponents(UpdaterCase):
def build_with_app(self, version="0.2.0", tamper=False):
public, secret = fx.minisign_pair()