mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-25 20:01:07 +01:00
Plug-ins: background loads check stored files and ids again before they install
- A stored module's file is read again on its worker thread once the module has loaded, whatever the file's modified time, and the install still skips a file whose stamp changed since. The UI thread no longer reads the file. - Stored and folder modules install through registry::install_for_load, which checks for an install or removal of the id elsewhere while the plug-ins' write lock is held, and records the module's grant in the same step. A grant is forgotten only while the plug-in that took that revision is still installed (registry::revoke_if_installed). - A grant that a stored load removed and must put back for a later file is written to grants.json first; when that write fails, the module is not installed, and a grant put back for a module that then did not install is removed again. - A folder load in which a file found no loader thread is loaded again the next time the preferences are applied. A plugin.reload keeps its report as the folder last loaded only when no load started after it. - Loads: a job's time is read while it is marked finished, the deadline check reads the clock under the same lock, and only the jobs taken from the queue fail when no worker is left. wait() counts outcomes taken with ready() as released, so the jobs after them start. - File › Open checks the path again after waiting for the plug-in loads. - Tests wait for workers with bounded receives.
This commit is contained in:
1 parent
f8bbfae755
commit
cef8a6d897
8 files changed
+530
-147
No files matched your search
@@ -701,6 +701,9 @@ 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
|
||||
@@ -990,14 +993,17 @@ fn load_path(_: &str) -> Result<(Plugin, Vec<u8>)> {
|
||||
}
|
||||
|
||||
/// The plug-in folder last loaded, the plug-in store whose grants it was loaded with, what
|
||||
/// happened, and the load whose report it is ([`FOLDER_LOADS`]; 0: a `plugin.reload`).
|
||||
type FolderRecord = (String, Option<std::path::PathBuf>, Value, u64);
|
||||
/// 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`] started, which it keeps in [`FOLDER`] while
|
||||
/// that load runs, so only that load replaces or clears the record.
|
||||
/// 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
|
||||
@@ -1024,11 +1030,12 @@ pub(crate) fn sync_prefs(s: &mut Session) {
|
||||
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.
|
||||
if last.as_ref().is_some_and(|(f, store, r, _)| *f == folder && *store == s.plugin_dir && r["loading"] != true) {
|
||||
// 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));
|
||||
*last = Some((folder.clone(), s.plugin_dir.clone(), json!({"folder": folder, "loading": true}), token, false));
|
||||
token
|
||||
};
|
||||
let load = start_folder(s, &folder, Some(token));
|
||||
@@ -1039,7 +1046,7 @@ pub(crate) fn sync_prefs(s: &mut Session) {
|
||||
/// 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;
|
||||
}
|
||||
}
|
||||
@@ -1074,6 +1081,9 @@ pub(crate) struct FolderPending {
|
||||
/// 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`]).
|
||||
@@ -1164,7 +1174,7 @@ impl Drop for FolderPending {
|
||||
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) {
|
||||
if last.as_ref().is_some_and(|(_, _, _, t, _)| *t == token) {
|
||||
*last = None;
|
||||
}
|
||||
}
|
||||
@@ -1175,7 +1185,8 @@ impl Drop for FolderPending {
|
||||
/// 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, load: Some(load), canceled: false };
|
||||
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})));
|
||||
}
|
||||
@@ -1198,7 +1209,7 @@ fn start_folder(s: &Session, folder: &str, record: Option<u64>) -> FolderPending
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
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, load: Some(load), canceled: false }
|
||||
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
|
||||
@@ -1228,37 +1239,61 @@ pub(crate) fn install_folder(s: &mut Session, load: &mut FolderPending, turn: &S
|
||||
/// 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 = match load.load.take() {
|
||||
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);
|
||||
}
|
||||
json!({"folder": load.folder, "loaded": r.loaded, "failed": r.failed.iter().map(|(f, e)| json!({"file": f, "error": e})).collect::<Vec<_>>(), "leftOut": r.left_out})
|
||||
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,
|
||||
None => Value::Null,
|
||||
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.
|
||||
if last.as_ref().is_some_and(|(_, _, _, t)| *t == token) {
|
||||
*last = if load.canceled { None } else { Some((load.folder.clone(), load.store.clone(), report.clone(), token)) };
|
||||
// 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.
|
||||
/// 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 load = start_folder(s, folder, None);
|
||||
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> {
|
||||
const C: &str = "plugin.reload";
|
||||
let folder = match p.get("path") {
|
||||
@@ -1274,7 +1309,6 @@ fn reload(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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(), 0));
|
||||
Ok(report)
|
||||
}
|
||||
|
||||
@@ -1323,7 +1357,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}),
|
||||
|
||||
+101
-54
@@ -324,8 +324,6 @@ pub(crate) struct StoredLoad {
|
||||
/// 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.
|
||||
@@ -350,6 +348,22 @@ fn before_stored_load(path: &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`]).
|
||||
@@ -415,6 +429,18 @@ fn list_stored_plugins(rest: &mut VecDeque<StoredFile>, left: &mut u64) -> (Vec<
|
||||
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 })
|
||||
}));
|
||||
@@ -753,9 +779,6 @@ impl Session {
|
||||
rest.push_back((path, Some(Some(stamp))));
|
||||
}
|
||||
}
|
||||
// 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.
|
||||
@@ -763,18 +786,8 @@ impl Session {
|
||||
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,
|
||||
listed,
|
||||
};
|
||||
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));
|
||||
}
|
||||
|
||||
@@ -825,17 +838,13 @@ impl Session {
|
||||
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 {}: it changed or went away while it loaded", path.display());
|
||||
log::warn!("skipping the stored plug-in {}: {CHANGED_WHILE_LOADING}", path.display());
|
||||
continue;
|
||||
}
|
||||
match loaded {
|
||||
// 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()) => {
|
||||
log::warn!("skipping the stored plug-in {}: {}", path.display(), vectorcraft_plugins::registry::SUPERSEDED);
|
||||
}
|
||||
@@ -851,21 +860,53 @@ impl Session {
|
||||
.flatten();
|
||||
match stored.or(back.clone()) {
|
||||
Some(g) => {
|
||||
// A grant this load removed for an earlier file with the id goes back.
|
||||
// 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() {
|
||||
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());
|
||||
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());
|
||||
}
|
||||
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));
|
||||
match vectorcraft_plugins::registry::install(plugin.with_source(path.display().to_string())) {
|
||||
Ok(p) => load.changes.installed(&p),
|
||||
Err(e) => log::warn!("skipping the stored plug-in {}: {e}", path.display()),
|
||||
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 => {
|
||||
@@ -875,14 +916,31 @@ impl Session {
|
||||
}
|
||||
Ok(plugin) => {
|
||||
let id = plugin.id().to_string();
|
||||
vectorcraft_plugins::registry::set_storage(&id, plugin_storage(Some(&dir), &id, turn));
|
||||
match vectorcraft_plugins::registry::install(plugin.with_source(path.display().to_string())) {
|
||||
Ok(p) => load.changes.installed(&p),
|
||||
Err(e) => log::warn!("skipping the stored plug-in {}: {e}", path.display()),
|
||||
}
|
||||
// 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.
|
||||
vectorcraft_plugins::registry::revoke(&id);
|
||||
// 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);
|
||||
}
|
||||
@@ -1595,17 +1653,6 @@ fn plugin_storage(dir: Option<&Path>, id: &str, turn: &StoreTurn) -> Option<Arc<
|
||||
/// A file's size and modified time (`None`: there is no file).
|
||||
type FileStamp = Option<(u64, SystemTime)>;
|
||||
|
||||
/// Does the file at `path` hold, in its first `len` bytes and no more, the module whose SHA-256 is
|
||||
/// `hash`?
|
||||
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<FileStamp, StorageError> {
|
||||
match std::fs::metadata(path) {
|
||||
|
||||
@@ -2143,34 +2143,40 @@ fn stored_files_whose_reads_fail_leave_the_store_budget_to_the_others() {
|
||||
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.
|
||||
/// 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() {
|
||||
let id = "test.engine.background.replaced";
|
||||
let (folder, path) = store_with("plugin-background-replaced", id);
|
||||
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.
|
||||
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();
|
||||
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();
|
||||
*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();
|
||||
}
|
||||
}));
|
||||
let mut s = session();
|
||||
s.attach_plugin_store(folder.0.clone());
|
||||
let installed = vectorcraft_plugins::registry::remove(&id);
|
||||
assert!(!installed, "the module installed from a file that no longer holds it ({n})");
|
||||
}
|
||||
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`
|
||||
@@ -2196,6 +2202,55 @@ fn another_session_lists_a_folder_still_loading_as_loading() {
|
||||
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.
|
||||
@@ -2263,8 +2318,11 @@ fn stored_plugins_load_without_holding_the_plugin_changes_lock() {
|
||||
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));
|
||||
}
|
||||
@@ -2374,6 +2432,73 @@ fn a_grant_given_elsewhere_since_the_load_removed_one_is_kept() {
|
||||
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));
|
||||
let listed: Vec<Value> = std::fs::read(&grants).ok().map(|b| serde_json::from_slice(&b).unwrap()).unwrap_or_default();
|
||||
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.
|
||||
|
||||
@@ -46,6 +46,9 @@ 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> {
|
||||
@@ -123,7 +126,7 @@ pub struct Loads<T: Send + 'static> {
|
||||
max_stuck: usize,
|
||||
/// Tests: no thread can be started from now on.
|
||||
#[cfg(test)]
|
||||
refuse_threads: bool,
|
||||
pub(crate) refuse_threads: bool,
|
||||
}
|
||||
|
||||
impl<T: Send + 'static> Loads<T> {
|
||||
@@ -244,17 +247,20 @@ impl<T: Send + 'static> Loads<T> {
|
||||
(i, job, at)
|
||||
};
|
||||
let r = run_job(job);
|
||||
let took = clock().saturating_sub(at);
|
||||
// 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.
|
||||
let retire = {
|
||||
// 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;
|
||||
s.expired[i] && {
|
||||
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 {
|
||||
@@ -331,8 +337,10 @@ impl<T: Send + 'static> Loads<T> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Waits for every outcome → those not taken yet, in the order of the jobs.
|
||||
/// 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();
|
||||
@@ -358,16 +366,16 @@ impl<T: Send + 'static> Loads<T> {
|
||||
|
||||
/// 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, and
|
||||
/// so does a job whose worker ended without an outcome.
|
||||
/// 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 now = (self.clock)();
|
||||
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() {
|
||||
@@ -390,20 +398,16 @@ impl<T: Send + 'static> Loads<T> {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let stranded = {
|
||||
let s = self.pool.lock();
|
||||
s.workers <= s.stuck
|
||||
// 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() }
|
||||
};
|
||||
if stranded && !self.outcomes.iter().all(Option::is_some) {
|
||||
// What the last workers sent before they ended counts.
|
||||
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.pool.lock().queue.clear();
|
||||
for o in self.outcomes.iter_mut().filter(|o| o.is_none()) {
|
||||
*o = Some(Err(Error::Failed("no thread was left to load it".into())));
|
||||
for i in stranded {
|
||||
if let Some(o @ None) = self.outcomes.get_mut(i) {
|
||||
*o = Some(Err(Error::Failed(NO_THREAD.into())));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -493,6 +497,19 @@ mod tests {
|
||||
})
|
||||
}
|
||||
|
||||
/// 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() {
|
||||
@@ -507,13 +524,13 @@ mod tests {
|
||||
let (_, clock) = manual();
|
||||
let mut loads = Loads::start_with(jobs, 3, LOAD_DEADLINE, clock);
|
||||
for _ in 0..3 {
|
||||
starts.recv().unwrap();
|
||||
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() {
|
||||
go[v].send(()).unwrap();
|
||||
let done = loads.results.lock().unwrap().recv().unwrap();
|
||||
let done = recv_soon(&loads.results.lock().unwrap());
|
||||
finished.push(done.0);
|
||||
loads.record(done);
|
||||
}
|
||||
@@ -541,7 +558,7 @@ mod tests {
|
||||
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!(starts.recv().unwrap(), 0);
|
||||
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));
|
||||
@@ -562,10 +579,10 @@ mod tests {
|
||||
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!(starts.recv().unwrap(), 0);
|
||||
assert_eq!(recv_soon(&starts), 0);
|
||||
ms.store(10_000, Ordering::SeqCst);
|
||||
loads.poll();
|
||||
assert_eq!(starts.recv().unwrap(), 1, "a worker took the place of the stuck one");
|
||||
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();
|
||||
@@ -614,6 +631,22 @@ mod tests {
|
||||
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]
|
||||
@@ -623,7 +656,7 @@ mod tests {
|
||||
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);
|
||||
starts.recv().unwrap();
|
||||
recv_soon(&starts);
|
||||
loads.refuse_threads = true;
|
||||
ms.store(10_000, Ordering::SeqCst);
|
||||
let done = loads.poll();
|
||||
@@ -651,7 +684,7 @@ mod tests {
|
||||
let (go, held_until) = mpsc::channel();
|
||||
let (ms, clock) = manual();
|
||||
let mut first = make(vec![held(0, started, held_until)], clock);
|
||||
starts.recv().unwrap();
|
||||
recv_soon(&starts);
|
||||
ms.store(10_000, Ordering::SeqCst);
|
||||
assert!(first.poll(), "the stuck job failed at its deadline");
|
||||
drop(first);
|
||||
@@ -677,7 +710,7 @@ mod tests {
|
||||
let mut loads = Loads::with(vec![held(0, started, held_until)], 1, Duration::from_secs(10), clock);
|
||||
loads.stuck_threads = stuck;
|
||||
loads.begin();
|
||||
starts.recv().unwrap();
|
||||
recv_soon(&starts);
|
||||
ms.store(10_000, Ordering::SeqCst);
|
||||
drop(loads);
|
||||
assert_eq!(stuck.load(Ordering::SeqCst), 1, "the stuck thread counts");
|
||||
|
||||
+139
-11
@@ -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,11 +76,53 @@ 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`]).
|
||||
@@ -326,6 +368,9 @@ 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
|
||||
@@ -543,17 +588,21 @@ impl FolderLoad {
|
||||
let asked = crate::permissions::names(&p.manifest().permissions()).join(", ");
|
||||
report.failed.push((name, 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) => {
|
||||
// `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.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
|
||||
@@ -587,8 +636,12 @@ impl FolderLoad {
|
||||
pub fn finish(self) -> FolderReport {
|
||||
let FolderLoad { report, changes, .. } = self;
|
||||
for id in &report.loaded {
|
||||
if get(id).is_some_and(|p| changes.own.get(id) == Some(&p.serial()) && !p.manifest().asks_permissions()) {
|
||||
revoke(id);
|
||||
// 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
|
||||
@@ -936,9 +989,12 @@ mod tests {
|
||||
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))
|
||||
};
|
||||
while !(seen.lock().unwrap_or_else(|e| e.into_inner()).contains(&first) && finished(&all[1]) && finished(&all[2])) {
|
||||
// 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();
|
||||
@@ -1075,4 +1131,76 @@ mod tests {
|
||||
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:?}");
|
||||
}
|
||||
}
|
||||
@@ -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>) {
|
||||
|
||||
@@ -538,6 +538,9 @@ fn open_file_with(app: &mut VectorcraftApp, path: &str, background: bool, p: &Va
|
||||
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
|
||||
|
||||
+8
-2
@@ -125,7 +125,10 @@ others install. So is a module whose read and load take 10 s or longer (VectorCr
|
||||
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
|
||||
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.
|
||||
|
||||
@@ -320,7 +323,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