From f8bbfae755a016376045b3c955c04d6ee0f301ee Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 23:04:22 -0800 Subject: [PATCH] Plug-ins: a stored file whose read fails gives back its share of the store's bytes - crates/engine/src/store.rs: each stored plug-in's load reports how much of its file it read. What a failed read did not read goes back to the 512 MiB the stored plug-ins may read together, on every platform; the permission check before the loads is removed. A file that what is left does not cover, but would if earlier reads failed, waits until those reads are done, so the files still install in file-name order. Disabled files and file stamps are taken once, when the store is listed. A file's content is compared with its loaded module at install only when the file was modified less than 2 s before the store was listed; the clock is read only when a file was listed. A grant the load removed goes back for a later file with the same id only when the grants file has no entry for the id, and each install turn reads the grants file once. At quit, a stored load takes no locks and a folder load does not wait for the store's turn or for another window that is changing the plug-ins. - crates/engine/src/cmd/plugin.rs and crates/plugins/src/registry.rs: when a folder load turns off the file of a plug-in disabled by its id, the disabled list is saved in the same install turn, not only when the load ends. A change made in another window while the folder is being listed is one the load does not undo. - crates/ui-egui: an export and File > Open install the plug-ins still loading before they look up the formats, and a control request waiting for the loads no longer asks for a frame of its own. - crates/engine/src/file_access.rs: `ScopeHandle::capture` is as on `main` again. The new `ScopeHandle::capture_now` keeps the process's automation roots in force at capture time, and only the Additional Plug-ins Folder's per-file check uses it. - New tests: a stored file replaced with one of the same length and modified time while it loaded is skipped; another window's `plugin.list` reports a folder still loading as loading; a grant given elsewhere after the load removed one is kept. - docs/plugins.md: a module whose read and load take 10 s or longer is skipped also when it would have finished later, and at quit the app waits for the modules already loading, for at most 10 s. File > Open waits for the loads. The Loading paragraph and the docs/mcp.md lines are rewrapped. --- crates/engine/src/cmd/plugin.rs | 9 +- crates/engine/src/file_access.rs | 40 ++-- crates/engine/src/store.rs | 291 ++++++++++++++++++++++------- crates/engine/src/tests/plugins.rs | 126 +++++++++++++ crates/plugins/src/registry.rs | 31 +-- crates/ui-egui/src/app/control.rs | 4 +- crates/ui-egui/src/io/export.rs | 5 +- crates/ui-egui/src/io/open.rs | 2 + docs/mcp.md | 9 +- docs/plugins.md | 21 ++- 10 files changed, 423 insertions(+), 115 deletions(-) diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index f34f8cdfa8..54ede6d1a7 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -1180,8 +1180,9 @@ fn start_folder(s: &Session, folder: &str, record: Option) -> FolderPending 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). - let scope = crate::file_access::ScopeHandle::capture(); + // 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), @@ -1214,6 +1215,10 @@ pub(crate) fn install_folder(s: &mut Session, load: &mut FolderPending, turn: &S 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); diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index 31baf206fe..79c831a58d 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -240,10 +240,16 @@ fn resolved(scope: Option, process: Option<&Arc>) -> Sco pub struct ScopeHandle(Option, Option>, bool); impl ScopeHandle { - /// The scope of the calling thread. A thread with no scope of its own takes the process's - /// roots as they are now ([`confine_process`]), so work captured before the process is confined - /// stays unconfined on the thread that runs it. + /// The scope of the calling thread. pub fn capture() -> Self { + 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)) } @@ -1167,23 +1173,21 @@ mod tests { let _ = std::fs::remove_dir_all(base); } - /// A scope captured on a thread without one keeps the process's roots as they were then: work - /// captured before the process was confined stays unconfined, and work captured after is - /// confined. + /// 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_captured_scope_keeps_the_process_roots_of_its_time() { - let (base, roots) = folders("captured"); + 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 before = ScopeHandle(Some(resolved(None, None)), None, false); - let after = ScopeHandle(Some(resolved(None, Some(&roots))), None, false); - confine(Some(&roots), || { - assert_eq!(before.run(|| check_read(&outside)), Ok(()), "captured before the roots were in force"); - }); - assert!(after.run(|| check_read(&outside)).is_err(), "captured while the roots were in force"); - // No test confines the process, so a thread without a scope captures an unconfined one, - // which roots put in force later don't narrow. - let captured = std::thread::spawn(ScopeHandle::capture).join().unwrap(); - assert!(matches!(captured.0, Some(Scope::Unconfined)), "{captured:?}"); + 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); } diff --git a/crates/engine/src/store.rs b/crates/engine/src/store.rs index aafe8ae1bc..c5a1aa170a 100644 --- a/crates/engine/src/store.rs +++ b/crates/engine/src/store.rs @@ -172,6 +172,29 @@ fn list_files(dir: &Path, ext: &str) -> Vec { 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, String> { let bytes = read_past_cap(path, max).map_err(|e| e.to_string())?; @@ -227,13 +250,13 @@ impl PluginLoad { /// Whether every module has been installed or skipped. fn done(&self) -> bool { match self { - PluginLoad::Stored(load) => load.next == load.files.len(), + 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. - fn ready(&mut self) -> bool { + 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(), @@ -258,6 +281,7 @@ impl PluginLoad { load.loads = Loads::deferred(Vec::new()); load.loaded.clear(); load.next = load.files.len(); + load.rest.clear(); } PluginLoad::Folder(load) => load.cancel(), } @@ -271,14 +295,18 @@ impl PluginLoad { } } +/// A stored plug-in file, with its stamp when it was listed ([`file_stamp`]; `None`: it couldn't be +/// read). +type StoredFile = (PathBuf, Option); + /// The stored plug-ins loading from the plug-in store `dir`. pub(crate) struct StoredLoad { dir: PathBuf, - /// Each file, with its stamp when it was listed ([`file_stamp`]; `None`: it couldn't be read). - files: Vec<(PathBuf, Option)>, - loads: Loads, + /// The files listed, in file-name order. + files: Vec, + loads: Loads, /// Outcomes taken from `loads` and not installed yet, in order. - loaded: VecDeque>, + loaded: VecDeque>, /// 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 @@ -288,6 +316,22 @@ pub(crate) struct StoredLoad { /// 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, + /// 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, + /// When the store was listed. + listed: SystemTime, +} + +/// 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, } /// Tests: what runs before a stored module is read, given its path. @@ -306,11 +350,79 @@ fn before_stored_load(path: &Path) { } } +#[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 = 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, left: &mut u64) -> (Vec, Vec>) { + 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), + }; + // 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 { @@ -627,61 +739,42 @@ impl Session { if safe_mode::active() { return; } - let limits = vectorcraft_plugins::Limits::default(); - let mut left = MAX_PLUGIN_STORE; - let mut files = Vec::new(); - let mut jobs = Vec::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 = 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()); - continue; + } 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)))); } - // Each file takes its listed length from what the files before it left of the total, - // and its load reads no more than that. - let cap = (limits.max_module_bytes as u64).min(left); - let stamp = file_stamp(&path); - let len = match &stamp { - Ok(Some((len, _))) if *len <= cap => *len, - Ok(Some(_)) => { - log::warn!("skipping the stored plug-in {}: {}", path.display(), too_large(cap)); - continue; - } - Ok(None) => continue, - Err(e) => { - log::warn!("skipping the stored plug-in {}: {e}", path.display()); - continue; - } - }; - // A file this process may not read takes nothing from the total, as one that couldn't - // be read didn't when the files were read one after the other. - #[cfg(not(target_arch = "wasm32"))] - if let Err(e) = vectorcraft_plugins::registry::may_read(&path) { - log::warn!("skipping the stored plug-in {}: {e}", path.display()); - continue; - } - left -= len; - let (read, limits) = (path.clone(), limits.clone()); - jobs.push(Job::new(Some(item), move || { - #[cfg(test)] - before_stored_load(&read); - let bytes = read_capped(&read, len).map_err(vectorcraft_plugins::Error::Io)?; - vectorcraft_plugins::Plugin::load(&bytes, limits) - })); - files.push((path, stamp.ok())); } + // The clock is read only when a file was listed: the web build has no wall clock, and no + // file to list. + let listed = if rest.is_empty() { SystemTime::UNIX_EPOCH } else { SystemTime::now() }; + 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 }; + let load = StoredLoad { + dir, + files, + loads: Loads::deferred(jobs), + loaded: VecDeque::new(), + next: 0, + retired: BTreeMap::new(), + changes, + rest, + left, + listed, + }; self.queue_plugin_load(PluginLoad::Stored(load)); } @@ -689,23 +782,58 @@ impl Session { /// 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(); - let mut grants = self.counted_grants(&dir); + // 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 = BTreeMap::new(); + let named = |written: &BTreeMap, 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 + }); if file_stamp(path).ok() != *stamp { log::warn!("skipping the stored plug-in {}: it changed or went away while it loaded", path.display()); continue; } match loaded { - // A file replaced by one of the same length within the clock's resolution keeps its - // stamp: its content is compared too. - Ok(plugin) if !holds_module(path, stamp.flatten().map_or(0, |(len, _)| len), plugin.hash()) => { + // A file modified less than 2 s (the coarsest file-system clock) before the store was + // listed may have been replaced by one of the same length that kept its stamp: its + // content is compared too. + Ok(plugin) if stamp.flatten().is_some_and(|(len, at)| near(at, load.listed) && !holds_module(path, len, plugin.hash())) => { log::warn!("skipping the stored plug-in {}: it changed or went away while it loaded", path.display()); } Ok(plugin) if load.changes.superseded(plugin.id()) => { @@ -716,13 +844,18 @@ impl Session { Ok(plugin) if plugin.manifest().asks_permissions() => { let m = plugin.manifest(); let stored = grants.get(&m.id).filter(|g| grant_covers(g, &plugin)).cloned(); - let back = stored.is_none().then(|| load.retired.get(&m.id).filter(|g| grant_covers(g, &plugin)).cloned()).flatten(); + // 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) => { // A grant this load removed for an earlier file with the id goes back. if back.is_some() { load.retired.remove(&m.id); if self.store_grant_in(turn, &m.id, Some(g.clone())) { + written.insert(m.id.clone(), true); grants.insert(m.id.clone(), g.clone()); } else { log::warn!("couldn't put back the grant for the stored plug-in {}", path.display()); @@ -753,9 +886,11 @@ impl Session { if let Some(g) = grants.remove(&id) { load.retired.insert(id.clone(), g); } - if self.holds_plugin_grant(&id) { + if named(&written, &id) { let writes = self.grant_writes(); - if !self.store_grant_in(turn, &id, None) && self.holds_plugin_grant(&id) { + 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); } } @@ -815,13 +950,29 @@ impl Session { /// 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, in turns on the store: the grant - /// for an id whose installed module lists no permissions is forgotten. + /// 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(); - let held = crate::cmd::plugin::hold_plugin_changes(); - let turn = self.plugin_install_turn(load.creates_store()); + // 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)); } @@ -1024,8 +1175,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 { + 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, + ) -> BTreeMap { 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); @@ -1441,6 +1601,11 @@ fn holds_module(path: &Path, len: u64, hash: &str) -> bool { read_capped(path, len).is_ok_and(|bytes| vectorcraft_plugins::permissions::sha256_hex(&bytes) == hash) } +/// Whether the modified time `at` is less than 2 s before `then`, or later. +fn near(at: SystemTime, then: SystemTime) -> bool { + then.duration_since(at).map_or(true, |before| before < std::time::Duration::from_secs(2)) +} + /// The stamp of the file at `path`. fn file_stamp(path: &Path) -> Result { match std::fs::metadata(path) { diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index a8368dc7c2..8cc8b9e5be 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -2107,6 +2107,95 @@ fn unreadable_stored_files_leave_the_store_budget_to_the_others() { 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 modified moments ago and replaced after its module loaded, by one of the same +/// length with the same modified time, is skipped when the loads install: its content no longer +/// holds the module. +#[test] +fn a_stored_file_replaced_with_the_same_stamp_while_it_loaded_is_skipped() { + let id = "test.engine.background.replaced"; + let (folder, path) = store_with("plugin-background-replaced", id); + // A modified time ahead of the clock counts as moments ago however long the test takes. + let modified = std::time::SystemTime::now() + std::time::Duration::from_secs(3600); + std::fs::File::options().write(true).open(&path).unwrap().set_modified(modified).unwrap(); + let mut s = session(); + s.load_plugins_in_background(true); + s.attach_plugin_store(folder.0.clone()); + { + // Nothing installs while the plug-in changes are held. + let _held = crate::cmd::plugin::hold_plugin_changes(); + let load = s.plugin_loads.front_mut().expect("attaching the store queued a load"); + while !load.ready() { + std::thread::yield_now(); + } + let mut bytes = std::fs::read(&path).unwrap(); + bytes.reverse(); + std::fs::write(&path, &bytes).unwrap(); + std::fs::File::options().write(true).open(&path).unwrap().set_modified(modified).unwrap(); + } + s.finish_plugin_loads(); + let installed = vectorcraft_plugins::registry::remove(id); + assert!(!installed, "the module installed from a file that no longer holds it"); +} + +/// 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 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. @@ -2248,6 +2337,43 @@ fn a_stored_module_without_permissions_ends_its_grant_when_it_installs() { 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 = 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::>(), [json!(sha256_hex(&other))], "{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. diff --git a/crates/plugins/src/registry.rs b/crates/plugins/src/registry.rs index 3d84d8a6f7..01696519f3 100644 --- a/crates/plugins/src/registry.rs +++ b/crates/plugins/src/registry.rs @@ -283,19 +283,6 @@ fn open_module(path: &std::path::Path) -> std::io::Result { open.open(path) } -/// Whether this process may read the file at `path`, checked against its permissions without -/// opening it. On Unix the check uses the effective user and group; elsewhere it passes. -#[cfg(all(unix, not(target_arch = "wasm32")))] -pub fn may_read(path: &std::path::Path) -> std::io::Result<()> { - rustix::fs::accessat(rustix::fs::CWD, path, rustix::fs::Access::READ_OK, rustix::fs::AtFlags::EACCESS).map_err(std::io::Error::from) -} - -/// [`may_read`] off Unix: it passes, and a file that can't be read fails when its load reads it. -#[cfg(all(not(unix), not(target_arch = "wasm32")))] -pub fn may_read(_path: &std::path::Path) -> std::io::Result<()> { - Ok(()) -} - /// The most `.wasm` files one [`load_folder`] reads. #[cfg(not(target_arch = "wasm32"))] const MAX_FOLDER_FILES: usize = 1000; @@ -443,6 +430,9 @@ impl 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()); @@ -475,8 +465,6 @@ impl FolderLoad { None => Loads::deferred(jobs), }; let report = FolderReport { left_out, ..FolderReport::default() }; - let mut changes = LoadChanges::default(); - changes.start(); Ok(FolderLoad { files, loads, loaded: Default::default(), next: 0, report, changes }) } @@ -571,6 +559,19 @@ impl FolderLoad { 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`]. diff --git a/crates/ui-egui/src/app/control.rs b/crates/ui-egui/src/app/control.rs index 87f04c0044..4bc285b9d9 100644 --- a/crates/ui-egui/src/app/control.rs +++ b/crates/ui-egui/src/app/control.rs @@ -36,10 +36,10 @@ impl VectorcraftApp { // 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 - // its caller gave up meanwhile is dropped below. + // its caller gave up meanwhile is dropped below. The frame's poll of the loads asks + // for the next frame. if self.session.plugins_loading() && !req.given_up() { self.deferred_control = Some(req); - ctx.request_repaint(); break; } // Its caller stopped waiting (the app was busy or its window not drawn for too long) diff --git a/crates/ui-egui/src/io/export.rs b/crates/ui-egui/src/io/export.rs index a646d55383..201601595f 100644 --- a/crates/ui-egui/src/io/export.rs +++ b/crates/ui-egui/src/io/export.rs @@ -66,12 +66,13 @@ pub fn export(app: &mut VectorcraftApp, format: Option<&str>, path: Option Option { /// File → Open… pub fn open_dialog(app: &mut VectorcraftApp) -> Result<(), String> { + // The picker lists the extensions of the importer plug-ins the launch is still loading too. + app.session.finish_plugin_loads(); if crate::picks::open_async(app) { return Ok(()); } diff --git a/docs/mcp.md b/docs/mcp.md index a7bea5799e..79cee6d543 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -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` 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 + 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 @@ -13279,7 +13279,8 @@ error and changes nothing when an object it would expand holds such an effect, i plain symbol instance in a group or layer with a raster effect, since the group's image draws the symbol's art. `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, 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 +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 diff --git a/docs/plugins.md b/docs/plugins.md index 81e7f56af0..84239935c4 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -116,15 +116,18 @@ 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, 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, -or whose load takes 10 s or longer (VectorCraft's own limit), is reported as failed or skipped with a log record, and -the others install. 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. The -web build loads one module at a time. +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. 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.", "params": {…}}`): while the plug-in is installed it is drawn, exported and expanded; without it