@rarog/server 1.1.0-beta.1 → 1.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 +14 -2
- package/node_modules/@rarog/shared/package.json +1 -1
- package/node_modules/@rarog/shared/src/decode.js +16 -1
- package/node_modules/@rarog/shared/src/protocol/folders.js +27 -0
- package/node_modules/@rarog/shared/src/protocol/herdr.js +23 -0
- package/node_modules/@rarog/shared/src/protocol/notes.js +7 -1
- package/node_modules/@rarog/shared/src/protocol.js +5 -31
- package/node_modules/@rarog/shared/src/sentences/herdr.js +0 -4
- package/node_modules/@rarog/shared/src/sentences/index.js +7 -1
- package/node_modules/@rarog/shared/src/sentences/rest.js +8 -0
- package/package.json +2 -2
- package/server/src/auth/admin.js +3 -1
- package/server/src/bootstrap/consent.js +11 -0
- package/server/src/bootstrap/folder-gate.js +55 -0
- package/server/src/cli/service-log.js +27 -0
- package/server/src/cli/service.js +5 -2
- package/server/src/cli/templates/launchd.plist +1 -1
- package/server/src/cli/templates/rarog.service +1 -1
- package/server/src/cli/update-provenance.js +37 -19
- package/server/src/cli/update-registry.js +31 -1
- package/server/src/cli/update.js +128 -6
- package/server/src/config/protected-dirs.js +2 -0
- package/server/src/config/roots.js +13 -8
- package/server/src/config/work-area.js +36 -12
- package/server/src/config-env.js +9 -0
- package/server/src/config.js +17 -1
- package/server/src/demo/control.js +9 -1
- package/server/src/drivers/herdr/consent-no-hook.js +103 -8
- package/server/src/drivers/herdr/screen-fallback.js +246 -0
- package/server/src/drivers/herdr-driver.js +78 -9
- package/server/src/files/file-index.js +5 -3
- package/server/src/files/listing.js +8 -2
- package/server/src/files/path-rule.js +95 -41
- package/server/src/files/refusals.js +14 -0
- package/server/src/files/session-gate.js +11 -6
- package/server/src/folder-gate/client.js +314 -0
- package/server/src/folder-gate/disk.js +455 -0
- package/server/src/folder-gate/folders.js +23 -0
- package/server/src/folder-gate/gate.js +220 -0
- package/server/src/folder-gate/helper.js +118 -0
- package/server/src/folder-gate/install.js +27 -0
- package/server/src/folder-gate/relay-worker.js +147 -0
- package/server/src/folder-gate/types.js +115 -0
- package/server/src/folder-gate/wire.js +170 -0
- package/server/src/fs-browse.js +55 -23
- package/server/src/fs-mkdir.js +3 -1
- package/server/src/git-status.js +13 -5
- package/server/src/git-watch.js +130 -19
- package/server/src/git-work-tree.js +3 -3
- package/server/src/herdr/client.js +2 -2
- package/server/src/herdr/commands/discover.js +21 -9
- package/server/src/herdr/dialogs/consent-gate.js +28 -8
- package/server/src/herdr/dialogs/decide/sources.js +5 -2
- package/server/src/herdr/dialogs/hook/contract.js +1 -1
- package/server/src/herdr/dialogs/index.js +7 -2
- package/server/src/herdr/dialogs/layer1/cycle.js +43 -7
- package/server/src/herdr/dialogs/layer1/hook-list/hook-list.js +34 -27
- package/server/src/herdr/dialogs/layer1/screen-key.js +52 -0
- package/server/src/herdr/dialogs/router.js +21 -6
- package/server/src/herdr/dialogs/screen/parse.js +23 -2
- package/server/src/herdr/dialogs/screen/resolve.js +9 -7
- package/server/src/herdr/dialogs/screen-fallback.js +55 -0
- package/server/src/herdr/dialogs/shadow/alive.js +9 -8
- package/server/src/herdr/jsonl-follow.js +55 -14
- package/server/src/herdr/provenance.js +3 -3
- package/server/src/herdr/socket.js +25 -28
- package/server/src/herdr/supervisor.js +13 -10
- package/server/src/herdr/transcript-path.js +36 -0
- package/server/src/herdr/trust.js +11 -8
- package/server/src/herdr/uploads-registry.js +3 -2
- package/server/src/herdr/uploads.js +170 -47
- package/server/src/index.js +22 -3
- package/server/src/iroh/listener.js +3 -0
- package/server/src/iroh/log-budget.js +1 -0
- package/server/src/iroh/socket.js +2 -1
- package/server/src/notes/store.js +3 -2
- package/server/src/router.js +13 -1
- package/server/src/routes/projects.js +5 -1
- package/server/src/routes/sessions.js +10 -4
- package/server/src/routes/system.js +4 -0
- package/server/src/safe-read.js +12 -12
- package/server/src/sessions/companion-scope.js +10 -5
- package/server/src/sessions/done-retention.js +57 -0
- package/server/src/sessions/launch-gate.js +2 -2
- package/server/src/sessions/manager.js +35 -59
- package/server/src/sessions/project-scan.js +9 -3
- package/server/src/sessions/ring-buffer.js +8 -21
- package/server/src/sessions/session-git.js +31 -2
- package/server/src/sessions/session.js +1 -1
- package/server/src/sessions/state-sentences.js +1 -1
- package/server/src/sse.js +121 -22
- package/server/src/term/herdr-backend.js +2 -2
- package/server/src/term/index.js +2 -15
- package/server/src/term/registry.js +4 -3
- package/server/src/term/ws.js +9 -1
|
@@ -1,21 +1,42 @@
|
|
|
1
|
-
import { lstatSync, readlinkSync, realpathSync } from 'node:fs';
|
|
2
|
-
import { lstat, readdir, realpath, stat } from 'node:fs/promises';
|
|
3
1
|
import path from 'node:path';
|
|
4
|
-
import { insideWorkArea, resolveInWorkArea } from '../config/work-area.js';
|
|
2
|
+
import { areaDiskOf, insideWorkArea, resolveInWorkArea } from '../config/work-area.js';
|
|
3
|
+
import { DIRECT_DISK } from '../folder-gate/disk.js';
|
|
4
|
+
import { FolderGateError } from '../folder-gate/types.js';
|
|
5
5
|
import { validateDiffPath } from '../git-diff.js';
|
|
6
|
-
import {
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
6
|
+
import { BAD_PATH, NOT_FOUND, closedFolder } from './refusals.js';
|
|
7
|
+
/**
|
|
8
|
+
* The rule's view of the work-area disk port. `realpath` is the native one (`fs.promises.realpath`, letter case of
|
|
9
|
+
* the disk), the walk's `area.realpath` the JavaScript one. The open of a file gives the port's handle, which the
|
|
10
|
+
* download reads and closes through the same port.
|
|
11
|
+
*/
|
|
12
|
+
export function filesDiskOf(disk) {
|
|
13
|
+
return {
|
|
14
|
+
// `buffer` gives every name as bytes.
|
|
15
|
+
readdir: async (dir) => [...await disk.call('readdir', { path: dir, encoding: 'buffer' })],
|
|
16
|
+
readdirByIdentity: async (dir) => {
|
|
17
|
+
const entries = await disk.call('readdirByIdentity', { path: dir.real, dev: dir.dev, ino: dir.ino });
|
|
18
|
+
return entries === null ? null : [...entries];
|
|
19
|
+
},
|
|
20
|
+
lstat: (file) => disk.call('lstat', { path: file }),
|
|
21
|
+
stat: (file) => disk.call('stat', { path: file }),
|
|
22
|
+
realpath: (file) => disk.call('realpathNative', { path: file }),
|
|
23
|
+
open: async (file) => {
|
|
24
|
+
const opened = await disk.call('openRead', { path: file, followSymlink: false });
|
|
25
|
+
if (opened === null)
|
|
26
|
+
return null;
|
|
27
|
+
const { handle } = opened;
|
|
28
|
+
return {
|
|
29
|
+
handle: {
|
|
30
|
+
read: (length, position) => disk.call('read', { handle, length, position }),
|
|
31
|
+
close: () => disk.call('close', { handle }),
|
|
32
|
+
},
|
|
33
|
+
stats: opened.stats,
|
|
34
|
+
};
|
|
35
|
+
},
|
|
36
|
+
area: areaDiskOf(disk),
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
export const FILES_DISK = filesDiskOf(DIRECT_DISK);
|
|
19
40
|
const refused = (refusal) => ({ ok: false, refusal });
|
|
20
41
|
/** Step 1: the segments of the path, or `null` for 400. `''` is the session directory where `allowEmpty`. */
|
|
21
42
|
function segmentsOf(rel, allowEmpty) {
|
|
@@ -58,14 +79,28 @@ function checkText(area, rel, allowEmpty) {
|
|
|
58
79
|
return refused(NOT_FOUND);
|
|
59
80
|
return { ok: true, value: segments };
|
|
60
81
|
}
|
|
82
|
+
/** The value of a disk call, or `null` for any error but the refusal of a closed folder, which goes on. */
|
|
61
83
|
async function attempt(call) {
|
|
62
84
|
try {
|
|
63
85
|
return await call();
|
|
64
86
|
}
|
|
65
|
-
catch {
|
|
87
|
+
catch (error) {
|
|
88
|
+
if (error instanceof FolderGateError)
|
|
89
|
+
throw error;
|
|
66
90
|
return null;
|
|
67
91
|
}
|
|
68
92
|
}
|
|
93
|
+
/** The answer of `rule`, or the refusal of a closed folder any of its disk calls met. */
|
|
94
|
+
async function orClosed(rule) {
|
|
95
|
+
try {
|
|
96
|
+
return await rule();
|
|
97
|
+
}
|
|
98
|
+
catch (error) {
|
|
99
|
+
if (error instanceof FolderGateError)
|
|
100
|
+
return refused(closedFolder(error));
|
|
101
|
+
throw error;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
69
104
|
/** Step 3: the walk down from `cwd` and the path on disk, or `null` for 404. */
|
|
70
105
|
async function walk(area, segments, last, disk) {
|
|
71
106
|
let current = area.cwd;
|
|
@@ -83,7 +118,10 @@ async function walk(area, segments, last, disk) {
|
|
|
83
118
|
return null;
|
|
84
119
|
current = next;
|
|
85
120
|
}
|
|
86
|
-
|
|
121
|
+
const resolved = resolveInWorkArea(current, area.realRoots, area.realHome, disk.area);
|
|
122
|
+
if (resolved.kind === 'excluded' && resolved.closed !== undefined)
|
|
123
|
+
throw resolved.closed;
|
|
124
|
+
if (resolved.kind !== 'resolved')
|
|
87
125
|
return null;
|
|
88
126
|
const real = await attempt(() => disk.realpath(current));
|
|
89
127
|
if (real !== path.join(area.realCwd, ...segments))
|
|
@@ -98,42 +136,58 @@ export async function resolveSessionDir(area, rel, disk = FILES_DISK) {
|
|
|
98
136
|
if (!text.ok)
|
|
99
137
|
return text;
|
|
100
138
|
const segments = text.value;
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
139
|
+
return orClosed(async () => {
|
|
140
|
+
const walked = await walk(area, segments, 'dir', disk);
|
|
141
|
+
if (walked === null)
|
|
142
|
+
return refused(NOT_FOUND);
|
|
143
|
+
const info = await attempt(() => disk.stat(walked.real));
|
|
144
|
+
if (info === null || !info.isDirectory())
|
|
145
|
+
return refused(NOT_FOUND);
|
|
146
|
+
return { ok: true, value: { rel, segments, path: walked.path, real: walked.real, dev: info.dev, ino: info.ino } };
|
|
147
|
+
});
|
|
108
148
|
}
|
|
109
149
|
/**
|
|
110
150
|
* Whether `dir` is still the directory the walk found: `realpath` of its path gives the same directory on disk with
|
|
111
151
|
* the same `dev` and `ino`. The listing asks after its read of the entries, as the open does after the open.
|
|
112
152
|
*/
|
|
113
153
|
export async function stillSessionDir(dir, disk = FILES_DISK) {
|
|
114
|
-
|
|
115
|
-
|
|
154
|
+
try {
|
|
155
|
+
const real = await attempt(() => disk.realpath(dir.path));
|
|
156
|
+
if (real !== dir.real)
|
|
157
|
+
return false;
|
|
158
|
+
const info = await attempt(() => disk.stat(real));
|
|
159
|
+
return info !== null && info.isDirectory() && info.dev === dir.dev && info.ino === dir.ino;
|
|
160
|
+
}
|
|
161
|
+
catch {
|
|
116
162
|
return false;
|
|
117
|
-
|
|
118
|
-
return info !== null && info.isDirectory() && info.dev === dir.dev && info.ino === dir.ino;
|
|
163
|
+
}
|
|
119
164
|
}
|
|
120
165
|
/** Steps 1 to 5 for a file: the open file, or the refusal with no descriptor left open. */
|
|
121
166
|
export async function openSessionFile(area, rel, disk = FILES_DISK) {
|
|
122
167
|
const text = checkText(area, rel, false);
|
|
123
168
|
if (!text.ok)
|
|
124
169
|
return text;
|
|
125
|
-
const
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
170
|
+
const segments = text.value;
|
|
171
|
+
return orClosed(async () => {
|
|
172
|
+
const walked = await walk(area, segments, 'file', disk);
|
|
173
|
+
if (walked === null)
|
|
174
|
+
return refused(NOT_FOUND);
|
|
175
|
+
const opened = await attempt(() => disk.open(walked.real));
|
|
176
|
+
if (opened === null)
|
|
177
|
+
return refused(NOT_FOUND);
|
|
178
|
+
const { handle, stats } = opened;
|
|
179
|
+
let same = false;
|
|
180
|
+
try {
|
|
181
|
+
same = stats.nlink <= 1n && await sameFileAgain(walked, stats, disk);
|
|
182
|
+
}
|
|
183
|
+
finally {
|
|
184
|
+
if (!same)
|
|
185
|
+
await handle.close();
|
|
186
|
+
}
|
|
187
|
+
if (!same)
|
|
188
|
+
return refused(NOT_FOUND);
|
|
189
|
+
return { ok: true, value: { handle, size: Number(stats.size), stats } };
|
|
190
|
+
});
|
|
137
191
|
}
|
|
138
192
|
/** Step 5: the path resolves to the same place, and that place is the file the descriptor holds. */
|
|
139
193
|
async function sameFileAgain(walked, opened, disk) {
|
|
@@ -11,6 +11,20 @@ export const BAD_PATH = { status: 400, code: FILES_BAD_PATH_ERROR, sentence: say
|
|
|
11
11
|
export const NOT_FOUND = {
|
|
12
12
|
status: 404, code: FILES_NOT_FOUND_ERROR, sentence: say('rest.files-not-found'),
|
|
13
13
|
};
|
|
14
|
+
/**
|
|
15
|
+
* A guarded folder of home the folder gate holds closed: the status and code of a path that cannot be read, with the
|
|
16
|
+
* sentence of the folder's state, so the app says why instead of "not found".
|
|
17
|
+
*/
|
|
18
|
+
export function closedFolder(error) {
|
|
19
|
+
const refusal = { status: 404, code: FILES_NOT_FOUND_ERROR, sentence: error.sentence };
|
|
20
|
+
CLOSED.add(refusal);
|
|
21
|
+
return refusal;
|
|
22
|
+
}
|
|
23
|
+
const CLOSED = new WeakSet();
|
|
24
|
+
/** Whether `refusal` is the one of a closed folder ({@link closedFolder}), not a path that is simply not there. */
|
|
25
|
+
export function isClosedFolder(refusal) {
|
|
26
|
+
return CLOSED.has(refusal);
|
|
27
|
+
}
|
|
14
28
|
/** A Codex entry: Rarog only observes it. */
|
|
15
29
|
export const CODEX = { status: 400, code: FILES_CODEX_ERROR, sentence: say('rest.files-codex') };
|
|
16
30
|
/** A pane outside the work area, or a session directory outside it on disk. */
|
|
@@ -6,18 +6,24 @@
|
|
|
6
6
|
* roots and home, never a path of the request.
|
|
7
7
|
*/
|
|
8
8
|
import { homedir } from 'node:os';
|
|
9
|
-
import { inWorkAreaOnDisk, onDiskForms } from '../config/work-area.js';
|
|
9
|
+
import { inWorkAreaOnDisk, onDiskForms, resolveInWorkArea } from '../config/work-area.js';
|
|
10
10
|
import { FILES_DISK } from './path-rule.js';
|
|
11
|
-
import { CODEX, NOT_FOUND, NO_PANE, OUT_OF_SCOPE } from './refusals.js';
|
|
11
|
+
import { CODEX, NOT_FOUND, NO_PANE, OUT_OF_SCOPE, closedFolder } from './refusals.js';
|
|
12
12
|
/**
|
|
13
13
|
* The area of the session directory `cwd`: refused when `cwd` lies outside the work area as written or on disk
|
|
14
|
-
* (`out-of-scope`),
|
|
14
|
+
* (`out-of-scope`), when the way to it passes a guarded folder that a root opens and the folder gate holds closed
|
|
15
|
+
* (404 with the sentence of the folder's state), and when it no longer resolves (`not-found`: the directory is gone).
|
|
15
16
|
*/
|
|
16
17
|
export function filesArea(cwd, config, disk = FILES_DISK.area) {
|
|
17
18
|
const roots = config.herdrRoots ?? [];
|
|
18
19
|
const home = config.home ?? homedir();
|
|
19
|
-
|
|
20
|
-
|
|
20
|
+
const real = onDiskForms(roots, home, disk.realpath);
|
|
21
|
+
if (!inWorkAreaOnDisk(cwd, roots, home, disk)) {
|
|
22
|
+
// The walk again, metadata only, for the one case a closed folder put `cwd` out: say why.
|
|
23
|
+
const walked = resolveInWorkArea(cwd, real.roots, real.home, disk);
|
|
24
|
+
const closed = walked.kind === 'excluded' ? walked.closed : undefined;
|
|
25
|
+
return { ok: false, refusal: closed === undefined ? OUT_OF_SCOPE : closedFolder(closed) };
|
|
26
|
+
}
|
|
21
27
|
let realCwd;
|
|
22
28
|
try {
|
|
23
29
|
realCwd = disk.realpath(cwd);
|
|
@@ -25,7 +31,6 @@ export function filesArea(cwd, config, disk = FILES_DISK.area) {
|
|
|
25
31
|
catch {
|
|
26
32
|
return { ok: false, refusal: NOT_FOUND };
|
|
27
33
|
}
|
|
28
|
-
const real = onDiskForms(roots, home, disk.realpath);
|
|
29
34
|
return { ok: true, value: { cwd, realCwd, roots, realRoots: real.roots, home, realHome: real.home } };
|
|
30
35
|
}
|
|
31
36
|
/**
|
|
@@ -0,0 +1,314 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The folder client: one disk operation in a folder helper, through the relay thread (`relay-worker.ts`). `callSync`
|
|
3
|
+
* blocks the calling thread in `Atomics.wait` for at most the sync bound and `call` resolves within the call bound, so
|
|
4
|
+
* a helper that waits for a macOS consent window costs the server one bounded wait, never a hung thread. The client
|
|
5
|
+
* owns request ids, generations and timeouts; an answer that comes after its caller gave up goes to `onLate`. It
|
|
6
|
+
* judges no path and keeps no folder state: that is the gate's.
|
|
7
|
+
*/
|
|
8
|
+
import { MessageChannel, receiveMessageOnPort, Worker } from 'node:worker_threads';
|
|
9
|
+
import { decodeResponse, encodeRequest } from './wire.js';
|
|
10
|
+
/** How long a sync call in a gated folder may block the server thread. */
|
|
11
|
+
export const FOLDER_SYNC_BOUND_MS = 1000;
|
|
12
|
+
/** How long an async call in a gated folder may stay unanswered. */
|
|
13
|
+
export const FOLDER_CALL_BOUND_MS = 1000;
|
|
14
|
+
/** A write gets the bound once per this many bytes, so a large file is not cut off by a bound meant for a read. */
|
|
15
|
+
const WRITE_BYTES_PER_BOUND = 1024 * 1024;
|
|
16
|
+
/** Slots of the shared pid table; one live helper per folder, plus killed ones until they are reaped. */
|
|
17
|
+
const PID_SLOTS = 64;
|
|
18
|
+
const GONE = { kind: 'gone' };
|
|
19
|
+
const TIMEOUT = { kind: 'timeout' };
|
|
20
|
+
/** The bound of one call: a write over a megabyte gets it once per started megabyte. */
|
|
21
|
+
function boundOf(op, args, base) {
|
|
22
|
+
if (op !== 'writeFile')
|
|
23
|
+
return base;
|
|
24
|
+
const data = args.data;
|
|
25
|
+
return base * Math.max(1, Math.ceil(data.length / WRITE_BYTES_PER_BOUND));
|
|
26
|
+
}
|
|
27
|
+
/** An `openRead` answer that left a file open in the helper: its handle. */
|
|
28
|
+
function openedHandle(op, answer) {
|
|
29
|
+
if (op !== 'openRead' || answer.kind !== 'ok' || typeof answer.value !== 'object' || answer.value === null) {
|
|
30
|
+
return null;
|
|
31
|
+
}
|
|
32
|
+
const handle = answer.value.handle;
|
|
33
|
+
return typeof handle === 'number' ? handle : null;
|
|
34
|
+
}
|
|
35
|
+
export class RelayFolderClient {
|
|
36
|
+
#options;
|
|
37
|
+
#syncBoundMs;
|
|
38
|
+
#callBoundMs;
|
|
39
|
+
#signal = new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));
|
|
40
|
+
#pids = new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT * PID_SLOTS));
|
|
41
|
+
#generations = new Map();
|
|
42
|
+
/**
|
|
43
|
+
* The files each folder's current helper holds open, by the handle number it gave, with its generation. A new
|
|
44
|
+
* generation starts with none: the files of a helper that ended went with it.
|
|
45
|
+
*/
|
|
46
|
+
#handles = new Map();
|
|
47
|
+
#waiting = new Map();
|
|
48
|
+
#abandoned = new Map();
|
|
49
|
+
#lateListeners = new Set();
|
|
50
|
+
#onExit = () => { this.#killHelpers(); };
|
|
51
|
+
#relay = null;
|
|
52
|
+
#nextId = 1;
|
|
53
|
+
#disposed = false;
|
|
54
|
+
constructor(options) {
|
|
55
|
+
this.#options = options;
|
|
56
|
+
this.#syncBoundMs = options.syncBoundMs ?? FOLDER_SYNC_BOUND_MS;
|
|
57
|
+
this.#callBoundMs = options.callBoundMs ?? FOLDER_CALL_BOUND_MS;
|
|
58
|
+
}
|
|
59
|
+
/** The generation of the folder's helper: answers of older generations are stale. */
|
|
60
|
+
generationOf(folder) {
|
|
61
|
+
return this.#generations.get(folder) ?? 1;
|
|
62
|
+
}
|
|
63
|
+
callSync(folder, op, args) {
|
|
64
|
+
const sent = this.#send(folder, op, args, null);
|
|
65
|
+
if (sent === null)
|
|
66
|
+
return GONE;
|
|
67
|
+
const { id, entry } = sent;
|
|
68
|
+
const stale = this.#staleHandle(folder, op, args);
|
|
69
|
+
if (stale !== null)
|
|
70
|
+
return stale;
|
|
71
|
+
// A monotonic clock: a step of the wall clock must not stretch the time the main thread waits.
|
|
72
|
+
const deadline = performance.now() + boundOf(op, args, this.#syncBoundMs);
|
|
73
|
+
for (;;) {
|
|
74
|
+
const seen = Atomics.load(this.#signal, 0);
|
|
75
|
+
this.#drain();
|
|
76
|
+
if (entry.answer !== null)
|
|
77
|
+
return entry.answer;
|
|
78
|
+
const remaining = deadline - performance.now();
|
|
79
|
+
if (remaining <= 0) {
|
|
80
|
+
this.#abandon(id, entry);
|
|
81
|
+
return TIMEOUT;
|
|
82
|
+
}
|
|
83
|
+
Atomics.wait(this.#signal, 0, seen, remaining);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
call(folder, op, args, gen) {
|
|
87
|
+
const stale = this.#staleHandle(folder, op, args, gen);
|
|
88
|
+
if (stale !== null)
|
|
89
|
+
return Promise.resolve(stale);
|
|
90
|
+
return new Promise((resolve) => {
|
|
91
|
+
const sent = this.#send(folder, op, args, resolve);
|
|
92
|
+
if (sent === null) {
|
|
93
|
+
resolve(GONE);
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
const { id, entry } = sent;
|
|
97
|
+
entry.timer = setTimeout(() => {
|
|
98
|
+
if (this.#waiting.get(id) !== entry)
|
|
99
|
+
return;
|
|
100
|
+
this.#abandon(id, entry);
|
|
101
|
+
resolve(TIMEOUT);
|
|
102
|
+
}, boundOf(op, args, this.#callBoundMs));
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
restart(folder) {
|
|
106
|
+
const gen = this.#nextGeneration(folder);
|
|
107
|
+
for (const [id, entry] of this.#waiting) {
|
|
108
|
+
if (entry.folder === folder)
|
|
109
|
+
this.#settle(id, entry, GONE);
|
|
110
|
+
}
|
|
111
|
+
this.#post({ type: 'restart', folder, gen });
|
|
112
|
+
return gen;
|
|
113
|
+
}
|
|
114
|
+
onLate(listener) {
|
|
115
|
+
this.#lateListeners.add(listener);
|
|
116
|
+
return () => { this.#lateListeners.delete(listener); };
|
|
117
|
+
}
|
|
118
|
+
dispose() {
|
|
119
|
+
if (this.#disposed)
|
|
120
|
+
return;
|
|
121
|
+
this.#disposed = true;
|
|
122
|
+
this.#killHelpers();
|
|
123
|
+
this.#stopRelay();
|
|
124
|
+
for (const [id, entry] of this.#waiting)
|
|
125
|
+
this.#settle(id, entry, GONE);
|
|
126
|
+
this.#abandoned.clear();
|
|
127
|
+
}
|
|
128
|
+
#send(folder, op, args, resolve) {
|
|
129
|
+
const relay = this.#ensureRelay();
|
|
130
|
+
if (relay === null)
|
|
131
|
+
return null;
|
|
132
|
+
const id = this.#nextId++;
|
|
133
|
+
const gen = this.generationOf(folder);
|
|
134
|
+
const entry = { folder, gen, op, resolve, timer: null, answer: null };
|
|
135
|
+
this.#waiting.set(id, entry);
|
|
136
|
+
relay.port.postMessage({ type: 'call', folder, gen, id, line: encodeRequest(id, op, args) });
|
|
137
|
+
return { id, entry };
|
|
138
|
+
}
|
|
139
|
+
#post(request) {
|
|
140
|
+
this.#relay?.port.postMessage(request);
|
|
141
|
+
}
|
|
142
|
+
#ensureRelay() {
|
|
143
|
+
if (this.#disposed)
|
|
144
|
+
return null;
|
|
145
|
+
if (this.#relay !== null)
|
|
146
|
+
return this.#relay;
|
|
147
|
+
const { port1, port2 } = new MessageChannel();
|
|
148
|
+
const workerData = {
|
|
149
|
+
port: port2, signal: this.#signal.buffer, pids: this.#pids.buffer,
|
|
150
|
+
helper: this.#options.helper,
|
|
151
|
+
};
|
|
152
|
+
const worker = new Worker(this.#options.relay, { workerData, transferList: [port2] });
|
|
153
|
+
const relay = { worker, port: port1 };
|
|
154
|
+
port1.on('message', (event) => { this.#handle(event); });
|
|
155
|
+
const lost = () => { this.#relayLost(relay); };
|
|
156
|
+
worker.on('error', lost);
|
|
157
|
+
worker.on('exit', lost);
|
|
158
|
+
// Neither the relay nor its channel keeps the process alive; a pending `call` does, through its timer.
|
|
159
|
+
worker.unref();
|
|
160
|
+
port1.unref();
|
|
161
|
+
process.on('exit', this.#onExit);
|
|
162
|
+
this.#relay = relay;
|
|
163
|
+
return relay;
|
|
164
|
+
}
|
|
165
|
+
/** The relay thread ended on its own: no answer can come, and its helpers would be left without a reader. */
|
|
166
|
+
#relayLost(relay) {
|
|
167
|
+
if (this.#relay !== relay)
|
|
168
|
+
return;
|
|
169
|
+
this.#killHelpers();
|
|
170
|
+
this.#stopRelay();
|
|
171
|
+
for (const [id, entry] of this.#waiting)
|
|
172
|
+
this.#settle(id, entry, GONE);
|
|
173
|
+
this.#abandoned.clear();
|
|
174
|
+
}
|
|
175
|
+
/**
|
|
176
|
+
* Lets the relay thread go without waiting for it: it kills its helpers, reaps them and ends on its own. Terminating
|
|
177
|
+
* it here would leave the killed helpers unreaped for the life of the server.
|
|
178
|
+
*/
|
|
179
|
+
#stopRelay() {
|
|
180
|
+
const relay = this.#relay;
|
|
181
|
+
if (relay === null)
|
|
182
|
+
return;
|
|
183
|
+
this.#relay = null;
|
|
184
|
+
process.off('exit', this.#onExit);
|
|
185
|
+
relay.port.postMessage({ type: 'dispose' });
|
|
186
|
+
relay.port.close();
|
|
187
|
+
}
|
|
188
|
+
/** SIGKILL to every live helper, by pid from the shared table: works in an `exit` hook and never waits. */
|
|
189
|
+
#killHelpers() {
|
|
190
|
+
for (let slot = 0; slot < this.#pids.length; slot += 1) {
|
|
191
|
+
const pid = Atomics.exchange(this.#pids, slot, 0);
|
|
192
|
+
if (pid <= 0)
|
|
193
|
+
continue;
|
|
194
|
+
try {
|
|
195
|
+
process.kill(pid, 'SIGKILL');
|
|
196
|
+
}
|
|
197
|
+
catch {
|
|
198
|
+
// Already gone.
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
#drain() {
|
|
203
|
+
const port = this.#relay?.port;
|
|
204
|
+
if (port === undefined)
|
|
205
|
+
return;
|
|
206
|
+
for (let message = receiveMessageOnPort(port); message !== undefined; message = receiveMessageOnPort(port)) {
|
|
207
|
+
this.#handle(message.message);
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
#handle(event) {
|
|
211
|
+
if (event.type === 'gone') {
|
|
212
|
+
// The current helper ended: its open files went with it, so the next call starts a new generation.
|
|
213
|
+
if (event.gen === this.generationOf(event.folder))
|
|
214
|
+
this.#nextGeneration(event.folder);
|
|
215
|
+
for (const id of event.ids) {
|
|
216
|
+
this.#abandoned.delete(id);
|
|
217
|
+
const entry = this.#waiting.get(id);
|
|
218
|
+
if (entry !== undefined)
|
|
219
|
+
this.#settle(id, entry, GONE);
|
|
220
|
+
}
|
|
221
|
+
return;
|
|
222
|
+
}
|
|
223
|
+
const answer = this.#decode(event.line);
|
|
224
|
+
const entry = this.#waiting.get(event.id);
|
|
225
|
+
if (entry !== undefined) {
|
|
226
|
+
this.#settle(event.id, entry, answer);
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
const abandoned = this.#abandoned.get(event.id);
|
|
230
|
+
if (abandoned === undefined)
|
|
231
|
+
return;
|
|
232
|
+
this.#abandoned.delete(event.id);
|
|
233
|
+
const handle = openedHandle(abandoned.op, answer);
|
|
234
|
+
if (handle !== null && abandoned.gen === this.generationOf(abandoned.folder)) {
|
|
235
|
+
this.#closeLate(abandoned.folder, abandoned.gen, handle);
|
|
236
|
+
}
|
|
237
|
+
for (const listener of this.#lateListeners)
|
|
238
|
+
listener(abandoned.folder, abandoned.gen, answer);
|
|
239
|
+
}
|
|
240
|
+
#decode(line) {
|
|
241
|
+
try {
|
|
242
|
+
const response = decodeResponse(line);
|
|
243
|
+
return response.ok ? { kind: 'ok', value: response.value } : { kind: 'fs-error', error: response.error };
|
|
244
|
+
}
|
|
245
|
+
catch {
|
|
246
|
+
// A line the codec cannot read means a broken helper, the same as one that ended.
|
|
247
|
+
return GONE;
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
/** Closes a file a late answer left open; nobody waits for the result. */
|
|
251
|
+
#closeLate(folder, gen, handle) {
|
|
252
|
+
const relay = this.#relay;
|
|
253
|
+
if (relay === null)
|
|
254
|
+
return;
|
|
255
|
+
const id = this.#nextId++;
|
|
256
|
+
relay.port.postMessage({
|
|
257
|
+
type: 'call', folder, gen, id, line: encodeRequest(id, 'close', { handle }),
|
|
258
|
+
});
|
|
259
|
+
}
|
|
260
|
+
#abandon(id, entry) {
|
|
261
|
+
this.#waiting.delete(id);
|
|
262
|
+
if (entry.timer !== null)
|
|
263
|
+
clearTimeout(entry.timer);
|
|
264
|
+
this.#abandoned.set(id, { folder: entry.folder, gen: entry.gen, op: entry.op });
|
|
265
|
+
}
|
|
266
|
+
#nextGeneration(folder) {
|
|
267
|
+
const gen = this.generationOf(folder) + 1;
|
|
268
|
+
this.#generations.set(folder, gen);
|
|
269
|
+
this.#handles.delete(folder);
|
|
270
|
+
return gen;
|
|
271
|
+
}
|
|
272
|
+
/** Remembers a file the folder's current helper opened; one an older helper opened went with that helper. */
|
|
273
|
+
#hold(folder, gen, handle) {
|
|
274
|
+
if (gen !== this.generationOf(folder))
|
|
275
|
+
return;
|
|
276
|
+
let held = this.#handles.get(folder);
|
|
277
|
+
if (held?.gen !== gen) {
|
|
278
|
+
held = { gen, open: new Set() };
|
|
279
|
+
this.#handles.set(folder, held);
|
|
280
|
+
}
|
|
281
|
+
held.open.add(handle);
|
|
282
|
+
}
|
|
283
|
+
/**
|
|
284
|
+
* A `read` or `close` of a handle that the folder's current helper did not give: `EBADF` without a call, since a
|
|
285
|
+
* new helper may hold another file under the same number. With `gen`, a handle of an older generation stays stale
|
|
286
|
+
* even when the current helper gave the same number again.
|
|
287
|
+
*/
|
|
288
|
+
#staleHandle(folder, op, args, gen) {
|
|
289
|
+
if (op !== 'read' && op !== 'close')
|
|
290
|
+
return null;
|
|
291
|
+
const handle = args.handle;
|
|
292
|
+
const current = this.generationOf(folder);
|
|
293
|
+
const held = this.#handles.get(folder);
|
|
294
|
+
if ((gen ?? current) === current && held?.gen === current && held.open.has(handle)) {
|
|
295
|
+
if (op === 'close')
|
|
296
|
+
held.open.delete(handle);
|
|
297
|
+
return null;
|
|
298
|
+
}
|
|
299
|
+
const error = Object.assign(new Error(`EBADF: bad file descriptor, ${op}`), {
|
|
300
|
+
code: 'EBADF', syscall: op,
|
|
301
|
+
});
|
|
302
|
+
return { kind: 'fs-error', error };
|
|
303
|
+
}
|
|
304
|
+
#settle(id, entry, answer) {
|
|
305
|
+
this.#waiting.delete(id);
|
|
306
|
+
if (entry.timer !== null)
|
|
307
|
+
clearTimeout(entry.timer);
|
|
308
|
+
const handle = openedHandle(entry.op, answer);
|
|
309
|
+
if (handle !== null)
|
|
310
|
+
this.#hold(entry.folder, entry.gen, handle);
|
|
311
|
+
entry.answer = answer;
|
|
312
|
+
entry.resolve?.(answer);
|
|
313
|
+
}
|
|
314
|
+
}
|