@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,341 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { constants } from 'node:fs';
|
|
3
|
+
import { lstat, mkdir, open, opendir, realpath, rmdir, unlink } from 'node:fs/promises';
|
|
4
|
+
import { basename, dirname, isAbsolute, join, resolve, sep } from 'node:path';
|
|
5
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
6
|
+
import manifest from '../package.json' with { type: 'json' };
|
|
7
|
+
import { MAX_NATIVE_LEASES } from './native-lease.js';
|
|
8
|
+
import {
|
|
9
|
+
acquireWin32Semaphore, candidateLockName, isCanonicalPath, isSamePath, isSupportedPlatform,
|
|
10
|
+
pathKey, releaseWin32Semaphore, tryPosixExclusiveLock,
|
|
11
|
+
} from './platform.js';
|
|
12
|
+
|
|
13
|
+
const namespace = ['plugins', ...manifest.name.split('/')];
|
|
14
|
+
const versionName = `v${manifest.version}`;
|
|
15
|
+
const versionPattern = /^v\d+\.\d+\.\d+(?:-[0-9a-z.-]+)?$/iu;
|
|
16
|
+
const rolloutName = /^session\.v4\.jsonl(?:\.zstd)?$/u;
|
|
17
|
+
const candidateName = /^candidate-[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/u;
|
|
18
|
+
const slotFiles = Object.freeze({ host: 'host.lock', worker: 'worker.lock' });
|
|
19
|
+
const pendingRetries = new Set();
|
|
20
|
+
const retryDelays = [250, 1000, 2000, 5000, 10_000, ...Array(8).fill(30_000)];
|
|
21
|
+
const directoryFlags = constants.O_RDONLY | (constants.O_DIRECTORY ?? 0) | (constants.O_NOFOLLOW ?? 0);
|
|
22
|
+
const transientWin32Codes = new Set(['EBUSY', 'EPERM', 'EACCES']);
|
|
23
|
+
|
|
24
|
+
function check(ok, message) {
|
|
25
|
+
if (!ok) throw new Error(message);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function stat(path) {
|
|
29
|
+
return lstat(path, { bigint: true }).catch(error => {
|
|
30
|
+
if (error.code !== 'ENOENT') throw error;
|
|
31
|
+
return undefined;
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function sameInode(first, second) {
|
|
36
|
+
return first !== undefined && second !== undefined && first.dev === second.dev && first.ino === second.ino;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function nativeSessionDirectory(path) {
|
|
40
|
+
check(typeof path === 'string' && isAbsolute(path) && isSamePath(resolve(path), path) && rolloutName.test(basename(path)),
|
|
41
|
+
'Invalid native rollout path for revision candidates');
|
|
42
|
+
return dirname(path);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
async function checkedDirectory(path, create) {
|
|
46
|
+
if (create) {
|
|
47
|
+
await mkdir(path, { mode: 0o700 }).catch(error => {
|
|
48
|
+
if (error.code !== 'EEXIST') throw error;
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
const identity = await stat(path);
|
|
52
|
+
if (identity === undefined) return false;
|
|
53
|
+
check(identity.isDirectory() && await isCanonicalPath(path), 'Unsafe revision candidate directory');
|
|
54
|
+
return true;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
async function candidateNamespace(session, create) {
|
|
58
|
+
if (!await checkedDirectory(session, false)) return undefined;
|
|
59
|
+
let path = session;
|
|
60
|
+
for (const part of namespace) {
|
|
61
|
+
path = join(path, part);
|
|
62
|
+
if (!await checkedDirectory(path, create)) return undefined;
|
|
63
|
+
}
|
|
64
|
+
return path;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
async function retryWin32Fs(operation) {
|
|
68
|
+
for (let attempt = 0; ; attempt++) {
|
|
69
|
+
try {
|
|
70
|
+
return await operation();
|
|
71
|
+
} catch (error) {
|
|
72
|
+
if (process.platform !== 'win32' || !transientWin32Codes.has(error?.code) || attempt >= 4) throw error;
|
|
73
|
+
await delay(25 * (attempt + 1));
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
async function acquireDirectoryWin32(path, slots, { createHost = false } = {}) {
|
|
79
|
+
const identity = await stat(path);
|
|
80
|
+
check(identity?.isDirectory() && await isCanonicalPath(path), 'Revision candidate namespace changed');
|
|
81
|
+
if (slots.includes('host') && !createHost) {
|
|
82
|
+
let hasCandidates = false;
|
|
83
|
+
for await (const entry of await opendir(path)) {
|
|
84
|
+
if (entry.isDirectory() && candidateName.test(entry.name)) {
|
|
85
|
+
hasCandidates = true;
|
|
86
|
+
break;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
if (!hasCandidates) return null;
|
|
90
|
+
}
|
|
91
|
+
const held = [];
|
|
92
|
+
let acquired = false;
|
|
93
|
+
try {
|
|
94
|
+
for (const slot of slots) {
|
|
95
|
+
const result = acquireWin32Semaphore(candidateLockName(path, slot), path);
|
|
96
|
+
if (result.busy) return undefined;
|
|
97
|
+
held.push(result.handle);
|
|
98
|
+
}
|
|
99
|
+
check(sameInode(await stat(path), identity) && await isCanonicalPath(path), 'Revision candidate namespace changed');
|
|
100
|
+
acquired = true;
|
|
101
|
+
return {
|
|
102
|
+
basePath: path,
|
|
103
|
+
async release() {
|
|
104
|
+
let failure;
|
|
105
|
+
for (const handle of held.toReversed()) {
|
|
106
|
+
try { releaseWin32Semaphore(handle); } catch (error) { failure ??= error; }
|
|
107
|
+
}
|
|
108
|
+
if (failure) throw failure;
|
|
109
|
+
},
|
|
110
|
+
};
|
|
111
|
+
} finally {
|
|
112
|
+
if (!acquired) {
|
|
113
|
+
for (const handle of held.toReversed()) {
|
|
114
|
+
try { releaseWin32Semaphore(handle); } catch { /* Best-effort rollback. */ }
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
async function acquireDirectoryPosix(path, slots, { createHost = false, createWorker = false } = {}) {
|
|
121
|
+
const directory = await open(path, directoryFlags);
|
|
122
|
+
const basePath = process.platform === 'linux' ? `/proc/self/fd/${directory.fd}` : path;
|
|
123
|
+
const held = [];
|
|
124
|
+
let acquired = false;
|
|
125
|
+
try {
|
|
126
|
+
const identity = await directory.stat({ bigint: true });
|
|
127
|
+
check(sameInode(await stat(path), identity) && await isCanonicalPath(path),
|
|
128
|
+
'Revision candidate namespace changed');
|
|
129
|
+
const baseFlags = constants.O_RDWR | constants.O_NOFOLLOW | constants.O_NONBLOCK;
|
|
130
|
+
for (const slot of slots) {
|
|
131
|
+
const fileName = slotFiles[slot];
|
|
132
|
+
const shouldCreate = slot === 'host' ? createHost : createWorker;
|
|
133
|
+
const handle = await open(join(basePath, fileName), shouldCreate ? baseFlags | constants.O_CREAT : baseFlags, 0o600);
|
|
134
|
+
held.push({ fileName, handle });
|
|
135
|
+
const lockIdentity = await handle.stat({ bigint: true });
|
|
136
|
+
check(lockIdentity.isFile() && lockIdentity.nlink === 1n, 'Unsafe revision candidate lock');
|
|
137
|
+
held[held.length - 1].identity = lockIdentity;
|
|
138
|
+
if (!await tryPosixExclusiveLock(handle.fd)) return undefined;
|
|
139
|
+
}
|
|
140
|
+
check(sameInode(await stat(path), identity) && await isCanonicalPath(path), 'Revision candidate namespace changed');
|
|
141
|
+
for (const { fileName, identity: lockIdentity } of held) {
|
|
142
|
+
check(sameInode(await stat(join(basePath, fileName)), lockIdentity), 'Revision candidate namespace changed');
|
|
143
|
+
}
|
|
144
|
+
acquired = true;
|
|
145
|
+
return {
|
|
146
|
+
basePath,
|
|
147
|
+
async release() {
|
|
148
|
+
let failure;
|
|
149
|
+
for (const { handle } of held.toReversed()) {
|
|
150
|
+
try { await handle.close(); } catch (error) { failure ??= error; }
|
|
151
|
+
}
|
|
152
|
+
try { await directory.close(); } catch (error) { failure ??= error; }
|
|
153
|
+
if (failure) throw failure;
|
|
154
|
+
},
|
|
155
|
+
};
|
|
156
|
+
} finally {
|
|
157
|
+
if (!acquired) {
|
|
158
|
+
for (const { handle } of held.toReversed()) {
|
|
159
|
+
try { await handle.close(); } catch { /* Best-effort cleanup. */ }
|
|
160
|
+
}
|
|
161
|
+
await directory.close();
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function acquireDirectory(path, slots, options) {
|
|
167
|
+
if (process.platform === 'win32') return acquireDirectoryWin32(path, slots, options);
|
|
168
|
+
return acquireDirectoryPosix(path, slots, options);
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
function candidateFileName(name) {
|
|
172
|
+
return /^(0|[1-9]\d{0,2})$/u.test(name) && Number(name) < MAX_NATIVE_LEASES;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
async function removeCandidate(scope, name, expected) {
|
|
176
|
+
const path = join(scope.basePath, name);
|
|
177
|
+
const entry = await stat(path);
|
|
178
|
+
if (!entry?.isDirectory() || entry.isSymbolicLink() || (expected && !sameInode(entry, expected))) return false;
|
|
179
|
+
if (process.platform === 'win32') {
|
|
180
|
+
check(await isCanonicalPath(path), 'Unsafe revision candidate directory');
|
|
181
|
+
const files = [];
|
|
182
|
+
for await (const child of await opendir(path)) {
|
|
183
|
+
check(files.length < MAX_NATIVE_LEASES && candidateFileName(child.name) && child.isFile() && !child.isSymbolicLink(),
|
|
184
|
+
'Unexpected file in revision candidate directory');
|
|
185
|
+
const file = join(path, child.name);
|
|
186
|
+
const info = await stat(file);
|
|
187
|
+
check(info?.isFile() && !info.isSymbolicLink() && info.nlink === 1n, 'Unsafe revision candidate output file');
|
|
188
|
+
files.push(file);
|
|
189
|
+
}
|
|
190
|
+
if (!sameInode(await stat(path), entry)) return false;
|
|
191
|
+
for (const file of files) await retryWin32Fs(() => unlink(file));
|
|
192
|
+
await retryWin32Fs(() => rmdir(path));
|
|
193
|
+
return true;
|
|
194
|
+
}
|
|
195
|
+
const directory = await open(path, directoryFlags);
|
|
196
|
+
try {
|
|
197
|
+
const identity = await directory.stat({ bigint: true });
|
|
198
|
+
if (!sameInode(entry, identity)) return false;
|
|
199
|
+
const basePath = process.platform === 'linux' ? `/proc/self/fd/${directory.fd}` : path;
|
|
200
|
+
if (process.platform !== 'linux') check(await isCanonicalPath(path), 'Unsafe revision candidate directory');
|
|
201
|
+
const files = [];
|
|
202
|
+
for await (const child of await opendir(basePath)) {
|
|
203
|
+
// Only remove the flat, numbered output files produced by the worker.
|
|
204
|
+
check(files.length < MAX_NATIVE_LEASES && candidateFileName(child.name) && child.isFile(),
|
|
205
|
+
'Unexpected file in revision candidate directory');
|
|
206
|
+
const file = join(basePath, child.name);
|
|
207
|
+
const info = await stat(file);
|
|
208
|
+
check(info?.isFile() && info.nlink === 1n, 'Unsafe revision candidate output file');
|
|
209
|
+
files.push(file);
|
|
210
|
+
}
|
|
211
|
+
if (!sameInode(await stat(path), identity)) return false;
|
|
212
|
+
for (const file of files) await unlink(file);
|
|
213
|
+
await rmdir(path);
|
|
214
|
+
return true;
|
|
215
|
+
} finally {
|
|
216
|
+
await directory.close();
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/** Hold the Host lock slot for the whole preparation and commit window. */
|
|
221
|
+
export async function createRevisionCandidateDirectory(parentRolloutPath) {
|
|
222
|
+
check(isSupportedPlatform(process.platform), '当前操作系统不支持保护编辑候选文件。');
|
|
223
|
+
const session = nativeSessionDirectory(parentRolloutPath);
|
|
224
|
+
const root = await candidateNamespace(session, true);
|
|
225
|
+
check(root, 'Native session directory is missing');
|
|
226
|
+
const version = join(root, versionName);
|
|
227
|
+
await checkedDirectory(version, true);
|
|
228
|
+
const scope = await acquireDirectory(version, ['host'], { createHost: true });
|
|
229
|
+
check(scope, '正在清理上次编辑的候选文件,请稍后重试。');
|
|
230
|
+
try {
|
|
231
|
+
const name = `candidate-${randomUUID()}`;
|
|
232
|
+
const path = join(scope.basePath, name);
|
|
233
|
+
await mkdir(path, { mode: 0o700 });
|
|
234
|
+
const identity = await stat(path);
|
|
235
|
+
let disposing;
|
|
236
|
+
return {
|
|
237
|
+
directory: join(version, name),
|
|
238
|
+
dispose() {
|
|
239
|
+
return disposing ??= removeCandidate(scope, name, identity).finally(() => scope.release());
|
|
240
|
+
},
|
|
241
|
+
};
|
|
242
|
+
} catch (error) {
|
|
243
|
+
await scope.release();
|
|
244
|
+
throw error;
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/** A detached worker holds the Worker lock slot so cleanup waits even after Host termination. */
|
|
249
|
+
export async function withRevisionCandidateOutput(output, operation) {
|
|
250
|
+
const directory = typeof output === 'string' ? dirname(output) : '';
|
|
251
|
+
if (!basename(directory).startsWith('candidate-')) return operation();
|
|
252
|
+
check(isAbsolute(output) && isSamePath(resolve(output), output) && candidateName.test(basename(directory))
|
|
253
|
+
&& candidateFileName(basename(output)), 'Invalid revision candidate output');
|
|
254
|
+
const version = dirname(directory);
|
|
255
|
+
const suffix = join(...namespace, versionName);
|
|
256
|
+
check(version.length > suffix.length + 1 && isSamePath(version.slice(-suffix.length - 1), `${sep}${suffix}`),
|
|
257
|
+
'Invalid revision candidate namespace');
|
|
258
|
+
const session = version.slice(0, -suffix.length - 1);
|
|
259
|
+
check(isSamePath(await candidateNamespace(session, false), dirname(version)), 'Revision candidate namespace disappeared');
|
|
260
|
+
if (process.platform !== 'win32') {
|
|
261
|
+
check((await stat(join(version, slotFiles.host)))?.isFile(), 'Revision candidate namespace disappeared');
|
|
262
|
+
}
|
|
263
|
+
const scope = await acquireDirectory(version, ['worker'], { createWorker: true });
|
|
264
|
+
check(scope, 'Revision candidate cleanup is in progress');
|
|
265
|
+
try {
|
|
266
|
+
const anchored = join(scope.basePath, basename(directory));
|
|
267
|
+
check((await stat(anchored))?.isDirectory() && isSamePath(await realpath(anchored), directory),
|
|
268
|
+
'Revision candidate directory disappeared');
|
|
269
|
+
return await operation();
|
|
270
|
+
} finally {
|
|
271
|
+
await scope.release();
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
async function sweepRevisionCandidates(parentRolloutPath) {
|
|
276
|
+
const session = nativeSessionDirectory(parentRolloutPath);
|
|
277
|
+
const root = await candidateNamespace(session, false);
|
|
278
|
+
if (root === undefined) return { removed: 0, busy: false };
|
|
279
|
+
let removed = 0;
|
|
280
|
+
let busy = false;
|
|
281
|
+
let failure;
|
|
282
|
+
for await (const version of await opendir(root)) {
|
|
283
|
+
if (!version.isDirectory() || !versionPattern.test(version.name)) continue;
|
|
284
|
+
const path = join(root, version.name);
|
|
285
|
+
const scope = await acquireDirectory(path, ['host', 'worker'], { createHost: false, createWorker: true }).catch(error => {
|
|
286
|
+
if (error.code === 'ENOENT') return null;
|
|
287
|
+
throw error;
|
|
288
|
+
});
|
|
289
|
+
if (scope === null) continue;
|
|
290
|
+
if (!scope) {
|
|
291
|
+
busy = true;
|
|
292
|
+
continue;
|
|
293
|
+
}
|
|
294
|
+
try {
|
|
295
|
+
for await (const entry of await opendir(scope.basePath)) {
|
|
296
|
+
if (!entry.isDirectory() || !candidateName.test(entry.name)) continue;
|
|
297
|
+
try {
|
|
298
|
+
if (await removeCandidate(scope, entry.name)) removed++;
|
|
299
|
+
} catch (error) {
|
|
300
|
+
failure ??= error;
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
} finally {
|
|
304
|
+
await scope.release();
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
if (failure) throw failure;
|
|
308
|
+
return { removed, busy };
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
function retryCleanup(path, onError) {
|
|
312
|
+
const key = pathKey(path);
|
|
313
|
+
if (pendingRetries.has(key) || pendingRetries.size >= MAX_NATIVE_LEASES) return;
|
|
314
|
+
pendingRetries.add(key);
|
|
315
|
+
function schedule(attempt) {
|
|
316
|
+
if (attempt === retryDelays.length) {
|
|
317
|
+
pendingRetries.delete(key);
|
|
318
|
+
return;
|
|
319
|
+
}
|
|
320
|
+
const timer = setTimeout(async () => {
|
|
321
|
+
try {
|
|
322
|
+
const { busy } = await sweepRevisionCandidates(path);
|
|
323
|
+
if (busy) schedule(attempt + 1);
|
|
324
|
+
else pendingRetries.delete(key);
|
|
325
|
+
} catch (error) {
|
|
326
|
+
pendingRetries.delete(key);
|
|
327
|
+
onError?.(error);
|
|
328
|
+
}
|
|
329
|
+
}, retryDelays[attempt]);
|
|
330
|
+
timer.unref();
|
|
331
|
+
}
|
|
332
|
+
schedule(0);
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
/** Reclaim closed preparations in the plugin namespace without opening any rollout. */
|
|
336
|
+
export async function cleanupRevisionCandidates(parentRolloutPath, { retryBusy = false, onError } = {}) {
|
|
337
|
+
if (!isSupportedPlatform(process.platform)) return 0;
|
|
338
|
+
const { removed, busy } = await sweepRevisionCandidates(parentRolloutPath);
|
|
339
|
+
if (busy && retryBusy) retryCleanup(parentRolloutPath, onError);
|
|
340
|
+
return removed;
|
|
341
|
+
}
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
|
|
3
|
+
const packageName = '@kabxx/dsh-message-revision';
|
|
4
|
+
const serviceKey = 'messageRevisionEvents';
|
|
5
|
+
const historySize = 64;
|
|
6
|
+
const historyBytesLimit = 1024 * 1024;
|
|
7
|
+
const subscriberLimit = 64;
|
|
8
|
+
const cursorPattern = /^[\da-f-]{36}:\d{1,16}$/u;
|
|
9
|
+
|
|
10
|
+
function parseCursor(value) {
|
|
11
|
+
if (value === null || (typeof value === 'string' && cursorPattern.test(value))) return value;
|
|
12
|
+
throw new TypeError('Invalid message revision notification cursor');
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function parseNotice(value) {
|
|
16
|
+
const ids = items => Array.isArray(items) && items.length <= 127
|
|
17
|
+
&& items.every(id => typeof id === 'string' && id.length > 0 && id.length <= 2048);
|
|
18
|
+
if (value && typeof value.cursor === 'string' && cursorPattern.test(value.cursor)
|
|
19
|
+
&& (value.type === 'reset' || (value.type === 'revision' && ids(value.rewrittenChildren)
|
|
20
|
+
&& ids(value.withdrawnChildren) && value.rewrittenChildren.length + value.withdrawnChildren.length <= 127
|
|
21
|
+
&& (value.affectedParentIds === undefined || ids(value.affectedParentIds))))) return value;
|
|
22
|
+
throw new TypeError('Invalid message revision notification');
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function codec(name, parse) {
|
|
26
|
+
return { mode: 'strict', typeSymbol: `${packageName}#${name}`, create: () => ({ parse }) };
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const descriptor = {
|
|
30
|
+
id: `${packageName}#${serviceKey}/watch`, service: serviceKey, namespace: serviceKey, method: 'watch',
|
|
31
|
+
invocation: { kind: 'direct' }, mode: 'stream', cancellation: { parameter: 'signal' },
|
|
32
|
+
parameters: [{ name: 'cursor', wire: 'cursor', source: 'json', codec: codec('Cursor', parseCursor) }],
|
|
33
|
+
result: codec('Notice', parseNotice),
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
export function registerRevisionNotifications(ctx, notifications) {
|
|
37
|
+
const service = {
|
|
38
|
+
ctx,
|
|
39
|
+
[Symbol.for('cordis.tracker')]: { property: 'ctx' },
|
|
40
|
+
watch(cursor, signal) {
|
|
41
|
+
const peer = this.ctx.invocation?.peer;
|
|
42
|
+
if (peer?.principal.kind !== 'owner' || peer.signal.aborted) throw new Error('Message revision notifications require an owner connection');
|
|
43
|
+
return notifications.watch(cursor, signal);
|
|
44
|
+
},
|
|
45
|
+
};
|
|
46
|
+
service.typertRemote = { service, serviceKey, namespace: serviceKey };
|
|
47
|
+
ctx.provide(serviceKey, service);
|
|
48
|
+
ctx.typert.register({
|
|
49
|
+
package: packageName, face: 'host', schemas: [],
|
|
50
|
+
model: { services: [], events: [], objects: [] }, invocations: [descriptor],
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function createRevisionNotifications() {
|
|
55
|
+
const epoch = randomUUID();
|
|
56
|
+
const history = [];
|
|
57
|
+
const waiters = new Set();
|
|
58
|
+
let sequence = 0;
|
|
59
|
+
let retainedBytes = 0;
|
|
60
|
+
let subscribers = 0;
|
|
61
|
+
let disposed = false;
|
|
62
|
+
|
|
63
|
+
function publish({ rewrittenChildren = [], withdrawnChildren = [], affectedParentIds = [] }) {
|
|
64
|
+
if (disposed || rewrittenChildren.length + withdrawnChildren.length + affectedParentIds.length === 0) return;
|
|
65
|
+
const notice = {
|
|
66
|
+
type: 'revision', cursor: `${epoch}:${++sequence}`, rewrittenChildren, withdrawnChildren,
|
|
67
|
+
...(affectedParentIds.length > 0 && { affectedParentIds }),
|
|
68
|
+
};
|
|
69
|
+
const bytes = Buffer.byteLength(JSON.stringify(notice));
|
|
70
|
+
history.push({ notice, bytes });
|
|
71
|
+
retainedBytes += bytes;
|
|
72
|
+
while (history.length > historySize || retainedBytes > historyBytesLimit) {
|
|
73
|
+
retainedBytes -= history.shift().bytes;
|
|
74
|
+
}
|
|
75
|
+
for (const wake of waiters) wake();
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function cursorFor(id) {
|
|
79
|
+
if (!id?.startsWith(`${epoch}:`)) return undefined;
|
|
80
|
+
const cursor = Number(id.slice(epoch.length + 1));
|
|
81
|
+
return Number.isSafeInteger(cursor) && cursor >= 0 && cursor <= sequence && id === `${epoch}:${cursor}`
|
|
82
|
+
? cursor : undefined;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
async function* watch(lastCursor, signal) {
|
|
86
|
+
if (disposed || signal.aborted) return;
|
|
87
|
+
if (subscribers >= subscriberLimit) throw new Error('Message revision notification subscriber limit reached');
|
|
88
|
+
subscribers++;
|
|
89
|
+
let cursor = cursorFor(lastCursor);
|
|
90
|
+
try {
|
|
91
|
+
while (!disposed && !signal.aborted) {
|
|
92
|
+
const oldestCursor = sequence - history.length;
|
|
93
|
+
if (cursor === undefined || cursor < oldestCursor) {
|
|
94
|
+
cursor = sequence;
|
|
95
|
+
yield { type: 'reset', cursor: `${epoch}:${cursor}` };
|
|
96
|
+
} else if (cursor < sequence) {
|
|
97
|
+
yield history[cursor++ - oldestCursor].notice;
|
|
98
|
+
} else {
|
|
99
|
+
const { promise, resolve } = Promise.withResolvers();
|
|
100
|
+
waiters.add(resolve);
|
|
101
|
+
signal.addEventListener('abort', resolve, { once: true });
|
|
102
|
+
try { await promise; } finally {
|
|
103
|
+
waiters.delete(resolve);
|
|
104
|
+
signal.removeEventListener('abort', resolve);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
} finally {
|
|
109
|
+
subscribers--;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
return {
|
|
114
|
+
watch, publish,
|
|
115
|
+
close() {
|
|
116
|
+
disposed = true;
|
|
117
|
+
for (const wake of waiters) wake();
|
|
118
|
+
history.length = 0;
|
|
119
|
+
retainedBytes = 0;
|
|
120
|
+
},
|
|
121
|
+
};
|
|
122
|
+
}
|