@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.
@@ -0,0 +1,143 @@
1
+ import { constants } from 'node:fs';
2
+ import { lstat, open, realpath } from 'node:fs/promises';
3
+ import { basename, dirname, isAbsolute, join, resolve } from 'node:path';
4
+ import {
5
+ acquireWin32Semaphore, dshSessionLockName, isCanonicalPath, isSamePath, isSupportedPlatform,
6
+ releaseWin32Semaphore, tryPosixExclusiveLock,
7
+ } from './platform.js';
8
+
9
+ export const MAX_NATIVE_LEASES = 128;
10
+ const reservationsKey = Symbol.for('dsh-message-revision.native-leases');
11
+ const slots = globalThis[reservationsKey] ??= { count: 0 };
12
+ const lockName = 'session.lock';
13
+ const logName = /^session\.v[34]\.jsonl(?:\.zstd)?$/u;
14
+
15
+ function validate(condition, message) {
16
+ if (!condition) throw new Error(message);
17
+ }
18
+
19
+ function sameInode(first, second) {
20
+ return first !== undefined && second !== undefined && first.dev === second.dev && first.ino === second.ino;
21
+ }
22
+
23
+ async function inodeAt(path) {
24
+ try {
25
+ return await lstat(path, { bigint: true });
26
+ } catch (error) {
27
+ if (error.code === 'ENOENT') return undefined;
28
+ throw error;
29
+ }
30
+ }
31
+
32
+ function alreadyOwned() {
33
+ const error = new Error('会话写锁正被占用,请关闭相关会话后重试。');
34
+ error.name = 'SessionAlreadyOwnedError';
35
+ return error;
36
+ }
37
+
38
+ /** Acquire the same kernel lease DSH rc.5 uses for a materialized rollout on Linux, macOS, and Windows. */
39
+ export async function acquireNativeLease(rolloutPath, dshPath = rolloutPath) {
40
+ validate(isSupportedPlatform(process.platform), '当前系统不支持轻量获取 DSH 会话写锁。');
41
+ validate(typeof rolloutPath === 'string' && isAbsolute(rolloutPath) && isSamePath(resolve(rolloutPath), rolloutPath)
42
+ && logName.test(basename(rolloutPath)), '会话日志路径异常。');
43
+ validate(slots.count < MAX_NATIVE_LEASES, '本次编辑涉及的会话过多,无法安全获取写锁。');
44
+ slots.count++;
45
+
46
+ const directory = dirname(rolloutPath);
47
+ const lockPath = join(directory, lockName);
48
+ let acquired;
49
+ try {
50
+ const original = await inodeAt(rolloutPath);
51
+ validate(original?.isFile() && await isCanonicalPath(rolloutPath), '会话日志路径异常。');
52
+
53
+ if (process.platform === 'win32') {
54
+ const dirIdentity = await inodeAt(directory);
55
+ const dshDirectory = dirname(dshPath);
56
+ const lockPaths = [join(dshDirectory, lockName)];
57
+ // DSH hashes its configured path. Also exclude writers using the target directly.
58
+ if (!isSamePath(lockPaths[0], lockPath)) lockPaths.push(lockPath);
59
+ async function sameDirectory() {
60
+ return sameInode(await inodeAt(directory), dirIdentity) && await isCanonicalPath(directory)
61
+ && (lockPaths.length === 1 || isSamePath(await realpath(dshDirectory), directory));
62
+ }
63
+ validate(dirIdentity?.isDirectory() && await sameDirectory(), '会话目录已变化。');
64
+ const held = [];
65
+ function releaseAll() {
66
+ let failure;
67
+ for (const handle of held.reverse()) {
68
+ try { releaseWin32Semaphore(handle); } catch (error) { failure ??= error; }
69
+ }
70
+ if (failure) throw failure;
71
+ }
72
+ try {
73
+ for (const path of lockPaths) {
74
+ const semaphore = acquireWin32Semaphore(dshSessionLockName(path), path);
75
+ if (semaphore.busy) throw alreadyOwned();
76
+ held.push(semaphore.handle);
77
+ }
78
+ validate(await sameDirectory(), '会话目录已变化。');
79
+ validate(sameInode(await inodeAt(rolloutPath), original), '会话日志文件已变化。');
80
+ let release;
81
+ acquired = {
82
+ async assertHeld() {
83
+ validate(!release && await sameDirectory(), '会话写锁已失效。');
84
+ },
85
+ close() {
86
+ return release ??= Promise.resolve().then(releaseAll).finally(() => { slots.count--; });
87
+ },
88
+ };
89
+ return acquired;
90
+ } finally {
91
+ if (!acquired) releaseAll();
92
+ }
93
+ }
94
+
95
+ const dir = await open(directory, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
96
+ try {
97
+ const dirIdentity = await dir.stat({ bigint: true });
98
+ validate(sameInode(await inodeAt(directory), dirIdentity)
99
+ && await isCanonicalPath(directory), '会话目录已变化。');
100
+ const openPath = process.platform === 'linux' ? `/proc/self/fd/${dir.fd}/${lockName}` : lockPath;
101
+ for (let attempt = 0; attempt < 3; attempt++) {
102
+ const handle = await open(openPath,
103
+ constants.O_WRONLY | constants.O_CREAT | constants.O_NONBLOCK | constants.O_NOFOLLOW, 0o600);
104
+ try {
105
+ const identity = await handle.stat({ bigint: true });
106
+ if (identity.isFile() && identity.nlink === 0n) continue;
107
+ validate(identity.isFile() && identity.nlink === 1n, '会话写锁文件异常。');
108
+ if (!await tryPosixExclusiveLock(handle.fd)) throw alreadyOwned();
109
+ validate(sameInode(await inodeAt(directory), dirIdentity)
110
+ && await isCanonicalPath(directory), '会话目录已变化。');
111
+ validate(sameInode(await inodeAt(rolloutPath), original), '会话日志文件已变化。');
112
+ if (!sameInode(await inodeAt(lockPath), identity)) continue;
113
+
114
+ let release;
115
+ acquired = {
116
+ // Check the canonical directory and lock inode before each mutation.
117
+ async assertHeld() {
118
+ validate(!release && sameInode(await inodeAt(directory), dirIdentity)
119
+ && await isCanonicalPath(directory)
120
+ && sameInode(await inodeAt(lockPath), identity), '会话写锁已失效。');
121
+ },
122
+ close() {
123
+ return release ??= handle.close().finally(() => { slots.count--; });
124
+ },
125
+ };
126
+ return acquired;
127
+ } finally {
128
+ if (!acquired) await handle.close();
129
+ }
130
+ }
131
+ throw alreadyOwned();
132
+ } finally {
133
+ try {
134
+ await dir.close();
135
+ } catch (error) {
136
+ await acquired?.close();
137
+ throw error;
138
+ }
139
+ }
140
+ } finally {
141
+ if (!acquired) slots.count--;
142
+ }
143
+ }