fix(desktop): 租约注册表跨实例共享、激活后不回收版本、安装冲突同口径

本轮 4 条未 resolve review + 1 条折叠意见:

1. 租约跨实例失效(P1,Greptile + Codex)。`PluginMarketService` 每次操作都
   `new MarketSourceManager(...)`,而引用计数是实例字段 —— 安装 manager 持有
   的租约对刷新 manager 完全不可见,刷新照样删掉正在被打包读取的旧版本,上一轮
   加的引用计数跨操作等于没做。注册表(versionRefs / pendingDeletes /
   activeIncoming)改为**模块级、按绝对路径为键**:受保护的对象本来就是文件系统
   路径,按路径为键才是正确作用域;owner 隔离由 ownerScopedUserDataPath 编进
   cloneRoot 的路径自带。租约测试改为读取与刷新走**两个不同的 manager 实例**,
   与生产一致。

2. 激活后不得回收新版本(P2)。原 catch 覆盖了 activate + prune + store.update:
   元数据写入失败(磁盘满/只读/文件锁)时指针已指向 newDir、旧版本已被清理,
   却仍把 newDir 删掉 —— 留下指向不存在目录的指针,整个来源从列表消失。现在
   可回滚的清理只覆盖"落位 + 激活"这一段,且删除前用指针再核对一次;激活之后
   的失败只如实上报,绝不回收已生效的缓存。

3. 服务端安装入口同口径重算冲突(P2)。快照按"服务端目录 + 全部自定义来源"合并
   计数标 conflict 并禁用,但 detail() 传空重复集合把它恢复成可安装,install()
   也只统计服务端目录内部重名 —— 普通 UI 流程或直接 IPC 都能装上本该被冲突闸
   拒绝的服务端项并抢占 ghostId。抽出 crossSourceDuplicateGhostIds /
   assertSourceOwnsGhostId,服务端与自定义两条安装路径、两个详情入口共用同一
   口径,已拥有安装记录的来源保留所有权。

4. sparse 克隆不再留 detached HEAD(Copilot 折叠意见)。无显式 ref 时原先
   `checkout HEAD`,导致刷新的 `git pull --ff-only` 稳定失败并回落整仓重克隆 ——
   sparse 源每次刷新都全量 clone,快进路径实际是死代码。改为解析 origin/HEAD
   取默认分支并 checkout 该分支,保留跟踪关系;解析失败才退回 HEAD。

合并 upstream/main:upstream 已 revert #1080(批准 receipt 改造),因此
expectedInstalledApproval / ghostInstallApprovalToken /
diffInstalledGhostPermissionItems / forbiddenRootDirs /
resolveThroughExistingAncestor / onReapprove 全部不再存在,上一轮为并存而保留
的这些引用同步撤掉,自定义源安装的权限对比回到 diffGhostPermissionItems。

存量插件影响:无。改的是市场克隆缓存布局(versions/ + current 指针 + incoming/),
不触及已安装插件的包目录、批准状态与账本 schema;旧布局(槽目录直接是缓存)由
resolveCurrentVersionSync 自动迁移进版本目录,升级后用户无需任何操作,已装、
已批准、已启用的插件照旧可用。基于旧布局的升级用例见 sources-manager.test.ts
的 legacy 迁移用例。

验证:desktop main(plugin-market 149 全过)、renderer 6840 全过、typecheck、
check:i18n、check:i18n-glossary 通过。新增 5 个用例均验证过"去掉修复即失败"。
scriptRunnerPythonProtocol 与 makerSendToSessionOrdering 的 6 个失败在移除本次
改动后同样存在(来自合并进来的 upstream/main),与本 PR 无关。

Signed-off-by: xxxcc <xxxcc123@126.com>
This commit is contained in:
xxxcc
2026-08-01 01:15:36 +08:00
parent 763004d7ab
commit 4e33fb6b1d
6 changed files with 269 additions and 64 deletions

View File

@@ -115,6 +115,18 @@ function serverSummary(overrides: Partial<VisiblePluginSummary> = {}): VisiblePl
};
}
/** 服务端详情夹具:summary + 该 release 的完整 manifest。 */
function serverDetail() {
const summary = serverSummary();
return {
...summary,
currentRelease: {
...summary.currentRelease,
manifest: ghostManifest(summary.ghostId),
},
};
}
/** 在临时目录造一个本地市场夹具(marketplace.json + 插件目录)。 */
function writeLocalMarket(
root: string,
@@ -546,6 +558,39 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
expect(runtime.install).not.toHaveBeenCalled();
});
it('rejects installing a server plugin that a custom source also declares', async () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));
roots.push(root);
const dir = writeLocalMarket(root, 'team-lib', [{ rel: 'plugins/x', id: 'server-plugin' }]);
const h = harness([serverSummary()], [{ name: 'team-lib', dir }]);
const item = serverSummary();
h.api.detail.mockResolvedValue(serverDetail());
// 列表把两边都标成 conflict 并禁用;服务端安装入口只查服务端目录内部重名,
// 必须用同一口径重算,否则普通 UI 流程或直接 IPC 都能装进来并抢占 ghostId。
const snapshot = await h.service.snapshot();
expect(
snapshot.items.find((entry) => entry.sourceType === 'server')?.installState,
).toBe('conflict');
await expect(
h.service.install(item.id, { expectedReleaseId: item.currentRelease.id }),
).rejects.toMatchObject({ code: 'ALREADY_EXISTS' });
expect(h.api.download).not.toHaveBeenCalled();
});
it('keeps the conflict state on the server detail view', async () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));
roots.push(root);
const dir = writeLocalMarket(root, 'team-lib', [{ rel: 'plugins/x', id: 'server-plugin' }]);
const h = harness([serverSummary()], [{ name: 'team-lib', dir }]);
h.api.detail.mockResolvedValue(serverDetail());
// 详情传空重复集合会把 conflict 项恢复成可安装,给出绕过冲突闸的入口。
const detail = await h.service.detail(serverSummary().id);
expect(detail.installState).toBe('conflict');
});
it('uninstalls a custom market plugin through the shared uninstall path', async () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));
roots.push(root);

View File

@@ -83,6 +83,35 @@ describe('cloneMarketplace', () => {
expect(calls[2]?.args).toEqual(['checkout', 'main']);
});
it('checks out the default branch for sparse clones without an explicit ref', async () => {
const { executor, calls } = fakeExecutor((args) =>
args[0] === 'symbolic-ref' ? { stdout: 'origin/trunk\n' } : { stdout: 'abc123\n' },
);
await cloneMarketplace(
{ url: 'https://x.test/r.git', sparsePaths: ['plugins/a'] },
destPath(),
executor,
);
// 必须 checkout 真实分支:`checkout HEAD` 会留下 detached HEAD,后续刷新的
// `git pull --ff-only` 稳定失败,每次刷新都退化成整仓重克隆。
expect(calls.map((call) => call.args[0])).toContain('symbolic-ref');
expect(calls.some((call) => call.args[0] === 'checkout' && call.args[1] === 'trunk')).toBe(true);
expect(calls.some((call) => call.args[0] === 'checkout' && call.args[1] === 'HEAD')).toBe(false);
});
it('falls back to HEAD when the default branch cannot be resolved', async () => {
const { executor, calls } = fakeExecutor((args) => {
if (args[0] === 'symbolic-ref') throw new Error('no origin/HEAD');
return { stdout: 'abc123\n' };
});
await cloneMarketplace(
{ url: 'https://x.test/r.git', sparsePaths: ['plugins/a'] },
destPath(),
executor,
);
expect(calls.some((call) => call.args[0] === 'checkout' && call.args[1] === 'HEAD')).toBe(true);
});
it('cleans the staging directory and classifies auth failures', async () => {
const { executor } = fakeExecutor(() => {
throw Object.assign(new Error('fatal: Authentication failed'), {

View File

@@ -466,6 +466,10 @@ describe('MarketSourceManager git sources', () => {
// 读取方持有租约期间发生刷新:指针切走,但被持有的版本目录不得被清理,
// 逐文件读取(安装打包的实质动作)必须全程可用。
//
// 刷新刻意走**另一个 manager 实例**:生产里 PluginMarketService 每次操作都
// 新建一个 manager,租约注册表若是实例字段,安装持有的租约对刷新不可见。
const refresher = makeManager(root, executor);
failFetch = true;
await manager.withDiscoveredSource('hub', async (discovered) => {
expect(discovered.result.ok).toBe(true);
@@ -475,7 +479,7 @@ describe('MarketSourceManager git sources', () => {
// discover 返回 realpath(macOS 下 /var → /private/var),按 realpath 比对。
expect(pluginDir.startsWith(fs.realpathSync(heldDir))).toBe(true);
await manager.refreshSource('hub');
await refresher.refreshSource('hub');
const switched = fs.readFileSync(path.join(slot, 'current'), 'utf8').trim();
expect(switched).not.toBe(held);
// 指针已切走,旧版本仍在,且包内容仍可逐文件读取。
@@ -488,6 +492,43 @@ describe('MarketSourceManager git sources', () => {
expect(fs.existsSync(heldDir)).toBe(false);
});
it('keeps the activated version when persisting sync metadata fails', async () => {
const root = makeRoot();
const { executor } = fakeGit('hub', [{ rel: 'p', id: 'alpha' }]);
const store = new MarketSourceStore(path.join(root, 'sources.v1.json'));
const manager = new MarketSourceManager({
store,
cloneRoot: path.join(root, 'sources'),
homeDir: root,
gitExecutor: executor,
});
await manager.addSource({ source: 'openai/plugins' });
const slot = path.join(
root,
'sources',
marketCloneSlug('hub', {
type: 'git',
url: 'https://github.com/openai/plugins.git',
sparsePaths: [],
}),
);
// 指针已切到新版本后元数据写入失败(磁盘满/只读/文件锁):必须如实报错,
// 但绝不能删掉已生效的版本目录——否则指针指向不存在的目录,来源整体消失。
store.update = () => {
throw new Error('disk full');
};
await expect(manager.refreshSource('hub')).rejects.toThrow('disk full');
const current = fs.readFileSync(path.join(slot, 'current'), 'utf8').trim();
expect(
fs.existsSync(path.join(slot, 'versions', current, '.agents', 'plugins', 'marketplace.json')),
).toBe(true);
// 来源仍然可发现(不会因为缓存被回收而变成 market root missing)。
const discovered = await manager.discoverSource('hub');
expect(discovered.result.ok).toBe(true);
});
it('prunes dead incoming staging directories left by a killed refresh', async () => {
const root = makeRoot();
const { executor } = fakeGit('hub', [{ rel: 'p', id: 'alpha' }]);
@@ -550,8 +591,9 @@ describe('MarketSourceManager git sources', () => {
holdNextClone = true;
const slowRefresh = manager.refreshSource('hub');
await waitFor(() => gateClone !== null);
// 第二次刷新完整跑完:切指针并清理非 current 版本。
await manager.refreshSource('hub');
// 第二次刷新走另一个 manager 实例(与生产一致:每次操作新建 manager),
// 完整跑完:切指针并清理非 current 版本。
await makeManager(root, executor).refreshSource('hub');
// 关键断言:清理不得碰到第一次正在写入的暂存目录(它还不是 current)。
expect(fs.existsSync(stagingMarker)).toBe(true);

View File

@@ -294,10 +294,14 @@ export class PluginMarketService {
if (!compatible.ok) {
throwIpcError('GHOST_FILE_INVALID', 'This Plugin manifest is not supported');
}
// 详情必须与列表同口径:传空重复集合会把列表标为 conflict 并禁用的项
// 在详情页恢复成可安装,给出一条绕过冲突闸的入口。
const { duplicates } = await this.crossSourceDuplicateGhostIds(owner);
requireSameMarketOwner(owner);
return {
...this.toItem(
plugin,
NO_DUPLICATE_GHOST_IDS,
duplicates,
this.localInstallSnapshot(this.ledgerForOwner(owner)),
),
manifest: compatible.manifest,
@@ -353,6 +357,16 @@ export class PluginMarketService {
const existing = getGhostManager()
.list()
.some((ghost) => ghost.manifest.id === plugin.ghostId);
// 上面只查了服务端目录内部重名。列表的 conflict 判定是"服务端 + 全部自定义
// 来源"合并计数,这里必须用同一口径重算,否则被标为 conflict 并禁用的服务端
// 项仍能经普通 UI 流程或直接 IPC 装进来并抢占 ghostId。
const record = ledger.installationForGhost(plugin.ghostId);
await this.assertSourceOwnsGhostId({
owner,
ghostId: plugin.ghostId,
ownsInstall: Boolean(existing && record?.installed && record.pluginId === plugin.id),
knownServerPlugins: catalog,
});
return {
ghost: await this.installDetail(
plugin,
@@ -491,10 +505,13 @@ export class PluginMarketService {
if (!plugin) {
throwIpcError('NOT_FOUND', 'The Plugin is no longer listed by this marketplace');
}
// 与服务端详情同理:详情必须沿用列表的 conflict 口径,不能传空重复集合。
const { duplicates } = await this.crossSourceDuplicateGhostIds(owner);
requireSameMarketOwner(owner);
return {
...this.customToItem(
{ config: discovered.config, plugin },
NO_DUPLICATE_GHOST_IDS,
duplicates,
this.localInstallSnapshot(this.ledgerForOwner(owner)),
),
manifest: plugin.manifest,
@@ -503,36 +520,53 @@ export class PluginMarketService {
}
/**
* 安装入口重算 ghostId 所有权:列表把跨来源重名标成 `conflict` 并禁用,但那份
* 判定是快照期算的。安装 IPC 可以被不可信 Renderer 直接调用,也可能在详情打开
* 后由另一个窗口添加了声明同一 ghostId 的来源 —— 所以真正产生副作用之前必须
* 用 snapshot 的同一口径(服务端目录 + 全部自定义来源合并计数)重新确认。
* 按 snapshot 的同一口径重算跨来源重复 ghostId(服务端目录 + 全部自定义来源)。
* 详情与安装都用它,保证"列表标成 conflict 并禁用"的判定不会在别处被放宽。
*
* 服务端目录不可用时降级为仅自定义来源(自定义安装本就不要求服务端可用):
* 未安装的服务端插件不构成本地运行期抢占,已安装的那种情况由调用方的
* `existing` 检查拦住。
* 服务端目录可选:未配置或拉取失败时降级为仅自定义来源,并把 `serverKnown`
* 置为 false 供调用方判断。自定义安装本就不要求服务端可用;未安装的服务端插件
* 不构成本地运行期抢占,已安装的那种情况由安装侧的 `existing` 检查拦住。
*/
private async assertCustomSourceOwnsGhostId(input: {
owner: ActiveAppSession;
pluginId: string;
ghostId: string;
ownsInstall: boolean;
}): Promise<void> {
// 已经拥有当前安装记录的来源保留所有权(先装先得,与列表判定一致)。
if (input.ownsInstall) return;
const customEntries = await this.discoverCustomEntriesSafe(input.owner);
let serverPlugins: readonly VisiblePluginSummary[] = [];
if (getClientEndpoint('pluginApiBaseUrl')) {
private async crossSourceDuplicateGhostIds(
owner: ActiveAppSession,
knownServerPlugins?: readonly VisiblePluginSummary[],
): Promise<{ duplicates: ReadonlySet<string>; serverKnown: boolean }> {
const customEntries = await this.discoverCustomEntriesSafe(owner);
let serverPlugins: readonly VisiblePluginSummary[] = knownServerPlugins ?? [];
let serverKnown = knownServerPlugins !== undefined;
if (!serverKnown && getClientEndpoint('pluginApiBaseUrl')) {
try {
serverPlugins = visiblePluginsForOwner(input.owner, await this.api.listAll());
serverPlugins = visiblePluginsForOwner(owner, await this.api.listAll());
serverKnown = true;
} catch (error) {
log.warn('market catalog unavailable while verifying custom install ownership', {
log.warn('market catalog unavailable while recomputing cross-source duplicates', {
error: error instanceof Error ? error.message : String(error),
});
}
}
requireSameMarketOwner(input.owner);
if (combinedDuplicateGhostIds(serverPlugins, customEntries).has(input.ghostId)) {
requireSameMarketOwner(owner);
return { duplicates: combinedDuplicateGhostIds(serverPlugins, customEntries), serverKnown };
}
/**
* 安装入口重算 ghostId 所有权:列表把跨来源重名标成 `conflict` 并禁用,但那份
* 判定是快照期算的。安装 IPC 可以被不可信 Renderer 直接调用,也可能在详情打开
* 后由另一个窗口添加了声明同一 ghostId 的来源 —— 所以真正产生副作用之前必须
* 用同一口径重新确认。服务端与自定义两条安装路径共用这道闸。
*/
private async assertSourceOwnsGhostId(input: {
owner: ActiveAppSession;
ghostId: string;
ownsInstall: boolean;
knownServerPlugins?: readonly VisiblePluginSummary[];
}): Promise<void> {
// 已经拥有当前安装记录的来源保留所有权(先装先得,与列表判定一致)。
if (input.ownsInstall) return;
const { duplicates } = await this.crossSourceDuplicateGhostIds(
input.owner,
input.knownServerPlugins,
);
if (duplicates.has(input.ghostId)) {
throwIpcError('ALREADY_EXISTS', 'Another marketplace already provides this Plugin ID');
}
}
@@ -581,9 +615,8 @@ export class PluginMarketService {
if (existing && (!currentRecord?.installed || currentRecord.pluginId !== pluginId)) {
throwIpcError('ALREADY_EXISTS', 'A local Plugin already uses this Plugin ID');
}
await this.assertCustomSourceOwnsGhostId({
await this.assertSourceOwnsGhostId({
owner,
pluginId,
ghostId: plugin.ghostId,
ownsInstall: Boolean(existing && currentRecord?.installed && currentRecord.pluginId === pluginId),
});

View File

@@ -137,6 +137,30 @@ export function isGitVersionSupported(version: { major: number; minor: number })
return version.minor >= MIN_GIT_VERSION.minor;
}
/**
* 远端默认分支名(`origin/HEAD` → `main`/`master`/…)。`--no-checkout` 克隆后
* 拿它来 checkout 一个**真实分支**,保留上游跟踪关系,后续 `pull --ff-only`
* 才能快进。解析失败返回 null,由调用方决定退路。
*/
async function defaultBranchName(
cwd: string,
executor: GitExecutor,
): Promise<string | null> {
try {
const { stdout } = await executor(['symbolic-ref', '--short', 'refs/remotes/origin/HEAD'], {
cwd,
timeoutMs: 10_000,
});
// 形如 `origin/main`,取 remote 前缀之后的分支名。
const value = stdout.trim();
const slash = value.indexOf('/');
const branch = slash >= 0 ? value.slice(slash + 1) : value;
return branch.length > 0 ? branch : null;
} catch {
return null;
}
}
/**
* 克隆市场仓库到 destPath(staging + rename 原子替换;Windows 不允许 rename
* 覆盖非空目录,因此调用方需保证 destPath 不存在或先移除)。
@@ -165,7 +189,11 @@ export async function cloneMarketplace(
cwd: stagingPath,
timeoutMs,
});
await executor(['checkout', input.ref ?? 'HEAD'], { cwd: stagingPath, timeoutMs });
// 无显式 ref 时必须 checkout 默认**分支**而不是 `HEAD`:后者留下 detached
// HEAD,刷新走的 `git pull --ff-only` 会稳定失败并回落到整仓重克隆,
// 等于每次刷新都重新 clone。取不到默认分支名时才退回 HEAD。
const target = input.ref ?? (await defaultBranchName(stagingPath, executor)) ?? 'HEAD';
await executor(['checkout', target], { cwd: stagingPath, timeoutMs });
}
await fs.promises.mkdir(path.dirname(destPath), { recursive: true });
await fs.promises.rename(stagingPath, destPath);

View File

@@ -19,6 +19,8 @@
* 仍被引用的进 pendingDeletes,等最后一个引用释放时才删。缺了这层,刷新在
* 切完指针后立即删非 current 版本,会把"已解析到旧版目录、正在异步发现或
* 逐文件打包安装"的读取方从中途抽走(安装随机失败/输入残缺)。
* - 计数注册表是**模块级、按绝对路径为键**的(见下方 versionRefs):调用方每次
* 操作都新建一个 manager,放实例字段会让安装持有的租约对刷新不可见。
* - 引用登记的关键是**与指针解析同步完成**:resolveCurrentVersionSync 全同步,
* acquireCurrentVersion 在同一个同步块里解析并登记,中间不 await,因此不存在
* "解析到登记"的窗口——任何 fs 回调都插不进来。文件系统标记(.reading 之类)
@@ -88,6 +90,30 @@ export function marketCloneSlug(name: string, source: MarketSource): string {
return `${base}-${hash}`;
}
/*
* 缓存版本目录的读取引用注册表。**必须是模块级、按绝对路径为键**:
* `PluginMarketService` 每次操作都新建一个 `MarketSourceManager`(store/cloneRoot
* 按操作开始时的 owner 现绑),若把计数放实例字段,安装 manager 持有的租约对刷新
* manager 完全不可见,刷新照样会删掉正在被打包读取的旧版本 —— 计数等于没做。
*
* 受保护的对象本来就是"文件系统路径",按路径为键才是正确的作用域;owner 隔离由
* 路径自带(`ownerScopedUserDataPath` 已把 owner 编进 cloneRoot),不同 owner 的
* 键天然不相交。仅 main 进程内有效(同一 userData 只有一个 main 进程,Electron
* 单实例)。
*/
/** 正在被读取的版本目录 → 引用数。清理只删引用数为 0 的版本目录。 */
const versionRefs = new Map<string, number>();
/** 清理时仍被引用、推迟到最后一个引用释放后再删的版本目录。 */
const pendingDeletes = new Set<string>();
/**
* 正在进行的刷新的暂存目录。清理按**前缀**放过它们:git clone 还会在同级建
* `<incoming>.staging-<uuid>`,只比对完整路径会把那个在途目录删掉。
*/
const activeIncoming = new Set<string>();
export class MarketSourceManager {
private readonly log = createLogger('plugin-market-sources');
@@ -179,22 +205,6 @@ export class MarketSourceManager {
return null;
}
/**
* 正在被读取的版本目录 → 引用数。清理只删引用数为 0 的版本目录。
* 进程内计数就是全部事实:所有发现/安装/刷新都发生在 main 进程的同一实例族,
* 且引用登记与指针解析同步完成,不需要任何跨进程/文件系统标记。
*/
private readonly versionRefs = new Map<string, number>();
/** 清理时仍被引用、推迟到最后一个引用释放后再删的版本目录。 */
private readonly pendingDeletes = new Set<string>();
/**
* 正在进行的刷新的暂存目录。清理按**前缀**放过它们:git clone 还会在同级建
* `<incoming>.staging-<uuid>`,只比对完整路径会把那个在途目录删掉。
*/
private readonly activeIncoming = new Set<string>();
/**
* 解析当前版本目录并登记一个读取引用。**解析与登记之间没有 await**:
* JS 单线程 run-to-completion 保证这段同步块执行期间不会有任何 fs 回调
@@ -215,18 +225,18 @@ export class MarketSourceManager {
* 历史版本删掉。
*/
private retainVersion(dir: string): void {
this.versionRefs.set(dir, (this.versionRefs.get(dir) ?? 0) + 1);
versionRefs.set(dir, (versionRefs.get(dir) ?? 0) + 1);
}
/** 释放引用;最后一个引用释放时执行被推迟的清理。 */
private releaseVersion(dir: string): void {
const remaining = (this.versionRefs.get(dir) ?? 0) - 1;
const remaining = (versionRefs.get(dir) ?? 0) - 1;
if (remaining > 0) {
this.versionRefs.set(dir, remaining);
versionRefs.set(dir, remaining);
return;
}
this.versionRefs.delete(dir);
if (!this.pendingDeletes.delete(dir)) return;
versionRefs.delete(dir);
if (!pendingDeletes.delete(dir)) return;
// 推迟期间该版本可能已经成为 current(并发刷新:A 的清理把 B 正在暂存的
// 目录记为待删,随后 B 把指针切到它)。执行前重新核对,不删当前生效版本。
if (this.isCurrentVersionDir(dir)) return;
@@ -319,8 +329,8 @@ export class MarketSourceManager {
const dir = path.join(this.versionsDir(slot), entry);
// 有读者:推迟到最后一个引用释放。释放路径同样会消费 pendingDeletes,
// 因此目录不会被永久留下(引用在 finally 里释放)。
if ((this.versionRefs.get(dir) ?? 0) > 0) {
this.pendingDeletes.add(dir);
if ((versionRefs.get(dir) ?? 0) > 0) {
pendingDeletes.add(dir);
continue;
}
await this.removeVersionDir(dir);
@@ -345,7 +355,7 @@ export class MarketSourceManager {
if (entry.includes('/') || entry.includes('\\') || entry === '..' || entry === '.') continue;
const dir = path.join(root, entry);
let inFlight = false;
for (const active of this.activeIncoming) {
for (const active of activeIncoming) {
if (dir === active || dir.startsWith(active)) {
inFlight = true;
break;
@@ -497,7 +507,7 @@ export class MarketSourceManager {
// 清理就永远碰不到在途工作。
const incoming = this.incomingDir(slot);
// 在途登记:并发刷新的 incoming/ 清理据此按前缀放过本次的暂存与 staging 目录。
this.activeIncoming.add(incoming);
activeIncoming.add(incoming);
try {
await fs.promises.mkdir(path.dirname(incoming), { recursive: true });
await fs.promises.mkdir(this.versionsDir(slot), { recursive: true });
@@ -558,26 +568,44 @@ export class MarketSourceManager {
// 并发刷新的清理会把它当历史版本删掉。
this.retainVersion(newDir);
try {
await fs.promises.rename(incoming, newDir);
await this.activateVersion(slot, newVersion);
// 落位与激活是唯一可回滚的一段:失败时指针可能仍指向旧版本,
// 此时清掉暂存与半落位目录是安全的。
try {
await fs.promises.rename(incoming, newDir);
await this.activateVersion(slot, newVersion);
} catch (error) {
await fs.promises.rm(incoming, { recursive: true, force: true }).catch(() => undefined);
// 只有指针确实没有指向 newDir 时才删它。指针一旦生效,newDir 就是唯一
// 有效缓存,删掉会留下"指针指向不存在目录"的槽,整个来源从列表消失。
if (!this.isCurrentVersionDir(newDir)) {
await fs.promises.rm(newDir, { recursive: true, force: true }).catch(() => undefined);
}
throw error;
}
// —— 到这里指针已生效:newDir 是当前唯一有效缓存,后续任何失败都不得删它 ——
// 指针已切到新版本:清理非 current 版本,仍被读取的推迟到引用释放后再删。
await this.pruneStaleVersions(slot);
const syncedAt = this.now();
this.deps.store.update(name, { lastSyncedAt: syncedAt, lastRevision: revision });
try {
this.deps.store.update(name, { lastSyncedAt: syncedAt, lastRevision: revision });
} catch (error) {
// 元数据写入失败(磁盘满/只读/文件锁)不影响缓存有效性:如实上报失败,
// 但绝不回收已生效的版本目录——下次刷新会重写元数据。
this.log.error('failed to persist marketplace sync metadata', {
name,
error: error instanceof Error ? error.message : String(error),
});
throw error;
}
return this.toSummary(
{ ...config, lastSyncedAt: syncedAt, lastRevision: revision },
discovered.marketplace,
);
} catch (error) {
// 落位/激活失败:暂存与半落位的目录都清掉,当前版本与指针不受影响。
await fs.promises.rm(incoming, { recursive: true, force: true }).catch(() => undefined);
await fs.promises.rm(newDir, { recursive: true, force: true }).catch(() => undefined);
throw error;
} finally {
this.releaseVersion(newDir);
}
} finally {
this.activeIncoming.delete(incoming);
activeIncoming.delete(incoming);
}
}