fix(plugins): make plugin uninstall state consistent on failure
This commit is contained in:
1 parent
88dccd7cde
commit
8be259be5f
7 files changed
+430
-33
No files matched your search
@@ -867,6 +867,10 @@ async function uninstallSelectedPlugin() {
|
|||||||
selectFirstProvider();
|
selectFirstProvider();
|
||||||
} catch (cause) {
|
} catch (cause) {
|
||||||
toast(cause instanceof Error ? cause.message : String(cause), 5000);
|
toast(cause instanceof Error ? cause.message : String(cause), 5000);
|
||||||
|
// A failed uninstall can still have changed the store (the container is renamed out of the
|
||||||
|
// plugin store before its physical delete, for instance), so re-read the installed list
|
||||||
|
// instead of leaving the panel on state it may no longer describe.
|
||||||
|
await refreshAfterBatch();
|
||||||
} finally {
|
} finally {
|
||||||
operating.value = false;
|
operating.value = false;
|
||||||
}
|
}
|
||||||
|
|||||||
+34
@@ -854,3 +854,37 @@ describe("PluginContributionsPanel marketplace sort", () => {
|
|||||||
expect(renderedOrder()).toEqual(["a.older", "b.newer"]);
|
expect(renderedOrder()).toEqual(["a.older", "b.newer"]);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe("PluginContributionsPanel single uninstall outcomes", () => {
|
||||||
|
it("re-reads the installed list and notifies listeners when a single uninstall fails", async () => {
|
||||||
|
const changed = vi.fn();
|
||||||
|
window.addEventListener("dbx:plugins-changed", changed);
|
||||||
|
const failure = "The process cannot access the file because it is being used by another process. (os error 32)";
|
||||||
|
mocks.uninstallPlugin.mockRejectedValueOnce(new Error(failure));
|
||||||
|
// The backend kept the plugin installed (the uninstall never committed), and the panel has to
|
||||||
|
// show exactly that instead of the state it guessed before the call.
|
||||||
|
mocks.listPlugins.mockResolvedValueOnce([installed("a"), installed("b", "9.9.9")]);
|
||||||
|
|
||||||
|
try {
|
||||||
|
await state.uninstallSelectedPlugin();
|
||||||
|
} finally {
|
||||||
|
window.removeEventListener("dbx:plugins-changed", changed);
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(mocks.toast).toHaveBeenLastCalledWith(failure, 5000);
|
||||||
|
expect(mocks.listPlugins).toHaveBeenCalledOnce();
|
||||||
|
expect(state.installedPlugins.map((plugin) => `${plugin.manifest.id}@${plugin.manifest.version}`)).toEqual(["a@1.0.0", "b@9.9.9"]);
|
||||||
|
expect(changed).toHaveBeenCalledOnce();
|
||||||
|
expect(state.error).toBe("");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps the uninstall failure visible when the follow-up refresh also fails", async () => {
|
||||||
|
mocks.uninstallPlugin.mockRejectedValueOnce(new Error("denied"));
|
||||||
|
mocks.listPlugins.mockRejectedValueOnce(new Error("refresh offline"));
|
||||||
|
|
||||||
|
await state.uninstallSelectedPlugin();
|
||||||
|
|
||||||
|
expect(mocks.toast).toHaveBeenLastCalledWith("denied", 5000);
|
||||||
|
expect(state.error).toBe('pluginPlatform.batchRefreshFailed:{"error":"refresh offline"}');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -198,6 +198,11 @@ impl PluginRegistry {
|
|||||||
let mut plugins = Vec::new();
|
let mut plugins = Vec::new();
|
||||||
for entry in entries {
|
for entry in entries {
|
||||||
let entry = entry.map_err(|err| err.to_string())?;
|
let entry = entry.map_err(|err| err.to_string())?;
|
||||||
|
if entry.file_name() == std::ffi::OsStr::new(installer::PLUGIN_TRASH_DIR) {
|
||||||
|
// Logical uninstall tombstones are not plugin containers: never discover one, not
|
||||||
|
// even while its physical delete is still pending.
|
||||||
|
continue;
|
||||||
|
}
|
||||||
let container_path = entry.path();
|
let container_path = entry.path();
|
||||||
if !container_path.is_dir() {
|
if !container_path.is_dir() {
|
||||||
continue;
|
continue;
|
||||||
@@ -292,6 +297,12 @@ impl PluginRegistry {
|
|||||||
let plugin =
|
let plugin =
|
||||||
self.find_driver(driver_id)?.ok_or_else(|| format!("Plugin driver '{driver_id}' is not installed"))?;
|
self.find_driver(driver_id)?.ok_or_else(|| format!("Plugin driver '{driver_id}' is not installed"))?;
|
||||||
ensure_plugin_compatible(&plugin)?;
|
ensure_plugin_compatible(&plugin)?;
|
||||||
|
// This is a short-lived, one-shot driver invocation: it starts its own sidecar instead of
|
||||||
|
// going through `PluginHost`, so it is not in `PluginHost::sessions` and needs its own
|
||||||
|
// lease. `begin_operation` matches those semantics (not a connection the user keeps open)
|
||||||
|
// and makes the whole start -> invoke -> shutdown sequence mutually exclusive with an
|
||||||
|
// install, rollback, or uninstall of the same plugin.
|
||||||
|
let _operation = self.lifecycle.begin_operation(&plugin.manifest.id)?;
|
||||||
let env = env.with_plugin_data_dir(&self.plugin_data_dir(&plugin.manifest.id));
|
let env = env.with_plugin_data_dir(&self.plugin_data_dir(&plugin.manifest.id));
|
||||||
let session = PluginSidecarSession::start(plugin, self.app_version.clone(), env).await?;
|
let session = PluginSidecarSession::start(plugin, self.app_version.clone(), env).await?;
|
||||||
let result = session.invoke_with_timeout(method, params, Some(driver_id), timeout_duration).await;
|
let result = session.invoke_with_timeout(method, params, Some(driver_id), timeout_duration).await;
|
||||||
@@ -694,6 +705,65 @@ sleep 30
|
|||||||
let _ = std::fs::remove_dir_all(root);
|
let _ = std::fs::remove_dir_all(root);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn driver_invocations_are_gated_by_the_update_lease_for_their_whole_session() {
|
||||||
|
let root = std::env::temp_dir().join(format!("dbx-plugin-driver-lease-test-{}", uuid::Uuid::new_v4()));
|
||||||
|
let plugin_dir = root.join("sample");
|
||||||
|
std::fs::create_dir_all(&plugin_dir).unwrap();
|
||||||
|
std::fs::write(
|
||||||
|
plugin_dir.join("manifest.json"),
|
||||||
|
// External drivers only exist on the legacy manifest shape, which is what
|
||||||
|
// `PluginRegistry::find_driver` resolves.
|
||||||
|
serde_json::json!({
|
||||||
|
"id": "sample",
|
||||||
|
"name": "Sample",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"publisher": "example",
|
||||||
|
"protocol_version": 1,
|
||||||
|
"executable": "plugin.sh",
|
||||||
|
"drivers": [{ "id": "sample-driver", "label": "Sample", "kind": "external", "database_type": "sample" }]
|
||||||
|
})
|
||||||
|
.to_string(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
// Present but never executable: the manifest stays compatible so the invocation gets past
|
||||||
|
// the lease, while starting the sidecar fails immediately and deterministically on every
|
||||||
|
// platform (no exec bit on unix, not a valid image on Windows).
|
||||||
|
std::fs::write(plugin_dir.join("plugin.sh"), "#!/bin/sh\nexit 1\n").unwrap();
|
||||||
|
let registry = PluginRegistry::new_with_app_version(root.clone(), "0.5.67");
|
||||||
|
|
||||||
|
let update = registry.lifecycle().begin_update("sample").unwrap();
|
||||||
|
let refused = registry
|
||||||
|
.invoke_driver_with_env_and_timeout::<serde_json::Value>(
|
||||||
|
"sample-driver",
|
||||||
|
"testConnection",
|
||||||
|
serde_json::json!({}),
|
||||||
|
PluginRuntimeEnv::default(),
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap_err();
|
||||||
|
assert!(refused.contains("Plugin update is in progress"), "{refused}");
|
||||||
|
drop(update);
|
||||||
|
|
||||||
|
// Once the update released the lease the invocation runs, and because the sidecar cannot
|
||||||
|
// start it must report that instead of the update error: the guard covered the start
|
||||||
|
// attempt and was released on the way out.
|
||||||
|
let failed_start = registry
|
||||||
|
.invoke_driver_with_env_and_timeout::<serde_json::Value>(
|
||||||
|
"sample-driver",
|
||||||
|
"testConnection",
|
||||||
|
serde_json::json!({}),
|
||||||
|
PluginRuntimeEnv::default(),
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap_err();
|
||||||
|
assert!(!failed_start.contains("Plugin update is in progress"), "{failed_start}");
|
||||||
|
assert!(registry.lifecycle().begin_update("sample").is_ok(), "a failed invocation must not leak its lease");
|
||||||
|
let _ = std::fs::remove_dir_all(root);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn installed_plugin_info_hides_runtime_paths() {
|
fn installed_plugin_info_hides_runtime_paths() {
|
||||||
let plugin = InstalledPlugin::new(
|
let plugin = InstalledPlugin::new(
|
||||||
|
|||||||
@@ -10,9 +10,9 @@ use tokio::sync::{broadcast, Mutex, RwLock};
|
|||||||
use super::{
|
use super::{
|
||||||
InstalledPlugin, PluginBinaryMessage, PluginConnectionActionContribution, PluginConnectionCapability,
|
InstalledPlugin, PluginBinaryMessage, PluginConnectionActionContribution, PluginConnectionCapability,
|
||||||
PluginConnectionProviderContribution, PluginEvent, PluginFormFieldBinding, PluginFormFieldDefinition,
|
PluginConnectionProviderContribution, PluginEvent, PluginFormFieldBinding, PluginFormFieldDefinition,
|
||||||
PluginFormFieldType, PluginRegistry, PluginRuntimeEnv, PluginSessionState, PluginSidecarSession,
|
PluginFormFieldType, PluginPackageInstaller, PluginRegistry, PluginRuntimeEnv, PluginSessionState,
|
||||||
PLUGIN_CONNECTION_ACTION_METHOD, PLUGIN_CONNECTION_CONNECT_METHOD, PLUGIN_CONNECTION_DISCONNECT_METHOD,
|
PluginSidecarSession, PluginTrustStore, PLUGIN_CONNECTION_ACTION_METHOD, PLUGIN_CONNECTION_CONNECT_METHOD,
|
||||||
PLUGIN_CONNECTION_TEST_METHOD,
|
PLUGIN_CONNECTION_DISCONNECT_METHOD, PLUGIN_CONNECTION_TEST_METHOD,
|
||||||
};
|
};
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize)]
|
#[derive(Debug, Clone, Serialize)]
|
||||||
@@ -352,6 +352,25 @@ impl PluginHost {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Runtime-aware uninstall. The lifecycle update lease is taken *before* the sidecar is stopped
|
||||||
|
/// and held until the store-level uninstall committed, so nothing can re-activate the plugin
|
||||||
|
/// and re-lock its container between the runtime stop and the filesystem rename. It also keeps
|
||||||
|
/// `PluginHost::sessions` and the plugin store consistent: the session is removed and the
|
||||||
|
/// container gone before the lease is released.
|
||||||
|
///
|
||||||
|
/// Callers drain the plugin's connection pools and external driver pools first: the lease is
|
||||||
|
/// refused while the plugin still has an active connection or operation.
|
||||||
|
pub async fn uninstall_plugin(&self, plugin_id: &str) -> Result<(), String> {
|
||||||
|
let _update = self.inner.registry.lifecycle.begin_update(plugin_id)?;
|
||||||
|
self.stop(plugin_id).await;
|
||||||
|
let root_dir = self.inner.registry.root_dir().to_path_buf();
|
||||||
|
let app_version = self.inner.registry.app_version().to_string();
|
||||||
|
// Uninstall never validates a package signature, so it must not load the user trust store.
|
||||||
|
let installer = PluginPackageInstaller::with_trust_store(root_dir, app_version, PluginTrustStore::default());
|
||||||
|
let plugin_id = plugin_id.to_string();
|
||||||
|
tokio::task::spawn_blocking(move || installer.uninstall(&plugin_id)).await.map_err(|error| error.to_string())?
|
||||||
|
}
|
||||||
|
|
||||||
async fn running_session(&self, plugin_id: &str) -> Option<Arc<PluginSidecarSession>> {
|
async fn running_session(&self, plugin_id: &str) -> Option<Arc<PluginSidecarSession>> {
|
||||||
let session = self.inner.sessions.read().await.get(plugin_id).cloned()?;
|
let session = self.inner.sessions.read().await.get(plugin_id).cloned()?;
|
||||||
(session.status().state == PluginSessionState::Running).then_some(session)
|
(session.status().state == PluginSessionState::Running).then_some(session)
|
||||||
@@ -836,6 +855,43 @@ mod tests {
|
|||||||
use crate::models::connection::ConnectionConfig;
|
use crate::models::connection::ConnectionConfig;
|
||||||
use crate::plugins::PluginConnectionProviderContribution;
|
use crate::plugins::PluginConnectionProviderContribution;
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn uninstall_plugin_holds_one_update_lease_across_the_runtime_and_the_store() {
|
||||||
|
use crate::plugins::installer::PLUGIN_TRASH_DIR;
|
||||||
|
use crate::plugins::{PluginHost, PluginRegistry};
|
||||||
|
|
||||||
|
let temp = tempfile::tempdir().unwrap();
|
||||||
|
let root = temp.path().join("plugins");
|
||||||
|
let plugin_dir = root.join("sample.hello");
|
||||||
|
std::fs::create_dir_all(&plugin_dir).unwrap();
|
||||||
|
std::fs::write(
|
||||||
|
plugin_dir.join("manifest.json"),
|
||||||
|
serde_json::json!({ "id": "sample.hello", "name": "Sample", "version": "1.0.0", "protocol_version": 1 })
|
||||||
|
.to_string(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let registry = PluginRegistry::new_with_app_version(root.clone(), "0.5.67");
|
||||||
|
let lifecycle = registry.lifecycle();
|
||||||
|
let host = PluginHost::new(registry);
|
||||||
|
|
||||||
|
// An active operation refuses the uninstall before anything is stopped or deleted, so the
|
||||||
|
// caller still sees a complete, discoverable plugin.
|
||||||
|
let operation = lifecycle.begin_operation("sample.hello").unwrap();
|
||||||
|
let refused = host.uninstall_plugin("sample.hello").await.unwrap_err();
|
||||||
|
assert!(refused.contains("active operations"), "{refused}");
|
||||||
|
assert!(plugin_dir.join("manifest.json").is_file(), "a refused uninstall must not touch the container");
|
||||||
|
drop(operation);
|
||||||
|
|
||||||
|
host.uninstall_plugin("sample.hello").await.unwrap();
|
||||||
|
assert!(!plugin_dir.exists());
|
||||||
|
let tombstones = std::fs::read_dir(root.join(PLUGIN_TRASH_DIR)).map(|entries| entries.count()).unwrap_or(0);
|
||||||
|
assert_eq!(tombstones, 0, "a successful uninstall sweeps its tombstone");
|
||||||
|
|
||||||
|
// The lease is released again, and it was scoped to just this plugin.
|
||||||
|
assert!(lifecycle.begin_update("sample.hello").is_ok());
|
||||||
|
assert!(lifecycle.begin_update("sample.other").is_ok());
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn ui_only_connections_hold_update_guards_but_saved_configs_do_not() {
|
async fn ui_only_connections_hold_update_guards_but_saved_configs_do_not() {
|
||||||
let root = tempfile::tempdir().unwrap();
|
let root = tempfile::tempdir().unwrap();
|
||||||
|
|||||||
@@ -25,6 +25,10 @@ const MAX_UNCOMPRESSED_BYTES: u64 = 1024 * 1024 * 1024;
|
|||||||
const MAX_FILE_BYTES: u64 = 256 * 1024 * 1024;
|
const MAX_FILE_BYTES: u64 = 256 * 1024 * 1024;
|
||||||
const MAX_ARCHIVE_ENTRIES: usize = 10_000;
|
const MAX_ARCHIVE_ENTRIES: usize = 10_000;
|
||||||
const INSTALL_LOCK_FILE: &str = ".install.lock";
|
const INSTALL_LOCK_FILE: &str = ".install.lock";
|
||||||
|
/// Where a logically uninstalled plugin container waits for its physical delete. The directory is
|
||||||
|
/// no plugin container of its own (no manifest, no activations), so installed plugin discovery
|
||||||
|
/// skips it, and `validate_plugin_id` rejects a leading dot, so no plugin id can collide with it.
|
||||||
|
pub(super) const PLUGIN_TRASH_DIR: &str = ".trash";
|
||||||
const VERSIONS_DIR: &str = "versions";
|
const VERSIONS_DIR: &str = "versions";
|
||||||
const ACTIVATIONS_DIR: &str = "activations";
|
const ACTIVATIONS_DIR: &str = "activations";
|
||||||
const TRUST_DIR: &str = ".trust";
|
const TRUST_DIR: &str = ".trust";
|
||||||
@@ -409,6 +413,10 @@ impl PluginPackageInstaller {
|
|||||||
let lock = open_install_lock(&self.root_dir)?;
|
let lock = open_install_lock(&self.root_dir)?;
|
||||||
lock.lock_exclusive().map_err(|error| format!("Failed to lock plugin store: {error}"))?;
|
lock.lock_exclusive().map_err(|error| format!("Failed to lock plugin store: {error}"))?;
|
||||||
let result = self.install_bytes_locked(package, policy, expectation, source, allow_source_change);
|
let result = self.install_bytes_locked(package, policy, expectation, source, allow_source_change);
|
||||||
|
if result.is_ok() {
|
||||||
|
// Opportunistic cleanup of tombstones an earlier uninstall could not delete yet.
|
||||||
|
self.sweep_plugin_trash(&TRANSIENT_LOCK_RETRY_DELAYS, |path: &Path| std::fs::remove_dir_all(path));
|
||||||
|
}
|
||||||
let _ = FileExt::unlock(&lock);
|
let _ = FileExt::unlock(&lock);
|
||||||
result
|
result
|
||||||
}
|
}
|
||||||
@@ -423,20 +431,81 @@ impl PluginPackageInstaller {
|
|||||||
result
|
result
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Store-level logical uninstall: the official `plugins/<plugin_id>` container is renamed into
|
||||||
|
/// `.trash` (that rename *is* the commit) and only then physically deleted. `remove_dir_all` is
|
||||||
|
/// not atomic, so deleting the container in place could leave a partially deleted tree behind;
|
||||||
|
/// a failed rename instead leaves the container exactly as it was and reports a clean failure.
|
||||||
pub fn uninstall(&self, plugin_id: &str) -> Result<(), String> {
|
pub fn uninstall(&self, plugin_id: &str) -> Result<(), String> {
|
||||||
|
self.uninstall_with_ops(
|
||||||
|
plugin_id,
|
||||||
|
&TRANSIENT_LOCK_RETRY_DELAYS,
|
||||||
|
|src: &Path, dst: &Path| std::fs::rename(src, dst),
|
||||||
|
|path: &Path| std::fs::remove_dir_all(path),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The uninstall body, parameterised for tests: `delays` is the transient Windows lock retry
|
||||||
|
/// window, and the two filesystem primitives are injected so error 5 / 32 failures can be
|
||||||
|
/// reproduced deterministically on every platform instead of depending on a real scanner.
|
||||||
|
fn uninstall_with_ops(
|
||||||
|
&self,
|
||||||
|
plugin_id: &str,
|
||||||
|
delays: &[Duration],
|
||||||
|
mut rename: impl FnMut(&Path, &Path) -> std::io::Result<()>,
|
||||||
|
mut remove_dir_all: impl FnMut(&Path) -> std::io::Result<()>,
|
||||||
|
) -> Result<(), String> {
|
||||||
validate_plugin_id(plugin_id)?;
|
validate_plugin_id(plugin_id)?;
|
||||||
let lock = open_install_lock(&self.root_dir)?;
|
let lock = open_install_lock(&self.root_dir)?;
|
||||||
lock.lock_exclusive().map_err(|error| format!("Failed to lock plugin store: {error}"))?;
|
lock.lock_exclusive().map_err(|error| format!("Failed to lock plugin store: {error}"))?;
|
||||||
let plugin_dir = self.root_dir.join(plugin_id);
|
let result = (|| {
|
||||||
let result = match std::fs::remove_dir_all(&plugin_dir) {
|
let plugin_dir = self.root_dir.join(plugin_id);
|
||||||
Ok(()) => Ok(()),
|
if plugin_dir.exists() {
|
||||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
|
let trash_dir = self.root_dir.join(PLUGIN_TRASH_DIR);
|
||||||
Err(error) => Err(format!("Failed to uninstall plugin '{plugin_id}': {error}")),
|
std::fs::create_dir_all(&trash_dir)
|
||||||
};
|
.map_err(|error| format!("Failed to prepare plugin trash '{}': {error}", trash_dir.display()))?;
|
||||||
|
let tombstone = unique_plugin_tombstone(&trash_dir, plugin_id);
|
||||||
|
// From here on the plugin is uninstalled: the container is out of the store root
|
||||||
|
// and discovery does not see it any more. An antivirus scanner holding a freshly
|
||||||
|
// extracted binary may fail this rename with error 5 / 32, hence the retry, and a
|
||||||
|
// rename that keeps failing leaves the container untouched for a clean failure.
|
||||||
|
retry_transient_lock(delays, || rename(&plugin_dir, &tombstone))
|
||||||
|
.map_err(|error| format!("Failed to uninstall plugin '{plugin_id}': {error}"))?;
|
||||||
|
}
|
||||||
|
self.sweep_plugin_trash(delays, &mut remove_dir_all);
|
||||||
|
Ok(())
|
||||||
|
})();
|
||||||
let _ = FileExt::unlock(&lock);
|
let _ = FileExt::unlock(&lock);
|
||||||
result
|
result
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Best-effort physical delete of every `.trash` tombstone: the one the caller just committed
|
||||||
|
/// plus leftovers from an earlier uninstall whose delete failed. Callers hold `.install.lock`,
|
||||||
|
/// every entry in there is already logically uninstalled, and a tombstone that still cannot be
|
||||||
|
/// removed only logs a warning — the plugin is uninstalled either way, and a later install or
|
||||||
|
/// uninstall sweeps it again.
|
||||||
|
fn sweep_plugin_trash(&self, delays: &[Duration], mut remove_dir_all: impl FnMut(&Path) -> std::io::Result<()>) {
|
||||||
|
let trash_dir = self.root_dir.join(PLUGIN_TRASH_DIR);
|
||||||
|
let entries = match std::fs::read_dir(&trash_dir) {
|
||||||
|
Ok(entries) => entries,
|
||||||
|
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return,
|
||||||
|
Err(error) => {
|
||||||
|
log::warn!("Failed to scan plugin trash '{}': {error}", trash_dir.display());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
for entry in entries.flatten() {
|
||||||
|
let tombstone = entry.path();
|
||||||
|
let removed = retry_transient_lock(delays, || match remove_dir_all(&tombstone) {
|
||||||
|
// Already gone (or not a directory): nothing left to clean up.
|
||||||
|
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
|
||||||
|
result => result,
|
||||||
|
});
|
||||||
|
if let Err(error) = removed {
|
||||||
|
log::warn!("Failed to remove plugin tombstone '{}': {error}", tombstone.display());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Recorded provenance of one container's active installation, if any.
|
/// Recorded provenance of one container's active installation, if any.
|
||||||
pub(super) fn read_container_provenance(container_dir: &Path) -> Result<Option<PluginInstallProvenance>, String> {
|
pub(super) fn read_container_provenance(container_dir: &Path) -> Result<Option<PluginInstallProvenance>, String> {
|
||||||
Ok(read_latest_activation(container_dir)?.and_then(|record| record.provenance))
|
Ok(read_latest_activation(container_dir)?.and_then(|record| record.provenance))
|
||||||
@@ -1088,6 +1157,19 @@ fn is_windows_lock_error(error: &std::io::Error) -> bool {
|
|||||||
matches!(error.raw_os_error(), Some(5 | 32))
|
matches!(error.raw_os_error(), Some(5 | 32))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Tombstone path for one logical uninstall: `.trash/<plugin id>`, or `.trash/<plugin id>-<n>`, the
|
||||||
|
/// same suffix convention `install_bytes_locked` uses for replaced versions, when an earlier
|
||||||
|
/// tombstone of that plugin is still waiting for its physical delete.
|
||||||
|
fn unique_plugin_tombstone(trash_dir: &Path, plugin_id: &str) -> PathBuf {
|
||||||
|
let mut candidate = trash_dir.join(plugin_id);
|
||||||
|
let mut suffix = 0u32;
|
||||||
|
while candidate.exists() {
|
||||||
|
suffix = suffix.saturating_add(1);
|
||||||
|
candidate = trash_dir.join(format!("{plugin_id}-{suffix}"));
|
||||||
|
}
|
||||||
|
candidate
|
||||||
|
}
|
||||||
|
|
||||||
fn make_backend_executable(path: &Option<PathBuf>) -> Result<(), String> {
|
fn make_backend_executable(path: &Option<PathBuf>) -> Result<(), String> {
|
||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
if let Some(path) = path {
|
if let Some(path) = path {
|
||||||
@@ -1198,7 +1280,7 @@ fn sync_directory(_path: &Path) -> Result<(), String> {
|
|||||||
mod tests {
|
mod tests {
|
||||||
use std::collections::{BTreeMap, BTreeSet};
|
use std::collections::{BTreeMap, BTreeSet};
|
||||||
use std::io::{Cursor, Write};
|
use std::io::{Cursor, Write};
|
||||||
use std::path::Path;
|
use std::path::{Path, PathBuf};
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
use base64::Engine;
|
use base64::Engine;
|
||||||
@@ -1208,8 +1290,8 @@ mod tests {
|
|||||||
use super::{
|
use super::{
|
||||||
is_activation_record_file, read_install_identity, retry_transient_lock, sha256_hex,
|
is_activation_record_file, read_install_identity, retry_transient_lock, sha256_hex,
|
||||||
validate_package_expectation, PluginInstallPolicy, PluginPackageExpectation, PluginPackageInstaller,
|
validate_package_expectation, PluginInstallPolicy, PluginPackageExpectation, PluginPackageInstaller,
|
||||||
PluginSignatureStatus, PluginTrustStore, ACTIVATIONS_DIR, PLUGIN_CHECKSUMS_FILE, PLUGIN_SIGNATURE_FILE,
|
PluginSignatureStatus, PluginTrustStore, ACTIVATIONS_DIR, INSTALL_LOCK_FILE, PLUGIN_CHECKSUMS_FILE,
|
||||||
VERSIONS_DIR,
|
PLUGIN_SIGNATURE_FILE, PLUGIN_TRASH_DIR, VERSIONS_DIR,
|
||||||
};
|
};
|
||||||
use crate::plugins::{PluginManifest, PluginRegistry};
|
use crate::plugins::{PluginManifest, PluginRegistry};
|
||||||
|
|
||||||
@@ -2093,4 +2175,168 @@ mod tests {
|
|||||||
assert_eq!(attempts.load(Ordering::SeqCst), 1);
|
assert_eq!(attempts.load(Ordering::SeqCst), 1);
|
||||||
assert_eq!(result.unwrap_err().raw_os_error(), Some(5));
|
assert_eq!(result.unwrap_err().raw_os_error(), Some(5));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Sorted `.trash` entries, so tombstone assertions are deterministic.
|
||||||
|
fn trash_entries(root: &Path) -> Vec<String> {
|
||||||
|
let mut names = std::fs::read_dir(root.join(PLUGIN_TRASH_DIR))
|
||||||
|
.map(|entries| {
|
||||||
|
entries
|
||||||
|
.filter_map(|entry| entry.ok())
|
||||||
|
.map(|entry| entry.file_name().to_string_lossy().into_owned())
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
})
|
||||||
|
.unwrap_or_default();
|
||||||
|
names.sort();
|
||||||
|
names
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Installs `sample.hello` into a store rooted at `<temp>/plugins`, so `<temp>/plugin-data`
|
||||||
|
/// sits next to it exactly like the real registry layout does.
|
||||||
|
fn uninstall_fixture(temp: &tempfile::TempDir, version: &str) -> (PluginPackageInstaller, PathBuf) {
|
||||||
|
let root = temp.path().join("plugins");
|
||||||
|
let installer = PluginPackageInstaller::with_trust_store(root.clone(), "0.5.67", PluginTrustStore::default());
|
||||||
|
installer.install_bytes(&package(version, None, false), PluginInstallPolicy::LocalDevelopment).unwrap();
|
||||||
|
(installer, root)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn uninstall_commits_logically_and_sweeps_its_own_tombstone() {
|
||||||
|
let temp = tempfile::tempdir().unwrap();
|
||||||
|
let (installer, root) = uninstall_fixture(&temp, "1.0.0");
|
||||||
|
let plugin_data = temp.path().join("plugin-data").join("sample.hello");
|
||||||
|
std::fs::create_dir_all(&plugin_data).unwrap();
|
||||||
|
std::fs::write(plugin_data.join("preferences.json"), "{}").unwrap();
|
||||||
|
let container = root.join("sample.hello");
|
||||||
|
assert!(container.join(VERSIONS_DIR).join("1.0.0").join("manifest.json").is_file());
|
||||||
|
|
||||||
|
installer.uninstall("sample.hello").unwrap();
|
||||||
|
|
||||||
|
assert!(!container.exists(), "the official container must be gone");
|
||||||
|
assert!(trash_entries(&root).is_empty(), "a successful uninstall sweeps its own tombstone");
|
||||||
|
assert!(root.join(INSTALL_LOCK_FILE).is_file(), "the store lock file stays in place");
|
||||||
|
assert!(plugin_data.join("preferences.json").is_file(), "plugin data survives an uninstall");
|
||||||
|
let registry = PluginRegistry::new_with_app_version(root, "0.5.67");
|
||||||
|
assert!(registry.list_installed().unwrap().is_empty());
|
||||||
|
assert!(registry.find_plugin("sample.hello").unwrap().is_none());
|
||||||
|
|
||||||
|
// Uninstalling a plugin that is already gone stays idempotent.
|
||||||
|
installer.uninstall("sample.hello").unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
#[cfg(windows)]
|
||||||
|
fn uninstall_retries_transient_windows_locks_on_the_commit_rename() {
|
||||||
|
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||||
|
|
||||||
|
let temp = tempfile::tempdir().unwrap();
|
||||||
|
let (installer, root) = uninstall_fixture(&temp, "1.0.0");
|
||||||
|
let attempts = AtomicUsize::new(0);
|
||||||
|
installer
|
||||||
|
.uninstall_with_ops(
|
||||||
|
"sample.hello",
|
||||||
|
&[Duration::ZERO, Duration::ZERO, Duration::ZERO],
|
||||||
|
|src: &Path, dst: &Path| match attempts.fetch_add(1, Ordering::SeqCst) {
|
||||||
|
0 => Err(std::io::Error::from_raw_os_error(5)),
|
||||||
|
1 => Err(std::io::Error::from_raw_os_error(32)),
|
||||||
|
_ => std::fs::rename(src, dst),
|
||||||
|
},
|
||||||
|
|path: &Path| std::fs::remove_dir_all(path),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
assert_eq!(attempts.load(Ordering::SeqCst), 3, "two lock errors then one successful rename");
|
||||||
|
assert!(!root.join("sample.hello").exists());
|
||||||
|
assert!(trash_entries(&root).is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn uninstall_reports_a_clean_failure_and_keeps_the_container_when_the_rename_keeps_failing() {
|
||||||
|
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||||
|
|
||||||
|
let temp = tempfile::tempdir().unwrap();
|
||||||
|
let (installer, root) = uninstall_fixture(&temp, "1.0.0");
|
||||||
|
let container = root.join("sample.hello");
|
||||||
|
let attempts = AtomicUsize::new(0);
|
||||||
|
let error = installer
|
||||||
|
.uninstall_with_ops(
|
||||||
|
"sample.hello",
|
||||||
|
&[Duration::ZERO, Duration::ZERO, Duration::ZERO],
|
||||||
|
|_: &Path, _: &Path| {
|
||||||
|
attempts.fetch_add(1, Ordering::SeqCst);
|
||||||
|
Err(std::io::Error::from_raw_os_error(32))
|
||||||
|
},
|
||||||
|
|path: &Path| std::fs::remove_dir_all(path),
|
||||||
|
)
|
||||||
|
.unwrap_err();
|
||||||
|
|
||||||
|
assert!(error.contains("Failed to uninstall plugin 'sample.hello'"), "{error}");
|
||||||
|
assert_eq!(attempts.load(Ordering::SeqCst), if cfg!(windows) { 4 } else { 1 });
|
||||||
|
// A failed logical commit must leave the container exactly as it was: the plugin has to
|
||||||
|
// stay installed, discoverable, and loadable after a restart.
|
||||||
|
assert!(container.join(VERSIONS_DIR).join("1.0.0").join("manifest.json").is_file());
|
||||||
|
assert_eq!(activation_record_count(&container), 1);
|
||||||
|
assert!(trash_entries(&root).is_empty(), "a failed commit must not leave a tombstone behind");
|
||||||
|
let registry = PluginRegistry::new_with_app_version(root, "0.5.67");
|
||||||
|
assert_eq!(registry.list_installed().unwrap().len(), 1);
|
||||||
|
assert_eq!(registry.find_plugin("sample.hello").unwrap().unwrap().manifest.version, "1.0.0");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn uninstall_stays_a_logical_success_when_the_tombstone_cannot_be_deleted() {
|
||||||
|
let temp = tempfile::tempdir().unwrap();
|
||||||
|
let (installer, root) = uninstall_fixture(&temp, "1.0.0");
|
||||||
|
|
||||||
|
installer
|
||||||
|
.uninstall_with_ops(
|
||||||
|
"sample.hello",
|
||||||
|
&[Duration::ZERO, Duration::ZERO, Duration::ZERO],
|
||||||
|
|src: &Path, dst: &Path| std::fs::rename(src, dst),
|
||||||
|
|_: &Path| Err(std::io::Error::from_raw_os_error(32)),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
assert!(!root.join("sample.hello").exists());
|
||||||
|
assert_eq!(trash_entries(&root), vec!["sample.hello".to_string()]);
|
||||||
|
let registry = PluginRegistry::new_with_app_version(root, "0.5.67");
|
||||||
|
assert!(registry.list_installed().unwrap().is_empty());
|
||||||
|
assert!(registry.find_plugin("sample.hello").unwrap().is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn install_and_uninstall_sweep_tombstones_left_by_an_earlier_attempt() {
|
||||||
|
let temp = tempfile::tempdir().unwrap();
|
||||||
|
let (installer, root) = uninstall_fixture(&temp, "1.0.0");
|
||||||
|
let stale = root.join(PLUGIN_TRASH_DIR).join("sample.hello");
|
||||||
|
std::fs::create_dir_all(stale.join(VERSIONS_DIR).join("1.0.0")).unwrap();
|
||||||
|
std::fs::write(stale.join(VERSIONS_DIR).join("1.0.0").join("manifest.json"), "{}").unwrap();
|
||||||
|
|
||||||
|
installer.install_bytes(&package("1.1.0", None, false), PluginInstallPolicy::LocalDevelopment).unwrap();
|
||||||
|
assert!(!stale.exists(), "an install sweeps leftovers of an earlier uninstall");
|
||||||
|
|
||||||
|
std::fs::create_dir_all(&stale).unwrap();
|
||||||
|
std::fs::write(stale.join("leftover.bin"), b"still locked").unwrap();
|
||||||
|
installer.uninstall("sample.hello").unwrap();
|
||||||
|
assert!(!root.join("sample.hello").exists());
|
||||||
|
assert!(!stale.exists(), "an uninstall sweeps old tombstones as well");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn tombstone_containers_are_never_discovered_as_installed_plugins() {
|
||||||
|
let temp = tempfile::tempdir().unwrap();
|
||||||
|
let (installer, root) = uninstall_fixture(&temp, "1.0.0");
|
||||||
|
let tombstone = root.join(PLUGIN_TRASH_DIR).join("sample.hello");
|
||||||
|
std::fs::create_dir_all(root.join(PLUGIN_TRASH_DIR)).unwrap();
|
||||||
|
std::fs::rename(root.join("sample.hello"), &tombstone).unwrap();
|
||||||
|
// The tombstone still holds a complete container: versions/, activations/, manifest.json.
|
||||||
|
assert!(tombstone.join(VERSIONS_DIR).join("1.0.0").join("manifest.json").is_file());
|
||||||
|
assert_eq!(activation_record_count(&tombstone), 1);
|
||||||
|
|
||||||
|
let registry = PluginRegistry::new_with_app_version(root.clone(), "0.5.67");
|
||||||
|
assert!(registry.list_installed().unwrap().is_empty());
|
||||||
|
assert!(registry.find_plugin("sample.hello").unwrap().is_none());
|
||||||
|
|
||||||
|
// The store stays usable: a reinstall does not collide with the pending tombstone.
|
||||||
|
installer.install_bytes(&package("1.0.0", None, false), PluginInstallPolicy::LocalDevelopment).unwrap();
|
||||||
|
assert_eq!(registry.list_installed().unwrap().len(), 1);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -353,22 +353,15 @@ pub async fn uninstall_plugin(
|
|||||||
}
|
}
|
||||||
let plugin = state.app.plugins.find_plugin(&request.plugin_id).map_err(AppError::from)?;
|
let plugin = state.app.plugins.find_plugin(&request.plugin_id).map_err(AppError::from)?;
|
||||||
state.app.remove_plugin_connection_pools(&request.plugin_id).await;
|
state.app.remove_plugin_connection_pools(&request.plugin_id).await;
|
||||||
state.app.plugin_host.stop(&request.plugin_id).await;
|
|
||||||
if let Some(plugin) = &plugin {
|
if let Some(plugin) = &plugin {
|
||||||
stop_external_driver_pools(&state, plugin).await;
|
stop_external_driver_pools(&state, plugin).await;
|
||||||
}
|
}
|
||||||
let root_dir = state.app.plugins.root_dir().to_path_buf();
|
// Stops the runtime and uninstalls the store under one lifecycle update lease, so a plugin
|
||||||
let app_version = state.app.plugins.app_version().to_string();
|
// call cannot re-activate the sidecar (and re-lock its container) in between.
|
||||||
let plugin_id = request.plugin_id.clone();
|
state.app.plugin_host.uninstall_plugin(&request.plugin_id).await.map_err(AppError::bad_request)?;
|
||||||
tokio::task::spawn_blocking(move || {
|
|
||||||
PluginPackageInstaller::new(root_dir, app_version)?.uninstall(&request.plugin_id)
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
.map_err(|error| AppError::internal(error.to_string()))?
|
|
||||||
.map_err(AppError::bad_request)?;
|
|
||||||
// A reinstall must ask for AI tool access and data grants again.
|
// A reinstall must ask for AI tool access and data grants again.
|
||||||
if let Err(error) = state.app.storage.forget_plugin_permissions(&plugin_id).await {
|
if let Err(error) = state.app.storage.forget_plugin_permissions(&request.plugin_id).await {
|
||||||
log::warn!("Failed to clear permissions of uninstalled plugin {plugin_id}: {error}");
|
log::warn!("Failed to clear permissions of uninstalled plugin {}: {error}", request.plugin_id);
|
||||||
}
|
}
|
||||||
list_plugins(State(state)).await
|
list_plugins(State(state)).await
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -276,18 +276,12 @@ pub async fn uninstall_plugin(
|
|||||||
}
|
}
|
||||||
let plugin = state.plugins.find_plugin(&plugin_id)?;
|
let plugin = state.plugins.find_plugin(&plugin_id)?;
|
||||||
state.remove_plugin_connection_pools(&plugin_id).await;
|
state.remove_plugin_connection_pools(&plugin_id).await;
|
||||||
state.plugin_host.stop(&plugin_id).await;
|
|
||||||
if let Some(plugin) = &plugin {
|
if let Some(plugin) = &plugin {
|
||||||
stop_external_driver_pools(&state, plugin).await;
|
stop_external_driver_pools(&state, plugin).await;
|
||||||
}
|
}
|
||||||
let root_dir = state.plugins.root_dir().to_path_buf();
|
// Stops the runtime and uninstalls the store under one lifecycle update lease, so a plugin
|
||||||
let app_version = state.plugins.app_version().to_string();
|
// call cannot re-activate the sidecar (and re-lock its container) in between.
|
||||||
let uninstalled_id = plugin_id.clone();
|
state.plugin_host.uninstall_plugin(&plugin_id).await?;
|
||||||
tauri::async_runtime::spawn_blocking(move || {
|
|
||||||
PluginPackageInstaller::new(root_dir, app_version)?.uninstall(&uninstalled_id)
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
.map_err(|error| error.to_string())??;
|
|
||||||
// A reinstall must ask for AI tool access and data grants again.
|
// A reinstall must ask for AI tool access and data grants again.
|
||||||
if let Err(error) = state.storage.forget_plugin_permissions(&plugin_id).await {
|
if let Err(error) = state.storage.forget_plugin_permissions(&plugin_id).await {
|
||||||
log::warn!("Failed to clear permissions of uninstalled plugin {plugin_id}: {error}");
|
log::warn!("Failed to clear permissions of uninstalled plugin {plugin_id}: {error}");
|
||||||
|
|||||||
Reference in new issue
Block a user