@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
package/src/platform.js
ADDED
|
@@ -0,0 +1,623 @@
|
|
|
1
|
+
import { execFile, spawn } from 'node:child_process';
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import { constants, realpathSync } from 'node:fs';
|
|
4
|
+
import { access, lstat, realpath, rename } from 'node:fs/promises';
|
|
5
|
+
import { createRequire } from 'node:module';
|
|
6
|
+
import { dirname, isAbsolute, join, relative, resolve, toNamespacedPath } from 'node:path';
|
|
7
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
8
|
+
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
9
|
+
|
|
10
|
+
export const SUPPORTED_PLATFORMS = Object.freeze(new Set(['linux', 'darwin', 'win32']));
|
|
11
|
+
export const JOB_OBJECT_LIMIT_PROCESS_MEMORY = 0x00000100;
|
|
12
|
+
export const JOB_OBJECT_LIMIT_JOB_MEMORY = 0x00000200;
|
|
13
|
+
export const JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x00002000;
|
|
14
|
+
|
|
15
|
+
const flockConflict = 73;
|
|
16
|
+
const moveReplaceExisting = 0x00000001;
|
|
17
|
+
const moveWriteThrough = 0x00000008;
|
|
18
|
+
const jobObjectExtendedLimitInfo = 9;
|
|
19
|
+
const processSetQuota = 0x0100;
|
|
20
|
+
const processTerminate = 0x0001;
|
|
21
|
+
const processQueryLimitedInformation = 0x1000;
|
|
22
|
+
const waitObject0 = 0;
|
|
23
|
+
const waitTimeout = 0x00000102;
|
|
24
|
+
const stillActive = 259;
|
|
25
|
+
const systemBootEnvironmentInfo = 90;
|
|
26
|
+
const errorFileNotFound = 2;
|
|
27
|
+
const errorPathNotFound = 3;
|
|
28
|
+
const errorAccessDenied = 5;
|
|
29
|
+
const errorNotSameDevice = 17;
|
|
30
|
+
const errorSharingViolation = 32;
|
|
31
|
+
const errorFileExists = 80;
|
|
32
|
+
const errorInvalidParameter = 87;
|
|
33
|
+
const errorInvalidName = 123;
|
|
34
|
+
const errorAlreadyExists = 183;
|
|
35
|
+
const transientMoveCodes = new Set(['EBUSY', 'EPERM', 'EACCES']);
|
|
36
|
+
const moveRetryDelays = [25, 50, 100, 200, 400];
|
|
37
|
+
|
|
38
|
+
let cachedHostBase;
|
|
39
|
+
let cachedFlockPromise;
|
|
40
|
+
let cachedFlockExecutablePromise;
|
|
41
|
+
let cachedKoffi;
|
|
42
|
+
let cachedWin32;
|
|
43
|
+
let cachedWin32BootId;
|
|
44
|
+
let cachedDarwinBoot;
|
|
45
|
+
|
|
46
|
+
export function isSupportedPlatform(platform = process.platform) {
|
|
47
|
+
return SUPPORTED_PLATFORMS.has(platform);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function isSamePath(left, right) {
|
|
51
|
+
if (typeof left !== 'string' || typeof right !== 'string') return false;
|
|
52
|
+
return process.platform === 'win32' ? left.toLowerCase() === right.toLowerCase() : left === right;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function pathKey(path) {
|
|
56
|
+
const normalized = resolve(path);
|
|
57
|
+
return process.platform === 'win32' ? normalized.toLowerCase() : normalized;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export async function isCanonicalPath(path) {
|
|
61
|
+
if (typeof path !== 'string' || path.length === 0) return false;
|
|
62
|
+
return isSamePath(await realpath(path), path);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function rolloutStorageRoot(path) {
|
|
66
|
+
return dirname(dirname(dirname(path)));
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Resolve only the configured Windows storage root, keeping the DSH log layout below it intact. */
|
|
70
|
+
export async function resolveRolloutPath(path) {
|
|
71
|
+
if (process.platform !== 'win32') return path;
|
|
72
|
+
if (!isAbsolute(path) || !isSamePath(resolve(path), path)) return undefined;
|
|
73
|
+
const actual = await realpath(path);
|
|
74
|
+
if (isSamePath(actual, path)) return path;
|
|
75
|
+
const session = dirname(path);
|
|
76
|
+
const project = dirname(session);
|
|
77
|
+
const root = rolloutStorageRoot(path);
|
|
78
|
+
const [physicalRoot, projectStat, sessionStat, fileStat] = await Promise.all([
|
|
79
|
+
realpath(root), lstat(project), lstat(session), lstat(path),
|
|
80
|
+
]);
|
|
81
|
+
if (!projectStat.isDirectory() || !sessionStat.isDirectory() || !fileStat.isFile()
|
|
82
|
+
|| !isSamePath(actual, join(physicalRoot, relative(root, path)))) return undefined;
|
|
83
|
+
return actual;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export function openReadOnlyFlags() {
|
|
87
|
+
return constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (process.platform === 'win32' ? 0 : (constants.O_NONBLOCK ?? 0));
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function candidateResolveAnchors() {
|
|
91
|
+
const anchors = [];
|
|
92
|
+
const seen = new Set();
|
|
93
|
+
const add = value => {
|
|
94
|
+
if (typeof value !== 'string' || value.length === 0 || seen.has(value)) return;
|
|
95
|
+
seen.add(value);
|
|
96
|
+
anchors.push(value);
|
|
97
|
+
};
|
|
98
|
+
add(cachedHostBase);
|
|
99
|
+
if (process.env.DSH_MESSAGE_REVISION_HOST_BASE) add(process.env.DSH_MESSAGE_REVISION_HOST_BASE);
|
|
100
|
+
if (process.env.DSH_HOST_ROOT) add(join(process.env.DSH_HOST_ROOT, 'package.json'));
|
|
101
|
+
if (typeof process.resourcesPath === 'string' && process.resourcesPath.length > 0) {
|
|
102
|
+
add(join(process.resourcesPath, 'app.asar', 'dsh', 'package.json'));
|
|
103
|
+
add(join(process.resourcesPath, 'app', 'dsh', 'package.json'));
|
|
104
|
+
}
|
|
105
|
+
if (typeof process.argv[1] === 'string' && process.argv[1].length > 0) {
|
|
106
|
+
const argvPaths = [resolve(process.argv[1])];
|
|
107
|
+
try {
|
|
108
|
+
const realArgv = realpathSync(process.argv[1]);
|
|
109
|
+
if (!isSamePath(realArgv, argvPaths[0])) argvPaths.push(realArgv);
|
|
110
|
+
} catch { /* Non-filesystem argv[1] such as -e or virtual entry. */ }
|
|
111
|
+
for (const startPath of argvPaths) {
|
|
112
|
+
let current = startPath;
|
|
113
|
+
add(current);
|
|
114
|
+
for (let depth = 0; depth < 6; depth++) {
|
|
115
|
+
const parent = dirname(current);
|
|
116
|
+
if (parent === current) break;
|
|
117
|
+
current = parent;
|
|
118
|
+
add(join(current, 'package.json'));
|
|
119
|
+
add(join(current, 'dsh', 'package.json'));
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
add(fileURLToPath(import.meta.url));
|
|
124
|
+
return anchors;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function expandHostAnchors(anchor) {
|
|
128
|
+
const expanded = [];
|
|
129
|
+
const seen = new Set();
|
|
130
|
+
const queue = [anchor];
|
|
131
|
+
const hops = ['@deepseek-ai/dsh-session-persistence-jsonl/package.json', '@deepseek-ai/dsh-base/package.json'];
|
|
132
|
+
while (queue.length > 0) {
|
|
133
|
+
const current = queue.shift();
|
|
134
|
+
if (!current || seen.has(current)) continue;
|
|
135
|
+
seen.add(current);
|
|
136
|
+
expanded.push(current);
|
|
137
|
+
let req;
|
|
138
|
+
try { req = createRequire(current); } catch { continue; }
|
|
139
|
+
for (const dep of hops) {
|
|
140
|
+
try {
|
|
141
|
+
const next = req.resolve(dep);
|
|
142
|
+
if (!seen.has(next)) queue.push(next);
|
|
143
|
+
} catch { /* Dependency not reachable from this anchor. */ }
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
return expanded;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
export function hostResolveBase() {
|
|
150
|
+
return cachedHostBase ?? process.env.DSH_MESSAGE_REVISION_HOST_BASE;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
export function workerEnv(extra = {}) {
|
|
154
|
+
const env = { ...process.env, ...extra };
|
|
155
|
+
delete env.NODE_OPTIONS;
|
|
156
|
+
if (process.versions.electron) env.ELECTRON_RUN_AS_NODE = '1';
|
|
157
|
+
const base = hostResolveBase();
|
|
158
|
+
if (base) env.DSH_MESSAGE_REVISION_HOST_BASE = base;
|
|
159
|
+
return env;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
export function loadHostFlock() {
|
|
163
|
+
if (cachedFlockPromise !== undefined) return cachedFlockPromise;
|
|
164
|
+
cachedFlockPromise = (async () => {
|
|
165
|
+
for (const rootAnchor of candidateResolveAnchors()) {
|
|
166
|
+
for (const anchor of expandHostAnchors(rootAnchor)) {
|
|
167
|
+
try {
|
|
168
|
+
const resolved = createRequire(anchor).resolve('@deepseek-ai/node-addon-system/flock');
|
|
169
|
+
const mod = await import(pathToFileURL(resolved).href);
|
|
170
|
+
if (typeof mod?.tryLockExclusive === 'function') {
|
|
171
|
+
cachedHostBase ??= anchor;
|
|
172
|
+
return mod.tryLockExclusive;
|
|
173
|
+
}
|
|
174
|
+
} catch { /* Try the next host anchor. */ }
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
return null;
|
|
178
|
+
})();
|
|
179
|
+
return cachedFlockPromise;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
export function loadHostKoffi() {
|
|
183
|
+
if (cachedKoffi !== undefined) return cachedKoffi;
|
|
184
|
+
for (const rootAnchor of candidateResolveAnchors()) {
|
|
185
|
+
for (const anchor of expandHostAnchors(rootAnchor)) {
|
|
186
|
+
try {
|
|
187
|
+
const req = createRequire(anchor);
|
|
188
|
+
const resolved = req.resolve('koffi');
|
|
189
|
+
const mod = req(resolved);
|
|
190
|
+
const koffi = mod?.default ?? mod;
|
|
191
|
+
if (typeof koffi?.load === 'function') {
|
|
192
|
+
cachedHostBase ??= anchor;
|
|
193
|
+
cachedKoffi = koffi;
|
|
194
|
+
return koffi;
|
|
195
|
+
}
|
|
196
|
+
} catch { /* Try the next host anchor. */ }
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
cachedKoffi = null;
|
|
200
|
+
return null;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
async function flockExecutable() {
|
|
204
|
+
cachedFlockExecutablePromise ??= (async () => {
|
|
205
|
+
for (const path of ['/usr/bin/flock', '/bin/flock']) {
|
|
206
|
+
try {
|
|
207
|
+
await access(path, constants.X_OK);
|
|
208
|
+
return path;
|
|
209
|
+
} catch (error) {
|
|
210
|
+
if (error.code !== 'ENOENT' && error.code !== 'EACCES') throw error;
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
return null;
|
|
214
|
+
})();
|
|
215
|
+
return cachedFlockExecutablePromise;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
function tryLinuxFlockCli(executable, descriptor) {
|
|
219
|
+
return new Promise((complete, fail) => {
|
|
220
|
+
// Linux flock is attached to the shared open file description. The helper
|
|
221
|
+
// inherits fd 3. Host ownership continues until its FileHandle closes.
|
|
222
|
+
const child = spawn(executable, ['--exclusive', '--nonblock', '--conflict-exit-code', String(flockConflict), '3'], {
|
|
223
|
+
stdio: ['ignore', 'ignore', 'ignore', descriptor],
|
|
224
|
+
});
|
|
225
|
+
let failure;
|
|
226
|
+
const timeout = setTimeout(() => child.kill('SIGKILL'), 5_000);
|
|
227
|
+
timeout.unref();
|
|
228
|
+
child.once('error', error => { failure = error; });
|
|
229
|
+
child.once('close', (code, signal) => {
|
|
230
|
+
clearTimeout(timeout);
|
|
231
|
+
if (failure) fail(failure);
|
|
232
|
+
else if (code === 0) complete(true);
|
|
233
|
+
else if (code === flockConflict) complete(false);
|
|
234
|
+
else fail(new Error(`无法取得 DSH 会话写锁(flock ${signal ?? code})。`));
|
|
235
|
+
});
|
|
236
|
+
});
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/** Acquire a non-blocking POSIX exclusive flock via DSH's native addon (or Linux /usr/bin/flock fallback). */
|
|
240
|
+
export async function tryPosixExclusiveLock(descriptor) {
|
|
241
|
+
const nativeFlock = await loadHostFlock();
|
|
242
|
+
if (nativeFlock) {
|
|
243
|
+
try {
|
|
244
|
+
await nativeFlock(descriptor);
|
|
245
|
+
return true;
|
|
246
|
+
} catch (error) {
|
|
247
|
+
if (error?.code === 'EAGAIN' || error?.code === 'EWOULDBLOCK') return false;
|
|
248
|
+
const isFlockSyscallError = error?.code === 'EBADF' || error?.code === 'EINVAL' || error?.code === 'EINTR';
|
|
249
|
+
if (process.platform === 'linux' && !isFlockSyscallError) {
|
|
250
|
+
// The addon loads its native binary lazily on first call; fall back to
|
|
251
|
+
// system flock on Linux if the prebuilt binary is unavailable.
|
|
252
|
+
cachedFlockPromise = Promise.resolve(null);
|
|
253
|
+
} else {
|
|
254
|
+
throw error;
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
if (process.platform === 'linux') {
|
|
259
|
+
const executable = await flockExecutable();
|
|
260
|
+
if (executable) return tryLinuxFlockCli(executable, descriptor);
|
|
261
|
+
throw new Error('未找到系统 flock,无法安全获取 DSH 会话写锁。');
|
|
262
|
+
}
|
|
263
|
+
throw new Error('未找到 DSH 原生 flock 模块,无法安全获取会话写锁。');
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
function win32Errno(code) {
|
|
267
|
+
switch (code) {
|
|
268
|
+
case errorFileNotFound:
|
|
269
|
+
case errorPathNotFound: return 'ENOENT';
|
|
270
|
+
case errorAccessDenied: return 'EACCES';
|
|
271
|
+
case errorNotSameDevice: return 'EXDEV';
|
|
272
|
+
case errorSharingViolation: return 'EBUSY';
|
|
273
|
+
case errorFileExists:
|
|
274
|
+
case errorAlreadyExists: return 'EEXIST';
|
|
275
|
+
case errorInvalidParameter:
|
|
276
|
+
case errorInvalidName: return 'EINVAL';
|
|
277
|
+
default: return 'EIO';
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
function win32Error(syscall, win32Code, path, dest) {
|
|
282
|
+
const code = win32Errno(win32Code);
|
|
283
|
+
const error = new Error(`${syscall} ${code} (Win32 ${win32Code}): ${path}${dest ? ` -> ${dest}` : ''}`);
|
|
284
|
+
error.code = code;
|
|
285
|
+
error.errno = win32Code;
|
|
286
|
+
error.syscall = syscall;
|
|
287
|
+
error.path = path;
|
|
288
|
+
if (dest !== undefined) error.dest = dest;
|
|
289
|
+
error.win32Code = win32Code;
|
|
290
|
+
return error;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
function isNullHandle(handle) {
|
|
294
|
+
return handle === 0 || handle === 0n || handle === null || handle === undefined;
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
function win32Bindings() {
|
|
298
|
+
if (cachedWin32 !== undefined) return cachedWin32;
|
|
299
|
+
const koffi = loadHostKoffi();
|
|
300
|
+
if (!koffi) {
|
|
301
|
+
cachedWin32 = null;
|
|
302
|
+
return null;
|
|
303
|
+
}
|
|
304
|
+
const kernel32 = koffi.load('kernel32.dll');
|
|
305
|
+
const basicLimitStruct = koffi.struct({
|
|
306
|
+
PerProcessUserTimeLimit: 'int64',
|
|
307
|
+
PerJobUserTimeLimit: 'int64',
|
|
308
|
+
LimitFlags: 'uint32',
|
|
309
|
+
MinimumWorkingSetSize: 'uintptr',
|
|
310
|
+
MaximumWorkingSetSize: 'uintptr',
|
|
311
|
+
ActiveProcessLimit: 'uint32',
|
|
312
|
+
Affinity: 'uintptr',
|
|
313
|
+
PriorityClass: 'uint32',
|
|
314
|
+
SchedulingClass: 'uint32',
|
|
315
|
+
});
|
|
316
|
+
const ioCountersStruct = koffi.struct({
|
|
317
|
+
ReadOperationCount: 'uint64',
|
|
318
|
+
WriteOperationCount: 'uint64',
|
|
319
|
+
OtherOperationCount: 'uint64',
|
|
320
|
+
ReadTransferCount: 'uint64',
|
|
321
|
+
WriteTransferCount: 'uint64',
|
|
322
|
+
OtherTransferCount: 'uint64',
|
|
323
|
+
});
|
|
324
|
+
const extendedLimitStruct = koffi.struct({
|
|
325
|
+
BasicLimitInformation: basicLimitStruct,
|
|
326
|
+
IoInfo: ioCountersStruct,
|
|
327
|
+
ProcessMemoryLimit: 'uintptr',
|
|
328
|
+
JobMemoryLimit: 'uintptr',
|
|
329
|
+
PeakProcessMemoryUsed: 'uintptr',
|
|
330
|
+
PeakJobMemoryUsed: 'uintptr',
|
|
331
|
+
});
|
|
332
|
+
cachedWin32 = {
|
|
333
|
+
koffi,
|
|
334
|
+
extendedLimitStruct,
|
|
335
|
+
extendedLimitSize: koffi.sizeof(extendedLimitStruct),
|
|
336
|
+
moveFileExW: kernel32.func('__stdcall', 'MoveFileExW', 'int', ['str16', 'str16', 'uint']),
|
|
337
|
+
createSemaphoreW: kernel32.func('__stdcall', 'CreateSemaphoreW', 'intptr', ['void*', 'int', 'int', 'str16']),
|
|
338
|
+
waitForSingleObject: kernel32.func('__stdcall', 'WaitForSingleObject', 'uint', ['intptr', 'uint']),
|
|
339
|
+
releaseSemaphore: kernel32.func('__stdcall', 'ReleaseSemaphore', 'int', ['intptr', 'int', 'void*']),
|
|
340
|
+
closeHandle: kernel32.func('__stdcall', 'CloseHandle', 'int', ['intptr']),
|
|
341
|
+
getLastError: kernel32.func('__stdcall', 'GetLastError', 'uint', []),
|
|
342
|
+
createJobObjectW: kernel32.func('__stdcall', 'CreateJobObjectW', 'intptr', ['void*', 'str16']),
|
|
343
|
+
setInformationJobObject: kernel32.func('__stdcall', 'SetInformationJobObject', 'int', ['intptr', 'int', 'void*', 'uint']),
|
|
344
|
+
queryInformationJobObject: kernel32.func('__stdcall', 'QueryInformationJobObject', 'int', ['intptr', 'int', 'void*', 'uint', 'void*']),
|
|
345
|
+
assignProcessToJobObject: kernel32.func('__stdcall', 'AssignProcessToJobObject', 'int', ['intptr', 'intptr']),
|
|
346
|
+
terminateJobObject: kernel32.func('__stdcall', 'TerminateJobObject', 'int', ['intptr', 'uint']),
|
|
347
|
+
openProcess: kernel32.func('__stdcall', 'OpenProcess', 'intptr', ['uint', 'int', 'uint']),
|
|
348
|
+
getProcessTimes: kernel32.func('__stdcall', 'GetProcessTimes', 'int', ['intptr', 'void*', 'void*', 'void*', 'void*']),
|
|
349
|
+
getExitCodeProcess: kernel32.func('__stdcall', 'GetExitCodeProcess', 'int', ['intptr', 'void*']),
|
|
350
|
+
ntQuerySystemInformation: (() => {
|
|
351
|
+
try {
|
|
352
|
+
return koffi.load('ntdll.dll').func('__stdcall', 'NtQuerySystemInformation', 'int', ['uint', 'void*', 'uint', 'void*']);
|
|
353
|
+
} catch {
|
|
354
|
+
return null;
|
|
355
|
+
}
|
|
356
|
+
})(),
|
|
357
|
+
};
|
|
358
|
+
return cachedWin32;
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
function requireWin32() {
|
|
362
|
+
const api = win32Bindings();
|
|
363
|
+
if (!api) throw new Error('未找到 DSH 内置 koffi 模块,无法调用 Windows 原生锁与进程接口。');
|
|
364
|
+
return api;
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
/** Exact Win32 semaphore name used by DSH SessionWriteLease (dsh-session-persistence-jsonl/src/win32.ts). */
|
|
368
|
+
export function dshSessionLockName(lockPath) {
|
|
369
|
+
return `Local\\dsh-session-lock-${createHash('sha256').update(resolve(lockPath).toLowerCase()).digest('hex')}`;
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
export function candidateLockName(versionDirectory, slot) {
|
|
373
|
+
return `Local\\dsh-msgrev-cand-${createHash('sha256').update(`${resolve(versionDirectory).toLowerCase()}:${slot}`).digest('hex')}`;
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
export function acquireWin32Semaphore(name, path = name) {
|
|
377
|
+
const api = requireWin32();
|
|
378
|
+
const handle = api.createSemaphoreW(null, 1, 1, name);
|
|
379
|
+
if (isNullHandle(handle)) throw win32Error('CreateSemaphoreW', api.getLastError(), path, name);
|
|
380
|
+
const wait = api.waitForSingleObject(handle, 0);
|
|
381
|
+
if (wait === waitObject0) return { busy: false, handle };
|
|
382
|
+
api.closeHandle(handle);
|
|
383
|
+
if (wait === waitTimeout) return { busy: true };
|
|
384
|
+
throw win32Error('WaitForSingleObject', api.getLastError(), path, name);
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
export function releaseWin32Semaphore(handle) {
|
|
388
|
+
const api = requireWin32();
|
|
389
|
+
const released = api.releaseSemaphore(handle, 1, null);
|
|
390
|
+
const releaseError = released === 0 ? api.getLastError() : 0;
|
|
391
|
+
const closed = api.closeHandle(handle);
|
|
392
|
+
const closeError = closed === 0 ? api.getLastError() : 0;
|
|
393
|
+
if (released === 0) throw win32Error('ReleaseSemaphore', releaseError, `handle:${handle}`);
|
|
394
|
+
if (closed === 0) throw win32Error('CloseHandle', closeError, `handle:${handle}`);
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
async function moveWithRetry(from, to, flags) {
|
|
398
|
+
if (process.platform !== 'win32') {
|
|
399
|
+
await rename(from, to);
|
|
400
|
+
return;
|
|
401
|
+
}
|
|
402
|
+
const api = win32Bindings();
|
|
403
|
+
const source = toNamespacedPath(from);
|
|
404
|
+
const destination = toNamespacedPath(to);
|
|
405
|
+
for (let attempt = 0; ; attempt++) {
|
|
406
|
+
try {
|
|
407
|
+
if (api) {
|
|
408
|
+
const ok = api.moveFileExW(source, destination, flags);
|
|
409
|
+
if (ok === 0) throw win32Error('MoveFileExW', api.getLastError(), from, to);
|
|
410
|
+
} else {
|
|
411
|
+
if ((flags & moveReplaceExisting) === 0) {
|
|
412
|
+
const exists = await lstat(to).then(() => true, error => error.code === 'ENOENT' ? false : Promise.reject(error));
|
|
413
|
+
if (exists) {
|
|
414
|
+
const error = new Error(`EEXIST: destination already exists, rename '${from}' -> '${to}'`);
|
|
415
|
+
error.code = 'EEXIST';
|
|
416
|
+
throw error;
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
await rename(from, to);
|
|
420
|
+
}
|
|
421
|
+
return;
|
|
422
|
+
} catch (error) {
|
|
423
|
+
if (!transientMoveCodes.has(error?.code) || attempt >= moveRetryDelays.length) throw error;
|
|
424
|
+
await delay(moveRetryDelays[attempt]);
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
export function replaceFileDurable(from, to) {
|
|
430
|
+
return moveWithRetry(from, to, moveReplaceExisting | moveWriteThrough);
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
export function moveEntryDurable(from, to) {
|
|
434
|
+
return moveWithRetry(from, to, moveWriteThrough);
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
export function createWin32MemoryJob(limitBytes) {
|
|
438
|
+
const api = win32Bindings();
|
|
439
|
+
if (!api) return null;
|
|
440
|
+
const handle = api.createJobObjectW(null, null);
|
|
441
|
+
if (isNullHandle(handle)) throw win32Error('CreateJobObjectW', api.getLastError(), 'job');
|
|
442
|
+
const flags = JOB_OBJECT_LIMIT_PROCESS_MEMORY | JOB_OBJECT_LIMIT_JOB_MEMORY | JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
|
|
443
|
+
const buffer = Buffer.alloc(api.extendedLimitSize);
|
|
444
|
+
api.koffi.encode(buffer, api.extendedLimitStruct, {
|
|
445
|
+
BasicLimitInformation: {
|
|
446
|
+
PerProcessUserTimeLimit: 0,
|
|
447
|
+
PerJobUserTimeLimit: 0,
|
|
448
|
+
LimitFlags: flags,
|
|
449
|
+
MinimumWorkingSetSize: 0,
|
|
450
|
+
MaximumWorkingSetSize: 0,
|
|
451
|
+
ActiveProcessLimit: 0,
|
|
452
|
+
Affinity: 0,
|
|
453
|
+
PriorityClass: 0,
|
|
454
|
+
SchedulingClass: 0,
|
|
455
|
+
},
|
|
456
|
+
IoInfo: {
|
|
457
|
+
ReadOperationCount: 0,
|
|
458
|
+
WriteOperationCount: 0,
|
|
459
|
+
OtherOperationCount: 0,
|
|
460
|
+
ReadTransferCount: 0,
|
|
461
|
+
WriteTransferCount: 0,
|
|
462
|
+
OtherTransferCount: 0,
|
|
463
|
+
},
|
|
464
|
+
ProcessMemoryLimit: limitBytes,
|
|
465
|
+
JobMemoryLimit: limitBytes,
|
|
466
|
+
PeakProcessMemoryUsed: 0,
|
|
467
|
+
PeakJobMemoryUsed: 0,
|
|
468
|
+
});
|
|
469
|
+
if (api.setInformationJobObject(handle, jobObjectExtendedLimitInfo, buffer, buffer.length) === 0) {
|
|
470
|
+
const code = api.getLastError();
|
|
471
|
+
api.closeHandle(handle);
|
|
472
|
+
throw win32Error('SetInformationJobObject', code, 'job');
|
|
473
|
+
}
|
|
474
|
+
let closed = false;
|
|
475
|
+
return {
|
|
476
|
+
assign(pid) {
|
|
477
|
+
if (closed || !Number.isSafeInteger(pid) || pid <= 0) return false;
|
|
478
|
+
const processHandle = api.openProcess(processSetQuota | processTerminate, 0, pid);
|
|
479
|
+
if (isNullHandle(processHandle)) return false;
|
|
480
|
+
try {
|
|
481
|
+
return api.assignProcessToJobObject(handle, processHandle) !== 0;
|
|
482
|
+
} finally {
|
|
483
|
+
api.closeHandle(processHandle);
|
|
484
|
+
}
|
|
485
|
+
},
|
|
486
|
+
terminate(exitCode = 1) {
|
|
487
|
+
if (closed) return;
|
|
488
|
+
api.terminateJobObject(handle, exitCode);
|
|
489
|
+
},
|
|
490
|
+
close() {
|
|
491
|
+
if (closed) return;
|
|
492
|
+
closed = true;
|
|
493
|
+
api.closeHandle(handle);
|
|
494
|
+
},
|
|
495
|
+
};
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
export function queryCurrentWin32JobLimits() {
|
|
499
|
+
const api = win32Bindings();
|
|
500
|
+
if (!api) return null;
|
|
501
|
+
const buffer = Buffer.alloc(api.extendedLimitSize);
|
|
502
|
+
if (api.queryInformationJobObject(0, jobObjectExtendedLimitInfo, buffer, buffer.length, null) === 0) return null;
|
|
503
|
+
const decoded = api.koffi.decode(buffer, api.extendedLimitStruct);
|
|
504
|
+
return {
|
|
505
|
+
flags: Number(decoded.BasicLimitInformation.LimitFlags),
|
|
506
|
+
processMemoryLimit: Number(decoded.ProcessMemoryLimit),
|
|
507
|
+
jobMemoryLimit: Number(decoded.JobMemoryLimit),
|
|
508
|
+
};
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
export function readWin32BootId() {
|
|
512
|
+
if (process.platform !== 'win32') return undefined;
|
|
513
|
+
if (cachedWin32BootId) return cachedWin32BootId;
|
|
514
|
+
const api = win32Bindings();
|
|
515
|
+
if (!api?.ntQuerySystemInformation) return undefined;
|
|
516
|
+
const buffer = Buffer.alloc(64);
|
|
517
|
+
const returned = Buffer.alloc(4);
|
|
518
|
+
if (api.ntQuerySystemInformation(systemBootEnvironmentInfo, buffer, buffer.length, returned) !== 0) return undefined;
|
|
519
|
+
if (returned.readUInt32LE(0) < 16) return undefined;
|
|
520
|
+
const id = buffer.subarray(0, 16).toString('hex');
|
|
521
|
+
if (/^0+$/u.test(id)) return undefined;
|
|
522
|
+
cachedWin32BootId = id;
|
|
523
|
+
return id;
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
export function readWin32ProcessCreationTime(pid) {
|
|
527
|
+
if (process.platform !== 'win32') return undefined;
|
|
528
|
+
const api = win32Bindings();
|
|
529
|
+
if (!api || !Number.isSafeInteger(pid) || pid <= 0) return undefined;
|
|
530
|
+
const handle = api.openProcess(processQueryLimitedInformation, 0, pid);
|
|
531
|
+
if (isNullHandle(handle)) {
|
|
532
|
+
const code = api.getLastError();
|
|
533
|
+
if (code === errorInvalidParameter) return null;
|
|
534
|
+
if (code === errorAccessDenied) throw win32Error('OpenProcess', code, `pid:${pid}`);
|
|
535
|
+
return undefined;
|
|
536
|
+
}
|
|
537
|
+
try {
|
|
538
|
+
const exitCode = Buffer.alloc(4);
|
|
539
|
+
if (api.getExitCodeProcess(handle, exitCode) === 0) return undefined;
|
|
540
|
+
if (exitCode.readUInt32LE(0) !== stillActive) return null;
|
|
541
|
+
const created = Buffer.alloc(8);
|
|
542
|
+
const exited = Buffer.alloc(8);
|
|
543
|
+
const kernel = Buffer.alloc(8);
|
|
544
|
+
const user = Buffer.alloc(8);
|
|
545
|
+
if (api.getProcessTimes(handle, created, exited, kernel, user) === 0) return undefined;
|
|
546
|
+
return created.readBigUInt64LE(0).toString();
|
|
547
|
+
} finally {
|
|
548
|
+
api.closeHandle(handle);
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
export function killWin32ProcessTree(pid) {
|
|
553
|
+
if (process.platform !== 'win32' || !Number.isSafeInteger(pid) || pid <= 0) return;
|
|
554
|
+
try {
|
|
555
|
+
const killer = spawn('taskkill', ['/PID', String(pid), '/T', '/F'], {
|
|
556
|
+
stdio: 'ignore',
|
|
557
|
+
windowsHide: true,
|
|
558
|
+
});
|
|
559
|
+
killer.unref();
|
|
560
|
+
killer.on('error', () => {});
|
|
561
|
+
} catch { /* Best-effort process tree termination. */ }
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
function execText(file, args, env) {
|
|
565
|
+
return new Promise((complete, fail) => {
|
|
566
|
+
execFile(file, args, { encoding: 'utf8', timeout: 5_000, env }, (error, stdout, stderr) => {
|
|
567
|
+
if (error) {
|
|
568
|
+
error.stderr = stderr;
|
|
569
|
+
fail(error);
|
|
570
|
+
} else {
|
|
571
|
+
complete(stdout);
|
|
572
|
+
}
|
|
573
|
+
});
|
|
574
|
+
});
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
export async function readDarwinProcessScope() {
|
|
578
|
+
if (process.platform !== 'darwin') return undefined;
|
|
579
|
+
if (cachedDarwinBoot) return cachedDarwinBoot;
|
|
580
|
+
try {
|
|
581
|
+
const uuid = (await execText('/usr/sbin/sysctl', ['-n', 'kern.bootsessionuuid'])).trim();
|
|
582
|
+
if (uuid.length === 0) return undefined;
|
|
583
|
+
cachedDarwinBoot = { darwinBootId: uuid };
|
|
584
|
+
return cachedDarwinBoot;
|
|
585
|
+
} catch {
|
|
586
|
+
return undefined;
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
export async function readDarwinProcessStart(pid) {
|
|
591
|
+
if (process.platform !== 'darwin' || !Number.isSafeInteger(pid) || pid <= 0) return undefined;
|
|
592
|
+
try {
|
|
593
|
+
process.kill(pid, 0);
|
|
594
|
+
} catch (error) {
|
|
595
|
+
if (error.code === 'ESRCH') return null;
|
|
596
|
+
if (error.code !== 'EPERM') throw error;
|
|
597
|
+
}
|
|
598
|
+
try {
|
|
599
|
+
const output = await execText('/bin/ps', ['-o', 'lstart=', '-p', String(pid)], {
|
|
600
|
+
...process.env,
|
|
601
|
+
LC_ALL: 'C',
|
|
602
|
+
TZ: 'UTC',
|
|
603
|
+
});
|
|
604
|
+
const text = output.trim();
|
|
605
|
+
return text.length > 0 ? text : null;
|
|
606
|
+
} catch (error) {
|
|
607
|
+
if (error.code === 1 && !String(error.stderr ?? '').trim()) return null;
|
|
608
|
+
throw error;
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
export async function readDarwinProcessRssBytes(pid) {
|
|
613
|
+
if (process.platform !== 'darwin' || !Number.isSafeInteger(pid) || pid <= 0) return undefined;
|
|
614
|
+
try {
|
|
615
|
+
const output = await execText('/bin/ps', ['-o', 'rss=', '-p', String(pid)]);
|
|
616
|
+
const trimmed = output.trim();
|
|
617
|
+
if (trimmed.length === 0) return undefined;
|
|
618
|
+
const kib = Number(trimmed);
|
|
619
|
+
return Number.isSafeInteger(kib) && kib >= 0 ? kib * 1024 : undefined;
|
|
620
|
+
} catch {
|
|
621
|
+
return undefined;
|
|
622
|
+
}
|
|
623
|
+
}
|