mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-25 20:01:07 +01:00
Merge pull request #9069 from dotCooCoo/feat/plugins-load-on-workers
Plug-ins: stored and folder plug-ins load on worker threads while the window shows
This commit is contained in:
54 files changed
+3428
-311
No files matched your search
@@ -104,6 +104,9 @@ impl eframe::App for App {
|
||||
// screen first (`quit_windows`).
|
||||
#[cfg(not(any(target_os = "macos", windows)))]
|
||||
super::quit_windows::before_teardown(self.winit_window.as_deref());
|
||||
// Plug-ins still loading end before the launch marker does (the macOS exit below skips
|
||||
// dropping the app).
|
||||
self.app.session.cancel_plugin_loads();
|
||||
end_before_teardown(self.frames);
|
||||
}
|
||||
}
|
||||
@@ -164,8 +167,9 @@ impl App {
|
||||
// dialog is open: what asked for it runs again on its document when it answers. They also
|
||||
// wait for the choice about a stopped plug-in, so they open after the plug-ins it loads, as
|
||||
// do the command line's files held back for it. Files later launches handed over before the
|
||||
// choice ended in Safe Mode open in a new app with plug-ins.
|
||||
if !self.app.file_dialog_open() && !safe_mode::choosing(&self.app) {
|
||||
// choice ended in Safe Mode open in a new app with plug-ins. They wait while plug-ins load
|
||||
// as well, since a plug-in may be what reads them.
|
||||
if !self.app.file_dialog_open() && !safe_mode::choosing(&self.app) && !self.app.session.plugins_loading() {
|
||||
let held = std::mem::take(&mut self.held_files);
|
||||
#[cfg(target_os = "macos")]
|
||||
let files = open_documents::take();
|
||||
@@ -215,9 +219,10 @@ pub(crate) fn bring_window_forward(ctx: &egui::Context) {
|
||||
}
|
||||
|
||||
/// Open the command line's `files` now, or, while the choice about a stopped plug-in is up
|
||||
/// ([`safe_mode::choosing`]), return them to open once it is made, with the plug-ins it loads.
|
||||
/// ([`safe_mode::choosing`]) or plug-ins are still loading (a plug-in may be what reads one),
|
||||
/// return them to open once it is made and they have loaded.
|
||||
pub(crate) fn open_or_hold(app: &mut VectorcraftApp, files: Vec<String>) -> Vec<String> {
|
||||
if safe_mode::choosing(app) {
|
||||
if safe_mode::choosing(app) || app.session.plugins_loading() {
|
||||
return files;
|
||||
}
|
||||
open_files(app, files);
|
||||
|
||||
@@ -811,6 +811,9 @@ fn main() -> std::process::ExitCode {
|
||||
let launch_dir = prefs_dir::prefs_dir().filter(|_| prefs_enabled()).map(|d| d.join("Launch"));
|
||||
let folder = |name: &str| prefs_dir::prefs_dir().map(|d| d.join(name).to_string_lossy().to_string());
|
||||
let stopped = safe_mode::begin_launch(launch_dir.as_deref(), safe_mode_flag);
|
||||
// The launch's loads of the stored plug-ins and the plug-ins folder go on on worker
|
||||
// threads while the window shows; the frames install them as they finish.
|
||||
session.load_plugins_in_background(true);
|
||||
prefs_dir::attach_plugin_store(&mut session);
|
||||
// File › Scripts lists the scripts of the Scripts folder next to the preferences.
|
||||
prefs_dir::attach_scripts_dir(&mut session);
|
||||
@@ -826,6 +829,9 @@ fn main() -> std::process::ExitCode {
|
||||
app.set_startup_update_check(!nightly);
|
||||
load_prefs(&mut app, &settings);
|
||||
safe_mode::after_start(&mut app, stopped);
|
||||
// Loads started later (a preference change, the end of Safe Mode) are waited for,
|
||||
// after the launch's own.
|
||||
app.session.load_plugins_in_background(false);
|
||||
// The saved PDF presets live in their own folder (also read by vectorcraft-cli),
|
||||
// which takes over from the copy the preferences file used to hold.
|
||||
prefs_dir::attach_pdf_preset_store(&mut app.session);
|
||||
|
||||
@@ -50,7 +50,8 @@ fn command_line_files_wait_for_the_choice_about_a_stopped_plug_in() {
|
||||
..Default::default()
|
||||
};
|
||||
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), services);
|
||||
app.ui.stopped_plugin = Some(serde_json::json!({"id": "test.held", "name": "Held"}));
|
||||
let held = serde_json::json!({"id": "test.held", "name": "Held"});
|
||||
app.ui.stopped_plugin = Some(serde_json::json!({"item": held, "items": [held]}));
|
||||
assert_eq!(open_or_hold(&mut app, files.clone()), files, "held while the choice is up");
|
||||
assert!(read.borrow().is_empty(), "nothing opened before the choice");
|
||||
app.ui.stopped_plugin = None;
|
||||
|
||||
+292
-50
@@ -52,7 +52,7 @@ use vectorcraft_doc::{Document, Effect, Node};
|
||||
use vectorcraft_plugins::{Budget, Command, Kind, Plugin, effect, export, objects, registry, safe_mode};
|
||||
|
||||
use super::{CommandSpec, EngineError, NodeId, Result, Session, always, bad, cmd, has_doc, ids_param, str_param, switch_or};
|
||||
use crate::store::StoreTurn;
|
||||
use crate::store::{PluginLoad, StoreTurn};
|
||||
|
||||
use vectorcraft_plugins::permissions::{self, Grant, GrantToken, Permission};
|
||||
|
||||
@@ -1010,12 +1010,16 @@ thread_local! {
|
||||
pub(crate) static BEFORE_GRANT_STORED: std::cell::RefCell<Option<Box<dyn FnOnce()>>> = const { std::cell::RefCell::new(None) };
|
||||
/// Tests: runs once on this thread when [`hold_plugin_changes`] finds the lock held and waits.
|
||||
pub(crate) static WHILE_WAITING: std::cell::RefCell<Option<Box<dyn FnOnce()>>> = const { std::cell::RefCell::new(None) };
|
||||
/// Tests: runs once in the next `plugin.reload` on this thread after its load started and before
|
||||
/// it installs, as another session loading a folder in between would.
|
||||
pub(crate) static BEFORE_RELOAD_INSTALLS: std::cell::RefCell<Option<Box<dyn FnOnce()>>> = const { std::cell::RefCell::new(None) };
|
||||
}
|
||||
|
||||
/// Held by `plugin.install` from its first read of the grant until the store holds what it
|
||||
/// installed, and throughout by `plugin.remove`, by loads of the stored plug-ins
|
||||
/// ([`Session::load_stored_plugins`]) and by loads of a plug-ins folder: these run one after the
|
||||
/// other across sessions.
|
||||
/// installed, throughout by `plugin.remove`, and while the loads of the stored plug-ins
|
||||
/// ([`Session::load_stored_plugins`]) and of a plug-ins folder install what they loaded: these run
|
||||
/// one after the other across sessions. It is not held while the modules load, so a session's
|
||||
/// plug-in commands don't wait for another session's loads.
|
||||
static PLUGIN_CHANGES: Mutex<()> = Mutex::new(());
|
||||
|
||||
/// Takes [`PLUGIN_CHANGES`], waiting while another session holds it.
|
||||
@@ -1033,6 +1037,21 @@ pub(crate) fn hold_plugin_changes() -> std::sync::MutexGuard<'static, ()> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Takes [`PLUGIN_CHANGES`] when no other session holds it, without waiting.
|
||||
pub(crate) fn try_hold_plugin_changes() -> Option<std::sync::MutexGuard<'static, ()>> {
|
||||
match PLUGIN_CHANGES.try_lock() {
|
||||
Ok(held) => Some(held),
|
||||
Err(std::sync::TryLockError::Poisoned(e)) => Some(e.into_inner()),
|
||||
Err(std::sync::TryLockError::WouldBlock) => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Tests: whether [`PLUGIN_CHANGES`] could be taken now.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn plugin_changes_free() -> bool {
|
||||
!matches!(PLUGIN_CHANGES.try_lock(), Err(std::sync::TryLockError::WouldBlock))
|
||||
}
|
||||
|
||||
/// `plugin.install`: loads and checks the module, refuses `grant` and `allowHeavy` that neither an
|
||||
/// [`InstallApproval`] for this module nor the session allows, one that asks for a heavy budget
|
||||
/// unless `allowHeavy` says a person agreed, one that lists permissions no person has granted this
|
||||
@@ -1282,31 +1301,61 @@ fn load_path(_: &str) -> Result<(Plugin, Vec<u8>)> {
|
||||
Err(EngineError::Other("installing from a path is not available on the web; pass the module as `dataBase64`".into()))
|
||||
}
|
||||
|
||||
/// The plug-in folder last loaded, the plug-in store whose grants it was loaded with, and what
|
||||
/// happened.
|
||||
static FOLDER: Mutex<Option<(String, Option<std::path::PathBuf>, Value)>> = Mutex::new(None);
|
||||
/// The plug-in folder last loaded, the plug-in store whose grants it was loaded with, what
|
||||
/// happened, the load whose report it is ([`FOLDER_LOADS`]), and whether a file failed because no
|
||||
/// loader thread was left to load it ([`vectorcraft_plugins::loader::NO_THREAD`]), so that the next
|
||||
/// [`sync_prefs`] loads the folder again.
|
||||
type FolderRecord = (String, Option<std::path::PathBuf>, Value, u64, bool);
|
||||
|
||||
/// The [`FolderRecord`] of the plug-in folder last loaded.
|
||||
static FOLDER: Mutex<Option<FolderRecord>> = Mutex::new(None);
|
||||
|
||||
/// The number of the last folder load [`sync_prefs`] or `plugin.reload` started. [`sync_prefs`]
|
||||
/// keeps it in [`FOLDER`] while its load runs, so only that load replaces or clears the record, and
|
||||
/// a `plugin.reload` keeps its report only when no load started after it.
|
||||
static FOLDER_LOADS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||
|
||||
/// Loads the Additional Plug-ins Folder preference (`*.wasm`) when it is set and it, or the
|
||||
/// session's plug-in store, has changed since the last load. Runs whenever preferences are applied
|
||||
/// (startup, `prefs.set`). Native only.
|
||||
pub(crate) fn sync_prefs(s: &Session) {
|
||||
let folder = s.prefs.plugins_folder.trim();
|
||||
/// (startup, `prefs.set`). With [`Session::load_plugins_in_background`] on, it returns while the
|
||||
/// modules load, and `plugin.list` reports the folder as loading until they are installed. Off, it
|
||||
/// returns once the folder's plug-ins are installed, also while another session is still loading
|
||||
/// the same folder. Native only.
|
||||
pub(crate) fn sync_prefs(s: &mut Session) {
|
||||
let folder = s.prefs.plugins_folder.trim().to_string();
|
||||
// In Safe Mode nothing loads, and the folder is loaded once it ends ([`load_prefs_folder`]).
|
||||
if folder.is_empty() || safe_mode::active() {
|
||||
return;
|
||||
}
|
||||
let mut last = FOLDER.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if last.as_ref().is_some_and(|(f, store, _)| f == folder && *store == s.plugin_dir) {
|
||||
// This session's own load of the folder, still running, is waited for unless loads go on in the
|
||||
// background.
|
||||
if s.plugin_loads.iter().any(|l| matches!(l, PluginLoad::Folder(f) if f.loads(&folder, &s.plugin_dir))) {
|
||||
if !s.plugin_loads_in_background {
|
||||
s.finish_plugin_loads();
|
||||
}
|
||||
return;
|
||||
}
|
||||
*last = Some((folder.to_string(), s.plugin_dir.clone(), load_folder(s, folder)));
|
||||
let token = {
|
||||
let mut last = FOLDER.lock().unwrap_or_else(|e| e.into_inner());
|
||||
// A folder another session is still loading is loaded here too: that load may end with its
|
||||
// session, and this one returns once its own plug-ins are installed.
|
||||
// A load in which a file found no thread to load it is tried again.
|
||||
if last.as_ref().is_some_and(|(f, store, r, _, retry)| *f == folder && *store == s.plugin_dir && r["loading"] != true && !retry) {
|
||||
return;
|
||||
}
|
||||
let token = FOLDER_LOADS.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
|
||||
*last = Some((folder.clone(), s.plugin_dir.clone(), json!({"folder": folder, "loading": true}), token, false));
|
||||
token
|
||||
};
|
||||
let load = start_folder(s, &folder, Some(token));
|
||||
s.queue_plugin_load(PluginLoad::Folder(load));
|
||||
}
|
||||
|
||||
/// The Additional Plug-ins Folder preference was cleared from `old`: when `old` is the folder last
|
||||
/// loaded, it is forgotten, so setting the preference to it again loads it again.
|
||||
pub(crate) fn forget_prefs_folder(old: &str) {
|
||||
let mut last = FOLDER.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if last.as_ref().is_some_and(|(f, _, _)| f == old.trim()) {
|
||||
if last.as_ref().is_some_and(|(f, _, _, _, _)| f == old.trim()) {
|
||||
*last = None;
|
||||
}
|
||||
}
|
||||
@@ -1326,42 +1375,232 @@ pub fn load_prefs_folder(s: &mut Session) {
|
||||
sync_prefs(s);
|
||||
}
|
||||
|
||||
/// Loads the plug-ins in `folder`, those that list permissions only when `s` has them granted
|
||||
/// ([`Session::plugin_approved`], with the store's grants read once) → its report; saves the
|
||||
/// disabled list when loading changed it.
|
||||
/// The modules of a folder loading ([`registry::FolderLoad`]); the web build has none.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn load_folder(s: &Session, folder: &str) -> Value {
|
||||
if let Err(e) = crate::file_access::check_read(folder) {
|
||||
return json!({"folder": folder, "error": e});
|
||||
}
|
||||
// A file in it may be a link to one elsewhere.
|
||||
let allow = |f: &std::path::Path| match f.to_str() {
|
||||
Some(f) => crate::file_access::check_read(f),
|
||||
// A lossy name would check another file than the one loaded.
|
||||
None if crate::file_access::current().is_none() => Ok(()),
|
||||
None => Err(format!("automation path rejected: {} isn't valid text", f.display())),
|
||||
};
|
||||
// A `plugin.install` in another session or process finishes writing the store first. When the
|
||||
// store can't be locked, the folder still loads, and the store isn't written.
|
||||
let _held = hold_plugin_changes();
|
||||
let turn = s.plugin_store_turn().unwrap_or_else(|_| StoreTurn::unheld());
|
||||
match registry::load_folder_where(std::path::Path::new(folder), allow, s.plugin_folder_approver()) {
|
||||
Ok(r) => {
|
||||
for id in &r.loaded {
|
||||
s.attach_plugin_storage(&turn, id);
|
||||
}
|
||||
if r.disabled_changed {
|
||||
s.store_disabled_plugins_in(&turn);
|
||||
}
|
||||
json!({"folder": folder, "loaded": r.loaded, "failed": r.failed.iter().map(|(f, e)| json!({"file": f, "error": e})).collect::<Vec<_>>(), "leftOut": r.left_out})
|
||||
type FolderModules = registry::FolderLoad;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
type FolderModules = std::convert::Infallible;
|
||||
|
||||
/// A load of the plug-ins in a folder ([`start_folder`]), which [`install_folder`] installs as the
|
||||
/// modules load and [`end_folder`] ends.
|
||||
pub(crate) struct FolderPending {
|
||||
folder: String,
|
||||
/// The plug-in store whose grants it loads with.
|
||||
store: Option<std::path::PathBuf>,
|
||||
/// The load's number in [`FOLDER`] when [`end_folder`] keeps its report as the folder last
|
||||
/// loaded ([`sync_prefs`]).
|
||||
record: Option<u64>,
|
||||
/// A `plugin.reload`'s load: [`end_folder`] keeps its report as the folder last loaded unless a
|
||||
/// load started after it.
|
||||
reload: bool,
|
||||
/// The modules loading, or the report of a folder that can't be loaded; `None` once ended.
|
||||
load: Option<std::result::Result<FolderModules, Value>>,
|
||||
/// Whether the modules not installed yet were dropped ([`FolderPending::cancel`]).
|
||||
canceled: bool,
|
||||
}
|
||||
|
||||
impl FolderPending {
|
||||
/// Whether every module has been installed or reported.
|
||||
pub(crate) fn done(&self) -> bool {
|
||||
match &self.load {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
Some(Ok(load)) => load.done(),
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
Some(Ok(never)) => match *never {},
|
||||
Some(Err(_)) | None => true,
|
||||
}
|
||||
Err(e) => json!({"folder": folder, "error": e.to_string()}),
|
||||
}
|
||||
|
||||
/// Starts the modules loading, unless they started already.
|
||||
pub(crate) fn start(&mut self) {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if let Some(Ok(load)) = &mut self.load {
|
||||
load.start();
|
||||
}
|
||||
}
|
||||
|
||||
/// The installs and removals its modules are checked against (`None`: the folder couldn't be
|
||||
/// listed, or the load ended).
|
||||
pub(crate) fn changes(&self) -> Option<®istry::LoadChanges> {
|
||||
match &self.load {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
Some(Ok(load)) => Some(load.changes()),
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
Some(Ok(never)) => match *never {},
|
||||
Some(Err(_)) | None => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// [`FolderPending::changes`], to adopt an earlier load's.
|
||||
pub(crate) fn changes_mut(&mut self) -> Option<&mut registry::LoadChanges> {
|
||||
match &mut self.load {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
Some(Ok(load)) => Some(load.changes_mut()),
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
Some(Ok(never)) => match *never {},
|
||||
Some(Err(_)) | None => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether something can be installed or reported now, without waiting.
|
||||
pub(crate) fn ready(&mut self) -> bool {
|
||||
match &mut self.load {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
Some(Ok(load)) => load.ready(),
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
Some(Ok(never)) => match *never {},
|
||||
Some(Err(_)) | None => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Waits until the next module in file-name order has loaded or failed.
|
||||
pub(crate) fn wait(&mut self) {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if let Some(Ok(load)) = &mut self.load {
|
||||
load.wait();
|
||||
}
|
||||
}
|
||||
|
||||
/// Drops the modules not installed yet, leaving it [`FolderPending::done`]; [`end_folder`]
|
||||
/// then keeps no report as the folder last loaded.
|
||||
pub(crate) fn cancel(&mut self) {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if let Some(Ok(load)) = &mut self.load {
|
||||
load.cancel();
|
||||
}
|
||||
self.canceled = true;
|
||||
}
|
||||
|
||||
/// Whether it is a load of `folder` with the plug-in store `store`.
|
||||
pub(crate) fn loads(&self, folder: &str, store: &Option<std::path::PathBuf>) -> bool {
|
||||
self.folder == folder && self.store == *store
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for FolderPending {
|
||||
/// A load dropped before it ended (its session closed) leaves no folder reported as loading, so
|
||||
/// the next session that applies the preference loads it.
|
||||
fn drop(&mut self) {
|
||||
if let Some(token) = self.record.filter(|_| self.load.is_some()) {
|
||||
let mut last = FOLDER.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if last.as_ref().is_some_and(|(_, _, _, t, _)| *t == token) {
|
||||
*last = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Starts loading the plug-ins in `folder` on worker threads ([`registry::FolderLoad`]); `record`:
|
||||
/// the load's number in [`FOLDER`], whose record [`end_folder`] replaces with the report.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn start_folder(s: &Session, folder: &str, record: Option<u64>) -> FolderPending {
|
||||
let pending =
|
||||
|load| FolderPending { folder: folder.to_string(), store: s.plugin_dir.clone(), record, reload: false, load: Some(load), canceled: false };
|
||||
if let Err(e) = crate::file_access::check_read(folder) {
|
||||
return pending(Err(json!({"folder": folder, "error": e})));
|
||||
}
|
||||
// A file in it may be a link to one elsewhere. Each file is checked again on its worker
|
||||
// thread, in the scope in force here (the automation roots and the script gate), as the
|
||||
// folder itself was.
|
||||
let scope = crate::file_access::ScopeHandle::capture_now();
|
||||
let allow = move |f: &std::path::Path| {
|
||||
scope.clone().run(|| match f.to_str() {
|
||||
Some(f) => crate::file_access::check_read(f),
|
||||
// A lossy name would check another file than the one loaded.
|
||||
None if crate::file_access::current().is_none() => Ok(()),
|
||||
None => Err(format!("automation path rejected: {} isn't valid text", f.display())),
|
||||
})
|
||||
};
|
||||
// The modules start loading once the loads queued before them are done.
|
||||
pending(registry::FolderLoad::list(std::path::Path::new(folder), allow).map_err(|e| json!({"folder": folder, "error": e.to_string()})))
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn load_folder(_: &Session, folder: &str) -> Value {
|
||||
json!({"folder": folder, "error": "plug-in folders are not available on the web"})
|
||||
fn start_folder(s: &Session, folder: &str, record: Option<u64>) -> FolderPending {
|
||||
let load = Err(json!({"folder": folder, "error": "plug-in folders are not available on the web"}));
|
||||
FolderPending { folder: folder.to_string(), store: s.plugin_dir.clone(), record, reload: false, load: Some(load), canceled: false }
|
||||
}
|
||||
|
||||
/// Installs what `load` has loaded so far, in file-name order up to the first module still
|
||||
/// loading, without waiting: those that list permissions only when `s` has them granted
|
||||
/// ([`Session::plugin_approved`], with the store's grants read once). Runs while
|
||||
/// [`hold_plugin_changes`] and `turn` are held, so a `plugin.install` in another session or process
|
||||
/// finishes writing the store first; when the store can't be locked, the folder still installs,
|
||||
/// and the store isn't written.
|
||||
pub(crate) fn install_folder(s: &mut Session, load: &mut FolderPending, turn: &StoreTurn) {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if let Some(Ok(load)) = &mut load.load
|
||||
&& !load.done()
|
||||
{
|
||||
for id in load.install_ready(s.plugin_folder_approver()) {
|
||||
s.attach_plugin_storage(turn, &id);
|
||||
}
|
||||
// A disabled plug-in's file matched by its id is saved in the same turn.
|
||||
if load.disabled_changed() && s.store_disabled_plugins_in(turn) {
|
||||
load.disabled_saved();
|
||||
}
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let _ = (s, load, turn);
|
||||
}
|
||||
|
||||
/// Ends `load` once [`FolderPending::done`], while [`hold_plugin_changes`] and `turn` are held, so
|
||||
/// the grants of ids whose module lists no permissions are forgotten while no `plugin.install` can
|
||||
/// record one for another module → its report; saves the disabled list when loading changed it.
|
||||
pub(crate) fn end_folder(s: &mut Session, mut load: FolderPending, turn: &StoreTurn) -> Value {
|
||||
let (report, retry) = match load.load.take() {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
Some(Ok(modules)) => {
|
||||
let r = modules.finish();
|
||||
if r.disabled_changed {
|
||||
s.store_disabled_plugins_in(turn);
|
||||
}
|
||||
let failed = r.failed.iter().map(|(f, e)| json!({"file": f, "error": e})).collect::<Vec<_>>();
|
||||
(json!({"folder": load.folder, "loaded": r.loaded, "failed": failed, "leftOut": r.left_out}), r.no_thread)
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
Some(Ok(never)) => match never {},
|
||||
Some(Err(report)) => (report, false),
|
||||
None => (Value::Null, false),
|
||||
};
|
||||
if let Some(token) = load.record {
|
||||
let mut last = FOLDER.lock().unwrap_or_else(|e| e.into_inner());
|
||||
// A later load, or a `plugin.reload`, replaced it meanwhile. A canceled load leaves no
|
||||
// folder reported, so the next session that applies the preference loads it. A
|
||||
// `plugin.reload`'s report replaces the record unless a load started after it, or the
|
||||
// folder couldn't be loaded.
|
||||
let current = if load.reload {
|
||||
FOLDER_LOADS.load(std::sync::atomic::Ordering::Relaxed) == token && report.get("error").is_none()
|
||||
} else {
|
||||
last.as_ref().is_some_and(|(_, _, _, t, _)| *t == token)
|
||||
};
|
||||
if current {
|
||||
*last = if load.canceled { None } else { Some((load.folder.clone(), load.store.clone(), report.clone(), token, retry)) };
|
||||
}
|
||||
}
|
||||
report
|
||||
}
|
||||
|
||||
/// Loads the plug-ins in `folder` and installs them, waiting for every module → the report, which is
|
||||
/// kept as the folder last loaded unless a load started after this one.
|
||||
fn load_folder_now(s: &mut Session, folder: &str) -> Value {
|
||||
let token = FOLDER_LOADS.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
|
||||
let mut load = start_folder(s, folder, Some(token));
|
||||
load.reload = true;
|
||||
#[cfg(test)]
|
||||
if let Some(between) = BEFORE_RELOAD_INSTALLS.take() {
|
||||
between();
|
||||
}
|
||||
s.finish_plugin_load(PluginLoad::Folder(load))
|
||||
}
|
||||
|
||||
/// Tests: the next [`sync_prefs`] treats the folder last loaded as one in which a file found no
|
||||
/// loader thread to load it.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn folder_found_no_thread() {
|
||||
if let Some(record) = FOLDER.lock().unwrap_or_else(|e| e.into_inner()).as_mut() {
|
||||
record.4 = true;
|
||||
}
|
||||
}
|
||||
|
||||
fn reload(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -1373,11 +1612,12 @@ fn reload(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if folder.is_empty() {
|
||||
return Err(bad(C, "no folder: pass `path` or set Preferences › Plug-ins & Scratch Disks › Additional Plug-ins Folder"));
|
||||
}
|
||||
let report = load_folder(s, &folder);
|
||||
// Loads started earlier install first, so this one's plug-ins replace theirs.
|
||||
s.finish_plugin_loads();
|
||||
let report = load_folder_now(s, &folder);
|
||||
if let Some(e) = report.get("error").and_then(Value::as_str) {
|
||||
return Err(EngineError::Other(e.to_string()));
|
||||
}
|
||||
*FOLDER.lock().unwrap_or_else(|e| e.into_inner()) = Some((folder, s.plugin_dir.clone(), report.clone()));
|
||||
Ok(report)
|
||||
}
|
||||
|
||||
@@ -1426,7 +1666,7 @@ fn shown_report(mut report: Value) -> Value {
|
||||
}
|
||||
|
||||
fn list(_: &mut Session, _: &Value) -> Result<Value> {
|
||||
let folder = FOLDER.lock().unwrap_or_else(|e| e.into_inner()).as_ref().map(|(_, _, r)| shown_report(r.clone()));
|
||||
let folder = FOLDER.lock().unwrap_or_else(|e| e.into_inner()).as_ref().map(|(_, _, r, _, _)| shown_report(r.clone()));
|
||||
let disabled: Vec<Value> = safe_mode::disabled().iter().map(shown_item).collect();
|
||||
Ok(
|
||||
json!({"plugins": registry::list().iter().map(|p| describe_installed(p)).collect::<Vec<_>>(), "folder": folder, "safeMode": safe_mode::active(), "disabled": disabled}),
|
||||
@@ -1434,13 +1674,15 @@ fn list(_: &mut Session, _: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
/// `plugin.safeMode`: whether Safe Mode is on and why, the plug-ins disabled for the next launch,
|
||||
/// and the plug-in the last launch was loading when it stopped while the user hasn't chosen yet.
|
||||
/// and the plug-ins the last launch was loading when it stopped while the user hasn't chosen yet.
|
||||
fn safe_mode_state(_: &mut Session, _: &Value) -> Result<Value> {
|
||||
let pending: Vec<Value> = safe_mode::previous().iter().map(shown_item).collect();
|
||||
Ok(json!({
|
||||
"active": safe_mode::active(),
|
||||
"source": safe_mode::source().map(safe_mode::Source::name),
|
||||
"disabled": safe_mode::disabled().iter().map(shown_item).collect::<Vec<_>>(),
|
||||
"pendingItem": safe_mode::previous().map(|i| shown_item(&i)),
|
||||
"pendingItem": pending.first(),
|
||||
"pendingItems": pending,
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -1651,7 +1893,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Safe Mode",
|
||||
[],
|
||||
None,
|
||||
"{} → {active: bool (no plug-in loads or runs: plugin.install, .run, .reload and exporters fail, live effects draw their object's geometry unchanged and the objects keep their effects), source: \"flag\" (started with --safe-mode) | \"startup\" (the user chose Safe Mode, or hasn't chosen yet, after a launch that stopped while a plug-in was loading) | null, disabled: [{id, file, name, label}] (turned off for the next launch; id is null for one known only by its file; under automation read roots, a file outside them is named by its file name here and in pendingItem, and plugin.setEnabled takes that name), pendingItem: {id, file, name, label} | null (the plug-in the last launch was loading when it stopped, until the user chooses; it may not be what stopped it)}. Safe Mode is chosen at launch, never by a command",
|
||||
"{} → {active: bool (no plug-in loads or runs: plugin.install, .run, .reload and exporters fail, live effects draw their object's geometry unchanged and the objects keep their effects), source: \"flag\" (started with --safe-mode) | \"startup\" (the user chose Safe Mode, or hasn't chosen yet, after a launch that stopped while a plug-in was loading) | null, disabled: [{id, file, name, label}] (turned off for the next launch; id is null for one known only by its file; under automation read roots, a file outside them is named by its file name here and in pendingItem, and plugin.setEnabled takes that name), pendingItem: {id, file, name, label} | null (the first of pendingItems), pendingItems: [{id, file, name, label}] (the plug-ins the last launch was loading when it stopped, oldest first, until the user chooses; any of them, or none, may be what stopped it)}. Safe Mode is chosen at launch, never by a command",
|
||||
always,
|
||||
safe_mode_state
|
||||
),
|
||||
|
||||
@@ -125,6 +125,14 @@ pub fn waits_for_tool_edit(id: &str) -> bool {
|
||||
find_command(id).is_some_and(|spec| spec.journal || WAIT_FOR_TOOL_EDIT.contains(&id))
|
||||
}
|
||||
|
||||
/// Does command `id` first install the plug-ins still loading on other threads
|
||||
/// ([`crate::Session::finish_plugin_loads`])? Plug-in commands do, a plug-in's own commands
|
||||
/// included, and so does every command that waits for a tool edit ([`waits_for_tool_edit`]);
|
||||
/// queries that only read, and view commands, go ahead while the plug-ins load.
|
||||
pub fn waits_for_plugin_loads(id: &str) -> bool {
|
||||
id.starts_with(vectorcraft_plugins::PREFIX) || waits_for_tool_edit(id)
|
||||
}
|
||||
|
||||
/// Journaled commands that write a file and change nothing in the document: with an object of a
|
||||
/// dynamic symbol instance's art selected, they read the instance as queries do
|
||||
/// ([`crate::Session::execute`]).
|
||||
|
||||
@@ -227,6 +227,14 @@ fn with_gate_reads_exempt<T>(exempt: bool, f: impl FnOnce() -> T) -> T {
|
||||
f()
|
||||
}
|
||||
|
||||
/// `scope`, or for a thread without one, the `process` roots in force now (none: unconfined).
|
||||
fn resolved(scope: Option<Scope>, process: Option<&Arc<AutomationRoots>>) -> Scope {
|
||||
scope.unwrap_or_else(|| match process {
|
||||
Some(r) => Scope::Confined(r.clone()),
|
||||
None => Scope::Unconfined,
|
||||
})
|
||||
}
|
||||
|
||||
/// This thread's scope, with the gate of the script command it runs, to carry to work it hands to
|
||||
/// another thread ([`ScopeHandle::run`]).
|
||||
#[derive(Clone, Debug)]
|
||||
@@ -238,6 +246,15 @@ impl ScopeHandle {
|
||||
Self(SCOPE.with(|s| s.borrow().clone()), GATE.with(|g| g.borrow().clone()), GATE_READS_EXEMPT.with(std::cell::Cell::get))
|
||||
}
|
||||
|
||||
/// [`ScopeHandle::capture`], except that a thread with no scope of its own takes the process's
|
||||
/// roots as they are now ([`confine_process`]): work captured before the process is confined
|
||||
/// stays unconfined on the thread that runs it, as it would have been had it run on the calling
|
||||
/// thread at once.
|
||||
pub fn capture_now() -> Self {
|
||||
let scope = resolved(SCOPE.with(|s| s.borrow().clone()), PROCESS.get());
|
||||
Self(Some(scope), GATE.with(|g| g.borrow().clone()), GATE_READS_EXEMPT.with(std::cell::Cell::get))
|
||||
}
|
||||
|
||||
/// Run `f` in the captured scope.
|
||||
pub fn run<T>(self, f: impl FnOnce() -> T) -> T {
|
||||
let Self(scope, gate, exempt) = self;
|
||||
@@ -1327,6 +1344,24 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// Work captured with [`ScopeHandle::capture_now`] before the process is confined stays
|
||||
/// unconfined when it runs after; work captured with [`ScopeHandle::capture`] is confined then.
|
||||
#[test]
|
||||
fn a_scope_captured_now_stays_unconfined_after_the_process_is_confined() {
|
||||
if !crate::tests::in_own_process("file_access::tests::a_scope_captured_now_stays_unconfined_after_the_process_is_confined") {
|
||||
return;
|
||||
}
|
||||
let (base, roots) = folders("captured-process");
|
||||
let outside = s(base.join("outside/secret.svg"));
|
||||
let (now, plain) = std::thread::spawn(|| (ScopeHandle::capture_now(), ScopeHandle::capture())).join().unwrap();
|
||||
assert!(confine_process(roots));
|
||||
assert_eq!(now.run(|| check_read(&outside)), Ok(()), "captured now, before the process was confined");
|
||||
assert!(plain.run(|| check_read(&outside)).is_err(), "captured plainly, run after the process was confined");
|
||||
let later = std::thread::spawn(ScopeHandle::capture_now).join().unwrap();
|
||||
assert!(later.run(|| check_read(&outside)).is_err(), "captured now, after the process was confined");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn device_names() {
|
||||
for d in ["CON", "nul", "Com1", "LPT9.txt", "aux.svg", "NUL ", "COM¹", "Lpt²", "lpt³.txt"] {
|
||||
|
||||
@@ -203,6 +203,11 @@ pub struct Session {
|
||||
/// Where the plug-ins `plugin.install` installs are kept; `None`: only for the process
|
||||
/// ([`Session::attach_plugin_store`]).
|
||||
plugin_dir: Option<std::path::PathBuf>,
|
||||
/// Plug-in loads running on worker threads, oldest first ([`Session::poll_plugin_loads`]).
|
||||
plugin_loads: std::collections::VecDeque<store::PluginLoad>,
|
||||
/// Whether the loads of the stored plug-ins and of the plug-ins folder go on after the call
|
||||
/// that starts them ([`Session::load_plugins_in_background`]).
|
||||
plugin_loads_in_background: bool,
|
||||
/// The Scripts folder, whose scripts File › Scripts lists; `None`: no folder
|
||||
/// ([`Session::attach_scripts_dir`]).
|
||||
scripts_dir: Option<std::path::PathBuf>,
|
||||
@@ -453,7 +458,7 @@ mod session;
|
||||
pub(crate) use command_sets::SELECTS_GIVEN_IDS;
|
||||
#[cfg(test)]
|
||||
use command_sets::given_ids;
|
||||
pub use command_sets::{DRAWS_SHAPE, FIT_ACTIVE_ARTBOARD, ON_ACTIVE_ARTBOARD, waits_for_tool_edit};
|
||||
pub use command_sets::{DRAWS_SHAPE, FIT_ACTIVE_ARTBOARD, ON_ACTIVE_ARTBOARD, waits_for_plugin_loads, waits_for_tool_edit};
|
||||
pub use doc_state::{DocState, LayersReveal, OpenRows, RecalledSelection};
|
||||
pub use error::{EngineError, READ_ONLY_LOCATION, Result, SCRIPT_BUSY};
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -106,6 +106,8 @@ impl Session {
|
||||
profile_dir: None,
|
||||
color_settings_file: None,
|
||||
plugin_dir: None,
|
||||
plugin_loads: Default::default(),
|
||||
plugin_loads_in_background: false,
|
||||
scripts_dir: None,
|
||||
metadata_templates_dir: None,
|
||||
new_doc_profile_dir: None,
|
||||
|
||||
@@ -59,6 +59,13 @@ impl Session {
|
||||
|
||||
/// Execute a command by id. This is THE entry point for every frontend.
|
||||
pub fn execute(&mut self, id: &str, params: &Value) -> Result<Value> {
|
||||
// Plug-ins still loading on other threads ([`Session::load_plugins_in_background`]) are
|
||||
// installed before a plug-in command, its own commands included, and before a command that
|
||||
// may edit, as they would have been before the window showed; a step of a batch waits for
|
||||
// the plug-ins an earlier step started loading.
|
||||
if self.plugins_loading() && crate::waits_for_plugin_loads(id) {
|
||||
self.finish_plugin_loads();
|
||||
}
|
||||
self.revealing(|s| s.execute_unwatched(id, params))
|
||||
}
|
||||
|
||||
|
||||
+650
-67
@@ -35,14 +35,16 @@
|
||||
//! The files are untrusted input like any other: sizes and counts are capped, a file that does not
|
||||
//! parse is skipped with a log record, and every write is atomic.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::collections::{BTreeMap, BTreeSet, VecDeque};
|
||||
use std::io::Read;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Mutex, MutexGuard};
|
||||
use std::time::SystemTime;
|
||||
|
||||
use serde_json::Value;
|
||||
use vectorcraft_pdf::{APP, PdfPreset, builtin_preset};
|
||||
use vectorcraft_plugins::loader::{Job, Loads};
|
||||
use vectorcraft_plugins::permissions::GrantToken;
|
||||
use vectorcraft_plugins::safe_mode;
|
||||
use vectorcraft_plugins::storage::{self, Meter, Storage, StorageError};
|
||||
@@ -170,6 +172,29 @@ fn list_files(dir: &Path, ext: &str) -> Vec<PathBuf> {
|
||||
files
|
||||
}
|
||||
|
||||
/// [`list_files`], each file with its stamp ([`file_stamp`]) from the same look at it.
|
||||
fn list_stamped_files(dir: &Path, ext: &str) -> Vec<(PathBuf, (u64, SystemTime))> {
|
||||
let Ok(entries) = std::fs::read_dir(dir) else { return vec![] };
|
||||
let mut files: Vec<_> = entries
|
||||
.filter_map(Result::ok)
|
||||
.map(|e| e.path())
|
||||
.filter(|p| p.extension().is_some_and(|e| e.eq_ignore_ascii_case(ext)))
|
||||
.filter_map(|p| {
|
||||
let m = std::fs::metadata(&p).ok().filter(std::fs::Metadata::is_file)?;
|
||||
match m.modified() {
|
||||
Ok(t) => Some((p, (m.len(), t))),
|
||||
Err(e) => {
|
||||
log::warn!("skipping the stored plug-in {}: {e}", p.display());
|
||||
None
|
||||
}
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
files.sort_by_key(|(p, _)| p.file_name().map(|n| n.to_string_lossy().to_lowercase()));
|
||||
files.truncate(MAX_STORE_FILES);
|
||||
files
|
||||
}
|
||||
|
||||
/// The content of `path` when it is at most `max` bytes; the file is never read past `max`.
|
||||
pub(crate) fn read_capped(path: &Path, max: u64) -> Result<Vec<u8>, String> {
|
||||
let bytes = read_past_cap(path, max).map_err(|e| e.to_string())?;
|
||||
@@ -187,11 +212,243 @@ fn read_past_cap(path: &Path, max: u64) -> std::io::Result<Vec<u8>> {
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
/// Plug-ins loading on worker threads, which [`Session::poll_plugin_loads`] and
|
||||
/// [`Session::finish_plugin_loads`] install.
|
||||
pub(crate) enum PluginLoad {
|
||||
/// The plug-in store's ([`Session::load_stored_plugins`]).
|
||||
Stored(StoredLoad),
|
||||
/// The Additional Plug-ins Folder's ([`crate::cmd::plugin::sync_prefs`]).
|
||||
Folder(crate::cmd::plugin::FolderPending),
|
||||
}
|
||||
|
||||
impl PluginLoad {
|
||||
/// Starts the modules loading, unless they started already.
|
||||
fn start(&mut self) {
|
||||
match self {
|
||||
PluginLoad::Stored(load) => load.loads.begin(),
|
||||
PluginLoad::Folder(load) => load.start(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The installs and removals it checks its modules against (`None`: a folder that couldn't be
|
||||
/// listed, or one ended already).
|
||||
fn changes(&self) -> Option<&vectorcraft_plugins::registry::LoadChanges> {
|
||||
match self {
|
||||
PluginLoad::Stored(load) => Some(&load.changes),
|
||||
PluginLoad::Folder(load) => load.changes(),
|
||||
}
|
||||
}
|
||||
|
||||
/// [`PluginLoad::changes`], to adopt an earlier load's.
|
||||
fn changes_mut(&mut self) -> Option<&mut vectorcraft_plugins::registry::LoadChanges> {
|
||||
match self {
|
||||
PluginLoad::Stored(load) => Some(&mut load.changes),
|
||||
PluginLoad::Folder(load) => load.changes_mut(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether every module has been installed or skipped.
|
||||
fn done(&self) -> bool {
|
||||
match self {
|
||||
PluginLoad::Stored(load) => load.next == load.files.len() && load.rest.is_empty(),
|
||||
PluginLoad::Folder(load) => load.done(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether something can be installed or ended now, without waiting.
|
||||
pub(crate) fn ready(&mut self) -> bool {
|
||||
match self {
|
||||
PluginLoad::Stored(load) => load.next == load.files.len() || !load.loaded.is_empty() || load.loads.next_ready(),
|
||||
PluginLoad::Folder(load) => load.ready(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Waits until [`PluginLoad::ready`], starting the modules loading first ([`PluginLoad::start`]).
|
||||
fn wait(&mut self) {
|
||||
self.start();
|
||||
match self {
|
||||
PluginLoad::Stored(load) if load.loaded.is_empty() && load.next < load.files.len() => load.loads.wait_next(),
|
||||
PluginLoad::Stored(_) => {}
|
||||
PluginLoad::Folder(load) => load.wait(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Drops the modules not installed yet ([`Session::cancel_plugin_loads`]), leaving it
|
||||
/// [`PluginLoad::done`] with what it installed.
|
||||
fn cancel(&mut self) {
|
||||
match self {
|
||||
PluginLoad::Stored(load) => {
|
||||
load.loads = Loads::deferred(Vec::new());
|
||||
load.loaded.clear();
|
||||
load.next = load.files.len();
|
||||
load.rest.clear();
|
||||
}
|
||||
PluginLoad::Folder(load) => load.cancel(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether installing it takes the plug-in store's own turn, making the store folder (a
|
||||
/// folder's plug-ins keep their settings and cache there), rather than one that goes ahead
|
||||
/// without a store folder.
|
||||
fn creates_store(&self) -> bool {
|
||||
matches!(self, PluginLoad::Folder(_))
|
||||
}
|
||||
}
|
||||
|
||||
/// A stored plug-in file, with its stamp when it was listed ([`file_stamp`]; `None`: it couldn't be
|
||||
/// read).
|
||||
type StoredFile = (PathBuf, Option<FileStamp>);
|
||||
|
||||
/// The stored plug-ins loading from the plug-in store `dir`.
|
||||
pub(crate) struct StoredLoad {
|
||||
dir: PathBuf,
|
||||
/// The files listed, in file-name order.
|
||||
files: Vec<StoredFile>,
|
||||
loads: Loads<StoredRead>,
|
||||
/// Outcomes taken from `loads` and not installed yet, in order.
|
||||
loaded: VecDeque<vectorcraft_plugins::Result<StoredRead>>,
|
||||
/// The next file to install.
|
||||
next: usize,
|
||||
/// The store's grants this load removed, by id, because the module stored for the id lists no
|
||||
/// permissions: a later file holding a module with that id that the grant covers still loads,
|
||||
/// and the grant goes back to the store.
|
||||
retired: BTreeMap<String, vectorcraft_plugins::permissions::Grant>,
|
||||
/// Installs and removals elsewhere since the store was listed, which a module loaded before
|
||||
/// them doesn't undo.
|
||||
changes: vectorcraft_plugins::registry::LoadChanges,
|
||||
/// The files listed after `files`, in file-name order, with their stamps from when the store was
|
||||
/// listed, that wait for `files` to load because what is left of [`MAX_PLUGIN_STORE`] may not
|
||||
/// cover them until the reads that fail give back what they didn't read
|
||||
/// ([`list_stored_plugins`]).
|
||||
rest: VecDeque<StoredFile>,
|
||||
/// What is left of [`MAX_PLUGIN_STORE`]: the listed length of each file in `files` is taken
|
||||
/// from it, and what a failed read didn't read of it is given back.
|
||||
left: u64,
|
||||
}
|
||||
|
||||
/// What a stored plug-in's load read of its file, at most its listed length, and the module.
|
||||
pub(crate) struct StoredRead {
|
||||
read: u64,
|
||||
plugin: vectorcraft_plugins::Result<vectorcraft_plugins::Plugin>,
|
||||
}
|
||||
|
||||
/// Tests: what runs before a stored module is read, given its path.
|
||||
#[cfg(test)]
|
||||
type StoredHook = Arc<dyn Fn(&Path) + Send + Sync>;
|
||||
|
||||
/// Tests: runs on the worker thread before the stored module at the path it is given is read.
|
||||
#[cfg(test)]
|
||||
pub(crate) static BEFORE_STORED_LOAD: Mutex<Option<StoredHook>> = Mutex::new(None);
|
||||
|
||||
#[cfg(test)]
|
||||
fn before_stored_load(path: &Path) {
|
||||
let hook = BEFORE_STORED_LOAD.lock().unwrap_or_else(|e| e.into_inner()).clone();
|
||||
if let Some(hook) = hook {
|
||||
hook(path);
|
||||
}
|
||||
}
|
||||
|
||||
/// Tests: runs on the worker thread once the stored module at the path it is given has loaded, and
|
||||
/// before its file is read again to check that it still holds the module.
|
||||
#[cfg(test)]
|
||||
pub(crate) static AFTER_STORED_LOAD: Mutex<Option<StoredHook>> = Mutex::new(None);
|
||||
|
||||
#[cfg(test)]
|
||||
fn after_stored_load(path: &Path) {
|
||||
let hook = AFTER_STORED_LOAD.lock().unwrap_or_else(|e| e.into_inner()).clone();
|
||||
if let Some(hook) = hook {
|
||||
hook(path);
|
||||
}
|
||||
}
|
||||
|
||||
/// Why a stored plug-in whose file changed between its listing and its install is skipped.
|
||||
const CHANGED_WHILE_LOADING: &str = "it changed or went away while it loaded";
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// Tests: the stored plug-in bytes a store listed on this thread may read ([`MAX_PLUGIN_STORE`]).
|
||||
pub(crate) static PLUGIN_STORE_BUDGET: std::cell::Cell<u64> = const { std::cell::Cell::new(MAX_PLUGIN_STORE) };
|
||||
}
|
||||
|
||||
/// The stored plug-in bytes one store's load reads, all files together ([`MAX_PLUGIN_STORE`]).
|
||||
#[cfg(not(test))]
|
||||
fn plugin_store_budget() -> u64 {
|
||||
MAX_PLUGIN_STORE
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn plugin_store_budget() -> u64 {
|
||||
PLUGIN_STORE_BUDGET.with(std::cell::Cell::get)
|
||||
}
|
||||
|
||||
/// What a file over its cap is told (a detail after the file's name, in the log or an error).
|
||||
fn too_large(max: u64) -> String {
|
||||
format!("larger than {max} bytes")
|
||||
}
|
||||
|
||||
/// Takes the stored plug-in files at the front of `rest`, in order, each one's listed length taken
|
||||
/// from `left` → those files, and the jobs that load them, each reading no more than that length.
|
||||
/// It stops at the first file that `left` doesn't cover but would if files taken before it failed to
|
||||
/// read and gave back what they took; that file and the ones after it stay in `rest`. A file that
|
||||
/// `left` wouldn't cover even then is skipped with a log record, and once nothing can be given back
|
||||
/// to a used-up `left` the rest are, as when the files were read one after the other.
|
||||
fn list_stored_plugins(rest: &mut VecDeque<StoredFile>, left: &mut u64) -> (Vec<StoredFile>, Vec<Job<StoredRead>>) {
|
||||
let limits = vectorcraft_plugins::Limits::default();
|
||||
let mut files = Vec::new();
|
||||
let mut jobs = Vec::new();
|
||||
// What the files taken so far took of `left`.
|
||||
let mut taken = 0;
|
||||
while let Some((path, stamp)) = rest.pop_front() {
|
||||
let len = stamp.flatten().map_or(0, |(len, _)| len);
|
||||
let most = *left + taken;
|
||||
if most == 0 {
|
||||
log::warn!("skipping the other stored plug-ins: they hold more than {MAX_PLUGIN_STORE} bytes together");
|
||||
rest.clear();
|
||||
break;
|
||||
}
|
||||
if len > most {
|
||||
log::warn!("skipping the stored plug-in {}: {}", path.display(), too_large(most));
|
||||
continue;
|
||||
}
|
||||
// An empty file too waits once `left` is used up.
|
||||
if len > *left || *left == 0 {
|
||||
rest.push_front((path, stamp));
|
||||
break;
|
||||
}
|
||||
*left -= len;
|
||||
taken += len;
|
||||
let item = safe_mode::Item::file(path.display().to_string());
|
||||
let (read, limits) = (path.clone(), limits.clone());
|
||||
jobs.push(Job::new(Some(item), move || {
|
||||
#[cfg(test)]
|
||||
before_stored_load(&read);
|
||||
let mut bytes = vec![];
|
||||
let got = std::fs::File::open(&read).and_then(|f| f.take(len + 1).read_to_end(&mut bytes));
|
||||
let plugin = match got {
|
||||
Err(e) => Err(vectorcraft_plugins::Error::Io(e.to_string())),
|
||||
Ok(_) if bytes.len() as u64 > len => Err(vectorcraft_plugins::Error::Io(too_large(len))),
|
||||
Ok(_) => vectorcraft_plugins::Plugin::load(&bytes, limits),
|
||||
};
|
||||
#[cfg(test)]
|
||||
after_stored_load(&read);
|
||||
// A file replaced while its module loaded, by one that kept its length and modified time,
|
||||
// is told apart by its content: it is read again here, within the load's deadline. The
|
||||
// install then skips a file whose stamp changed since.
|
||||
let plugin = plugin.and_then(|p| {
|
||||
if std::fs::File::open(&read).is_ok_and(|f| holds(f, &bytes)) {
|
||||
Ok(p)
|
||||
} else {
|
||||
Err(vectorcraft_plugins::Error::Io(CHANGED_WHILE_LOADING.into()))
|
||||
}
|
||||
});
|
||||
// A read that failed part way read what `bytes` holds.
|
||||
Ok(StoredRead { read: (bytes.len() as u64).min(len), plugin })
|
||||
}));
|
||||
files.push((path, stamp));
|
||||
}
|
||||
(files, jobs)
|
||||
}
|
||||
|
||||
/// Whether `old` holds exactly `bytes`. It is read no further than one byte past their length, so a
|
||||
/// large file is not read into memory.
|
||||
pub(crate) fn holds(old: impl Read, bytes: &[u8]) -> bool {
|
||||
@@ -230,8 +487,7 @@ fn write_atomic(_: &Path, _: &[u8]) -> std::io::Result<()> {
|
||||
/// replaced or removed, so that every window locks the same file.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn lock_store(dir: &Path) -> std::io::Result<std::fs::File> {
|
||||
std::fs::create_dir_all(dir)?;
|
||||
let file = std::fs::File::options().create(true).truncate(false).read(true).write(true).open(dir.join(DISABLED_LOCK))?;
|
||||
let file = open_store_lock(dir)?;
|
||||
match file.try_lock() {
|
||||
Ok(()) => return Ok(file),
|
||||
Err(std::fs::TryLockError::WouldBlock) => {}
|
||||
@@ -245,6 +501,30 @@ fn lock_store(dir: &Path) -> std::io::Result<std::fs::File> {
|
||||
Ok(file)
|
||||
}
|
||||
|
||||
/// [`DISABLED_LOCK`] in `dir`, opened (and made, with the folder) but not locked.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn open_store_lock(dir: &Path) -> std::io::Result<std::fs::File> {
|
||||
std::fs::create_dir_all(dir)?;
|
||||
std::fs::File::options().create(true).truncate(false).read(true).write(true).open(dir.join(DISABLED_LOCK))
|
||||
}
|
||||
|
||||
/// [`lock_store`] without waiting: `None` while another window or process holds the lock.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn try_lock_store(dir: &Path) -> std::io::Result<Option<std::fs::File>> {
|
||||
let file = open_store_lock(dir)?;
|
||||
match file.try_lock() {
|
||||
Ok(()) => Ok(Some(file)),
|
||||
Err(std::fs::TryLockError::WouldBlock) => Ok(None),
|
||||
Err(std::fs::TryLockError::Error(e)) => Err(e),
|
||||
}
|
||||
}
|
||||
|
||||
/// The browser has no folders to keep anything in.
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn try_lock_store(_: &Path) -> std::io::Result<Option<std::fs::File>> {
|
||||
Err(std::io::Error::new(std::io::ErrorKind::Unsupported, "no file system"))
|
||||
}
|
||||
|
||||
/// The browser has no folders to keep anything in.
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn lock_store(_: &Path) -> std::io::Result<std::fs::File> {
|
||||
@@ -445,78 +725,188 @@ impl Session {
|
||||
}
|
||||
|
||||
/// Keep the plug-ins this session installs in `dir`, take the disabled plug-ins saved there
|
||||
/// ([`DISABLED_FILE`]), and install the stored ones ([`Session::load_stored_plugins`]).
|
||||
/// ([`DISABLED_FILE`]), and install the stored ones ([`Session::load_stored_plugins`]). Loads
|
||||
/// still running from an earlier call are finished first.
|
||||
pub fn attach_plugin_store(&mut self, dir: PathBuf) {
|
||||
let path = dir.join(DISABLED_FILE);
|
||||
self.finish_plugin_loads();
|
||||
self.plugin_dir = Some(dir);
|
||||
// A `plugin.install` in another session or process writes the store before this reads it.
|
||||
let _held = crate::cmd::plugin::hold_plugin_changes();
|
||||
let turn = self.plugin_store_turn_for_load();
|
||||
let disabled = read_capped(&path, safe_mode::MAX_DISABLED_FILE_BYTES).map(|b| safe_mode::parse_disabled_file(&b)).unwrap_or_default();
|
||||
safe_mode::set_disabled(disabled);
|
||||
self.load_stored_plugins_in(&turn);
|
||||
self.start_stored_plugins(true);
|
||||
}
|
||||
|
||||
/// Install the plug-ins kept in the plug-in folder: none in Safe Mode, and none the user
|
||||
/// disabled (matched by file name, which is made from the id). The launch marker names each
|
||||
/// file while it loads. A module that doesn't load, and one that lists permissions the grants
|
||||
/// there don't grant that very module ([`grant_covers`]), is skipped with a log record, and
|
||||
/// stays in the folder with its grant. A grant for an id whose stored module lists no
|
||||
/// permissions is forgotten; one that can't be removed from the grants file doesn't count for
|
||||
/// any session in the process attached to the folder until the file can be written for the id
|
||||
/// ([`Session::ignore_stored_grant`]). The folder is read and changed in one turn on it
|
||||
/// ([`Session::plugin_store_turn_for_load`]).
|
||||
/// disabled (matched by file name, which is made from the id). The modules load on worker
|
||||
/// threads ([`vectorcraft_plugins::loader`]) and install in file-name order, whatever order
|
||||
/// their loads finish in; the launch marker names each file while it loads. A module that
|
||||
/// doesn't load (its load panicked or didn't finish in time included), one that changed or
|
||||
/// went away while it loaded, and one that lists permissions the grants there don't grant that
|
||||
/// very module ([`grant_covers`]), is skipped with a log record, and stays in the folder with
|
||||
/// its grant. A grant for an id whose stored module lists no permissions is forgotten; one that
|
||||
/// can't be removed from the grants file doesn't count for any session in the process attached
|
||||
/// to the folder until the file can be written for the id ([`Session::ignore_stored_grant`]).
|
||||
/// The folder is listed, and what loaded is installed and the folder changed, in turns on it
|
||||
/// ([`Session::plugin_store_turn_for_load`]); the modules load between them. With
|
||||
/// [`Session::load_plugins_in_background`] on, this returns while the modules load.
|
||||
pub fn load_stored_plugins(&mut self) {
|
||||
if self.plugin_dir.is_none() || safe_mode::active() {
|
||||
return;
|
||||
}
|
||||
// A `plugin.install` in another session or process writes the store before this reads it.
|
||||
let _held = crate::cmd::plugin::hold_plugin_changes();
|
||||
let turn = self.plugin_store_turn_for_load();
|
||||
self.load_stored_plugins_in(&turn);
|
||||
self.start_stored_plugins(false);
|
||||
}
|
||||
|
||||
/// [`Session::load_stored_plugins`] in `turn`, while [`crate::cmd::plugin::hold_plugin_changes`]
|
||||
/// is held.
|
||||
fn load_stored_plugins_in(&mut self, turn: &StoreTurn) {
|
||||
/// [`Session::load_stored_plugins`]; `disabled`: first take the disabled plug-ins saved in the
|
||||
/// folder ([`DISABLED_FILE`]).
|
||||
fn start_stored_plugins(&mut self, disabled: bool) {
|
||||
let Some(dir) = self.plugin_dir.clone() else { return };
|
||||
// A `plugin.install` in another session or process writes the store before this lists it.
|
||||
let held = crate::cmd::plugin::hold_plugin_changes();
|
||||
let turn = self.plugin_store_turn_for_load();
|
||||
if disabled {
|
||||
let path = dir.join(DISABLED_FILE);
|
||||
let saved = read_capped(&path, safe_mode::MAX_DISABLED_FILE_BYTES).map(|b| safe_mode::parse_disabled_file(&b)).unwrap_or_default();
|
||||
safe_mode::set_disabled(saved);
|
||||
}
|
||||
if safe_mode::active() {
|
||||
return;
|
||||
}
|
||||
let grants = self.counted_grants(&dir);
|
||||
let limits = vectorcraft_plugins::Limits::default();
|
||||
let mut left = MAX_PLUGIN_STORE;
|
||||
let mut asks_nothing = BTreeSet::new();
|
||||
for path in list_files(&dir, PLUGIN_EXT) {
|
||||
if left == 0 {
|
||||
log::warn!("skipping the other stored plug-ins: they hold more than {MAX_PLUGIN_STORE} bytes together");
|
||||
break;
|
||||
}
|
||||
let module = vectorcraft_plugins::Limits::default().max_module_bytes as u64;
|
||||
let mut rest = VecDeque::new();
|
||||
let disabled: BTreeSet<String> = safe_mode::skipped_ids().iter().map(|id| file_stem(id)).collect();
|
||||
for (path, stamp) in list_stamped_files(&dir, PLUGIN_EXT) {
|
||||
let item = safe_mode::Item::file(path.display().to_string());
|
||||
let stem = path.file_stem().map(|s| s.to_string_lossy().to_string());
|
||||
let by_id = safe_mode::skipped_ids().iter().any(|id| stem.as_deref() == Some(file_stem(id).as_str()));
|
||||
let by_id = path.file_stem().is_some_and(|s| disabled.contains(s.to_string_lossy().as_ref()));
|
||||
if safe_mode::skipped(&item) || by_id {
|
||||
log::info!("skipping the stored plug-in {}: disabled", path.display());
|
||||
} else if stamp.0 > module {
|
||||
log::warn!("skipping the stored plug-in {}: {}", path.display(), too_large(module));
|
||||
} else {
|
||||
rest.push_back((path, Some(Some(stamp))));
|
||||
}
|
||||
}
|
||||
let mut left = plugin_store_budget();
|
||||
let (files, jobs) = list_stored_plugins(&mut rest, &mut left);
|
||||
// A change made after the listing, while `held` no longer stops one, is made elsewhere.
|
||||
let mut changes = vectorcraft_plugins::registry::LoadChanges::default();
|
||||
changes.start();
|
||||
// The modules load after the turn, once the loads queued before them are done.
|
||||
drop((turn, held));
|
||||
let load =
|
||||
StoredLoad { dir, files, loads: Loads::deferred(jobs), loaded: VecDeque::new(), next: 0, retired: BTreeMap::new(), changes, rest, left };
|
||||
self.queue_plugin_load(PluginLoad::Stored(load));
|
||||
}
|
||||
|
||||
/// Installs what the stored plug-ins' `load` has loaded so far, in file-name order up to the
|
||||
/// first module still loading, without waiting ([`Session::load_stored_plugins`]), while
|
||||
/// [`crate::cmd::plugin::hold_plugin_changes`] and `turn` are held.
|
||||
fn install_stored_plugins(&mut self, load: &mut StoredLoad, turn: &StoreTurn) {
|
||||
if load.next == load.files.len() && !load.rest.is_empty() {
|
||||
// Every file listed so far is installed or skipped, and the reads that failed gave
|
||||
// back their length: the files waiting for them are listed now.
|
||||
let (files, jobs) = list_stored_plugins(&mut load.rest, &mut load.left);
|
||||
load.files = files;
|
||||
load.next = 0;
|
||||
load.loads = Loads::start(jobs);
|
||||
return;
|
||||
}
|
||||
load.loaded.extend(load.loads.ready());
|
||||
if load.loaded.is_empty() {
|
||||
return;
|
||||
}
|
||||
let dir = load.dir.clone();
|
||||
// The grants file is read once for this turn. `written` holds whether it names each id
|
||||
// whose grant this turn removed or put back.
|
||||
let file = read_grants(&dir);
|
||||
let mut grants = self.counted(
|
||||
&dir,
|
||||
match &file {
|
||||
Ok(file) => file.grants.clone(),
|
||||
Err(e) => {
|
||||
log::warn!("skipping the stored plug-in grants {}: {}", dir.join(GRANTS_FILE).display(), e.why);
|
||||
BTreeMap::new()
|
||||
}
|
||||
},
|
||||
);
|
||||
let mut written: BTreeMap<String, bool> = BTreeMap::new();
|
||||
let named = |written: &BTreeMap<String, bool>, id: &str| {
|
||||
written.get(id).copied().unwrap_or_else(|| match &file {
|
||||
Ok(file) => file.names(id),
|
||||
Err(e) => e.unread,
|
||||
})
|
||||
};
|
||||
while let (Some(loaded), Some((path, stamp))) = (load.loaded.pop_front(), load.files.get(load.next)) {
|
||||
load.next += 1;
|
||||
load.loads.release(1);
|
||||
// What a read that failed didn't read takes nothing from the total. A load that panicked
|
||||
// or passed its deadline gives nothing back.
|
||||
let loaded = loaded.and_then(|r| {
|
||||
load.left += stamp.flatten().map_or(0, |(len, _)| len).saturating_sub(r.read);
|
||||
r.plugin
|
||||
});
|
||||
// The worker read the file again once its module loaded ([`list_stored_plugins`]); one
|
||||
// whose stamp changed since then is skipped too.
|
||||
if file_stamp(path).ok() != *stamp {
|
||||
log::warn!("skipping the stored plug-in {}: {CHANGED_WHILE_LOADING}", path.display());
|
||||
continue;
|
||||
}
|
||||
let token = safe_mode::loading(&item);
|
||||
let loaded = read_capped(&path, (limits.max_module_bytes as u64).min(left)).and_then(|bytes| {
|
||||
left -= bytes.len() as u64;
|
||||
vectorcraft_plugins::Plugin::load(&bytes, limits.clone()).map_err(|e| e.to_string())
|
||||
});
|
||||
safe_mode::loaded(token);
|
||||
match loaded {
|
||||
Ok(plugin) if load.changes.superseded(plugin.id()) => {
|
||||
log::warn!("skipping the stored plug-in {}: {}", path.display(), vectorcraft_plugins::registry::SUPERSEDED);
|
||||
}
|
||||
// Only this store's grants count: one given elsewhere in the process doesn't let a
|
||||
// module stored here load.
|
||||
Ok(plugin) if plugin.manifest().asks_permissions() => {
|
||||
let m = plugin.manifest();
|
||||
match grants.get(&m.id).filter(|g| grant_covers(g, &plugin)) {
|
||||
let stored = grants.get(&m.id).filter(|g| grant_covers(g, &plugin)).cloned();
|
||||
// A grant given for the id since this load removed one, in another window or
|
||||
// process, is kept.
|
||||
let back = (!grants.contains_key(&m.id) && !named(&written, &m.id))
|
||||
.then(|| load.retired.get(&m.id).filter(|g| grant_covers(g, &plugin)).cloned())
|
||||
.flatten();
|
||||
match stored.or(back.clone()) {
|
||||
Some(g) => {
|
||||
asks_nothing.remove(&m.id);
|
||||
vectorcraft_plugins::registry::grant(GrantToken::from_engine_grants_file(g.clone()));
|
||||
vectorcraft_plugins::registry::set_storage(&m.id, plugin_storage(Some(&dir), &m.id, turn));
|
||||
if let Err(e) = vectorcraft_plugins::registry::install(plugin.with_source(path.display().to_string())) {
|
||||
log::warn!("skipping the stored plug-in {}: {e}", path.display());
|
||||
// A grant this load removed for an earlier file with the id goes back. When
|
||||
// it can't be written back, the module isn't installed: the store doesn't
|
||||
// grant it, so it wouldn't load at the next launch either.
|
||||
if back.is_some() {
|
||||
if !self.store_grant_in(turn, &m.id, Some(g.clone())) {
|
||||
log::warn!("skipping the stored plug-in {}: couldn't put back its grant", path.display());
|
||||
continue;
|
||||
}
|
||||
load.retired.remove(&m.id);
|
||||
written.insert(m.id.clone(), true);
|
||||
grants.insert(m.id.clone(), g.clone());
|
||||
}
|
||||
let id = m.id.clone();
|
||||
let token = GrantToken::from_engine_grants_file(g.clone());
|
||||
// The storage is made before the plug-ins are held: making it reads the store.
|
||||
let storage = plugin_storage(Some(&dir), &id, turn);
|
||||
let attach = || vectorcraft_plugins::registry::set_storage(&id, storage);
|
||||
// The id is checked for a change elsewhere again while the plug-ins are held.
|
||||
let installed = match vectorcraft_plugins::registry::install_for_load(
|
||||
plugin.with_source(path.display().to_string()),
|
||||
&load.changes,
|
||||
Some(token),
|
||||
attach,
|
||||
) {
|
||||
Ok(Some(p)) => {
|
||||
load.changes.installed(&p);
|
||||
true
|
||||
}
|
||||
Ok(None) => {
|
||||
log::warn!("skipping the stored plug-in {}: {}", path.display(), vectorcraft_plugins::registry::SUPERSEDED);
|
||||
false
|
||||
}
|
||||
Err(e) => {
|
||||
log::warn!("skipping the stored plug-in {}: {e}", path.display());
|
||||
false
|
||||
}
|
||||
};
|
||||
// A grant put back for a module that didn't install is removed again, so the
|
||||
// store doesn't grant those bytes at the next launch.
|
||||
if back.is_some() && !installed {
|
||||
if self.store_grant_in(turn, &id, None) {
|
||||
written.insert(id.clone(), false);
|
||||
grants.remove(&id);
|
||||
load.retired.insert(id, g);
|
||||
} else {
|
||||
log::warn!("couldn't remove the grant put back for the stored plug-in {}", path.display());
|
||||
}
|
||||
}
|
||||
}
|
||||
None => {
|
||||
@@ -525,29 +915,213 @@ impl Session {
|
||||
}
|
||||
}
|
||||
Ok(plugin) => {
|
||||
asks_nothing.insert(plugin.id().to_string());
|
||||
vectorcraft_plugins::registry::set_storage(plugin.id(), plugin_storage(Some(&dir), plugin.id(), turn));
|
||||
if let Err(e) = vectorcraft_plugins::registry::install(plugin.with_source(path.display().to_string())) {
|
||||
log::warn!("skipping the stored plug-in {}: {e}", path.display());
|
||||
let id = plugin.id().to_string();
|
||||
// The storage is made before the plug-ins are held: making it reads the store.
|
||||
let storage = plugin_storage(Some(&dir), &id, turn);
|
||||
let attach = || vectorcraft_plugins::registry::set_storage(&id, storage);
|
||||
// The id is checked for a change elsewhere again while the plug-ins are held.
|
||||
let p = match vectorcraft_plugins::registry::install_for_load(
|
||||
plugin.with_source(path.display().to_string()),
|
||||
&load.changes,
|
||||
None,
|
||||
attach,
|
||||
) {
|
||||
Ok(Some(p)) => p,
|
||||
Ok(None) => {
|
||||
log::warn!("skipping the stored plug-in {}: {}", path.display(), vectorcraft_plugins::registry::SUPERSEDED);
|
||||
continue;
|
||||
}
|
||||
Err(e) => {
|
||||
log::warn!("skipping the stored plug-in {}: {e}", path.display());
|
||||
continue;
|
||||
}
|
||||
};
|
||||
load.changes.installed(&p);
|
||||
// In the same turn: the grants for the id stop counting, the process's and the
|
||||
// store's, so no session sees the earlier module as approved. A module installed
|
||||
// in its place meanwhile keeps the process's grant recorded for it.
|
||||
vectorcraft_plugins::registry::revoke_if_installed(&id, p.serial());
|
||||
if let Some(g) = grants.remove(&id) {
|
||||
load.retired.insert(id.clone(), g);
|
||||
}
|
||||
if named(&written, &id) {
|
||||
let writes = self.grant_writes();
|
||||
if self.store_grant_in(turn, &id, None) {
|
||||
written.insert(id.clone(), false);
|
||||
} else if self.holds_plugin_grant(&id) {
|
||||
self.ignore_stored_grant(&id, writes);
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => log::warn!("skipping the stored plug-in {}: {e}", path.display()),
|
||||
}
|
||||
}
|
||||
let kept = read_grants(&dir);
|
||||
for id in &asks_nothing {
|
||||
vectorcraft_plugins::registry::revoke(id);
|
||||
let named = match &kept {
|
||||
Ok(file) => file.names(id),
|
||||
Err(e) => e.unread,
|
||||
}
|
||||
|
||||
/// Whether the loads of the stored plug-ins and of the Additional Plug-ins Folder go on after
|
||||
/// the call that starts them ([`Session::attach_plugin_store`], [`Session::load_stored_plugins`],
|
||||
/// preferences that set the folder): the app turns it on for its launch so that its window
|
||||
/// shows while they load, installs what loaded with [`Session::poll_plugin_loads`] as its
|
||||
/// frames go by, and turns it off once the launch's loads have started. Off (the default),
|
||||
/// those calls return once what loaded is installed, the loads still running from before
|
||||
/// included.
|
||||
pub fn load_plugins_in_background(&mut self, on: bool) {
|
||||
self.plugin_loads_in_background = on;
|
||||
}
|
||||
|
||||
/// Installs what the plug-in loads have loaded so far, in the order the loads started and each
|
||||
/// load's file-name order, up to the first module still loading, without waiting → whether
|
||||
/// some are still loading. A load starts once the loads before it are done. When another
|
||||
/// session or process is changing the plug-ins or the store, nothing installs until a later
|
||||
/// call.
|
||||
pub fn poll_plugin_loads(&mut self) -> bool {
|
||||
while let Some(mut next) = self.plugin_loads.pop_front() {
|
||||
next.start();
|
||||
if !next.ready() {
|
||||
self.plugin_loads.push_front(next);
|
||||
return true;
|
||||
}
|
||||
let Some((held, turn)) = self.plugin_install_turn_now(next.creates_store()) else {
|
||||
self.plugin_loads.push_front(next);
|
||||
return true;
|
||||
};
|
||||
if named {
|
||||
let writes = self.grant_writes();
|
||||
if !self.store_grant_in(turn, id, None) && self.holds_plugin_grant(id) {
|
||||
self.ignore_stored_grant(id, writes);
|
||||
self.install_plugin_load(&mut next, &turn);
|
||||
if !next.done() {
|
||||
self.plugin_loads.push_front(next);
|
||||
return true;
|
||||
}
|
||||
self.end_plugin_load(next, &turn);
|
||||
drop((turn, held));
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Waits for every plug-in load still running and installs what they loaded, in the order the
|
||||
/// loads started. Plug-in commands, and commands that may edit, call it first
|
||||
/// ([`Session::execute`]).
|
||||
pub fn finish_plugin_loads(&mut self) {
|
||||
while let Some(next) = self.plugin_loads.pop_front() {
|
||||
self.finish_plugin_load(next);
|
||||
}
|
||||
}
|
||||
|
||||
/// Ends the plug-in loads still running without installing more of what they load: the app
|
||||
/// calls it as it quits. Modules not started are dropped, and the ones running are given until
|
||||
/// their deadline, so the launch marker is not left naming a plug-in that was loading. Each load
|
||||
/// then ends as one that finished does for what it installed; a folder's end saves the disabled
|
||||
/// list only when the store's turn can be taken without waiting.
|
||||
pub fn cancel_plugin_loads(&mut self) {
|
||||
while let Some(mut load) = self.plugin_loads.pop_front() {
|
||||
load.cancel();
|
||||
// A stored load's grants were settled as each module installed: its end writes nothing.
|
||||
if !load.creates_store() {
|
||||
self.end_plugin_load(load, &StoreTurn::unheld());
|
||||
continue;
|
||||
}
|
||||
// Another session changing the plug-ins isn't waited for either: the folder's load then
|
||||
// ends without the store's turn, so the grants of what it installed are still forgotten
|
||||
// and the store isn't written.
|
||||
let Some(held) = crate::cmd::plugin::try_hold_plugin_changes() else {
|
||||
self.end_plugin_load(load, &StoreTurn::unheld());
|
||||
continue;
|
||||
};
|
||||
// A store another window or process is using isn't waited for: the turn then isn't
|
||||
// held, and the folder's end writes nothing to the store.
|
||||
let turn = match self.plugin_dir.as_deref().map(try_lock_store) {
|
||||
Some(Ok(Some(file))) => StoreTurn { lock: Some(file) },
|
||||
_ => StoreTurn::unheld(),
|
||||
};
|
||||
self.end_plugin_load(load, &turn);
|
||||
drop((turn, held));
|
||||
}
|
||||
}
|
||||
|
||||
/// Waits for `load`'s modules and installs them as they load, in turns on the store, then
|
||||
/// ends it → its report (a folder's; `null` for the stored plug-ins).
|
||||
pub(crate) fn finish_plugin_load(&mut self, mut load: PluginLoad) -> Value {
|
||||
load.start();
|
||||
loop {
|
||||
load.wait();
|
||||
let held = crate::cmd::plugin::hold_plugin_changes();
|
||||
let turn = self.plugin_install_turn(load.creates_store());
|
||||
self.install_plugin_load(&mut load, &turn);
|
||||
if load.done() {
|
||||
let report = self.end_plugin_load(load, &turn);
|
||||
drop((turn, held));
|
||||
return report;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A turn on the store for installing what a load loaded, taken after
|
||||
/// [`crate::cmd::plugin::hold_plugin_changes`]: the folder's own turn
|
||||
/// ([`Session::plugin_store_turn`]) when `create`, else one that goes ahead without a store
|
||||
/// folder ([`Session::plugin_store_turn_for_load`]). One that can't be locked goes ahead
|
||||
/// unheld.
|
||||
fn plugin_install_turn(&self, create: bool) -> StoreTurn {
|
||||
if create { self.plugin_store_turn().unwrap_or_else(|_| StoreTurn::unheld()) } else { self.plugin_store_turn_for_load() }
|
||||
}
|
||||
|
||||
/// [`crate::cmd::plugin::hold_plugin_changes`] and [`Session::plugin_install_turn`] without
|
||||
/// waiting: `None` while another session holds the one or another window or process the other.
|
||||
fn plugin_install_turn_now(&self, create: bool) -> Option<(MutexGuard<'static, ()>, StoreTurn)> {
|
||||
let held = crate::cmd::plugin::try_hold_plugin_changes()?;
|
||||
let turn = match self.plugin_dir.as_deref() {
|
||||
Some(dir) if create || dir.is_dir() => match try_lock_store(dir) {
|
||||
Ok(Some(file)) => StoreTurn { lock: Some(file) },
|
||||
Ok(None) => return None,
|
||||
Err(e) => {
|
||||
log::warn!("can't lock {}: {e}", dir.join(DISABLED_LOCK).display());
|
||||
StoreTurn::unheld()
|
||||
}
|
||||
},
|
||||
_ => StoreTurn::unheld(),
|
||||
};
|
||||
Some((held, turn))
|
||||
}
|
||||
|
||||
/// Whether plug-ins are still loading on worker threads ([`Session::load_plugins_in_background`]).
|
||||
pub fn plugins_loading(&self) -> bool {
|
||||
!self.plugin_loads.is_empty()
|
||||
}
|
||||
|
||||
/// Keeps `load` to install after the loads started before it; without
|
||||
/// [`Session::load_plugins_in_background`], waits for them all and installs what they loaded.
|
||||
pub(crate) fn queue_plugin_load(&mut self, load: PluginLoad) {
|
||||
self.plugin_loads.push_back(load);
|
||||
// The first load starts now; one queued after it starts once those before it are done.
|
||||
if let [only] = self.plugin_loads.make_contiguous() {
|
||||
only.start();
|
||||
}
|
||||
if !self.plugin_loads_in_background {
|
||||
self.finish_plugin_loads();
|
||||
}
|
||||
}
|
||||
|
||||
/// Installs what `load` has loaded so far, without waiting, in `turn`.
|
||||
fn install_plugin_load(&mut self, load: &mut PluginLoad, turn: &StoreTurn) {
|
||||
match load {
|
||||
PluginLoad::Stored(load) => self.install_stored_plugins(load, turn),
|
||||
PluginLoad::Folder(load) => crate::cmd::plugin::install_folder(self, load, turn),
|
||||
}
|
||||
}
|
||||
|
||||
/// Ends `load` once [`PluginLoad::done`], in `turn` → its report (a folder's).
|
||||
fn end_plugin_load(&mut self, load: PluginLoad, turn: &StoreTurn) -> Value {
|
||||
// The loads queued after it count what it installed as their own: one of theirs replaces
|
||||
// it, as it would have with the loads run one after the other.
|
||||
if let Some(ended) = load.changes() {
|
||||
for later in &mut self.plugin_loads {
|
||||
if let Some(changes) = later.changes_mut() {
|
||||
changes.adopt(ended);
|
||||
}
|
||||
}
|
||||
}
|
||||
match load {
|
||||
// A stored load's grants were settled as each module installed.
|
||||
PluginLoad::Stored(_) => Value::Null,
|
||||
PluginLoad::Folder(load) => crate::cmd::plugin::end_folder(self, load, turn),
|
||||
}
|
||||
}
|
||||
|
||||
/// Take a turn on the attached plug-in store ([`StoreTurn`]), waiting while another window or
|
||||
@@ -659,8 +1233,17 @@ impl Session {
|
||||
/// doesn't count for that folder ([`Session::ignore_stored_grant`]). The folder's key is worked
|
||||
/// out on each call, so a path whose link now leads elsewhere is matched with where it leads.
|
||||
fn counted_grants(&self, dir: &Path) -> BTreeMap<String, vectorcraft_plugins::permissions::Grant> {
|
||||
self.counted(dir, stored_grants(dir))
|
||||
}
|
||||
|
||||
/// `grants`, read from the plug-in store `dir`, without those the process doesn't count for
|
||||
/// that folder ([`Session::counted_grants`]).
|
||||
fn counted(
|
||||
&self,
|
||||
dir: &Path,
|
||||
mut grants: BTreeMap<String, vectorcraft_plugins::permissions::Grant>,
|
||||
) -> BTreeMap<String, vectorcraft_plugins::permissions::Grant> {
|
||||
let key = plugin_store_key(dir);
|
||||
let mut grants = stored_grants(dir);
|
||||
let shared = IGNORED_PLUGIN_GRANTS.lock().unwrap_or_else(|e| e.into_inner());
|
||||
for (_, id) in shared.ignored.range((key.clone(), String::new())..).take_while(|(folder, _)| *folder == key) {
|
||||
grants.remove(id);
|
||||
|
||||
@@ -2196,6 +2196,550 @@ fn installed_plugins_are_kept_in_the_store() {
|
||||
assert!(vectorcraft_plugins::registry::get(id).is_none());
|
||||
}
|
||||
|
||||
/// Held by the tests that set [`crate::store::BEFORE_STORED_LOAD`].
|
||||
static STORED_HOOK: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
||||
|
||||
/// A stored module's load waits on its worker thread until the test lets it go
|
||||
/// ([`crate::store::BEFORE_STORED_LOAD`]). The hook is cleared when this is dropped.
|
||||
struct HeldLoad {
|
||||
_lock: std::sync::MutexGuard<'static, ()>,
|
||||
entered: std::sync::Arc<std::sync::atomic::AtomicBool>,
|
||||
go: std::sync::Arc<std::sync::atomic::AtomicBool>,
|
||||
gave_up: std::sync::Arc<std::sync::atomic::AtomicBool>,
|
||||
}
|
||||
|
||||
impl HeldLoad {
|
||||
/// Holds the load of the file at `path`. A load the test never lets go gives up after a
|
||||
/// million yields (so a test of code that waits for it ends) and says so in `gave_up`.
|
||||
fn new(path: std::path::PathBuf) -> HeldLoad {
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
let lock = STORED_HOOK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let (entered, go, gave_up) = (Arc::new(AtomicBool::new(false)), Arc::new(AtomicBool::new(false)), Arc::new(AtomicBool::new(false)));
|
||||
let (e, g, q) = (entered.clone(), go.clone(), gave_up.clone());
|
||||
*crate::store::BEFORE_STORED_LOAD.lock().unwrap_or_else(|e| e.into_inner()) = Some(Arc::new(move |p: &std::path::Path| {
|
||||
if p != path {
|
||||
return;
|
||||
}
|
||||
e.store(true, Ordering::SeqCst);
|
||||
if !(0..1_000_000).any(|_| {
|
||||
std::thread::yield_now();
|
||||
g.load(Ordering::SeqCst)
|
||||
}) {
|
||||
q.store(true, Ordering::SeqCst);
|
||||
}
|
||||
}));
|
||||
HeldLoad { _lock: lock, entered, go, gave_up }
|
||||
}
|
||||
|
||||
fn entered(&self) -> bool {
|
||||
self.entered.load(std::sync::atomic::Ordering::SeqCst)
|
||||
}
|
||||
|
||||
fn release(&self) {
|
||||
self.go.store(true, std::sync::atomic::Ordering::SeqCst);
|
||||
}
|
||||
|
||||
fn gave_up(&self) -> bool {
|
||||
self.gave_up.load(std::sync::atomic::Ordering::SeqCst)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for HeldLoad {
|
||||
fn drop(&mut self) {
|
||||
self.release();
|
||||
*crate::store::BEFORE_STORED_LOAD.lock().unwrap_or_else(|e| e.into_inner()) = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// A store holding the module of a filter `id` in `<id>.wasm`.
|
||||
fn store_with(name: &str, id: &str) -> (crate::tests_links::Folder, std::path::PathBuf) {
|
||||
let folder = crate::tests_links::Folder::new(name);
|
||||
let path = folder.0.join(format!("{id}.wasm"));
|
||||
std::fs::create_dir_all(&folder.0).unwrap();
|
||||
std::fs::write(&path, wat::parse_str(tpl::returning(&tpl::manifest(id, "filter", "{}"), r#"{"objects":[]}"#)).unwrap()).unwrap();
|
||||
(folder, path)
|
||||
}
|
||||
|
||||
/// With loads in the background, attaching a plug-in store returns while a stored module is
|
||||
/// still loading: the plug-in installs once its load is done, at the next plug-in command.
|
||||
#[test]
|
||||
fn a_store_attached_with_background_loads_returns_before_its_plugins_load() {
|
||||
let id = "test.engine.background";
|
||||
let (folder, path) = store_with("plugin-background", id);
|
||||
let held = HeldLoad::new(path);
|
||||
let mut s = session();
|
||||
s.load_plugins_in_background(true);
|
||||
s.attach_plugin_store(folder.0.clone());
|
||||
let returned_while_loading = !held.gave_up();
|
||||
while !held.entered() {
|
||||
std::thread::yield_now();
|
||||
}
|
||||
assert!(returned_while_loading, "attaching the store waited for the module to load");
|
||||
assert!(vectorcraft_plugins::registry::get(id).is_none(), "nothing installs before its load is done");
|
||||
assert!(s.poll_plugin_loads(), "still loading");
|
||||
held.release();
|
||||
let listed = run(&mut s, "plugin.list", json!({}));
|
||||
assert!(listed.to_string().contains(id), "plugin.list waits for the load and lists it: {listed}");
|
||||
assert!(!s.poll_plugin_loads());
|
||||
assert!(vectorcraft_plugins::registry::remove(id));
|
||||
}
|
||||
|
||||
/// Stored files that can't be opened take nothing from the bytes the stored plug-ins may read
|
||||
/// together: a module after 512 MiB of them still installs.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn unreadable_stored_files_leave_the_store_budget_to_the_others() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let id = "test.engine.budget.after";
|
||||
let (folder, _) = store_with("plugin-budget-unreadable", id);
|
||||
let per_file = vectorcraft_plugins::Limits::default().max_module_bytes as u64;
|
||||
let locked: Vec<_> = (0..crate::store::MAX_PLUGIN_STORE.div_ceil(per_file))
|
||||
.map(|n| {
|
||||
// Sparse files sorted before the module, each as long as a module may be.
|
||||
let path = folder.0.join(format!("a{n:03}.wasm"));
|
||||
std::fs::File::create(&path).unwrap().set_len(per_file).unwrap();
|
||||
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o000)).unwrap();
|
||||
path
|
||||
})
|
||||
.collect();
|
||||
// A process that may read any file (root) opens them all: nothing to check.
|
||||
if std::fs::File::open(&locked[0]).is_ok() {
|
||||
return;
|
||||
}
|
||||
let mut s = session();
|
||||
s.attach_plugin_store(folder.0.clone());
|
||||
let installed = vectorcraft_plugins::registry::get(id).is_some();
|
||||
for path in &locked {
|
||||
std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)).unwrap();
|
||||
}
|
||||
assert!(installed, "the files that couldn't be opened used up the store's bytes");
|
||||
assert!(vectorcraft_plugins::registry::remove(id));
|
||||
}
|
||||
|
||||
/// A stored file whose read fails on the worker thread gives back what it took of the bytes the
|
||||
/// stored plug-ins may read together, so a module after files that use them all up still installs.
|
||||
#[test]
|
||||
fn stored_files_whose_reads_fail_leave_the_store_budget_to_the_others() {
|
||||
struct Unhook {
|
||||
_lock: std::sync::MutexGuard<'static, ()>,
|
||||
}
|
||||
impl Drop for Unhook {
|
||||
fn drop(&mut self) {
|
||||
*crate::store::BEFORE_STORED_LOAD.lock().unwrap_or_else(|e| e.into_inner()) = None;
|
||||
}
|
||||
}
|
||||
let id = "test.engine.budget.failed";
|
||||
let (folder, module) = store_with("plugin-budget-failed", id);
|
||||
let len = std::fs::metadata(&module).unwrap().len();
|
||||
// Files sorted before the module, as long as it, that use up the bytes this test's store may read.
|
||||
for n in 0..4 {
|
||||
std::fs::write(folder.0.join(format!("a{n:03}.wasm")), vec![0; len as usize]).unwrap();
|
||||
}
|
||||
crate::store::PLUGIN_STORE_BUDGET.with(|b| b.set(4 * len));
|
||||
let _unhook = Unhook { _lock: STORED_HOOK.lock().unwrap_or_else(|e| e.into_inner()) };
|
||||
// Each of those files goes away as its load starts, so its read fails.
|
||||
let dir = folder.0.clone();
|
||||
*crate::store::BEFORE_STORED_LOAD.lock().unwrap_or_else(|e| e.into_inner()) = Some(std::sync::Arc::new(move |p: &std::path::Path| {
|
||||
if p.parent() == Some(dir.as_path()) && p.file_name().is_some_and(|n| n.to_string_lossy().starts_with('a')) {
|
||||
let _ = std::fs::remove_file(p);
|
||||
}
|
||||
}));
|
||||
let mut s = session();
|
||||
s.attach_plugin_store(folder.0.clone());
|
||||
let installed = vectorcraft_plugins::registry::get(id).is_some();
|
||||
crate::store::PLUGIN_STORE_BUDGET.with(|b| b.set(crate::store::MAX_PLUGIN_STORE));
|
||||
assert!(installed, "the files whose reads failed used up the store's bytes");
|
||||
assert!(vectorcraft_plugins::registry::remove(id));
|
||||
}
|
||||
|
||||
/// A stored file replaced after its module loaded, by one of the same length with the same modified
|
||||
/// time, is skipped: its content no longer holds the module. That holds for a file modified moments
|
||||
/// ago and for one modified an hour ago.
|
||||
#[test]
|
||||
fn a_stored_file_replaced_with_the_same_stamp_while_it_loaded_is_skipped() {
|
||||
struct Unhook {
|
||||
_lock: std::sync::MutexGuard<'static, ()>,
|
||||
}
|
||||
impl Drop for Unhook {
|
||||
fn drop(&mut self) {
|
||||
*crate::store::AFTER_STORED_LOAD.lock().unwrap_or_else(|e| e.into_inner()) = None;
|
||||
}
|
||||
}
|
||||
let _unhook = Unhook { _lock: STORED_HOOK.lock().unwrap_or_else(|e| e.into_inner()) };
|
||||
let hour = std::time::Duration::from_secs(3600);
|
||||
// A modified time ahead of the clock counts as moments ago however long the test takes.
|
||||
for (n, modified) in [std::time::SystemTime::now() + hour, std::time::SystemTime::now() - hour].into_iter().enumerate() {
|
||||
let id = format!("test.engine.background.replaced{n}");
|
||||
let (folder, path) = store_with(&format!("plugin-background-replaced{n}"), &id);
|
||||
std::fs::File::options().write(true).open(&path).unwrap().set_modified(modified).unwrap();
|
||||
let replaced = path.clone();
|
||||
// Set once the file holds other bytes with the old stamp, so the case reaches the check.
|
||||
let rewritten = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
let done = rewritten.clone();
|
||||
*crate::store::AFTER_STORED_LOAD.lock().unwrap_or_else(|e| e.into_inner()) = Some(std::sync::Arc::new(move |p: &std::path::Path| {
|
||||
if p == replaced {
|
||||
let mut bytes = std::fs::read(p).unwrap();
|
||||
bytes.reverse();
|
||||
std::fs::write(p, &bytes).unwrap();
|
||||
std::fs::File::options().write(true).open(p).unwrap().set_modified(modified).unwrap();
|
||||
done.store(true, std::sync::atomic::Ordering::SeqCst);
|
||||
}
|
||||
}));
|
||||
let mut s = session();
|
||||
s.attach_plugin_store(folder.0.clone());
|
||||
let installed = vectorcraft_plugins::registry::remove(&id);
|
||||
assert!(rewritten.load(std::sync::atomic::Ordering::SeqCst), "the file was not replaced while it loaded ({n})");
|
||||
assert!(!installed, "the module installed from a file that no longer holds it ({n})");
|
||||
}
|
||||
}
|
||||
|
||||
/// While a session loads the plug-ins folder in the background, another session's `plugin.list`
|
||||
/// reports the folder as loading; once the load installs, it reports what loaded.
|
||||
#[test]
|
||||
fn another_session_lists_a_folder_still_loading_as_loading() {
|
||||
// Other tests' `prefs.set` replaces the folder last loaded, which the process keeps.
|
||||
if !in_own_process("another_session_lists_a_folder_still_loading_as_loading") {
|
||||
return;
|
||||
}
|
||||
let id = "test.engine.listedloading";
|
||||
let (folder, _) = store_with("plugin-listed-loading", id);
|
||||
let mut background = session();
|
||||
background.load_plugins_in_background(true);
|
||||
run(&mut background, "prefs.set", json!({"values": {"pluginsFolder": folder.0.display().to_string()}}));
|
||||
let mut other = session();
|
||||
let listed = run(&mut other, "plugin.list", json!({}));
|
||||
assert_eq!(listed["folder"]["loading"], true, "{listed}");
|
||||
background.finish_plugin_loads();
|
||||
let listed = run(&mut other, "plugin.list", json!({}));
|
||||
assert!(vectorcraft_plugins::registry::remove(id));
|
||||
assert_eq!(listed["folder"]["loaded"], json!([id]), "{listed}");
|
||||
assert!(listed["folder"].get("loading").is_none(), "{listed}");
|
||||
}
|
||||
|
||||
/// A `plugin.reload` doesn't replace the record of a folder load that started after it: once that
|
||||
/// load installs, `plugin.list` reports its folder.
|
||||
#[test]
|
||||
fn a_reload_keeps_the_record_of_a_folder_load_started_after_it() {
|
||||
// Other tests' `prefs.set` replaces the folder last loaded, which the process keeps.
|
||||
if !in_own_process("a_reload_keeps_the_record_of_a_folder_load_started_after_it") {
|
||||
return;
|
||||
}
|
||||
let (reloaded, later) = ("test.engine.reloadorder.reloaded", "test.engine.reloadorder.later");
|
||||
let (reload_folder, _) = store_with("plugin-reload-order-reloaded", reloaded);
|
||||
let (later_folder, _) = store_with("plugin-reload-order-later", later);
|
||||
let other = std::rc::Rc::new(std::cell::RefCell::new(None));
|
||||
let started = other.clone();
|
||||
let path = later_folder.0.display().to_string();
|
||||
// Another session sets the plug-ins folder while the reload loads.
|
||||
crate::cmd::plugin::BEFORE_RELOAD_INSTALLS.set(Some(Box::new(move || {
|
||||
let mut background = session();
|
||||
background.load_plugins_in_background(true);
|
||||
run(&mut background, "prefs.set", json!({"values": {"pluginsFolder": path}}));
|
||||
*started.borrow_mut() = Some(background);
|
||||
})));
|
||||
let mut s = session();
|
||||
run(&mut s, "plugin.reload", json!({"path": reload_folder.0.display().to_string()}));
|
||||
let mut background = other.borrow_mut().take().expect("the other session's load started while the reload loaded");
|
||||
background.finish_plugin_loads();
|
||||
let listed = run(&mut s, "plugin.list", json!({}));
|
||||
assert!(vectorcraft_plugins::registry::remove(reloaded) && vectorcraft_plugins::registry::remove(later));
|
||||
assert_eq!(listed["folder"]["loaded"], json!([later]), "{listed}");
|
||||
}
|
||||
|
||||
/// The plug-ins folder already loaded isn't loaded again when the preferences are applied, unless
|
||||
/// a file in it found no loader thread to load it: then it is.
|
||||
#[test]
|
||||
fn a_folder_in_which_a_file_found_no_thread_is_loaded_again() {
|
||||
if !in_own_process("a_folder_in_which_a_file_found_no_thread_is_loaded_again") {
|
||||
return;
|
||||
}
|
||||
let id = "test.engine.nothread";
|
||||
let (folder, _) = store_with("plugin-no-thread", id);
|
||||
let mut s = session();
|
||||
run(&mut s, "prefs.set", json!({"values": {"pluginsFolder": folder.0.display().to_string()}}));
|
||||
assert!(vectorcraft_plugins::registry::remove(id), "installed from the folder");
|
||||
crate::cmd::plugin::sync_prefs(&mut s);
|
||||
assert!(vectorcraft_plugins::registry::get(id).is_none(), "a folder already loaded was loaded again");
|
||||
crate::cmd::plugin::folder_found_no_thread();
|
||||
crate::cmd::plugin::sync_prefs(&mut s);
|
||||
assert!(vectorcraft_plugins::registry::remove(id), "the folder wasn't loaded again");
|
||||
}
|
||||
|
||||
/// A folder listed while the stored plug-ins still load, in the same session, replaces a stored
|
||||
/// plug-in with a module of the same id once it loads, as it does when the loads run one after the
|
||||
/// other: what an earlier load of the session installed doesn't count as a change made elsewhere.
|
||||
#[test]
|
||||
fn a_folder_queued_behind_the_stored_plugins_replaces_one_with_its_id() {
|
||||
let _folder = PREFS_FOLDER.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let id = "test.engine.queued.same";
|
||||
let (store, stored) = store_with("plugin-queued-store", id);
|
||||
let (folder, from_folder) = store_with("plugin-queued-folder", id);
|
||||
let held = HeldLoad::new(stored);
|
||||
let mut s = session();
|
||||
s.load_plugins_in_background(true);
|
||||
s.attach_plugin_store(store.0.clone());
|
||||
while !held.entered() {
|
||||
std::thread::yield_now();
|
||||
}
|
||||
s.prefs.plugins_folder = folder.0.display().to_string();
|
||||
crate::cmd::plugin::sync_prefs(&mut s);
|
||||
held.release();
|
||||
s.finish_plugin_loads();
|
||||
let source = vectorcraft_plugins::registry::get(id).and_then(|p| p.source().map(str::to_string));
|
||||
assert!(vectorcraft_plugins::registry::remove(id));
|
||||
assert_eq!(source.as_deref(), Some(from_folder.display().to_string().as_str()), "the folder's module replaces the stored one");
|
||||
}
|
||||
|
||||
/// A query that only reads runs while the stored plug-ins load in the background, and doesn't
|
||||
/// wait for them; a plug-in command does.
|
||||
#[test]
|
||||
fn a_query_runs_while_the_plugins_load() {
|
||||
let id = "test.engine.background.query";
|
||||
let (folder, path) = store_with("plugin-background-query", id);
|
||||
let held = HeldLoad::new(path);
|
||||
let mut s = session();
|
||||
run(&mut s, "file.new", json!({}));
|
||||
s.load_plugins_in_background(true);
|
||||
s.attach_plugin_store(folder.0.clone());
|
||||
while !held.entered() {
|
||||
std::thread::yield_now();
|
||||
}
|
||||
run(&mut s, "document.info", json!({}));
|
||||
let waited = held.gave_up() || !s.plugins_loading();
|
||||
held.release();
|
||||
assert!(!waited, "document.info waited for the plug-ins to load");
|
||||
assert!(crate::waits_for_plugin_loads("plugin.list") && !crate::waits_for_plugin_loads("document.info"));
|
||||
s.finish_plugin_loads();
|
||||
assert!(vectorcraft_plugins::registry::remove(id));
|
||||
}
|
||||
|
||||
/// The stored plug-ins load without holding the lock that `plugin.install` and `plugin.remove`
|
||||
/// take, so another session's plug-in changes don't wait for them.
|
||||
#[test]
|
||||
fn stored_plugins_load_without_holding_the_plugin_changes_lock() {
|
||||
let id = "test.engine.unlocked";
|
||||
let (folder, path) = store_with("plugin-unlocked", id);
|
||||
let held = HeldLoad::new(path);
|
||||
let mut s = session();
|
||||
s.load_plugins_in_background(true);
|
||||
s.attach_plugin_store(folder.0.clone());
|
||||
while !held.entered() && !held.gave_up() {
|
||||
std::thread::yield_now();
|
||||
}
|
||||
// Other tests take the lock for a moment; the load holding it would hold it throughout (a
|
||||
// tenth of the yields the held load waits before it gives up).
|
||||
let free = (0..100_000).any(|_| {
|
||||
std::thread::yield_now();
|
||||
crate::cmd::plugin::plugin_changes_free()
|
||||
});
|
||||
// A load that gave up waiting no longer holds anything, so a free lock then shows nothing.
|
||||
let gave_up = held.gave_up();
|
||||
held.release();
|
||||
s.finish_plugin_loads();
|
||||
assert!(!gave_up, "the held load gave up before the lock was looked at");
|
||||
assert!(free, "the lock was held while the module loaded");
|
||||
assert!(vectorcraft_plugins::registry::remove(id));
|
||||
}
|
||||
|
||||
/// Loads canceled as the app quits still end for what they installed: a stored module listing no
|
||||
/// permissions that installed before a later one finished loading has its id's grant forgotten,
|
||||
/// in the process and in `grants.json`, and the module still loading doesn't install.
|
||||
#[test]
|
||||
fn canceled_loads_forget_the_grants_of_what_they_installed() {
|
||||
use vectorcraft_plugins::permissions::sha256_hex;
|
||||
let (first, later) = ("test.engine.cancel.a", "test.engine.cancel.b");
|
||||
let (folder, _) = store_with("plugin-cancel", first);
|
||||
let held_path = folder.0.join(format!("{later}.wasm"));
|
||||
std::fs::write(&held_path, wat::parse_str(tpl::returning(&tpl::manifest(later, "filter", "{}"), r#"{"objects":[]}"#)).unwrap()).unwrap();
|
||||
let empty = json!({"objects": []});
|
||||
let approved = asking(first, r#"["doc.read"]"#, &empty);
|
||||
let grants = folder.0.join("grants.json");
|
||||
let entry = json!([{"id": first, "hash": sha256_hex(&approved), "permissions": ["doc.read"]}]);
|
||||
std::fs::write(&grants, serde_json::to_vec(&entry).unwrap()).unwrap();
|
||||
let held = HeldLoad::new(held_path);
|
||||
let mut s = session();
|
||||
s.load_plugins_in_background(true);
|
||||
s.attach_plugin_store(folder.0.clone());
|
||||
while vectorcraft_plugins::registry::get(first).is_none() && !held.gave_up() {
|
||||
s.poll_plugin_loads();
|
||||
std::thread::yield_now();
|
||||
}
|
||||
assert!(vectorcraft_plugins::registry::get(first).is_some(), "the first module installed while the second loads");
|
||||
s.cancel_plugin_loads();
|
||||
// The file goes once it holds no grant.
|
||||
let listed: Vec<Value> = std::fs::read(&grants).map(|b| serde_json::from_slice(&b).unwrap()).unwrap_or_default();
|
||||
assert!(listed.iter().all(|e| e["id"] != first), "{listed:?}");
|
||||
assert!(vectorcraft_plugins::registry::granted(first).is_none());
|
||||
assert!(vectorcraft_plugins::registry::get(later).is_none(), "the module still loading doesn't install");
|
||||
assert!(!s.plugins_loading());
|
||||
drop(held);
|
||||
assert!(vectorcraft_plugins::registry::remove(first));
|
||||
}
|
||||
|
||||
/// The grants for a stored module that lists no permissions stop counting when it installs, in the
|
||||
/// same turn, while a later module of the load is still loading.
|
||||
#[test]
|
||||
fn a_stored_module_without_permissions_ends_its_grant_when_it_installs() {
|
||||
use vectorcraft_plugins::permissions::sha256_hex;
|
||||
let (first, later) = ("test.engine.retire.a", "test.engine.retire.b");
|
||||
let (folder, _) = store_with("plugin-retire", first);
|
||||
let held_path = folder.0.join(format!("{later}.wasm"));
|
||||
std::fs::write(&held_path, wat::parse_str(tpl::returning(&tpl::manifest(later, "filter", "{}"), r#"{"objects":[]}"#)).unwrap()).unwrap();
|
||||
let empty = json!({"objects": []});
|
||||
let approved = asking(first, r#"["doc.read"]"#, &empty);
|
||||
let grants = folder.0.join("grants.json");
|
||||
let entry = json!([{"id": first, "hash": sha256_hex(&approved), "permissions": ["doc.read"]}]);
|
||||
std::fs::write(&grants, serde_json::to_vec(&entry).unwrap()).unwrap();
|
||||
let held = HeldLoad::new(held_path);
|
||||
let mut s = session();
|
||||
s.load_plugins_in_background(true);
|
||||
s.attach_plugin_store(folder.0.clone());
|
||||
while vectorcraft_plugins::registry::get(first).is_none() && !held.gave_up() {
|
||||
s.poll_plugin_loads();
|
||||
std::thread::yield_now();
|
||||
}
|
||||
assert!(vectorcraft_plugins::registry::get(first).is_some(), "the first module installed while the second loads");
|
||||
assert!(s.plugins_loading(), "the second module is still loading");
|
||||
let listed: Vec<Value> = std::fs::read(&grants).map(|b| serde_json::from_slice(&b).unwrap()).unwrap_or_default();
|
||||
assert!(listed.iter().all(|e| e["id"] != first), "{listed:?}");
|
||||
assert!(vectorcraft_plugins::registry::granted(first).is_none());
|
||||
drop(held);
|
||||
s.finish_plugin_loads();
|
||||
assert!(vectorcraft_plugins::registry::remove(first));
|
||||
assert!(vectorcraft_plugins::registry::remove(later));
|
||||
}
|
||||
|
||||
/// A grant the load removed for a stored module without permissions doesn't go back for a later
|
||||
/// file with the same id when another window or process granted the id since: that grant stays, and
|
||||
/// the later module, which it doesn't cover, is skipped.
|
||||
#[test]
|
||||
fn a_grant_given_elsewhere_since_the_load_removed_one_is_kept() {
|
||||
use vectorcraft_plugins::permissions::sha256_hex;
|
||||
let id = "test.engine.retire.kept";
|
||||
let folder = crate::tests_links::Folder::new("plugin-retire-kept");
|
||||
std::fs::create_dir_all(&folder.0).unwrap();
|
||||
let empty = json!({"objects": []});
|
||||
let (first, later) = (folder.0.join("a.wasm"), folder.0.join("b.wasm"));
|
||||
std::fs::write(&first, wat::parse_str(tpl::returning(&tpl::manifest(id, "filter", "{}"), r#"{"objects":[]}"#)).unwrap()).unwrap();
|
||||
let approved = asking(id, r#"["doc.read"]"#, &empty);
|
||||
std::fs::write(&later, &approved).unwrap();
|
||||
let grants = folder.0.join("grants.json");
|
||||
let entry = |hash: String| serde_json::to_vec(&json!([{"id": id, "hash": hash, "permissions": ["doc.read"]}])).unwrap();
|
||||
std::fs::write(&grants, entry(sha256_hex(&approved))).unwrap();
|
||||
let held = HeldLoad::new(later.clone());
|
||||
let mut s = session();
|
||||
s.load_plugins_in_background(true);
|
||||
s.attach_plugin_store(folder.0.clone());
|
||||
while vectorcraft_plugins::registry::get(id).is_none() && !held.gave_up() {
|
||||
s.poll_plugin_loads();
|
||||
std::thread::yield_now();
|
||||
}
|
||||
// Another process grants the id for another module while the later file loads.
|
||||
let other = asking(id, r#"["doc.read"]"#, &json!({"objects": [{"path": triangle()}]}));
|
||||
std::fs::write(&grants, entry(sha256_hex(&other))).unwrap();
|
||||
drop(held);
|
||||
s.finish_plugin_loads();
|
||||
let source = vectorcraft_plugins::registry::get(id).and_then(|p| p.source().map(str::to_string));
|
||||
assert!(vectorcraft_plugins::registry::remove(id));
|
||||
let listed: Vec<Value> = serde_json::from_slice(&std::fs::read(&grants).unwrap()).unwrap();
|
||||
assert_eq!(source.as_deref(), Some(first.display().to_string().as_str()), "the later module installed");
|
||||
assert_eq!(listed.iter().map(|e| e["hash"].clone()).collect::<Vec<_>>(), [json!(sha256_hex(&other))], "{listed:?}");
|
||||
}
|
||||
|
||||
/// A grant the load removed for a stored module without permissions that can't be written back for
|
||||
/// a later file with the same id leaves that file's module uninstalled: the store doesn't grant it.
|
||||
#[test]
|
||||
fn a_grant_that_cannot_be_put_back_leaves_the_later_module_uninstalled() {
|
||||
use vectorcraft_plugins::permissions::sha256_hex;
|
||||
let id = "test.engine.retire.unwritten";
|
||||
let folder = crate::tests_links::Folder::new("plugin-retire-unwritten");
|
||||
std::fs::create_dir_all(&folder.0).unwrap();
|
||||
let empty = json!({"objects": []});
|
||||
let (first, later) = (folder.0.join("a.wasm"), folder.0.join("b.wasm"));
|
||||
std::fs::write(&first, wat::parse_str(tpl::returning(&tpl::manifest(id, "filter", "{}"), r#"{"objects":[]}"#)).unwrap()).unwrap();
|
||||
let approved = asking(id, r#"["doc.read"]"#, &empty);
|
||||
std::fs::write(&later, &approved).unwrap();
|
||||
let grants = folder.0.join("grants.json");
|
||||
std::fs::write(&grants, serde_json::to_vec(&json!([{"id": id, "hash": sha256_hex(&approved), "permissions": ["doc.read"]}])).unwrap()).unwrap();
|
||||
// The first write removes the grant; the second, which puts it back, finds a folder where the
|
||||
// file goes and fails.
|
||||
let blocked = grants.clone();
|
||||
crate::store::AFTER_GRANTS_READ.set(Some(Box::new(move || {
|
||||
crate::store::AFTER_GRANTS_READ.set(Some(Box::new(move || {
|
||||
let _ = std::fs::remove_file(&blocked);
|
||||
std::fs::create_dir_all(&blocked).unwrap();
|
||||
})));
|
||||
})));
|
||||
let mut s = session();
|
||||
s.attach_plugin_store(folder.0.clone());
|
||||
crate::store::AFTER_GRANTS_READ.set(None);
|
||||
let source = vectorcraft_plugins::registry::get(id).and_then(|p| p.source().map(str::to_string));
|
||||
let _ = std::fs::remove_dir(&grants);
|
||||
assert!(vectorcraft_plugins::registry::remove(id));
|
||||
assert_eq!(source.as_deref(), Some(first.display().to_string().as_str()), "the later module installed without its grant in the store");
|
||||
}
|
||||
|
||||
/// A grant the load put back for a later stored file with the same id is removed again when that
|
||||
/// file's module doesn't install because the id was installed elsewhere meanwhile: the store doesn't
|
||||
/// grant bytes that weren't installed.
|
||||
#[test]
|
||||
fn a_grant_put_back_for_a_module_that_did_not_install_is_removed_again() {
|
||||
use vectorcraft_plugins::permissions::sha256_hex;
|
||||
let id = "test.engine.retire.superseded";
|
||||
let folder = crate::tests_links::Folder::new("plugin-retire-superseded");
|
||||
std::fs::create_dir_all(&folder.0).unwrap();
|
||||
let empty = json!({"objects": []});
|
||||
let (first, later) = (folder.0.join("a.wasm"), folder.0.join("b.wasm"));
|
||||
let plain = wat::parse_str(tpl::returning(&tpl::manifest(id, "filter", "{}"), r#"{"objects":[]}"#)).unwrap();
|
||||
std::fs::write(&first, &plain).unwrap();
|
||||
let approved = asking(id, r#"["doc.read"]"#, &empty);
|
||||
std::fs::write(&later, &approved).unwrap();
|
||||
let grants = folder.0.join("grants.json");
|
||||
std::fs::write(&grants, serde_json::to_vec(&json!([{"id": id, "hash": sha256_hex(&approved), "permissions": ["doc.read"]}])).unwrap()).unwrap();
|
||||
// The first write removes the grant; while the second puts it back, the id is installed
|
||||
// elsewhere.
|
||||
crate::store::AFTER_GRANTS_READ.set(Some(Box::new(move || {
|
||||
crate::store::AFTER_GRANTS_READ.set(Some(Box::new(move || {
|
||||
vectorcraft_plugins::registry::install_bytes(&plain).unwrap();
|
||||
})));
|
||||
})));
|
||||
let mut s = session();
|
||||
s.attach_plugin_store(folder.0.clone());
|
||||
crate::store::AFTER_GRANTS_READ.set(None);
|
||||
let source = vectorcraft_plugins::registry::get(id).and_then(|p| p.source().map(str::to_string));
|
||||
assert!(vectorcraft_plugins::registry::remove(id));
|
||||
// A grants file that went away holds no grant; one still there must read as a list.
|
||||
let listed: Vec<Value> = match std::fs::read(&grants) {
|
||||
Ok(b) => serde_json::from_slice(&b).unwrap(),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => vec![],
|
||||
Err(e) => panic!("the grants file could not be read: {e}"),
|
||||
};
|
||||
assert_eq!(source, None, "the later module replaced the one installed elsewhere");
|
||||
assert!(listed.iter().all(|e| e["id"] != id), "the grant put back stayed in the store: {listed:?}");
|
||||
}
|
||||
|
||||
/// A session that waits for its loads and sets the plug-ins folder another session is still
|
||||
/// loading in the background loads the folder itself: its plug-in is installed when `prefs.set`
|
||||
/// returns, and the other session's load, when it installs, counts the same module as loaded.
|
||||
#[test]
|
||||
fn a_folder_another_session_is_loading_is_loaded_by_a_session_that_waits() {
|
||||
let _folder = PREFS_FOLDER.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let id = "test.engine.sharedfolder";
|
||||
let (folder, _) = store_with("plugin-shared-folder", id);
|
||||
let path = folder.0.display().to_string();
|
||||
let mut background = session();
|
||||
background.load_plugins_in_background(true);
|
||||
run(&mut background, "prefs.set", json!({"values": {"pluginsFolder": path}}));
|
||||
assert!(background.plugins_loading(), "the folder loads in the background");
|
||||
let mut waits = session();
|
||||
run(&mut waits, "prefs.set", json!({"values": {"pluginsFolder": path}}));
|
||||
assert!(vectorcraft_plugins::registry::get(id).is_some(), "prefs.set returned before the folder's plug-in installed");
|
||||
let report = run(&mut background, "plugin.list", json!({}));
|
||||
assert!(!background.plugins_loading());
|
||||
assert!(vectorcraft_plugins::registry::remove(id), "{report}");
|
||||
}
|
||||
|
||||
/// A heavy test filter `id` that counts `steps` down, then adds a triangle named "Plug-in".
|
||||
fn heavy(id: &str, steps: u64) -> Vec<u8> {
|
||||
let manifest = format!(r#"{{"id":"{id}","name":"Test {id}","version":"1","kind":"filter","budget":"heavy"}}"#);
|
||||
|
||||
@@ -90,7 +90,7 @@ fn a_disabled_plug_in_stays_installed_and_loads_again_once_enabled_at_the_next_l
|
||||
let list = s.execute("plugin.list", &json!({})).unwrap();
|
||||
assert_eq!((list["safeMode"].clone(), list["disabled"][0]["id"].clone()), (json!(false), json!("test.sm.x")));
|
||||
let state = s.execute("plugin.safeMode", &json!({})).unwrap();
|
||||
assert_eq!(state, json!({"active": false, "source": null, "pendingItem": null, "disabled": state["disabled"].clone()}));
|
||||
assert_eq!(state, json!({"active": false, "source": null, "pendingItem": null, "pendingItems": [], "disabled": state["disabled"].clone()}));
|
||||
assert_eq!(state["disabled"].as_array().map(Vec::len), Some(1));
|
||||
|
||||
s.execute("plugin.setEnabled", &json!({"id": "test.sm.x", "enabled": true})).unwrap();
|
||||
|
||||
@@ -807,7 +807,7 @@ mod tests {
|
||||
crate::safe_mode::set_active(None);
|
||||
let dir = std::env::temp_dir().join(format!("vc-effect-overlap-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
assert_eq!(crate::safe_mode::begin_launch(&dir), None);
|
||||
assert_eq!(crate::safe_mode::begin_launch(&dir), []);
|
||||
let marker = || {
|
||||
let files = std::fs::read_dir(&dir).unwrap().filter_map(|e| Some(e.ok()?.path()));
|
||||
let json = files.filter(|p| p.extension().is_some_and(|x| x == "json")).collect::<Vec<_>>();
|
||||
@@ -816,8 +816,8 @@ mod tests {
|
||||
};
|
||||
let src = crate::wat::returning(&crate::wat::manifest("test.effect.overlap", "effect", "{}"), r#"{"objects":[]}"#);
|
||||
let plugin = registry::install(crate::Plugin::load(&wat::parse_str(&src).unwrap(), Limits::default()).unwrap()).unwrap();
|
||||
let named = Some(crate::safe_mode::Item::of(&plugin));
|
||||
assert_eq!(marker(), None);
|
||||
let named = vec![crate::safe_mode::Item::of(&plugin)];
|
||||
assert_eq!(marker(), []);
|
||||
|
||||
assert!(begin_run(&plugin), "the first run is guarded");
|
||||
assert!(begin_run(&plugin), "a run that starts while the first is running is guarded");
|
||||
@@ -829,9 +829,9 @@ mod tests {
|
||||
end_run(plugin.serial(), true);
|
||||
assert_eq!(marker(), named, "the third run is still running");
|
||||
end_run(plugin.serial(), false);
|
||||
assert_eq!(marker(), None, "no run is running");
|
||||
assert_eq!(marker(), [], "no run is running");
|
||||
assert!(!begin_run(&plugin), "later runs aren't guarded");
|
||||
assert_eq!(marker(), None);
|
||||
assert_eq!(marker(), []);
|
||||
|
||||
crate::safe_mode::end_launch();
|
||||
crate::safe_mode::forget_previous();
|
||||
|
||||
@@ -40,6 +40,7 @@ pub mod effect;
|
||||
pub mod export;
|
||||
pub mod host;
|
||||
pub mod import;
|
||||
pub mod loader;
|
||||
pub mod manifest;
|
||||
pub mod objects;
|
||||
pub mod painted;
|
||||
|
||||
@@ -0,0 +1,753 @@
|
||||
//! Loads plug-ins on worker threads.
|
||||
//!
|
||||
//! [`Loads::start`] hands its jobs to a pool of at most [`MAX_WORKERS`] threads and returns at
|
||||
//! once. The web build has no threads, so there it runs the jobs one after the other before it
|
||||
//! returns. Each job runs inside a panic boundary: a job that panics fails with [`Error::Failed`],
|
||||
//! and the launch marker stops naming its item ([`crate::safe_mode::loading`]), as when it loads.
|
||||
//! A job that takes [`LOAD_DEADLINE`] or longer fails too, and the marker names its item until its
|
||||
//! thread returns; while it is still running, its thread is left to finish on its own, and another worker
|
||||
//! takes the jobs after it, up to twice as many threads as were started. While
|
||||
//! [`MAX_STUCK_THREADS`] threads in the process still run jobs past their deadline, no load starts
|
||||
//! a thread. When no thread is left to take them, the jobs not started fail.
|
||||
//!
|
||||
//! The caller takes the outcomes in the order of the jobs, whatever order they finish in
|
||||
//! ([`Loads::ready`]), so it installs them in the same order on every launch. A job starts only
|
||||
//! while fewer than twice the workers' count of outcomes before it are waiting to be taken or are
|
||||
//! still held by the caller ([`Loads::release`]), so the loaded modules held at once stay bounded
|
||||
//! however many jobs there are.
|
||||
|
||||
use std::collections::VecDeque;
|
||||
use std::panic::{AssertUnwindSafe, catch_unwind};
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender};
|
||||
use std::sync::{Arc, Condvar, Mutex, MutexGuard};
|
||||
use std::time::Duration;
|
||||
|
||||
use web_time::Instant;
|
||||
|
||||
use crate::safe_mode::{self, Item};
|
||||
use crate::{Error, Result};
|
||||
|
||||
/// The most worker threads one [`Loads`] starts, besides those that replace a worker whose job
|
||||
/// passed [`LOAD_DEADLINE`].
|
||||
pub const MAX_WORKERS: usize = 4;
|
||||
|
||||
/// How long one job may take; one that takes longer fails as not finished.
|
||||
pub const LOAD_DEADLINE: Duration = Duration::from_secs(10);
|
||||
|
||||
/// How often a wait looks at the deadlines while no job finishes.
|
||||
const TICK: Duration = Duration::from_millis(50);
|
||||
|
||||
/// The most loader threads in the process still running a job past its deadline. While that many
|
||||
/// are, no [`Loads`] starts another thread, so loads started again and again on files whose reads
|
||||
/// never return don't pile up threads.
|
||||
pub const MAX_STUCK_THREADS: usize = 2 * MAX_WORKERS;
|
||||
|
||||
/// Loader threads in the process running a job past its deadline, across every [`Loads`].
|
||||
static STUCK_THREADS: AtomicUsize = AtomicUsize::new(0);
|
||||
|
||||
/// The [`Error::Failed`] message of a job that failed because no thread was left to run it.
|
||||
pub const NO_THREAD: &str = "no thread was left to load it";
|
||||
|
||||
/// One plug-in to load: the item the launch marker names while it loads, and the work, which runs
|
||||
/// on a worker thread.
|
||||
pub struct Job<T> {
|
||||
pub item: Option<Item>,
|
||||
pub work: Box<dyn FnOnce() -> Result<T> + Send>,
|
||||
}
|
||||
|
||||
impl<T> Job<T> {
|
||||
pub fn new(item: Option<Item>, work: impl FnOnce() -> Result<T> + Send + 'static) -> Self {
|
||||
Job { item, work: Box::new(work) }
|
||||
}
|
||||
}
|
||||
|
||||
/// The time since a fixed start, for the deadlines.
|
||||
type Clock = Arc<dyn Fn() -> Duration + Send + Sync>;
|
||||
|
||||
/// A job's outcome as its worker sends it: the job, its result and how long it took.
|
||||
type Done<T> = (usize, Result<T>, Duration);
|
||||
|
||||
/// What the workers and [`Loads`] share.
|
||||
struct State<T> {
|
||||
/// The jobs not started yet, in order.
|
||||
queue: VecDeque<(usize, Job<T>)>,
|
||||
/// When each job started, and whether it has finished or passed its deadline.
|
||||
started: Vec<Option<Duration>>,
|
||||
finished: Vec<bool>,
|
||||
expired: Vec<bool>,
|
||||
/// Jobs whose index is below this may start.
|
||||
limit: usize,
|
||||
/// Worker threads alive, and how many of them run a job past its deadline.
|
||||
workers: usize,
|
||||
stuck: usize,
|
||||
}
|
||||
|
||||
struct Pool<T> {
|
||||
state: Mutex<State<T>>,
|
||||
/// Told when a job may start, or when the queue is emptied.
|
||||
wake: Condvar,
|
||||
}
|
||||
|
||||
impl<T> Pool<T> {
|
||||
fn lock(&self) -> MutexGuard<'_, State<T>> {
|
||||
self.state.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
}
|
||||
|
||||
/// Counts a worker as alive until its thread ends, however it ends.
|
||||
struct Alive<T>(Arc<Pool<T>>);
|
||||
|
||||
impl<T> Drop for Alive<T> {
|
||||
fn drop(&mut self) {
|
||||
self.0.lock().workers -= 1;
|
||||
}
|
||||
}
|
||||
|
||||
/// Jobs loading on worker threads ([`Loads::start`]).
|
||||
pub struct Loads<T: Send + 'static> {
|
||||
pool: Arc<Pool<T>>,
|
||||
results: Mutex<Receiver<Done<T>>>,
|
||||
send: Sender<Done<T>>,
|
||||
outcomes: Vec<Option<Result<T>>>,
|
||||
/// The outcomes before this one were taken ([`Loads::ready`]).
|
||||
next: usize,
|
||||
/// Of those, the ones the caller is done with ([`Loads::release`]).
|
||||
released: usize,
|
||||
/// How many jobs past `next` may start.
|
||||
window: usize,
|
||||
clock: Clock,
|
||||
deadline: Duration,
|
||||
/// The workers [`Loads::begin`] starts, and whether it has.
|
||||
workers: usize,
|
||||
begun: bool,
|
||||
/// The process's count of stuck loader threads ([`STUCK_THREADS`]), and its most.
|
||||
stuck_threads: &'static AtomicUsize,
|
||||
max_stuck: usize,
|
||||
/// Tests: no thread can be started from now on.
|
||||
#[cfg(test)]
|
||||
pub(crate) refuse_threads: bool,
|
||||
}
|
||||
|
||||
impl<T: Send + 'static> Loads<T> {
|
||||
/// Starts `jobs` on `min(available parallelism, MAX_WORKERS)` threads.
|
||||
pub fn start(jobs: Vec<Job<T>>) -> Self {
|
||||
let mut loads = Self::deferred(jobs);
|
||||
loads.begin();
|
||||
loads
|
||||
}
|
||||
|
||||
/// `jobs` to start on `min(available parallelism, MAX_WORKERS)` threads once [`Loads::begin`]
|
||||
/// is called (or something waits for them).
|
||||
pub fn deferred(jobs: Vec<Job<T>>) -> Self {
|
||||
Self::deferred_on(jobs, std::thread::available_parallelism().map_or(1, |n| n.get()).min(MAX_WORKERS))
|
||||
}
|
||||
|
||||
/// [`Loads::deferred`] on `workers` threads (at least one).
|
||||
pub(crate) fn deferred_on(jobs: Vec<Job<T>>, workers: usize) -> Self {
|
||||
let origin = Instant::now();
|
||||
Self::with(jobs, workers, LOAD_DEADLINE, Arc::new(move || origin.elapsed()))
|
||||
}
|
||||
|
||||
/// Starts the jobs, unless they started already.
|
||||
pub fn begin(&mut self) {
|
||||
if self.begun {
|
||||
return;
|
||||
}
|
||||
self.begun = true;
|
||||
if cfg!(target_arch = "wasm32") {
|
||||
// The web build has no threads: each job runs here, in order.
|
||||
let jobs: Vec<_> = self.pool.lock().queue.drain(..).collect();
|
||||
for (i, job) in jobs {
|
||||
// A job can't be stopped here, but one that took past its deadline fails as on
|
||||
// the desktop.
|
||||
let at = (self.clock)();
|
||||
let r = run_job(job);
|
||||
let took = (self.clock)().saturating_sub(at);
|
||||
self.record((i, r, took));
|
||||
}
|
||||
} else {
|
||||
for _ in 0..self.workers.min(self.outcomes.len()) {
|
||||
self.spawn_worker();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn start_with(jobs: Vec<Job<T>>, workers: usize, deadline: Duration, clock: Clock) -> Self {
|
||||
let mut loads = Self::with(jobs, workers, deadline, clock);
|
||||
loads.begin();
|
||||
loads
|
||||
}
|
||||
|
||||
fn with(jobs: Vec<Job<T>>, workers: usize, deadline: Duration, clock: Clock) -> Self {
|
||||
let n = jobs.len();
|
||||
let workers = workers.max(1);
|
||||
let window = workers * 2;
|
||||
let state = State {
|
||||
queue: jobs.into_iter().enumerate().collect(),
|
||||
started: vec![None; n],
|
||||
finished: vec![false; n],
|
||||
expired: vec![false; n],
|
||||
limit: window,
|
||||
workers: 0,
|
||||
stuck: 0,
|
||||
};
|
||||
let (send, results) = mpsc::channel();
|
||||
Loads {
|
||||
pool: Arc::new(Pool { state: Mutex::new(state), wake: Condvar::new() }),
|
||||
results: Mutex::new(results),
|
||||
send,
|
||||
outcomes: (0..n).map(|_| None).collect(),
|
||||
next: 0,
|
||||
released: 0,
|
||||
window,
|
||||
clock,
|
||||
deadline,
|
||||
workers,
|
||||
begun: false,
|
||||
stuck_threads: &STUCK_THREADS,
|
||||
max_stuck: MAX_STUCK_THREADS,
|
||||
#[cfg(test)]
|
||||
refuse_threads: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Starts a thread that takes jobs until none are left → whether it started.
|
||||
fn spawn_worker(&self) -> bool {
|
||||
#[cfg(test)]
|
||||
if self.refuse_threads {
|
||||
return false;
|
||||
}
|
||||
if self.stuck_threads.load(Ordering::SeqCst) >= self.max_stuck {
|
||||
log::warn!("not starting a thread to load plug-ins: {} loader threads are still running loads past their deadline", self.max_stuck);
|
||||
return false;
|
||||
}
|
||||
let pool = self.pool.clone();
|
||||
let send = self.send.clone();
|
||||
let clock = self.clock.clone();
|
||||
let target = self.workers;
|
||||
let stuck_threads = self.stuck_threads;
|
||||
self.pool.lock().workers += 1;
|
||||
let spawned = std::thread::Builder::new().name("plug-in loader".into()).spawn(move || {
|
||||
let alive = Alive(pool);
|
||||
loop {
|
||||
let (i, job, at) = {
|
||||
let mut s = alive.0.lock();
|
||||
loop {
|
||||
match s.queue.front() {
|
||||
None => return,
|
||||
Some((i, _)) if *i < s.limit => break,
|
||||
Some(_) => s = alive.0.wake.wait(s).unwrap_or_else(|e| e.into_inner()),
|
||||
}
|
||||
}
|
||||
let Some((i, job)) = s.queue.pop_front() else { return };
|
||||
let at = clock();
|
||||
s.started[i] = Some(at);
|
||||
(i, job, at)
|
||||
};
|
||||
let r = run_job(job);
|
||||
// A worker whose job passed its deadline and was replaced ends once the job
|
||||
// returns, unless the workers able to take jobs are fewer than started. The time
|
||||
// the job took is read while the job is marked finished, so a deadline check that
|
||||
// finds it unfinished counts a time that its own outcome reaches too.
|
||||
let (took, retire) = {
|
||||
let mut s = alive.0.lock();
|
||||
let took = clock().saturating_sub(at);
|
||||
s.finished[i] = true;
|
||||
let retire = s.expired[i] && {
|
||||
s.stuck -= 1;
|
||||
stuck_threads.fetch_sub(1, Ordering::SeqCst);
|
||||
s.workers - s.stuck > target
|
||||
};
|
||||
(took, retire)
|
||||
};
|
||||
let _ = send.send((i, r, took));
|
||||
if retire {
|
||||
return;
|
||||
}
|
||||
}
|
||||
});
|
||||
if let Err(e) = spawned {
|
||||
self.pool.lock().workers -= 1;
|
||||
log::warn!("can't start a thread to load plug-ins: {e}");
|
||||
return false;
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Takes the outcomes that came in and fails the jobs past their deadline → whether every job
|
||||
/// has its outcome.
|
||||
pub fn poll(&mut self) -> bool {
|
||||
loop {
|
||||
let next = self.results.lock().unwrap_or_else(|e| e.into_inner()).try_recv();
|
||||
let Ok(done) = next else { break };
|
||||
self.record(done);
|
||||
}
|
||||
self.expire();
|
||||
self.outcomes.iter().all(Option::is_some)
|
||||
}
|
||||
|
||||
/// The outcomes not taken yet that come in order from the last one taken, without waiting
|
||||
/// ([`Loads::poll`] first). The jobs after them start as the caller releases them
|
||||
/// ([`Loads::release`]).
|
||||
pub fn ready(&mut self) -> Vec<Result<T>> {
|
||||
self.poll();
|
||||
let mut out = Vec::new();
|
||||
while let Some(o) = self.outcomes.get_mut(self.next).and_then(Option::take) {
|
||||
out.push(o);
|
||||
self.next += 1;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The caller is done with `n` more of the outcomes it took (installed or dropped them): as
|
||||
/// many more jobs may start, so the outcomes held, here and by the caller, stay at most twice
|
||||
/// the workers' count.
|
||||
pub fn release(&mut self, n: usize) {
|
||||
let released = (self.released + n).min(self.next);
|
||||
if released != self.released {
|
||||
self.released = released;
|
||||
self.pool.lock().limit = released + self.window;
|
||||
self.pool.wake.notify_all();
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether every outcome has been taken.
|
||||
pub fn taken(&self) -> bool {
|
||||
self.next == self.outcomes.len()
|
||||
}
|
||||
|
||||
/// Whether the next outcome in order can be taken ([`Loads::ready`]).
|
||||
pub fn next_ready(&mut self) -> bool {
|
||||
self.poll();
|
||||
self.outcomes.get(self.next).is_some_and(Option::is_some)
|
||||
}
|
||||
|
||||
/// Waits until the next outcome in order can be taken, or every one has been. Jobs that have
|
||||
/// not been started are started first ([`Loads::begin`]).
|
||||
pub fn wait_next(&mut self) {
|
||||
self.begin();
|
||||
while !self.taken() && !self.next_ready() {
|
||||
let next = self.results.lock().unwrap_or_else(|e| e.into_inner()).recv_timeout(TICK);
|
||||
match next {
|
||||
Ok(done) => self.record(done),
|
||||
Err(RecvTimeoutError::Timeout | RecvTimeoutError::Disconnected) => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Waits for every outcome → those not taken yet, in the order of the jobs. The outcomes taken
|
||||
/// before ([`Loads::ready`]) count as released, so the jobs after them start.
|
||||
pub fn wait(mut self) -> Vec<Result<T>> {
|
||||
self.release(self.next - self.released);
|
||||
let mut out = Vec::new();
|
||||
while !self.taken() {
|
||||
self.wait_next();
|
||||
let ready = self.ready();
|
||||
self.release(ready.len());
|
||||
out.extend(ready);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn record(&mut self, (i, r, took): Done<T>) {
|
||||
let r = if took >= self.deadline { Err(self.too_long()) } else { r };
|
||||
// An outcome that comes after the job failed past its deadline is dropped.
|
||||
if let Some(slot @ None) = self.outcomes.get_mut(i) {
|
||||
*slot = Some(r);
|
||||
}
|
||||
}
|
||||
|
||||
fn too_long(&self) -> Error {
|
||||
let secs = self.deadline.as_secs();
|
||||
Error::Failed(format!("did not finish loading within {secs} s"))
|
||||
}
|
||||
|
||||
/// Fails the jobs still running past their deadline, starting a worker in place of each one's
|
||||
/// while the threads alive are fewer than twice the workers started. When no worker is left to
|
||||
/// take the jobs not started (none could be made, or every one is stuck), those fail too.
|
||||
fn expire(&mut self) {
|
||||
if !self.begun {
|
||||
return;
|
||||
}
|
||||
let mut expired = Vec::new();
|
||||
{
|
||||
let mut s = self.pool.lock();
|
||||
// Read while the workers can't mark a job finished ([`Loads::spawn_worker`]).
|
||||
let now = (self.clock)();
|
||||
for i in 0..self.outcomes.len() {
|
||||
let late = s.started[i].is_some_and(|at| now.saturating_sub(at) >= self.deadline);
|
||||
if late && !s.finished[i] && !s.expired[i] && self.outcomes[i].is_none() {
|
||||
s.expired[i] = true;
|
||||
s.stuck += 1;
|
||||
self.stuck_threads.fetch_add(1, Ordering::SeqCst);
|
||||
expired.push(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
for i in &expired {
|
||||
self.outcomes[*i] = Some(Err(self.too_long()));
|
||||
}
|
||||
for _ in &expired {
|
||||
let room = {
|
||||
let s = self.pool.lock();
|
||||
!s.queue.is_empty() && s.workers < 2 * self.workers
|
||||
};
|
||||
if !room || !self.spawn_worker() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
// The jobs not started are taken from the queue under the lock that finds no worker able to
|
||||
// take them, so a stuck worker that returns can't start one of them in between. Only those
|
||||
// fail: a job already started reports its own outcome.
|
||||
let stranded: Vec<usize> = {
|
||||
let mut s = self.pool.lock();
|
||||
if s.workers <= s.stuck { s.queue.drain(..).map(|(i, _)| i).collect() } else { Vec::new() }
|
||||
};
|
||||
for i in stranded {
|
||||
if let Some(o @ None) = self.outcomes.get_mut(i) {
|
||||
*o = Some(Err(Error::Failed(NO_THREAD.into())));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Send + 'static> Drop for Loads<T> {
|
||||
/// Jobs not started yet are dropped; the running ones are given until their deadline, so the
|
||||
/// launch marker is not left naming a plug-in that was still loading when the app quit.
|
||||
fn drop(&mut self) {
|
||||
self.pool.lock().queue.clear();
|
||||
self.pool.wake.notify_all();
|
||||
loop {
|
||||
let running = {
|
||||
let s = self.pool.lock();
|
||||
let now = (self.clock)();
|
||||
(0..self.outcomes.len())
|
||||
.any(|i| !s.finished[i] && !s.expired[i] && s.started[i].is_some_and(|at| now.saturating_sub(at) < self.deadline))
|
||||
};
|
||||
if !running {
|
||||
break;
|
||||
}
|
||||
let next = self.results.lock().unwrap_or_else(|e| e.into_inner()).recv_timeout(TICK);
|
||||
if let Ok(done) = next {
|
||||
self.record(done);
|
||||
}
|
||||
}
|
||||
// A job still running past its deadline leaves its thread stuck, and the thread counts
|
||||
// against the process's stuck threads until the job returns.
|
||||
let mut s = self.pool.lock();
|
||||
for i in 0..self.outcomes.len() {
|
||||
if s.started[i].is_some() && !s.finished[i] && !s.expired[i] {
|
||||
s.expired[i] = true;
|
||||
s.stuck += 1;
|
||||
self.stuck_threads.fetch_add(1, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs `job` inside a panic boundary, with the launch marker naming its item while it runs.
|
||||
fn run_job<T>(job: Job<T>) -> Result<T> {
|
||||
let token = job.item.as_ref().map(safe_mode::loading);
|
||||
let result = catch_unwind(AssertUnwindSafe(job.work));
|
||||
if let Some(t) = token {
|
||||
safe_mode::loaded(t);
|
||||
}
|
||||
match result {
|
||||
Ok(r) => r,
|
||||
Err(panic) => {
|
||||
let what = panic.downcast_ref::<&str>().map(|s| s.to_string()).or_else(|| panic.downcast_ref::<String>().cloned());
|
||||
Err(match what {
|
||||
Some(what) => Error::Failed(format!("panicked while loading: {what}")),
|
||||
None => Error::Failed("panicked while loading".into()),
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::atomic::AtomicU64;
|
||||
use std::sync::mpsc::sync_channel;
|
||||
|
||||
/// A clock the test moves.
|
||||
fn manual() -> (Arc<AtomicU64>, Clock) {
|
||||
let ms = Arc::new(AtomicU64::new(0));
|
||||
let read = ms.clone();
|
||||
(ms, Arc::new(move || Duration::from_millis(read.load(Ordering::SeqCst))))
|
||||
}
|
||||
|
||||
/// A job that says it started on `started`, then waits for `go` and returns `v`.
|
||||
fn held(v: u32, started: mpsc::SyncSender<u32>, go: Receiver<()>) -> Job<u32> {
|
||||
Job::new(None, move || {
|
||||
let _ = started.send(v);
|
||||
let _ = go.recv();
|
||||
Ok(v)
|
||||
})
|
||||
}
|
||||
|
||||
/// Polls `loads` until `done` says so, at most a million times.
|
||||
fn poll_until(loads: &mut Loads<u32>, mut done: impl FnMut(&mut Loads<u32>) -> bool) -> bool {
|
||||
(0..1_000_000).any(|_| {
|
||||
std::thread::yield_now();
|
||||
loads.poll();
|
||||
done(loads)
|
||||
})
|
||||
}
|
||||
|
||||
/// What `rx` receives, looked for 100 million times at most, so a worker that never sends fails the
|
||||
/// test instead of holding it. The test fails at once when every sender is gone.
|
||||
fn recv_soon<V>(rx: &Receiver<V>) -> V {
|
||||
for _ in 0..100_000_000 {
|
||||
match rx.try_recv() {
|
||||
Ok(v) => return v,
|
||||
Err(mpsc::TryRecvError::Disconnected) => panic!("every sender ended without sending"),
|
||||
Err(mpsc::TryRecvError::Empty) => std::thread::yield_now(),
|
||||
}
|
||||
}
|
||||
panic!("nothing was received");
|
||||
}
|
||||
|
||||
/// The outcomes come back in the order of the jobs when they finish in the reverse order.
|
||||
#[test]
|
||||
fn outcomes_keep_the_order_of_the_jobs() {
|
||||
let (started, starts) = sync_channel(3);
|
||||
let mut go = Vec::new();
|
||||
let mut jobs = Vec::new();
|
||||
for v in 0..3 {
|
||||
let (tx, rx) = mpsc::channel();
|
||||
go.push(tx);
|
||||
jobs.push(held(v, started.clone(), rx));
|
||||
}
|
||||
let (_, clock) = manual();
|
||||
let mut loads = Loads::start_with(jobs, 3, LOAD_DEADLINE, clock);
|
||||
// Bound after `loads`, so a failing assertion drops the senders first: the held jobs then
|
||||
// return, and dropping `loads` does not wait on them while the test clock stands still.
|
||||
let release = go;
|
||||
for _ in 0..3 {
|
||||
recv_soon(&starts);
|
||||
}
|
||||
// Each job is let go only once the one after it has finished.
|
||||
let mut finished = Vec::new();
|
||||
for v in (0..3).rev() {
|
||||
release[v].send(()).unwrap();
|
||||
let done = recv_soon(&loads.results.lock().unwrap());
|
||||
finished.push(done.0);
|
||||
loads.record(done);
|
||||
}
|
||||
assert_eq!(finished, vec![2, 1, 0], "they finished in reverse");
|
||||
assert_eq!(loads.wait().into_iter().map(|r| r.unwrap()).collect::<Vec<_>>(), vec![0, 1, 2]);
|
||||
}
|
||||
|
||||
/// A job that panics fails with the panic's message, and the others load.
|
||||
#[test]
|
||||
fn a_job_that_panics_fails_alone() {
|
||||
let jobs: Vec<Job<u32>> = vec![Job::new(None, || Ok(1)), Job::new(None, || panic!("broken module")), Job::new(None, || Ok(3))];
|
||||
let (_, clock) = manual();
|
||||
let out = Loads::start_with(jobs, 2, LOAD_DEADLINE, clock).wait();
|
||||
assert_eq!(out[0], Ok(1));
|
||||
assert!(matches!(&out[1], Err(Error::Failed(m)) if m.contains("panicked") && m.contains("broken module")), "{:?}", out[1]);
|
||||
assert_eq!(out[2], Ok(3));
|
||||
}
|
||||
|
||||
/// With one worker, a job that never finishes fails at its deadline, and the job after it
|
||||
/// still loads, on the worker that takes its place.
|
||||
#[test]
|
||||
fn a_job_that_hangs_fails_at_its_deadline_and_the_rest_load() {
|
||||
let (started, starts) = sync_channel(2);
|
||||
let (go, held_until) = mpsc::channel();
|
||||
let jobs = vec![held(0, started.clone(), held_until), Job::new(None, || Ok(1))];
|
||||
let (ms, clock) = manual();
|
||||
let mut loads = Loads::start_with(jobs, 1, Duration::from_secs(10), clock);
|
||||
assert_eq!(recv_soon(&starts), 0);
|
||||
assert!(!loads.poll(), "the first job is still running and the second waits for a worker");
|
||||
ms.store(10_000, Ordering::SeqCst);
|
||||
let done = poll_until(&mut loads, |l| l.outcomes.iter().all(Option::is_some));
|
||||
go.send(()).unwrap();
|
||||
assert!(done, "the job after the one that hangs never got its outcome");
|
||||
let out = loads.wait();
|
||||
assert!(matches!(&out[0], Err(Error::Failed(m)) if m.contains("did not finish")), "{:?}", out[0]);
|
||||
assert_eq!(out[1], Ok(1));
|
||||
}
|
||||
|
||||
/// Workers that replace stuck ones stop at twice the workers started: with one worker and two
|
||||
/// jobs that never finish, the third job fails instead of a third thread taking it.
|
||||
#[test]
|
||||
fn replacements_stop_at_twice_the_workers() {
|
||||
let (started, starts) = sync_channel(3);
|
||||
let (go0, held0) = mpsc::channel();
|
||||
let (go1, held1) = mpsc::channel();
|
||||
let jobs = vec![held(0, started.clone(), held0), held(1, started, held1), Job::new(None, || Ok(2))];
|
||||
let (ms, clock) = manual();
|
||||
let mut loads = Loads::start_with(jobs, 1, Duration::from_secs(10), clock);
|
||||
assert_eq!(recv_soon(&starts), 0);
|
||||
ms.store(10_000, Ordering::SeqCst);
|
||||
loads.poll();
|
||||
assert_eq!(recv_soon(&starts), 1, "a worker took the place of the stuck one");
|
||||
ms.store(20_000, Ordering::SeqCst);
|
||||
let done = loads.poll();
|
||||
go0.send(()).unwrap();
|
||||
go1.send(()).unwrap();
|
||||
assert!(done, "every job has its outcome");
|
||||
let out = loads.wait();
|
||||
assert!(matches!(&out[2], Err(Error::Failed(m)) if m.contains("no thread")), "{:?}", out[2]);
|
||||
}
|
||||
|
||||
/// A job that finished but took longer than the deadline fails, however soon it is looked at.
|
||||
#[test]
|
||||
fn a_job_that_took_too_long_fails_when_it_is_taken() {
|
||||
let (ms, clock) = manual();
|
||||
let moved = ms.clone();
|
||||
let jobs = vec![Job::new(None, move || {
|
||||
moved.store(10_000, Ordering::SeqCst);
|
||||
Ok(1u32)
|
||||
})];
|
||||
let out = Loads::start_with(jobs, 1, Duration::from_secs(10), clock).wait();
|
||||
assert!(matches!(&out[0], Err(Error::Failed(m)) if m.contains("did not finish")), "{:?}", out[0]);
|
||||
}
|
||||
|
||||
/// Only twice the workers' count of jobs past the last outcome taken start: the next one waits
|
||||
/// until an outcome is taken.
|
||||
#[test]
|
||||
fn jobs_past_the_window_wait_until_outcomes_are_taken() {
|
||||
let ran = Arc::new(AtomicUsize::new(0));
|
||||
let jobs: Vec<Job<u32>> = (0..5)
|
||||
.map(|v| {
|
||||
let ran = ran.clone();
|
||||
Job::new(None, move || {
|
||||
ran.fetch_add(1, Ordering::SeqCst);
|
||||
Ok(v)
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let (_, clock) = manual();
|
||||
let mut loads = Loads::start_with(jobs, 1, LOAD_DEADLINE, clock);
|
||||
assert!(poll_until(&mut loads, |l| l.outcomes.iter().filter(|o| o.is_some()).count() == 2), "the first two loaded");
|
||||
let early = ran.load(Ordering::SeqCst);
|
||||
assert_eq!(loads.ready(), vec![Ok(0), Ok(1)]);
|
||||
assert_eq!(early, 2, "the third job waited for the first outcomes to be taken");
|
||||
assert!(!poll_until(&mut loads, |l| l.outcomes.iter().filter(|o| o.is_some()).count() > 0), "taken but not released");
|
||||
assert_eq!(ran.load(Ordering::SeqCst), 2, "the third job waits until the caller is done with the first outcomes");
|
||||
loads.release(2);
|
||||
assert_eq!(loads.wait(), vec![Ok(2), Ok(3), Ok(4)]);
|
||||
}
|
||||
|
||||
/// `wait` after outcomes were taken and not released still gets the rest: it counts the outcomes
|
||||
/// taken as released, so the job past the window starts.
|
||||
#[test]
|
||||
fn wait_after_outcomes_were_taken_gets_the_jobs_past_the_window() {
|
||||
let jobs: Vec<Job<u32>> = (0..3).map(|v| Job::new(None, move || Ok(v))).collect();
|
||||
let (_, clock) = manual();
|
||||
let mut loads = Loads::start_with(jobs, 1, LOAD_DEADLINE, clock);
|
||||
assert!(poll_until(&mut loads, |l| l.outcomes.iter().filter(|o| o.is_some()).count() == 2), "the first two loaded");
|
||||
assert_eq!(loads.ready(), vec![Ok(0), Ok(1)]);
|
||||
let (done, rest) = mpsc::channel();
|
||||
std::thread::spawn(move || {
|
||||
let _ = done.send(loads.wait());
|
||||
});
|
||||
assert_eq!(recv_soon(&rest), vec![Ok(2)]);
|
||||
}
|
||||
|
||||
/// When no worker can take the jobs left, because the only one is stuck past its deadline and
|
||||
/// no thread takes its place, those jobs fail instead of being waited for.
|
||||
#[test]
|
||||
fn jobs_no_worker_can_take_fail() {
|
||||
let (started, starts) = sync_channel(1);
|
||||
let (go, held_until) = mpsc::channel();
|
||||
let jobs = vec![held(0, started, held_until), Job::new(None, || Ok(1))];
|
||||
let (ms, clock) = manual();
|
||||
let mut loads = Loads::start_with(jobs, 1, Duration::from_secs(10), clock);
|
||||
recv_soon(&starts);
|
||||
loads.refuse_threads = true;
|
||||
ms.store(10_000, Ordering::SeqCst);
|
||||
let done = loads.poll();
|
||||
go.send(()).unwrap();
|
||||
assert!(done, "every job has its outcome");
|
||||
let out = loads.wait();
|
||||
assert!(matches!(&out[0], Err(Error::Failed(m)) if m.contains("did not finish")), "{:?}", out[0]);
|
||||
assert!(matches!(&out[1], Err(Error::Failed(m)) if m.contains("no thread")), "{:?}", out[1]);
|
||||
}
|
||||
|
||||
/// A thread stuck past its deadline counts against later loads until its job returns: with
|
||||
/// room for one stuck thread in the process, the load after one that left a thread stuck
|
||||
/// starts no thread and fails its job, and once the stuck job returns a load runs again.
|
||||
#[test]
|
||||
fn stuck_threads_count_across_loads_until_they_end() {
|
||||
let stuck: &'static AtomicUsize = Box::leak(Box::new(AtomicUsize::new(0)));
|
||||
let make = |jobs: Vec<Job<u32>>, clock: Clock| {
|
||||
let mut loads = Loads::with(jobs, 1, Duration::from_secs(10), clock);
|
||||
loads.stuck_threads = stuck;
|
||||
loads.max_stuck = 1;
|
||||
loads.begin();
|
||||
loads
|
||||
};
|
||||
let (started, starts) = sync_channel(1);
|
||||
let (go, held_until) = mpsc::channel();
|
||||
let (ms, clock) = manual();
|
||||
let mut first = make(vec![held(0, started, held_until)], clock);
|
||||
recv_soon(&starts);
|
||||
ms.store(10_000, Ordering::SeqCst);
|
||||
assert!(first.poll(), "the stuck job failed at its deadline");
|
||||
drop(first);
|
||||
let (_, clock) = manual();
|
||||
let out = make(vec![Job::new(None, || Ok(1))], clock.clone()).wait();
|
||||
assert!(matches!(&out[0], Err(Error::Failed(m)) if m.contains("no thread")), "{:?}", out[0]);
|
||||
go.send(()).unwrap();
|
||||
assert!((0..1_000_000).any(|_| {
|
||||
std::thread::yield_now();
|
||||
stuck.load(Ordering::SeqCst) == 0
|
||||
}));
|
||||
assert_eq!(make(vec![Job::new(None, || Ok(2))], clock).wait(), vec![Ok(2)]);
|
||||
}
|
||||
|
||||
/// A load dropped while a job runs past its deadline, before anything looked at the job, still
|
||||
/// counts the job's thread as stuck until the job returns.
|
||||
#[test]
|
||||
fn a_dropped_load_counts_a_job_past_its_deadline_as_stuck() {
|
||||
let stuck: &'static AtomicUsize = Box::leak(Box::new(AtomicUsize::new(0)));
|
||||
let (started, starts) = sync_channel(1);
|
||||
let (go, held_until) = mpsc::channel();
|
||||
let (ms, clock) = manual();
|
||||
let mut loads = Loads::with(vec![held(0, started, held_until)], 1, Duration::from_secs(10), clock);
|
||||
loads.stuck_threads = stuck;
|
||||
loads.begin();
|
||||
recv_soon(&starts);
|
||||
ms.store(10_000, Ordering::SeqCst);
|
||||
drop(loads);
|
||||
assert_eq!(stuck.load(Ordering::SeqCst), 1, "the stuck thread counts");
|
||||
go.send(()).unwrap();
|
||||
assert!((0..1_000_000).any(|_| {
|
||||
std::thread::yield_now();
|
||||
stuck.load(Ordering::SeqCst) == 0
|
||||
}));
|
||||
}
|
||||
|
||||
/// The launch marker names an item while its job runs, and stops naming it when the job
|
||||
/// returns, a job that panicked included.
|
||||
#[test]
|
||||
fn a_job_names_its_item_until_it_returns_even_when_it_panics() {
|
||||
let _lock = crate::safe_mode::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let ok = Item::file("test-loader-ok.wasm");
|
||||
let bad = Item::file("test-loader-panics.wasm");
|
||||
let named = |item: &Item| crate::safe_mode::still_loading().iter().any(|i| i.same(item));
|
||||
let (ok2, bad2) = (ok.clone(), bad.clone());
|
||||
let bad_named = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
let seen = bad_named.clone();
|
||||
let jobs: Vec<Job<bool>> = vec![
|
||||
Job::new(Some(ok.clone()), move || Ok(named(&ok2))),
|
||||
Job::new(Some(bad.clone()), move || {
|
||||
seen.store(named(&bad2), Ordering::SeqCst);
|
||||
panic!("x")
|
||||
}),
|
||||
];
|
||||
let (_, clock) = manual();
|
||||
let outcomes = Loads::start_with(jobs, 2, LOAD_DEADLINE, clock).wait();
|
||||
assert!(matches!(outcomes.first(), Some(Ok(true))), "named while it runs");
|
||||
assert!(bad_named.load(Ordering::SeqCst), "named while it runs, before it panics");
|
||||
assert!(matches!(outcomes.get(1), Some(Err(Error::Failed(m))) if m.contains("panicked while loading")), "the panic is the job's failure");
|
||||
let running = crate::safe_mode::still_loading();
|
||||
assert!(!running.iter().any(|i| i.same(&bad) || i.same(&ok)), "{running:?}");
|
||||
}
|
||||
}
|
||||
+632
-47
@@ -68,7 +68,7 @@ pub fn approved(plugin: &Plugin) -> bool {
|
||||
/// Installs `plugin`, replacing one with the same id, when it is [`approved`]: a module that lists
|
||||
/// permissions no recorded grant gives this very module is refused ([`Error::NeedsApproval`]), and
|
||||
/// the plug-in installed under its id, the grants and the revision stay as they were.
|
||||
pub fn install(mut plugin: Plugin) -> Result<Arc<Plugin>> {
|
||||
pub fn install(plugin: Plugin) -> Result<Arc<Plugin>> {
|
||||
// The revision moves while the write lock is held, so a cache that reads the new revision and
|
||||
// then the plug-ins finds the new plug-in among them. The approval is checked while it is held
|
||||
// too.
|
||||
@@ -76,12 +76,112 @@ pub fn install(mut plugin: Plugin) -> Result<Arc<Plugin>> {
|
||||
if !approved(&plugin) {
|
||||
return Err(Error::NeedsApproval(crate::permissions::names(&plugin.manifest().permissions()).join(", ")));
|
||||
}
|
||||
Ok(insert(&mut plugins, plugin))
|
||||
}
|
||||
|
||||
/// Installs `plugin` in `plugins`, which the plug-ins' write lock holds, with the next revision.
|
||||
fn insert(plugins: &mut BTreeMap<String, Arc<Plugin>>, mut plugin: Plugin) -> Arc<Plugin> {
|
||||
plugin.set_serial(REVISION.fetch_add(1, Ordering::Relaxed) + 1);
|
||||
note_change(plugin.id(), plugin.serial());
|
||||
let p = Arc::new(plugin);
|
||||
plugins.insert(p.id().to_string(), p.clone());
|
||||
Ok(p)
|
||||
p
|
||||
}
|
||||
|
||||
/// [`install`] for a load that installs plug-ins one by one, recording `grant` first when it is
|
||||
/// given: while the plug-ins' write lock is held, a plug-in whose id was installed or removed
|
||||
/// elsewhere since the load started ([`LoadChanges::superseded`]) is not installed (`Ok(None)`), and
|
||||
/// neither the plug-ins nor the grants change. A grant that doesn't give this very module every
|
||||
/// permission it lists is refused ([`Error::NeedsApproval`]) and not recorded. Otherwise `attach`
|
||||
/// runs, then the grant is recorded and the plug-in installed. `attach` runs while the plug-ins are
|
||||
/// held, so it may call [`set_storage`] but no function that reads or changes the plug-ins or grants.
|
||||
pub fn install_for_load(plugin: Plugin, changes: &LoadChanges, grant: Option<GrantToken>, attach: impl FnOnce()) -> Result<Option<Arc<Plugin>>> {
|
||||
let mut plugins = PLUGINS.write().unwrap_or_else(|e| e.into_inner());
|
||||
if changes.superseded(plugin.id()) {
|
||||
return Ok(None);
|
||||
}
|
||||
let m = plugin.manifest();
|
||||
let approved = match &grant {
|
||||
Some(token) => !m.asks_permissions() || token.grant().covers(&m.id, plugin.hash(), &m.permissions()),
|
||||
None => approved(&plugin),
|
||||
};
|
||||
if !approved {
|
||||
return Err(Error::NeedsApproval(crate::permissions::names(&m.permissions()).join(", ")));
|
||||
}
|
||||
attach();
|
||||
if let Some(token) = grant {
|
||||
let g = token.grant().clone();
|
||||
GRANTS.write().unwrap_or_else(|e| e.into_inner()).insert(g.id.clone(), g);
|
||||
}
|
||||
Ok(Some(insert(&mut plugins, plugin)))
|
||||
}
|
||||
|
||||
/// Forgets the grant for `id` when the plug-in installed under it is the one that took the revision
|
||||
/// `serial` ([`Plugin::serial`]), checked while the plug-ins are held, so a plug-in installed in its
|
||||
/// place meanwhile keeps the grant recorded for it → whether a grant was forgotten.
|
||||
pub fn revoke_if_installed(id: &str, serial: u64) -> bool {
|
||||
// The same order as `install`, which reads the grants while it holds the plug-ins.
|
||||
let plugins = PLUGINS.read().unwrap_or_else(|e| e.into_inner());
|
||||
plugins.get(id).is_some_and(|p| p.serial() == serial) && GRANTS.write().unwrap_or_else(|e| e.into_inner()).remove(id).is_some()
|
||||
}
|
||||
|
||||
/// The [`revision`] of each id's last install or removal ([`changed_since`]).
|
||||
static CHANGED: RwLock<BTreeMap<String, u64>> = RwLock::new(BTreeMap::new());
|
||||
|
||||
/// Records that `id` was installed or removed at revision `rev`; called while the plug-ins' write
|
||||
/// lock is held.
|
||||
fn note_change(id: &str, rev: u64) {
|
||||
CHANGED.write().unwrap_or_else(|e| e.into_inner()).insert(id.to_string(), rev);
|
||||
}
|
||||
|
||||
/// Whether plug-in `id` was installed or removed after [`revision`] gave `rev`.
|
||||
pub fn changed_since(id: &str, rev: u64) -> bool {
|
||||
CHANGED.read().unwrap_or_else(|e| e.into_inner()).get(id).is_some_and(|&r| r > rev)
|
||||
}
|
||||
|
||||
/// What a load that installs plug-ins one by one has to check, so that a module it loaded before
|
||||
/// another session installed or removed the same id doesn't undo that change: the [`revision`] when
|
||||
/// the load listed its files, and the revision of each id it, or a load of the same session that
|
||||
/// ended before it, installed.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct LoadChanges {
|
||||
since: Option<u64>,
|
||||
own: BTreeMap<String, u64>,
|
||||
}
|
||||
|
||||
impl LoadChanges {
|
||||
/// Marks the load as started now, unless it started already. A load calls it as it lists its
|
||||
/// files, so a change made between the listing and the loads counts as one made elsewhere.
|
||||
pub fn start(&mut self) {
|
||||
self.since.get_or_insert_with(revision);
|
||||
}
|
||||
|
||||
/// Whether `id` was installed or removed since the load started, other than by the load itself
|
||||
/// or a load it [adopted](LoadChanges::adopt).
|
||||
pub fn superseded(&self, id: &str) -> bool {
|
||||
self.since.is_some_and(|since| changed_since(id, since.max(self.own.get(id).copied().unwrap_or(0))))
|
||||
}
|
||||
|
||||
/// Records that the load installed `plugin`.
|
||||
pub fn installed(&mut self, plugin: &Plugin) {
|
||||
self.own.insert(plugin.id().to_string(), plugin.serial());
|
||||
}
|
||||
|
||||
/// Counts what `earlier`, a load of the same session queued before this one that has ended,
|
||||
/// installed as this load's own: a module this load installs after it then replaces it, as it
|
||||
/// would have with the loads run one after the other.
|
||||
pub fn adopt(&mut self, earlier: &LoadChanges) {
|
||||
for (id, &serial) in &earlier.own {
|
||||
let own = self.own.entry(id.clone()).or_default();
|
||||
*own = (*own).max(serial);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What a load reports for a module it skips because the plug-in under its id was installed or
|
||||
/// removed elsewhere while it loaded ([`LoadChanges`]).
|
||||
pub const SUPERSEDED: &str = "skipped: the plug-in with its id was installed or removed elsewhere while it loaded";
|
||||
|
||||
/// What [`install_checked`] does to the grant recorded for the plug-in's id.
|
||||
pub enum GrantUpdate {
|
||||
/// Records this grant, replacing an earlier one for the id ([`grant`]).
|
||||
@@ -128,6 +228,7 @@ pub fn install_checked<E>(
|
||||
}
|
||||
}
|
||||
plugin.set_serial(REVISION.fetch_add(1, Ordering::Relaxed) + 1);
|
||||
note_change(&id, plugin.serial());
|
||||
let p = Arc::new(plugin);
|
||||
plugins.insert(id, p.clone());
|
||||
Ok(p)
|
||||
@@ -154,7 +255,7 @@ pub fn remove(id: &str) -> bool {
|
||||
let mut plugins = PLUGINS.write().unwrap_or_else(|e| e.into_inner());
|
||||
let gone = plugins.remove(id).is_some();
|
||||
if gone {
|
||||
REVISION.fetch_add(1, Ordering::Relaxed);
|
||||
note_change(id, REVISION.fetch_add(1, Ordering::Relaxed) + 1);
|
||||
}
|
||||
gone
|
||||
}
|
||||
@@ -267,14 +368,19 @@ pub struct FolderReport {
|
||||
/// found in a file, which is now disabled too ([`crate::safe_mode::disable_file_of`]). The app
|
||||
/// saves the list again.
|
||||
pub disabled_changed: bool,
|
||||
/// A file failed because no loader thread was left to load it ([`crate::loader::NO_THREAD`]):
|
||||
/// loading the folder again may load it.
|
||||
pub no_thread: bool,
|
||||
}
|
||||
|
||||
/// Installs every `*.wasm` directly in `dir` (not recursive), in file-name order, up to the first
|
||||
/// 1,000 by file name; the report counts the files left out ([`FolderReport::left_out`]). Anything
|
||||
/// that isn't a regular file, such as a named pipe, is reported and skipped without waiting on it
|
||||
/// ([`load_file`]). A bad module is reported and skipped, the others still load; so is a heavy one
|
||||
/// ([`crate::Budget::Heavy`]), which installs only once the user agrees, and one that lists
|
||||
/// permissions the user has not granted this very module ([`approved`]).
|
||||
/// ([`load_file`]). The modules load on worker threads ([`FolderLoad`]) and install in file-name
|
||||
/// order. A bad module is reported and skipped, the others still load; so is one whose load panics
|
||||
/// or doesn't finish in time ([`crate::loader`]), a heavy one ([`crate::Budget::Heavy`]), which
|
||||
/// installs only once the user agrees, and one that lists permissions the user has not granted this
|
||||
/// very module ([`approved`]).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn load_folder(dir: &std::path::Path) -> Result<FolderReport> {
|
||||
load_folder_where(dir, |_| Ok(()), approved)
|
||||
@@ -291,54 +397,255 @@ pub fn load_folder(dir: &std::path::Path) -> Result<FolderReport> {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn load_folder_where(
|
||||
dir: &std::path::Path,
|
||||
allow: impl Fn(&std::path::Path) -> std::result::Result<(), String>,
|
||||
allow: impl Fn(&std::path::Path) -> std::result::Result<(), String> + Send + Sync + 'static,
|
||||
approve: impl Fn(&Plugin) -> bool,
|
||||
) -> Result<FolderReport> {
|
||||
use crate::safe_mode::{self, Item};
|
||||
safe_mode::check()?;
|
||||
let (files, left_out) = folder_files(dir)?;
|
||||
let mut report = FolderReport { left_out, ..FolderReport::default() };
|
||||
for f in files {
|
||||
if let Err(why) = allow(&f) {
|
||||
report.failed.push((f.display().to_string(), why));
|
||||
continue;
|
||||
let mut load = FolderLoad::begin(dir, allow)?;
|
||||
while !load.done() {
|
||||
load.wait();
|
||||
load.install_ready(&approve);
|
||||
}
|
||||
Ok(load.finish())
|
||||
}
|
||||
|
||||
/// Tests: what runs before a folder module loads, given its path.
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
type FileHook = std::sync::Arc<dyn Fn(&std::path::Path) + Send + Sync>;
|
||||
|
||||
/// Tests: runs on the worker thread before the module at the path it is given loads.
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
pub(crate) static BEFORE_FOLDER_FILE: Mutex<Option<FileHook>> = Mutex::new(None);
|
||||
|
||||
/// A [`load_folder_where`] whose modules load on worker threads ([`crate::loader`]) while the
|
||||
/// caller goes on: [`FolderLoad::begin`] lists the folder and starts the loads,
|
||||
/// [`FolderLoad::install_ready`] installs what loaded so far in file-name order, whatever order the
|
||||
/// loads finish in, and [`FolderLoad::finish`] ends the load once [`FolderLoad::done`]. A module
|
||||
/// whose load panics or doesn't finish in time is reported as failed, and the others still install.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub struct FolderLoad {
|
||||
/// Each file in file-name order, with why it was refused before loading, if it was.
|
||||
files: Vec<(std::path::PathBuf, Option<String>)>,
|
||||
loads: crate::loader::Loads<Plugin>,
|
||||
/// Outcomes taken from `loads` and not installed yet, in order.
|
||||
loaded: std::collections::VecDeque<Result<Plugin>>,
|
||||
/// The next file to install or report.
|
||||
next: usize,
|
||||
report: FolderReport,
|
||||
/// Installs and removals elsewhere since the folder was listed, which a module loaded before
|
||||
/// them doesn't undo.
|
||||
changes: LoadChanges,
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
impl FolderLoad {
|
||||
/// Lists `dir` and starts loading the files `allow` accepts and the user didn't disable. Each
|
||||
/// file is checked with `allow` again on its worker thread, right before it is read. In Safe
|
||||
/// Mode nothing loads ([`Error::SafeMode`]); an error listing the folder is returned.
|
||||
pub fn begin(
|
||||
dir: &std::path::Path,
|
||||
allow: impl Fn(&std::path::Path) -> std::result::Result<(), String> + Send + Sync + 'static,
|
||||
) -> Result<FolderLoad> {
|
||||
let mut load = Self::list_on(dir, allow, None)?;
|
||||
load.start();
|
||||
Ok(load)
|
||||
}
|
||||
|
||||
/// [`FolderLoad::begin`] without starting the loads: [`FolderLoad::start`] starts them, and
|
||||
/// so does waiting for them.
|
||||
pub fn list(
|
||||
dir: &std::path::Path,
|
||||
allow: impl Fn(&std::path::Path) -> std::result::Result<(), String> + Send + Sync + 'static,
|
||||
) -> Result<FolderLoad> {
|
||||
Self::list_on(dir, allow, None)
|
||||
}
|
||||
|
||||
/// Starts the loads, unless they started already.
|
||||
pub fn start(&mut self) {
|
||||
self.changes.start();
|
||||
self.loads.begin();
|
||||
}
|
||||
|
||||
/// [`FolderLoad::list`] for `workers` threads (`None`: as many as [`crate::loader::Loads::start`]
|
||||
/// starts).
|
||||
fn list_on(
|
||||
dir: &std::path::Path,
|
||||
allow: impl Fn(&std::path::Path) -> std::result::Result<(), String> + Send + Sync + 'static,
|
||||
workers: Option<usize>,
|
||||
) -> Result<FolderLoad> {
|
||||
use crate::loader::{Job, Loads};
|
||||
use crate::safe_mode::{self, Item};
|
||||
safe_mode::check()?;
|
||||
// A change made elsewhere once the folder starts being listed is one the load doesn't undo.
|
||||
let mut changes = LoadChanges::default();
|
||||
changes.start();
|
||||
let (found, left_out) = folder_files(dir)?;
|
||||
let allow = std::sync::Arc::new(allow);
|
||||
let mut files = Vec::with_capacity(found.len());
|
||||
let mut jobs = Vec::new();
|
||||
for f in found {
|
||||
let item = Item::file(f.display().to_string());
|
||||
let refused = match allow(&f) {
|
||||
Err(why) => Some(why),
|
||||
Ok(()) if safe_mode::skipped(&item) => Some(DISABLED.to_string()),
|
||||
Ok(()) => None,
|
||||
};
|
||||
if refused.is_none() {
|
||||
let (path, allow) = (f.clone(), allow.clone());
|
||||
jobs.push(Job::new(Some(item), move || {
|
||||
allow(&path).map_err(Error::Io)?;
|
||||
#[cfg(test)]
|
||||
{
|
||||
let hook = BEFORE_FOLDER_FILE.lock().unwrap_or_else(|e| e.into_inner()).clone();
|
||||
if let Some(hook) = hook {
|
||||
hook(&path);
|
||||
}
|
||||
}
|
||||
load_file(&path, Limits::default())
|
||||
}));
|
||||
}
|
||||
files.push((f, refused));
|
||||
}
|
||||
let item = Item::file(f.display().to_string());
|
||||
if safe_mode::skipped(&item) {
|
||||
report.failed.push((f.display().to_string(), DISABLED.into()));
|
||||
continue;
|
||||
}
|
||||
let token = safe_mode::loading(&item);
|
||||
let loaded = load_file(&f, Limits::default());
|
||||
safe_mode::loaded(token);
|
||||
match loaded {
|
||||
Ok(p) if safe_mode::skipped(&Item::of(&p)) => {
|
||||
report.disabled_changed |= safe_mode::disable_file_of(&Item::of(&p));
|
||||
report.failed.push((f.display().to_string(), DISABLED.into()));
|
||||
}
|
||||
// A heavy plug-in installs once the user agrees, which loading a folder doesn't ask.
|
||||
Ok(p) if p.manifest().budget == crate::Budget::Heavy => {
|
||||
report.failed.push((f.display().to_string(), "asks for a heavy budget, which the user allows when installing it on its own".into()));
|
||||
}
|
||||
Ok(p) if p.manifest().asks_permissions() && !approve(&p) => {
|
||||
let asked = crate::permissions::names(&p.manifest().permissions()).join(", ");
|
||||
report.failed.push((f.display().to_string(), Error::NeedsApproval(asked).to_string()));
|
||||
}
|
||||
// `approve` only narrows what installs: `install` still refuses a module that no
|
||||
// recorded grant covers.
|
||||
Ok(p) => match install(p) {
|
||||
Ok(p) => report.loaded.push(p.id().to_string()),
|
||||
Err(e) => report.failed.push((f.display().to_string(), e.to_string())),
|
||||
},
|
||||
Err(e) => report.failed.push((f.display().to_string(), e.to_string())),
|
||||
let loads = match workers {
|
||||
Some(n) => Loads::deferred_on(jobs, n),
|
||||
None => Loads::deferred(jobs),
|
||||
};
|
||||
let report = FolderReport { left_out, ..FolderReport::default() };
|
||||
Ok(FolderLoad { files, loads, loaded: Default::default(), next: 0, report, changes })
|
||||
}
|
||||
|
||||
/// The installs and removals the load checks its modules against ([`LoadChanges`]).
|
||||
pub fn changes(&self) -> &LoadChanges {
|
||||
&self.changes
|
||||
}
|
||||
|
||||
/// [`FolderLoad::changes`], to [adopt](LoadChanges::adopt) an earlier load's.
|
||||
pub fn changes_mut(&mut self) -> &mut LoadChanges {
|
||||
&mut self.changes
|
||||
}
|
||||
|
||||
/// Whether every file has been installed or reported.
|
||||
pub fn done(&self) -> bool {
|
||||
self.next == self.files.len()
|
||||
}
|
||||
|
||||
/// Whether [`FolderLoad::install_ready`] has something to install or report now, without
|
||||
/// waiting (or nothing is left).
|
||||
pub fn ready(&mut self) -> bool {
|
||||
match self.files.get(self.next) {
|
||||
None => true,
|
||||
Some((_, Some(_))) => true,
|
||||
Some((_, None)) => !self.loaded.is_empty() || self.loads.next_ready(),
|
||||
}
|
||||
}
|
||||
for id in &report.loaded {
|
||||
if get(id).is_some_and(|p| !p.manifest().asks_permissions()) {
|
||||
revoke(id);
|
||||
|
||||
/// Waits until [`FolderLoad::ready`], starting the loads first ([`FolderLoad::start`]).
|
||||
pub fn wait(&mut self) {
|
||||
self.start();
|
||||
while !self.ready() && !self.loads.taken() {
|
||||
self.loads.wait_next();
|
||||
}
|
||||
}
|
||||
Ok(report)
|
||||
|
||||
/// Installs the plug-ins that loaded, and reports the files that failed, in file-name order up
|
||||
/// to the first file still loading, as [`load_folder_where`] does: those that list permissions
|
||||
/// only when `approve` accepts them and a recorded grant covers them → the ids it installed.
|
||||
pub fn install_ready(&mut self, approve: impl Fn(&Plugin) -> bool) -> Vec<String> {
|
||||
use crate::safe_mode::{self, Item};
|
||||
self.loaded.extend(self.loads.ready());
|
||||
let mut installed = Vec::new();
|
||||
while let Some((f, refused)) = self.files.get(self.next) {
|
||||
let name = f.display().to_string();
|
||||
if let Some(why) = refused {
|
||||
self.report.failed.push((name, why.clone()));
|
||||
self.next += 1;
|
||||
continue;
|
||||
}
|
||||
let Some(loaded) = self.loaded.pop_front() else { break };
|
||||
self.loads.release(1);
|
||||
self.next += 1;
|
||||
let report = &mut self.report;
|
||||
match loaded {
|
||||
Ok(p) if safe_mode::skipped(&Item::of(&p)) => {
|
||||
report.disabled_changed |= safe_mode::disable_file_of(&Item::of(&p));
|
||||
report.failed.push((name, DISABLED.into()));
|
||||
}
|
||||
// A heavy plug-in installs once the user agrees, which loading a folder doesn't ask.
|
||||
Ok(p) if p.manifest().budget == crate::Budget::Heavy => {
|
||||
report.failed.push((name, "asks for a heavy budget, which the user allows when installing it on its own".into()));
|
||||
}
|
||||
// The very module installed elsewhere meanwhile (another session loading the same
|
||||
// folder) counts as loaded. `approve` may record a grant, so it is asked only for
|
||||
// that module: a module another session replaced or removed changes no grant.
|
||||
Ok(p) if self.changes.superseded(p.id()) => match get(p.id()) {
|
||||
Some(q) if q.hash() == p.hash() && (!p.manifest().asks_permissions() || approve(&p)) => report.loaded.push(p.id().to_string()),
|
||||
Some(q) if q.hash() == p.hash() => {
|
||||
let asked = crate::permissions::names(&p.manifest().permissions()).join(", ");
|
||||
report.failed.push((name, Error::NeedsApproval(asked).to_string()));
|
||||
}
|
||||
_ => report.failed.push((name, SUPERSEDED.into())),
|
||||
},
|
||||
Ok(p) if p.manifest().asks_permissions() && !approve(&p) => {
|
||||
let asked = crate::permissions::names(&p.manifest().permissions()).join(", ");
|
||||
report.failed.push((name, Error::NeedsApproval(asked).to_string()));
|
||||
}
|
||||
// `approve` only narrows what installs: `install_for_load` still refuses a module that
|
||||
// no recorded grant covers, and one whose id changed elsewhere since the check above.
|
||||
Ok(p) => match install_for_load(p, &self.changes, None, || {}) {
|
||||
Ok(Some(p)) => {
|
||||
self.changes.installed(&p);
|
||||
report.loaded.push(p.id().to_string());
|
||||
installed.push(p.id().to_string());
|
||||
}
|
||||
Ok(None) => report.failed.push((name, SUPERSEDED.into())),
|
||||
Err(e) => report.failed.push((name, e.to_string())),
|
||||
},
|
||||
Err(e) => {
|
||||
report.no_thread |= matches!(&e, Error::Failed(m) if m == crate::loader::NO_THREAD);
|
||||
report.failed.push((name, e.to_string()));
|
||||
}
|
||||
}
|
||||
}
|
||||
installed
|
||||
}
|
||||
|
||||
/// Whether [`FolderLoad::install_ready`] turned off the file of a disabled plug-in it matched by
|
||||
/// id ([`crate::safe_mode::disable_file_of`]) since the list of disabled plug-ins was last saved
|
||||
/// ([`FolderLoad::disabled_saved`]).
|
||||
pub fn disabled_changed(&self) -> bool {
|
||||
self.report.disabled_changed
|
||||
}
|
||||
|
||||
/// The list of disabled plug-ins was saved: [`FolderLoad::disabled_changed`] is false until the
|
||||
/// load changes it again.
|
||||
pub fn disabled_saved(&mut self) {
|
||||
self.report.disabled_changed = false;
|
||||
}
|
||||
|
||||
/// Drops the loads not taken yet: jobs not started don't start, and running ones are given
|
||||
/// until their deadline ([`crate::loader::Loads`]). What was installed stays, and the load is
|
||||
/// [`FolderLoad::done`].
|
||||
pub fn cancel(&mut self) {
|
||||
self.loads = crate::loader::Loads::deferred(Vec::new());
|
||||
self.loaded.clear();
|
||||
self.next = self.files.len();
|
||||
}
|
||||
|
||||
/// Ends the load → its report. When the module the load installed under an id lists no
|
||||
/// permissions and is still installed, the process's grant for that id is forgotten. Files not
|
||||
/// installed or reported yet ([`FolderLoad::done`] false) are left out.
|
||||
pub fn finish(self) -> FolderReport {
|
||||
let FolderLoad { report, changes, .. } = self;
|
||||
for id in &report.loaded {
|
||||
// The serial is checked again while the grant is removed, so a module installed in its
|
||||
// place meanwhile keeps its grant.
|
||||
if let Some(&serial) = changes.own.get(id)
|
||||
&& get(id).is_some_and(|p| p.serial() == serial && !p.manifest().asks_permissions())
|
||||
{
|
||||
revoke_if_installed(id, serial);
|
||||
}
|
||||
}
|
||||
report
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -618,4 +925,282 @@ mod tests {
|
||||
let first: Vec<String> = (0..MAX_FOLDER_FILES).map(|i| dir.join(format!("{i:05}.wasm")).display().to_string()).collect();
|
||||
assert_eq!(tried, first, "the first files by name, in that order");
|
||||
}
|
||||
|
||||
/// Clears [`BEFORE_FOLDER_FILE`] when a test ends, failed or not.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
struct Hooked;
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
impl Hooked {
|
||||
fn set(hook: impl Fn(&std::path::Path) + Send + Sync + 'static) -> Hooked {
|
||||
*BEFORE_FOLDER_FILE.lock().unwrap_or_else(|e| e.into_inner()) = Some(std::sync::Arc::new(hook));
|
||||
Hooked
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
impl Drop for Hooked {
|
||||
fn drop(&mut self) {
|
||||
*BEFORE_FOLDER_FILE.lock().unwrap_or_else(|e| e.into_inner()) = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// The plug-ins of a folder install in file-name order, and take their revisions in that order,
|
||||
/// when the first file's load finishes after the others.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn a_folder_installs_in_file_name_order_whatever_order_the_loads_finish_in() {
|
||||
let _lock = crate::safe_mode::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
crate::safe_mode::set_active(None);
|
||||
let dir = test_dir("order");
|
||||
let ids = ["test.registry.order.a", "test.registry.order.b", "test.registry.order.c"];
|
||||
for (n, id) in ["a", "b", "c"].iter().zip(ids) {
|
||||
std::fs::write(dir.join(format!("{n}.wasm")), module(id, None, 11)).unwrap();
|
||||
}
|
||||
let first = dir.join("a.wasm");
|
||||
let (go, a_waits) = std::sync::mpsc::channel::<()>();
|
||||
let a_waits = Mutex::new(a_waits);
|
||||
let seen = std::sync::Arc::new(Mutex::new(Vec::new()));
|
||||
let held = first.clone();
|
||||
let saw = seen.clone();
|
||||
let _hook = Hooked::set(move |p| {
|
||||
saw.lock().unwrap_or_else(|e| e.into_inner()).push(p.to_path_buf());
|
||||
if p == held {
|
||||
let _ = a_waits.lock().unwrap_or_else(|e| e.into_inner()).recv();
|
||||
}
|
||||
});
|
||||
// Two workers, so the other files load while the first one waits.
|
||||
let loading = std::thread::spawn({
|
||||
let dir = dir.clone();
|
||||
move || {
|
||||
let mut load = FolderLoad::list_on(&dir, |_| Ok(()), Some(2))?;
|
||||
load.start();
|
||||
while !load.done() {
|
||||
load.wait();
|
||||
load.install_ready(|_| false);
|
||||
}
|
||||
Ok::<_, Error>(load.finish())
|
||||
}
|
||||
});
|
||||
// The other two files load on the other worker while the first one waits: their loads have
|
||||
// started (the hook saw them) and ended (the launch marker list no longer has them).
|
||||
let all = ["a", "b", "c"].map(|n| dir.join(format!("{n}.wasm")));
|
||||
let finished = |p: &std::path::Path| {
|
||||
let item = crate::safe_mode::Item::file(p.display().to_string());
|
||||
seen.lock().unwrap_or_else(|e| e.into_inner()).iter().any(|s| s == p) && !crate::safe_mode::still_loading().iter().any(|i| i.same(&item))
|
||||
};
|
||||
// Looked at a bounded number of times, and given up when the load ends first.
|
||||
let reached = (0..10_000_000).any(|_| {
|
||||
std::thread::yield_now();
|
||||
loading.is_finished() || (seen.lock().unwrap_or_else(|e| e.into_inner()).contains(&first) && finished(&all[1]) && finished(&all[2]))
|
||||
});
|
||||
assert!(reached && !loading.is_finished(), "the load ended, or the other files didn't load, while the first one waited");
|
||||
assert!(ids.iter().all(|id| get(id).is_none()), "nothing installs before the first file has loaded");
|
||||
go.send(()).unwrap();
|
||||
let r = loading.join().unwrap();
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
let r = r.unwrap();
|
||||
assert_eq!(r.loaded, ids.to_vec(), "{r:?}");
|
||||
let serials: Vec<u64> = ids.iter().map(|id| get(id).unwrap().serial()).collect();
|
||||
assert!(serials.windows(2).all(|w| w[0] < w[1]), "installed in file-name order: {serials:?}");
|
||||
for id in ids {
|
||||
assert!(remove(id));
|
||||
}
|
||||
}
|
||||
|
||||
/// A folder module that loaded before something else installed or removed the same id, while
|
||||
/// an earlier file still loaded, doesn't undo that change: it is reported as skipped, and the
|
||||
/// plug-in installed meanwhile stays, as does the removal.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn a_folder_module_doesnt_undo_a_change_made_while_it_waited() {
|
||||
let _lock = crate::safe_mode::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
crate::safe_mode::set_active(None);
|
||||
let dir = test_dir("superseded");
|
||||
let ids = ["test.registry.superseded.a", "test.registry.superseded.b", "test.registry.superseded.c"];
|
||||
// b's file asks for a permission: asking whether it may install could record a grant.
|
||||
for (n, id) in ["a", "b", "c"].iter().zip(ids) {
|
||||
let asks = (*n == "b").then_some(r#"["doc.read"]"#);
|
||||
std::fs::write(dir.join(format!("{n}.wasm")), module(id, asks, 13)).unwrap();
|
||||
}
|
||||
install_bytes(&module(ids[2], None, 14)).unwrap();
|
||||
let first = dir.join("a.wasm");
|
||||
let (go, a_waits) = std::sync::mpsc::channel::<()>();
|
||||
let a_waits = Mutex::new(a_waits);
|
||||
let (reached, a_reached) = std::sync::mpsc::channel::<()>();
|
||||
let held = first.clone();
|
||||
let _hook = Hooked::set(move |p| {
|
||||
if p == held {
|
||||
let _ = reached.send(());
|
||||
let _ = a_waits.lock().unwrap_or_else(|e| e.into_inner()).recv();
|
||||
}
|
||||
});
|
||||
let mut load = FolderLoad::list_on(&dir, |_| Ok(()), Some(2)).unwrap();
|
||||
load.start();
|
||||
a_reached.recv().unwrap();
|
||||
// Elsewhere, while the first file still loads: `b` is installed and `c` removed.
|
||||
let theirs = install_bytes(&module(ids[1], None, 15)).unwrap().serial();
|
||||
assert!(remove(ids[2]));
|
||||
go.send(()).unwrap();
|
||||
let asked = Mutex::new(Vec::new());
|
||||
while !load.done() {
|
||||
load.wait();
|
||||
load.install_ready(|p| {
|
||||
asked.lock().unwrap_or_else(|e| e.into_inner()).push(p.id().to_string());
|
||||
false
|
||||
});
|
||||
}
|
||||
let r = load.finish();
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
assert_eq!(r.loaded, vec![ids[0]], "{r:?}");
|
||||
assert!(r.failed.iter().all(|(_, why)| why == SUPERSEDED) && r.failed.len() == 2, "{r:?}");
|
||||
assert!(asked.lock().unwrap_or_else(|e| e.into_inner()).is_empty(), "no grant is asked for a superseded module");
|
||||
assert_eq!(get(ids[1]).map(|p| p.serial()), Some(theirs), "the plug-in installed meanwhile stays");
|
||||
assert!(get(ids[2]).is_none(), "the removal stays");
|
||||
for id in &ids[..2] {
|
||||
assert!(remove(id));
|
||||
}
|
||||
}
|
||||
|
||||
/// A plug-in installed elsewhere after the folder was listed and before its loads started
|
||||
/// stays: the folder's module with its id is skipped. One a load of the same session installed
|
||||
/// before it ([`LoadChanges::adopt`]) is replaced.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn a_folder_module_doesnt_undo_a_change_made_before_its_loads_started() {
|
||||
let _lock = crate::safe_mode::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
crate::safe_mode::set_active(None);
|
||||
let dir = test_dir("superseded-listed");
|
||||
let ids = ["test.registry.listed.a", "test.registry.listed.b"];
|
||||
for (n, id) in ["a", "b"].iter().zip(ids) {
|
||||
std::fs::write(dir.join(format!("{n}.wasm")), module(id, None, 13)).unwrap();
|
||||
}
|
||||
let mut load = FolderLoad::list_on(&dir, |_| Ok(()), Some(2)).unwrap();
|
||||
// Before the loads start: another session installs `a`, and an earlier load of this
|
||||
// session installs `b`.
|
||||
let theirs = install_bytes(&module(ids[0], None, 14)).unwrap().serial();
|
||||
let mut earlier = LoadChanges::default();
|
||||
earlier.start();
|
||||
earlier.installed(&install_bytes(&module(ids[1], None, 15)).unwrap());
|
||||
load.changes_mut().adopt(&earlier);
|
||||
load.start();
|
||||
while !load.done() {
|
||||
load.wait();
|
||||
load.install_ready(|_| false);
|
||||
}
|
||||
let r = load.finish();
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
assert_eq!(r.loaded, vec![ids[1]], "{r:?}");
|
||||
assert!(r.failed.iter().all(|(_, why)| why == SUPERSEDED) && r.failed.len() == 1, "{r:?}");
|
||||
assert_eq!(get(ids[0]).map(|p| p.serial()), Some(theirs), "the plug-in installed elsewhere stays");
|
||||
for id in ids {
|
||||
assert!(remove(id));
|
||||
}
|
||||
}
|
||||
|
||||
/// A folder whose second module panics while it loads reports it as failed and installs the
|
||||
/// others.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn a_folder_module_that_panics_while_loading_fails_alone() {
|
||||
let _lock = crate::safe_mode::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
crate::safe_mode::set_active(None);
|
||||
let dir = test_dir("panics");
|
||||
let ids = ["test.registry.panics.a", "test.registry.panics.b", "test.registry.panics.c"];
|
||||
for (n, id) in ["a", "b", "c"].iter().zip(ids) {
|
||||
std::fs::write(dir.join(format!("{n}.wasm")), module(id, None, 12)).unwrap();
|
||||
}
|
||||
let broken = dir.join("b.wasm");
|
||||
let hooked = broken.clone();
|
||||
let hook = Hooked::set(move |p| {
|
||||
if p == hooked {
|
||||
panic!("a defect while loading");
|
||||
}
|
||||
});
|
||||
let r = load_folder_where(&dir, |_| Ok(()), |_| false);
|
||||
drop(hook);
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
let item = crate::safe_mode::Item::file(broken.display().to_string());
|
||||
let marked = crate::safe_mode::still_loading().iter().any(|i| i.same(&item));
|
||||
let r = r.unwrap();
|
||||
assert_eq!(r.loaded, vec![ids[0], ids[2]], "{r:?}");
|
||||
assert_eq!(r.failed.len(), 1, "{r:?}");
|
||||
assert!(r.failed[0].0 == broken.display().to_string() && r.failed[0].1.contains("panicked"), "{r:?}");
|
||||
assert!(!marked, "the launch marker stops naming the module whose load failed");
|
||||
for id in [ids[0], ids[2]] {
|
||||
assert!(remove(id));
|
||||
}
|
||||
}
|
||||
|
||||
/// A folder module isn't installed over a plug-in installed elsewhere with its id while the load
|
||||
/// asked whether it may install: that plug-in stays, and the module is reported as skipped.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn a_folder_module_doesnt_replace_one_installed_while_it_was_approved() {
|
||||
use crate::permissions::Permission::DocRead;
|
||||
let _lock = crate::safe_mode::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
crate::safe_mode::set_active(None);
|
||||
let dir = test_dir("approving");
|
||||
let id = "test.registry.approving";
|
||||
let asking = module(id, Some(r#"["doc.read"]"#), 17);
|
||||
std::fs::write(dir.join("a.wasm"), &asking).unwrap();
|
||||
grant(GrantToken::after_engine_approval(grant_for(id, &asking, vec![DocRead])));
|
||||
let theirs = std::cell::Cell::new(None);
|
||||
let r = load_folder_where(
|
||||
&dir,
|
||||
|_| Ok(()),
|
||||
|_| {
|
||||
theirs.set(Some(install_bytes(&module(id, None, 18)).unwrap().serial()));
|
||||
true
|
||||
},
|
||||
);
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
let now = get(id).map(|p| p.serial());
|
||||
assert!(remove(id));
|
||||
revoke(id);
|
||||
let r = r.unwrap();
|
||||
assert_eq!(now, theirs.get(), "the plug-in installed meanwhile was replaced: {r:?}");
|
||||
assert!(r.loaded.is_empty() && r.failed.len() == 1 && r.failed[0].1 == SUPERSEDED, "{r:?}");
|
||||
}
|
||||
|
||||
/// A grant is forgotten only while the plug-in that took the given revision is installed under
|
||||
/// its id: a plug-in installed in its place keeps the grant recorded for it.
|
||||
#[test]
|
||||
fn a_grant_is_revoked_only_for_the_plugin_still_installed() {
|
||||
use crate::permissions::Permission::DocRead;
|
||||
let _lock = crate::safe_mode::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let id = "test.registry.revokeinstalled";
|
||||
let first = install_bytes(&module(id, None, 19)).unwrap().serial();
|
||||
let asking = module(id, Some(r#"["doc.read"]"#), 20);
|
||||
grant(GrantToken::after_engine_approval(grant_for(id, &asking, vec![DocRead])));
|
||||
let second = install_bytes(&asking).unwrap().serial();
|
||||
assert!(!revoke_if_installed(id, first), "the grant of the plug-in installed in its place was forgotten");
|
||||
assert!(granted(id).is_some());
|
||||
assert!(revoke_if_installed(id, second));
|
||||
assert!(granted(id).is_none() && remove(id));
|
||||
}
|
||||
|
||||
/// A folder file that no loader thread was left to load fails with that reason, and the report
|
||||
/// says a file found no thread ([`FolderReport::no_thread`]).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn a_folder_file_no_thread_was_left_to_load_is_reported() {
|
||||
let _lock = crate::safe_mode::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
crate::safe_mode::set_active(None);
|
||||
let dir = test_dir("nothread");
|
||||
let id = "test.registry.nothread";
|
||||
std::fs::write(dir.join("a.wasm"), module(id, None, 16)).unwrap();
|
||||
let mut load = FolderLoad::list_on(&dir, |_| Ok(()), Some(1)).unwrap();
|
||||
load.loads.refuse_threads = true;
|
||||
load.start();
|
||||
while !load.done() {
|
||||
load.wait();
|
||||
load.install_ready(|_| false);
|
||||
}
|
||||
let r = load.finish();
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
assert!(get(id).is_none(), "{r:?}");
|
||||
assert_eq!(r.failed.len(), 1, "{r:?}");
|
||||
assert!(r.no_thread && r.failed[0].1.contains(crate::loader::NO_THREAD), "{r:?}");
|
||||
}
|
||||
}
|
||||
+177
-84
@@ -14,16 +14,16 @@
|
||||
//!
|
||||
//! **Launch marker** (native builds): a small file in a folder the app picks, written before the
|
||||
//! stored plug-ins load, updated before and after each module load and each live effect's first
|
||||
//! evaluation (and each evaluation that starts while one of those is running) to name the oldest
|
||||
//! item still loading (several threads can load at once), and removed
|
||||
//! when the app quits ([`begin_launch`], [`loading`], [`loaded`], [`end_launch`]). A launch that
|
||||
//! ends while an item is still loading (a panic the app caught while a plug-in loaded) keeps its
|
||||
//! marker naming that item. A marker left behind by a
|
||||
//! launch that is no longer running names the item that was loading when it stopped, which may or
|
||||
//! may not be what stopped it. Until the user
|
||||
//! chooses what to do about that item ([`forget_previous`]), the next launch's marker names it too
|
||||
//! and stays when that launch quits, so a launch that asks nothing (`--safe-mode`) or one closed in
|
||||
//! Safe Mode leaves the choice to the launch after it. Each launch has
|
||||
//! evaluation (and each evaluation that starts while one of those is running) to name every item
|
||||
//! still loading, oldest first (several threads can load at once; at most [`MAX_MARKER_ITEMS`]),
|
||||
//! and removed when the app quits ([`begin_launch`], [`loading`], [`loaded`], [`end_launch`]). A
|
||||
//! launch that ends while an item is still loading (a panic the app caught outside a load job
|
||||
//! while a plug-in loaded) keeps its marker naming that item. A marker left behind by a launch
|
||||
//! that is no longer running names the items that were loading when it stopped; any one of them,
|
||||
//! or none, may be what stopped it. Until the user chooses what to do about those items
|
||||
//! ([`forget_previous`]), the next launch's marker names them too and stays when that launch
|
||||
//! quits, so a launch that asks nothing (`--safe-mode`) or one closed in Safe Mode leaves the
|
||||
//! choice to the launch after it. Each launch has
|
||||
//! its own marker and holds a lock on a file beside it, so a launch that is still running (a second
|
||||
//! window) is never taken for one that stopped. A marker that is missing, empty, unreadable,
|
||||
//! malformed, larger than [`MAX_MARKER_BYTES`] or of another version names nothing.
|
||||
@@ -41,8 +41,11 @@ const MAX_FIELD_CHARS: usize = 1024;
|
||||
/// The most bytes one stored item takes in JSON: three fields of [`MAX_FIELD_CHARS`] characters,
|
||||
/// each written in at most 6 bytes (`\u001f`), plus keys, quotes and indentation.
|
||||
const MAX_ITEM_JSON_BYTES: usize = 3 * MAX_FIELD_CHARS * 6 + 256;
|
||||
/// The largest launch marker read, in bytes: room for one stored item.
|
||||
pub const MAX_MARKER_BYTES: u64 = (MAX_ITEM_JSON_BYTES + 256) as u64;
|
||||
/// The most items a launch marker names.
|
||||
pub const MAX_MARKER_ITEMS: usize = 16;
|
||||
/// The largest launch marker read, in bytes: room for [`MAX_MARKER_ITEMS`] stored items, and the
|
||||
/// first of them again as `item`.
|
||||
pub const MAX_MARKER_BYTES: u64 = ((MAX_MARKER_ITEMS + 1) * MAX_ITEM_JSON_BYTES + 256) as u64;
|
||||
/// The longest name an item is shown with, in characters (longer ones end with "…").
|
||||
pub const MAX_NAME_CHARS: usize = 64;
|
||||
/// The most disabled items kept.
|
||||
@@ -413,18 +416,19 @@ pub fn read_disabled_file(bytes: &[u8]) -> Option<Vec<Item>> {
|
||||
)
|
||||
}
|
||||
|
||||
/// The item the launch before this one was loading when it stopped, once [`begin_launch`] read it.
|
||||
static PREVIOUS: Mutex<Option<Item>> = Mutex::new(None);
|
||||
/// The items the launch before this one was loading when it stopped, once [`begin_launch`] read
|
||||
/// them.
|
||||
static PREVIOUS: Mutex<Vec<Item>> = Mutex::new(Vec::new());
|
||||
|
||||
/// The item the launch before this one was loading when it stopped ([`begin_launch`]); `None` once
|
||||
/// the user chose what to do about it ([`forget_previous`]).
|
||||
pub fn previous() -> Option<Item> {
|
||||
/// The items the launch before this one was loading when it stopped, oldest first
|
||||
/// ([`begin_launch`]); none once the user chose what to do about them ([`forget_previous`]).
|
||||
pub fn previous() -> Vec<Item> {
|
||||
PREVIOUS.lock().unwrap_or_else(|e| e.into_inner()).clone()
|
||||
}
|
||||
|
||||
/// The user chose what to do about [`previous`]: this launch's marker stops naming it.
|
||||
/// The user chose what to do about [`previous`]: this launch's marker stops naming them.
|
||||
pub fn forget_previous() {
|
||||
*PREVIOUS.lock().unwrap_or_else(|e| e.into_inner()) = None;
|
||||
PREVIOUS.lock().unwrap_or_else(|e| e.into_inner()).clear();
|
||||
refresh();
|
||||
}
|
||||
|
||||
@@ -437,9 +441,19 @@ struct Running {
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
impl Running {
|
||||
/// The item this launch's marker names: the oldest item still loading, else [`previous`].
|
||||
fn pending(&self) -> Option<Item> {
|
||||
self.items.first().map(|(_, i)| i.clone()).or_else(previous)
|
||||
/// The items this launch's marker names: the items still loading, oldest first, each plug-in
|
||||
/// once, at most [`MAX_MARKER_ITEMS`]; with none loading, [`previous`].
|
||||
fn pending(&self) -> Vec<Item> {
|
||||
let mut items: Vec<Item> = Vec::new();
|
||||
for (_, item) in &self.items {
|
||||
if items.len() == MAX_MARKER_ITEMS {
|
||||
break;
|
||||
}
|
||||
if !items.iter().any(|i| i.same(item)) {
|
||||
items.push(item.clone());
|
||||
}
|
||||
}
|
||||
if items.is_empty() { previous() } else { items }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -450,22 +464,33 @@ static LOADING: Mutex<Running> = Mutex::new(Running { next: 0, items: Vec::new()
|
||||
#[derive(Debug)]
|
||||
pub struct Loading(u64);
|
||||
|
||||
/// Writes this launch's marker naming the item [`Running::pending`] gives, while holding the lock
|
||||
/// Writes this launch's marker naming the items [`Running::pending`] gives, while holding the lock
|
||||
/// on the items still loading, so two threads' writes land in the order of their changes.
|
||||
fn refresh() {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
marker::write(LOADING.lock().unwrap_or_else(|e| e.into_inner()).pending().as_ref());
|
||||
marker::write(&LOADING.lock().unwrap_or_else(|e| e.into_inner()).pending());
|
||||
}
|
||||
|
||||
/// The marker's content naming `item`, cut as a stored item is (none: nothing is loading).
|
||||
/// The marker's content naming `items` (none: nothing is loading), each cut as a stored item is,
|
||||
/// at most [`MAX_MARKER_ITEMS`]: the first as `item`, and all of them as `items` when there are
|
||||
/// several.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn marker_bytes(item: Option<&Item>) -> Vec<u8> {
|
||||
let item = item.cloned().and_then(Item::bounded);
|
||||
serde_json::to_vec(&json!({"format": MARKER_FORMAT, "version": MARKER_VERSION, "item": item})).unwrap_or_default()
|
||||
fn marker_bytes(items: &[Item]) -> Vec<u8> {
|
||||
let items: Vec<Item> = items.iter().cloned().filter_map(Item::bounded).take(MAX_MARKER_ITEMS).collect();
|
||||
let mut v = json!({"format": MARKER_FORMAT, "version": MARKER_VERSION, "item": items.first()});
|
||||
if items.len() > 1 {
|
||||
v["items"] = json!(items);
|
||||
}
|
||||
serde_json::to_vec(&v).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The item a marker's content names; `None` when it names none or isn't a marker of this version.
|
||||
pub fn parse_marker(bytes: &[u8]) -> Option<Item> {
|
||||
/// The items a marker's content names, oldest first: its `items` when it has them, else its
|
||||
/// `item`; none when it names none or isn't a marker of this version.
|
||||
pub fn parse_marker(bytes: &[u8]) -> Vec<Item> {
|
||||
read_marker(bytes).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn read_marker(bytes: &[u8]) -> Option<Vec<Item>> {
|
||||
if bytes.len() as u64 > MAX_MARKER_BYTES {
|
||||
return None;
|
||||
}
|
||||
@@ -473,31 +498,44 @@ pub fn parse_marker(bytes: &[u8]) -> Option<Item> {
|
||||
if v["format"] != MARKER_FORMAT || v["version"] != MARKER_VERSION {
|
||||
return None;
|
||||
}
|
||||
serde_json::from_value::<Item>(v.get("item").filter(|i| i.is_object())?.clone()).ok()?.bounded()
|
||||
let item = |i: &Value| serde_json::from_value::<Item>(i.clone()).ok()?.bounded();
|
||||
let mut items: Vec<Item> = Vec::new();
|
||||
for i in v["items"].as_array().into_iter().flatten().filter(|i| i.is_object()) {
|
||||
if items.len() == MAX_MARKER_ITEMS {
|
||||
break;
|
||||
}
|
||||
if let Some(i) = item(i).filter(|i| !items.iter().any(|e| e.same(i))) {
|
||||
items.push(i);
|
||||
}
|
||||
}
|
||||
if items.is_empty() {
|
||||
items.extend(v.get("item").filter(|i| i.is_object()).and_then(item));
|
||||
}
|
||||
Some(items)
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub use marker::{begin_launch, end_launch};
|
||||
|
||||
/// Adds `item` to the items still loading and writes this launch's marker naming the oldest of
|
||||
/// them (no marker: only the list changes) → the [`Loading`] to give to [`loaded`] when it is done.
|
||||
/// Adds `item` to the items still loading and writes this launch's marker naming them (no marker:
|
||||
/// only the list changes) → the [`Loading`] to give to [`loaded`] when it is done.
|
||||
pub fn loading(item: &Item) -> Loading {
|
||||
let mut running = LOADING.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let token = running.next;
|
||||
running.next = running.next.wrapping_add(1);
|
||||
running.items.push((token, item.clone()));
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
marker::write(running.pending().as_ref());
|
||||
marker::write(&running.pending());
|
||||
Loading(token)
|
||||
}
|
||||
|
||||
/// Removes the item `token` names from the items still loading and writes this launch's marker
|
||||
/// naming the oldest one left; with none left, the item of [`previous`] or nothing.
|
||||
/// naming the ones left; with none left, the items of [`previous`] or nothing.
|
||||
pub fn loaded(token: Loading) {
|
||||
let mut running = LOADING.lock().unwrap_or_else(|e| e.into_inner());
|
||||
running.items.retain(|(t, _)| *t != token.0);
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
marker::write(running.pending().as_ref());
|
||||
marker::write(&running.pending());
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -551,12 +589,12 @@ mod marker {
|
||||
(bytes.len() as u64 <= MAX_MARKER_BYTES).then_some(bytes)
|
||||
}
|
||||
|
||||
/// Starts this launch's marker in `dir` → the item a launch that is no longer running was
|
||||
/// loading when it stopped, if one was (its marker is then removed, and this launch's marker
|
||||
/// names the item until [`super::forget_previous`]). A folder that can't be written leaves this
|
||||
/// launch without a marker; it still starts.
|
||||
pub fn begin_launch(dir: &Path) -> Option<Item> {
|
||||
let mut previous = None;
|
||||
/// Starts this launch's marker in `dir` → the items a launch that is no longer running was
|
||||
/// loading when it stopped, if it was loading any (its marker is then removed, and this
|
||||
/// launch's marker names the items until [`super::forget_previous`]). A folder that can't be
|
||||
/// written leaves this launch without a marker; it still starts.
|
||||
pub fn begin_launch(dir: &Path) -> Vec<Item> {
|
||||
let mut previous = Vec::new();
|
||||
let mut tokens: Vec<String> = std::fs::read_dir(dir)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
@@ -569,8 +607,8 @@ mod marker {
|
||||
if running(dir, &token) {
|
||||
continue;
|
||||
}
|
||||
if previous.is_none() {
|
||||
previous = read(&json_path(dir, &token)).as_deref().and_then(parse_marker);
|
||||
if previous.is_empty() {
|
||||
previous = read(&json_path(dir, &token)).as_deref().map(parse_marker).unwrap_or_default();
|
||||
}
|
||||
for path in [json_path(dir, &token), tmp_path(dir, &token), lock_path(dir, &token)] {
|
||||
let _ = std::fs::remove_file(path);
|
||||
@@ -588,32 +626,32 @@ mod marker {
|
||||
previous
|
||||
}
|
||||
|
||||
/// Replaces this launch's marker with one naming `item`: written to a temporary file first,
|
||||
/// Replaces this launch's marker with one naming `items`: written to a temporary file first,
|
||||
/// then renamed over the marker, so a reader finds the old marker or the new one. A write that
|
||||
/// fails leaves the marker as it was.
|
||||
pub(super) fn write(item: Option<&Item>) {
|
||||
pub(super) fn write(items: &[Item]) {
|
||||
let current = CURRENT.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let Some(c) = current.as_ref() else { return };
|
||||
let tmp = tmp_path(&c.dir, &c.token);
|
||||
let _ = File::create(&tmp)
|
||||
.and_then(|mut f| f.write_all(&marker_bytes(item)).and_then(|()| f.sync_all()))
|
||||
.and_then(|mut f| f.write_all(&marker_bytes(items)).and_then(|()| f.sync_all()))
|
||||
.and_then(|()| std::fs::rename(&tmp, json_path(&c.dir, &c.token)));
|
||||
}
|
||||
|
||||
/// Removes this launch's marker: the app is quitting normally. While an item is still loading
|
||||
/// ([`super::loading`] without [`super::loaded`]), the marker stays, naming the oldest one;
|
||||
/// otherwise, while the user has not chosen what to do about [`super::previous`], the marker
|
||||
/// stays, naming that, so the next launch asks.
|
||||
/// ([`super::loading`] without [`super::loaded`]), the marker stays, naming the items still
|
||||
/// loading; otherwise, while the user has not chosen what to do about [`super::previous`], the
|
||||
/// marker stays, naming those, so the next launch asks.
|
||||
pub fn end_launch() {
|
||||
let running = LOADING.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let pending = running.pending();
|
||||
if pending.is_some() {
|
||||
write(pending.as_ref());
|
||||
if !pending.is_empty() {
|
||||
write(&pending);
|
||||
}
|
||||
let Some(c) = CURRENT.lock().unwrap_or_else(|e| e.into_inner()).take() else { return };
|
||||
let Current { dir, token, _lock } = c;
|
||||
drop(_lock);
|
||||
let marker = pending.is_none().then(|| json_path(&dir, &token));
|
||||
let marker = pending.is_empty().then(|| json_path(&dir, &token));
|
||||
for path in marker.into_iter().chain([tmp_path(&dir, &token), lock_path(&dir, &token)]) {
|
||||
let _ = std::fs::remove_file(path);
|
||||
}
|
||||
@@ -629,6 +667,12 @@ mod marker {
|
||||
#[cfg(test)]
|
||||
pub(crate) static TEST_LOCK: Mutex<()> = Mutex::new(());
|
||||
|
||||
/// Tests: the items still loading, oldest first.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn still_loading() -> Vec<Item> {
|
||||
LOADING.lock().unwrap_or_else(|e| e.into_inner()).items.iter().map(|(_, i)| i.clone()).collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -683,11 +727,18 @@ mod tests {
|
||||
assert_eq!(Item::file("C:\\Plug-ins\\x.wasm").label(), "x.wasm");
|
||||
}
|
||||
|
||||
/// The items the marker at `path` names.
|
||||
fn marker_at(path: &std::path::Path) -> Vec<Item> {
|
||||
std::fs::read(path).ok().as_deref().map(parse_marker).unwrap_or_default()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_a_marker_of_this_version_names_an_item() {
|
||||
let item = Item { id: Some("org.example.x".into()), file: Some("/p/x.wasm".into()), name: None };
|
||||
assert_eq!(parse_marker(&marker_bytes(Some(&item))), Some(item));
|
||||
assert_eq!(parse_marker(&marker_bytes(None)), None, "nothing was loading");
|
||||
assert_eq!(parse_marker(&marker_bytes(std::slice::from_ref(&item))), std::slice::from_ref(&item));
|
||||
assert_eq!(parse_marker(&marker_bytes(&[])), [], "nothing was loading");
|
||||
// A marker naming one item has no `items`, as before markers named several.
|
||||
assert!(!String::from_utf8(marker_bytes(std::slice::from_ref(&item))).unwrap().contains("\"items\""));
|
||||
for bad in [
|
||||
&b""[..],
|
||||
b"{",
|
||||
@@ -698,13 +749,28 @@ mod tests {
|
||||
br#"{"format":"vectorcraft-launch","version":1,"item":{}}"#,
|
||||
br#"{"format":"vectorcraft-launch","version":1,"item":{"id":"x""#,
|
||||
] {
|
||||
assert_eq!(parse_marker(bad), None, "{}", String::from_utf8_lossy(bad));
|
||||
assert_eq!(parse_marker(bad), [], "{}", String::from_utf8_lossy(bad));
|
||||
}
|
||||
let mut big =
|
||||
format!(r#"{{"format":"vectorcraft-launch","version":1,"item":{{"id":"{}"}}}}"#, "y".repeat(MAX_MARKER_BYTES as usize)).into_bytes();
|
||||
assert_eq!(parse_marker(&big), None, "larger than the limit");
|
||||
assert_eq!(parse_marker(&big), [], "larger than the limit");
|
||||
big.truncate(10);
|
||||
assert_eq!(parse_marker(&big), None, "cut short");
|
||||
assert_eq!(parse_marker(&big), [], "cut short");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_marker_names_every_item_up_to_its_limit() {
|
||||
let field = |i: usize, tag: &str| format!("{tag}{i:04}{}", "\u{1}".repeat(MAX_FIELD_CHARS));
|
||||
let items: Vec<Item> =
|
||||
(0..MAX_MARKER_ITEMS + 3).map(|i| Item { id: Some(field(i, "i")), file: Some(field(i, "f")), name: Some(field(i, "n")) }).collect();
|
||||
let bytes = marker_bytes(&items);
|
||||
assert!(bytes.len() as u64 <= MAX_MARKER_BYTES, "{} bytes", bytes.len());
|
||||
let read = parse_marker(&bytes);
|
||||
assert_eq!(read.len(), MAX_MARKER_ITEMS);
|
||||
assert!(read.iter().zip(&items).all(|(r, i)| r.same(i)), "oldest first");
|
||||
// A marker whose `items` names nothing readable falls back to its `item`.
|
||||
let x = br#"{"format":"vectorcraft-launch","version":1,"item":{"id":"x"},"items":[{},"y"]}"#;
|
||||
assert_eq!(parse_marker(x), [Item { id: Some("x".into()), ..Item::default() }]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -714,23 +780,23 @@ mod tests {
|
||||
// A launch that stopped while loading x: its marker without a held lock, and a stray
|
||||
// temporary file from a write it didn't finish.
|
||||
let x = Item { id: Some("org.example.x".into()), file: None, name: Some("X".into()) };
|
||||
std::fs::write(dir.join("launch-1-a.json"), marker_bytes(Some(&x))).unwrap();
|
||||
std::fs::write(dir.join("launch-1-a.json"), marker_bytes(std::slice::from_ref(&x))).unwrap();
|
||||
std::fs::write(dir.join("launch-1-a.json.tmp"), b"{\"format\":\"vectorcr").unwrap();
|
||||
assert_eq!(begin_launch(&dir), Some(x.clone()));
|
||||
assert_eq!(previous(), Some(x.clone()));
|
||||
assert_eq!(begin_launch(&dir), std::slice::from_ref(&x));
|
||||
assert_eq!(previous(), std::slice::from_ref(&x));
|
||||
assert!(!dir.join("launch-1-a.json").exists() && !dir.join("launch-1-a.json.tmp").exists(), "read once");
|
||||
let mine = marker::path_of_current().unwrap();
|
||||
assert_eq!(std::fs::read(&mine).ok().as_deref().and_then(parse_marker), Some(x.clone()), "named until the user chooses");
|
||||
assert_eq!(marker_at(&mine), std::slice::from_ref(&x), "named until the user chooses");
|
||||
forget_previous();
|
||||
assert_eq!(std::fs::read(&mine).ok().as_deref().and_then(parse_marker), None);
|
||||
assert_eq!(marker_at(&mine), []);
|
||||
let token = loading(&x);
|
||||
assert_eq!(std::fs::read(&mine).ok().as_deref().and_then(parse_marker), Some(x.clone()));
|
||||
assert_eq!(marker_at(&mine), std::slice::from_ref(&x));
|
||||
assert!(!mine.with_extension("json.tmp").exists(), "the temporary file is renamed over the marker");
|
||||
loaded(token);
|
||||
assert_eq!(std::fs::read(&mine).ok().as_deref().and_then(parse_marker), None);
|
||||
assert_eq!(marker_at(&mine), []);
|
||||
end_launch();
|
||||
assert!(!mine.exists(), "a normal quit removes the marker");
|
||||
assert_eq!(begin_launch(&dir), None, "nothing left behind");
|
||||
assert_eq!(begin_launch(&dir), [], "nothing left behind");
|
||||
end_launch();
|
||||
forget_previous();
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
@@ -741,13 +807,13 @@ mod tests {
|
||||
let _f = fresh();
|
||||
let dir = temp_dir("pending");
|
||||
let x = Item { id: Some("org.example.x".into()), file: None, name: Some("X".into()) };
|
||||
std::fs::write(dir.join("launch-1-a.json"), marker_bytes(Some(&x))).unwrap();
|
||||
assert_eq!(begin_launch(&dir), Some(x.clone()));
|
||||
std::fs::write(dir.join("launch-1-a.json"), marker_bytes(std::slice::from_ref(&x))).unwrap();
|
||||
assert_eq!(begin_launch(&dir), std::slice::from_ref(&x));
|
||||
end_launch();
|
||||
assert_eq!(begin_launch(&dir), Some(x.clone()), "asked again");
|
||||
assert_eq!(begin_launch(&dir), std::slice::from_ref(&x), "asked again");
|
||||
forget_previous();
|
||||
end_launch();
|
||||
assert_eq!(begin_launch(&dir), None, "once the user chose");
|
||||
assert_eq!(begin_launch(&dir), [], "once the user chose");
|
||||
end_launch();
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -757,15 +823,15 @@ mod tests {
|
||||
let _f = fresh();
|
||||
let dir = temp_dir("ends-loading");
|
||||
let x = Item { id: Some("org.example.x".into()), file: None, name: Some("X".into()) };
|
||||
assert_eq!(begin_launch(&dir), None);
|
||||
assert_eq!(begin_launch(&dir), []);
|
||||
let token = loading(&x);
|
||||
// A panic the app caught while x loaded: the app quits without `loaded`.
|
||||
end_launch();
|
||||
loaded(token);
|
||||
assert_eq!(begin_launch(&dir), Some(x.clone()), "the next launch asks");
|
||||
assert_eq!(begin_launch(&dir), std::slice::from_ref(&x), "the next launch asks");
|
||||
forget_previous();
|
||||
end_launch();
|
||||
assert_eq!(begin_launch(&dir), None);
|
||||
assert_eq!(begin_launch(&dir), []);
|
||||
end_launch();
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -776,22 +842,49 @@ mod tests {
|
||||
let dir = temp_dir("two-loading");
|
||||
let a = Item { id: Some("org.example.a".into()), file: None, name: Some("A".into()) };
|
||||
let b = Item { id: Some("org.example.b".into()), file: None, name: Some("B".into()) };
|
||||
assert_eq!(begin_launch(&dir), None);
|
||||
assert_eq!(begin_launch(&dir), []);
|
||||
let mine = marker::path_of_current().unwrap();
|
||||
let marker = || std::fs::read(&mine).ok().as_deref().and_then(parse_marker);
|
||||
// Two threads run their plug-ins' first evaluations at once.
|
||||
let ta = loading(&a);
|
||||
let tb = loading(&b);
|
||||
assert_eq!(marker(), Some(a.clone()), "the oldest item still loading");
|
||||
assert_eq!(marker_at(&mine), [a.clone(), b.clone()], "both items still loading, oldest first");
|
||||
loaded(ta);
|
||||
assert_eq!(marker(), Some(b.clone()), "b is still loading");
|
||||
assert_eq!(marker_at(&mine), std::slice::from_ref(&b), "b is still loading");
|
||||
// The app stops while b loads.
|
||||
end_launch();
|
||||
loaded(tb);
|
||||
assert_eq!(begin_launch(&dir), Some(b.clone()), "the next launch offers b");
|
||||
assert_eq!(begin_launch(&dir), std::slice::from_ref(&b), "the next launch offers b");
|
||||
forget_previous();
|
||||
end_launch();
|
||||
assert_eq!(begin_launch(&dir), None);
|
||||
assert_eq!(begin_launch(&dir), []);
|
||||
end_launch();
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A launch that stops while two plug-ins load offers both at the next launch, until the user
|
||||
/// chooses, however many launches that takes.
|
||||
#[test]
|
||||
fn a_launch_that_stops_while_two_plug_ins_load_offers_both() {
|
||||
let _f = fresh();
|
||||
let dir = temp_dir("two-stopped");
|
||||
let a = Item { id: Some("org.example.a".into()), file: None, name: Some("A".into()) };
|
||||
let b = Item { id: Some("org.example.b".into()), file: None, name: Some("B".into()) };
|
||||
assert_eq!(begin_launch(&dir), []);
|
||||
let ta = loading(&a);
|
||||
let tb = loading(&b);
|
||||
// The same plug-in loading twice is named once.
|
||||
let ta2 = loading(&a);
|
||||
end_launch();
|
||||
for t in [ta, tb, ta2] {
|
||||
loaded(t);
|
||||
}
|
||||
assert_eq!(begin_launch(&dir), [a.clone(), b.clone()], "the next launch offers both");
|
||||
assert_eq!(previous(), [a.clone(), b.clone()]);
|
||||
end_launch();
|
||||
assert_eq!(begin_launch(&dir), [a.clone(), b.clone()], "asked again");
|
||||
forget_previous();
|
||||
end_launch();
|
||||
assert_eq!(begin_launch(&dir), []);
|
||||
end_launch();
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -802,11 +895,11 @@ mod tests {
|
||||
let dir = temp_dir("long-path");
|
||||
// Each character written as 6 or 2 bytes, so the item is far larger in JSON than in characters.
|
||||
let long = format!("C:\\{}\\x.wasm", "\u{1}é".repeat(700));
|
||||
assert_eq!(begin_launch(&dir), None);
|
||||
assert_eq!(begin_launch(&dir), []);
|
||||
let token = loading(&Item::file(long.clone()));
|
||||
end_launch();
|
||||
loaded(token);
|
||||
let stopped = begin_launch(&dir).expect("the marker names the module");
|
||||
let stopped = begin_launch(&dir).into_iter().next().expect("the marker names the module");
|
||||
assert!(stopped.same(&Item::file(long.clone())), "the stored item matches the full path");
|
||||
disable(stopped);
|
||||
assert!(skipped(&Item::file(long.clone())), "Disable and Continue skips it");
|
||||
@@ -891,14 +984,14 @@ mod tests {
|
||||
let _f = fresh();
|
||||
let dir = temp_dir("running");
|
||||
let x = Item { id: Some("org.example.x".into()), file: None, name: None };
|
||||
std::fs::write(dir.join("launch-9-b.json"), marker_bytes(Some(&x))).unwrap();
|
||||
std::fs::write(dir.join("launch-9-b.json"), marker_bytes(std::slice::from_ref(&x))).unwrap();
|
||||
let lock = std::fs::File::create(dir.join("launch-9-b.lock")).unwrap();
|
||||
lock.try_lock().unwrap();
|
||||
assert_eq!(begin_launch(&dir), None, "that launch is still running");
|
||||
assert_eq!(begin_launch(&dir), [], "that launch is still running");
|
||||
assert!(dir.join("launch-9-b.json").exists());
|
||||
end_launch();
|
||||
drop(lock);
|
||||
assert_eq!(begin_launch(&dir), Some(x), "once it stopped");
|
||||
assert_eq!(begin_launch(&dir), [x], "once it stopped");
|
||||
end_launch();
|
||||
forget_previous();
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! The shipped code that records a plug-in grant: only the engine's install approval and its load
|
||||
//! of the plug-in folder's grants file make a `GrantToken` and call `registry::grant` or
|
||||
//! `registry::install_checked`. A new call site fails this test until it is added to the list. It
|
||||
//! checks the source, not what native code can do at run time.
|
||||
//! of the plug-in folder's grants file make a `GrantToken` and call `registry::grant`,
|
||||
//! `registry::install_checked` or `registry::install_for_load`. A new call site fails this test until
|
||||
//! it is added to the list. It checks the source, not what native code can do at run time.
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
@@ -11,12 +11,19 @@ use std::path::{Path, PathBuf};
|
||||
const EXPECTED: &[(&str, &str, usize)] = &[
|
||||
("GrantToken::after_engine_approval", "crates/engine/src/cmd/plugin.rs", 1),
|
||||
("GrantToken::from_engine_grants_file", "crates/engine/src/store.rs", 2),
|
||||
("registry::grant", "crates/engine/src/store.rs", 2),
|
||||
("registry::grant", "crates/engine/src/store.rs", 1),
|
||||
("registry::install_checked", "crates/engine/src/cmd/plugin.rs", 1),
|
||||
("registry::install_for_load", "crates/engine/src/store.rs", 2),
|
||||
];
|
||||
|
||||
/// The names the audit counts.
|
||||
const NAMES: [&str; 4] = ["GrantToken::after_engine_approval", "GrantToken::from_engine_grants_file", "registry::grant", "registry::install_checked"];
|
||||
const NAMES: [&str; 5] = [
|
||||
"GrantToken::after_engine_approval",
|
||||
"GrantToken::from_engine_grants_file",
|
||||
"registry::grant",
|
||||
"registry::install_checked",
|
||||
"registry::install_for_load",
|
||||
];
|
||||
|
||||
/// Every `.rs` file under `dir`, without test files and folders.
|
||||
fn sources(dir: &Path, out: &mut Vec<PathBuf>) {
|
||||
|
||||
@@ -508,6 +508,18 @@ impl VectorcraftApp {
|
||||
crate::keymap::note_os(ctx);
|
||||
prefs_dialog::apply_runtime(self, ctx);
|
||||
self.run_control(ctx);
|
||||
// Plug-ins loading on other threads since launch install as their loads finish; until then
|
||||
// the host keeps coming back to look again, and once more when the last one installs, for
|
||||
// what waits for them. They install after the control requests are drained, so the frame
|
||||
// after the last one opens the files held for them (the desktop app does that before this
|
||||
// pass) before a control request waiting for them runs.
|
||||
if self.session.plugins_loading() {
|
||||
if self.session.poll_plugin_loads() {
|
||||
ctx.request_repaint_after(std::time::Duration::from_millis(50));
|
||||
} else {
|
||||
ctx.request_repaint();
|
||||
}
|
||||
}
|
||||
// In the next frame's first pass, as production's one-pass frames did: a second pass of the frame that asked
|
||||
// for it (one a background run's result can bring) doesn't open it early.
|
||||
if ctx.current_pass_index() == 0
|
||||
|
||||
@@ -57,6 +57,15 @@ impl VectorcraftApp {
|
||||
ctx.request_repaint();
|
||||
break;
|
||||
}
|
||||
// An automation request sees every plug-in the launch loads: what it reads or writes
|
||||
// (rendered artwork, file formats, effect lists) would otherwise depend on timing. It
|
||||
// waits in the queue while the frames install them, so the window keeps drawing; one
|
||||
// held past its deadline meanwhile is answered above as expired. The frame's poll of
|
||||
// the loads asks for the next frame.
|
||||
if self.session.plugins_loading() {
|
||||
self.deferred_control = Some(req);
|
||||
break;
|
||||
}
|
||||
let roots = self.automation_roots.clone();
|
||||
self.ui.answering_control = true;
|
||||
// Guarded per request: a panic must not stop the requests behind it.
|
||||
|
||||
@@ -7,13 +7,14 @@
|
||||
use craft::ui::contract::Bind;
|
||||
use craft::ui::dialog::{DialogResult, PromptChoice, StandardPrompt, StartupStage, dialog_id};
|
||||
use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind};
|
||||
use serde_json::Value;
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_plugins::safe_mode::{self, Item};
|
||||
|
||||
use crate::VectorcraftApp;
|
||||
|
||||
/// Key of the choice after a launch that stopped. It holds `UiState::stopped_plugin` (the item as
|
||||
/// `{id, file, name, label}`) until answered. Cancel starts in Safe Mode.
|
||||
/// Key of the choice after a launch that stopped. It holds `UiState::stopped_plugin` until
|
||||
/// answered: `items` (`[{id, file, name, label}]`, the plug-ins that were loading, oldest first)
|
||||
/// and `item` (the first of them). Cancel starts in Safe Mode.
|
||||
pub const STOPPED: &str = "pluginStopped";
|
||||
|
||||
/// Key of Help › Safe Mode's dialog. It has a check box `enable-{k}` (Enable on Re-launch) and the
|
||||
@@ -32,17 +33,17 @@ fn enable_key(k: usize) -> String {
|
||||
|
||||
/// Before any plug-in loads (desktop): starts this launch's marker in `marker_dir` (none: no
|
||||
/// marker), and turns Safe Mode on for `--safe-mode` (`flag`), or until the user chooses after a
|
||||
/// launch that stopped while a plug-in was loading → that plug-in, for [`after_start`]. With `flag`
|
||||
/// nothing is asked, and the plug-in stays pending (`plugin.safeMode`'s `pendingItem`): the next
|
||||
/// launch asks about it.
|
||||
/// launch that stopped while plug-ins were loading → those plug-ins, for [`after_start`]. With
|
||||
/// `flag` nothing is asked, and the plug-ins stay pending (`plugin.safeMode`'s `pendingItems`): the
|
||||
/// next launch asks about them.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn begin_launch(marker_dir: Option<&std::path::Path>, flag: bool) -> Option<Item> {
|
||||
let stopped = marker_dir.and_then(safe_mode::begin_launch);
|
||||
pub fn begin_launch(marker_dir: Option<&std::path::Path>, flag: bool) -> Vec<Item> {
|
||||
let stopped = marker_dir.map(safe_mode::begin_launch).unwrap_or_default();
|
||||
if flag {
|
||||
safe_mode::set_active(Some(safe_mode::Source::Flag));
|
||||
return None;
|
||||
return Vec::new();
|
||||
}
|
||||
if stopped.is_some() {
|
||||
if !stopped.is_empty() {
|
||||
safe_mode::set_active(Some(safe_mode::Source::Startup));
|
||||
}
|
||||
stopped
|
||||
@@ -56,20 +57,21 @@ pub fn end_launch() {
|
||||
|
||||
/// Once the app is made: the choice about `stopped` ([`begin_launch`]), or in Safe Mode a status
|
||||
/// line saying so.
|
||||
pub fn after_start(app: &mut VectorcraftApp, stopped: Option<Item>) {
|
||||
match stopped {
|
||||
Some(item) => ask_about_stopped(app, &item),
|
||||
None if safe_mode::active() => app.status(vectorcraft_plugins::Error::SafeMode.to_string()),
|
||||
None => {}
|
||||
pub fn after_start(app: &mut VectorcraftApp, stopped: Vec<Item>) {
|
||||
if !stopped.is_empty() {
|
||||
ask_about_stopped(app, &stopped);
|
||||
} else if safe_mode::active() {
|
||||
app.status(vectorcraft_plugins::Error::SafeMode.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
/// Ask what to do about `item`, the plug-in the last launch was loading when it stopped. Safe Mode
|
||||
/// is on until the user chooses. The app holds the item; [`pump`] puts the question on the dialog
|
||||
/// host once the host exists and no other dialog holds it, so a dialog that takes the choice's
|
||||
/// place leaves it waiting.
|
||||
pub fn ask_about_stopped(app: &mut VectorcraftApp, item: &Item) {
|
||||
app.ui.stopped_plugin = Some(item.to_json());
|
||||
/// Ask what to do about `items`, the plug-ins the last launch was loading when it stopped. Safe
|
||||
/// Mode is on until the user chooses. The app holds the items; [`pump`] puts the question on the
|
||||
/// dialog host once the host exists and no other dialog holds it, so a dialog that takes the
|
||||
/// choice's place leaves it waiting.
|
||||
pub fn ask_about_stopped(app: &mut VectorcraftApp, items: &[Item]) {
|
||||
let items: Vec<Value> = items.iter().map(Item::to_json).collect();
|
||||
app.ui.stopped_plugin = Some(json!({ "item": items.first(), "items": items }));
|
||||
}
|
||||
|
||||
/// The choice's Cancel, Start in Safe Mode: Safe Mode stays on for this launch, and the plug-in
|
||||
@@ -95,27 +97,56 @@ fn item_of(v: &Value) -> Item {
|
||||
Item { id: s("id"), file: s("file"), name: s("name") }
|
||||
}
|
||||
|
||||
/// The question about the stopped plug-in `item`.
|
||||
fn stopped_prompt(item: &Value) -> StandardPrompt {
|
||||
let name = item_of(item).label();
|
||||
let text = crate::i18n::fmt(
|
||||
tl!("The last launch of VectorCraft stopped while the plug-in {name} was loading. It may not be what stopped it."),
|
||||
&[("name", &name)],
|
||||
);
|
||||
/// The items the held choice names: its `items`, else its `item`.
|
||||
fn stopped_items(fields: &Value) -> Vec<Item> {
|
||||
match fields.get("items").and_then(Value::as_array).filter(|i| !i.is_empty()) {
|
||||
Some(items) => items.iter().map(item_of).collect(),
|
||||
None => fields.get("item").filter(|i| i.is_object()).map(item_of).into_iter().collect(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The question about the stopped plug-ins the held choice `fields` names.
|
||||
fn stopped_prompt(fields: &Value) -> StandardPrompt {
|
||||
let items = stopped_items(fields);
|
||||
let (text, proceed) = if let [item] = items.as_slice() {
|
||||
let text = crate::i18n::fmt(
|
||||
tl!("The last launch of VectorCraft stopped while the plug-in {name} was loading. It may not be what stopped it."),
|
||||
&[("name", &item.label())],
|
||||
);
|
||||
(text, tl!("Disable and Continue").to_string())
|
||||
} else {
|
||||
let mut text =
|
||||
tl!("The last launch of VectorCraft stopped while these plug-ins were loading. Any one of them, or none, may be what stopped it.")
|
||||
.to_string();
|
||||
text.push('\n');
|
||||
for item in &items {
|
||||
// A name made safe to show: control and reordering characters removed, bounded.
|
||||
text.push('\n');
|
||||
text.push_str(&safe_mode::display_name(&item.label()));
|
||||
}
|
||||
(text, tl!("Disable Listed Plug-ins and Continue").to_string())
|
||||
};
|
||||
StandardPrompt::custom(text)
|
||||
.title(tl!("Safe Mode").to_string())
|
||||
.button(PromptChoice::Proceed, tl!("Disable and Continue").to_string())
|
||||
.button(PromptChoice::Proceed, proceed)
|
||||
.button(PromptChoice::Alternate, tl!("Start Normally").to_string())
|
||||
.button(PromptChoice::Cancel, tl!("Start in Safe Mode").to_string())
|
||||
}
|
||||
|
||||
/// The choice's Disable and Continue (`normal` false) or Start Normally: Safe Mode ends and the
|
||||
/// plug-ins load, without the stopped one for Disable and Continue (kept off for later launches
|
||||
/// plug-ins load, without the stopped ones for Disable and Continue (kept off for later launches
|
||||
/// too).
|
||||
fn confirm_stopped(app: &mut VectorcraftApp, normal: bool) {
|
||||
let item = item_of(&app.ui.stopped_plugin.take().unwrap_or(Value::Null));
|
||||
// When the disabled plug-in can't be saved for the next launch, that launch asks again.
|
||||
let saved = normal || (safe_mode::disable(item) && app.session.store_disabled_plugins());
|
||||
let items = stopped_items(&app.ui.stopped_plugin.take().unwrap_or(Value::Null));
|
||||
// When a disabled plug-in can't be saved for the next launch, that launch asks again. Every
|
||||
// listed plug-in is turned off for this launch, whether or not the one before it was saved.
|
||||
let saved = normal || {
|
||||
let mut all = true;
|
||||
for item in items {
|
||||
all &= safe_mode::disable(item);
|
||||
}
|
||||
all && app.session.store_disabled_plugins()
|
||||
};
|
||||
if saved {
|
||||
safe_mode::forget_previous();
|
||||
} else {
|
||||
@@ -203,14 +234,14 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
}
|
||||
|
||||
fn pump_stopped(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
let Some(item) = app.ui.stopped_plugin.clone() else { return };
|
||||
let Some(fields) = app.ui.stopped_plugin.clone() else { return };
|
||||
// PLAN: assumed `VectorcraftApp::dialogs() -> Option<handle>` whose `with(|host: &mut DialogHost| ..)` runs on the host (wg.S1).
|
||||
let Some(dialogs) = app.dialogs() else { return };
|
||||
let answered = dialogs.with(|h| {
|
||||
let answered = h.take::<StandardPrompt>();
|
||||
// An empty host has neither an open dialog nor a queued one: otherwise the choice waits.
|
||||
if answered.is_none() && h.is_empty() {
|
||||
h.enqueue(StartupStage::Warning, stopped_prompt(&item));
|
||||
h.enqueue(StartupStage::Warning, stopped_prompt(&fields));
|
||||
ctx.request_repaint();
|
||||
}
|
||||
answered
|
||||
|
||||
@@ -7745,6 +7745,10 @@ variable-list-end {0}, {1} {0} i {1}
|
||||
@msg vc_alloc returned 0 (out of memory) vc_alloc ha retornat 0 (sense memòria)
|
||||
@msg vc_alloc returned a block outside memory vc_alloc ha retornat un bloc fora de la memòria
|
||||
@msg vc_run returned error code {packed} vc_run ha retornat el codi d’error {packed}
|
||||
@msg did not finish loading within {secs} s no ha acabat de carregar-se en {secs} s
|
||||
@msg no thread was left to load it no ha quedat cap fil per carregar-lo
|
||||
@msg panicked while loading ha fallat inesperadament en carregar-se
|
||||
@msg panicked while loading: {what} ha fallat inesperadament en carregar-se: {what}
|
||||
@msg {_1} is not a file {_1} no és un fitxer
|
||||
@msg {_1} is {_2} bytes (limit {_3}) {_1} té {_2} bytes (límit {_3})
|
||||
@msg {_1} objects (limit {MAX_OBJECTS}) {_1} objectes (límit {MAX_OBJECTS})
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -7359,6 +7359,10 @@ axis Y Axis osa Y
|
||||
@msg vc_alloc returned 0 (out of memory) vc_alloc vrátila 0 (nedostatek paměti)
|
||||
@msg vc_alloc returned a block outside memory vc_alloc vrátila blok mimo paměť
|
||||
@msg vc_run returned error code {packed} vc_run vrátila chybový kód {packed}
|
||||
@msg did not finish loading within {secs} s nedokončil načítání do {secs} s
|
||||
@msg no thread was left to load it nezbylo žádné vlákno, které by ho načetlo
|
||||
@msg panicked while loading při načítání došlo k panice
|
||||
@msg panicked while loading: {what} při načítání došlo k panice: {what}
|
||||
@msg {_1} is not a file {_1} není soubor
|
||||
@msg {_1} is {_2} bytes (limit {_3}) {_1} má {_2} bajtů (limit {_3})
|
||||
@msg {_1} objects (limit {MAX_OBJECTS}) {_1} objektů (limit {MAX_OBJECTS})
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -574,6 +574,10 @@ liquify-list-end {0}, {1} {0} og {1}
|
||||
@msg vc_alloc returned 0 (out of memory) vc_alloc returnerede 0 (ikke mere hukommelse)
|
||||
@msg vc_alloc returned a block outside memory vc_alloc returnerede en blok uden for hukommelsen
|
||||
@msg vc_run returned error code {packed} vc_run returnerede fejlkoden {packed}
|
||||
@msg did not finish loading within {secs} s blev ikke færdig med at indlæse inden for {secs} s
|
||||
@msg no thread was left to load it der var ingen tråd tilbage til at indlæse den
|
||||
@msg panicked while loading gik ned under indlæsningen
|
||||
@msg panicked while loading: {what} gik ned under indlæsningen: {what}
|
||||
@msg {_1} is not a file {_1} er ikke en fil
|
||||
@msg {_1} is {_2} bytes (limit {_3}) {_1} fylder {_2} byte (grænse {_3})
|
||||
@msg {_1} objects (limit {MAX_OBJECTS}) {_1} objekter (grænse {MAX_OBJECTS})
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -6942,6 +6942,10 @@ axis Y Axis Y-Achse
|
||||
@msg vc_alloc returned 0 (out of memory) vc_alloc hat 0 zurückgegeben (kein Speicher mehr)
|
||||
@msg vc_alloc returned a block outside memory vc_alloc hat einen Block außerhalb des Speichers zurückgegeben
|
||||
@msg vc_run returned error code {packed} vc_run hat den Fehlercode {packed} zurückgegeben
|
||||
@msg did not finish loading within {secs} s wurde nicht innerhalb von {secs} s fertig geladen
|
||||
@msg no thread was left to load it es war kein Thread mehr frei, um es zu laden
|
||||
@msg panicked while loading ist beim Laden abgestürzt
|
||||
@msg panicked while loading: {what} ist beim Laden abgestürzt: {what}
|
||||
@msg {_1} is not a file {_1} ist keine Datei
|
||||
@msg {_1} is {_2} bytes (limit {_3}) {_1} ist {_2} Byte groß (Grenze {_3})
|
||||
@msg {_1} objects (limit {MAX_OBJECTS}) {_1} Objekte (Grenze {MAX_OBJECTS})
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -7348,6 +7348,10 @@ axis Y Axis Άξονας Y
|
||||
@msg vc_alloc returned 0 (out of memory) η vc_alloc επέστρεψε 0 (η μνήμη εξαντλήθηκε)
|
||||
@msg vc_alloc returned a block outside memory η vc_alloc επέστρεψε ένα μπλοκ εκτός μνήμης
|
||||
@msg vc_run returned error code {packed} η vc_run επέστρεψε τον κωδικό σφάλματος {packed}
|
||||
@msg did not finish loading within {secs} s δεν ολοκλήρωσε τη φόρτωση μέσα σε {secs} s
|
||||
@msg no thread was left to load it δεν έμεινε νήμα για να το φορτώσει
|
||||
@msg panicked while loading κατέρρευσε κατά τη φόρτωση
|
||||
@msg panicked while loading: {what} κατέρρευσε κατά τη φόρτωση: {what}
|
||||
@msg {_1} is not a file το {_1} δεν είναι αρχείο
|
||||
@msg {_1} is {_2} bytes (limit {_3}) το {_1} έχει {_2} byte (όριο {_3})
|
||||
@msg {_1} objects (limit {MAX_OBJECTS}) {_1} αντικείμενα (όριο {MAX_OBJECTS})
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -7334,6 +7334,10 @@ axis Y Axis Eje Y
|
||||
@msg vc_alloc returned 0 (out of memory) vc_alloc devolvió 0 (sin memoria)
|
||||
@msg vc_alloc returned a block outside memory vc_alloc devolvió un bloque fuera de la memoria
|
||||
@msg vc_run returned error code {packed} vc_run devolvió el código de error {packed}
|
||||
@msg did not finish loading within {secs} s no terminó de cargarse en {secs} s
|
||||
@msg no thread was left to load it no quedó ningún hilo para cargarlo
|
||||
@msg panicked while loading falló de forma inesperada al cargarse
|
||||
@msg panicked while loading: {what} falló de forma inesperada al cargarse: {what}
|
||||
@msg {_1} is not a file {_1} no es un archivo
|
||||
@msg {_1} is {_2} bytes (limit {_3}) {_1} ocupa {_2} bytes (límite {_3})
|
||||
@msg {_1} objects (limit {MAX_OBJECTS}) {_1} objetos (límite {MAX_OBJECTS})
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -7425,6 +7425,10 @@ axis Y Axis Y-akseli
|
||||
@msg vc_alloc returned 0 (out of memory) vc_alloc palautti 0 (muisti loppui)
|
||||
@msg vc_alloc returned a block outside memory vc_alloc palautti lohkon muistin ulkopuolelta
|
||||
@msg vc_run returned error code {packed} vc_run palautti virhekoodin {packed}
|
||||
@msg did not finish loading within {secs} s ei latautunut loppuun {secs} sekunnissa
|
||||
@msg no thread was left to load it sen lataamiseen ei jäänyt yhtään säiettä
|
||||
@msg panicked while loading kaatui latauksen aikana
|
||||
@msg panicked while loading: {what} kaatui latauksen aikana: {what}
|
||||
@msg {_1} is not a file {_1} ei ole tiedosto
|
||||
@msg {_1} is {_2} bytes (limit {_3}) {_1} on {_2} tavua (raja {_3})
|
||||
@msg {_1} objects (limit {MAX_OBJECTS}) {_1} objektia (raja {MAX_OBJECTS})
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -7355,6 +7355,10 @@ axis Y Axis Axe Y
|
||||
@msg vc_alloc returned 0 (out of memory) vc_alloc a renvoyé 0 (mémoire épuisée)
|
||||
@msg vc_alloc returned a block outside memory vc_alloc a renvoyé un bloc hors de la mémoire
|
||||
@msg vc_run returned error code {packed} vc_run a renvoyé le code d’erreur {packed}
|
||||
@msg did not finish loading within {secs} s n’a pas fini de se charger en {secs} s
|
||||
@msg no thread was left to load it aucun fil d’exécution n’était libre pour le charger
|
||||
@msg panicked while loading a planté pendant le chargement
|
||||
@msg panicked while loading: {what} a planté pendant le chargement ({what})
|
||||
@msg {_1} is not a file {_1} n’est pas un fichier
|
||||
@msg {_1} is {_2} bytes (limit {_3}) {_1} fait {_2} octets (limite {_3})
|
||||
@msg {_1} objects (limit {MAX_OBJECTS}) {_1} objets (limite {MAX_OBJECTS})
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -9819,6 +9819,10 @@ variable-list-end {0}, {1} {0} और {1}
|
||||
@msg vc_alloc returned 0 (out of memory) vc_alloc ने 0 लौटाया (मेमोरी खत्म)
|
||||
@msg vc_alloc returned a block outside memory vc_alloc ने मेमोरी के बाहर का ब्लॉक लौटाया
|
||||
@msg vc_run returned error code {packed} vc_run ने त्रुटि कोड {packed} लौटाया
|
||||
@msg did not finish loading within {secs} s {secs} सेकंड के भीतर लोड होना पूरा नहीं हुआ
|
||||
@msg no thread was left to load it इसे लोड करने के लिए कोई थ्रेड नहीं बचा
|
||||
@msg panicked while loading लोड होते समय क्रैश हो गया
|
||||
@msg panicked while loading: {what} लोड होते समय क्रैश हो गया: {what}
|
||||
@msg VectorCraft doesn't search other apps' or the system's folders: {path} वेक्टर क्रेफ्ट अन्य एप्लिकेशन या सिस्टम के फ़ोल्डर्स की खोज नहीं करता है: {path}
|
||||
@msg VectorCraft doesn't search the Shared or Public folder in Users: {path} वेक्टर क्रेफ्ट उपयोगकर्ताओं में साझा या सार्वजनिक फ़ोल्डर की खोज नहीं करता है: {path}
|
||||
@msg VectorCraft failed to start: {e} वेक्टर क्रेफ्ट शुरू करने में विफल रहा: {e}
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -7344,6 +7344,10 @@ axis Y Axis Y tengely
|
||||
@msg vc_alloc returned 0 (out of memory) a vc_alloc 0-t adott vissza (elfogyott a memória)
|
||||
@msg vc_alloc returned a block outside memory a vc_alloc a memórián kívüli blokkot adott vissza
|
||||
@msg vc_run returned error code {packed} a vc_run {packed} hibakódot adott vissza
|
||||
@msg did not finish loading within {secs} s nem töltődött be {secs} másodpercen belül
|
||||
@msg no thread was left to load it nem maradt szál a betöltéséhez
|
||||
@msg panicked while loading összeomlott betöltés közben
|
||||
@msg panicked while loading: {what} összeomlott betöltés közben: {what}
|
||||
@msg {_1} is not a file nem fájl: {_1}
|
||||
@msg {_1} is {_2} bytes (limit {_3}) {_1}: {_2} bájt (korlát: {_3})
|
||||
@msg {_1} objects (limit {MAX_OBJECTS}) {_1} objektum (korlát: {MAX_OBJECTS})
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -457,6 +457,10 @@
|
||||
@msg vc_alloc returned 0 (out of memory) vc_alloc mengembalikan 0 (memori habis)
|
||||
@msg vc_alloc returned a block outside memory vc_alloc mengembalikan blok di luar memori
|
||||
@msg vc_run returned error code {packed} vc_run mengembalikan kode galat {packed}
|
||||
@msg did not finish loading within {secs} s tidak selesai dimuat dalam {secs} detik
|
||||
@msg no thread was left to load it tidak ada utas tersisa untuk memuatnya
|
||||
@msg panicked while loading mogok saat dimuat
|
||||
@msg panicked while loading: {what} mogok saat dimuat: {what}
|
||||
@msg {_1} is not a file {_1} bukan berkas
|
||||
@msg {_1} is {_2} bytes (limit {_3}) {_1} berukuran {_2} byte (batas {_3})
|
||||
@msg {_1} objects (limit {MAX_OBJECTS}) {_1} objek (batas {MAX_OBJECTS})
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -6981,6 +6981,10 @@ axis Y Axis Asse Y
|
||||
@msg vc_alloc returned 0 (out of memory) vc_alloc ha restituito 0 (memoria esaurita)
|
||||
@msg vc_alloc returned a block outside memory vc_alloc ha restituito un blocco fuori dalla memoria
|
||||
@msg vc_run returned error code {packed} vc_run ha restituito il codice di errore {packed}
|
||||
@msg did not finish loading within {secs} s non ha finito di caricarsi entro {secs} s
|
||||
@msg no thread was left to load it non è rimasto alcun thread per caricarlo
|
||||
@msg panicked while loading si è arrestato in modo anomalo durante il caricamento
|
||||
@msg panicked while loading: {what} si è arrestato in modo anomalo durante il caricamento: {what}
|
||||
@msg {_1} is not a file {_1} non è un file
|
||||
@msg {_1} is {_2} bytes (limit {_3}) {_1} occupa {_2} byte (limite {_3})
|
||||
@msg {_1} objects (limit {MAX_OBJECTS}) {_1} oggetti (limite {MAX_OBJECTS})
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -7056,6 +7056,10 @@ axis Y Axis Y 軸
|
||||
@msg vc_alloc returned 0 (out of memory) vc_alloc が 0 を返しました (メモリ不足)
|
||||
@msg vc_alloc returned a block outside memory vc_alloc がメモリの外のブロックを返しました
|
||||
@msg vc_run returned error code {packed} vc_run がエラーコード {packed} を返しました
|
||||
@msg did not finish loading within {secs} s {secs} 秒以内に読み込みが完了しませんでした
|
||||
@msg no thread was left to load it 読み込むためのスレッドが残っていませんでした
|
||||
@msg panicked while loading 読み込み中にパニックが発生しました
|
||||
@msg panicked while loading: {what} 読み込み中にパニックが発生しました: {what}
|
||||
@msg {_1} is not a file {_1} はファイルではありません
|
||||
@msg {_1} is {_2} bytes (limit {_3}) {_1} は {_2} バイトです (上限 {_3})
|
||||
@msg {_1} objects (limit {MAX_OBJECTS}) オブジェクトが {_1} 個あります (上限 {MAX_OBJECTS})
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -9463,6 +9463,10 @@ axis Y Axis Y ღერძი
|
||||
@msg vc_alloc returned 0 (out of memory) vc_alloc-მა დააბრუნა 0 (მეხსიერება ამოიწურა)
|
||||
@msg vc_alloc returned a block outside memory vc_alloc-მა დააბრუნა ბლოკი მეხსიერების გარეთ
|
||||
@msg vc_run returned error code {packed} vc_run-მა დააბრუნა შეცდომის კოდი {packed}
|
||||
@msg did not finish loading within {secs} s ჩატვირთვა {secs} წამში არ დასრულდა
|
||||
@msg no thread was left to load it მის ჩასატვირთად ნაკადი აღარ დარჩა
|
||||
@msg panicked while loading ჩატვირთვისას ავარიულად შეწყდა
|
||||
@msg panicked while loading: {what} ჩატვირთვისას ავარიულად შეწყდა: {what}
|
||||
@msg {_1} is not a file {_1} ფაილი არ არის
|
||||
@msg {_1} is {_2} bytes (limit {_3}) {_1} {_2} ბაიტია (ლიმიტი {_3})
|
||||
@msg {_1} objects (limit {MAX_OBJECTS}) {_1} ობიექტი (ლიმიტი {MAX_OBJECTS})
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -6953,6 +6953,10 @@ axis Y Axis Y축
|
||||
@msg vc_alloc returned 0 (out of memory) vc_alloc이 0을 반환했습니다(메모리 부족)
|
||||
@msg vc_alloc returned a block outside memory vc_alloc이 메모리 밖의 블록을 반환했습니다
|
||||
@msg vc_run returned error code {packed} vc_run이 오류 코드 {packed}을(를) 반환했습니다
|
||||
@msg did not finish loading within {secs} s {secs}초 안에 로드를 마치지 못했습니다
|
||||
@msg no thread was left to load it 로드할 스레드가 남아 있지 않았습니다
|
||||
@msg panicked while loading 로드하는 중에 비정상 종료되었습니다
|
||||
@msg panicked while loading: {what} 로드하는 중에 비정상 종료되었습니다: {what}
|
||||
@msg {_1} is not a file {_1}은(는) 파일이 아닙니다
|
||||
@msg {_1} is {_2} bytes (limit {_3}) {_1}이(가) {_2}바이트입니다(한도 {_3})
|
||||
@msg {_1} objects (limit {MAX_OBJECTS}) 개체 {_1}개(한도 {MAX_OBJECTS})
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -420,6 +420,10 @@ liquify-list-end {0}, {1} {0} en {1}
|
||||
@msg vc_alloc returned 0 (out of memory) vc_alloc gaf 0 terug (onvoldoende geheugen)
|
||||
@msg vc_alloc returned a block outside memory vc_alloc gaf een blok buiten het geheugen terug
|
||||
@msg vc_run returned error code {packed} vc_run gaf foutcode {packed} terug
|
||||
@msg did not finish loading within {secs} s was niet binnen {secs} s klaar met laden
|
||||
@msg no thread was left to load it er was geen thread meer over om het te laden
|
||||
@msg panicked while loading is tijdens het laden gecrasht
|
||||
@msg panicked while loading: {what} is tijdens het laden gecrasht: {what}
|
||||
@msg {_1} is not a file {_1} is geen bestand
|
||||
@msg {_1} is {_2} bytes (limit {_3}) {_1} is {_2} bytes (limiet {_3})
|
||||
@msg {_1} objects (limit {MAX_OBJECTS}) {_1} objecten (limiet {MAX_OBJECTS})
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -7214,6 +7214,10 @@ axis Y Axis Oś Y
|
||||
@msg vc_alloc returned 0 (out of memory) vc_alloc zwróciła 0 (brak pamięci)
|
||||
@msg vc_alloc returned a block outside memory vc_alloc zwróciła blok poza pamięcią
|
||||
@msg vc_run returned error code {packed} vc_run zwróciła kod błędu {packed}
|
||||
@msg did not finish loading within {secs} s nie zakończył wczytywania w ciągu {secs} s
|
||||
@msg no thread was left to load it nie został żaden wątek, który mógłby go wczytać
|
||||
@msg panicked while loading uległ awarii podczas wczytywania
|
||||
@msg panicked while loading: {what} uległ awarii podczas wczytywania: {what}
|
||||
@msg {_1} is not a file {_1} nie jest plikiem
|
||||
@msg {_1} is {_2} bytes (limit {_3}) {_1} ma {_2} bajtów (limit {_3})
|
||||
@msg {_1} objects (limit {MAX_OBJECTS}) {_1} obiektów (limit {MAX_OBJECTS})
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -7258,6 +7258,10 @@ axis Y Axis Eixo Y
|
||||
@msg vc_alloc returned 0 (out of memory) vc_alloc retornou 0 (sem memória)
|
||||
@msg vc_alloc returned a block outside memory vc_alloc retornou um bloco fora da memória
|
||||
@msg vc_run returned error code {packed} vc_run retornou o código de erro {packed}
|
||||
@msg did not finish loading within {secs} s não terminou de carregar em {secs} s
|
||||
@msg no thread was left to load it não restou nenhuma thread para carregá-lo
|
||||
@msg panicked while loading falhou inesperadamente ao carregar
|
||||
@msg panicked while loading: {what} falhou inesperadamente ao carregar: {what}
|
||||
@msg {_1} is not a file {_1} não é um arquivo
|
||||
@msg {_1} is {_2} bytes (limit {_3}) {_1} tem {_2} bytes (limite {_3})
|
||||
@msg {_1} objects (limit {MAX_OBJECTS}) {_1} objetos (limite {MAX_OBJECTS})
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -6980,6 +6980,10 @@ axis Y Axis Ось Y
|
||||
@msg vc_alloc returned 0 (out of memory) vc_alloc вернула 0 (нехватка памяти)
|
||||
@msg vc_alloc returned a block outside memory vc_alloc вернула блок вне памяти
|
||||
@msg vc_run returned error code {packed} vc_run вернула код ошибки {packed}
|
||||
@msg did not finish loading within {secs} s не завершил загрузку за {secs} с
|
||||
@msg no thread was left to load it не осталось потока, чтобы его загрузить
|
||||
@msg panicked while loading аварийно завершился при загрузке
|
||||
@msg panicked while loading: {what} аварийно завершился при загрузке: {what}
|
||||
@msg {_1} is not a file {_1} не является файлом
|
||||
@msg {_1} is {_2} bytes (limit {_3}) {_1} занимает {_2} байт (предел {_3})
|
||||
@msg {_1} objects (limit {MAX_OBJECTS}) объектов: {_1} (предел {MAX_OBJECTS})
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -10134,6 +10134,10 @@ digits Hindi Hindi
|
||||
@msg vc_alloc returned 0 (out of memory) vc_alloc returnerade 0 (slut på minne)
|
||||
@msg vc_alloc returned a block outside memory vc_alloc returnerade ett block utanför minnet
|
||||
@msg vc_run returned error code {packed} vc_run returnerade felkoden {packed}
|
||||
@msg did not finish loading within {secs} s blev inte färdigläst inom {secs} s
|
||||
@msg no thread was left to load it ingen tråd fanns kvar som kunde läsa in den
|
||||
@msg panicked while loading kraschade under inläsningen
|
||||
@msg panicked while loading: {what} kraschade under inläsningen: {what}
|
||||
@msg view is required view krävs
|
||||
@msg view must be one of {_1} view måste vara något av {_1}
|
||||
@msg warpStyle can only edit an applied Warp effect warpStyle kan bara redigera en tillämpad Förvräng-effekt
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -7431,6 +7431,10 @@ axis Y Axis Y ekseni
|
||||
@msg vc_alloc returned 0 (out of memory) vc_alloc 0 döndürdü (bellek yetersiz)
|
||||
@msg vc_alloc returned a block outside memory vc_alloc bellek dışında bir blok döndürdü
|
||||
@msg vc_run returned error code {packed} vc_run {packed} hata kodunu döndürdü
|
||||
@msg did not finish loading within {secs} s {secs} sn içinde yüklenmeyi bitirmedi
|
||||
@msg no thread was left to load it onu yükleyecek iş parçacığı kalmadı
|
||||
@msg panicked while loading yüklenirken çöktü
|
||||
@msg panicked while loading: {what} yüklenirken çöktü: {what}
|
||||
@msg {_1} is not a file {_1} bir dosya değil
|
||||
@msg {_1} is {_2} bytes (limit {_3}) {_1} {_2} bayt (sınır {_3})
|
||||
@msg {_1} objects (limit {MAX_OBJECTS}) {_1} nesne (sınır {MAX_OBJECTS})
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -6963,6 +6963,10 @@ axis Y Axis Вісь Y
|
||||
@msg vc_alloc returned 0 (out of memory) vc_alloc повернула 0 (бракує пам’яті)
|
||||
@msg vc_alloc returned a block outside memory vc_alloc повернула блок поза пам’яттю
|
||||
@msg vc_run returned error code {packed} vc_run повернула код помилки {packed}
|
||||
@msg did not finish loading within {secs} s не завершив завантаження за {secs} с
|
||||
@msg no thread was left to load it не залишилося потоку, щоб його завантажити
|
||||
@msg panicked while loading аварійно завершився під час завантаження
|
||||
@msg panicked while loading: {what} аварійно завершився під час завантаження: {what}
|
||||
@msg {_1} is not a file {_1} не є файлом
|
||||
@msg {_1} is {_2} bytes (limit {_3}) {_1} займає {_2} байтів (межа {_3})
|
||||
@msg {_1} objects (limit {MAX_OBJECTS}) об’єктів: {_1} (межа {MAX_OBJECTS})
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -7009,6 +7009,10 @@ axis Y Axis Trục Y
|
||||
@msg vc_alloc returned 0 (out of memory) vc_alloc trả về 0 (hết bộ nhớ)
|
||||
@msg vc_alloc returned a block outside memory vc_alloc trả về một khối nằm ngoài bộ nhớ
|
||||
@msg vc_run returned error code {packed} vc_run trả về mã lỗi {packed}
|
||||
@msg did not finish loading within {secs} s không tải xong trong vòng {secs} giây
|
||||
@msg no thread was left to load it không còn luồng nào để tải nó
|
||||
@msg panicked while loading gặp sự cố khi đang tải
|
||||
@msg panicked while loading: {what} gặp sự cố khi đang tải: {what}
|
||||
@msg {_1} is not a file {_1} không phải là tệp
|
||||
@msg {_1} is {_2} bytes (limit {_3}) {_1} có {_2} byte (giới hạn {_3})
|
||||
@msg {_1} objects (limit {MAX_OBJECTS}) {_1} đối tượng (giới hạn {MAX_OBJECTS})
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -7191,6 +7191,10 @@ axis Y Axis Y 轴
|
||||
@msg vc_alloc returned 0 (out of memory) vc_alloc 返回了 0(内存不足)
|
||||
@msg vc_alloc returned a block outside memory vc_alloc 返回了内存之外的块
|
||||
@msg vc_run returned error code {packed} vc_run 返回了错误代码 {packed}
|
||||
@msg did not finish loading within {secs} s 未在 {secs} 秒内完成加载
|
||||
@msg no thread was left to load it 没有剩余的线程来加载它
|
||||
@msg panicked while loading 加载时崩溃
|
||||
@msg panicked while loading: {what} 加载时崩溃:{what}
|
||||
@msg {_1} is not a file {_1} 不是文件
|
||||
@msg {_1} is {_2} bytes (limit {_3}) {_1} 为 {_2} 字节(上限 {_3})
|
||||
@msg {_1} objects (limit {MAX_OBJECTS}) {_1} 个对象(上限 {MAX_OBJECTS})
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -7012,6 +7012,10 @@ axis Y Axis Y 軸
|
||||
@msg vc_alloc returned 0 (out of memory) vc_alloc 傳回了 0(記憶體不足)
|
||||
@msg vc_alloc returned a block outside memory vc_alloc 傳回了記憶體之外的區塊
|
||||
@msg vc_run returned error code {packed} vc_run 傳回了錯誤代碼 {packed}
|
||||
@msg did not finish loading within {secs} s 未在 {secs} 秒內完成載入
|
||||
@msg no thread was left to load it 沒有剩餘的執行緒可以載入它
|
||||
@msg panicked while loading 載入時當機
|
||||
@msg panicked while loading: {what} 載入時當機:{what}
|
||||
@msg {_1} is not a file {_1} 不是檔案
|
||||
@msg {_1} is {_2} bytes (limit {_3}) {_1} 為 {_2} 位元組(上限 {_3})
|
||||
@msg {_1} objects (limit {MAX_OBJECTS}) {_1} 個物件(上限 {MAX_OBJECTS})
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -66,6 +66,9 @@ pub fn export(app: &mut VectorcraftApp, format: Option<&str>, path: Option<Strin
|
||||
let params = &if params.is_object() { params.clone() } else { json!({}) };
|
||||
let (selection, params) = take_selection(params)?;
|
||||
let params = ¶ms;
|
||||
// An exporter plug-in, or a live effect's, that the launch is still loading is installed
|
||||
// before the format is looked up and the document drawn.
|
||||
app.session.finish_plugin_loads();
|
||||
let f = fileio::writable_format(format, path.as_deref())?;
|
||||
// A Shape Builder merge still being computed for a click is exported with the document.
|
||||
let r = app.session.finish_tool_edit();
|
||||
|
||||
@@ -390,6 +390,8 @@ fn open_dialog_folder(app: &VectorcraftApp) -> Option<String> {
|
||||
|
||||
/// File → Open…: `{pending: "fileDialog"}` while its picker is open.
|
||||
pub fn open_dialog(app: &mut VectorcraftApp) -> Result<Value, String> {
|
||||
// The picker lists the extensions of the importer plug-ins the launch is still loading too.
|
||||
app.session.finish_plugin_loads();
|
||||
let request = open_request("document", open_dialog_folder(app), fileio::open_filters());
|
||||
ask_open(app, request, Owner::Free, |app, path| open_reporting(app, &path))
|
||||
}
|
||||
@@ -559,6 +561,11 @@ pub(crate) fn open_file(app: &mut VectorcraftApp, path: &str, background: bool)
|
||||
fn open_file_with(app: &mut VectorcraftApp, path: &str, background: bool, p: &Value) -> Result<Value, String> {
|
||||
// Automation confined to some folders reaches no file outside them, open in a tab or not.
|
||||
vectorcraft_engine::file_access::check_read(path)?;
|
||||
// A plug-in still loading may be the importer that reads the file, or what installs it.
|
||||
app.session.finish_plugin_loads();
|
||||
// The path is checked again after the wait, so a link replaced while the plug-ins loaded
|
||||
// doesn't lead the read outside the folders.
|
||||
vectorcraft_engine::file_access::check_read(path)?;
|
||||
// File › Open, Open Recent, the Home screen, a drop and the Finder all focus a document that
|
||||
// is already open, or still being read, instead of opening a second copy. While a dialog or
|
||||
// a drag acts on the active document, its tab comes to the front once that ends
|
||||
|
||||
@@ -79,6 +79,12 @@ pub fn invoke(app: &mut VectorcraftApp, id: &str, p: Value) {
|
||||
// (Recolor Artwork), opens on the art as the gesture left it.
|
||||
let r = app.session.finish_tool_edit();
|
||||
crate::canvas::apply_requests(app, r);
|
||||
// So do the plug-ins the launch is still loading, for a command chosen meanwhile that the
|
||||
// engine holds until they install (a plug-in's own command, one that may edit); view commands
|
||||
// and queries go ahead.
|
||||
if vectorcraft_engine::waits_for_plugin_loads(id) {
|
||||
app.session.finish_plugin_loads();
|
||||
}
|
||||
// A shortcut or a palette pick on a filter plug-in does nothing while its menu item is dimmed.
|
||||
if id == "plugin.dialog" && !enabled(app, id) {
|
||||
return;
|
||||
|
||||
@@ -77,6 +77,8 @@ pub fn start(app: &mut VectorcraftApp, path: &str, bytes: Vec<u8>) -> Value {
|
||||
|
||||
/// [`start`] with the `document.open` options in `params` (`importer` and its `params`).
|
||||
pub fn start_with(app: &mut VectorcraftApp, path: &str, bytes: Vec<u8>, params: Value) -> Value {
|
||||
// A plug-in still loading may be the importer that reads the file.
|
||||
app.session.finish_plugin_loads();
|
||||
let (tx, done) = channel();
|
||||
let name = path.to_string();
|
||||
// Update Links (Preferences › File Handling) applies there as it is set now.
|
||||
|
||||
@@ -871,8 +871,9 @@ pub struct UiState {
|
||||
/// show first.
|
||||
#[serde(skip)]
|
||||
pub pending_fonts: Vec<u64>,
|
||||
/// The plug-in (`{id, file, name, label}`) the last launch was loading when it stopped, while
|
||||
/// the user has not chosen what to do about it.
|
||||
/// The plug-ins the last launch was loading when it stopped (`{item, items}`, each
|
||||
/// `{id, file, name, label}`, `item` the first of `items`), while the user has not chosen what
|
||||
/// to do about them.
|
||||
#[serde(skip)]
|
||||
pub stopped_plugin: Option<Value>,
|
||||
/// The open Proof Setup dialog's record: the proof view it found and the one its preview
|
||||
|
||||
@@ -172,6 +172,51 @@ fn disable_and_continue_loads_every_plug_in_but_the_one_that_was_loading() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A marker left by a launch that stopped while the stored plug-ins x and y were both loading.
|
||||
fn stopped_while_loading_both(launch: &Path, dir: &Path) {
|
||||
let file = |tag: &str| {
|
||||
let p = std::fs::read_dir(dir).unwrap().flatten().map(|e| e.path()).find(|p| p.to_string_lossy().contains(tag)).unwrap();
|
||||
json!({"file": p.display().to_string()})
|
||||
};
|
||||
let (x, y) = (file("test_ui_x"), file("test_ui_y"));
|
||||
let marker = json!({"format": "vectorcraft-launch", "version": 1, "item": x, "items": [x, y]});
|
||||
std::fs::create_dir_all(launch).unwrap();
|
||||
std::fs::write(launch.join("launch-1-dead.json"), marker.to_string()).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_launch_that_stopped_while_two_plug_ins_loaded_offers_to_disable_both() {
|
||||
let _f = fresh();
|
||||
let dir = store_with_two("both");
|
||||
let launch_dir = dir.join("Launch");
|
||||
stopped_while_loading_both(&launch_dir, &dir);
|
||||
let mut app = launch(&dir, &launch_dir, false);
|
||||
let ctx = window();
|
||||
frame(&mut app, &ctx);
|
||||
assert!(ui::choosing(&app));
|
||||
let listed = |app: &VectorcraftApp| app.ui.stopped_plugin.as_ref().and_then(|f| f["items"].as_array().map(Vec::len));
|
||||
assert_eq!(listed(&app), Some(2), "both are listed");
|
||||
let state = app.run("plugin.safeMode", json!({})).unwrap();
|
||||
assert_eq!(state["pendingItems"].as_array().map(Vec::len), Some(2), "{state}");
|
||||
assert_eq!(state["pendingItem"], state["pendingItems"][0]);
|
||||
// Start in Safe Mode leaves both to the next launch.
|
||||
let reply = control(&mut app, &ctx, "ui.dialog.cancel", json!({}));
|
||||
assert_eq!(reply["ok"], true, "{reply}");
|
||||
assert!(!ui::choosing(&app) && registry::list().is_empty());
|
||||
ui::end_launch();
|
||||
safe_mode::set_active(None);
|
||||
let mut app = launch(&dir, &launch_dir, false);
|
||||
let ctx = window();
|
||||
frame(&mut app, &ctx);
|
||||
assert_eq!(listed(&app), Some(2), "both asked again");
|
||||
confirm(&mut app, &ctx);
|
||||
assert!(!safe_mode::active() && safe_mode::previous().is_empty());
|
||||
assert!(registry::get("test.ui.x").is_none() && registry::get("test.ui.y").is_none(), "both are off");
|
||||
assert_eq!(safe_mode::disabled().len(), 2, "both kept off at later launches");
|
||||
done(&launch_dir);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn start_normally_loads_everything_and_start_in_safe_mode_loads_nothing() {
|
||||
let _f = fresh();
|
||||
@@ -225,7 +270,7 @@ fn a_disabled_list_that_cannot_be_saved_says_so() {
|
||||
asking_frames(&mut app, &ctx);
|
||||
confirm(&mut app, &ctx);
|
||||
assert_eq!(app.ui.status, unsaved, "Disable and Continue");
|
||||
assert!(safe_mode::previous().is_some(), "the next launch asks again");
|
||||
assert!(!safe_mode::previous().is_empty(), "the next launch asks again");
|
||||
assert!(registry::get("test.ui.x").is_none(), "this launch still skips it");
|
||||
app.ui.status.clear();
|
||||
app.run("help.safeMode", json!({})).unwrap();
|
||||
@@ -300,7 +345,7 @@ fn a_safe_mode_flag_launch_leaves_the_stopped_plug_in_to_the_next_launch() {
|
||||
let ctx = window();
|
||||
frame(&mut app, &ctx);
|
||||
assert!(!ui::choosing(&app) && registry::list().is_empty(), "--safe-mode asks nothing");
|
||||
assert!(safe_mode::previous().is_some(), "the plug-in is still pending");
|
||||
assert!(!safe_mode::previous().is_empty(), "the plug-in is still pending");
|
||||
ui::end_launch();
|
||||
safe_mode::set_active(None);
|
||||
|
||||
|
||||
+8
-6
@@ -301,9 +301,9 @@ the suite) keep the agent to the folders you give it:
|
||||
outside the read roots, also those the person or an earlier request put there. In `plugin.list`, the plug-in
|
||||
folder last loaded is `null` in `folder.folder`, and a failed file in `folder.failed` and a plug-in's `source`
|
||||
(also in `plugin.info`) are named by their file name, in the errors too. A plug-in turned off for the next
|
||||
launch (`disabled`, and `pendingItem` in `plugin.safeMode`) has a file outside the read roots named by its file
|
||||
name. `plugin.setEnabled {file}` takes that name, and a plug-in's `source` name, when no other listed file has
|
||||
it. In `file.recovery.list` and `file.recovery.restore`, a
|
||||
launch (`disabled`, and `pendingItem` and `pendingItems` in `plugin.safeMode`) has a file outside the read roots
|
||||
named by its file name. `plugin.setEnabled {file}` takes that name, and a plug-in's `source` name, when no other
|
||||
listed file has it. In `file.recovery.list` and `file.recovery.restore`, a
|
||||
document's original file in `path` is `null`, and so is the recovery folder in `location` (`file.recovery.save`
|
||||
too); the restored documents keep their files. In `scriptReport`, a file the run wrote (`written`) and the
|
||||
included file a failed run stopped in (`file`, also in `message` and the run's error lines in `console`) are named
|
||||
@@ -13673,8 +13673,9 @@ commands, `ids` left out or null means the selection, and an `ids` that is not a
|
||||
|
||||
Safe Mode starts VectorCraft without plug-ins: `vectorcraft --safe-mode`, `vectorcraft-cli --safe-mode <subcommand>`, or
|
||||
the choice the desktop app offers when the last launch stopped while a plug-in was loading (Disable and Continue, Start
|
||||
Normally, Start in Safe Mode). It names that plug-in without saying it caused the stop. Until the user picks Disable and
|
||||
Continue or Start Normally, the next launch asks again, also after a `--safe-mode` launch, which asks nothing.
|
||||
Normally, Start in Safe Mode). It names that plug-in without saying it caused the stop. When several plug-ins were
|
||||
loading at once, it lists all of them, and Disable Listed Plug-ins and Continue turns off every one. Until the user picks
|
||||
Disable and Continue or Start Normally, the next launch asks again, also after a `--safe-mode` launch, which asks nothing.
|
||||
`vectorcraft --safe-mode` opens its files in a window of its own, and on Windows and Linux a file opened from the file
|
||||
manager while the app is in Safe Mode starts a window with plug-ins. Files given on the command line, or opened from
|
||||
the file manager while the choice is up, open after the user picks. On Windows and Linux, when the choice is Start in Safe
|
||||
@@ -13688,7 +13689,8 @@ visible plain symbol instance in a group or layer with a raster effect, since th
|
||||
hidden instance, or one in a template sublayer, draws nothing in that image, so its symbol's art does not count. `vectorcraft` rejects an option it does not know (such as
|
||||
`--safe-mod`) instead of opening it as a file; `--` before a file name that starts with `-` opens it. The web build keeps
|
||||
no installed plug-ins from one page load to the next and has no launch marker, so it never offers the choice. `plugin.safeMode` returns `{active, source, disabled,
|
||||
pendingItem}`; a command does not turn Safe Mode on or off. `plugin.setEnabled {id | file, enabled}` turns a plug-in on or
|
||||
pendingItem, pendingItems}` (`pendingItems` lists every plug-in the choice names, and `pendingItem` is the first);
|
||||
a command does not turn Safe Mode on or off. `plugin.setEnabled {id | file, enabled}` turns a plug-in on or
|
||||
off for the next launch, as Help › Safe Mode's Enable on Re-launch does; it does not load, unload or uninstall anything
|
||||
now, and `plugin.install` of a disabled plug-in turns it on. Turning a plug-in on by `id` or by installing it also turns
|
||||
on the file it is stored in, which names it when it stopped a launch while loading; when the new version can't be saved
|
||||
|
||||
+23
-1
@@ -149,6 +149,25 @@ most 1,000 `.wasm` files, the first ones by file name (VectorCraft's own limit);
|
||||
(`leftOut`). An entry that is not a regular file, such as a subfolder or a named pipe with a `.wasm` name, is listed in
|
||||
the report and skipped, and the load does not wait on a named pipe.
|
||||
|
||||
**Loading.** On the desktop, the plug-ins in the `Plug-ins` folder and the Additional Plug-ins Folder load on up to four
|
||||
worker threads and install in file-name order, whatever order their loads finish in; at most eight loaded modules wait
|
||||
to be installed at once. When the desktop app starts, its window shows while they load, and they install as their loads
|
||||
finish. Plug-in commands, commands that edit a document, exports, File › Open, control-channel requests and files
|
||||
opened at launch wait for them first; view commands and queries chosen from a menu do not. Until then a live effect
|
||||
whose plug-in is still loading is drawn as if it weren't there, and another window's `plugin.list` reports the folder
|
||||
as `{"folder", "loading": true}`. A folder set later in Preferences, `vectorcraft-cli` and `plugin.reload` wait for
|
||||
the loads before they go on. A module whose load panics is reported as failed or skipped with a log record, and the
|
||||
others install. So is a module whose read and load take 10 s or longer (VectorCraft's own limit), also one that would have
|
||||
finished later, such as a module on a slow network share. The launch marker names every module still loading, so when
|
||||
the app stops during the loads, the next launch's Safe Mode choice lists all of them. A module whose load panicked or
|
||||
failed is no longer named; one past its 10 s limit is named until its load returns. A module is also skipped when the
|
||||
plug-in with its id was installed or removed in another window while it loaded. A module from the `Plug-ins` folder
|
||||
installs only when its file, read again on the worker thread after the module loaded, still holds that module, whatever
|
||||
the file's modified time. When a file fails because no thread was left to load it, the Additional Plug-ins Folder is
|
||||
loaded again the next time the preferences are applied. When the app quits while plug-ins are
|
||||
loading, it waits for the modules already loading, for at most 10 s, before it exits. The web build loads one
|
||||
module at a time.
|
||||
|
||||
Plug-ins are installed **per process**, not per document. Documents store a live effect as an ordinary effect record
|
||||
(`{"id": "plugin.<id>", "params": {…}}`): while the plug-in is installed it is drawn, exported and expanded; without it
|
||||
the object is drawn as if the effect weren't there, and the record is kept for when the plug-in comes back.
|
||||
@@ -340,7 +359,10 @@ capability model proposed for PhotoCraft plug-ins
|
||||
and `plugin.remove` removes the plug-in. A `grants.json` that can't be opened or read counts as a grant that can't be
|
||||
removed. When VectorCraft loads the `Plug-ins` folder, it forgets any grant for an id whose stored module lists no
|
||||
permissions. When it can't remove that grant from `grants.json`, or can't read the file, the grant stops counting,
|
||||
including for the next load, which tries the removal again. A grant that stops counting in either of these cases
|
||||
including for the next load, which tries the removal again. When a later file in the folder holds a module with the
|
||||
same id that the forgotten grant covers, the grant is written back and that module installs. When the grant can't be
|
||||
written back, that module is skipped, and when the module doesn't install, the grant is removed again. A grant that
|
||||
stops counting in either of these cases
|
||||
does not count for any session in the same process that uses the same `Plug-ins` folder, by any path to it, until
|
||||
`grants.json` can be written for that plug-in, as when the plug-in is granted again. Another process on the same
|
||||
folder, for example `vectorcraft-cli` beside the app, still reads `grants.json` as it is written. A grant for the
|
||||
|
||||
Reference in new issue
Block a user