mirror of
https://github.com/storytold/materialcraft.git
synced 2026-11-26 01:11:00 +01:00
Combine worker panic reporting with cancellation and cook epoch protection
This commit is contained in:
commit
4f5b1a29bb
6 files changed
+161
-20
No files matched your search
@@ -225,7 +225,7 @@ pub fn handle(app: &mut MaterialCraftApp, ctx: &egui::Context, method: &str, p:
|
||||
"command.run" => {
|
||||
let Some(id) = p.get("id").and_then(Value::as_str) else { return err("`id` is required") };
|
||||
let params = p.get("params").cloned().unwrap_or(Value::Null);
|
||||
match materialcraft_engine::execute(&mut app.session, id, ¶ms) {
|
||||
match crate::cook::execute_guarded(&mut app.session, id, ¶ms) {
|
||||
Ok(v) => {
|
||||
if id == "view.previewSize" {
|
||||
app.ui.prefs.preview_size = app.session.preview_size.unwrap_or(0);
|
||||
|
||||
+56
-14
@@ -1,15 +1,41 @@
|
||||
//! Background cooking: when the open graph changes, a worker thread cooks a snapshot of the
|
||||
//! package through the shared cache while the UI keeps drawing the previous results.
|
||||
|
||||
use std::panic::{AssertUnwindSafe, catch_unwind};
|
||||
use std::sync::mpsc::{Receiver, TryRecvError};
|
||||
|
||||
use materialcraft_engine::eval::Cooked;
|
||||
use materialcraft_engine::eval::{Cooked, NodeResult};
|
||||
|
||||
use crate::MaterialCraftApp;
|
||||
|
||||
/// Run `f`, turning a panic into an error naming `what`, so one bad node or command can't take
|
||||
/// the app (and unsaved work) down.
|
||||
pub fn guard<T>(what: &str, f: impl FnOnce() -> Result<T, String>) -> Result<T, String> {
|
||||
catch_unwind(AssertUnwindSafe(f)).unwrap_or_else(|p| {
|
||||
let msg = p.downcast_ref::<&str>().map(|s| s.to_string()).or_else(|| p.downcast_ref::<String>().cloned()).unwrap_or_default();
|
||||
Err(format!("internal error in {what}: {msg}"))
|
||||
})
|
||||
}
|
||||
|
||||
/// Run an engine command; a panic inside it becomes an error reply (the session is kept).
|
||||
pub fn execute_guarded(session: &mut materialcraft_engine::Session, id: &str, params: &serde_json::Value) -> Result<serde_json::Value, String> {
|
||||
guard(&format!("command `{id}`"), || materialcraft_engine::execute(session, id, params).map_err(|e| e.to_string()))
|
||||
}
|
||||
|
||||
/// A cook that crashed or died: every node of the open graph shows the error instead of stale
|
||||
/// previews, and the user sees a toast.
|
||||
fn report_failure(app: &mut MaterialCraftApp, msg: String) {
|
||||
let ids: Vec<_> = app.session.graph().map(|g| g.nodes.iter().map(|n| n.id).collect()).unwrap_or_default();
|
||||
app.session.cooked = Cooked::default();
|
||||
for id in ids {
|
||||
app.session.cooked.nodes.insert(id, NodeResult { outputs: Default::default(), error: Some(msg.clone()), ms: 0.0, key: 0, cached: false });
|
||||
}
|
||||
app.toast(msg, true);
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Cooker {
|
||||
rx: Option<Receiver<Cooked>>,
|
||||
rx: Option<Receiver<Result<Cooked, String>>>,
|
||||
/// Stops the running cook between nodes once its result is stale.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
cancel: Option<std::sync::Arc<std::sync::atomic::AtomicBool>>,
|
||||
@@ -29,21 +55,24 @@ impl Cooker {
|
||||
pub fn drive(app: &mut MaterialCraftApp, ctx: &egui::Context) {
|
||||
if let Some(rx) = &app.cooker.rx {
|
||||
match rx.try_recv() {
|
||||
Ok(c) => {
|
||||
if c.cancelled {
|
||||
// A stopped cook is partial: keep the previous results and cook again.
|
||||
app.session.dirty = true;
|
||||
} else if !app.session.dirty && app.cooker.epoch == app.session.cook_epoch {
|
||||
// (A synchronous cook, e.g. `session.inspect`, since this one started is newer:
|
||||
// its results stand and this stale snapshot is dropped.)
|
||||
app.session.cooked = c;
|
||||
}
|
||||
Ok(result) => {
|
||||
app.cooker.rx = None;
|
||||
app.cooker.started = None;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
app.cooker.cancel = None;
|
||||
}
|
||||
match result {
|
||||
// A stopped cook is partial: keep the previous results and cook again.
|
||||
Ok(c) if c.cancelled => app.session.dirty = true,
|
||||
Ok(c) => {
|
||||
if !app.session.dirty && app.cooker.epoch == app.session.cook_epoch {
|
||||
app.session.cooked = c;
|
||||
}
|
||||
}
|
||||
Err(msg) if !app.session.dirty && app.cooker.epoch == app.session.cook_epoch => report_failure(app, msg),
|
||||
Err(_) => {}
|
||||
}
|
||||
ctx.request_repaint();
|
||||
}
|
||||
Err(TryRecvError::Empty) if app.session.dirty => {
|
||||
@@ -63,6 +92,9 @@ pub fn drive(app: &mut MaterialCraftApp, ctx: &egui::Context) {
|
||||
Err(TryRecvError::Disconnected) => {
|
||||
app.cooker.rx = None;
|
||||
app.cooker.started = None;
|
||||
if !app.session.dirty && app.cooker.epoch == app.session.cook_epoch {
|
||||
report_failure(app, "the cook worker stopped unexpectedly".into());
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
app.cooker.cancel = None;
|
||||
@@ -93,7 +125,7 @@ fn start(app: &mut MaterialCraftApp, now: f64) {
|
||||
let mut opts = Options::new(&dec);
|
||||
opts.max_size = max;
|
||||
opts.cancel = Some(&thread_flag);
|
||||
let cooked = materialcraft_engine::eval::cook(&pkg, gi, &opts, &cache);
|
||||
let cooked = guard("cook", || Ok(materialcraft_engine::eval::cook(&pkg, gi, &opts, &cache)));
|
||||
let _ = tx.send(cooked);
|
||||
});
|
||||
match spawned {
|
||||
@@ -105,15 +137,25 @@ fn start(app: &mut MaterialCraftApp, now: f64) {
|
||||
}
|
||||
Err(e) => {
|
||||
log::warn!("could not start a cook thread ({e}); cooking here");
|
||||
app.session.cook();
|
||||
cook_here(app);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn cook_here(app: &mut MaterialCraftApp) {
|
||||
if let Err(msg) = guard("cook", || {
|
||||
app.session.cook();
|
||||
Ok(())
|
||||
}) {
|
||||
app.session.dirty = false;
|
||||
report_failure(app, msg);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn start(app: &mut MaterialCraftApp, _now: f64) {
|
||||
// shortcut: no threads on the web; the cook runs on the UI thread (the page pauses).
|
||||
app.session.cook();
|
||||
cook_here(app);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -37,3 +37,75 @@ mod cook_tests {
|
||||
assert!(app.session.cooked.nodes.contains_key(&id), "stale cook replaced the newer results");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod worker_failure_tests {
|
||||
use crate::MaterialCraftApp;
|
||||
use crate::cook::{drive, guard};
|
||||
use crate::state::UiState;
|
||||
use materialcraft_engine::eval::Cooked;
|
||||
use materialcraft_engine::sample_session;
|
||||
|
||||
fn app() -> MaterialCraftApp {
|
||||
let mut session = sample_session();
|
||||
session.preview_size = Some(64);
|
||||
session.cook();
|
||||
MaterialCraftApp::headless(session, UiState::default())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn guard_turns_a_panic_into_an_error() {
|
||||
let r: Result<u32, String> = guard("test", || -> Result<u32, String> { panic!("boom") });
|
||||
let e = r.unwrap_err();
|
||||
assert!(e.contains("boom"), "{e}");
|
||||
assert_eq!(guard("test", || Ok::<_, String>(7)).unwrap(), 7);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_panicked_cook_worker_reports_errors_on_every_node() {
|
||||
let mut app = app();
|
||||
assert!(app.session.cook_failures().0.is_empty());
|
||||
let (tx, rx) = std::sync::mpsc::channel::<Result<Cooked, String>>();
|
||||
app.cooker.rx = Some(rx);
|
||||
app.cooker.epoch = app.session.cook_epoch;
|
||||
tx.send(Err("boom".into())).unwrap();
|
||||
app.session.dirty = false;
|
||||
drive(&mut app, &egui::Context::default());
|
||||
assert!(!app.cooker.busy());
|
||||
let (failed, _) = app.session.cook_failures();
|
||||
assert!(!failed.is_empty());
|
||||
assert!(failed.iter().all(|(_, e)| e.contains("boom")));
|
||||
assert!(app.toasts.iter().any(|t| t.error && t.text.contains("boom")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dead_cook_worker_is_reported_not_silent() {
|
||||
let mut app = app();
|
||||
let (tx, rx) = std::sync::mpsc::channel::<Result<Cooked, String>>();
|
||||
app.cooker.rx = Some(rx);
|
||||
app.cooker.epoch = app.session.cook_epoch;
|
||||
drop(tx);
|
||||
app.session.dirty = false;
|
||||
drive(&mut app, &egui::Context::default());
|
||||
assert!(!app.cooker.busy());
|
||||
assert!(app.toasts.iter().any(|t| t.error));
|
||||
assert!(!app.session.cook_failures().0.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_worker_failure_does_not_replace_a_newer_sync_cook() {
|
||||
let mut session = materialcraft_engine::sample_session();
|
||||
session.preview_size = Some(64);
|
||||
session.cook();
|
||||
let mut app = crate::MaterialCraftApp::headless(session, crate::UiState::default());
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
app.cooker.rx = Some(rx);
|
||||
app.cooker.epoch = app.session.cook_epoch.wrapping_sub(1);
|
||||
tx.send(Err("stale failure".into())).unwrap();
|
||||
let count = app.session.cooked.nodes.len();
|
||||
crate::cook::drive(&mut app, &egui::Context::default());
|
||||
assert_eq!(app.session.cooked.nodes.len(), count);
|
||||
assert!(app.session.cook_failures().0.is_empty());
|
||||
assert!(app.toasts.is_empty());
|
||||
}
|
||||
@@ -5,7 +5,7 @@ use std::sync::{
|
||||
mpsc,
|
||||
};
|
||||
|
||||
fn waiting() -> (MaterialCraftApp, mpsc::Sender<Cooked>, Arc<AtomicBool>) {
|
||||
fn waiting() -> (MaterialCraftApp, mpsc::Sender<Result<Cooked, String>>, Arc<AtomicBool>) {
|
||||
let mut app = MaterialCraftApp::headless(materialcraft_engine::new_session(), crate::UiState::default());
|
||||
app.session.cook();
|
||||
app.session.cooked.ms = 123.0;
|
||||
@@ -26,7 +26,7 @@ fn rapid_edits_wait_for_the_cancelled_worker() {
|
||||
assert!(flag.load(Ordering::Relaxed));
|
||||
assert!(Arc::ptr_eq(app.cooker.cancel.as_ref().unwrap(), &flag));
|
||||
}
|
||||
tx.send(Cooked { cancelled: true, ..Default::default() }).unwrap();
|
||||
tx.send(Ok(Cooked { cancelled: true, ..Default::default() })).unwrap();
|
||||
drive(&mut app, &egui::Context::default());
|
||||
assert!(!app.session.dirty, "latest snapshot should start once the worker ends");
|
||||
assert_eq!(app.session.cooked.ms, 123.0, "partial results replaced the display");
|
||||
@@ -35,7 +35,7 @@ fn rapid_edits_wait_for_the_cancelled_worker() {
|
||||
#[test]
|
||||
fn ready_results_are_discarded_when_an_edit_is_pending() {
|
||||
let (mut app, tx, _) = waiting();
|
||||
tx.send(Cooked { ms: 7.0, ..Default::default() }).unwrap();
|
||||
tx.send(Ok(Cooked { ms: 7.0, ..Default::default() })).unwrap();
|
||||
app.session.dirty = true;
|
||||
drive(&mut app, &egui::Context::default());
|
||||
assert_eq!(app.session.cooked.ms, 123.0);
|
||||
|
||||
@@ -16,6 +16,9 @@ pub mod function_editor;
|
||||
pub mod graph_view;
|
||||
pub mod i18n;
|
||||
pub mod levels_editor;
|
||||
#[cfg(test)]
|
||||
#[path = "lib.test.rs"]
|
||||
mod lib_test;
|
||||
pub mod library;
|
||||
pub mod menus;
|
||||
pub mod properties;
|
||||
@@ -134,7 +137,7 @@ impl MaterialCraftApp {
|
||||
|
||||
/// Run an engine command, reporting errors as toasts. Returns the result on success.
|
||||
pub fn run(&mut self, id: &str, params: Value) -> Option<Value> {
|
||||
match materialcraft_engine::execute(&mut self.session, id, ¶ms) {
|
||||
match cook::execute_guarded(&mut self.session, id, ¶ms) {
|
||||
Ok(v) => {
|
||||
if id == "view.previewSize" {
|
||||
self.ui.prefs.preview_size = self.session.preview_size.unwrap_or(0);
|
||||
@@ -142,7 +145,7 @@ impl MaterialCraftApp {
|
||||
Some(v)
|
||||
}
|
||||
Err(e) => {
|
||||
self.toast(e.to_string(), true);
|
||||
self.toast(e, true);
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
#[cfg(test)]
|
||||
mod lib_tests {
|
||||
use crate::MaterialCraftApp;
|
||||
use crate::cook::execute_guarded;
|
||||
use crate::state::UiState;
|
||||
use materialcraft_engine::sample_session;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn run_reports_errors_as_toasts_and_keeps_the_session() {
|
||||
let mut app = MaterialCraftApp::headless(sample_session(), UiState::default());
|
||||
assert!(app.run("no.such.command", json!({})).is_none());
|
||||
assert!(app.toasts.iter().any(|t| t.error));
|
||||
assert!(app.run("graph.node.add", json!({"def": "levels"})).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn guarded_execute_returns_command_errors_as_strings() {
|
||||
let mut s = sample_session();
|
||||
let e = execute_guarded(&mut s, "no.such.command", &json!({})).unwrap_err();
|
||||
assert!(!e.is_empty());
|
||||
assert!(execute_guarded(&mut s, "graph.node.add", &json!({"def": "levels"})).is_ok());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user