Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# Agent 笔记:插件暂存目录的跨进程清理

状态:已实现

## 先说结论

桌面安装、后台准备更新和卸载使用同一个用户插件根目录。启动时只有取得独占锁的进程才清理临时目录,使用临时目录的进程共同持有共享锁。这样在另一个窗口启动时,正在验包或等候用户批准的安装仍能继续。

## 问题

每个桌面进程会在加载插件服务时清理 `.staging` 和 `.trash`,原先假定此时没有安装或卸载。打开新窗口可能启动另一个进程。后台更新在发布待激活目录之前已经解包,用于串行发布的锁也无法覆盖此前的准备过程。

## 决策

- 使用写在用户插件根目录的 `.staging-sweep.lock`。安装和卸载从准备临时文件前到发布或清理完成为止持有共享锁。启动先探测是否有遗留目录,然后只尝试一次独占锁。获取锁后重新读取目录,目录正在使用时留给以后启动清理。异常退出时系统会释放锁,锁文件继续供其他进程使用。
- 包发布和审批记录继续使用原有的独占锁。用户等待审批时其他进程仍能准备各自的包,也能打开窗口。
- 例如:进程 A 解包并进入审批,进程 B 启动并读取插件列表。B 发现暂存目录正由 A 使用,略过启动清理,A 可以继续发布。取得独占锁后才读取临时目录,可避免用加锁前的列表误删刚创建的包。

## 考虑过的备选方案

- 扩大包发布独占锁以覆盖下载、解包和审批。审批时间由用户决定,持有该锁会让其他安装或卸载等到超时。
- 按文件修改时间删除旧目录。后台检查、用户审批和休眠都可能持续超过选定期限,目录年龄无法证明已经没有进程使用它。

## 后果

同时准备的包不互相等待,启动清理也不等待用户操作。其他桌面进程正在安装或卸载时,已中断任务的文件会留到下一次可清理的启动。锁文件随用户的插件数据根存在,位于发行包之外,因此不改变代码签名或应用增量更新基线。

## 验证

- `./scripts/desktop/desktop-go.sh test ./internal/workbench -run TestPluginAutoUpdateStagesAnApprovedNewVersionUntilRestart` 在合成插件归档解包和发布之间运行第二个桌面插件服务,验证更新成功暂存,并在随后激活。
- `./scripts/desktop/desktop-go.sh test ./internal/pluginpkg ./internal/plugininstall ./internal/pluginservice` 验证遗留文件清理和安装包只读边界。
- `./scripts/desktop/verify/verify-runtime-bundle-immutability.sh` 检查 macOS 和 Windows 的发行目录只读门禁。

## 适用范围

- `desktop/internal/pluginpkg/install.go`
- `desktop/internal/workbench/plugins.go`
- `desktop/internal/workbench/plugin_auto_update.go`
- `desktop/internal/pluginservice/lifecycle.go`
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@

不同进程共享插件数据根。激活、手动安装、后台暂存、禁用和卸载使用同一个原生文件锁。卸载先取消并等待进程内的安装任务,再加锁让 Core 读取安装快照。这样即使另一个窗口刚刚激活新版,卸载计划也会包含它。锁文件保留在可写的插件数据根,进程退出时由操作系统释放锁。

启动清理也需要和使用临时目录的进程协调。安装和卸载在使用临时目录期间持有共享锁,启动只在立即取得独占锁时清理。原因和回归场景见 [插件暂存目录的跨进程清理](../bug-fix/2026-11-24-plugin-staging-sweep-ownership.md)。

## 考虑过的备选方案

- 默认无条件自动更新:用户没有同意后台下载或插件执行代码更换,拒绝。
Expand Down
23 changes: 21 additions & 2 deletions desktop/internal/filelock/lock.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,23 @@ var (
// Acquire uses an OS lock, not a pid or timestamp lease: process death releases
// ownership automatically. The file stays in place so another opener cannot
// lock a different inode while a previous waiter still holds the old one.
func Acquire(ctx context.Context, name string) (unlock func() error, err error) {
func Acquire(ctx context.Context, name string) (func() error, error) {
return acquire(ctx, name, true, true)
}

// AcquireShared lets multiple users hold the same lock until an exclusive
// operation can run without any of them.
func AcquireShared(ctx context.Context, name string) (func() error, error) {
return acquire(ctx, name, false, true)
}

// TryAcquire attempts an exclusive lock once. A nil closer with no error means
// another process owns the lock.
func TryAcquire(name string) (func() error, error) {
return acquire(context.Background(), name, true, false)
}

func acquire(ctx context.Context, name string, exclusive, wait bool) (unlock func() error, err error) {
defer func() {
if err != nil && unlock != nil {
err = errors.Join(err, unlock())
Expand Down Expand Up @@ -57,7 +73,7 @@ func Acquire(ctx context.Context, name string) (unlock func() error, err error)
bounded, cancel := context.WithTimeout(ctx, 5*time.Minute)
defer cancel()
for {
locked, err := tryLock(file)
locked, err := tryLock(file, exclusive)
if err != nil {
return nil, err
}
Expand All @@ -68,6 +84,9 @@ func Acquire(ctx context.Context, name string) (unlock func() error, err error)
owned = true
return file.Close, nil
}
if !wait {
return nil, nil
}
// Native advisory locks have no cross-platform cancellable wait. The
// bounded timer performs no filesystem scanning and owns no goroutine.
timer := time.NewTimer(100 * time.Millisecond)
Expand Down
8 changes: 6 additions & 2 deletions desktop/internal/filelock/lock_unix.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,12 @@ import (
"golang.org/x/sys/unix"
)

func tryLock(file *os.File) (bool, error) {
err := unix.Flock(int(file.Fd()), unix.LOCK_EX|unix.LOCK_NB)
func tryLock(file *os.File, exclusive bool) (bool, error) {
mode := unix.LOCK_SH
if exclusive {
mode = unix.LOCK_EX
}
err := unix.Flock(int(file.Fd()), mode|unix.LOCK_NB)
if errors.Is(err, unix.EWOULDBLOCK) || errors.Is(err, unix.EAGAIN) {
return false, nil
}
Expand Down
8 changes: 6 additions & 2 deletions desktop/internal/filelock/lock_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,12 @@ import (
"golang.org/x/sys/windows"
)

func tryLock(file *os.File) (bool, error) {
err := windows.LockFileEx(windows.Handle(file.Fd()), windows.LOCKFILE_EXCLUSIVE_LOCK|windows.LOCKFILE_FAIL_IMMEDIATELY, 0, 1, 0, new(windows.Overlapped))
func tryLock(file *os.File, exclusive bool) (bool, error) {
mode := uint32(windows.LOCKFILE_FAIL_IMMEDIATELY)
if exclusive {
mode |= windows.LOCKFILE_EXCLUSIVE_LOCK
}
err := windows.LockFileEx(windows.Handle(file.Fd()), mode, 0, 1, 0, new(windows.Overlapped))
if errors.Is(err, windows.ERROR_LOCK_VIOLATION) {
return false, nil
}
Expand Down
13 changes: 13 additions & 0 deletions desktop/internal/plugininstall/pending_test.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
package plugininstall

import (
"context"
"os"
"path/filepath"
"testing"
"time"

"github.com/1lck/Lithe-IDEA/desktop/internal/installedpackagetest"
"github.com/1lck/Lithe-IDEA/desktop/internal/pluginpkg"
Expand All @@ -18,6 +20,17 @@ func TestStageUpdateLeavesInstalledPackageUnchanged(t *testing.T) {
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
release, err := pluginpkg.ProtectStaging(ctx, root)
if err != nil {
t.Fatal(err)
}
defer func() {
if err := release(); err != nil {
t.Error(err)
}
}()
staging, err := pluginpkg.NewStaging(root)
if err != nil {
t.Fatal(err)
Expand Down
45 changes: 41 additions & 4 deletions desktop/internal/pluginpkg/install.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
package pluginpkg

import (
"context"
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"sort"
"strings"

"github.com/1lck/Lithe-IDEA/desktop/internal/filelock"
)

const (
Expand All @@ -16,6 +19,7 @@ const (
// plugin, which is also why a plugin ID may not start with one.
stagingDirectory = ".staging"
trashDirectory = ".trash"
stagingSweepLock = ".staging-sweep.lock"
// StateDirectory is where the programs of installed plugins keep their
// writable state, one directory per plugin ID; see RemoveState.
StateDirectory = ".state"
Expand Down Expand Up @@ -44,19 +48,52 @@ type Installed struct {
Path string
}

// Sweep removes what an interrupted install or uninstall left behind.
// ProtectStaging holds the temporary package directories against startup
// cleanup. Keep the lock from before creating any files until publication or
// cleanup. Other installations can still prepare their own directories.
func ProtectStaging(ctx context.Context, root string) (func() error, error) {
if err := checkRoot(root); err != nil {
return nil, err
}
if err := ctx.Err(); err != nil {
return nil, err
}
if err := os.MkdirAll(root, 0o700); err != nil {
return nil, err
}
return filelock.AcquireShared(ctx, filepath.Join(root, stagingSweepLock))
}

// Sweep removes what an interrupted install or uninstall left behind when
// no operation in any desktop process is using the temporary directories.
//
// Nothing else cleans the staging and trash areas: a process killed mid-install, or
// a delete that failed, leaves a complete extracted package there. Call it before
// any installation can start, so it never races one.
func Sweep(root string) error {
// a delete that failed, leaves a complete extracted package there. A busy
// sweep waits for a later process startup rather than blocking this one.
func Sweep(root string) (err error) {
if err := checkRoot(root); err != nil {
return err
}
var release func() error
defer func() {
if release != nil {
err = errors.Join(err, release())
}
}()
var failures []error
for _, name := range []string{stagingDirectory, trashDirectory} {
directory := filepath.Join(root, name)
entries, err := os.ReadDir(directory)
if err == nil && len(entries) != 0 && release == nil {
release, err = filelock.TryAcquire(filepath.Join(root, stagingSweepLock))
if err != nil || release == nil {
return errors.Join(append(failures, err)...)
}
// An owner may have created, removed or published a package
// between the unlocked probe and acquisition.
entries, err = os.ReadDir(directory)
}
// log-exempt: 预期的缺失:插件根目录还没有该临时目录。
if errors.Is(err, fs.ErrNotExist) {
continue
}
Expand Down
51 changes: 50 additions & 1 deletion desktop/internal/pluginpkg/install_test.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
package pluginpkg

import (
"context"
"errors"
"os"
"path/filepath"
"testing"
"time"

"github.com/1lck/Lithe-IDEA/desktop/internal/installedpackagetest"
)
Expand Down Expand Up @@ -227,6 +229,37 @@ func TestSweepRemovesLeftoversAndKeepsInstalledPackages(t *testing.T) {
t.Fatal(err)
}
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
acquire := func() func() {
t.Helper()
release, err := ProtectStaging(ctx, root)
if err != nil {
t.Fatal(err)
}
finish := func() {
t.Helper()
if release != nil {
if err := release(); err != nil {
t.Error(err)
}
release = nil
}
}
t.Cleanup(finish)
return finish
}
first, second := acquire(), acquire()
first()
if err := Sweep(root); err != nil {
t.Fatal(err)
}
for _, directory := range leftovers {
if _, err := os.Stat(filepath.Join(directory, "leftover")); err != nil {
t.Fatalf("sweep removed an in-use file: %v", err)
}
}
second()
if err := Sweep(root); err != nil {
t.Fatalf("sweep: %v", err)
}
Expand All @@ -242,9 +275,13 @@ func TestSweepRemovesLeftoversAndKeepsInstalledPackages(t *testing.T) {
}

func TestSweepAcceptsAnEmptyRoot(t *testing.T) {
if err := Sweep(t.TempDir()); err != nil {
root := t.TempDir()
if err := Sweep(root); err != nil {
t.Fatalf("sweep: %v", err)
}
if _, err := os.Stat(filepath.Join(root, stagingSweepLock)); !errors.Is(err, os.ErrNotExist) {
t.Fatalf("startup wrote a lock without any files to sweep: %v", err)
}
if err := Sweep("relative"); !errors.Is(err, ErrUnsafePath) {
t.Fatalf("err = %v", err)
}
Expand All @@ -265,6 +302,18 @@ func TestInstallLeavesTheInstalledPackageUnchanged(t *testing.T) {
if err := Sweep(root); err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
release, err := ProtectStaging(ctx, root)
if err != nil {
t.Fatal(err)
}
defer func() {
if err := release(); err != nil {
t.Error(err)
}
}()
installedpackagetest.Outside(t, filepath.Join(root, stagingSweepLock))
staging, err := NewStaging(root)
if err != nil {
t.Fatal(err)
Expand Down
Loading
Loading