diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index 2926196fe0..2a6da1960c 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -628,8 +628,13 @@ fn end_held(s: &mut Session, c: &str, p: &Value, handed: &mut Option) s.plugin_calling = Some(held); return Some(Err(EngineError::PluginBusy)); }; - let Calling { run, calls, tx, .. } = held; - let r = if calls.kept(s) { run.finish(s, &h.output) } else { Err(EngineError::Cancelled) }; + let Calling { cmd, run, calls, tx, .. } = held; + // A panic applying the output still ends the run, so what its calls did is undone. + let r = if calls.kept(s) { + crate::guard::catch_panic(|| run.finish(s, &h.output)).unwrap_or_else(|msg| Err(EngineError::Internal { cmd, msg })) + } else { + Err(EngineError::Cancelled) + }; Some(tx.end(s, r)) } @@ -1264,6 +1269,9 @@ impl Session { /// canceled): every document and the session state go back to how they were before it. pub fn end_plugin_calls(&mut self) { if let Some(c) = self.plugin_calling.take() { + // An output handed in for it is dropped with it: a later run with the same input and + // params is not given it. + self.plugin_output = None; let _ = c.tx.end(self, Err(EngineError::Cancelled)); } } diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index 200ecb0914..2a7b546dc2 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -7782,6 +7782,28 @@ fn a_calling_run_made_away_from_the_session_that_ends_changes_nothing() { run(&mut s, "plugin.remove", json!({"id": id})); } +/// An output handed in for a run that holds the documents is dropped when that run ends: a later +/// run with the same input and params is not given it, and `plugin.run` without its own output is +/// refused. +#[test] +fn an_ended_calling_run_drops_the_output_handed_in_for_it() { + use cmd::plugin::FilterRun; + let id = "test.engine.callsawaystale"; + let mut s = session(); + install_select_all_then_remove(&mut s, id); + let (a, b) = (rect(&mut s, 10.0, "#ff0000"), rect(&mut s, 40.0, "#00ff00")); + run(&mut s, "select.set", json!({"ids": [a.0]})); + let job = FilterRun::begin_calls(&mut s, "plugin.run", &json!({"id": id})).unwrap(); + let output = run_job_away(&mut s, &job); + s.hand_in_plugin_calls(output); + s.end_plugin_calls(); + FilterRun::begin_calls(&mut s, "plugin.run", &json!({"id": id})).unwrap(); + assert!(matches!(s.execute("plugin.run", &json!({"id": id})), Err(EngineError::PluginBusy)), "the ended run's output was not kept"); + assert!(s.doc().unwrap().doc.node(a).is_some() && s.doc().unwrap().doc.node(b).is_some(), "nothing applied"); + s.end_plugin_calls(); + run(&mut s, "plugin.remove", json!({"id": id})); +} + /// A plug-in command's run made away from the session applies through the command itself: an /// output handed in for it, and the calls of one that holds the documents, are one undo step named /// after the command. diff --git a/crates/plugins/src/worker.rs b/crates/plugins/src/worker.rs index 1e7a76ba24..0816103e8d 100644 --- a/crates/plugins/src/worker.rs +++ b/crates/plugins/src/worker.rs @@ -304,7 +304,7 @@ impl Worker { } Some(ToWorker::Run { module, manifest, input, params, limits, calls }) => { self.run = None; - let plugin = match Plugin::load_checked(&module, Limits::default(), &manifest) { + let plugin = match Plugin::load_checked(&module, limits.clone(), &manifest) { Ok(p) => p, Err(e) => return self.done(Err(e), Report::default()), }; @@ -517,6 +517,19 @@ mod tests { assert_eq!(page.run_calling(INPUT.as_bytes(), b"{}", page.limits(), &mut bridge).0.unwrap(), br#"{"n":1}"#); } + /// A run in the worker keeps to the memory limit the page sends with it, as a run on the page + /// with those limits does. + #[test] + fn a_run_keeps_to_the_memory_limit_it_is_sent() { + let (mut w, got) = worker(); + let module = wat::parse_str(tpl::module(&tpl::manifest("test.worker.memory", "filter", "{}"), tpl::ECHO, "", 2)).unwrap(); + let manifest = checked(&mut w, &got, &module); + let limits = Limits { max_memory_bytes: 1 << 16, ..Limits::default() }; + let msg = ToWorker::Run { module, manifest, input: INPUT.into(), params: b"{}".to_vec(), limits, calls: false }; + w.handle(&msg.encode()); + assert!(matches!(take(&got).as_slice(), [FromWorker::Done(Err(_), _)]), "two pages don't fit in one"); + } + #[test] fn a_refused_call_fails_the_run_with_the_reason() { let (mut w, got) = worker(); diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index 30069d71e2..720b389df1 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -40,11 +40,7 @@ impl VectorcraftApp { let mut arrived: Vec<_> = take(self.services.inbox.as_ref()).into_iter().map(|f| (f, false)).collect(); arrived.extend(take(self.services.page_inbox.as_ref()).into_iter().map(|f| (f, true))); for ((name, bytes), automated) in arrived { - crate::file_asks::as_automated(self, automated, |app| { - if let Err(e) = io::open_bytes(app, &name, &bytes, None) { - io::report_open_error(app, &name, &e); - } - }); + crate::file_asks::as_automated(self, automated, |app| io::open_bytes_reporting(app, &name, &bytes)); } place::drain(self); } diff --git a/crates/ui-egui/src/dialogs/plugin.rs b/crates/ui-egui/src/dialogs/plugin.rs index 7694a59054..a21ef77253 100644 --- a/crates/ui-egui/src/dialogs/plugin.rs +++ b/crates/ui-egui/src/dialogs/plugin.rs @@ -710,8 +710,9 @@ fn confirm_filter(app: &mut VectorcraftApp, kind: Opened, values: Map { + // On the web, with no Preview, the filter or its command always runs in a worker; a command + // automation confirmed runs on the page and returns its result, as `routes` runs it. + Some(found) if crate::plugin_runs::in_workers(app) && !(own.is_some() && app.automation_asked()) => { preview.cancel(app); match own { None => run(app, &found, p), diff --git a/crates/ui-egui/src/io.rs b/crates/ui-egui/src/io.rs index 48a8e39f03..8d311212aa 100644 --- a/crates/ui-egui/src/io.rs +++ b/crates/ui-egui/src/io.rs @@ -31,7 +31,7 @@ pub use open::{ MAX_RECENT_FILES, OpensAs, ask_revert, install_module, install_plugin, new_from_template, note_recent, open_bytes, open_dialog, open_document, open_path, open_path_with, open_reporting, open_with, opens_as, place_bytes, recent_files, report_open_error, }; -pub(crate) use open::{install_module_as, report_installed}; +pub(crate) use open::{install_module_as, open_bytes_reporting, report_installed}; #[cfg(test)] pub(crate) use open::{open_file, opened_with_notes}; #[cfg(test)] diff --git a/crates/ui-egui/src/io/open.rs b/crates/ui-egui/src/io/open.rs index b28de38bcf..f46365b06b 100644 --- a/crates/ui-egui/src/io/open.rs +++ b/crates/ui-egui/src/io/open.rs @@ -236,9 +236,7 @@ fn ask_open( Ok(file_asks::ask(app, request, owner, move |app, picked| match picked { Picked::Contents(files) => { for (name, bytes) in &files { - if let Err(e) = open_bytes(app, name, bytes, None) { - report_open_error(app, name, &e); - } + open_bytes_reporting(app, name, bytes); } Ok(Value::Null) } @@ -512,6 +510,17 @@ pub fn report_open_error(app: &mut VectorcraftApp, name: &str, e: &str) { dialogs::confirm::tell(app, &message, &crate::i18n::message(crate::i18n::current(), e)); } +/// [`open_bytes`] for a file the user asked to open, a failure reported ([`report_open_error`]), +/// also one that a worker's check of a plug-in module finds after it returned +/// ([`crate::plugin_runs::report_checks_as_opened`]). +pub fn open_bytes_reporting(app: &mut VectorcraftApp, name: &str, bytes: &[u8]) { + let from = crate::plugin_runs::checks_started(app); + match open_bytes(app, name, bytes, None) { + Ok(_) => crate::plugin_runs::report_checks_as_opened(app, from, name), + Err(e) => report_open_error(app, name, &e), + } +} + /// [`open_path`] for a file the user asked for, a failure reported ([`report_open_error`]). On /// the desktop a document is decoded off the UI thread ([`crate::opening`]): the result is then /// `{background: true, status}`, and the document opens in its tab (or the failure is reported) diff --git a/crates/ui-egui/src/plugin_runs.rs b/crates/ui-egui/src/plugin_runs.rs index 475a587871..067302ddcb 100644 --- a/crates/ui-egui/src/plugin_runs.rs +++ b/crates/ui-egui/src/plugin_runs.rs @@ -87,6 +87,12 @@ impl Inbox { pub fn failed(&self) -> bool { self.error.is_some() } + + /// The messages the page hasn't read yet. + #[cfg(test)] + pub(crate) fn queued(&self) -> &VecDeque { + &self.messages + } } /// A worker's inbox, which its message and error handlers fill. @@ -137,17 +143,22 @@ impl InWorker { Ok(InWorker { link, inbox, request: Some(request), deadline, held: None }) } - /// Its next message, posting its request once it is ready → the message, or why it can't go on. - /// A message waiting in its inbox is read even past the deadline. + /// Its next message, posting its request once it is ready, before the deadline → the message, or + /// why it can't go on. A message waiting in its inbox is read even past the deadline. fn next(&mut self, now: f64) -> Result, String> { let mut inbox = self.inbox.borrow_mut(); if let Some(e) = inbox.error.take() { return Err(e); } - if now >= self.deadline && inbox.messages.is_empty() { + let late = now >= self.deadline; + if late && inbox.messages.is_empty() { return Err(vectorcraft_plugins::Error::Limit("time budget".into()).to_string()); } match inbox.messages.pop_front() { + // Past the deadline the request is not posted: the run would end before it answers. + Some(FromWorker::Ready { protocol }) if protocol == PROTOCOL && late => { + Err(vectorcraft_plugins::Error::Limit("time budget".into()).to_string()) + } Some(FromWorker::Ready { protocol }) if protocol == PROTOCOL => { drop(inbox); let request = self.request.take().ok_or_else(unexpected)?; @@ -160,12 +171,12 @@ impl InWorker { } /// While a dialog is open, its answer waits in its inbox: this posts its request once it is - /// ready → why it must end now (it failed, or its deadline passed with no final answer waiting), - /// if it must. A command call waiting is not answered then, so it doesn't keep the run past its - /// deadline. + /// ready, before the deadline → why it must end now (it failed, or its deadline passed with no + /// final answer waiting), if it must. A command call waiting is not answered then, so it doesn't + /// keep the run past its deadline. fn watch(&mut self, now: f64) -> Option { while matches!(self.inbox.borrow().messages.front(), Some(FromWorker::Ready { .. })) { - if let Err(e) = self.next(f64::NEG_INFINITY) { + if let Err(e) = self.next(now) { return Some(e); } } @@ -232,6 +243,9 @@ struct Check { module: Value, hash: String, automated: bool, + /// The name of the file the user opened that holds the module: a failure is reported as File › + /// Open reports one ([`crate::io::report_open_error`]). + opened: Option, } /// The heavy filters running, and the installs being checked. @@ -411,10 +425,23 @@ pub fn check_install(app: &mut VectorcraftApp, module: &Value, automated: bool) Ok(w) => w, Err(e) => return Some(Err(e)), }; - app.plugin_runs.checks.push(Check { worker, module: module.clone(), hash, automated }); + app.plugin_runs.checks.push(Check { worker, module: module.clone(), hash, automated, opened: None }); Some(Ok(json!({ "pending": true }))) } +/// How many install checks run now, for [`report_checks_as_opened`]. +pub fn checks_started(app: &VectorcraftApp) -> usize { + app.plugin_runs.checks.len() +} + +/// Reports a failure of each install check started since there were `from` as File › Open reports +/// one for file `name` ([`crate::io::report_open_error`]), not only in the status bar. +pub fn report_checks_as_opened(app: &mut VectorcraftApp, from: usize, name: &str) { + for c in app.plugin_runs.checks.iter_mut().skip(from) { + c.opened = Some(name.to_string()); + } +} + /// The page's clock, when workers run plug-ins. fn now(app: &VectorcraftApp) -> f64 { app.services.plugin_workers.as_ref().map_or(0.0, |w| w.now_ms()) @@ -481,7 +508,19 @@ fn watch_worker(app: &mut VectorcraftApp, i: usize) -> Option { if worker.held.is_some() { return None; } - worker.watch(t).map(|e| Ended::Worker(Some(Err(e)))) + if let Some(e) = worker.watch(t) { + return Some(Ended::Worker(Some(Err(e)))); + } + // A run that failed ends at once, so one that holds the documents frees them; only an output + // waits for the dialog to close. + let mut inbox = worker.inbox.borrow_mut(); + if matches!(inbox.messages.front(), Some(FromWorker::Done(Err(_), _))) + && let Some(FromWorker::Done(Err(e), lines)) = inbox.messages.pop_front() + { + vectorcraft_plugins::worker::log_lines(&r.plugin, &lines); + return Some(Ended::Worker(Some(Err(e.to_string())))); + } + None } /// Reads the inbox of worker run `i` → how it ended, if it has. @@ -617,14 +656,16 @@ fn poll_checks(app: &mut VectorcraftApp) { continue; }; let c = app.plugin_runs.checks.remove(i); - let Check { worker, module, hash, automated } = c; + let Check { worker, module, hash, automated, opened } = c; drop(worker); let r = checked.and_then(|manifest| { app.session.hand_in_checked_plugin(&hash, manifest); crate::io::install_module_as(app, module, automated) }); - if let Err(e) = r { - app.status(e); + match (r, opened) { + (Err(e), Some(name)) => crate::io::report_open_error(app, &name, &e), + (Err(e), None) => app.status(e), + (Ok(_), _) => {} } } } diff --git a/crates/ui-egui/src/tests/plugin_runs.rs b/crates/ui-egui/src/tests/plugin_runs.rs index bb8d669b30..843a5a9973 100644 --- a/crates/ui-egui/src/tests/plugin_runs.rs +++ b/crates/ui-egui/src/tests/plugin_runs.rs @@ -700,6 +700,27 @@ fn on_the_web_a_command_dialog_runs_its_command_in_a_worker() { assert_eq!(app.session.doc().unwrap().history.undo.last().unwrap().label, "Same", "as an undo step of its own"); } +/// On the web a plug-in command's dialog that automation confirms runs the command on the page, as +/// a command automation runs directly does: no worker starts, and the command has applied. +#[test] +fn on_the_web_a_command_dialog_automation_confirms_runs_on_the_page() { + let (mut app, _fake) = web_app(); + let id = "test.ui.web.commandautomation"; + let manifest = format!( + r#"{{"id":"{id}","name":"Test {id}","kind":"filter","api":2,"permissions":["doc.read","doc.write"],"commands":[{{"id":"same","label":"Same","params":{{"size":{{"type":"number","min":1,"max":9,"default":3}}}}}}]}}"# + ); + let data = vectorcraft_format::base64_encode(&wat::parse_str(tpl::returning(&manifest, TRIANGLE)).unwrap()); + app.run("plugin.install", json!({"dataBase64": data, "grant": ["doc.read", "doc.write"]})).unwrap(); + assert!(dialogs::plugin::open_command(&mut app, &format!("plugin.{id}.same"))); + pump(&mut app); + app.ui.answering_control = true; + answer_open(&mut app, true); + app.ui.answering_control = false; + assert!(none_open(&app)); + assert!(app.plugin_runs.running.is_empty(), "no worker run"); + assert_eq!(app.session.doc().unwrap().history.undo.last().unwrap().label, "Same", "it applied at once"); +} + /// While a dialog is open a worker still gets its run, and Cancel and the time budget still end it; /// only an output waits for the dialog to close. #[test] @@ -880,6 +901,24 @@ fn on_the_web_a_module_is_checked_in_a_worker_before_it_installs() { registry::remove(id); } +/// A plug-in file opened on the web whose check in a worker fails is reported as File › Open +/// reports a file it can't open: in a dialog, as well as in the status bar. +#[test] +fn on_the_web_an_opened_module_that_fails_its_check_is_reported_in_a_dialog() { + let (mut app, fake) = web_app(); + let bad_id = "test.ui.web.badopen"; + let traps = wat::parse_str(tpl::module(&tpl::manifest(bad_id, "filter", "{}"), tpl::ECHO, "(start $s) (func $s unreachable)", 1)).unwrap(); + crate::io::open_bytes_reporting(&mut app, "bad.wasm", &traps); + assert!(none_open(&app), "nothing to report before the check ends"); + fake.ready(0); + plugin_runs::poll(&mut app); + fake.serve(0); + plugin_runs::poll(&mut app); + assert!(registry::get(bad_id).is_none()); + assert!(app.ui.status.contains("trapped"), "{}", app.ui.status); + assert!(!none_open(&app), "the failure is shown in a dialog"); +} + /// Two checked installs that both ask for approval ask one at a time: the second waits while the /// first one's question is open. #[test] @@ -975,8 +1014,13 @@ fn on_the_web_a_call_waiting_under_a_dialog_ends_at_the_time_budget() { open_dialog(&app); fake.ready(0); plugin_runs::poll(&mut app); + assert_eq!(fake.worker(0).sent.borrow().len(), 1, "the run is posted under the dialog"); // The worker runs it to its command call, which waits for the dialog. fake.serve(0); + plugin_runs::poll(&mut app); + let call_waits = matches!(fake.worker(0).inbox.borrow().queued().front(), Some(vectorcraft_plugins::worker::FromWorker::Call { .. })); + assert!(call_waits, "the command call waits in the inbox"); + assert_eq!(app.plugin_runs.running.len(), 1, "within its time budget"); fake.clock.set(vectorcraft_plugins::Limits::default().wall_time_ms as f64 + plugin_runs::GRACE_MS); plugin_runs::poll(&mut app); assert!(app.plugin_runs.running.is_empty() && fake.worker(0).terminated.get()); @@ -984,6 +1028,54 @@ fn on_the_web_a_call_waiting_under_a_dialog_ends_at_the_time_budget() { assert_eq!(app.session.doc().unwrap().doc, doc); } +/// A worker that is ready only after the run's deadline is not sent the run, with or without a +/// dialog open: the run ends at its time budget. +#[test] +fn on_the_web_a_worker_ready_after_the_deadline_is_not_sent_the_run() { + let (mut app, fake) = web_app(); + let id = "test.ui.web.readylate"; + install_light(&mut app, id, false, "{}", ""); + let late = vectorcraft_plugins::Limits::default().wall_time_ms as f64 + plugin_runs::GRACE_MS; + for (k, dialog) in [(0, false), (1, true)] { + fake.clock.set(0.0); + app.run("plugin.dialog", json!({"id": id})).unwrap(); + if dialog { + open_dialog(&app); + } + fake.clock.set(late); + fake.ready(k); + plugin_runs::poll(&mut app); + assert!(fake.worker(k).sent.borrow().is_empty(), "dialog {dialog}: nothing is posted past the deadline"); + assert!(app.plugin_runs.running.is_empty() && fake.worker(k).terminated.get(), "dialog {dialog}"); + assert!(app.ui.status.contains("time budget"), "{}", app.ui.status); + } +} + +/// A run that holds the documents and fails while a dialog is open ends at once: its calls are +/// undone and the documents are free, without waiting for the dialog or the deadline. +#[test] +fn on_the_web_a_holding_run_that_fails_under_a_dialog_frees_the_documents() { + let (mut app, fake) = web_app(); + let id = "test.ui.web.failsunderdialog"; + let grant = json!(["doc.read", "doc.write", "commands"]); + let manifest = format!(r#"{{"id":"{id}","name":"Test {id}","kind":"filter","api":2,"permissions":{grant},"commandAllowlist":["select.all"]}}"#); + let imports = r#"(import "env" "vc_call" (func $vc_call (param i32 i32 i32 i32) (result i32)))"#; + let wasm = wat::parse_str(tpl::with_imports(&manifest, imports, "unreachable", TRIANGLE)).unwrap(); + app.run("plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&wasm), "grant": grant})).unwrap(); + let doc = app.session.doc().unwrap().doc.clone(); + app.run("plugin.dialog", json!({"id": id})).unwrap(); + assert!(app.session.plugin_calls_open()); + open_dialog(&app); + fake.ready(0); + plugin_runs::poll(&mut app); + fake.serve(0); + plugin_runs::poll(&mut app); + assert!(app.plugin_runs.running.is_empty() && fake.worker(0).terminated.get(), "{}", app.ui.status); + assert!(!app.session.plugin_calls_open(), "the documents are free again"); + assert_eq!(app.session.doc().unwrap().doc, doc); + assert!(app.ui.status.contains("failed"), "{}", app.ui.status); +} + /// A run whose document changes is stopped at once, also while a dialog is open. #[test] fn on_the_web_an_edit_ends_the_worker_while_a_dialog_is_open() { @@ -1069,8 +1161,10 @@ fn on_the_web_a_worker_run_starts_after_the_tool_edit_in_progress() { app.session.pointer(&PointerEvent::new(kind, 15.0, 10.0), v).unwrap(); } assert!(app.session.tool_editing(), "the merge is being computed"); + let unmerged = app.session.doc().unwrap().doc.clone(); assert_eq!(app.run(&format!("plugin.{id}.same"), json!({})).unwrap()["background"], true); - assert!(!app.session.tool_editing(), "the merge applied before the run was given the document"); + assert!(!app.session.tool_editing(), "the merge is no longer in progress"); + assert_ne!(app.session.doc().unwrap().doc, unmerged, "the merge applied before the run was given the document"); fake.ready(0); plugin_runs::poll(&mut app); fake.serve(0); diff --git a/packaging/web/README.md b/packaging/web/README.md index 6d4e216902..81acf0918d 100644 --- a/packaging/web/README.md +++ b/packaging/web/README.md @@ -33,7 +33,7 @@ files need revalidation. `vectorcraft-web-` `.wasm` and `.js` files, and `no-cache` on `index.html` and the `vectorcraft-plugin-worker` files. The page refuses a cached worker whose messages differ from its own, and plug-ins then fail to install and run until the browser fetches the new worker. -- **Content Security Policy:** a site that sends one must allow three things +- **Content Security Policy:** a site that sends one must allow four things ([CSP Level 3](https://www.w3.org/TR/CSP3/)): - The inline `