dsh-config-manager 0.3.1 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/client.d.ts +54 -3
- package/lib/client.js +1078 -845
- package/lib/core/env-lock-lifecycle.d.ts +45 -0
- package/lib/core/env-lock-lifecycle.js +43 -0
- package/lib/core/history-prune.d.ts +34 -0
- package/lib/core/history-prune.js +43 -0
- package/lib/core/index.d.ts +1 -1
- package/lib/core/index.js +1 -1
- package/lib/core/messages-core.d.ts +1 -0
- package/lib/core/messages-core.js +2 -0
- package/lib/core/migration-history.d.ts +46 -4
- package/lib/core/migration-history.js +60 -7
- package/lib/index.d.ts +2 -2
- package/lib/index.js +26 -8
- package/lib/routes/history.js +70 -5
- package/lib/routes/index.d.ts +1 -1
- package/lib/routes/kit.d.ts +2 -2
- package/lib/routes/messages.d.ts +1 -0
- package/lib/routes/messages.js +3 -0
- package/lib/sync/autosync-scheduler.js +12 -2
- package/lib/sync/backup-scheduler.js +6 -0
- package/lib/sync/baseline-heal.d.ts +35 -0
- package/lib/sync/baseline-heal.js +39 -0
- package/lib/sync/push-precheck.d.ts +35 -0
- package/lib/sync/push-precheck.js +58 -0
- package/lib/sync/sync-engine.d.ts +9 -12
- package/lib/sync/sync-engine.js +24 -43
- package/lib/sync/ui-prefs.d.ts +8 -0
- package/lib/sync/ui-prefs.js +8 -0
- package/lib/ui/history-model.js +3 -2
- package/lib/ui/overview-view.d.ts +3 -3
- package/lib/ui/overview-view.js +9 -1
- package/lib/utils/env-lock.d.ts +55 -1
- package/lib/utils/env-lock.js +131 -2
- package/lib/utils/messages-utils.d.ts +3 -0
- package/lib/utils/messages-utils.js +6 -0
- package/package.json +1 -1
- package/src/client/common/InfoHint.tsx +12 -3
- package/src/client/common/Skeleton.tsx +45 -8
- package/src/client/common/info-hint-guard.test.ts +196 -0
- package/src/client/common/routes.ts +3 -1
- package/src/client/common/skeleton-guard.test.ts +58 -0
- package/src/client/common/ui.tsx +17 -4
- package/src/client/config-manager.module.css +256 -27
- package/src/client/css-motion-guard.test.ts +230 -0
- package/src/client/environment/EnvironmentPanel.tsx +41 -29
- package/src/client/environment/maintenance/DiskUsageCard.tsx +28 -33
- package/src/client/environment/profiles-incomplete-ui.test.ts +9 -5
- package/src/client/export/ExportView.tsx +6 -6
- package/src/client/history/HistoryPanel.tsx +87 -2
- package/src/client/history/history-api.ts +49 -3
- package/src/client/history/history-locales.ts +32 -0
- package/src/client/home/HomePanel.tsx +64 -26
- package/src/client/locales.ts +2 -0
- package/src/client/market/MyConfigsWizard.tsx +12 -3
- package/src/client/recovery/RecoveryPanel.tsx +93 -92
- package/src/client/recovery/RollbackCard.tsx +25 -16
- package/src/client/sync/AutosyncCard.tsx +12 -6
- package/src/client/sync/ChannelConfigDialog.tsx +45 -45
- package/src/client/sync/DecryptPasswordCard.tsx +3 -3
- package/src/client/sync/SecurityOptionsCard.tsx +3 -3
- package/src/client/sync/SyncSectionPickerDialog.tsx +3 -3
- package/src/client/sync/history-model.ts +3 -0
- package/src/client/sync/sync-locales.ts +2 -0
- package/src/core/env-lock-lifecycle.ts +73 -0
- package/src/core/history-prune.test.ts +115 -0
- package/src/core/history-prune.ts +61 -0
- package/src/core/index.ts +2 -0
- package/src/core/messages-core.ts +2 -0
- package/src/core/migration-history.test.ts +97 -0
- package/src/core/migration-history.ts +74 -9
- package/src/index.ts +27 -8
- package/src/routes/history.ts +81 -4
- package/src/routes/index.ts +1 -1
- package/src/routes/kit.ts +2 -2
- package/src/routes/messages.ts +3 -0
- package/src/sync/autosync-scheduler.test.ts +23 -0
- package/src/sync/autosync-scheduler.ts +9 -2
- package/src/sync/backup-scheduler.ts +3 -0
- package/src/sync/baseline-heal.ts +74 -0
- package/src/sync/push-precheck.ts +75 -0
- package/src/sync/sync-engine.test.ts +88 -0
- package/src/sync/sync-engine.ts +33 -43
- package/src/sync/ui-prefs.test.ts +32 -0
- package/src/sync/ui-prefs.ts +16 -0
- package/src/ui/history-model.test.ts +2 -1
- package/src/ui/history-model.ts +3 -2
- package/src/ui/overview-view.test.ts +12 -0
- package/src/ui/overview-view.ts +12 -4
- package/src/utils/env-lock.test.ts +107 -0
- package/src/utils/env-lock.ts +124 -2
- package/src/utils/messages-utils.ts +6 -0
|
@@ -59,6 +59,38 @@ test('ui-prefs:会话格式处置(T1)字段往返 + 非法值忽略(绝
|
|
|
59
59
|
} finally { await fs.rm(dir, { recursive: true, force: true }); }
|
|
60
60
|
});
|
|
61
61
|
|
|
62
|
+
test('ui-prefs:历史保留上限往返 + 0 = 不限制 + 非法值丢弃(auto-cleanup)', async () => {
|
|
63
|
+
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'dsh-ui-prefs-retention-'));
|
|
64
|
+
try {
|
|
65
|
+
// 合法值往返(0 是「不限制」,必须能存下去,不能当成「没配置」被省略)
|
|
66
|
+
await writeUiPrefs(dir, { schemaVersion: 1, historyRetentionMaxEntries: 0 });
|
|
67
|
+
assert.equal((await readUiPrefs(dir)).historyRetentionMaxEntries, 0);
|
|
68
|
+
assert.equal(JSON.parse(await fs.readFile(path.join(dir, UI_PREFS_FILE), 'utf8')).historyRetentionMaxEntries, 0);
|
|
69
|
+
|
|
70
|
+
await writeUiPrefs(dir, { schemaVersion: 1, historyRetentionMaxEntries: 5000 });
|
|
71
|
+
assert.equal((await readUiPrefs(dir)).historyRetentionMaxEntries, 5000);
|
|
72
|
+
|
|
73
|
+
// updateUiPrefs 局部更新不丢其它字段
|
|
74
|
+
await updateUiPrefs(dir, { historyRetentionMaxEntries: 200 });
|
|
75
|
+
const afterPatch = await readUiPrefs(dir);
|
|
76
|
+
assert.equal(afterPatch.historyRetentionMaxEntries, 200);
|
|
77
|
+
|
|
78
|
+
// 未配置 → 不落字段、读回 undefined(由调用方回落 DEFAULT_MIGRATION_RETENTION)
|
|
79
|
+
await writeUiPrefs(dir, defaultUiPrefs());
|
|
80
|
+
assert.equal((await readUiPrefs(dir)).historyRetentionMaxEntries, undefined);
|
|
81
|
+
|
|
82
|
+
// 手改文件写非法值 → 忽略(负数 / 小数 / 超上限 / 字符串)
|
|
83
|
+
for (const bad of [-1, 1.5, 100_001, '1000']) {
|
|
84
|
+
await fs.writeFile(
|
|
85
|
+
path.join(dir, UI_PREFS_FILE),
|
|
86
|
+
JSON.stringify({ schemaVersion: 1, historyRetentionMaxEntries: bad }),
|
|
87
|
+
'utf8',
|
|
88
|
+
);
|
|
89
|
+
assert.equal((await readUiPrefs(dir)).historyRetentionMaxEntries, undefined, String(bad));
|
|
90
|
+
}
|
|
91
|
+
} finally { await fs.rm(dir, { recursive: true, force: true }); }
|
|
92
|
+
});
|
|
93
|
+
|
|
62
94
|
test('readUiPrefs:文件不存在 → 缺省(无通道)', async () => {
|
|
63
95
|
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'dsh-ui-prefs-default-'));
|
|
64
96
|
try {
|
package/src/sync/ui-prefs.ts
CHANGED
|
@@ -26,6 +26,7 @@ import path from 'node:path';
|
|
|
26
26
|
|
|
27
27
|
import { parseJsonSafe, stringifyJsonSafe } from '../utils/json.ts';
|
|
28
28
|
import { atomicWriteFile } from '../utils/atomic-write.ts';
|
|
29
|
+
import { isValidHistoryRetention } from '../core/migration-history.ts';
|
|
29
30
|
import { parseSyncChannel } from './sync-config.ts';
|
|
30
31
|
import type { SyncTransportType } from './sync-config.ts';
|
|
31
32
|
import type { SessionFormatDisposition } from '../core/types.ts';
|
|
@@ -73,6 +74,14 @@ export interface UiPrefs {
|
|
|
73
74
|
* 台账 / 回退路由本身仍可用:已有回滚点仍能查看、回退、删除、清理 —— 关的是「自动留点」。
|
|
74
75
|
*/
|
|
75
76
|
rollbackEnabled?: boolean;
|
|
77
|
+
/**
|
|
78
|
+
* 迁移历史自动清理的保留上限(条)。
|
|
79
|
+
*
|
|
80
|
+
* 语义:缺省 = 1000(core 的 DEFAULT_MIGRATION_RETENTION);0 = 不限制(只增不减,老行为);
|
|
81
|
+
* 非法值一律回落缺省。宿主每次写入历史后按本值节流清理最旧条目,
|
|
82
|
+
* 用户可在「迁移历史」面板改(GET/POST /history/retention)。
|
|
83
|
+
*/
|
|
84
|
+
historyRetentionMaxEntries?: number;
|
|
76
85
|
}
|
|
77
86
|
|
|
78
87
|
/** 缺省配置(首次无文件 / 损坏 / 不支持 schema 时回退) */
|
|
@@ -135,6 +144,10 @@ export async function readUiPrefs(dir: string): Promise<UiPrefs> {
|
|
|
135
144
|
if (obj['rollbackEnabled'] === true) {
|
|
136
145
|
prefs.rollbackEnabled = true;
|
|
137
146
|
}
|
|
147
|
+
// 保留上限只认 0..100000 的整数(与路由校验同一口径);字符串/小数/越界一律丢,回落缺省
|
|
148
|
+
if (isValidHistoryRetention(obj['historyRetentionMaxEntries'])) {
|
|
149
|
+
prefs.historyRetentionMaxEntries = obj['historyRetentionMaxEntries'];
|
|
150
|
+
}
|
|
138
151
|
return prefs;
|
|
139
152
|
}
|
|
140
153
|
|
|
@@ -172,6 +185,9 @@ export async function writeUiPrefs(dir: string, prefs: UiPrefs): Promise<void> {
|
|
|
172
185
|
...(prefs.releaseNotesDismissed === true ? { releaseNotesDismissed: true } : {}),
|
|
173
186
|
...(prefs.sessionFormatDisposition !== undefined ? { sessionFormatDisposition: prefs.sessionFormatDisposition } : {}),
|
|
174
187
|
...(prefs.rollbackEnabled === true ? { rollbackEnabled: true } : {}),
|
|
188
|
+
...(isValidHistoryRetention(prefs.historyRetentionMaxEntries)
|
|
189
|
+
? { historyRetentionMaxEntries: prefs.historyRetentionMaxEntries }
|
|
190
|
+
: {}),
|
|
175
191
|
};
|
|
176
192
|
const target = path.join(dir, UI_PREFS_FILE);
|
|
177
193
|
const data = stringifyJsonSafe(payload, { space: 2 });
|
|
@@ -56,7 +56,8 @@ test('HISTORY_KIND_OPTIONS:恰为 §5 全清单(含 profile-import)', () =
|
|
|
56
56
|
'sync-apply', 'autosync', 'recovery',
|
|
57
57
|
'backup', 'backup-manual', 'snapshot-delete', 'snapshot-prune',
|
|
58
58
|
]);
|
|
59
|
-
|
|
59
|
+
// pending(待裁决)排在 skipped 之前:它需要用户动手,比「跳过」更该先看到。
|
|
60
|
+
assert.deepEqual(HISTORY_RESULT_OPTIONS, ['success', 'pending', 'skipped', 'failed']);
|
|
60
61
|
});
|
|
61
62
|
|
|
62
63
|
test('groupByKind:空组不渲染、组内按时间倒序、顺序保持清单序', () => {
|
package/src/ui/history-model.ts
CHANGED
|
@@ -15,7 +15,8 @@ import type { MigrationKind, MigrationResult, StoredMigrationHistoryEntry } from
|
|
|
15
15
|
export function resultBadgeKind(result: MigrationResult): 'ok' | 'error' | 'warn' | 'info' {
|
|
16
16
|
if (result === 'success') return 'ok';
|
|
17
17
|
if (result === 'failed') return 'error';
|
|
18
|
-
|
|
18
|
+
// pending(0.4.1)= 跑完了但还有待裁决项:绝不当成失败(红),也不是跳过 —— 用琥珀告警色
|
|
19
|
+
return 'warn'; // skipped / pending
|
|
19
20
|
}
|
|
20
21
|
|
|
21
22
|
/** kind 标签(本地化 key 基名;i18n 字典用 `history.kind.<kind>` 渲染)。 */
|
|
@@ -34,7 +35,7 @@ export const HISTORY_KIND_OPTIONS: readonly MigrationKind[] = [
|
|
|
34
35
|
] as const;
|
|
35
36
|
|
|
36
37
|
/** 结果过滤选项。 */
|
|
37
|
-
export const HISTORY_RESULT_OPTIONS: readonly MigrationResult[] = ['success', '
|
|
38
|
+
export const HISTORY_RESULT_OPTIONS: readonly MigrationResult[] = ['success', 'pending', 'skipped', 'failed'] as const;
|
|
38
39
|
|
|
39
40
|
/** 过滤模型(UI 状态;空 = 不过滤)。 */
|
|
40
41
|
export interface HistoryFilter {
|
|
@@ -183,6 +183,18 @@ test('overviewActivity: 倒序 + limit + 徽章语义 + kind key 归一', () =>
|
|
|
183
183
|
assert.equal(overviewActivity([]).length, 0)
|
|
184
184
|
})
|
|
185
185
|
|
|
186
|
+
test('overviewActivity: result=pending(跑完但仍有待裁决)→ badge pending,既不红成失败也不混进跳过', () => {
|
|
187
|
+
const items = overviewActivity([
|
|
188
|
+
{ at: '2026-09-01T00:00:00Z', kind: 'autosync', result: 'pending', summary: '自动同步有冲突待裁决' },
|
|
189
|
+
{ at: '2026-09-02T00:00:00Z', kind: 'autosync', result: 'skipped', summary: '跳过' },
|
|
190
|
+
{ at: '2026-09-03T00:00:00Z', kind: 'autosync', result: 'failed', summary: '失败' },
|
|
191
|
+
])
|
|
192
|
+
const bySummary = (s: string) => items.find((i) => i.summary === s)!
|
|
193
|
+
assert.equal(bySummary('自动同步有冲突待裁决').badge, 'pending')
|
|
194
|
+
assert.equal(bySummary('跳过').badge, 'warn', 'skipped 仍是 warn —— 两种语义不能合并')
|
|
195
|
+
assert.equal(bySummary('失败').badge, 'error')
|
|
196
|
+
})
|
|
197
|
+
|
|
186
198
|
/* ---------------- 空态 ---------------- */
|
|
187
199
|
|
|
188
200
|
test('overviewEmptyState: 备份与快照均加载且为空 → true', () => {
|
package/src/ui/overview-view.ts
CHANGED
|
@@ -45,7 +45,7 @@ export interface OverviewSyncLite {
|
|
|
45
45
|
export interface OverviewHistoryLite {
|
|
46
46
|
at: string
|
|
47
47
|
kind: string
|
|
48
|
-
result: 'success' | 'failed' | 'skipped'
|
|
48
|
+
result: 'success' | 'failed' | 'skipped' | 'pending'
|
|
49
49
|
summary: string
|
|
50
50
|
}
|
|
51
51
|
|
|
@@ -290,8 +290,8 @@ export function overviewKindKey(kind: string): string {
|
|
|
290
290
|
|
|
291
291
|
export interface OverviewActivityItem {
|
|
292
292
|
at: string
|
|
293
|
-
/** 徽章语义(success→ok / failed→error / skipped→warn,与 history-model 同判定)。 */
|
|
294
|
-
badge: 'ok' | 'error' | 'warn'
|
|
293
|
+
/** 徽章语义(success→ok / failed→error / skipped→warn / pending→pending,与 history-model 同判定)。 */
|
|
294
|
+
badge: 'ok' | 'error' | 'warn' | 'pending'
|
|
295
295
|
/** UI 渲染 key(`overview.kind.<kind>`;未知 kind 归一为 other → `overview.kind.other`)。 */
|
|
296
296
|
kindKey: string
|
|
297
297
|
/** 原始摘要(上层渲染前 redact())。 */
|
|
@@ -311,7 +311,15 @@ export function overviewActivity(
|
|
|
311
311
|
})
|
|
312
312
|
return sorted.slice(0, limit).map((e) => ({
|
|
313
313
|
at: e.at,
|
|
314
|
-
badge: e.result === 'success'
|
|
314
|
+
badge: e.result === 'success'
|
|
315
|
+
? 'ok'
|
|
316
|
+
: e.result === 'failed'
|
|
317
|
+
? 'error'
|
|
318
|
+
// pending:跑完了但仍有待裁决项(自动同步下行冲突未裁决)—— 首页必须说「待裁决」,
|
|
319
|
+
// 既不能红成「失败」,也不该混进「跳过」(那一轮确有上传/应用发生)
|
|
320
|
+
: e.result === 'pending'
|
|
321
|
+
? 'pending'
|
|
322
|
+
: 'warn',
|
|
315
323
|
kindKey: overviewKindKey(e.kind),
|
|
316
324
|
summary: e.summary,
|
|
317
325
|
}))
|
|
@@ -9,6 +9,9 @@
|
|
|
9
9
|
* - 跨进程用例(#3 / #16 / #17)用子进程 `node child.mjs` 动态 import 真实 env-lock.ts 验证,
|
|
10
10
|
* 父进程与子进程共享同一 locks 目录(真实文件级互斥)。
|
|
11
11
|
*
|
|
12
|
+
* 另含 §11.7(未发布):自动回收只承认结构性可证 stale(owner 确证死亡 / PID 复用),
|
|
13
|
+
* corrupt 残留与心跳长过期启发式一律拒绝;退出兜底释放与孤儿心跳清理同样只动「可证」对象。
|
|
14
|
+
*
|
|
12
15
|
* 只测试,不修改实现。若某用例暴露实现 bug,以诊断注释记录 interleaving,供 Lead 修复。
|
|
13
16
|
*/
|
|
14
17
|
import test from 'node:test';
|
|
@@ -1308,3 +1311,107 @@ test('§11.5-p6 linux `/proc/<pid>/stat` 解析:comm 含空格/括号时也要
|
|
|
1308
1311
|
assert.equal(parseLinuxProcessStarttime('4796 (node) S 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 x'), null, '字段 22 非数字 → null');
|
|
1309
1312
|
});
|
|
1310
1313
|
|
|
1314
|
+
/* ------------------------------------------------- §11.7 自动回收边界(P1–P4) */
|
|
1315
|
+
|
|
1316
|
+
/*
|
|
1317
|
+
* 这一组锁定「自动路径」的**边界**而不是能力:可证的才删,不可证的必须一动不动。
|
|
1318
|
+
* 背景(真机):正常关窗时后台同步正在跑 → 各入口 finally 等不到 → ownership + heartbeat 留盘;
|
|
1319
|
+
* 下次启动分类是 NORMAL(无未决 journal),于是锁一直在、写操作全 423、自动同步每轮静默 skip。
|
|
1320
|
+
* 修法必须同时满足两条:自动路径能把**可证**的摘掉,且绝不因为「看起来像残留」就删。
|
|
1321
|
+
*/
|
|
1322
|
+
|
|
1323
|
+
test('§11.7-a 自动回收:owner pid 确证死亡 → 删 ownership + 该 owner 的 sidecar;removedOwner 带 op/pid', async (t) => {
|
|
1324
|
+
const locksDir = tmp(t);
|
|
1325
|
+
const clk = makeClock();
|
|
1326
|
+
const p = makeProbe();
|
|
1327
|
+
p.respond(() => ({ alive: false, osProcessStartIdentity: null }));
|
|
1328
|
+
await seedOwnership(locksDir, { instanceId: 'dead1', pid: 999_001, op: 'autosync' });
|
|
1329
|
+
await seedHeartbeat(locksDir, 'dead1', clk.clock() - 60_000);
|
|
1330
|
+
const m = lockManager(t, { locksDir, now: clk.clock, probe: p.probe, staleAfterMs: 1000 });
|
|
1331
|
+
const r = await m.reclaimProvableStaleLock();
|
|
1332
|
+
assert.notEqual(r, null, '确证死亡属结构性可证 → 必须回收');
|
|
1333
|
+
assert.equal(r?.ok, true);
|
|
1334
|
+
assert.deepEqual(r?.removedOwner, { op: 'autosync', pid: 999_001 }, '日志需要知道回收了谁的锁');
|
|
1335
|
+
assert.deepEqual(fssync.readdirSync(locksDir), [], 'ownership 与该 owner 的 heartbeat 都必须清掉');
|
|
1336
|
+
});
|
|
1337
|
+
|
|
1338
|
+
test('§11.7-b 自动回收:心跳**长过期**启发式(pid 存活、身份不可验证)→ 拒绝,文件保留;显式回收仍可做', async (t) => {
|
|
1339
|
+
const locksDir = tmp(t);
|
|
1340
|
+
const clk = makeClock();
|
|
1341
|
+
const p = makeProbe();
|
|
1342
|
+
p.respond(() => ({ alive: true, osProcessStartIdentity: null }));
|
|
1343
|
+
await seedOwnership(locksDir, { instanceId: 'heur1', pid: 999_002 });
|
|
1344
|
+
await seedHeartbeat(locksDir, 'heur1', clk.clock() - 120_000);
|
|
1345
|
+
const m = lockManager(t, { locksDir, now: clk.clock, probe: p.probe, staleAfterMs: 1000, longExpiredAfterMs: 5_000 });
|
|
1346
|
+
assert.equal((await m.inspectLockState()).state, 'STALE_LOCK_DETECTED', '前提:显式判据(长过期)确实判 stale');
|
|
1347
|
+
assert.equal(await m.reclaimProvableStaleLock(), null, '长过期只是「像残留」,自动路径不得据此删锁');
|
|
1348
|
+
assert.ok(fssync.existsSync(path.join(locksDir, OWNERSHIP_FILE)), '拒绝后必须原样保留现场');
|
|
1349
|
+
const explicit = await m.recoverStaleLock();
|
|
1350
|
+
assert.equal(explicit.ok, true, '显式回收(--recover-stale-lock)口径不变,仍可回收');
|
|
1351
|
+
});
|
|
1352
|
+
|
|
1353
|
+
test('§11.7-c 自动回收:corrupt/空 ownership(崩溃残留)→ 返回 null,不删、不 rename', async (t) => {
|
|
1354
|
+
const locksDir = tmp(t);
|
|
1355
|
+
await fs.writeFile(path.join(locksDir, OWNERSHIP_FILE), '');
|
|
1356
|
+
const m = lockManager(t, { locksDir });
|
|
1357
|
+
assert.equal(await m.reclaimProvableStaleLock(), null, '无有效 owner 的残留不归自动路径判断');
|
|
1358
|
+
assert.deepEqual(fssync.readdirSync(locksDir), [OWNERSHIP_FILE], '现场必须保留,交给显式回收');
|
|
1359
|
+
});
|
|
1360
|
+
|
|
1361
|
+
test('§11.7-d 自动回收:心跳新鲜(有人在干活)→ 不探测进程、直接返回 null', async (t) => {
|
|
1362
|
+
const locksDir = tmp(t);
|
|
1363
|
+
const a = lockManager(t, { locksDir });
|
|
1364
|
+
const acq = await a.acquire({ op: 'holder' });
|
|
1365
|
+
assert.equal(acq.state, 'ACQUIRED');
|
|
1366
|
+
await waitHeartbeat(a); // 首写是异步的:判 fresh 前必须已落盘
|
|
1367
|
+
const p = makeProbe();
|
|
1368
|
+
p.respond(() => ({ alive: true, osProcessStartIdentity: null }));
|
|
1369
|
+
const b = lockManager(t, { locksDir, probe: p.probe });
|
|
1370
|
+
assert.equal(await b.reclaimProvableStaleLock(), null, '活锁不得进入回收流程');
|
|
1371
|
+
assert.equal(p.calls, 0, '新鲜心跳就是「有人在干活」的证据,连进程探测都不该付(Windows 上要 spawn PowerShell)');
|
|
1372
|
+
await a.release(acq.token!);
|
|
1373
|
+
});
|
|
1374
|
+
|
|
1375
|
+
test('§11.7-e 自动回收:pid 存活但 OS identity 与 recorded 不同(PID 复用)→ 回收', async (t) => {
|
|
1376
|
+
const locksDir = tmp(t);
|
|
1377
|
+
const clk = makeClock();
|
|
1378
|
+
const p = makeProbe();
|
|
1379
|
+
p.respond(() => ({ alive: true, osProcessStartIdentity: 'identity-B' }));
|
|
1380
|
+
await seedOwnership(locksDir, { instanceId: 'reused1', pid: 999_003, osIdentity: 'identity-A' });
|
|
1381
|
+
await seedHeartbeat(locksDir, 'reused1', clk.clock() - 60_000);
|
|
1382
|
+
const m = lockManager(t, { locksDir, now: clk.clock, probe: p.probe, staleAfterMs: 1000 });
|
|
1383
|
+
const r = await m.reclaimProvableStaleLock();
|
|
1384
|
+
assert.equal(r?.ok, true, '原 owner 已死(同一 pid 已被别的进程占用)= 结构性可证');
|
|
1385
|
+
assert.deepEqual(fssync.readdirSync(locksDir), []);
|
|
1386
|
+
});
|
|
1387
|
+
|
|
1388
|
+
test('§11.7-f 退出兜底释放:只删自己 instanceId 的 ownership/sidecar;未持锁时是 no-op', async (t) => {
|
|
1389
|
+
const locksDir = tmp(t);
|
|
1390
|
+
const a = lockManager(t, { locksDir });
|
|
1391
|
+
const acq = await a.acquire({ op: 'inflight' });
|
|
1392
|
+
assert.equal(acq.state, 'ACQUIRED');
|
|
1393
|
+
await waitHeartbeat(a);
|
|
1394
|
+
a.releaseOnExitSync();
|
|
1395
|
+
assert.deepEqual(fssync.readdirSync(locksDir), [], '自己持有的锁与心跳都必须被同步清掉(exit 里不能 await)');
|
|
1396
|
+
// 没持锁(或持的是别人的锁)→ 绝不删
|
|
1397
|
+
await seedOwnership(locksDir, { instanceId: 'foreign1', pid: 999_004 });
|
|
1398
|
+
const b = lockManager(t, { locksDir });
|
|
1399
|
+
b.releaseOnExitSync();
|
|
1400
|
+
assert.deepEqual(fssync.readdirSync(locksDir), [OWNERSHIP_FILE], 'foreign ownership 一根汗毛都不许动');
|
|
1401
|
+
});
|
|
1402
|
+
|
|
1403
|
+
test('§11.7-g 孤儿心跳清理:只删「非持有者且心跳过期」的 sidecar;持有者/新鲜/读不出的都保留', async (t) => {
|
|
1404
|
+
const locksDir = tmp(t);
|
|
1405
|
+
const clk = makeClock();
|
|
1406
|
+
await seedOwnership(locksDir, { instanceId: 'hold1', pid: 999_005 });
|
|
1407
|
+
await seedHeartbeat(locksDir, 'hold1', clk.clock() - 500); // 当前持有者,心跳仍新鲜
|
|
1408
|
+
await seedHeartbeat(locksDir, 'gone1', clk.clock() - 60_000); // 崩溃残留
|
|
1409
|
+
await fs.writeFile(path.join(locksDir, heartbeatFile('bad1')), 'not json'); // 读不出 → 无判据
|
|
1410
|
+
const m = lockManager(t, { locksDir, now: clk.clock, staleAfterMs: 1000 });
|
|
1411
|
+
assert.equal(await m.cleanupOrphanHeartbeats(), 1, '只有 gone1 满足「非持有者 + 心跳过期」');
|
|
1412
|
+
const left = fssync.readdirSync(locksDir).sort();
|
|
1413
|
+
assert.deepEqual(left, [OWNERSHIP_FILE, heartbeatFile('bad1'), heartbeatFile('hold1')].sort());
|
|
1414
|
+
assert.ok(fssync.existsSync(path.join(locksDir, heartbeatFile('hold1'))), '持有者的 heartbeat 是活锁判据,不许删');
|
|
1415
|
+
});
|
|
1416
|
+
|
|
1417
|
+
|
package/src/utils/env-lock.ts
CHANGED
|
@@ -11,7 +11,11 @@
|
|
|
11
11
|
* - `environment.lock` 是 **immutable ownership record**:创建后直到 release 不被 rename/replace。
|
|
12
12
|
* - heartbeat 走 **独立 sidecar** `environment.heartbeat.<instanceId>`,可安全用 Phase 1 `atomicWriteFile` 更新。
|
|
13
13
|
* - **operation-scoped** `MutationLockToken`:禁止 process-level reentrant(instanceId/handle/reenterCount 判嵌套)。
|
|
14
|
-
* - stale 检测只分类(LOCKED / STALE_LOCK_DETECTED / UNKNOWN_STATE
|
|
14
|
+
* - stale 检测只分类(LOCKED / STALE_LOCK_DETECTED / UNKNOWN_STATE);**acquire 侧绝不自动 unlink/takeover**。
|
|
15
|
+
* - 唯一允许的**自动**回收 = `reclaimProvableStaleLock()` → `recoverStaleLock({ require: 'provable' })`:
|
|
16
|
+
* 只删「owner 确证死亡 / PID 复用」两类**结构性可证** stale;corrupt 残留与 issue #36 的心跳长过期启发式
|
|
17
|
+
* **刻意排除**(那两类只是「像残留」,不能当误删许可)。
|
|
18
|
+
|
|
15
19
|
* - PID 复用判据**优先**用 OS process creation identity(linux `/proc`、win32 `Get-Process` StartTime、
|
|
16
20
|
* macOS `ps`);拿不到才退回「心跳长过期」启发式(issue #36)。
|
|
17
21
|
* - recover 是独立显式动作(CLI `--recover-stale-lock`),用原子 rename 捕获 + 二次验证,二次验证失败不覆盖 successor。
|
|
@@ -196,6 +200,16 @@ export interface MutationLockPort {
|
|
|
196
200
|
|
|
197
201
|
/** release(release 前校验 instanceId;mismatch 抛 EnvironmentLockOwnedByAnotherError) */
|
|
198
202
|
release(token: MutationLockToken): Promise<void>
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* 可选:只回收**结构性可证** stale 残留锁(owner 确证死亡 / PID 复用),其余一律不动。
|
|
206
|
+
* 端口实现缺这个方法(mock / 远端代理)时调用方必须当作「不支持」跳过,不得自行 inspect+release。
|
|
207
|
+
* @returns null = 无需/无权回收;否则为该次 recover 的结果
|
|
208
|
+
*/
|
|
209
|
+
reclaimProvableStaleLock?(): Promise<RecoverResult | null>
|
|
210
|
+
|
|
211
|
+
/** 可选:同步兜底释放本实例持有的锁(进程 exit/dispose 用;永不抛错)。 */
|
|
212
|
+
releaseOnExitSync?(): void
|
|
199
213
|
}
|
|
200
214
|
|
|
201
215
|
/**
|
|
@@ -293,6 +307,17 @@ export interface RecoverResult {
|
|
|
293
307
|
state: LockState
|
|
294
308
|
/** 诊断 */
|
|
295
309
|
detail?: string
|
|
310
|
+
/** 实际被回收的 owner(供自动路径记日志;corrupt 回收时为 undefined) */
|
|
311
|
+
removedOwner?: { op: string; pid: number }
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/**
|
|
315
|
+
* recover 的调用约束。
|
|
316
|
+
* - `'any'`(缺省)= 显式动作:沿用全部既有判据(含 corrupt 残留与心跳长过期启发式)。
|
|
317
|
+
* - `'provable'` = 自动路径:只承认 owner 确证死亡 / PID 复用,其余一律拒绝并保留现场。
|
|
318
|
+
*/
|
|
319
|
+
export interface RecoverOptions {
|
|
320
|
+
require?: 'any' | 'provable'
|
|
296
321
|
}
|
|
297
322
|
|
|
298
323
|
/**
|
|
@@ -348,6 +373,7 @@ function defaultIo(): EnvLockIo {
|
|
|
348
373
|
async stat(p) { try { return await fs.stat(p) } catch (e) { if (isENOENT(e)) return null; throw e } },
|
|
349
374
|
async readFileText(p) { return (await fs.readFile(p, 'utf8')).toString() },
|
|
350
375
|
async lstat(p) { try { return await fs.lstat(p) } catch (e) { if (isENOENT(e)) return null; throw e } },
|
|
376
|
+
async listLocksDir(d) { try { return await fs.readdir(d) } catch (e) { if (isENOENT(e)) return []; throw e } },
|
|
351
377
|
}
|
|
352
378
|
}
|
|
353
379
|
|
|
@@ -1053,7 +1079,7 @@ export class EnvironmentLockManager {
|
|
|
1053
1079
|
* **不自动触发**;仅当检测为 STALE_LOCK_DETECTED 才允许 capture。
|
|
1054
1080
|
* 二次验证失败 → quarantine(保留 recovering 文件,不 rename 回环境锁,不覆盖 successor)。
|
|
1055
1081
|
*/
|
|
1056
|
-
async recoverStaleLock(): Promise<RecoverResult> {
|
|
1082
|
+
async recoverStaleLock(options: RecoverOptions = {}): Promise<RecoverResult> {
|
|
1057
1083
|
// 1. inspect:必须 definitely stale 或 corrupt(崩溃残留无有效 owner)
|
|
1058
1084
|
const insp = await this.inspectLockState()
|
|
1059
1085
|
const st = await this.readOwnershipState()
|
|
@@ -1061,6 +1087,17 @@ export class EnvironmentLockManager {
|
|
|
1061
1087
|
// 判据必须是**结构性的**(inspectLockState 的 corruptOwnership / readOwnershipState 的 kind)——
|
|
1062
1088
|
// **不得**再依赖 detail 文案子串:detail 自 t5 起按界面语言本地化,按子串判定在英文界面下会失效。
|
|
1063
1089
|
const isCorruptReclaim = insp.state === 'UNKNOWN_STATE' && st.kind === 'corrupt'
|
|
1090
|
+
if (options.require === 'provable') {
|
|
1091
|
+
// 自动路径:只承认结构性可证 stale。corrupt 残留不是 stale(交给显式回收,不替用户判断损坏文件),
|
|
1092
|
+
// 长过期启发式也不是(issue #36 的放宽只是「像残留」)。判定必须发生在 rename **之前**:
|
|
1093
|
+
// rename 之后才发现不可证,quarantine 已经产生、ownership 已不在原位,等于把现场搞脏。
|
|
1094
|
+
if (insp.state !== 'STALE_LOCK_DETECTED' || st.kind !== 'ok') {
|
|
1095
|
+
return { ok: false, removed: false, state: insp.state, detail: insp.detail ?? utilsMsg('utils.envLock.notStaleRefuseRecovery') }
|
|
1096
|
+
}
|
|
1097
|
+
if (!(await this.isProvablyStale(st.rec))) {
|
|
1098
|
+
return { ok: false, removed: false, state: insp.state, detail: utilsMsg('utils.envLock.reclaimNotProvable') }
|
|
1099
|
+
}
|
|
1100
|
+
}
|
|
1064
1101
|
if (insp.state !== 'STALE_LOCK_DETECTED' && !isCorruptReclaim) {
|
|
1065
1102
|
return { ok: false, removed: false, state: insp.state, detail: insp.detail ?? utilsMsg('utils.envLock.notStaleRefuseRecovery') }
|
|
1066
1103
|
}
|
|
@@ -1122,12 +1159,44 @@ export class EnvironmentLockManager {
|
|
|
1122
1159
|
}
|
|
1123
1160
|
return {
|
|
1124
1161
|
ok: true, removed: true, state: 'STALE_LOCK_DETECTED',
|
|
1162
|
+
removedOwner: rec !== null ? { op: (rec as LockOwnershipRecord).op, pid: (rec as LockOwnershipRecord).owner.pid } : undefined,
|
|
1125
1163
|
detail: rec !== null
|
|
1126
1164
|
? utilsMsg('utils.envLock.removedStaleOwnership', { op: (rec as LockOwnershipRecord).op, pid: (rec as LockOwnershipRecord).owner.pid })
|
|
1127
1165
|
: utilsMsg('utils.envLock.removedCorruptOwnership'),
|
|
1128
1166
|
}
|
|
1129
1167
|
}
|
|
1130
1168
|
|
|
1169
|
+
/**
|
|
1170
|
+
* 自动回收入口(宿主启动 / 调度器本轮预检共用):只删**可证** stale,其余返回 null(一动不动)。
|
|
1171
|
+
*
|
|
1172
|
+
* 为什么不直接让调用方 inspect + recoverStaleLock:判据分散在 inspect(长过期放宽)、recover(corrupt 分支)
|
|
1173
|
+
* 和调用方文案三处必然漂移。这里把「自动」的边界收在一处,并且先做两次廉价读(ownership + sidecar):
|
|
1174
|
+
* - 无 ownership / corrupt → null(corrupt 留给显式回收);
|
|
1175
|
+
* - heartbeat 仍新鲜(≤ staleAfterMs)→ null:**死进程写不出新鲜心跳**,新鲜就是「有人在干活」的证据,
|
|
1176
|
+
* 连进程探测都省掉(Windows 上探测活 pid 要 spawn 一次 PowerShell,不能每轮同步都付这个钱)。
|
|
1177
|
+
* 通过这两道之后再走结构性判定(kill(pid,0) 的 ESRCH 是快路径)。
|
|
1178
|
+
*/
|
|
1179
|
+
async reclaimProvableStaleLock(): Promise<RecoverResult | null> {
|
|
1180
|
+
const st = await this.readOwnershipState()
|
|
1181
|
+
if (st.kind !== 'ok') return null
|
|
1182
|
+
const heartbeat = await this.readHeartbeat(st.rec.owner.instanceId).catch(() => null)
|
|
1183
|
+
if (heartbeat !== null && (this.now() - heartbeat.heartbeatAt) <= this.staleAfterMs) return null
|
|
1184
|
+
if (!(await this.isProvablyStale(st.rec))) return null
|
|
1185
|
+
return this.recoverStaleLock({ require: 'provable' })
|
|
1186
|
+
}
|
|
1187
|
+
|
|
1188
|
+
/** 结构性可证 stale:owner pid 确证死亡,或 pid 存活但 OS identity 与 recorded 不同(PID 复用)。
|
|
1189
|
+
* 与 inspectLockState / reProveStale 的「长过期」放宽**刻意不同**:自动回收不承认启发式。
|
|
1190
|
+
* 探测失败/不确定 → false(保守,绝不构成误删许可)。 */
|
|
1191
|
+
private async isProvablyStale(rec: LockOwnershipRecord): Promise<boolean> {
|
|
1192
|
+
let ident: ProcessIdentity
|
|
1193
|
+
try { ident = await this.probe.probe(rec.owner.pid) } catch { return false }
|
|
1194
|
+
if (!ident.alive) return true
|
|
1195
|
+
if (!this.probe.canGetOsIdentity()) return false
|
|
1196
|
+
if (rec.owner.osProcessStartIdentity === null || ident.osProcessStartIdentity === null) return false
|
|
1197
|
+
return rec.owner.osProcessStartIdentity !== ident.osProcessStartIdentity
|
|
1198
|
+
}
|
|
1199
|
+
|
|
1131
1200
|
/** recovery 二次验证:重新探测 recorded pid 是否确证死亡(保守——任何不确定性 → 失败)。
|
|
1132
1201
|
* 与 inspectLockState 同一套语义:alive:false 仅确证死亡 → stale 成立;
|
|
1133
1202
|
* alive 则需 OS identity 判断是否 reuse;无法确定 → 保守失败(不删除)。 */
|
|
@@ -1159,6 +1228,59 @@ export class EnvironmentLockManager {
|
|
|
1159
1228
|
return utilsMsg('utils.envLock.longExpired', { age: formatDuration(age), threshold: formatDuration(this.longExpiredAfterMs) })
|
|
1160
1229
|
}
|
|
1161
1230
|
|
|
1231
|
+
/* ------------------------------------------------------------ shutdown / orphan cleanup */
|
|
1232
|
+
|
|
1233
|
+
/**
|
|
1234
|
+
* 进程退出(exit 事件 / 插件 dispose)时的**同步**兜底释放:只删自己 instanceId 名下的 ownership + sidecar。
|
|
1235
|
+
*
|
|
1236
|
+
* 为什么必须同步:Node 的 'exit' 事件里不能 await,异步 fs 写不进去。为什么必须核对 instanceId:
|
|
1237
|
+
* 退出路径同样不许删别人的锁(与 release() 同一不变量)。语义 = best-effort:永不抛错、永不留半删态。
|
|
1238
|
+
* 覆盖的场景 = **正常关窗但后台同步正在跑**(此时 release() 永远不会被调用),这也是残留锁的主要来源。
|
|
1239
|
+
*/
|
|
1240
|
+
releaseOnExitSync(): void {
|
|
1241
|
+
const token = this.activeToken
|
|
1242
|
+
if (token === null || token.instanceId !== this.activeInstanceId) return
|
|
1243
|
+
this.activeToken = null
|
|
1244
|
+
this.stopHeartbeat()
|
|
1245
|
+
try { fssync.unlinkSync(path.join(this.locksDir, `${HEARTBEAT_PREFIX}${this.activeInstanceId}`)) } catch { /* 尽力 */ }
|
|
1246
|
+
try {
|
|
1247
|
+
const rec = readLockJsonSafe(fssync.readFileSync(this.ownershipPath, 'utf8')) as LockOwnershipRecord | null
|
|
1248
|
+
if (rec !== null && typeof rec === 'object' && rec.owner?.instanceId === this.activeInstanceId) {
|
|
1249
|
+
fssync.unlinkSync(this.ownershipPath)
|
|
1250
|
+
}
|
|
1251
|
+
} catch { /* 缺失/不可读/被占用 → 不动(下次启动的自动回收会处理) */ }
|
|
1252
|
+
}
|
|
1253
|
+
|
|
1254
|
+
/**
|
|
1255
|
+
* 清理孤儿 heartbeat sidecar(P4):只删「已不是当前持有者、且心跳早已停更」的 sidecar。
|
|
1256
|
+
*
|
|
1257
|
+
* 判据不需要 pid(sidecar 里本来就没有 pid):sidecar 的生命周期被三处保证——acquire 时创建、
|
|
1258
|
+
* release 时删、recover 时删被回收者的那份。于是「instanceId 既不是当前 ownership 的持有者、
|
|
1259
|
+
* 心跳又超过 stale 窗口」只可能是崩溃/强杀留下的孤儿。心跳仍新鲜的跳过:那是接管竞态窗口。
|
|
1260
|
+
* 不碰 environment.lock 与 environment.recovering.*(那属于判定,不归清理)。
|
|
1261
|
+
* @returns 实际删除数量
|
|
1262
|
+
*/
|
|
1263
|
+
async cleanupOrphanHeartbeats(): Promise<number> {
|
|
1264
|
+
let names: string[]
|
|
1265
|
+
try { names = await (this.io.listLocksDir ? this.io.listLocksDir(this.locksDir) : Promise.resolve([])) } catch { return 0 }
|
|
1266
|
+
const st = await this.readOwnershipState()
|
|
1267
|
+
const holderId = st.kind === 'ok' ? st.rec.owner.instanceId : null
|
|
1268
|
+
let removed = 0
|
|
1269
|
+
for (const name of names) {
|
|
1270
|
+
if (!name.startsWith(HEARTBEAT_PREFIX)) continue
|
|
1271
|
+
const instanceId = name.slice(HEARTBEAT_PREFIX.length)
|
|
1272
|
+
if (instanceId === this.activeInstanceId || instanceId === holderId) continue
|
|
1273
|
+
const rec = await this.readHeartbeat(instanceId).catch(() => null)
|
|
1274
|
+
if (rec === null) continue // 读不出/形状不符 → 没有判据,保留
|
|
1275
|
+
if ((this.now() - rec.heartbeatAt) <= this.staleAfterMs) continue
|
|
1276
|
+
try {
|
|
1277
|
+
await this.io.unlink(path.join(this.locksDir, name))
|
|
1278
|
+
removed += 1
|
|
1279
|
+
} catch { /* 尽力;下轮再试 */ }
|
|
1280
|
+
}
|
|
1281
|
+
return removed
|
|
1282
|
+
}
|
|
1283
|
+
|
|
1162
1284
|
/* ------------------------------------------------------------ diag */
|
|
1163
1285
|
|
|
1164
1286
|
/** 列出 locks 目录内容(诊断;不存在 → 空) */
|
|
@@ -82,6 +82,9 @@ export const zh = {
|
|
|
82
82
|
'utils.envLock.removeCapturedFailed': '删除 captured 失败',
|
|
83
83
|
'utils.envLock.removedStaleOwnership': '已移除 stale ownership (op={op}, pid={pid})',
|
|
84
84
|
'utils.envLock.removedCorruptOwnership': '已移除 corrupt/崩溃残留所有权文件',
|
|
85
|
+
'utils.envLock.reclaimNotProvable': '无法结构性证明该残留锁的持有进程已消失,保留现场(可用 --recover-stale-lock 显式回收)',
|
|
86
|
+
'utils.envLock.autoReclaimedStale': '已自动回收可证的残留锁(op={op}, pid={pid})',
|
|
87
|
+
'utils.envLock.orphanHeartbeatsRemoved': '已清理 {count} 个孤儿心跳文件',
|
|
85
88
|
'utils.envLock.longExpired': '已过期 {age}(阈值 {threshold})',
|
|
86
89
|
'utils.envLock.durationDays': '{value} 天',
|
|
87
90
|
'utils.envLock.durationHours': '{value} 小时',
|
|
@@ -185,6 +188,9 @@ export const en: Record<keyof typeof zh, string> = {
|
|
|
185
188
|
'utils.envLock.removeCapturedFailed': 'failed to delete the captured file',
|
|
186
189
|
'utils.envLock.removedStaleOwnership': 'removed stale ownership (op={op}, pid={pid})',
|
|
187
190
|
'utils.envLock.removedCorruptOwnership': 'removed the corrupt/crash-left ownership file',
|
|
191
|
+
'utils.envLock.reclaimNotProvable': 'cannot structurally prove the stale lock owner is gone — leaving it in place (use --recover-stale-lock to reclaim explicitly)',
|
|
192
|
+
'utils.envLock.autoReclaimedStale': 'auto-reclaimed a provably stale lock (op={op}, pid={pid})',
|
|
193
|
+
'utils.envLock.orphanHeartbeatsRemoved': 'removed {count} orphaned heartbeat sidecar(s)',
|
|
188
194
|
'utils.envLock.longExpired': 'expired {age} ago (threshold {threshold})',
|
|
189
195
|
'utils.envLock.durationDays': '{value} days',
|
|
190
196
|
'utils.envLock.durationHours': '{value} hours',
|