@kabxx/dsh-message-revision 0.1.0 → 0.1.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/README.md +26 -17
- package/package.json +4 -2
- package/src/bounded-commit.js +121 -0
- package/src/bounded-revision.js +250 -0
- package/src/client.js +426 -72
- package/src/index.js +388 -89
- package/src/native-lease.js +143 -0
- package/src/platform.js +623 -0
- package/src/revision-candidates.js +341 -0
- package/src/revision-notifications.js +122 -0
- package/src/revision.js +170 -53
- package/src/rewrite-journal.js +631 -55
- package/src/rollback-events.js +8 -0
- package/src/rollout-process.js +259 -0
- package/src/rollout-stream.js +521 -0
- package/src/rollout-worker.js +452 -0
|
@@ -0,0 +1,452 @@
|
|
|
1
|
+
import { writeSync } from 'node:fs';
|
|
2
|
+
import { readFile } from 'node:fs/promises';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { getHeapStatistics } from 'node:v8';
|
|
5
|
+
import {
|
|
6
|
+
JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE, JOB_OBJECT_LIMIT_PROCESS_MEMORY, queryCurrentWin32JobLimits,
|
|
7
|
+
} from './platform.js';
|
|
8
|
+
import { withRevisionCandidateOutput } from './revision-candidates.js';
|
|
9
|
+
import { isProvisionalResumeMarker } from './rollback-events.js';
|
|
10
|
+
import {
|
|
11
|
+
checkRolloutIdentity, probeSeededSubagentTail, readRolloutLines, readRolloutLinesFromOffset,
|
|
12
|
+
requireRollout, writeRolloutCandidate,
|
|
13
|
+
} from './rollout-stream.js';
|
|
14
|
+
|
|
15
|
+
export const maxMessageBytes = 8 * 1024 * 1024;
|
|
16
|
+
const maxCatalogBytes = 4 * 1024 * 1024;
|
|
17
|
+
const maxQueue = 4096;
|
|
18
|
+
const maxCopies = 8192;
|
|
19
|
+
|
|
20
|
+
const createStats = () => ({ bytes: 0, records: 0, maxRecordBytes: 0 });
|
|
21
|
+
|
|
22
|
+
function measure(stats, line) {
|
|
23
|
+
stats.bytes += line.length;
|
|
24
|
+
stats.records++;
|
|
25
|
+
stats.maxRecordBytes = Math.max(stats.maxRecordBytes, line.length);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function createPlanTracker(messageId) {
|
|
29
|
+
const queues = { 'next-turn': [], 'next-step': [] };
|
|
30
|
+
let turn;
|
|
31
|
+
let selected = false;
|
|
32
|
+
let checkpoint;
|
|
33
|
+
let latestTime = 0;
|
|
34
|
+
let copies = [];
|
|
35
|
+
let prefix;
|
|
36
|
+
return {
|
|
37
|
+
accept(event, stats, framePrefix) {
|
|
38
|
+
const { seq, data, time } = event;
|
|
39
|
+
// Sequence numbers order the parent log, but comparing parent and child
|
|
40
|
+
// logs requires the wall clock to agree on both sides of this cutoff.
|
|
41
|
+
if (checkpoint && time < checkpoint.time) checkpoint.timestampAmbiguous = true;
|
|
42
|
+
if (turn?.input && time < turn.time) turn.timestampAmbiguous = true;
|
|
43
|
+
const earlierTime = latestTime;
|
|
44
|
+
latestTime = Math.max(latestTime, time);
|
|
45
|
+
if (event.type === 'agent/inbox/spliced') {
|
|
46
|
+
const queue = queues[data.target];
|
|
47
|
+
const removed = data.removedCount ?? 0;
|
|
48
|
+
requireRollout(Array.isArray(queue) && Number.isSafeInteger(data.start) && data.start >= 0
|
|
49
|
+
&& data.start <= queue.length && Number.isSafeInteger(removed) && removed >= 0
|
|
50
|
+
&& removed <= queue.length - data.start && Array.isArray(data.inserted)
|
|
51
|
+
&& queue.length - removed + data.inserted.length <= maxQueue,
|
|
52
|
+
'会话消息队列无效或超出检查上限。');
|
|
53
|
+
const inserted = data.inserted.map((message, offset) => {
|
|
54
|
+
requireRollout(typeof message?.id === 'string' && message.id.length <= 2048, '消息记录无效。');
|
|
55
|
+
if (message.id !== messageId) return { id: message.id };
|
|
56
|
+
requireRollout(copies.length < maxCopies, '同一消息的历史入队记录超出检查上限。');
|
|
57
|
+
const item = { index: seq, offset, kind: message.source?.kind };
|
|
58
|
+
if (copies.length === 0) prefix = framePrefix;
|
|
59
|
+
copies.push(item);
|
|
60
|
+
return { id: message.id, ...item };
|
|
61
|
+
});
|
|
62
|
+
queue.splice(data.start, removed, ...inserted);
|
|
63
|
+
} else if (event.type === 'turn/start') {
|
|
64
|
+
requireRollout(turn === undefined, '会话日志中存在未关闭的对话轮次。');
|
|
65
|
+
const candidate = queues['next-turn'][0];
|
|
66
|
+
turn = { number: data.turn, index: seq, time, queuedCount: queues['next-turn'].length,
|
|
67
|
+
hasSteering: queues['next-step'].length > 0, input: candidate?.id === messageId ? candidate : undefined,
|
|
68
|
+
timestampAmbiguous: earlierTime > time, stats: candidate?.id === messageId ? { ...stats } : undefined };
|
|
69
|
+
} else if (event.type === 'turn/end') {
|
|
70
|
+
requireRollout(turn?.number === data.turn, '会话日志的轮次边界不完整。');
|
|
71
|
+
turn = undefined;
|
|
72
|
+
} else if (event.type === 'user/message' && data?.id === messageId && data.source?.kind === 'user') {
|
|
73
|
+
requireRollout(!selected, '日志中找到了重复的用户消息。');
|
|
74
|
+
selected = true;
|
|
75
|
+
checkpoint = turn;
|
|
76
|
+
if (checkpoint) copies = copies.filter(item => item.index < checkpoint.index);
|
|
77
|
+
}
|
|
78
|
+
},
|
|
79
|
+
finish(inheritedCount) {
|
|
80
|
+
if (turn !== undefined) throw Object.assign(new Error('回复生成中,请先停止或等待完成。'), { reason: 'busy' });
|
|
81
|
+
if (!(selected && checkpoint?.input && checkpoint.index > inheritedCount
|
|
82
|
+
&& checkpoint.input.index >= inheritedCount && !checkpoint.hasSteering && checkpoint.queuedCount === 1)) {
|
|
83
|
+
throw Object.assign(new Error('此消息没有可独立回退的对话轮次。'), { reason: 'non-independent-turn' });
|
|
84
|
+
}
|
|
85
|
+
if (queues['next-turn'].length !== 0 || queues['next-step'].length !== 0) {
|
|
86
|
+
throw Object.assign(new Error('会话仍有排队消息,请等队列清空后再试。'), { reason: 'queue-pending' });
|
|
87
|
+
}
|
|
88
|
+
const retainedInputs = copies.filter(item => item.index < checkpoint.index);
|
|
89
|
+
if (!retainedInputs.every(item => item.index >= inheritedCount && item.kind === 'user')) {
|
|
90
|
+
throw Object.assign(new Error('无法替换继承历史中的同一条消息。'), { reason: 'inherited-duplicate' });
|
|
91
|
+
}
|
|
92
|
+
const { index, offset } = checkpoint.input;
|
|
93
|
+
return { plan: { cut: checkpoint.index, time: checkpoint.time, input: { index, offset },
|
|
94
|
+
...(checkpoint.timestampAmbiguous && { timestampAmbiguous: true }),
|
|
95
|
+
retainedInputs: retainedInputs.map(({ index, offset }) => ({ index, offset })) }, prefixStats: checkpoint.stats, prefix };
|
|
96
|
+
},
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
async function scanSeededSubagentTail({ path, sessionId, cutoff }) {
|
|
101
|
+
const probe = await probeSeededSubagentTail(path, sessionId, cutoff);
|
|
102
|
+
if (!probe) return null;
|
|
103
|
+
const tailStats = createStats();
|
|
104
|
+
const catalog = [];
|
|
105
|
+
let catalogBytes = 0;
|
|
106
|
+
let seen = 0;
|
|
107
|
+
let sawDescriptor = false;
|
|
108
|
+
let inTurn;
|
|
109
|
+
for await (const { record, line } of readRolloutLinesFromOffset(path, probe.tailOffset, probe.startSeq, probe.identity)) {
|
|
110
|
+
if (seen === 0) {
|
|
111
|
+
if (record.type === 'subagent/descriptor') sawDescriptor = true;
|
|
112
|
+
else if (probe.header.agentPreset === undefined || record.type !== 'agent-preset/selected'
|
|
113
|
+
|| record.data?.agentPreset !== probe.header.agentPreset) return null;
|
|
114
|
+
} else if (seen === 1 && !sawDescriptor) {
|
|
115
|
+
if (record.type === 'subagent/descriptor') sawDescriptor = true;
|
|
116
|
+
else return null;
|
|
117
|
+
}
|
|
118
|
+
if (record.type === 'session/end-seed' && record.data?.inherited === true) return null;
|
|
119
|
+
if (record.time >= cutoff) return null;
|
|
120
|
+
if (record.type === 'subagent/catalog') {
|
|
121
|
+
catalogBytes += line.length;
|
|
122
|
+
requireRollout(catalogBytes <= maxCatalogBytes, '子智能体登记超出单次检查上限。');
|
|
123
|
+
catalog.push(record);
|
|
124
|
+
}
|
|
125
|
+
if (record.type === 'turn/start') {
|
|
126
|
+
if (inTurn !== undefined || record.data?.turn === undefined) return null;
|
|
127
|
+
inTurn = record.data.turn;
|
|
128
|
+
} else if (record.type === 'turn/end') {
|
|
129
|
+
if (inTurn === undefined || inTurn !== record.data?.turn) return null;
|
|
130
|
+
inTurn = undefined;
|
|
131
|
+
}
|
|
132
|
+
measure(tailStats, line);
|
|
133
|
+
seen++;
|
|
134
|
+
}
|
|
135
|
+
if (!sawDescriptor || inTurn !== undefined) return null;
|
|
136
|
+
const totalRecords = probe.startSeq + seen;
|
|
137
|
+
const stats = {
|
|
138
|
+
bytes: probe.seedFrameBytes + tailStats.bytes,
|
|
139
|
+
records: totalRecords,
|
|
140
|
+
maxRecordBytes: tailStats.maxRecordBytes,
|
|
141
|
+
};
|
|
142
|
+
return {
|
|
143
|
+
header: probe.header,
|
|
144
|
+
identity: probe.identity,
|
|
145
|
+
catalog,
|
|
146
|
+
stats,
|
|
147
|
+
inheritedCount: probe.inheritedCount,
|
|
148
|
+
prefixStats: stats,
|
|
149
|
+
cut: totalRecords,
|
|
150
|
+
crosses: false,
|
|
151
|
+
inTurnAtCut: false,
|
|
152
|
+
inTurn: false,
|
|
153
|
+
ambiguous: false,
|
|
154
|
+
provisional: true,
|
|
155
|
+
fastSeededTail: true,
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
async function scan({ path, sessionId, cutoff, inheritedCount: expectedInheritedCount, fromSeq, permitResumeMarker, messageId, allowLegacy }, planning = false) {
|
|
160
|
+
requireRollout(typeof sessionId === 'string' && sessionId.length <= 2048, '会话标识无效。');
|
|
161
|
+
requireRollout(cutoff === undefined || (Number.isSafeInteger(cutoff) && cutoff >= 0), '回退时刻无效。');
|
|
162
|
+
requireRollout(fromSeq === undefined || (Number.isSafeInteger(fromSeq) && fromSeq >= 0), '恢复位置无效。');
|
|
163
|
+
requireRollout(!planning || (typeof messageId === 'string' && messageId.length <= 2048), '消息标识无效。');
|
|
164
|
+
if (!planning && cutoff !== undefined && expectedInheritedCount === undefined
|
|
165
|
+
&& fromSeq === undefined && allowLegacy !== true) {
|
|
166
|
+
const fast = await scanSeededSubagentTail({ path, sessionId, cutoff });
|
|
167
|
+
if (fast) return fast;
|
|
168
|
+
}
|
|
169
|
+
const tracker = planning ? createPlanTracker(messageId) : undefined;
|
|
170
|
+
const stats = createStats();
|
|
171
|
+
let prefixStats;
|
|
172
|
+
let header;
|
|
173
|
+
let identity;
|
|
174
|
+
let catalog = [];
|
|
175
|
+
let catalogBytes = 0;
|
|
176
|
+
let inheritedCount = 0;
|
|
177
|
+
let sawInherited = false;
|
|
178
|
+
let inTurn;
|
|
179
|
+
let legacyStep;
|
|
180
|
+
let inTurnAtCut = false;
|
|
181
|
+
let cut;
|
|
182
|
+
let prefix;
|
|
183
|
+
let ambiguous = false;
|
|
184
|
+
let provisional = true;
|
|
185
|
+
const legacy = allowLegacy === true && !planning && cutoff !== undefined;
|
|
186
|
+
for await (const item of readRolloutLines(path, sessionId, {
|
|
187
|
+
allowLegacy: legacy, trackZstdPrefix: planning || (cutoff !== undefined && !legacy),
|
|
188
|
+
})) {
|
|
189
|
+
const { record, line, index, framePrefix } = item;
|
|
190
|
+
if (index === -1) {
|
|
191
|
+
header = record;
|
|
192
|
+
identity = item.identity;
|
|
193
|
+
continue;
|
|
194
|
+
}
|
|
195
|
+
const inheritedMarker = record.type === 'session/end-seed' && record.data?.inherited === true;
|
|
196
|
+
if (inheritedMarker) {
|
|
197
|
+
requireRollout(header.isSeeded === true, '日志文件头与继承边界不匹配。');
|
|
198
|
+
inheritedCount = index;
|
|
199
|
+
sawInherited = true;
|
|
200
|
+
catalog = [];
|
|
201
|
+
catalogBytes = 0;
|
|
202
|
+
cut = undefined;
|
|
203
|
+
prefixStats = undefined;
|
|
204
|
+
prefix = undefined;
|
|
205
|
+
ambiguous = false;
|
|
206
|
+
inTurnAtCut = false;
|
|
207
|
+
} else {
|
|
208
|
+
if (record.type === 'subagent/catalog') {
|
|
209
|
+
catalogBytes += line.length;
|
|
210
|
+
requireRollout(catalogBytes <= maxCatalogBytes, '子智能体登记超出单次检查上限。');
|
|
211
|
+
catalog.push(record);
|
|
212
|
+
}
|
|
213
|
+
if (cutoff !== undefined) {
|
|
214
|
+
// Session sequence numbers order only this rollout. A millisecond tie
|
|
215
|
+
// with the parent's cutoff does not tell us which event came first.
|
|
216
|
+
if (record.time === cutoff) ambiguous = true;
|
|
217
|
+
if (cut === undefined && record.time >= cutoff) {
|
|
218
|
+
cut = index;
|
|
219
|
+
inTurnAtCut = inTurn !== undefined;
|
|
220
|
+
prefixStats = { ...stats };
|
|
221
|
+
prefix = framePrefix;
|
|
222
|
+
} else if (cut !== undefined && record.time < cutoff) {
|
|
223
|
+
ambiguous = true;
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
tracker?.accept(record, stats, framePrefix);
|
|
228
|
+
if (record.type === 'turn/start') {
|
|
229
|
+
requireRollout(inTurn === undefined, '会话日志中存在嵌套对话轮次。');
|
|
230
|
+
if (header.version === 3) requireRollout(Number.isSafeInteger(record.data?.turn) && record.data.turn > 0,
|
|
231
|
+
'旧版子会话轮次无效。');
|
|
232
|
+
inTurn = record.data.turn;
|
|
233
|
+
} else if (record.type === 'turn/end') {
|
|
234
|
+
requireRollout(inTurn !== undefined && inTurn === record.data.turn && legacyStep === undefined,
|
|
235
|
+
'会话日志的轮次边界不完整。');
|
|
236
|
+
inTurn = undefined;
|
|
237
|
+
} else if (header.version === 3 && record.type === 'step/start') {
|
|
238
|
+
requireRollout(legacyStep === undefined && inTurn !== undefined && record.data?.turn === inTurn
|
|
239
|
+
&& Number.isSafeInteger(record.data.step) && record.data.step > 0, '旧版子会话的步骤边界不完整。');
|
|
240
|
+
legacyStep = record.data.step;
|
|
241
|
+
} else if (header.version === 3 && record.type === 'step/end') {
|
|
242
|
+
requireRollout(legacyStep !== undefined && record.data?.turn === inTurn && record.data.step === legacyStep,
|
|
243
|
+
'旧版子会话的步骤边界不完整。');
|
|
244
|
+
legacyStep = undefined;
|
|
245
|
+
}
|
|
246
|
+
if (fromSeq !== undefined && index >= fromSeq
|
|
247
|
+
&& !(permitResumeMarker === true && isProvisionalResumeMarker(record, fromSeq))) provisional = false;
|
|
248
|
+
measure(stats, line);
|
|
249
|
+
}
|
|
250
|
+
requireRollout(header.isSeeded !== true || sawInherited, '缺少可验证的继承边界。');
|
|
251
|
+
requireRollout(expectedInheritedCount === undefined || expectedInheritedCount === inheritedCount, '继承的会话历史已变化。');
|
|
252
|
+
const common = { header, identity, catalog, stats, inheritedCount };
|
|
253
|
+
if (tracker) return { ...common, ...tracker.finish(inheritedCount) };
|
|
254
|
+
return { ...common, prefixStats: prefixStats ?? stats, cut: cut ?? stats.records, crosses: cut !== undefined,
|
|
255
|
+
inTurnAtCut: cut === undefined ? inTurn !== undefined : inTurnAtCut, inTurn: inTurn !== undefined,
|
|
256
|
+
ambiguous, provisional: provisional && (fromSeq === undefined || stats.records >= fromSeq), prefix };
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
async function prepare({ path, sessionId, output, cut, inputCopies = [], message, appendEvents = [], identity: expected, prefix }) {
|
|
260
|
+
requireRollout(Number.isSafeInteger(cut) && cut >= 0 && Array.isArray(inputCopies) && inputCopies.length <= maxCopies
|
|
261
|
+
&& Array.isArray(appendEvents) && (inputCopies.length === 0 || Array.isArray(message?.content)), '编辑参数无效。');
|
|
262
|
+
const swaps = new Map();
|
|
263
|
+
let firstChanged = cut;
|
|
264
|
+
for (const { index, offset } of inputCopies) {
|
|
265
|
+
requireRollout(Number.isSafeInteger(index) && index >= 0 && index < cut
|
|
266
|
+
&& Number.isSafeInteger(offset) && offset >= 0, '原消息的位置无效。');
|
|
267
|
+
const offsets = swaps.get(index) ?? [];
|
|
268
|
+
requireRollout(!offsets.includes(offset), '原消息的位置重复。');
|
|
269
|
+
offsets.push(offset);
|
|
270
|
+
swaps.set(index, offsets);
|
|
271
|
+
if (index < firstChanged) firstChanged = index;
|
|
272
|
+
}
|
|
273
|
+
// The Host passes this boundary only from a completed scan of this file
|
|
274
|
+
// identity. Older callers without a boundary use the streaming fallback.
|
|
275
|
+
const prefixCopy = expected && path.endsWith('.zstd') && Number.isSafeInteger(prefix?.end) && prefix.end > 0
|
|
276
|
+
&& Number.isSafeInteger(prefix.startSeq) && prefix.startSeq > 0 && prefix.startSeq <= firstChanged
|
|
277
|
+
? { sourcePath: path, end: prefix.end, startSeq: prefix.startSeq, expected } : undefined;
|
|
278
|
+
const stats = createStats();
|
|
279
|
+
let identity = prefixCopy?.expected;
|
|
280
|
+
let copied = prefixCopy?.startSeq ?? 0;
|
|
281
|
+
function applySwaps(item) {
|
|
282
|
+
const offsets = swaps.get(item.index);
|
|
283
|
+
if (!offsets) return;
|
|
284
|
+
for (const offset of offsets) {
|
|
285
|
+
const occurrence = item.record.data?.inserted?.[offset];
|
|
286
|
+
requireRollout(item.record.type === 'agent/inbox/spliced' && occurrence?.id === message.id
|
|
287
|
+
&& occurrence.source?.kind === 'user', '无法定位原消息的入队记录。');
|
|
288
|
+
item.record.data.inserted[offset] = { ...occurrence, content: message.content };
|
|
289
|
+
}
|
|
290
|
+
item.line = Buffer.from(`${JSON.stringify(item.record)}\n`);
|
|
291
|
+
swaps.delete(item.index);
|
|
292
|
+
}
|
|
293
|
+
async function* outputLines() {
|
|
294
|
+
if (prefixCopy) {
|
|
295
|
+
if (copied < cut) {
|
|
296
|
+
for await (const item of readRolloutLinesFromOffset(path, prefixCopy.end, copied, prefixCopy.expected)) {
|
|
297
|
+
if (item.index >= cut) break;
|
|
298
|
+
applySwaps(item);
|
|
299
|
+
copied++;
|
|
300
|
+
measure(stats, item.line);
|
|
301
|
+
yield item;
|
|
302
|
+
if (copied === cut) break;
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
requireRollout(copied === cut && swaps.size === 0, '日志没有包含完整的候选前缀。');
|
|
306
|
+
await checkRolloutIdentity(path, prefixCopy.expected);
|
|
307
|
+
} else {
|
|
308
|
+
for await (const item of readRolloutLines(path, sessionId)) {
|
|
309
|
+
if (item.index === -1) {
|
|
310
|
+
identity = item.identity;
|
|
311
|
+
if (expected) await checkRolloutIdentity(path, expected);
|
|
312
|
+
yield item;
|
|
313
|
+
} else {
|
|
314
|
+
applySwaps(item);
|
|
315
|
+
copied++;
|
|
316
|
+
measure(stats, item.line);
|
|
317
|
+
yield item;
|
|
318
|
+
}
|
|
319
|
+
if (copied === cut) break;
|
|
320
|
+
}
|
|
321
|
+
requireRollout(copied === cut && swaps.size === 0, '日志没有包含完整的候选前缀。');
|
|
322
|
+
await checkRolloutIdentity(path, identity);
|
|
323
|
+
}
|
|
324
|
+
for (const entry of appendEvents) {
|
|
325
|
+
const index = copied++;
|
|
326
|
+
const time = entry.time ?? Date.now();
|
|
327
|
+
requireRollout(typeof entry.type === 'string' && Number.isSafeInteger(time) && time >= 0
|
|
328
|
+
&& Object.hasOwn(entry, 'data'), '附加会话事件无效。');
|
|
329
|
+
const line = Buffer.from(`${JSON.stringify({ ...entry, seq: index, time })}\n`);
|
|
330
|
+
measure(stats, line);
|
|
331
|
+
yield { line, index };
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
const result = await writeRolloutCandidate(output, path.endsWith('.zstd'), outputLines(), prefixCopy);
|
|
335
|
+
return { path: output, ...result, retained: copied, writtenStats: stats, identity, copiedPrefixBytes: prefixCopy?.end ?? 0 };
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
export async function runOperation(operation, input) {
|
|
339
|
+
switch (operation) {
|
|
340
|
+
case 'plan': return scan(input, true);
|
|
341
|
+
case 'inspect':
|
|
342
|
+
case 'scan': return scan(input);
|
|
343
|
+
case 'scanMany': {
|
|
344
|
+
requireRollout(Array.isArray(input.items) && input.items.length <= 10_000, '批量会话核对超出上限。');
|
|
345
|
+
const result = [];
|
|
346
|
+
let bytes = 0;
|
|
347
|
+
for (const item of input.items) {
|
|
348
|
+
const summary = await scan(item);
|
|
349
|
+
bytes += Buffer.byteLength(JSON.stringify(summary));
|
|
350
|
+
requireRollout(bytes < maxMessageBytes - 16 * 1024, '批量会话核对结果过大。');
|
|
351
|
+
result.push(summary);
|
|
352
|
+
}
|
|
353
|
+
return result;
|
|
354
|
+
}
|
|
355
|
+
case 'prepare': return withRevisionCandidateOutput(input.output, () => prepare(input));
|
|
356
|
+
default: throw new Error('不支持此日志操作。');
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
const heapLimitCeilingBytes = 384 * 1024 * 1024;
|
|
361
|
+
const win32JobCeilingBytes = process.versions.electron ? 384 * 1024 * 1024 : 256 * 1024 * 1024;
|
|
362
|
+
const watchdogRssLimitBytes = process.versions.electron ? 384 * 1024 * 1024 : 256 * 1024 * 1024;
|
|
363
|
+
|
|
364
|
+
function assertBoundedHeap() {
|
|
365
|
+
requireRollout(process.execArgv.includes('--max-old-space-size=128')
|
|
366
|
+
&& getHeapStatistics().heap_size_limit <= heapLimitCeilingBytes, '系统未应用日志准备堆内存上限。');
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
function startRssWatchdog() {
|
|
370
|
+
const timer = setInterval(() => {
|
|
371
|
+
if (process.memoryUsage.rss() > watchdogRssLimitBytes) process.exit(137);
|
|
372
|
+
}, 100);
|
|
373
|
+
timer.unref();
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
async function verifyIsolation(mode) {
|
|
377
|
+
if (mode === 'cgroup') {
|
|
378
|
+
const cgroup = (await readFile('/proc/self/cgroup', 'utf8')).split('\n').find(line => line.startsWith('0::'));
|
|
379
|
+
const relative = cgroup?.slice(3);
|
|
380
|
+
requireRollout(relative?.startsWith('/') && /\/dsh-message-revision-[a-f0-9-]+\.scope$/u.test(relative),
|
|
381
|
+
'日志准备进程未进入隔离组。');
|
|
382
|
+
const directory = join('/sys/fs/cgroup', relative);
|
|
383
|
+
const memory = Number((await readFile(join(directory, 'memory.max'), 'utf8')).trim());
|
|
384
|
+
const swap = Number((await readFile(join(directory, 'memory.swap.max'), 'utf8')).trim());
|
|
385
|
+
requireRollout(Number.isSafeInteger(memory) && memory > 0 && memory <= 268435456 && swap === 0,
|
|
386
|
+
'系统未应用日志准备内存上限。');
|
|
387
|
+
} else if (mode === 'rlimit') {
|
|
388
|
+
const limits = await readFile('/proc/self/limits', 'utf8');
|
|
389
|
+
const match = /^Max address space\s+(\d+)\s+(\d+)\s+bytes/mu.exec(limits);
|
|
390
|
+
requireRollout(match && Number(match[2]) <= 1073741824, '系统未应用进程地址空间上限。');
|
|
391
|
+
} else if (mode === 'win32-job') {
|
|
392
|
+
requireRollout(process.platform === 'win32', '日志准备进程隔离模式与当前系统不匹配。');
|
|
393
|
+
assertBoundedHeap();
|
|
394
|
+
const limits = queryCurrentWin32JobLimits();
|
|
395
|
+
requireRollout(limits !== null
|
|
396
|
+
&& (limits.flags & JOB_OBJECT_LIMIT_PROCESS_MEMORY) !== 0
|
|
397
|
+
&& (limits.flags & JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE) !== 0
|
|
398
|
+
&& Number.isSafeInteger(limits.processMemoryLimit)
|
|
399
|
+
&& limits.processMemoryLimit > 0 && limits.processMemoryLimit <= win32JobCeilingBytes,
|
|
400
|
+
'系统未应用日志准备内存上限。');
|
|
401
|
+
} else if (mode === 'darwin-rlimit' || mode === 'win32-watchdog') {
|
|
402
|
+
requireRollout(process.platform === (mode === 'darwin-rlimit' ? 'darwin' : 'win32'),
|
|
403
|
+
'日志准备进程隔离模式与当前系统不匹配。');
|
|
404
|
+
assertBoundedHeap();
|
|
405
|
+
startRssWatchdog();
|
|
406
|
+
} else {
|
|
407
|
+
throw new Error('不支持的日志准备隔离模式。');
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
async function readRequestBytes() {
|
|
412
|
+
const chunks = [];
|
|
413
|
+
let bytes = 0;
|
|
414
|
+
for await (const chunk of process.stdin) {
|
|
415
|
+
bytes += chunk.length;
|
|
416
|
+
requireRollout(bytes <= maxMessageBytes, '日志准备参数超出大小上限。');
|
|
417
|
+
chunks.push(chunk);
|
|
418
|
+
}
|
|
419
|
+
return Buffer.concat(chunks, bytes);
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
async function main() {
|
|
423
|
+
const mode = process.argv[3];
|
|
424
|
+
let rawRequest;
|
|
425
|
+
if (mode === 'win32-job') {
|
|
426
|
+
// Host assigns the Job Object before closing stdin, so reading the bounded
|
|
427
|
+
// request first ensures the kernel job limits are active before self-check.
|
|
428
|
+
rawRequest = await readRequestBytes();
|
|
429
|
+
await verifyIsolation(mode);
|
|
430
|
+
writeSync(1, 'R1\n');
|
|
431
|
+
} else {
|
|
432
|
+
await verifyIsolation(mode);
|
|
433
|
+
writeSync(1, 'R1\n');
|
|
434
|
+
rawRequest = await readRequestBytes();
|
|
435
|
+
}
|
|
436
|
+
try {
|
|
437
|
+
const payload = JSON.parse(rawRequest.toString('utf8'));
|
|
438
|
+
const value = await runOperation(payload.operation, payload.input);
|
|
439
|
+
const json = JSON.stringify({ ok: true, value });
|
|
440
|
+
requireRollout(Buffer.byteLength(json) < maxMessageBytes - 3, '日志准备结果超出大小上限。');
|
|
441
|
+
await new Promise((resolve, reject) => process.stdout.write(json, error => error ? reject(error) : resolve()));
|
|
442
|
+
} catch (error) {
|
|
443
|
+
const message = error instanceof SyntaxError ? '会话日志包含无效 JSON。'
|
|
444
|
+
: error?.code === 'Z_BUF_ERROR' || error?.code?.startsWith?.('ZSTD_') ? '压缩日志无效或尚未完整落盘。'
|
|
445
|
+
: error?.code ? '读取或准备会话日志时遇到文件错误。' : error?.message ?? '会话日志准备失败。';
|
|
446
|
+
await new Promise(resolve => process.stdout.write(JSON.stringify({ ok: false, message, reason: error?.reason }), resolve));
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
if (process.argv[2] === 'dsh-rollout-worker') {
|
|
451
|
+
await main().catch(() => { process.exitCode = 1; });
|
|
452
|
+
}
|