Merge pull request #188 from reiasu2/fix/plugin-install-rename-retry

fix(plugin): retry Windows directory rename on transient antivirus locks
This commit is contained in:
千川白浪 authored and GitHub committed 2026-12-05 15:40:19 +08:00
commit 2f7f33b53f
6 files changed
+449 -17

No files matched your search

+7
View File
@@ -0,0 +1,7 @@
{
"group": "fixes",
"order": 0,
"authors": ["reiasu2"],
"zh": "在 Windows 上从插件市场安装、重装插件或导入本地 ZIP 插件包时,若杀毒软件实时防护短暂占用刚解压的插件可执行文件,自动短暂重试,避免报 `Access is denied` 失败。",
"en": "When installing or reinstalling a plugin from the market or importing a local ZIP package on Windows, briefly retry if real-time antivirus protection holds newly extracted plugin executables open so installation does not fail with `Access is denied`."
}
+2 -1
View File
@@ -25,7 +25,8 @@ var renameOwners = map[string]bool{
"internal/macos/reims/suspend_fileops_windows.go": true, // state and metadata commit together
"internal/plugin/broker.go": true, // log rotation
"internal/plugin/pack.go": true, // archive
"internal/plugin/package.go": true, // plugin directory
"internal/plugin/package_rename_other.go": true, // plugin directory
"internal/plugin/package_rename_windows.go": true, // plugin directory
"internal/runtime/runtime.go": true, // runtime directory
"internal/selfupdate/selfupdate.go": true, // running executable
}
+37 -16
View File
@@ -17,6 +17,7 @@ import (
"runtime"
"sort"
"strings"
"sync"
"time"
"github.com/Nwflower/reims-go/internal/i18n"
@@ -28,6 +29,8 @@ var (
reKeymapName = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$`)
)
var packageInstallLocks sync.Map // plugin parent directory -> *sync.Mutex
// ForbiddenMarketPatterns enforces §1.3 & §9 market redlines: reject Apple
// proprietary payloads, closed firmware, and SMBIOS literal secrets.
var ForbiddenMarketPatterns = []string{
@@ -559,7 +562,7 @@ func InstallArchive(layout PluginsLayout, archivePath string, opts PackageInstal
cleanupStage := true
defer func() {
if cleanupStage {
_ = os.RemoveAll(stageDir)
_ = removePackageDir(stageDir)
}
}()
@@ -652,26 +655,44 @@ func InstallArchive(layout PluginsLayout, archivePath string, opts PackageInstal
if err != nil {
return nil, fmt.Errorf("invalid plugin install target: %w", err)
}
if err := os.MkdirAll(filepath.Dir(finalDir), 0o755); err != nil {
return nil, err
}
// If same version already exists, replace atomically via backup swap.
parentDir := filepath.Clean(filepath.Dir(finalDir))
backupDir := ""
if _, err := os.Stat(finalDir); err == nil {
backupDir = finalDir + ".prev-" + fmt.Sprintf("%d", time.Now().UnixNano())
if err := os.Rename(finalDir, backupDir); err != nil {
return nil, fmt.Errorf("prepare upgrade swap: %w", err)
activationErr := func() error {
lock, _ := packageInstallLocks.LoadOrStore(parentDir, &sync.Mutex{})
installMu := lock.(*sync.Mutex)
installMu.Lock()
defer installMu.Unlock()
if err := os.MkdirAll(parentDir, 0o755); err != nil {
return err
}
}
if err := os.Rename(stageDir, finalDir); err != nil {
if backupDir != "" {
_ = os.Rename(backupDir, finalDir)
// If same version already exists, replace atomically via backup swap.
if _, err := os.Stat(finalDir); err == nil {
backupDir = finalDir + ".prev-" + fmt.Sprintf("%d", time.Now().UnixNano())
if err := renamePackageDir(finalDir, backupDir); err != nil {
return fmt.Errorf("prepare upgrade swap: %w", err)
}
}
return nil, fmt.Errorf("activate plugin package: %w", err)
if err := renamePackageDir(stageDir, finalDir); err != nil {
action := "activate plugin package"
if isTransientRenameLockErr(err) {
action += " (directory may be temporarily locked by antivirus or another process)"
}
if backupDir == "" {
_ = os.Remove(parentDir)
} else if rollbackErr := renamePackageDir(backupDir, finalDir); rollbackErr != nil {
return fmt.Errorf("%s: %w; restore previous version from %s also failed: %w", action, err, backupDir, rollbackErr)
}
return fmt.Errorf("%s: %w", action, err)
}
cleanupStage = false
return nil
}()
if activationErr != nil {
return nil, activationErr
}
cleanupStage = false
if backupDir != "" {
_ = os.RemoveAll(backupDir)
_ = removePackageDir(backupDir)
}
entryAbs := ""
+17
View File
@@ -0,0 +1,17 @@
//go:build !windows
package plugin
import "os"
func renamePackageDir(oldPath, newPath string) error {
return os.Rename(oldPath, newPath)
}
func removePackageDir(path string) error {
return os.RemoveAll(path)
}
func isTransientRenameLockErr(error) bool {
return false
}
+60
View File
@@ -0,0 +1,60 @@
//go:build windows
package plugin
import (
"errors"
"os"
"time"
"golang.org/x/sys/windows"
)
var (
renameDirFn = os.Rename
removeDirFn = os.RemoveAll
sleepRetryFn = time.Sleep
// Real-time antivirus scans of a newly extracted executable can take several seconds.
renameDirBackoff = []time.Duration{
50 * time.Millisecond, 100 * time.Millisecond, 150 * time.Millisecond,
250 * time.Millisecond, 350 * time.Millisecond,
500 * time.Millisecond, 500 * time.Millisecond, 500 * time.Millisecond,
500 * time.Millisecond, 500 * time.Millisecond, 500 * time.Millisecond,
500 * time.Millisecond, 500 * time.Millisecond, 500 * time.Millisecond,
500 * time.Millisecond,
}
removeDirBackoff = []time.Duration{
50 * time.Millisecond, 100 * time.Millisecond, 200 * time.Millisecond, 400 * time.Millisecond,
}
)
func renamePackageDir(oldPath, newPath string) error {
return retryPackageDirLock(renameDirBackoff, func() error {
return renameDirFn(oldPath, newPath)
})
}
func removePackageDir(path string) error {
return retryPackageDirLock(removeDirBackoff, func() error {
return removeDirFn(path)
})
}
func isTransientRenameLockErr(err error) bool {
return errors.Is(err, windows.ERROR_ACCESS_DENIED) ||
errors.Is(err, windows.ERROR_SHARING_VIOLATION) ||
errors.Is(err, windows.ERROR_LOCK_VIOLATION)
}
func retryPackageDirLock(backoff []time.Duration, op func() error) error {
err := op()
for _, delay := range backoff {
if !isTransientRenameLockErr(err) {
break
}
sleepRetryFn(delay)
err = op()
}
return err
}
@@ -0,0 +1,326 @@
//go:build windows
package plugin
import (
"errors"
"fmt"
"os"
"path/filepath"
"slices"
"strings"
"testing"
"time"
"golang.org/x/sys/windows"
)
func TestRenamePackageDirWithOpenWindowsHandle(t *testing.T) {
root := t.TempDir()
stageDir := filepath.Join(root, "stage")
finalDir := filepath.Join(root, "final")
if err := os.Mkdir(stageDir, 0o755); err != nil {
t.Fatal(err)
}
payload := filepath.Join(stageDir, "sidecar.exe")
if err := os.WriteFile(payload, []byte("sidecar contents"), 0o644); err != nil {
t.Fatal(err)
}
path, err := windows.UTF16PtrFromString(payload)
if err != nil {
t.Fatal(err)
}
handle, err := windows.CreateFile(path, windows.GENERIC_READ, windows.FILE_SHARE_READ, nil, windows.OPEN_EXISTING, windows.FILE_ATTRIBUTE_NORMAL, 0)
if err != nil {
t.Fatal(err)
}
oldSleep := sleepRetryFn
retries := 0
closed := false
t.Cleanup(func() {
sleepRetryFn = oldSleep
if !closed {
if err := windows.CloseHandle(handle); err != nil {
t.Error(err)
}
}
})
sleepRetryFn = func(delay time.Duration) {
retries++
if retries == 1 {
if err := windows.CloseHandle(handle); err != nil {
t.Fatal(err)
}
closed = true
}
oldSleep(delay)
}
if err := renamePackageDir(stageDir, finalDir); err != nil {
t.Fatal(err)
}
if retries < 1 {
t.Fatal("rename did not retry while the Windows handle was open")
}
assertRenameTestContents(t, filepath.Join(finalDir, "sidecar.exe"), "sidecar contents")
if _, err := os.Stat(stageDir); !errors.Is(err, os.ErrNotExist) {
t.Errorf("stage directory after rename: %v, want absent", err)
}
}
func TestInstallArchiveRenameRetry(t *testing.T) {
const (
id = "test.rename"
version = "1.0.0"
entry = "bin/sidecar.exe"
)
opts := PackageInstallOptions{HostVersion: "0.3.0", AllowUnsigned: true}
for _, tc := range []struct {
name string
existingVersion string
activationLockRetries int
wantErr error
wantAttempts int
}{
{name: "retry then activate", activationLockRetries: 2, wantAttempts: 3},
{name: "first install exhausts retries", wantErr: windows.ERROR_ACCESS_DENIED, wantAttempts: 16},
{name: "same version rolls back", existingVersion: version, wantErr: windows.ERROR_ACCESS_DENIED, wantAttempts: 16},
{name: "other version stays installed", existingVersion: "0.9.0", wantErr: windows.ERROR_ACCESS_DENIED, wantAttempts: 16},
{name: "missing path fails immediately", wantErr: os.ErrNotExist, wantAttempts: 1},
{name: "successful swap removes backup", existingVersion: version, wantAttempts: 1},
} {
t.Run(tc.name, func(t *testing.T) {
layout := NewPluginsLayout(t.TempDir())
parent := filepath.Join(layout.PkgsDir(), id)
finalDir := filepath.Join(parent, version)
if tc.existingVersion != "" {
archive := packRenameTestPlugin(t, id, tc.existingVersion, entry, "old sidecar")
if _, err := InstallArchive(layout, archive, opts); err != nil {
t.Fatalf("install existing version: %v", err)
}
}
archive := packRenameTestPlugin(t, id, version, entry, "new sidecar")
oldRename, oldRemove, oldSleep := renameDirFn, removeDirFn, sleepRetryFn
t.Cleanup(func() {
renameDirFn, removeDirFn, sleepRetryFn = oldRename, oldRemove, oldSleep
})
var sleeps []time.Duration
sleepRetryFn = func(delay time.Duration) {
sleeps = append(sleeps, delay)
}
var activationAttempts, backupAttempts, rollbackAttempts, cleanupAttempts int
renameDirFn = func(oldPath, newPath string) error {
switch {
case filepath.Dir(oldPath) == layout.TmpDir() && newPath == finalDir:
activationAttempts++
if tc.wantErr != nil {
return &os.LinkError{Op: "rename", Old: oldPath, New: newPath, Err: tc.wantErr}
}
if activationAttempts <= tc.activationLockRetries {
return windows.ERROR_ACCESS_DENIED
}
case oldPath == finalDir && strings.HasPrefix(newPath, finalDir+".prev-"):
backupAttempts++
if backupAttempts == 1 {
return windows.ERROR_SHARING_VIOLATION
}
case strings.HasPrefix(oldPath, finalDir+".prev-") && newPath == finalDir:
rollbackAttempts++
if rollbackAttempts == 1 {
return windows.ERROR_LOCK_VIOLATION
}
default:
t.Fatalf("unexpected rename from %q to %q", oldPath, newPath)
}
return oldRename(oldPath, newPath)
}
removeDirFn = func(path string) error {
cleanupAttempts++
if tc.wantErr != nil && filepath.Dir(path) != layout.TmpDir() ||
tc.wantErr == nil && !strings.HasPrefix(path, finalDir+".prev-") {
t.Fatalf("unexpected cleanup of %q", path)
}
if cleanupAttempts == 1 {
return &os.PathError{Op: "remove", Path: path, Err: windows.ERROR_SHARING_VIOLATION}
}
return oldRemove(path)
}
installed, err := InstallArchive(layout, archive, opts)
if !errors.Is(err, tc.wantErr) {
t.Fatalf("InstallArchive error = %v, want %v", err, tc.wantErr)
}
if activationAttempts != tc.wantAttempts {
t.Errorf("activation attempts = %d, want %d", activationAttempts, tc.wantAttempts)
}
var wantSleeps []time.Duration
if tc.existingVersion == version {
wantSleeps = append(wantSleeps, 50*time.Millisecond)
if backupAttempts != 2 {
t.Errorf("backup attempts = %d, want 2", backupAttempts)
}
}
switch tc.wantErr {
case nil:
if installed.InstallDir != finalDir {
t.Errorf("installed directory = %q, want %q", installed.InstallDir, finalDir)
}
assertRenameTestContents(t, filepath.Join(finalDir, entry), "new sidecar")
if tc.activationLockRetries > 0 {
wantSleeps = append(wantSleeps, 50*time.Millisecond, 100*time.Millisecond)
}
case windows.ERROR_ACCESS_DENIED:
if !strings.Contains(err.Error(), "directory may be temporarily locked by antivirus or another process") {
t.Errorf("missing lock hint in %v", err)
}
wantSleeps = append(wantSleeps, renameDirBackoff...)
default:
if !strings.HasPrefix(err.Error(), "activate plugin package: ") {
t.Errorf("unexpected error for missing path: %v", err)
}
}
if tc.wantErr != nil && tc.existingVersion == version {
wantSleeps = append(wantSleeps, 50*time.Millisecond)
if rollbackAttempts != 2 {
t.Errorf("rollback attempts = %d, want 2", rollbackAttempts)
}
}
if tc.wantErr != nil || tc.existingVersion == version {
wantSleeps = append(wantSleeps, 50*time.Millisecond)
if cleanupAttempts != 2 {
t.Errorf("cleanup attempts = %d, want 2", cleanupAttempts)
}
}
if !slices.Equal(sleeps, wantSleeps) {
t.Errorf("retry delays = %v, want %v", sleeps, wantSleeps)
}
staged, err := os.ReadDir(layout.TmpDir())
if err != nil || len(staged) != 0 {
t.Errorf("staging contents = %v, error = %v, want empty", staged, err)
}
if tc.wantErr != nil && tc.existingVersion == "" {
if _, err := os.Stat(parent); !errors.Is(err, os.ErrNotExist) {
t.Errorf("empty package parent: %v, want absent", err)
}
return
}
wantVersion := version
if tc.wantErr != nil {
wantVersion = tc.existingVersion
assertRenameTestContents(t, filepath.Join(parent, wantVersion, entry), "old sidecar")
}
versions, err := os.ReadDir(parent)
if err != nil || len(versions) != 1 || versions[0].Name() != wantVersion {
t.Errorf("package versions = %v, error = %v, want only %s", versions, err, wantVersion)
}
})
}
}
func TestInstallArchiveRenameAndRollbackFail(t *testing.T) {
const (
id = "test.rename"
version = "1.0.0"
entry = "bin/sidecar.exe"
)
layout := NewPluginsLayout(t.TempDir())
opts := PackageInstallOptions{HostVersion: "0.3.0", AllowUnsigned: true}
archive := packRenameTestPlugin(t, id, version, entry, "old sidecar")
installed, err := InstallArchive(layout, archive, opts)
if err != nil {
t.Fatalf("install existing version: %v", err)
}
oldFiles := make(map[string]string)
for _, name := range []string{"plugin.json", "SHA256SUMS", entry} {
data, err := os.ReadFile(filepath.Join(installed.InstallDir, name))
if err != nil {
t.Fatal(err)
}
oldFiles[name] = string(data)
}
archive = packRenameTestPlugin(t, id, version, entry, "new sidecar")
oldRename, oldSleep := renameDirFn, sleepRetryFn
t.Cleanup(func() {
renameDirFn, sleepRetryFn = oldRename, oldSleep
})
sleepRetryFn = func(time.Duration) {}
activateErr, rollbackErr := windows.ERROR_ACCESS_DENIED, windows.ERROR_LOCK_VIOLATION
var backupDir string
renameDirFn = func(oldPath, newPath string) error {
if newPath == installed.InstallDir {
if oldPath == backupDir {
return rollbackErr
}
return activateErr
}
backupDir = newPath
return oldRename(oldPath, newPath)
}
_, err = InstallArchive(layout, archive, opts)
if !errors.Is(err, activateErr) || !errors.Is(err, rollbackErr) {
t.Fatalf("InstallArchive error = %v, want activation and rollback errors", err)
}
if !strings.HasPrefix(backupDir, installed.InstallDir+".prev-") || !strings.Contains(err.Error(), backupDir) {
t.Errorf("InstallArchive error = %v, want .prev- backup path %q", err, backupDir)
}
if !strings.Contains(err.Error(), "directory may be temporarily locked by antivirus or another process") {
t.Errorf("missing activation lock hint in %v", err)
}
for name, contents := range oldFiles {
assertRenameTestContents(t, filepath.Join(backupDir, name), contents)
}
}
func TestRemovePackageDirRenameLockRetry(t *testing.T) {
oldRemove, oldSleep := removeDirFn, sleepRetryFn
t.Cleanup(func() {
removeDirFn, sleepRetryFn = oldRemove, oldSleep
})
var sleeps []time.Duration
sleepRetryFn = func(delay time.Duration) {
sleeps = append(sleeps, delay)
}
attempts := 0
removeDirFn = func(path string) error {
attempts++
return &os.PathError{Op: "remove", Path: path, Err: windows.ERROR_LOCK_VIOLATION}
}
if err := removePackageDir("stage"); !errors.Is(err, windows.ERROR_LOCK_VIOLATION) {
t.Errorf("removePackageDir error = %v, want ERROR_LOCK_VIOLATION", err)
}
wantSleeps := []time.Duration{50 * time.Millisecond, 100 * time.Millisecond, 200 * time.Millisecond, 400 * time.Millisecond}
if attempts != 5 || !slices.Equal(sleeps, wantSleeps) {
t.Errorf("remove attempts = %d, delays = %v, want 5 attempts and %v", attempts, sleeps, wantSleeps)
}
}
func packRenameTestPlugin(t *testing.T, id, version, entry, contents string) string {
t.Helper()
source := t.TempDir()
payload := filepath.Join(source, entry)
if err := os.MkdirAll(filepath.Dir(payload), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(payload, []byte(contents), 0o644); err != nil {
t.Fatal(err)
}
manifest := fmt.Sprintf(`{"schema":1,"id":%q,"version":%q,"name":{"en-US":"Rename test"},"entry":{"sidecar":%q}}`, id, version, entry)
if err := os.WriteFile(filepath.Join(source, "plugin.json"), []byte(manifest), 0o644); err != nil {
t.Fatal(err)
}
archive := filepath.Join(t.TempDir(), "plugin.zip")
if _, err := PackDirectory(source, PackOptions{HostVersion: "0.3.0", OutputPath: archive}); err != nil {
t.Fatal(err)
}
return archive
}
func assertRenameTestContents(t *testing.T, path, want string) {
t.Helper()
got, err := os.ReadFile(path)
if err != nil || string(got) != want {
t.Fatalf("read %q = %q, error = %v, want %q", path, got, err, want)
}
}