Desktop: never a blank window (frozen-prototype fix, error screens, logs, state migration, boot check)
The signed release showed only its background colour and never started the sidecar. Tauri's freezePrototype freezes Object.prototype before the bundle runs; d3-color and d3-format (under the visx charts) assign `constructor` / `toString` on plain objects while loading, which throws on a frozen prototype, so the bundle stopped before React drew anything. The saved state was not the cause. - build/freeze-safe.ts: Vite plugin that rewrites those assignments in dependencies into a helper that defines the property when the frozen prototype would refuse it - error boundaries for the window, each screen and each app tab (Copy details, Reload, Reset saved state with a backup); public/boot.js shows the same panel when the bundle fails or the window stays empty - logs/host.log (start, saved state, sidecar start/stop, panics) and logs/webview.log (log_webview), rotated, home as ~, keys, tokens and e-mail addresses replaced - state.json `version` 2 with an explicit 1 -> 2 migration (original kept as state.json.v1.bak), per-entry tolerant parsing, partial settings keep their fields, unreadable files kept aside - folders that are gone: "Folder not found" with Locate... (project_locate) / Remove; portfolio reads skip them - tools/desktop-boot-check.ts: the built window with the release CSP and the frozen prototype, a mocked host from the state fixtures (empty, D1 with folders gone, D3) and the real sidecar, through every screen; in bun run ci, the Forgejo CI workflow and the macOS release
This commit is contained in:
parent
209b8d0559
commit
08eb314196
45 changed files with 2080 additions and 69 deletions
|
|
@ -321,10 +321,57 @@ pub async fn write_with_confirm(window: WebviewWindow, app: AppHandle, state: St
|
|||
Ok(json!({ "confirmed": true, "stage": "done", "dryRun": dry, "result": result }))
|
||||
}
|
||||
|
||||
/// An app folder as the window sees it: `missing` when the folder is gone (moved, renamed, deleted, or an old
|
||||
/// worktree), so the app shows "Folder not found" with Locate / Remove instead of reading it.
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ProjectView {
|
||||
#[serde(flatten)]
|
||||
pub project: Project,
|
||||
pub missing: bool,
|
||||
}
|
||||
|
||||
pub fn project_view(p: &Project) -> ProjectView {
|
||||
ProjectView { project: p.clone(), missing: !Path::new(&p.path).is_dir() }
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn projects_list(window: WebviewWindow, state: State<'_, AppState>) -> Res<Vec<Project>> {
|
||||
pub fn projects_list(window: WebviewWindow, state: State<'_, AppState>) -> Res<Vec<ProjectView>> {
|
||||
guard(&window)?;
|
||||
Ok(saved(&state)?.projects.clone())
|
||||
Ok(saved(&state)?.projects.iter().map(project_view).collect())
|
||||
}
|
||||
|
||||
/// "Locate…" for a folder that moved: native folder picker; the folder must hold a storebound.config.ts and not be in
|
||||
/// the list already. Keeps the app's id, accounts, links and saved reads. None = cancelled.
|
||||
#[tauri::command]
|
||||
pub async fn project_locate(window: WebviewWindow, app: AppHandle, state: State<'_, AppState>, id: String) -> Res<Option<ProjectView>> {
|
||||
guard(&window)?;
|
||||
if !saved(&state)?.projects.iter().any(|p| p.id == id) {
|
||||
return Err(Fail::host("unknown project"));
|
||||
}
|
||||
let Some(dir) = pick_folder(&window, "Locate the app folder (with storebound.config.ts)").await? else { return Ok(None) };
|
||||
if !has_config(&dir) {
|
||||
return Err(Fail::host(format!("no storebound.config.ts in {}", dir.display())));
|
||||
}
|
||||
let path = dir.to_string_lossy().to_string();
|
||||
// the app's name from its config when the sidecar can read it; the old name otherwise
|
||||
let name = match state.sidecar.get(&app).await {
|
||||
Ok(r) => r.call("project.inspect", json!({ "project": path })).await.ok().and_then(|v| v["name"].as_str().map(str::to_string)),
|
||||
Err(_) => None,
|
||||
};
|
||||
let mut st = saved(&state)?;
|
||||
if st.projects.iter().any(|p| p.path == path && p.id != id) {
|
||||
return Err(Fail::host("this folder is already in the list"));
|
||||
}
|
||||
let p = st.projects.iter_mut().find(|p| p.id == id).ok_or_else(|| Fail::host("unknown project"))?;
|
||||
p.path = path;
|
||||
if let Some(n) = name.filter(|n| !n.trim().is_empty()) {
|
||||
p.name = n;
|
||||
}
|
||||
let view = project_view(p);
|
||||
persist(&state, &st)?;
|
||||
crate::logs::host("info", &format!("app folder located: {}", view.project.path));
|
||||
Ok(Some(view))
|
||||
}
|
||||
|
||||
const CONFIG_NAMES: [&str; 3] = ["storebound.config.ts", "storebound.config.js", "storebound.config.json"];
|
||||
|
|
@ -671,7 +718,9 @@ pub async fn portfolio_status(window: WebviewWindow, app: AppHandle, state: Stat
|
|||
let (projects, parallel) = {
|
||||
let st = saved(&state)?;
|
||||
let ignored: Vec<&str> = st.overrides.ignored.iter().filter_map(|i| i.strip_prefix("project:")).collect();
|
||||
(st.projects.iter().filter(|p| !ignored.contains(&p.id.as_str())).cloned().collect::<Vec<_>>(), st.settings.refresh.parallel.clamp(1, 8) as usize)
|
||||
// folders that are gone are skipped (the window shows them as "Folder not found")
|
||||
let projects = st.projects.iter().filter(|p| !ignored.contains(&p.id.as_str()) && Path::new(&p.path).is_dir()).cloned().collect::<Vec<_>>();
|
||||
(projects, st.settings.refresh.parallel.clamp(1, 8) as usize)
|
||||
};
|
||||
// store-only apps (live reads only): validated targets with their accounts' credentials
|
||||
let mut targets = Vec::new();
|
||||
|
|
@ -1026,6 +1075,66 @@ pub async fn app_reset(window: WebviewWindow, state: State<'_, AppState>) -> Res
|
|||
Ok(true)
|
||||
}
|
||||
|
||||
/// "Reset saved state" of the error screen: after a native confirmation, state.json is moved aside as
|
||||
/// `state.json.reset-<time>.bak` (nothing is deleted: store keys stay in the keychain, saved reads stay) and the app
|
||||
/// starts with an empty list. The backup's path (~), or null when cancelled.
|
||||
#[tauri::command]
|
||||
pub async fn state_reset(window: WebviewWindow, app: AppHandle, state: State<'_, AppState>) -> Res<Option<String>> {
|
||||
guard(&window)?;
|
||||
let w = window.clone();
|
||||
let yes = tauri::async_runtime::spawn_blocking(move || {
|
||||
w.app_handle()
|
||||
.dialog()
|
||||
.message("storebound forgets its list of app folders, accounts, studios, pairing and settings, and starts empty.\n\nNothing is deleted: the saved state is kept as a backup file in the app data folder, store keys stay in the system keychain, and your app folders are not touched.")
|
||||
.title("Reset saved state?")
|
||||
.kind(MessageDialogKind::Warning)
|
||||
.buttons(MessageDialogButtons::OkCancelCustom("Reset and keep a backup".into(), "Cancel".into()))
|
||||
.parent(&w)
|
||||
.blocking_show()
|
||||
})
|
||||
.await
|
||||
.map_err(|e| Fail::host(e.to_string()))?;
|
||||
if !yes {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut st = saved(&state)?;
|
||||
let backup = store::reset(&state.data_dir).map_err(Fail::host)?;
|
||||
*st = Saved::default();
|
||||
persist(&state, &st)?;
|
||||
let home = app.path().home_dir().ok().map(|h| h.to_string_lossy().to_string());
|
||||
let shown = backup.map(|b| tilde(&b.to_string_lossy(), home.as_deref())).unwrap_or_default();
|
||||
crate::logs::host("warn", &format!("saved state reset from the error screen; backup: {shown}"));
|
||||
Ok(Some(shown))
|
||||
}
|
||||
|
||||
/// Uncaught errors of the window (window.onerror, unhandled rejections, React error boundaries) into
|
||||
/// `<app data>/logs/webview.log`. Sanitized there (home as ~, no keys, tokens or e-mail addresses), size-capped, and
|
||||
/// limited to WEBVIEW_LOG_BURST entries a minute so a render loop cannot fill the disk.
|
||||
#[tauri::command]
|
||||
pub fn log_webview(window: WebviewWindow, level: String, message: String, detail: Option<String>) -> Res<()> {
|
||||
guard(&window)?;
|
||||
static BUDGET: Mutex<(u64, u32)> = Mutex::new((0, 0));
|
||||
let minute = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs() / 60).unwrap_or(0);
|
||||
{
|
||||
let mut b = BUDGET.lock().map_err(|_| Fail::host("log state poisoned"))?;
|
||||
if b.0 != minute {
|
||||
*b = (minute, 0);
|
||||
}
|
||||
b.1 += 1;
|
||||
if b.1 > WEBVIEW_LOG_BURST {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
let text = match detail.filter(|d| !d.trim().is_empty()) {
|
||||
Some(d) => format!("{message}\n{d}"),
|
||||
None => message,
|
||||
};
|
||||
crate::logs::webview(&level, &text);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub const WEBVIEW_LOG_BURST: u32 = 60;
|
||||
|
||||
// ---------------------------------------------------------------------------------------------------------------------
|
||||
// Updates (Settings > Updates): signed bundles from storebound.dev, installed only after the owner's click.
|
||||
|
||||
|
|
|
|||
|
|
@ -42,4 +42,7 @@ pub const COMMANDS: &[&str] = &[
|
|||
"export_save",
|
||||
"price_sheet_pick",
|
||||
"project_reveal",
|
||||
"project_locate",
|
||||
"state_reset",
|
||||
"log_webview",
|
||||
];
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ pub mod cache;
|
|||
pub mod commands;
|
||||
pub mod confirm;
|
||||
pub mod downloads;
|
||||
pub mod logs;
|
||||
pub mod policy;
|
||||
pub mod selftest;
|
||||
pub mod updates;
|
||||
|
|
@ -140,9 +141,22 @@ pub fn run() {
|
|||
.plugin(tauri_plugin_process::init())
|
||||
.setup(|app| {
|
||||
let data_dir = app.path().app_data_dir()?;
|
||||
logs::init(&data_dir, app.path().home_dir().ok().map(|h| h.to_string_lossy().to_string()));
|
||||
logs::panic_hook();
|
||||
logs::host("info", &format!("storebound desktop {} starting ({} {}{})", env!("CARGO_PKG_VERSION"), std::env::consts::OS, std::env::consts::ARCH, if cfg!(debug_assertions) { ", debug" } else { "" }));
|
||||
dev_seed(&data_dir);
|
||||
let cache = cache::Cache::open(&data_dir).or_else(|_| cache::Cache::in_memory()).map_err(std::io::Error::other)?;
|
||||
let saved = store::load(&data_dir);
|
||||
let (saved, report) = store::load_report(&data_dir);
|
||||
logs::host("info", &format!("saved state: {} app folders ({} not found), {} accounts, {} studios, format {}", saved.projects.len(), saved.projects.iter().filter(|p| !std::path::Path::new(&p.path).is_dir()).count(), saved.accounts.len(), saved.studios.len(), saved.version));
|
||||
if let Some(from) = report.migrated_from {
|
||||
logs::host("info", &format!("saved state migrated from format {from} to {}", store::VERSION));
|
||||
}
|
||||
for n in &report.notes {
|
||||
logs::host("warn", &format!("saved state: {n}"));
|
||||
}
|
||||
if let Some(b) = &report.backup {
|
||||
logs::host("info", &format!("saved state: original kept as {}", b.display()));
|
||||
}
|
||||
let keep_days = saved.settings.cache.keep_days;
|
||||
let state = commands::AppState {
|
||||
sidecar: sidecar::Sidecar::default(),
|
||||
|
|
@ -225,6 +239,9 @@ pub fn run() {
|
|||
commands::export_save,
|
||||
commands::price_sheet_pick,
|
||||
commands::project_reveal,
|
||||
commands::project_locate,
|
||||
commands::state_reset,
|
||||
commands::log_webview,
|
||||
])
|
||||
.build(tauri::generate_context!())
|
||||
.expect("storebound desktop failed to start");
|
||||
|
|
|
|||
213
apps/desktop/src-tauri/src/logs.rs
Normal file
213
apps/desktop/src-tauri/src/logs.rs
Normal file
|
|
@ -0,0 +1,213 @@
|
|||
//! Local diagnostics in `<app data>/logs`: `host.log` (this process: start, saved state, sidecar, panics) and
|
||||
//! `webview.log` (uncaught errors of the window, sent through the `log_webview` command). Each file is rotated at
|
||||
//! MAX_BYTES (one older `.1.log` kept). Every line goes through `sanitize`: the home folder shows as `~`, and keys,
|
||||
//! tokens, long secrets and e-mail addresses are replaced, so a log can be attached to a bug report as it is.
|
||||
use std::fs::{self, OpenOptions};
|
||||
use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Mutex, OnceLock};
|
||||
|
||||
pub const DIR: &str = "logs";
|
||||
pub const HOST: &str = "host.log";
|
||||
pub const WEBVIEW: &str = "webview.log";
|
||||
pub const MAX_BYTES: u64 = 512 * 1024;
|
||||
/// Longest single entry kept (the rest is cut).
|
||||
pub const MAX_ENTRY: usize = 16 * 1024;
|
||||
|
||||
struct Logs {
|
||||
dir: PathBuf,
|
||||
home: Option<String>,
|
||||
lock: Mutex<()>,
|
||||
}
|
||||
|
||||
static LOGS: OnceLock<Logs> = OnceLock::new();
|
||||
|
||||
/// Sets the log folder once (the first call wins).
|
||||
pub fn init(data_dir: &Path, home: Option<String>) {
|
||||
let _ = LOGS.set(Logs { dir: data_dir.join(DIR), home, lock: Mutex::new(()) });
|
||||
}
|
||||
|
||||
pub fn dir() -> Option<PathBuf> {
|
||||
LOGS.get().map(|l| l.dir.clone())
|
||||
}
|
||||
|
||||
/// One line in host.log (no-op before `init`).
|
||||
pub fn host(level: &str, message: &str) {
|
||||
write(HOST, "host", level, message);
|
||||
}
|
||||
|
||||
/// One entry in webview.log.
|
||||
pub fn webview(level: &str, message: &str) {
|
||||
write(WEBVIEW, "webview", level, message);
|
||||
}
|
||||
|
||||
fn write(file: &str, source: &str, level: &str, message: &str) {
|
||||
let Some(l) = LOGS.get() else { return };
|
||||
let _g = l.lock.lock();
|
||||
let level = match level {
|
||||
"error" | "warn" | "info" | "debug" => level,
|
||||
_ => "info",
|
||||
};
|
||||
let text = sanitize(message, l.home.as_deref());
|
||||
let line = entry(&crate::store::now_iso(), source, level, &text);
|
||||
let _ = append(&l.dir, file, &line);
|
||||
}
|
||||
|
||||
/// `<time> <level> [<source>] <text>`; continuation lines are indented.
|
||||
pub fn entry(at: &str, source: &str, level: &str, text: &str) -> String {
|
||||
let mut t: String = text.chars().take(MAX_ENTRY).collect();
|
||||
if t.len() < text.len() {
|
||||
t.push_str(" [cut]");
|
||||
}
|
||||
format!("{at} {level:<5} [{source}] {}\n", t.trim_end().replace('\n', "\n "))
|
||||
}
|
||||
|
||||
/// Appends, rotating first when the file would pass MAX_BYTES.
|
||||
pub fn append(dir: &Path, file: &str, line: &str) -> std::io::Result<()> {
|
||||
fs::create_dir_all(dir)?;
|
||||
let path = dir.join(file);
|
||||
if fs::metadata(&path).map(|m| m.len() + line.len() as u64 > MAX_BYTES).unwrap_or(false) {
|
||||
let old = dir.join(file.replace(".log", ".1.log"));
|
||||
let _ = fs::remove_file(&old);
|
||||
fs::rename(&path, &old)?;
|
||||
}
|
||||
OpenOptions::new().create(true).append(true).open(&path)?.write_all(line.as_bytes())
|
||||
}
|
||||
|
||||
const SECRET_KEYS: &[&str] = &["secret", "token", "password", "passwd", "private_key", "privatekey", "apikey", "api_key", "authorization", "credential", "p8"];
|
||||
|
||||
/// The home folder as `~`, then keys, tokens and e-mail addresses replaced. Control characters other than newline and
|
||||
/// tab are dropped.
|
||||
pub fn sanitize(text: &str, home: Option<&str>) -> String {
|
||||
let mut s: String = text.chars().filter(|c| !c.is_control() || *c == '\n' || *c == '\t').collect();
|
||||
if let Some(h) = home.map(|h| h.trim_end_matches(['/', '\\'])).filter(|h| h.len() > 1) {
|
||||
s = s.replace(h, "~");
|
||||
}
|
||||
s = redact_pem(&s);
|
||||
s = redact_assignments(&s);
|
||||
redact_words(&s)
|
||||
}
|
||||
|
||||
fn redact_pem(s: &str) -> String {
|
||||
let mut out = String::new();
|
||||
let mut rest = s;
|
||||
while let Some(i) = rest.find("-----BEGIN") {
|
||||
out.push_str(&rest[..i]);
|
||||
let after = &rest[i..];
|
||||
match after.find("-----END").and_then(|e| after[e + 8..].find("-----").map(|k| e + 8 + k + 5)) {
|
||||
Some(end) => {
|
||||
out.push_str("[redacted key]");
|
||||
rest = &after[end..];
|
||||
}
|
||||
None => {
|
||||
out.push_str("[redacted key]");
|
||||
rest = "";
|
||||
}
|
||||
}
|
||||
}
|
||||
out.push_str(rest);
|
||||
out
|
||||
}
|
||||
|
||||
/// `token=...`, `"password": "..."`, `Authorization: Bearer ...`: the value goes.
|
||||
fn redact_assignments(s: &str) -> String {
|
||||
let lower = s.to_ascii_lowercase();
|
||||
let b = s.as_bytes();
|
||||
let mut cut: Vec<(usize, usize)> = Vec::new();
|
||||
for k in SECRET_KEYS {
|
||||
let mut from = 0;
|
||||
while let Some(i) = lower[from..].find(k) {
|
||||
let mut j = i + from + k.len();
|
||||
from = j;
|
||||
// rest of the key name ("tokenId", "secret_key"), a closing quote, spaces, then ':' or '='
|
||||
while j < b.len() && (b[j].is_ascii_alphanumeric() || b[j] == b'_' || b[j] == b'-') {
|
||||
j += 1;
|
||||
}
|
||||
while j < b.len() && (b[j] == b'"' || b[j] == b'\'' || b[j] == b' ') {
|
||||
j += 1;
|
||||
}
|
||||
if j >= b.len() || (b[j] != b':' && b[j] != b'=') {
|
||||
continue;
|
||||
}
|
||||
j += 1;
|
||||
while j < b.len() && (b[j] == b' ' || b[j] == b'"' || b[j] == b'\'') {
|
||||
j += 1;
|
||||
}
|
||||
if lower[j..].starts_with("bearer ") || lower[j..].starts_with("basic ") {
|
||||
j += lower[j..].find(' ').unwrap_or(0) + 1;
|
||||
}
|
||||
let start = j;
|
||||
while j < b.len() && !matches!(b[j], b'"' | b'\'' | b',' | b'}' | b' ' | b'\n' | b'&' | b';') {
|
||||
j += 1;
|
||||
}
|
||||
if j > start {
|
||||
cut.push((start, j));
|
||||
}
|
||||
}
|
||||
}
|
||||
cut.sort();
|
||||
let mut out = String::new();
|
||||
let mut at = 0;
|
||||
for (a, z) in cut {
|
||||
if a < at {
|
||||
continue;
|
||||
}
|
||||
out.push_str(&s[at..a]);
|
||||
out.push_str("[redacted]");
|
||||
at = z;
|
||||
}
|
||||
out.push_str(&s[at..]);
|
||||
out
|
||||
}
|
||||
|
||||
/// Long random-looking words (keys, JWTs, hashes of 32+ characters with letters and digits) and e-mail addresses.
|
||||
fn redact_words(s: &str) -> String {
|
||||
let is_word = |c: char| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '+' | '/' | '=' | '.' | '@');
|
||||
let mut out = String::with_capacity(s.len());
|
||||
let mut word = String::new();
|
||||
let flush = |w: &mut String, out: &mut String| {
|
||||
if !w.is_empty() {
|
||||
out.push_str(&judge(w));
|
||||
w.clear();
|
||||
}
|
||||
};
|
||||
for c in s.chars() {
|
||||
if is_word(c) {
|
||||
word.push(c);
|
||||
} else {
|
||||
flush(&mut word, &mut out);
|
||||
out.push(c);
|
||||
}
|
||||
}
|
||||
flush(&mut word, &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
fn judge(w: &str) -> String {
|
||||
if let Some((user, domain)) = w.split_once('@') {
|
||||
if !user.is_empty() && domain.contains('.') && !domain.starts_with('.') {
|
||||
return "[email]".into();
|
||||
}
|
||||
}
|
||||
let mixed = |p: &str| p.chars().any(|c| c.is_ascii_alphabetic()) && p.chars().any(|c| c.is_ascii_digit());
|
||||
// a long base64 / hex run (may hold '/' or '+'): not a path, not a dotted name
|
||||
if w.len() >= 40 && !w.starts_with(['/', '~']) && !w.contains('.') && mixed(w) {
|
||||
return "[redacted]".into();
|
||||
}
|
||||
// paths and dotted names stay (file names in stacks); one long run of key-like characters inside them goes
|
||||
for part in w.split(['/', '.']) {
|
||||
if part.len() >= 32 && mixed(part) {
|
||||
return w.replace(part, "[redacted]");
|
||||
}
|
||||
}
|
||||
w.to_string()
|
||||
}
|
||||
|
||||
/// Records panics in host.log (release builds abort right after).
|
||||
pub fn panic_hook() {
|
||||
let prev = std::panic::take_hook();
|
||||
std::panic::set_hook(Box::new(move |info| {
|
||||
host("error", &format!("panic: {info}"));
|
||||
prev(info);
|
||||
}));
|
||||
}
|
||||
|
|
@ -187,7 +187,14 @@ impl Sidecar {
|
|||
return Ok(r.clone());
|
||||
}
|
||||
}
|
||||
let r = Arc::new(start(app).await?);
|
||||
let r = match start(app).await {
|
||||
Ok(r) => Arc::new(r),
|
||||
Err(e) => {
|
||||
crate::logs::host("error", &format!("sidecar did not start: {}", e.message));
|
||||
return Err(e);
|
||||
}
|
||||
};
|
||||
crate::logs::host("info", &format!("sidecar started: storebound {} ({})", r.version, r.protocol));
|
||||
*cur = Some(r.clone());
|
||||
Ok(r)
|
||||
}
|
||||
|
|
@ -249,6 +256,9 @@ async fn start<R: Runtime>(app: &AppHandle<R>) -> Result<Running, Fail> {
|
|||
tauri::async_runtime::spawn(async move {
|
||||
let mut out: Vec<u8> = Vec::new();
|
||||
let mut err: Vec<u8> = Vec::new();
|
||||
// the last stderr lines, written to host.log when the sidecar stops
|
||||
let mut tail: std::collections::VecDeque<String> = std::collections::VecDeque::new();
|
||||
let mut end = String::from("closed");
|
||||
while let Some(ev) = rx.recv().await {
|
||||
match ev {
|
||||
CommandEvent::Stdout(bytes) => {
|
||||
|
|
@ -262,16 +272,30 @@ async fn start<R: Runtime>(app: &AppHandle<R>) -> Result<Running, Fail> {
|
|||
err.extend_from_slice(&bytes);
|
||||
while let Some(nl) = err.iter().position(|b| *b == b'\n') {
|
||||
let line: Vec<u8> = err.drain(..=nl).collect();
|
||||
let text = String::from_utf8_lossy(&line).to_string();
|
||||
if cfg!(debug_assertions) {
|
||||
eprint!("[sidecar] {}", String::from_utf8_lossy(&line));
|
||||
eprint!("[sidecar] {text}");
|
||||
}
|
||||
if tail.len() == 20 {
|
||||
tail.pop_front();
|
||||
}
|
||||
tail.push_back(text.trim_end().to_string());
|
||||
}
|
||||
}
|
||||
CommandEvent::Terminated(_) | CommandEvent::Error(_) => break,
|
||||
CommandEvent::Terminated(t) => {
|
||||
end = format!("exit code {:?}, signal {:?}", t.code, t.signal);
|
||||
break;
|
||||
}
|
||||
CommandEvent::Error(e) => {
|
||||
end = format!("error: {e}");
|
||||
break;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
a.store(false, Ordering::SeqCst);
|
||||
let expected = !a.swap(false, Ordering::SeqCst);
|
||||
let tail: Vec<String> = tail.into_iter().collect();
|
||||
crate::logs::host(if expected { "info" } else { "warn" }, &format!("sidecar stopped ({end}){}", if tail.is_empty() { String::new() } else { format!("\n{}", tail.join("\n")) }));
|
||||
if let Ok(mut map) = p.lock() {
|
||||
for (_, tx) in map.drain() {
|
||||
let _ = tx.send(Err(Fail::host("the storebound sidecar stopped")));
|
||||
|
|
|
|||
|
|
@ -3,7 +3,9 @@
|
|||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use serde::de::DeserializeOwned;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
use crate::accounts::Account;
|
||||
use crate::workspace::{Overrides, Settings, Studio};
|
||||
|
|
@ -14,16 +16,25 @@ pub struct Project {
|
|||
pub id: String,
|
||||
/// Absolute folder that holds storebound.config.ts.
|
||||
pub path: String,
|
||||
/// Filled from the folder name when an old or hand-edited file has none.
|
||||
#[serde(default)]
|
||||
pub name: String,
|
||||
#[serde(default)]
|
||||
pub play_account: Option<String>,
|
||||
#[serde(default)]
|
||||
pub apple_account: Option<String>,
|
||||
#[serde(default)]
|
||||
pub added: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
/// The state file format. Files without `version` are format 1 (desktop D1 to D3: projects and accounts, later
|
||||
/// studios, overrides and settings, all optional); `migrate` lifts them to this one.
|
||||
pub const VERSION: u32 = 2;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct State {
|
||||
#[serde(default)]
|
||||
pub version: u32,
|
||||
#[serde(default)]
|
||||
pub projects: Vec<Project>,
|
||||
#[serde(default)]
|
||||
|
|
@ -36,16 +47,172 @@ pub struct State {
|
|||
pub settings: Settings,
|
||||
}
|
||||
|
||||
impl Default for State {
|
||||
fn default() -> State {
|
||||
State { version: VERSION, projects: vec![], accounts: vec![], studios: vec![], overrides: Overrides::default(), settings: Settings::default() }
|
||||
}
|
||||
}
|
||||
|
||||
pub const FILE: &str = "state.json";
|
||||
|
||||
/// What `load_report` found besides the state: the format it migrated from, entries it had to drop, and where the
|
||||
/// original file was kept. Logged in host.log; nothing here is fatal.
|
||||
#[derive(Debug, Default, PartialEq, Eq)]
|
||||
pub struct LoadReport {
|
||||
pub migrated_from: Option<u32>,
|
||||
pub notes: Vec<String>,
|
||||
pub backup: Option<PathBuf>,
|
||||
}
|
||||
|
||||
pub fn load(dir: &Path) -> State {
|
||||
fs::read_to_string(dir.join(FILE)).ok().and_then(|s| serde_json::from_str(&s).ok()).unwrap_or_default()
|
||||
load_report(dir).0
|
||||
}
|
||||
|
||||
/// Reads state.json and migrates it to VERSION. Never fails: an unreadable file is kept as a backup and the app starts
|
||||
/// empty; entries that do not parse are dropped one by one (and named in the report) instead of losing the whole file.
|
||||
/// A migrated file is written back in the new format after the original is copied to `state.json.v<old>.bak`.
|
||||
pub fn load_report(dir: &Path) -> (State, LoadReport) {
|
||||
let mut report = LoadReport::default();
|
||||
let path = dir.join(FILE);
|
||||
let text = match fs::read_to_string(&path) {
|
||||
Ok(t) => t,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return (State::default(), report),
|
||||
Err(e) => {
|
||||
report.notes.push(format!("state.json unreadable ({e})"));
|
||||
report.backup = keep_copy(dir, &format!("{FILE}.unreadable-{}", stamp()));
|
||||
return (State::default(), report);
|
||||
}
|
||||
};
|
||||
let value: Value = match serde_json::from_str(&text) {
|
||||
Ok(v @ Value::Object(_)) => v,
|
||||
Ok(_) | Err(_) => {
|
||||
report.notes.push("state.json is not a JSON object: started empty".into());
|
||||
report.backup = keep_copy(dir, &format!("{FILE}.unreadable-{}", stamp()));
|
||||
return (State::default(), report);
|
||||
}
|
||||
};
|
||||
let (state, from, notes) = migrate(value);
|
||||
report.notes = notes;
|
||||
if from < VERSION {
|
||||
report.migrated_from = Some(from);
|
||||
report.backup = keep_copy(dir, &format!("{FILE}.v{from}.bak"));
|
||||
if let Err(e) = save(dir, &state) {
|
||||
report.notes.push(format!("migrated state not written: {e}"));
|
||||
}
|
||||
} else if from > VERSION {
|
||||
report.notes.push(format!("state.json is format {from}, newer than this app ({VERSION}): read what it understands"));
|
||||
}
|
||||
(state, report)
|
||||
}
|
||||
|
||||
/// Lifts a state file of any known format to VERSION. Returns the state, the format it had, and notes on dropped
|
||||
/// entries. Pure: tests call it on the old formats directly.
|
||||
pub fn migrate(mut v: Value) -> (State, u32, Vec<String>) {
|
||||
let from = v.get("version").and_then(Value::as_u64).map(|n| n.min(u32::MAX as u64) as u32).unwrap_or(1);
|
||||
let mut notes = Vec::new();
|
||||
if from < 2 {
|
||||
migrate_1_to_2(&mut v);
|
||||
}
|
||||
let o = v.as_object().cloned().unwrap_or_default();
|
||||
let mut state = State {
|
||||
version: VERSION.max(from),
|
||||
projects: list(&o, "projects", &mut notes),
|
||||
accounts: list(&o, "accounts", &mut notes),
|
||||
studios: list(&o, "studios", &mut notes),
|
||||
overrides: one(&o, "overrides", &mut notes),
|
||||
settings: one(&o, "settings", &mut notes),
|
||||
};
|
||||
// two entries with one id (hand-edited or merged files): the first one wins
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
state.projects.retain(|p| seen.insert(p.id.clone()));
|
||||
for p in &mut state.projects {
|
||||
if p.name.trim().is_empty() {
|
||||
p.name = Path::new(&p.path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "App".into());
|
||||
}
|
||||
}
|
||||
(state, from, notes)
|
||||
}
|
||||
|
||||
/// Format 1 -> 2: `version` added; studios, overrides and settings (added in D3) written out with their defaults, and
|
||||
/// each account gets an explicit `studio` (null). Fields this app does not know are left alone.
|
||||
fn migrate_1_to_2(v: &mut Value) {
|
||||
let Some(o) = v.as_object_mut() else { return };
|
||||
for k in ["projects", "accounts", "studios"] {
|
||||
if !o.get(k).is_some_and(Value::is_array) {
|
||||
o.insert(k.into(), Value::Array(vec![]));
|
||||
}
|
||||
}
|
||||
if !o.get("overrides").is_some_and(Value::is_object) {
|
||||
o.insert("overrides".into(), serde_json::to_value(Overrides::default()).unwrap_or(Value::Null));
|
||||
}
|
||||
if !o.get("settings").is_some_and(Value::is_object) {
|
||||
o.insert("settings".into(), serde_json::to_value(Settings::default()).unwrap_or(Value::Null));
|
||||
}
|
||||
if let Some(Value::Array(accs)) = o.get_mut("accounts") {
|
||||
for a in accs.iter_mut().filter_map(Value::as_object_mut) {
|
||||
a.entry("studio").or_insert(Value::Null);
|
||||
}
|
||||
}
|
||||
o.insert("version".into(), Value::from(2));
|
||||
}
|
||||
|
||||
fn list<T: DeserializeOwned>(o: &Map<String, Value>, key: &str, notes: &mut Vec<String>) -> Vec<T> {
|
||||
let Some(items) = o.get(key).and_then(Value::as_array) else { return vec![] };
|
||||
items
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(i, x)| match serde_json::from_value::<T>(x.clone()) {
|
||||
Ok(t) => Some(t),
|
||||
Err(e) => {
|
||||
notes.push(format!("{key}[{i}] dropped: {e}"));
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn one<T: DeserializeOwned + Default>(o: &Map<String, Value>, key: &str, notes: &mut Vec<String>) -> T {
|
||||
match o.get(key) {
|
||||
None | Some(Value::Null) => T::default(),
|
||||
Some(x) => serde_json::from_value(x.clone()).unwrap_or_else(|e| {
|
||||
notes.push(format!("{key} reset to defaults: {e}"));
|
||||
T::default()
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// Copies state.json to `name` in the same folder (an existing copy is kept). The copy's path, or None.
|
||||
fn keep_copy(dir: &Path, name: &str) -> Option<PathBuf> {
|
||||
let to = dir.join(name);
|
||||
if to.exists() {
|
||||
return Some(to);
|
||||
}
|
||||
fs::copy(dir.join(FILE), &to).ok().map(|_| to)
|
||||
}
|
||||
|
||||
/// Moves state.json aside as `state.json.reset-<time>.bak` (Reset saved state). The backup's path; None when there was
|
||||
/// no file.
|
||||
pub fn reset(dir: &Path) -> Result<Option<PathBuf>, String> {
|
||||
let from = dir.join(FILE);
|
||||
if !from.exists() {
|
||||
return Ok(None);
|
||||
}
|
||||
let to = dir.join(format!("{FILE}.reset-{}.bak", stamp()));
|
||||
fs::rename(&from, &to).map_err(|e| e.to_string())?;
|
||||
Ok(Some(to))
|
||||
}
|
||||
|
||||
/// File-name-safe UTC time: 20261011T101500Z.
|
||||
fn stamp() -> String {
|
||||
now_iso().replace(['-', ':'], "")
|
||||
}
|
||||
|
||||
pub fn save(dir: &Path, state: &State) -> Result<(), String> {
|
||||
fs::create_dir_all(dir).map_err(|e| e.to_string())?;
|
||||
let tmp: PathBuf = dir.join(format!("{FILE}.tmp"));
|
||||
let json = serde_json::to_string_pretty(state).map_err(|e| e.to_string())?;
|
||||
let mut state = state.clone();
|
||||
state.version = state.version.max(VERSION);
|
||||
let json = serde_json::to_string_pretty(&state).map_err(|e| e.to_string())?;
|
||||
fs::write(&tmp, json + "\n").map_err(|e| e.to_string())?;
|
||||
fs::rename(&tmp, dir.join(FILE)).map_err(|e| e.to_string())
|
||||
}
|
||||
|
|
|
|||
|
|
@ -242,7 +242,7 @@ pub fn check_overrides(o: &Overrides) -> Result<(), String> {
|
|||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[serde(rename_all = "camelCase", default)]
|
||||
pub struct RefreshSettings {
|
||||
/// Minutes between automatic store reads; 0 = off.
|
||||
pub auto_minutes: u32,
|
||||
|
|
@ -254,14 +254,14 @@ pub struct RefreshSettings {
|
|||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[serde(rename_all = "camelCase", default)]
|
||||
pub struct CacheSettings {
|
||||
/// Saved reads older than this many days are dropped; 0 = keep.
|
||||
pub keep_days: u32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[serde(rename_all = "camelCase", default)]
|
||||
pub struct NotifySettings {
|
||||
pub review_state: bool,
|
||||
pub low_reviews: bool,
|
||||
|
|
@ -269,7 +269,7 @@ pub struct NotifySettings {
|
|||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[serde(rename_all = "camelCase", default)]
|
||||
pub struct Settings {
|
||||
pub refresh: RefreshSettings,
|
||||
pub cache: CacheSettings,
|
||||
|
|
@ -278,14 +278,29 @@ pub struct Settings {
|
|||
pub channel: String,
|
||||
}
|
||||
|
||||
// Every settings struct fills a missing field with its default (`#[serde(default)]`), so a file written by an older
|
||||
// build that lacks a newer setting keeps the rest.
|
||||
impl Default for RefreshSettings {
|
||||
fn default() -> RefreshSettings {
|
||||
RefreshSettings { auto_minutes: 0, on_launch: false, parallel: 4, icons: true }
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for CacheSettings {
|
||||
fn default() -> CacheSettings {
|
||||
CacheSettings { keep_days: 30 }
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for NotifySettings {
|
||||
fn default() -> NotifySettings {
|
||||
NotifySettings { review_state: true, low_reviews: true, crash: true }
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Settings {
|
||||
fn default() -> Settings {
|
||||
Settings {
|
||||
refresh: RefreshSettings { auto_minutes: 0, on_launch: false, parallel: 4, icons: true },
|
||||
cache: CacheSettings { keep_days: 30 },
|
||||
notify: NotifySettings { review_state: true, low_reviews: true, crash: true },
|
||||
channel: "stable".into(),
|
||||
}
|
||||
Settings { refresh: RefreshSettings::default(), cache: CacheSettings::default(), notify: NotifySettings::default(), channel: "stable".into() }
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue