@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,8 @@
|
|
|
1
|
+
// DSH 0.2.2-rc.5 may append one empty seed marker when it opens a log.
|
|
2
|
+
// Other suffix events can be user writes from an independent DSH instance.
|
|
3
|
+
export function isProvisionalResumeMarker(event, firstSeq) {
|
|
4
|
+
return event.seq === firstSeq && event.type === 'session/end-seed'
|
|
5
|
+
&& event.data !== null && typeof event.data === 'object' && !Array.isArray(event.data)
|
|
6
|
+
&& Object.keys(event.data).length === 0
|
|
7
|
+
&& Object.keys(event).every(key => key === 'type' || key === 'seq' || key === 'time' || key === 'data');
|
|
8
|
+
}
|
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { randomUUID } from 'node:crypto';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
import {
|
|
5
|
+
createWin32MemoryJob, isSupportedPlatform, killWin32ProcessTree, loadHostFlock,
|
|
6
|
+
readDarwinProcessRssBytes, workerEnv,
|
|
7
|
+
} from './platform.js';
|
|
8
|
+
|
|
9
|
+
const entry = fileURLToPath(new URL('./rollout-worker.js', import.meta.url));
|
|
10
|
+
const maxMessageBytes = 8 * 1024 * 1024;
|
|
11
|
+
const defaultTimeout = 180_000;
|
|
12
|
+
const win32JobMemoryBytes = process.versions.electron ? 384 * 1024 * 1024 : 256 * 1024 * 1024;
|
|
13
|
+
const darwinRssLimitBytes = process.versions.electron ? 384 * 1024 * 1024 : 256 * 1024 * 1024;
|
|
14
|
+
const darwinWatchdogIntervalMs = 150;
|
|
15
|
+
const processKey = Symbol.for('dsh-message-revision.rollout-process');
|
|
16
|
+
const userFacingReasons = Object.freeze({
|
|
17
|
+
busy: '回复生成中,请先停止或等待完成。',
|
|
18
|
+
'queue-pending': '会话仍有排队消息,请等队列清空后再试。',
|
|
19
|
+
'non-independent-turn': '此消息没有可独立回退的对话轮次。',
|
|
20
|
+
'inherited-duplicate': '无法替换继承历史中的同一条消息。',
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
export class RolloutWorkerError extends Error {
|
|
24
|
+
constructor(message, options, reason) {
|
|
25
|
+
super(message, options);
|
|
26
|
+
this.name = 'RolloutWorkerError';
|
|
27
|
+
if (reason !== undefined) this.reason = reason;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function startWorker(command, args, request, {
|
|
32
|
+
signal,
|
|
33
|
+
timeout,
|
|
34
|
+
detached = true,
|
|
35
|
+
windowsHide = false,
|
|
36
|
+
beforeRequest,
|
|
37
|
+
watchChild,
|
|
38
|
+
onTerminate,
|
|
39
|
+
onClose,
|
|
40
|
+
}) {
|
|
41
|
+
return new Promise(resolve => {
|
|
42
|
+
const child = spawn(command, args, {
|
|
43
|
+
stdio: ['pipe', 'pipe', 'ignore'],
|
|
44
|
+
detached,
|
|
45
|
+
windowsHide,
|
|
46
|
+
env: workerEnv(),
|
|
47
|
+
});
|
|
48
|
+
const output = [];
|
|
49
|
+
let size = 0;
|
|
50
|
+
let ready = false;
|
|
51
|
+
let error;
|
|
52
|
+
let closed = false;
|
|
53
|
+
let stopWatch;
|
|
54
|
+
const terminate = reason => {
|
|
55
|
+
error ??= reason;
|
|
56
|
+
try { onTerminate?.(child); } catch { /* Fall through to direct signal. */ }
|
|
57
|
+
if (child.pid) {
|
|
58
|
+
if (detached && process.platform !== 'win32') {
|
|
59
|
+
try { process.kill(-child.pid, 'SIGKILL'); } catch { child.kill('SIGKILL'); }
|
|
60
|
+
} else {
|
|
61
|
+
try { child.kill('SIGKILL'); } catch { /* Process may have exited. */ }
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
};
|
|
65
|
+
const abort = () => terminate(new RolloutWorkerError('日志准备已取消。', undefined, 'aborted'));
|
|
66
|
+
signal?.addEventListener('abort', abort, { once: true });
|
|
67
|
+
if (signal?.aborted) abort();
|
|
68
|
+
const deadline = setTimeout(() => terminate(new RolloutWorkerError('日志准备超时,原会话已保留。', undefined, 'timeout')), timeout);
|
|
69
|
+
child.on('error', cause => { error ??= cause; });
|
|
70
|
+
child.stdout.on('data', chunk => {
|
|
71
|
+
if (error) return;
|
|
72
|
+
size += chunk.length;
|
|
73
|
+
if (size > maxMessageBytes) {
|
|
74
|
+
terminate(new RolloutWorkerError('日志准备结果超出大小上限。'));
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
output.push(chunk);
|
|
78
|
+
if (output[0].length >= 3) ready = output[0].subarray(0, 3).toString() === 'R1\n';
|
|
79
|
+
else if (size >= 3) ready = Buffer.concat(output, size).subarray(0, 3).toString() === 'R1\n';
|
|
80
|
+
});
|
|
81
|
+
child.stdin.on('error', () => {});
|
|
82
|
+
let launchOk = true;
|
|
83
|
+
if (beforeRequest && !error) {
|
|
84
|
+
try {
|
|
85
|
+
launchOk = beforeRequest(child) !== false;
|
|
86
|
+
} catch (cause) {
|
|
87
|
+
error ??= cause;
|
|
88
|
+
launchOk = false;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
if (!launchOk) {
|
|
92
|
+
terminate(error ?? new Error('无法将日志准备进程加入隔离容器。'));
|
|
93
|
+
} else if (!error) {
|
|
94
|
+
stopWatch = watchChild?.(child, terminate);
|
|
95
|
+
child.stdin.end(request);
|
|
96
|
+
}
|
|
97
|
+
child.on('close', (code, exitSignal) => {
|
|
98
|
+
if (closed) return;
|
|
99
|
+
closed = true;
|
|
100
|
+
clearTimeout(deadline);
|
|
101
|
+
stopWatch?.();
|
|
102
|
+
signal?.removeEventListener('abort', abort);
|
|
103
|
+
try { onClose?.(); } catch { /* Ignore post-close cleanup errors. */ }
|
|
104
|
+
// Timed-out and canceled requests must not start a fallback process.
|
|
105
|
+
if (error instanceof RolloutWorkerError) return resolve({ error, ready: true });
|
|
106
|
+
if (error || code !== 0 || !ready) {
|
|
107
|
+
return resolve({ ready, error: new RolloutWorkerError(ready
|
|
108
|
+
? '日志准备进程达到资源上限或意外退出,原会话已保留。'
|
|
109
|
+
: '无法启动受保护的日志准备进程。', { cause: error, ...(exitSignal && { exitSignal }) }) });
|
|
110
|
+
}
|
|
111
|
+
try {
|
|
112
|
+
const result = JSON.parse(Buffer.concat(output, size).subarray(3).toString('utf8'));
|
|
113
|
+
if (result.ok !== true) {
|
|
114
|
+
const reason = typeof result.reason === 'string' && Object.hasOwn(userFacingReasons, result.reason)
|
|
115
|
+
? result.reason : undefined;
|
|
116
|
+
return resolve({ ready, error: new RolloutWorkerError(
|
|
117
|
+
reason === undefined ? result.message : userFacingReasons[reason], undefined, reason,
|
|
118
|
+
) });
|
|
119
|
+
}
|
|
120
|
+
resolve({ ready, value: result.value });
|
|
121
|
+
} catch (cause) {
|
|
122
|
+
resolve({ ready, error: new RolloutWorkerError('无法读取日志准备结果。', { cause }) });
|
|
123
|
+
}
|
|
124
|
+
});
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
async function runLinuxWorker(node, request, { signal, timeout }) {
|
|
129
|
+
await loadHostFlock();
|
|
130
|
+
const launchAt = Date.now();
|
|
131
|
+
const result = await startWorker('systemd-run', [
|
|
132
|
+
'--user', '--scope', '--quiet', '--collect', `--unit=dsh-message-revision-${randomUUID()}`,
|
|
133
|
+
'-p', 'MemoryMax=256M', '-p', 'MemorySwapMax=0', '--',
|
|
134
|
+
'prlimit', '--core=0', '--', ...node, entry, 'dsh-rollout-worker', 'cgroup',
|
|
135
|
+
], request, { signal, timeout });
|
|
136
|
+
if (result.ready) {
|
|
137
|
+
if (result.error) throw result.error;
|
|
138
|
+
return result.value;
|
|
139
|
+
}
|
|
140
|
+
const remaining = timeout - (Date.now() - launchAt);
|
|
141
|
+
if (remaining <= 0 || signal?.aborted) throw result.error;
|
|
142
|
+
// The V8 code range is reserved address space. A larger RLIMIT_AS is
|
|
143
|
+
// required to boot Node even with a small old generation.
|
|
144
|
+
const fallback = await startWorker('prlimit', [
|
|
145
|
+
'--as=1073741824', '--core=0', '--', ...node, '--jitless',
|
|
146
|
+
entry, 'dsh-rollout-worker', 'rlimit',
|
|
147
|
+
], request, { signal, timeout: remaining });
|
|
148
|
+
if (fallback.error) throw fallback.error;
|
|
149
|
+
return fallback.value;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
async function runWin32Worker(node, request, { signal, timeout }) {
|
|
153
|
+
const launchAt = Date.now();
|
|
154
|
+
let job = null;
|
|
155
|
+
try {
|
|
156
|
+
job = createWin32MemoryJob(win32JobMemoryBytes);
|
|
157
|
+
} catch {
|
|
158
|
+
job = null;
|
|
159
|
+
}
|
|
160
|
+
if (job) {
|
|
161
|
+
const result = await startWorker(node[0], [
|
|
162
|
+
...node.slice(1), entry, 'dsh-rollout-worker', 'win32-job',
|
|
163
|
+
], request, {
|
|
164
|
+
signal,
|
|
165
|
+
timeout,
|
|
166
|
+
detached: false,
|
|
167
|
+
windowsHide: true,
|
|
168
|
+
beforeRequest: child => child.pid !== undefined && job.assign(child.pid),
|
|
169
|
+
onTerminate: () => job.terminate(1),
|
|
170
|
+
onClose: () => job.close(),
|
|
171
|
+
});
|
|
172
|
+
if (result.ready) {
|
|
173
|
+
if (result.error) throw result.error;
|
|
174
|
+
return result.value;
|
|
175
|
+
}
|
|
176
|
+
const remaining = timeout - (Date.now() - launchAt);
|
|
177
|
+
if (remaining <= 0 || signal?.aborted) throw result.error;
|
|
178
|
+
const fallback = await startWorker(node[0], [
|
|
179
|
+
...node.slice(1), entry, 'dsh-rollout-worker', 'win32-watchdog',
|
|
180
|
+
], request, {
|
|
181
|
+
signal,
|
|
182
|
+
timeout: remaining,
|
|
183
|
+
detached: false,
|
|
184
|
+
windowsHide: true,
|
|
185
|
+
onTerminate: child => killWin32ProcessTree(child.pid),
|
|
186
|
+
});
|
|
187
|
+
if (fallback.error) throw fallback.error;
|
|
188
|
+
return fallback.value;
|
|
189
|
+
}
|
|
190
|
+
const fallback = await startWorker(node[0], [
|
|
191
|
+
...node.slice(1), entry, 'dsh-rollout-worker', 'win32-watchdog',
|
|
192
|
+
], request, {
|
|
193
|
+
signal,
|
|
194
|
+
timeout,
|
|
195
|
+
detached: false,
|
|
196
|
+
windowsHide: true,
|
|
197
|
+
onTerminate: child => killWin32ProcessTree(child.pid),
|
|
198
|
+
});
|
|
199
|
+
if (fallback.error) throw fallback.error;
|
|
200
|
+
return fallback.value;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
async function runDarwinWorker(node, request, { signal, timeout }) {
|
|
204
|
+
// Warm up host flock anchor before spawning so the worker inherits DSH_MESSAGE_REVISION_HOST_BASE.
|
|
205
|
+
await loadHostFlock();
|
|
206
|
+
const result = await startWorker(node[0], [
|
|
207
|
+
...node.slice(1), entry, 'dsh-rollout-worker', 'darwin-rlimit',
|
|
208
|
+
], request, {
|
|
209
|
+
signal,
|
|
210
|
+
timeout,
|
|
211
|
+
detached: true,
|
|
212
|
+
watchChild(child, terminate) {
|
|
213
|
+
let stopped = false;
|
|
214
|
+
let checking = false;
|
|
215
|
+
const timer = setInterval(async () => {
|
|
216
|
+
if (stopped || checking || !child.pid) return;
|
|
217
|
+
checking = true;
|
|
218
|
+
try {
|
|
219
|
+
const rss = await readDarwinProcessRssBytes(child.pid);
|
|
220
|
+
if (!stopped && rss !== undefined && rss > darwinRssLimitBytes) {
|
|
221
|
+
terminate(new RolloutWorkerError('日志准备进程达到资源上限或意外退出,原会话已保留。'));
|
|
222
|
+
}
|
|
223
|
+
} finally {
|
|
224
|
+
checking = false;
|
|
225
|
+
}
|
|
226
|
+
}, darwinWatchdogIntervalMs);
|
|
227
|
+
timer.unref();
|
|
228
|
+
return () => {
|
|
229
|
+
stopped = true;
|
|
230
|
+
clearInterval(timer);
|
|
231
|
+
};
|
|
232
|
+
},
|
|
233
|
+
});
|
|
234
|
+
if (result.error) throw result.error;
|
|
235
|
+
return result.value;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/** Process exactly one bounded preparation task per Host process. */
|
|
239
|
+
export async function runRolloutWorker(operation, input, { signal, timeout = defaultTimeout } = {}) {
|
|
240
|
+
if (globalThis[processKey]) throw new RolloutWorkerError('已有会话正在准备编辑,请稍后重试。', undefined, 'worker-busy');
|
|
241
|
+
if (signal?.aborted) throw new RolloutWorkerError('日志准备已取消。', undefined, 'aborted');
|
|
242
|
+
if (!isSupportedPlatform(process.platform)) {
|
|
243
|
+
throw new RolloutWorkerError('当前系统无法启动受内存约束的日志准备进程。');
|
|
244
|
+
}
|
|
245
|
+
if (!Number.isSafeInteger(timeout) || timeout <= 0 || timeout > defaultTimeout) {
|
|
246
|
+
throw new RolloutWorkerError('日志准备时限无效。');
|
|
247
|
+
}
|
|
248
|
+
const request = JSON.stringify({ operation, input });
|
|
249
|
+
if (Buffer.byteLength(request) > maxMessageBytes) throw new RolloutWorkerError('日志准备参数超出大小上限。');
|
|
250
|
+
globalThis[processKey] = true;
|
|
251
|
+
try {
|
|
252
|
+
const node = [process.execPath, '--max-old-space-size=128'];
|
|
253
|
+
if (process.platform === 'linux') return await runLinuxWorker(node, request, { signal, timeout });
|
|
254
|
+
if (process.platform === 'win32') return await runWin32Worker(node, request, { signal, timeout });
|
|
255
|
+
return await runDarwinWorker(node, request, { signal, timeout });
|
|
256
|
+
} finally {
|
|
257
|
+
globalThis[processKey] = false;
|
|
258
|
+
}
|
|
259
|
+
}
|