dsh-config-manager 0.3.0 → 0.4.0
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 +33 -1
- package/lib/client.js +1063 -838
- 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/migration-history.d.ts +28 -2
- package/lib/core/migration-history.js +41 -4
- package/lib/index.d.ts +2 -2
- package/lib/index.js +24 -6
- 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 +6 -0
- package/lib/sync/backup-scheduler.js +6 -0
- package/lib/sync/s3/oss4-verify.js +21 -6
- package/lib/sync/s3/s3-providers.d.ts +13 -0
- package/lib/sync/s3/s3-providers.js +6 -0
- package/lib/sync/s3/s3-transport.d.ts +22 -0
- package/lib/sync/s3/s3-transport.js +89 -18
- package/lib/sync/ui-prefs.d.ts +8 -0
- package/lib/sync/ui-prefs.js +8 -0
- 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 +30 -0
- package/src/client/home/HomePanel.tsx +55 -23
- 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/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/migration-history.test.ts +78 -0
- package/src/core/migration-history.ts +46 -4
- package/src/index.ts +25 -6
- 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.ts +3 -0
- package/src/sync/backup-scheduler.ts +3 -0
- package/src/sync/s3/oss4-verify.ts +22 -6
- package/src/sync/s3/s3-conditional-write.test.ts +153 -3
- package/src/sync/s3/s3-providers.ts +20 -0
- package/src/sync/s3/s3-transport.oss4-server.test.ts +48 -0
- package/src/sync/s3/s3-transport.ts +98 -17
- package/src/sync/ui-prefs.test.ts +32 -0
- package/src/sync/ui-prefs.ts +16 -0
- 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
|
@@ -7,6 +7,10 @@
|
|
|
7
7
|
* `getResourceV4`、`oss/auth.go` 的 `getSubResource` / `getSignedStrV4`)**独立重写**一遍,
|
|
8
8
|
* 只吃「收到的 HTTP 请求」(method / url / 头 / body),绝不复用客户端的签名中间量。
|
|
9
9
|
*
|
|
10
|
+
* 也照真服务端实现**条件写能力**:PutObject 收到 If-Match / If-None-Match 一律拒(0017-00000245),
|
|
11
|
+
* 只接受 `x-oss-forbid-overwrite: true`(已存在 → 409 FileAlreadyExists)—— 这一层不照真服务端写,
|
|
12
|
+
* 「本地全绿、真机 400」的盲点就会回来(issue #109 第二层)。
|
|
13
|
+
*
|
|
10
14
|
* 用法:`s3-transport.oss4-server.test.ts`(内存对象存储,逐请求验签)与
|
|
11
15
|
* `scripts/oss-live-check.mjs`(真桶联调)。它证明的是「与本仓库对官方算法的独立复现一致」,
|
|
12
16
|
* 不等于官方服务端盖章 —— 真桶连通性要靠带真实密钥跑一次脚本。
|
|
@@ -96,6 +100,10 @@ export function verifyOssV4(init, cfg) {
|
|
|
96
100
|
}
|
|
97
101
|
return { ok: true, reason: '', canonicalRequest, stringToSign, signature, objectKey, bucketLevel };
|
|
98
102
|
}
|
|
103
|
+
/** 真 OSS 会拒绝的条件写头(PutObject 不支持;错误码 0017-00000245)。 */
|
|
104
|
+
const IF_CONDITIONAL_HEADERS = ['if-match', 'if-none-match'];
|
|
105
|
+
/** OSS 回显头名时用的原始大小写(真机报文里看到的是 `If-None-Match`)。 */
|
|
106
|
+
const IF_HEADER_ECHO = { 'if-match': 'If-Match', 'if-none-match': 'If-None-Match' };
|
|
99
107
|
/**
|
|
100
108
|
* 内存 OSS(验签通过才落盘/回读):返回可直接注入 S3Transport 的 `request`,
|
|
101
109
|
* 以及验签成功/失败流水,供测试与联调脚本断言。
|
|
@@ -127,13 +135,20 @@ export function makeOssVerifyServer(cfg) {
|
|
|
127
135
|
const h = lower(headers);
|
|
128
136
|
const existing = objects.get(key);
|
|
129
137
|
if (method === 'PUT') {
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
138
|
+
// 真 OSS 的 PutObject **不支持 If-Match / If-None-Match**:收到就回
|
|
139
|
+
// 400 InvalidArgument「A header you provided implies functionality that is not implemented.」
|
|
140
|
+
// (错误码 0017-00000245,issue #109 第二层)。这里必须照真服务端拒掉 —— 之前这个验签器
|
|
141
|
+
// 自己实现了 if-none-match,等于用自家规则验自家人,于是「14 个请求零失败」漏掉了这一层。
|
|
142
|
+
const unsupported = IF_CONDITIONAL_HEADERS.find((n) => h[n] !== undefined);
|
|
143
|
+
if (unsupported !== undefined) {
|
|
144
|
+
return respond(400, '<Error><Code>InvalidArgument</Code><Message>A header you provided implies '
|
|
145
|
+
+ 'functionality that is not implemented.</Message><Header>' + IF_HEADER_ECHO[unsupported]
|
|
146
|
+
+ '</Header><EC>0017-00000245</EC></Error>');
|
|
134
147
|
}
|
|
135
|
-
|
|
136
|
-
|
|
148
|
+
// OSS 唯一支持的「禁止覆盖」:对象已存在即 409 FileAlreadyExists。
|
|
149
|
+
if ((h['x-oss-forbid-overwrite'] ?? '').trim().toLowerCase() === 'true' && existing !== undefined) {
|
|
150
|
+
return respond(409, '<Error><Code>FileAlreadyExists</Code><Message>The object you specified already '
|
|
151
|
+
+ 'exists and cannot be overwritten again.</Message></Error>');
|
|
137
152
|
}
|
|
138
153
|
const body = opts.body ?? '';
|
|
139
154
|
const etag = sha256(body).slice(0, 32);
|
|
@@ -6,6 +6,15 @@ export declare const S3_DEFAULT_PREFIX = "dsh-config-manager";
|
|
|
6
6
|
export declare const S3_INDEX_FILE = "index.json";
|
|
7
7
|
export declare const S3_BLOBS_SEG = "blobs";
|
|
8
8
|
export declare const S3_BLOBS_INDEX_FILE = "blobs-index.json";
|
|
9
|
+
/**
|
|
10
|
+
* 条件写能力(决定「防两台设备同时写」怎么落地):
|
|
11
|
+
* - `etag`:AWS 风格 If-Match / If-None-Match(s3 / minio / cos / kodo);
|
|
12
|
+
* - `forbid-overwrite`:阿里云 OSS —— PutObject **不支持 If-\***(真机会回 400
|
|
13
|
+
* InvalidArgument「A header you provided implies functionality that is not implemented.」,
|
|
14
|
+
* 错误码 0017-00000245;issue #109 第二层),只有 `x-oss-forbid-overwrite: true`
|
|
15
|
+
* 「对象已存在即拒」这一种禁止覆盖语义。
|
|
16
|
+
*/
|
|
17
|
+
export type S3ConditionalWrite = 'etag' | 'forbid-overwrite';
|
|
9
18
|
export interface S3ProviderVariant {
|
|
10
19
|
id: S3CompatProvider;
|
|
11
20
|
/** 默认签名方言(可被 \`dialectId\` 覆盖) */
|
|
@@ -18,6 +27,8 @@ export interface S3ProviderVariant {
|
|
|
18
27
|
endpointTemplate?: string;
|
|
19
28
|
/** 默认寻址风格:true = path-style(<endpoint>/<bucket>/<key>),false = virtual-host(<bucket>.<endpoint>/<key>) */
|
|
20
29
|
defaultPathStyle: boolean;
|
|
30
|
+
/** 条件写能力(见 S3ConditionalWrite;与签名方言解耦,跟着服务商走而不是跟着 dialectId 走) */
|
|
31
|
+
conditionalWrite: S3ConditionalWrite;
|
|
21
32
|
/**
|
|
22
33
|
* 变体说明的**目录键**(自 t6 起字段是键而不是文案 —— 中文只存在于 `sync/s3/messages.ts` 的本地目录,
|
|
23
34
|
* 经 `s3Msg` / `composeMsg(host, s3Msg)` 解析成当前语言;本字段本身不渲染)。
|
|
@@ -46,6 +57,8 @@ export interface S3Target {
|
|
|
46
57
|
prefix: string;
|
|
47
58
|
pathStyle: boolean;
|
|
48
59
|
dialect: SigV4Dialect;
|
|
60
|
+
/** 条件写能力(来自变体表;dialectId 覆盖不影响它) */
|
|
61
|
+
conditionalWrite: S3ConditionalWrite;
|
|
49
62
|
}
|
|
50
63
|
export interface S3TargetInput {
|
|
51
64
|
provider: S3CompatProvider;
|
|
@@ -31,25 +31,30 @@ export const S3_PROVIDER_VARIANTS = {
|
|
|
31
31
|
s3: {
|
|
32
32
|
id: 's3', dialectId: 'aws4', service: 's3', defaultRegion: 'us-east-1',
|
|
33
33
|
endpointTemplate: 'https://s3.{region}.amazonaws.com', defaultPathStyle: false,
|
|
34
|
+
conditionalWrite: 'etag',
|
|
34
35
|
note: 'sync.s3.providerNoteS3',
|
|
35
36
|
},
|
|
36
37
|
oss: {
|
|
37
38
|
id: 'oss', dialectId: 'oss4', service: 'oss',
|
|
38
39
|
endpointTemplate: 'https://oss-{region}.aliyuncs.com', defaultPathStyle: false,
|
|
40
|
+
conditionalWrite: 'forbid-overwrite',
|
|
39
41
|
note: 'sync.s3.providerNoteOss',
|
|
40
42
|
},
|
|
41
43
|
cos: {
|
|
42
44
|
id: 'cos', dialectId: 'aws4', service: 's3',
|
|
43
45
|
endpointTemplate: 'https://cos.{region}.myqcloud.com', defaultPathStyle: false,
|
|
46
|
+
conditionalWrite: 'etag',
|
|
44
47
|
note: 'sync.s3.providerNoteCos',
|
|
45
48
|
},
|
|
46
49
|
minio: {
|
|
47
50
|
id: 'minio', dialectId: 'aws4', service: 's3', defaultRegion: 'us-east-1', defaultPathStyle: true,
|
|
51
|
+
conditionalWrite: 'etag',
|
|
48
52
|
note: 'sync.s3.providerNoteMinio',
|
|
49
53
|
},
|
|
50
54
|
kodo: {
|
|
51
55
|
id: 'kodo', dialectId: 'aws4', service: 's3',
|
|
52
56
|
endpointTemplate: 'https://s3-{region}.qiniucs.com', defaultPathStyle: false,
|
|
57
|
+
conditionalWrite: 'etag',
|
|
53
58
|
note: 'sync.s3.providerNoteKodo',
|
|
54
59
|
},
|
|
55
60
|
};
|
|
@@ -119,6 +124,7 @@ export function resolveS3Target(input) {
|
|
|
119
124
|
prefix,
|
|
120
125
|
pathStyle: input.pathStyle ?? variant.defaultPathStyle,
|
|
121
126
|
dialect: sigV4Dialect(input.dialectId ?? variant.dialectId),
|
|
127
|
+
conditionalWrite: variant.conditionalWrite,
|
|
122
128
|
},
|
|
123
129
|
};
|
|
124
130
|
}
|
|
@@ -84,6 +84,25 @@ export declare class S3Transport implements SyncTransport {
|
|
|
84
84
|
delete(id: string): Promise<void>;
|
|
85
85
|
/** 条件写失败:远端索引在本次读取之后被别人改过 —— 中止写入让用户重跑(cloud-sync 借鉴项 ①)。 */
|
|
86
86
|
private concurrentWrite;
|
|
87
|
+
/**
|
|
88
|
+
* OSS 方言的「ETag 条件写」替身(issue #109 第二层):PutObject 既无 If-Match 也无
|
|
89
|
+
* If-None-Match,`x-oss-forbid-overwrite` 只能表达「别覆盖已存在的对象」,表达不了
|
|
90
|
+
* 「远端必须还是我读到的那一版」。所以索引进已存在时改成**写前 HEAD 复核 ETag**:
|
|
91
|
+
* 变了 / 对象没了 → 按并发写中止(零写入)。
|
|
92
|
+
*
|
|
93
|
+
* **不是原子的**:复核与 PUT 之间仍有窗口(服务端不支持条件写就没有真正的解),
|
|
94
|
+
* 比无保护强、比 If-Match 弱 —— 如实登记在 docs/decisions/0003。
|
|
95
|
+
* 其它方言(etag)与「服务端不给 ETag」两种情况一律直接放行,不改既有行为。
|
|
96
|
+
*/
|
|
97
|
+
private reassertIndexEtag;
|
|
98
|
+
/**
|
|
99
|
+
* 条件写失败分类(issue #109 第二层复核):`isConcurrentWrite` 只看「状态码像不像」,
|
|
100
|
+
* 这里再问报文一句确认「对象确实已存在」。OSS 的 **409 不止 FileAlreadyExists** ——
|
|
101
|
+
* FileImmutable(Bucket 数据处于保护状态,删改都会被拒)同为 409,一律按并发写报
|
|
102
|
+
* 「别的设备改过索引」就是假话。报文读不出时仍按并发写处理(宁可让用户重跑一次,
|
|
103
|
+
* 不吞掉真冲突)。412 是 If-Match 语义,恒为并发写。
|
|
104
|
+
*/
|
|
105
|
+
private conditionalFailure;
|
|
87
106
|
/**
|
|
88
107
|
* 连通性探针(cloud-sync 借鉴项 ②):HEAD 桶证明端点/凭据/桶可达,再读一次索引回报快照数。
|
|
89
108
|
* 重定向(301/307/308)时读 x-amz-bucket-region 直接把「region 该填什么」告诉用户 ——
|
|
@@ -95,7 +114,10 @@ export declare class S3Transport implements SyncTransport {
|
|
|
95
114
|
private secretOnce;
|
|
96
115
|
/** 发送一次已签名请求;网络错误/超时归一为带分类的通道错误 */
|
|
97
116
|
private send;
|
|
117
|
+
/** 读错误响应体(未脱敏原文,截断到 ERR_BODY_MAX;读不出按空串) */
|
|
118
|
+
private errorBody;
|
|
98
119
|
/** 构造 HTTP 非 2xx 失败消息:附上脱敏后的响应体片段(截断) */
|
|
120
|
+
private failMessage;
|
|
99
121
|
private failText;
|
|
100
122
|
/** 识别超时错误(AbortError / TimeoutError) */
|
|
101
123
|
private isTimeout;
|
|
@@ -43,17 +43,32 @@ const REDACTED = '[REDACTED]';
|
|
|
43
43
|
/**
|
|
44
44
|
* 条件写头(cloud-sync 借鉴项 ①):有 ETag → If-Match(远端必须仍是我读到的那一版);
|
|
45
45
|
* 索引本来就不存在 → If-None-Match: *(防两设备同时首推);服务端不给 ETag → 空(无条件写,不改既有行为)。
|
|
46
|
+
*
|
|
47
|
+
* **阿里云 OSS 没有 If-\***(issue #109 第二层):PutObject 收到 If-Match / If-None-Match 一律回
|
|
48
|
+
* 400 InvalidArgument「A header you provided implies functionality that is not implemented.」
|
|
49
|
+
* (错误码 0017-00000245,真机报文里的 `Header: If-None-Match` 即此)。它只提供
|
|
50
|
+
* `x-oss-forbid-overwrite: true`(对象已存在即 409 FileAlreadyExists)。于是按变体的
|
|
51
|
+
* `conditionalWrite` 能力位映射:
|
|
52
|
+
* - 首推(索引本来就不存在)→ 语义完全等价,改用 x-oss-forbid-overwrite;
|
|
53
|
+
* - 索引已存在(拿到了 ETag)→ 没有对应头,退回「写前 HEAD 复核 ETag」
|
|
54
|
+
* (`assertIndexEtagUnchanged`;非原子,尽力而为)。
|
|
46
55
|
*/
|
|
47
|
-
function conditionalHeaders(etag, indexMissing) {
|
|
56
|
+
function conditionalHeaders(etag, indexMissing, mode) {
|
|
57
|
+
const guarded = mode === 'forbid-overwrite';
|
|
48
58
|
if (etag !== undefined)
|
|
49
|
-
return { 'if-match': etag };
|
|
50
|
-
|
|
59
|
+
return guarded ? {} : { 'if-match': etag };
|
|
60
|
+
if (!indexMissing)
|
|
61
|
+
return {};
|
|
62
|
+
return guarded ? { 'x-oss-forbid-overwrite': 'true' } : { 'if-none-match': '*' };
|
|
51
63
|
}
|
|
52
|
-
/**
|
|
53
|
-
|
|
64
|
+
/**
|
|
65
|
+
* 条件写失败判定:412 恒是;409 仅在**确实带了条件写头**时才算
|
|
66
|
+
* (无条件的 409 另有含义,不吞;条件写头的存在由调用方显式告知)。
|
|
67
|
+
*/
|
|
68
|
+
function isConcurrentWrite(status, guarded) {
|
|
54
69
|
if (status === 412)
|
|
55
70
|
return true;
|
|
56
|
-
return status === 409 &&
|
|
71
|
+
return status === 409 && guarded;
|
|
57
72
|
}
|
|
58
73
|
/** S3 通道错误:继承统一错误基类(kind / retryable / status 对上层可见)。 */
|
|
59
74
|
export class S3TransportError extends SyncTransportError {
|
|
@@ -210,14 +225,16 @@ export class S3Transport {
|
|
|
210
225
|
const merged = idxBefore.filter((m) => m.id !== snapshot.id);
|
|
211
226
|
merged.push(meta);
|
|
212
227
|
merged.sort((a, b) => (a.createdAt < b.createdAt ? -1 : a.createdAt > b.createdAt ? 1 : 0));
|
|
213
|
-
const condHeaders = conditionalHeaders(idxEtag, indexMissing);
|
|
228
|
+
const condHeaders = conditionalHeaders(idxEtag, indexMissing, this.target.conditionalWrite);
|
|
229
|
+
await this.reassertIndexEtag(idxEtag, secret);
|
|
214
230
|
const putIdx = await this.send('PUT', indexKey(this.target.prefix), {
|
|
215
231
|
body: JSON.stringify(merged),
|
|
216
232
|
secret,
|
|
217
233
|
headers: condHeaders,
|
|
218
234
|
});
|
|
219
|
-
|
|
220
|
-
|
|
235
|
+
const idxFailure = await this.conditionalFailure('PUT', putIdx.url, putIdx.res, Object.keys(condHeaders).length > 0, secret);
|
|
236
|
+
if (idxFailure !== undefined)
|
|
237
|
+
throw idxFailure;
|
|
221
238
|
if (!putIdx.res.ok) {
|
|
222
239
|
throw new S3TransportError(await this.failText('PUT', putIdx.url, putIdx.res, secret), classifyHttpStatus(putIdx.res.status));
|
|
223
240
|
}
|
|
@@ -262,14 +279,16 @@ export class S3Transport {
|
|
|
262
279
|
const remaining = idx.filter((m) => m.id !== id);
|
|
263
280
|
if (remaining.length === idx.length && del.res.status === 404)
|
|
264
281
|
return; // 对象与索引都没有 → 静默成功
|
|
265
|
-
const condHeaders = conditionalHeaders(idxEtag, false);
|
|
282
|
+
const condHeaders = conditionalHeaders(idxEtag, false, this.target.conditionalWrite);
|
|
283
|
+
await this.reassertIndexEtag(idxEtag, secret);
|
|
266
284
|
const putIdx = await this.send('PUT', indexKey(this.target.prefix), {
|
|
267
285
|
body: JSON.stringify(remaining),
|
|
268
286
|
secret,
|
|
269
287
|
headers: condHeaders,
|
|
270
288
|
});
|
|
271
|
-
|
|
272
|
-
|
|
289
|
+
const idxFailure = await this.conditionalFailure('PUT', putIdx.url, putIdx.res, Object.keys(condHeaders).length > 0, secret);
|
|
290
|
+
if (idxFailure !== undefined)
|
|
291
|
+
throw idxFailure;
|
|
273
292
|
if (!putIdx.res.ok) {
|
|
274
293
|
throw new S3TransportError(await this.failText('PUT', putIdx.url, putIdx.res, secret), classifyHttpStatus(putIdx.res.status));
|
|
275
294
|
}
|
|
@@ -280,6 +299,53 @@ export class S3Transport {
|
|
|
280
299
|
concurrentWrite(url, status) {
|
|
281
300
|
return new S3TransportError(this.o.msg('sync.s3.concurrentWrite', { status: String(status), url }), { kind: 'conflict', retryable: false, status });
|
|
282
301
|
}
|
|
302
|
+
/**
|
|
303
|
+
* OSS 方言的「ETag 条件写」替身(issue #109 第二层):PutObject 既无 If-Match 也无
|
|
304
|
+
* If-None-Match,`x-oss-forbid-overwrite` 只能表达「别覆盖已存在的对象」,表达不了
|
|
305
|
+
* 「远端必须还是我读到的那一版」。所以索引进已存在时改成**写前 HEAD 复核 ETag**:
|
|
306
|
+
* 变了 / 对象没了 → 按并发写中止(零写入)。
|
|
307
|
+
*
|
|
308
|
+
* **不是原子的**:复核与 PUT 之间仍有窗口(服务端不支持条件写就没有真正的解),
|
|
309
|
+
* 比无保护强、比 If-Match 弱 —— 如实登记在 docs/decisions/0003。
|
|
310
|
+
* 其它方言(etag)与「服务端不给 ETag」两种情况一律直接放行,不改既有行为。
|
|
311
|
+
*/
|
|
312
|
+
async reassertIndexEtag(etag, secret) {
|
|
313
|
+
if (this.target.conditionalWrite !== 'forbid-overwrite' || etag === undefined)
|
|
314
|
+
return;
|
|
315
|
+
const key = indexKey(this.target.prefix);
|
|
316
|
+
const url = objectUrl(this.target, key);
|
|
317
|
+
const head = await this.send('HEAD', key, { secret });
|
|
318
|
+
if (head.res.status === 404)
|
|
319
|
+
throw this.concurrentWrite(url, 409);
|
|
320
|
+
if (!head.res.ok) {
|
|
321
|
+
throw new S3TransportError(await this.failText('HEAD', head.url, head.res, secret), classifyHttpStatus(head.res.status));
|
|
322
|
+
}
|
|
323
|
+
const current = head.res.headers?.['etag'];
|
|
324
|
+
if (typeof current === 'string' && current !== '' && current !== etag) {
|
|
325
|
+
throw this.concurrentWrite(url, 409);
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
/**
|
|
329
|
+
* 条件写失败分类(issue #109 第二层复核):`isConcurrentWrite` 只看「状态码像不像」,
|
|
330
|
+
* 这里再问报文一句确认「对象确实已存在」。OSS 的 **409 不止 FileAlreadyExists** ——
|
|
331
|
+
* FileImmutable(Bucket 数据处于保护状态,删改都会被拒)同为 409,一律按并发写报
|
|
332
|
+
* 「别的设备改过索引」就是假话。报文读不出时仍按并发写处理(宁可让用户重跑一次,
|
|
333
|
+
* 不吞掉真冲突)。412 是 If-Match 语义,恒为并发写。
|
|
334
|
+
*/
|
|
335
|
+
async conditionalFailure(method, url, res, guarded, secret) {
|
|
336
|
+
if (!isConcurrentWrite(res.status, guarded))
|
|
337
|
+
return undefined;
|
|
338
|
+
if (res.status !== 409)
|
|
339
|
+
return this.concurrentWrite(url, res.status);
|
|
340
|
+
// 只有 forbid-overwrite 方言的 409 有两种含义(FileAlreadyExists / FileImmutable);
|
|
341
|
+
// etag 方言的 409 由各家自定语义,报文不可当作判据 —— 沿用「带条件头的 409 = 并发写」。
|
|
342
|
+
if (this.target.conditionalWrite !== 'forbid-overwrite')
|
|
343
|
+
return this.concurrentWrite(url, res.status);
|
|
344
|
+
const body = await this.errorBody(res);
|
|
345
|
+
if (body === '' || body.includes('FileAlreadyExists'))
|
|
346
|
+
return this.concurrentWrite(url, res.status);
|
|
347
|
+
return new S3TransportError(this.failMessage(method, url, res.status, body, secret), classifyHttpStatus(res.status));
|
|
348
|
+
}
|
|
283
349
|
/**
|
|
284
350
|
* 连通性探针(cloud-sync 借鉴项 ②):HEAD 桶证明端点/凭据/桶可达,再读一次索引回报快照数。
|
|
285
351
|
* 重定向(301/307/308)时读 x-amz-bucket-region 直接把「region 该填什么」告诉用户 ——
|
|
@@ -368,22 +434,27 @@ export class S3Transport {
|
|
|
368
434
|
throw new S3TransportError(this.o.msg('sync.s3.requestError', { method, url, err: this.mask(rawMsg, opts.secret) }), { ...classifyNetworkErrorText(rawMsg), cause: err });
|
|
369
435
|
}
|
|
370
436
|
}
|
|
371
|
-
/**
|
|
372
|
-
async
|
|
373
|
-
let body = '';
|
|
437
|
+
/** 读错误响应体(未脱敏原文,截断到 ERR_BODY_MAX;读不出按空串) */
|
|
438
|
+
async errorBody(res) {
|
|
374
439
|
try {
|
|
375
|
-
|
|
440
|
+
return (await res.text()).slice(0, ERR_BODY_MAX);
|
|
376
441
|
}
|
|
377
442
|
catch {
|
|
378
|
-
|
|
443
|
+
return '';
|
|
379
444
|
}
|
|
445
|
+
}
|
|
446
|
+
/** 构造 HTTP 非 2xx 失败消息:附上脱敏后的响应体片段(截断) */
|
|
447
|
+
failMessage(method, url, status, body, secret) {
|
|
380
448
|
return this.o.msg('sync.s3.requestFailed', {
|
|
381
449
|
method,
|
|
382
450
|
url,
|
|
383
|
-
status: String(
|
|
451
|
+
status: String(status),
|
|
384
452
|
err: this.mask(body, secret),
|
|
385
453
|
});
|
|
386
454
|
}
|
|
455
|
+
async failText(method, url, res, secret) {
|
|
456
|
+
return this.failMessage(method, url, res.status, await this.errorBody(res), secret);
|
|
457
|
+
}
|
|
387
458
|
/** 识别超时错误(AbortError / TimeoutError) */
|
|
388
459
|
isTimeout(err) {
|
|
389
460
|
const name = err?.name ?? '';
|
package/lib/sync/ui-prefs.d.ts
CHANGED
|
@@ -41,6 +41,14 @@ export interface UiPrefs {
|
|
|
41
41
|
* 台账 / 回退路由本身仍可用:已有回滚点仍能查看、回退、删除、清理 —— 关的是「自动留点」。
|
|
42
42
|
*/
|
|
43
43
|
rollbackEnabled?: boolean;
|
|
44
|
+
/**
|
|
45
|
+
* 迁移历史自动清理的保留上限(条)。
|
|
46
|
+
*
|
|
47
|
+
* 语义:缺省 = 1000(core 的 DEFAULT_MIGRATION_RETENTION);0 = 不限制(只增不减,老行为);
|
|
48
|
+
* 非法值一律回落缺省。宿主每次写入历史后按本值节流清理最旧条目,
|
|
49
|
+
* 用户可在「迁移历史」面板改(GET/POST /history/retention)。
|
|
50
|
+
*/
|
|
51
|
+
historyRetentionMaxEntries?: number;
|
|
44
52
|
}
|
|
45
53
|
/** 缺省配置(首次无文件 / 损坏 / 不支持 schema 时回退) */
|
|
46
54
|
export declare function defaultUiPrefs(): UiPrefs;
|
package/lib/sync/ui-prefs.js
CHANGED
|
@@ -25,6 +25,7 @@ import fsSync from 'node:fs';
|
|
|
25
25
|
import path from 'node:path';
|
|
26
26
|
import { parseJsonSafe, stringifyJsonSafe } from '../utils/json.js';
|
|
27
27
|
import { atomicWriteFile } from '../utils/atomic-write.js';
|
|
28
|
+
import { isValidHistoryRetention } from '../core/migration-history.js';
|
|
28
29
|
import { parseSyncChannel } from './sync-config.js';
|
|
29
30
|
export const UI_PREFS_FILE = 'ui-prefs.json';
|
|
30
31
|
export const UI_PREFS_SCHEMA_VERSION = 1;
|
|
@@ -89,6 +90,10 @@ export async function readUiPrefs(dir) {
|
|
|
89
90
|
if (obj['rollbackEnabled'] === true) {
|
|
90
91
|
prefs.rollbackEnabled = true;
|
|
91
92
|
}
|
|
93
|
+
// 保留上限只认 0..100000 的整数(与路由校验同一口径);字符串/小数/越界一律丢,回落缺省
|
|
94
|
+
if (isValidHistoryRetention(obj['historyRetentionMaxEntries'])) {
|
|
95
|
+
prefs.historyRetentionMaxEntries = obj['historyRetentionMaxEntries'];
|
|
96
|
+
}
|
|
92
97
|
return prefs;
|
|
93
98
|
}
|
|
94
99
|
/**
|
|
@@ -126,6 +131,9 @@ export async function writeUiPrefs(dir, prefs) {
|
|
|
126
131
|
...(prefs.releaseNotesDismissed === true ? { releaseNotesDismissed: true } : {}),
|
|
127
132
|
...(prefs.sessionFormatDisposition !== undefined ? { sessionFormatDisposition: prefs.sessionFormatDisposition } : {}),
|
|
128
133
|
...(prefs.rollbackEnabled === true ? { rollbackEnabled: true } : {}),
|
|
134
|
+
...(isValidHistoryRetention(prefs.historyRetentionMaxEntries)
|
|
135
|
+
? { historyRetentionMaxEntries: prefs.historyRetentionMaxEntries }
|
|
136
|
+
: {}),
|
|
129
137
|
};
|
|
130
138
|
const target = path.join(dir, UI_PREFS_FILE);
|
|
131
139
|
const data = stringifyJsonSafe(payload, { space: 2 });
|
package/lib/utils/env-lock.d.ts
CHANGED
|
@@ -149,6 +149,14 @@ export interface MutationLockPort {
|
|
|
149
149
|
validate(token: unknown): token is MutationLockToken;
|
|
150
150
|
/** release(release 前校验 instanceId;mismatch 抛 EnvironmentLockOwnedByAnotherError) */
|
|
151
151
|
release(token: MutationLockToken): Promise<void>;
|
|
152
|
+
/**
|
|
153
|
+
* 可选:只回收**结构性可证** stale 残留锁(owner 确证死亡 / PID 复用),其余一律不动。
|
|
154
|
+
* 端口实现缺这个方法(mock / 远端代理)时调用方必须当作「不支持」跳过,不得自行 inspect+release。
|
|
155
|
+
* @returns null = 无需/无权回收;否则为该次 recover 的结果
|
|
156
|
+
*/
|
|
157
|
+
reclaimProvableStaleLock?(): Promise<RecoverResult | null>;
|
|
158
|
+
/** 可选:同步兜底释放本实例持有的锁(进程 exit/dispose 用;永不抛错)。 */
|
|
159
|
+
releaseOnExitSync?(): void;
|
|
152
160
|
}
|
|
153
161
|
/**
|
|
154
162
|
* 便捷包装:核心引擎「无父 token → acquire;有有效父 token → reuse(不 reacquire)」。
|
|
@@ -199,6 +207,19 @@ export interface RecoverResult {
|
|
|
199
207
|
state: LockState;
|
|
200
208
|
/** 诊断 */
|
|
201
209
|
detail?: string;
|
|
210
|
+
/** 实际被回收的 owner(供自动路径记日志;corrupt 回收时为 undefined) */
|
|
211
|
+
removedOwner?: {
|
|
212
|
+
op: string;
|
|
213
|
+
pid: number;
|
|
214
|
+
};
|
|
215
|
+
}
|
|
216
|
+
/**
|
|
217
|
+
* recover 的调用约束。
|
|
218
|
+
* - `'any'`(缺省)= 显式动作:沿用全部既有判据(含 corrupt 残留与心跳长过期启发式)。
|
|
219
|
+
* - `'provable'` = 自动路径:只承认 owner 确证死亡 / PID 复用,其余一律拒绝并保留现场。
|
|
220
|
+
*/
|
|
221
|
+
export interface RecoverOptions {
|
|
222
|
+
require?: 'any' | 'provable';
|
|
202
223
|
}
|
|
203
224
|
/**
|
|
204
225
|
* heartbeat 定时器注入面(缺省 = 全局 setInterval/clearInterval)。
|
|
@@ -417,7 +438,22 @@ export declare class EnvironmentLockManager {
|
|
|
417
438
|
* **不自动触发**;仅当检测为 STALE_LOCK_DETECTED 才允许 capture。
|
|
418
439
|
* 二次验证失败 → quarantine(保留 recovering 文件,不 rename 回环境锁,不覆盖 successor)。
|
|
419
440
|
*/
|
|
420
|
-
recoverStaleLock(): Promise<RecoverResult>;
|
|
441
|
+
recoverStaleLock(options?: RecoverOptions): Promise<RecoverResult>;
|
|
442
|
+
/**
|
|
443
|
+
* 自动回收入口(宿主启动 / 调度器本轮预检共用):只删**可证** stale,其余返回 null(一动不动)。
|
|
444
|
+
*
|
|
445
|
+
* 为什么不直接让调用方 inspect + recoverStaleLock:判据分散在 inspect(长过期放宽)、recover(corrupt 分支)
|
|
446
|
+
* 和调用方文案三处必然漂移。这里把「自动」的边界收在一处,并且先做两次廉价读(ownership + sidecar):
|
|
447
|
+
* - 无 ownership / corrupt → null(corrupt 留给显式回收);
|
|
448
|
+
* - heartbeat 仍新鲜(≤ staleAfterMs)→ null:**死进程写不出新鲜心跳**,新鲜就是「有人在干活」的证据,
|
|
449
|
+
* 连进程探测都省掉(Windows 上探测活 pid 要 spawn 一次 PowerShell,不能每轮同步都付这个钱)。
|
|
450
|
+
* 通过这两道之后再走结构性判定(kill(pid,0) 的 ESRCH 是快路径)。
|
|
451
|
+
*/
|
|
452
|
+
reclaimProvableStaleLock(): Promise<RecoverResult | null>;
|
|
453
|
+
/** 结构性可证 stale:owner pid 确证死亡,或 pid 存活但 OS identity 与 recorded 不同(PID 复用)。
|
|
454
|
+
* 与 inspectLockState / reProveStale 的「长过期」放宽**刻意不同**:自动回收不承认启发式。
|
|
455
|
+
* 探测失败/不确定 → false(保守,绝不构成误删许可)。 */
|
|
456
|
+
private isProvablyStale;
|
|
421
457
|
/** recovery 二次验证:重新探测 recorded pid 是否确证死亡(保守——任何不确定性 → 失败)。
|
|
422
458
|
* 与 inspectLockState 同一套语义:alive:false 仅确证死亡 → stale 成立;
|
|
423
459
|
* alive 则需 OS identity 判断是否 reuse;无法确定 → 保守失败(不删除)。 */
|
|
@@ -426,6 +462,24 @@ export declare class EnvironmentLockManager {
|
|
|
426
462
|
* heartbeat sidecar 缺失时返回 null(无从判断过期时长)——只对「确实读过 heartbeat
|
|
427
463
|
* 且它早已停更」的锁放宽,避免把「sidecar 被清掉」误判成残留。 */
|
|
428
464
|
private longExpiredReason;
|
|
465
|
+
/**
|
|
466
|
+
* 进程退出(exit 事件 / 插件 dispose)时的**同步**兜底释放:只删自己 instanceId 名下的 ownership + sidecar。
|
|
467
|
+
*
|
|
468
|
+
* 为什么必须同步:Node 的 'exit' 事件里不能 await,异步 fs 写不进去。为什么必须核对 instanceId:
|
|
469
|
+
* 退出路径同样不许删别人的锁(与 release() 同一不变量)。语义 = best-effort:永不抛错、永不留半删态。
|
|
470
|
+
* 覆盖的场景 = **正常关窗但后台同步正在跑**(此时 release() 永远不会被调用),这也是残留锁的主要来源。
|
|
471
|
+
*/
|
|
472
|
+
releaseOnExitSync(): void;
|
|
473
|
+
/**
|
|
474
|
+
* 清理孤儿 heartbeat sidecar(P4):只删「已不是当前持有者、且心跳早已停更」的 sidecar。
|
|
475
|
+
*
|
|
476
|
+
* 判据不需要 pid(sidecar 里本来就没有 pid):sidecar 的生命周期被三处保证——acquire 时创建、
|
|
477
|
+
* release 时删、recover 时删被回收者的那份。于是「instanceId 既不是当前 ownership 的持有者、
|
|
478
|
+
* 心跳又超过 stale 窗口」只可能是崩溃/强杀留下的孤儿。心跳仍新鲜的跳过:那是接管竞态窗口。
|
|
479
|
+
* 不碰 environment.lock 与 environment.recovering.*(那属于判定,不归清理)。
|
|
480
|
+
* @returns 实际删除数量
|
|
481
|
+
*/
|
|
482
|
+
cleanupOrphanHeartbeats(): Promise<number>;
|
|
429
483
|
/** 列出 locks 目录内容(诊断;不存在 → 空) */
|
|
430
484
|
listLockFiles(): Promise<string[]>;
|
|
431
485
|
}
|
package/lib/utils/env-lock.js
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。
|
|
@@ -159,6 +163,14 @@ function defaultIo() {
|
|
|
159
163
|
return null;
|
|
160
164
|
throw e;
|
|
161
165
|
} },
|
|
166
|
+
async listLocksDir(d) { try {
|
|
167
|
+
return await fs.readdir(d);
|
|
168
|
+
}
|
|
169
|
+
catch (e) {
|
|
170
|
+
if (isENOENT(e))
|
|
171
|
+
return [];
|
|
172
|
+
throw e;
|
|
173
|
+
} },
|
|
162
174
|
};
|
|
163
175
|
}
|
|
164
176
|
/** 默认 heartbeat 定时器实现(全局定时器;unref 由调用方按句柄能力决定) */
|
|
@@ -859,7 +871,7 @@ export class EnvironmentLockManager {
|
|
|
859
871
|
* **不自动触发**;仅当检测为 STALE_LOCK_DETECTED 才允许 capture。
|
|
860
872
|
* 二次验证失败 → quarantine(保留 recovering 文件,不 rename 回环境锁,不覆盖 successor)。
|
|
861
873
|
*/
|
|
862
|
-
async recoverStaleLock() {
|
|
874
|
+
async recoverStaleLock(options = {}) {
|
|
863
875
|
// 1. inspect:必须 definitely stale 或 corrupt(崩溃残留无有效 owner)
|
|
864
876
|
const insp = await this.inspectLockState();
|
|
865
877
|
const st = await this.readOwnershipState();
|
|
@@ -867,6 +879,17 @@ export class EnvironmentLockManager {
|
|
|
867
879
|
// 判据必须是**结构性的**(inspectLockState 的 corruptOwnership / readOwnershipState 的 kind)——
|
|
868
880
|
// **不得**再依赖 detail 文案子串:detail 自 t5 起按界面语言本地化,按子串判定在英文界面下会失效。
|
|
869
881
|
const isCorruptReclaim = insp.state === 'UNKNOWN_STATE' && st.kind === 'corrupt';
|
|
882
|
+
if (options.require === 'provable') {
|
|
883
|
+
// 自动路径:只承认结构性可证 stale。corrupt 残留不是 stale(交给显式回收,不替用户判断损坏文件),
|
|
884
|
+
// 长过期启发式也不是(issue #36 的放宽只是「像残留」)。判定必须发生在 rename **之前**:
|
|
885
|
+
// rename 之后才发现不可证,quarantine 已经产生、ownership 已不在原位,等于把现场搞脏。
|
|
886
|
+
if (insp.state !== 'STALE_LOCK_DETECTED' || st.kind !== 'ok') {
|
|
887
|
+
return { ok: false, removed: false, state: insp.state, detail: insp.detail ?? utilsMsg('utils.envLock.notStaleRefuseRecovery') };
|
|
888
|
+
}
|
|
889
|
+
if (!(await this.isProvablyStale(st.rec))) {
|
|
890
|
+
return { ok: false, removed: false, state: insp.state, detail: utilsMsg('utils.envLock.reclaimNotProvable') };
|
|
891
|
+
}
|
|
892
|
+
}
|
|
870
893
|
if (insp.state !== 'STALE_LOCK_DETECTED' && !isCorruptReclaim) {
|
|
871
894
|
return { ok: false, removed: false, state: insp.state, detail: insp.detail ?? utilsMsg('utils.envLock.notStaleRefuseRecovery') };
|
|
872
895
|
}
|
|
@@ -933,11 +956,52 @@ export class EnvironmentLockManager {
|
|
|
933
956
|
}
|
|
934
957
|
return {
|
|
935
958
|
ok: true, removed: true, state: 'STALE_LOCK_DETECTED',
|
|
959
|
+
removedOwner: rec !== null ? { op: rec.op, pid: rec.owner.pid } : undefined,
|
|
936
960
|
detail: rec !== null
|
|
937
961
|
? utilsMsg('utils.envLock.removedStaleOwnership', { op: rec.op, pid: rec.owner.pid })
|
|
938
962
|
: utilsMsg('utils.envLock.removedCorruptOwnership'),
|
|
939
963
|
};
|
|
940
964
|
}
|
|
965
|
+
/**
|
|
966
|
+
* 自动回收入口(宿主启动 / 调度器本轮预检共用):只删**可证** stale,其余返回 null(一动不动)。
|
|
967
|
+
*
|
|
968
|
+
* 为什么不直接让调用方 inspect + recoverStaleLock:判据分散在 inspect(长过期放宽)、recover(corrupt 分支)
|
|
969
|
+
* 和调用方文案三处必然漂移。这里把「自动」的边界收在一处,并且先做两次廉价读(ownership + sidecar):
|
|
970
|
+
* - 无 ownership / corrupt → null(corrupt 留给显式回收);
|
|
971
|
+
* - heartbeat 仍新鲜(≤ staleAfterMs)→ null:**死进程写不出新鲜心跳**,新鲜就是「有人在干活」的证据,
|
|
972
|
+
* 连进程探测都省掉(Windows 上探测活 pid 要 spawn 一次 PowerShell,不能每轮同步都付这个钱)。
|
|
973
|
+
* 通过这两道之后再走结构性判定(kill(pid,0) 的 ESRCH 是快路径)。
|
|
974
|
+
*/
|
|
975
|
+
async reclaimProvableStaleLock() {
|
|
976
|
+
const st = await this.readOwnershipState();
|
|
977
|
+
if (st.kind !== 'ok')
|
|
978
|
+
return null;
|
|
979
|
+
const heartbeat = await this.readHeartbeat(st.rec.owner.instanceId).catch(() => null);
|
|
980
|
+
if (heartbeat !== null && (this.now() - heartbeat.heartbeatAt) <= this.staleAfterMs)
|
|
981
|
+
return null;
|
|
982
|
+
if (!(await this.isProvablyStale(st.rec)))
|
|
983
|
+
return null;
|
|
984
|
+
return this.recoverStaleLock({ require: 'provable' });
|
|
985
|
+
}
|
|
986
|
+
/** 结构性可证 stale:owner pid 确证死亡,或 pid 存活但 OS identity 与 recorded 不同(PID 复用)。
|
|
987
|
+
* 与 inspectLockState / reProveStale 的「长过期」放宽**刻意不同**:自动回收不承认启发式。
|
|
988
|
+
* 探测失败/不确定 → false(保守,绝不构成误删许可)。 */
|
|
989
|
+
async isProvablyStale(rec) {
|
|
990
|
+
let ident;
|
|
991
|
+
try {
|
|
992
|
+
ident = await this.probe.probe(rec.owner.pid);
|
|
993
|
+
}
|
|
994
|
+
catch {
|
|
995
|
+
return false;
|
|
996
|
+
}
|
|
997
|
+
if (!ident.alive)
|
|
998
|
+
return true;
|
|
999
|
+
if (!this.probe.canGetOsIdentity())
|
|
1000
|
+
return false;
|
|
1001
|
+
if (rec.owner.osProcessStartIdentity === null || ident.osProcessStartIdentity === null)
|
|
1002
|
+
return false;
|
|
1003
|
+
return rec.owner.osProcessStartIdentity !== ident.osProcessStartIdentity;
|
|
1004
|
+
}
|
|
941
1005
|
/** recovery 二次验证:重新探测 recorded pid 是否确证死亡(保守——任何不确定性 → 失败)。
|
|
942
1006
|
* 与 inspectLockState 同一套语义:alive:false 仅确证死亡 → stale 成立;
|
|
943
1007
|
* alive 则需 OS identity 判断是否 reuse;无法确定 → 保守失败(不删除)。 */
|
|
@@ -976,6 +1040,71 @@ export class EnvironmentLockManager {
|
|
|
976
1040
|
return null; // NaN / 负值(时钟回拨)→ 保守
|
|
977
1041
|
return utilsMsg('utils.envLock.longExpired', { age: formatDuration(age), threshold: formatDuration(this.longExpiredAfterMs) });
|
|
978
1042
|
}
|
|
1043
|
+
/* ------------------------------------------------------------ shutdown / orphan cleanup */
|
|
1044
|
+
/**
|
|
1045
|
+
* 进程退出(exit 事件 / 插件 dispose)时的**同步**兜底释放:只删自己 instanceId 名下的 ownership + sidecar。
|
|
1046
|
+
*
|
|
1047
|
+
* 为什么必须同步:Node 的 'exit' 事件里不能 await,异步 fs 写不进去。为什么必须核对 instanceId:
|
|
1048
|
+
* 退出路径同样不许删别人的锁(与 release() 同一不变量)。语义 = best-effort:永不抛错、永不留半删态。
|
|
1049
|
+
* 覆盖的场景 = **正常关窗但后台同步正在跑**(此时 release() 永远不会被调用),这也是残留锁的主要来源。
|
|
1050
|
+
*/
|
|
1051
|
+
releaseOnExitSync() {
|
|
1052
|
+
const token = this.activeToken;
|
|
1053
|
+
if (token === null || token.instanceId !== this.activeInstanceId)
|
|
1054
|
+
return;
|
|
1055
|
+
this.activeToken = null;
|
|
1056
|
+
this.stopHeartbeat();
|
|
1057
|
+
try {
|
|
1058
|
+
fssync.unlinkSync(path.join(this.locksDir, `${HEARTBEAT_PREFIX}${this.activeInstanceId}`));
|
|
1059
|
+
}
|
|
1060
|
+
catch { /* 尽力 */ }
|
|
1061
|
+
try {
|
|
1062
|
+
const rec = readLockJsonSafe(fssync.readFileSync(this.ownershipPath, 'utf8'));
|
|
1063
|
+
if (rec !== null && typeof rec === 'object' && rec.owner?.instanceId === this.activeInstanceId) {
|
|
1064
|
+
fssync.unlinkSync(this.ownershipPath);
|
|
1065
|
+
}
|
|
1066
|
+
}
|
|
1067
|
+
catch { /* 缺失/不可读/被占用 → 不动(下次启动的自动回收会处理) */ }
|
|
1068
|
+
}
|
|
1069
|
+
/**
|
|
1070
|
+
* 清理孤儿 heartbeat sidecar(P4):只删「已不是当前持有者、且心跳早已停更」的 sidecar。
|
|
1071
|
+
*
|
|
1072
|
+
* 判据不需要 pid(sidecar 里本来就没有 pid):sidecar 的生命周期被三处保证——acquire 时创建、
|
|
1073
|
+
* release 时删、recover 时删被回收者的那份。于是「instanceId 既不是当前 ownership 的持有者、
|
|
1074
|
+
* 心跳又超过 stale 窗口」只可能是崩溃/强杀留下的孤儿。心跳仍新鲜的跳过:那是接管竞态窗口。
|
|
1075
|
+
* 不碰 environment.lock 与 environment.recovering.*(那属于判定,不归清理)。
|
|
1076
|
+
* @returns 实际删除数量
|
|
1077
|
+
*/
|
|
1078
|
+
async cleanupOrphanHeartbeats() {
|
|
1079
|
+
let names;
|
|
1080
|
+
try {
|
|
1081
|
+
names = await (this.io.listLocksDir ? this.io.listLocksDir(this.locksDir) : Promise.resolve([]));
|
|
1082
|
+
}
|
|
1083
|
+
catch {
|
|
1084
|
+
return 0;
|
|
1085
|
+
}
|
|
1086
|
+
const st = await this.readOwnershipState();
|
|
1087
|
+
const holderId = st.kind === 'ok' ? st.rec.owner.instanceId : null;
|
|
1088
|
+
let removed = 0;
|
|
1089
|
+
for (const name of names) {
|
|
1090
|
+
if (!name.startsWith(HEARTBEAT_PREFIX))
|
|
1091
|
+
continue;
|
|
1092
|
+
const instanceId = name.slice(HEARTBEAT_PREFIX.length);
|
|
1093
|
+
if (instanceId === this.activeInstanceId || instanceId === holderId)
|
|
1094
|
+
continue;
|
|
1095
|
+
const rec = await this.readHeartbeat(instanceId).catch(() => null);
|
|
1096
|
+
if (rec === null)
|
|
1097
|
+
continue; // 读不出/形状不符 → 没有判据,保留
|
|
1098
|
+
if ((this.now() - rec.heartbeatAt) <= this.staleAfterMs)
|
|
1099
|
+
continue;
|
|
1100
|
+
try {
|
|
1101
|
+
await this.io.unlink(path.join(this.locksDir, name));
|
|
1102
|
+
removed += 1;
|
|
1103
|
+
}
|
|
1104
|
+
catch { /* 尽力;下轮再试 */ }
|
|
1105
|
+
}
|
|
1106
|
+
return removed;
|
|
1107
|
+
}
|
|
979
1108
|
/* ------------------------------------------------------------ diag */
|
|
980
1109
|
/** 列出 locks 目录内容(诊断;不存在 → 空) */
|
|
981
1110
|
async listLockFiles() {
|
|
@@ -60,6 +60,9 @@ export declare const zh: {
|
|
|
60
60
|
'utils.envLock.removeCapturedFailed': string;
|
|
61
61
|
'utils.envLock.removedStaleOwnership': string;
|
|
62
62
|
'utils.envLock.removedCorruptOwnership': string;
|
|
63
|
+
'utils.envLock.reclaimNotProvable': string;
|
|
64
|
+
'utils.envLock.autoReclaimedStale': string;
|
|
65
|
+
'utils.envLock.orphanHeartbeatsRemoved': string;
|
|
63
66
|
'utils.envLock.longExpired': string;
|
|
64
67
|
'utils.envLock.durationDays': string;
|
|
65
68
|
'utils.envLock.durationHours': string;
|