@k-electron/k-bench 0.0.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/LICENSE +21 -0
- package/README.md +69 -2
- package/dist/js/scripts/command-lib.js +56 -0
- package/dist/js/scripts/install-lib.js +187 -0
- package/dist/js/scripts/install.js +233 -0
- package/dist/js/scripts/k-bench.js +53 -0
- package/dist/js/scripts/status.js +178 -0
- package/dist/js/scripts/tailscale-serve.js +135 -0
- package/dist/js/scripts/uninstall.js +150 -0
- package/dist/js/src/server/access-guard.js +63 -0
- package/dist/js/src/server/app.js +122 -0
- package/dist/js/src/server/attachments.js +273 -0
- package/dist/js/src/server/config.js +42 -0
- package/dist/js/src/server/directories.js +34 -0
- package/dist/js/src/server/events.js +31 -0
- package/dist/js/src/server/main.js +42 -0
- package/dist/js/src/server/naming.js +9 -0
- package/dist/js/src/server/reconciler.js +41 -0
- package/dist/js/src/server/server.js +86 -0
- package/dist/js/src/server/service.js +217 -0
- package/dist/js/src/server/state-feed.js +115 -0
- package/dist/js/src/server/static.js +46 -0
- package/dist/js/src/server/store.js +127 -0
- package/dist/js/src/server/terminal.js +64 -0
- package/dist/js/src/server/tmux.js +323 -0
- package/dist/js/src/shared/terminal-protocol.js +67 -0
- package/dist/web/assets/index-BeaoLAfY.css +2 -0
- package/dist/web/assets/index-rujAJZxv.js +68 -0
- package/dist/web/index.html +13 -0
- package/package.json +91 -3
- package/scripts/fix-node-pty.mjs +21 -0
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
/** A terminal dimension a pty can take: a whole number from 1 to 999. */
|
|
2
|
+
function isDimension(value) {
|
|
3
|
+
return Number.isInteger(value) && value > 0 && value < 1000;
|
|
4
|
+
}
|
|
5
|
+
const DEFAULT_SIZE = { cols: 80, rows: 24 };
|
|
6
|
+
/** How long a stop waits for detached tmux clients to exit before killing them outright. */
|
|
7
|
+
const CLIENT_EXIT_TIMEOUT_MS = 3_000;
|
|
8
|
+
/** How long a stop then waits for killed tmux clients to exit before giving up on them. */
|
|
9
|
+
const CLIENT_KILL_TIMEOUT_MS = 1_000;
|
|
10
|
+
/**
|
|
11
|
+
* Every browser terminal's life, from open to drained: looking up the Session, starting a
|
|
12
|
+
* tmux client for it, relaying input and output, sizing the window to whoever typed last,
|
|
13
|
+
* and detaching. `stop` drains them all.
|
|
14
|
+
*/
|
|
15
|
+
export class Attachments {
|
|
16
|
+
context;
|
|
17
|
+
/** Every terminal that is not yet gone. */
|
|
18
|
+
terminals = new Set();
|
|
19
|
+
stopping;
|
|
20
|
+
constructor(tmux, sessions) {
|
|
21
|
+
/** Per Session, the terminal the window was last sized for (see `writeSizedToTyper`). */
|
|
22
|
+
const lastTyper = new Map();
|
|
23
|
+
this.context = {
|
|
24
|
+
tmux,
|
|
25
|
+
sessions,
|
|
26
|
+
lastTyper,
|
|
27
|
+
forget: (terminal) => {
|
|
28
|
+
this.terminals.delete(terminal);
|
|
29
|
+
if (lastTyper.get(terminal.sessionId) === terminal) {
|
|
30
|
+
lastTyper.delete(terminal.sessionId);
|
|
31
|
+
}
|
|
32
|
+
},
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Opens a terminal on the Session for `viewer`, with the viewer's size (80 columns or 24
|
|
37
|
+
* rows in place of a dimension that is not a whole number from 1 to 999). Returns at once; the Session is looked up and attached in the background.
|
|
38
|
+
* If there is nothing to attach to, or the server is stopping, the viewer is ended.
|
|
39
|
+
*/
|
|
40
|
+
attach(sessionId, size, viewer) {
|
|
41
|
+
const terminal = new Terminal(this.context, sessionId, size, viewer);
|
|
42
|
+
if (this.stopping) {
|
|
43
|
+
terminal.end("server-stopping");
|
|
44
|
+
}
|
|
45
|
+
else {
|
|
46
|
+
this.terminals.add(terminal);
|
|
47
|
+
void terminal.open();
|
|
48
|
+
}
|
|
49
|
+
return terminal;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Ends every terminal; their tmux clients detach and the Sessions keep running. From the
|
|
53
|
+
* first call on, `attach` ends its viewer at once. Resolves once no tmux client this module
|
|
54
|
+
* started is running or will start, so tmux can then be killed without a client racing it
|
|
55
|
+
* (a tmux client that connects after that can start a fresh tmux server). Idempotent.
|
|
56
|
+
*/
|
|
57
|
+
stop() {
|
|
58
|
+
// Assigned before any terminal is ended, so a viewer that reattaches from its `end` is
|
|
59
|
+
// already refused.
|
|
60
|
+
this.stopping ??= Promise.resolve().then(() => this.drain());
|
|
61
|
+
return this.stopping;
|
|
62
|
+
}
|
|
63
|
+
async drain() {
|
|
64
|
+
const draining = [...this.terminals];
|
|
65
|
+
for (const terminal of draining)
|
|
66
|
+
terminal.end("server-stopping");
|
|
67
|
+
const gone = Promise.allSettled(draining.map((terminal) => terminal.gone));
|
|
68
|
+
if (await settlesWithin(gone, CLIENT_EXIT_TIMEOUT_MS))
|
|
69
|
+
return;
|
|
70
|
+
for (const terminal of draining)
|
|
71
|
+
terminal.kill();
|
|
72
|
+
await settlesWithin(gone, CLIENT_KILL_TIMEOUT_MS);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
class Terminal {
|
|
76
|
+
sessionId;
|
|
77
|
+
/** Settles when the terminal is gone. */
|
|
78
|
+
gone;
|
|
79
|
+
context;
|
|
80
|
+
viewer;
|
|
81
|
+
phase = "looking-up";
|
|
82
|
+
/** The viewer has been told the terminal ended, or has left: it is told nothing more. */
|
|
83
|
+
viewerDone = false;
|
|
84
|
+
size;
|
|
85
|
+
client;
|
|
86
|
+
/** Input sent before the tmux client was attached, in order. */
|
|
87
|
+
pendingInput = [];
|
|
88
|
+
/** Writes run one at a time, so waiting for tmux to resize never reorders input. */
|
|
89
|
+
writes = Promise.resolve();
|
|
90
|
+
markGone;
|
|
91
|
+
constructor(context, sessionId, size, viewer) {
|
|
92
|
+
this.context = context;
|
|
93
|
+
this.sessionId = sessionId;
|
|
94
|
+
this.viewer = viewer;
|
|
95
|
+
this.size = {
|
|
96
|
+
cols: isDimension(size.cols) ? size.cols : DEFAULT_SIZE.cols,
|
|
97
|
+
rows: isDimension(size.rows) ? size.rows : DEFAULT_SIZE.rows,
|
|
98
|
+
};
|
|
99
|
+
this.gone = new Promise((resolve) => {
|
|
100
|
+
this.markGone = resolve;
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
async open() {
|
|
104
|
+
let running;
|
|
105
|
+
try {
|
|
106
|
+
running = await this.context.sessions.hasRunningShell(this.sessionId);
|
|
107
|
+
}
|
|
108
|
+
catch (error) {
|
|
109
|
+
if (this.phase !== "looking-up")
|
|
110
|
+
return;
|
|
111
|
+
console.error(`terminal for Session ${this.sessionId} failed to look it up`, error);
|
|
112
|
+
return this.end("failed");
|
|
113
|
+
}
|
|
114
|
+
// The viewer left, or the module is stopping, while the Session was being looked up:
|
|
115
|
+
// a tmux client started now would outlive them.
|
|
116
|
+
if (this.phase !== "looking-up")
|
|
117
|
+
return;
|
|
118
|
+
if (!running)
|
|
119
|
+
return this.end("session-ended");
|
|
120
|
+
try {
|
|
121
|
+
this.client = this.context.tmux.spawnClient(this.sessionId, this.size);
|
|
122
|
+
}
|
|
123
|
+
catch (error) {
|
|
124
|
+
console.error(`terminal for Session ${this.sessionId} failed to attach`, error);
|
|
125
|
+
return this.end("failed");
|
|
126
|
+
}
|
|
127
|
+
this.phase = "attached";
|
|
128
|
+
this.client.onData((data) => {
|
|
129
|
+
if (this.phase === "attached")
|
|
130
|
+
this.viewer.show(data);
|
|
131
|
+
});
|
|
132
|
+
// The shell ended, or the Session was deleted (which kills its shell), or it detached.
|
|
133
|
+
this.client.onExit(() => {
|
|
134
|
+
if (this.phase === "attached")
|
|
135
|
+
this.end("session-ended");
|
|
136
|
+
this.becomeGone();
|
|
137
|
+
});
|
|
138
|
+
for (const { data, automatic } of this.pendingInput.splice(0)) {
|
|
139
|
+
this.input(data, { automatic });
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
input(data, { automatic = false } = {}) {
|
|
143
|
+
if (data === "")
|
|
144
|
+
return;
|
|
145
|
+
if (this.phase === "looking-up")
|
|
146
|
+
this.pendingInput.push({ data, automatic });
|
|
147
|
+
else if (this.phase === "attached") {
|
|
148
|
+
const write = automatic
|
|
149
|
+
? () => this.write(data)
|
|
150
|
+
: () => this.writeSizedToTyper(data);
|
|
151
|
+
// Nothing in a write throws; the catch keeps one that did from stopping all the rest.
|
|
152
|
+
this.writes = this.writes.then(write).catch(() => { });
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
resize(cols, rows) {
|
|
156
|
+
if (!isDimension(cols) || !isDimension(rows))
|
|
157
|
+
return;
|
|
158
|
+
this.size = { cols, rows };
|
|
159
|
+
if (this.phase === "attached")
|
|
160
|
+
this.ignoringExitedPty((client) => client.resize(cols, rows));
|
|
161
|
+
}
|
|
162
|
+
detach() {
|
|
163
|
+
this.viewerDone = true;
|
|
164
|
+
this.leave();
|
|
165
|
+
}
|
|
166
|
+
/** Lets go of the tmux client, and tells the viewer why the terminal ended (once). */
|
|
167
|
+
end(reason) {
|
|
168
|
+
// Let go first, so a viewer that throws cannot keep a tmux client running.
|
|
169
|
+
this.leave();
|
|
170
|
+
if (this.viewerDone)
|
|
171
|
+
return;
|
|
172
|
+
this.viewerDone = true;
|
|
173
|
+
try {
|
|
174
|
+
this.viewer.end(reason);
|
|
175
|
+
}
|
|
176
|
+
catch (error) {
|
|
177
|
+
console.error(`terminal for Session ${this.sessionId} failed to end its viewer`, error);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
/** Kills a tmux client that would not detach. */
|
|
181
|
+
kill() {
|
|
182
|
+
if (this.phase === "detaching")
|
|
183
|
+
this.ignoringExitedPty((c) => c.kill("SIGKILL"));
|
|
184
|
+
}
|
|
185
|
+
leave() {
|
|
186
|
+
if (this.phase === "looking-up")
|
|
187
|
+
this.becomeGone();
|
|
188
|
+
else if (this.phase === "attached") {
|
|
189
|
+
this.phase = "detaching";
|
|
190
|
+
this.ignoringExitedPty((client) => client.kill());
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
becomeGone() {
|
|
194
|
+
if (this.phase === "gone")
|
|
195
|
+
return;
|
|
196
|
+
this.phase = "gone";
|
|
197
|
+
this.pendingInput = [];
|
|
198
|
+
this.context.forget(this);
|
|
199
|
+
this.markGone();
|
|
200
|
+
}
|
|
201
|
+
/** Writes to the tmux client only while it is attached; a gone pty must not be written. */
|
|
202
|
+
write(data) {
|
|
203
|
+
if (this.phase === "attached")
|
|
204
|
+
this.ignoringExitedPty((client) => client.write(data));
|
|
205
|
+
}
|
|
206
|
+
/**
|
|
207
|
+
* The pty can close a moment before its exit is reported, and then refuses writes, resizes
|
|
208
|
+
* and signals. That is not an error: the exit, already on its way, ends the terminal.
|
|
209
|
+
*/
|
|
210
|
+
ignoringExitedPty(use) {
|
|
211
|
+
if (!this.client)
|
|
212
|
+
return;
|
|
213
|
+
try {
|
|
214
|
+
use(this.client);
|
|
215
|
+
}
|
|
216
|
+
catch {
|
|
217
|
+
// The tmux client is exiting.
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
/**
|
|
221
|
+
* The window takes the size of whoever typed last. tmux (`window-size latest`) resizes the
|
|
222
|
+
* window to the client that last sent a key, but only after it has read that key, and the
|
|
223
|
+
* shell can read the same key first, and the shell's terminal follows the window only some
|
|
224
|
+
* time later. So when a different terminal starts typing, its first character goes in alone
|
|
225
|
+
* and the rest waits until the shell sees that terminal's size, or half a second has gone
|
|
226
|
+
* by.
|
|
227
|
+
*/
|
|
228
|
+
async writeSizedToTyper(data) {
|
|
229
|
+
const { lastTyper, tmux } = this.context;
|
|
230
|
+
if (lastTyper.get(this.sessionId) === this) {
|
|
231
|
+
return this.write(data);
|
|
232
|
+
}
|
|
233
|
+
if (this.phase !== "attached")
|
|
234
|
+
return;
|
|
235
|
+
lastTyper.set(this.sessionId, this);
|
|
236
|
+
// Against this terminal's size now, not when the key arrived: a resize during the wait
|
|
237
|
+
// changes the size the shell will get.
|
|
238
|
+
const isThisSize = (a) => a.cols === this.size.cols && a.rows === this.size.rows;
|
|
239
|
+
try {
|
|
240
|
+
if (isThisSize(await tmux.shellSize(this.sessionId)))
|
|
241
|
+
return this.write(data);
|
|
242
|
+
// An escape sequence must not be cut, so it goes in whole.
|
|
243
|
+
const head = data.startsWith("\x1b")
|
|
244
|
+
? data
|
|
245
|
+
: String.fromCodePoint(data.codePointAt(0) ?? 0);
|
|
246
|
+
this.write(head);
|
|
247
|
+
for (let i = 0; i < 50 && this.phase === "attached"; i++) {
|
|
248
|
+
await new Promise((resolve) => setTimeout(resolve, 10));
|
|
249
|
+
if (isThisSize(await tmux.shellSize(this.sessionId)))
|
|
250
|
+
break;
|
|
251
|
+
}
|
|
252
|
+
if (data.length > head.length)
|
|
253
|
+
this.write(data.slice(head.length));
|
|
254
|
+
}
|
|
255
|
+
catch {
|
|
256
|
+
// The Session went away while we were waiting; the tmux client's exit reports that.
|
|
257
|
+
this.write(data);
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
/** Whether `promise` settles within `ms`. */
|
|
262
|
+
async function settlesWithin(promise, ms) {
|
|
263
|
+
let timer;
|
|
264
|
+
const timedOut = new Promise((resolve) => {
|
|
265
|
+
timer = setTimeout(() => resolve(false), ms);
|
|
266
|
+
});
|
|
267
|
+
try {
|
|
268
|
+
return await Promise.race([promise.then(() => true), timedOut]);
|
|
269
|
+
}
|
|
270
|
+
finally {
|
|
271
|
+
clearTimeout(timer);
|
|
272
|
+
}
|
|
273
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { homedir } from "node:os";
|
|
2
|
+
import { join, resolve } from "node:path";
|
|
3
|
+
const PRESETS = {
|
|
4
|
+
installed: {
|
|
5
|
+
dataDir: join(homedir(), "Library", "Application Support", "k-bench"),
|
|
6
|
+
tmuxSocket: "k-bench",
|
|
7
|
+
port: 7680,
|
|
8
|
+
},
|
|
9
|
+
dev: {
|
|
10
|
+
dataDir: resolve(".data"),
|
|
11
|
+
tmuxSocket: "k-bench-dev",
|
|
12
|
+
port: 7690,
|
|
13
|
+
},
|
|
14
|
+
};
|
|
15
|
+
function parsePort(value) {
|
|
16
|
+
if (value === undefined || value === "")
|
|
17
|
+
return undefined;
|
|
18
|
+
const port = /^\d+$/.test(value) ? Number(value) : Number.NaN;
|
|
19
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535) {
|
|
20
|
+
throw new Error(`K_BENCH_PORT must be a whole number from 1 to 65535, got "${value}"`);
|
|
21
|
+
}
|
|
22
|
+
return port;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Resolves the instance config. `K_BENCH_INSTANCE` picks the preset (`installed` or `dev`,
|
|
26
|
+
* default `dev`, so a stray run can never touch the Installed instance); each value can be
|
|
27
|
+
* overridden by its own variable.
|
|
28
|
+
*/
|
|
29
|
+
export function resolveConfig(env = process.env) {
|
|
30
|
+
const name = env.K_BENCH_INSTANCE ?? "dev";
|
|
31
|
+
if (name !== "installed" && name !== "dev") {
|
|
32
|
+
throw new Error(`K_BENCH_INSTANCE must be "installed" or "dev", got "${name}"`);
|
|
33
|
+
}
|
|
34
|
+
const preset = PRESETS[name];
|
|
35
|
+
return {
|
|
36
|
+
dataDir: resolve(env.K_BENCH_DATA_DIR ?? preset.dataDir),
|
|
37
|
+
tmuxSocket: env.K_BENCH_TMUX_SOCKET ?? preset.tmuxSocket,
|
|
38
|
+
port: parsePort(env.K_BENCH_PORT) ?? preset.port,
|
|
39
|
+
allowedLogin: env.K_BENCH_ALLOWED_LOGIN ?? "",
|
|
40
|
+
pickerRoot: resolve(env.K_BENCH_PICKER_ROOT ?? homedir()),
|
|
41
|
+
};
|
|
42
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { readdirSync, statSync } from "node:fs";
|
|
2
|
+
import { dirname, isAbsolute, join, resolve } from "node:path";
|
|
3
|
+
/** A path that cannot be listed: not absolute, missing, or not a folder. */
|
|
4
|
+
export class DirectoryError extends Error {
|
|
5
|
+
}
|
|
6
|
+
function isDirectory(path) {
|
|
7
|
+
try {
|
|
8
|
+
return statSync(path).isDirectory();
|
|
9
|
+
}
|
|
10
|
+
catch {
|
|
11
|
+
return false;
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
/** The subfolders of `path`, for the folder picker. Symlinks to folders count as folders. */
|
|
15
|
+
export function listDirectories(path) {
|
|
16
|
+
if (!isAbsolute(path))
|
|
17
|
+
throw new DirectoryError(`Path must be absolute: ${path}`);
|
|
18
|
+
const folder = resolve(path);
|
|
19
|
+
if (!isDirectory(folder))
|
|
20
|
+
throw new DirectoryError(`Folder does not exist: ${folder}`);
|
|
21
|
+
let names;
|
|
22
|
+
try {
|
|
23
|
+
names = readdirSync(folder);
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
throw new DirectoryError(`Cannot read folder: ${folder}`);
|
|
27
|
+
}
|
|
28
|
+
const directories = names
|
|
29
|
+
.filter((name) => !name.startsWith(".") && isDirectory(join(folder, name)))
|
|
30
|
+
.sort((a, b) => a.localeCompare(b, "en", { sensitivity: "base" }))
|
|
31
|
+
.map((name) => ({ name, path: join(folder, name) }));
|
|
32
|
+
const parent = dirname(folder);
|
|
33
|
+
return { path: folder, ...(parent === folder ? {} : { parent }), directories };
|
|
34
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { WebSocketServer } from "ws";
|
|
2
|
+
const EVENTS_PATH = "/api/events";
|
|
3
|
+
/**
|
|
4
|
+
* The events WebSocket, one per browser tab: `GET /api/events`. The server sends the current
|
|
5
|
+
* state as a JSON text frame on connect, then a fresh full snapshot whenever state changes.
|
|
6
|
+
* Snapshots rather than diffs, so a client can never drift. Clients send nothing.
|
|
7
|
+
*/
|
|
8
|
+
export class EventSockets {
|
|
9
|
+
feed;
|
|
10
|
+
wss = new WebSocketServer({ noServer: true });
|
|
11
|
+
constructor(feed) {
|
|
12
|
+
this.feed = feed;
|
|
13
|
+
}
|
|
14
|
+
static match(request) {
|
|
15
|
+
return new URL(request.url ?? "/", "http://localhost").pathname === EVENTS_PATH;
|
|
16
|
+
}
|
|
17
|
+
handleUpgrade(request, socket, head) {
|
|
18
|
+
this.wss.handleUpgrade(request, socket, head, (ws) => {
|
|
19
|
+
const unsubscribe = this.feed.subscribe((snapshot) => {
|
|
20
|
+
if (ws.readyState === ws.OPEN)
|
|
21
|
+
ws.send(snapshot);
|
|
22
|
+
});
|
|
23
|
+
ws.on("close", unsubscribe);
|
|
24
|
+
ws.on("error", () => ws.terminate());
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
closeAll() {
|
|
28
|
+
for (const client of this.wss.clients)
|
|
29
|
+
client.terminate();
|
|
30
|
+
}
|
|
31
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
2
|
+
import { resolve } from "node:path";
|
|
3
|
+
import { resolveConfig } from "./config.js";
|
|
4
|
+
import { startServer } from "./server.js";
|
|
5
|
+
const config = resolveConfig();
|
|
6
|
+
if (!config.allowedLogin) {
|
|
7
|
+
console.warn("K_BENCH_ALLOWED_LOGIN is not set: every request will be refused with 403 until it is.");
|
|
8
|
+
}
|
|
9
|
+
// A production build (`pnpm build`) is served by this server alone. In `pnpm dev` there is
|
|
10
|
+
// usually none, and Vite serves the front end instead.
|
|
11
|
+
const webDir = resolve("dist/web");
|
|
12
|
+
const server = await startServer(config, {
|
|
13
|
+
webDir: existsSync(webDir) ? webDir : undefined,
|
|
14
|
+
});
|
|
15
|
+
console.log(`k-bench ${describeBuild()} listening on http://127.0.0.1:${server.port} (tmux socket "${config.tmuxSocket}", data ${config.dataDir})`);
|
|
16
|
+
function readJson(file) {
|
|
17
|
+
try {
|
|
18
|
+
return JSON.parse(readFileSync(resolve(file), "utf8"));
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
return {};
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Which version, and from a checkout which commit, is running. `k-bench install` records
|
|
26
|
+
* both in build-info.json; without it (a checkout, or the package run in place) the version
|
|
27
|
+
* is read from package.json.
|
|
28
|
+
*/
|
|
29
|
+
function describeBuild() {
|
|
30
|
+
const info = readJson("build-info.json");
|
|
31
|
+
const version = info.version ?? readJson("package.json").version ?? "(unknown version)";
|
|
32
|
+
const commit = info.commit
|
|
33
|
+
? ` commit ${String(info.commit).slice(0, 7)}${info.dirty ? "+uncommitted" : ""}`
|
|
34
|
+
: "";
|
|
35
|
+
return `${version}${commit} (${info.installedAt ? `installed ${info.installedAt}` : "not installed"})`;
|
|
36
|
+
}
|
|
37
|
+
for (const signal of ["SIGINT", "SIGTERM"]) {
|
|
38
|
+
process.once(signal, () => {
|
|
39
|
+
// Stopping the server leaves tmux, and so every Session, running.
|
|
40
|
+
void server.stop().then(() => process.exit(0));
|
|
41
|
+
});
|
|
42
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Compares the store with what is alive in tmux (ADR-0002). A Session in the store with no
|
|
3
|
+
* live tmux session is Stopped, which callers learn from the returned live ids. A live tmux
|
|
4
|
+
* session on this instance's socket with no store row is an orphan and is killed.
|
|
5
|
+
*/
|
|
6
|
+
export class Reconciler {
|
|
7
|
+
store;
|
|
8
|
+
tmux;
|
|
9
|
+
/** Sessions whose tmux session exists before their store row does. Never orphans. */
|
|
10
|
+
starting = new Set();
|
|
11
|
+
constructor(store, tmux) {
|
|
12
|
+
this.store = store;
|
|
13
|
+
this.tmux = tmux;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Runs `start`, which brings the tmux session for `id` to life, without letting a
|
|
17
|
+
* concurrent `reconcile()` mistake it for an orphan. The store row for `id` must exist by
|
|
18
|
+
* the time `start` resolves.
|
|
19
|
+
*/
|
|
20
|
+
async whileStarting(id, start) {
|
|
21
|
+
this.starting.add(id);
|
|
22
|
+
try {
|
|
23
|
+
return await start();
|
|
24
|
+
}
|
|
25
|
+
finally {
|
|
26
|
+
this.starting.delete(id);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
/** Kills orphans and returns the Sessions that are alive, by id. */
|
|
30
|
+
async reconcile() {
|
|
31
|
+
const live = new Map((await this.tmux.listSessions()).map((s) => [s.id, s]));
|
|
32
|
+
for (const id of [...live.keys()]) {
|
|
33
|
+
// Order matters: a Session no longer starting already has its store row.
|
|
34
|
+
if (this.starting.has(id) || this.store.getSession(id))
|
|
35
|
+
continue;
|
|
36
|
+
live.delete(id);
|
|
37
|
+
await this.tmux.killSession(id);
|
|
38
|
+
}
|
|
39
|
+
return live;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { serve } from "@hono/node-server";
|
|
2
|
+
import { AccessGuard } from "./access-guard.js";
|
|
3
|
+
import { createApp } from "./app.js";
|
|
4
|
+
import { Attachments } from "./attachments.js";
|
|
5
|
+
import { EventSockets } from "./events.js";
|
|
6
|
+
import { Service } from "./service.js";
|
|
7
|
+
import { StateFeed } from "./state-feed.js";
|
|
8
|
+
import { Store } from "./store.js";
|
|
9
|
+
import { TerminalSockets } from "./terminal.js";
|
|
10
|
+
import { TmuxDriver } from "./tmux.js";
|
|
11
|
+
/** Boots a server for one instance config. Used by `main.ts` and by the test harness. */
|
|
12
|
+
export async function startServer(config, options = {}) {
|
|
13
|
+
const store = new Store(config.dataDir);
|
|
14
|
+
const tmux = new TmuxDriver(config.tmuxSocket);
|
|
15
|
+
const service = new Service(store, tmux);
|
|
16
|
+
// Anything on the socket that the store does not know is left over: clean it up first.
|
|
17
|
+
await service.reconcile();
|
|
18
|
+
// A tmux server that outlived the previous k-bench gets this version's hooks.
|
|
19
|
+
await tmux.configure();
|
|
20
|
+
const attachments = new Attachments(tmux, service);
|
|
21
|
+
const terminals = new TerminalSockets(attachments);
|
|
22
|
+
const feed = new StateFeed(() => service.getState(), {
|
|
23
|
+
intervalMs: options.statePollMs,
|
|
24
|
+
});
|
|
25
|
+
const events = new EventSockets(feed);
|
|
26
|
+
const bells = tmux.watchBells(() => feed.notify());
|
|
27
|
+
// The guard sits in front of everything the server answers, so no route or static file
|
|
28
|
+
// (now or added later) can be reached without the allowed login.
|
|
29
|
+
const guard = new AccessGuard(config.allowedLogin);
|
|
30
|
+
const app = createApp(service, {
|
|
31
|
+
webDir: options.webDir,
|
|
32
|
+
pickerRoot: config.pickerRoot,
|
|
33
|
+
onMutation: () => feed.notify(),
|
|
34
|
+
});
|
|
35
|
+
// Requests whose handlers are still running. A handler outlives its connection (closing
|
|
36
|
+
// the sockets does not cancel it), so stopping waits for them before the database closes.
|
|
37
|
+
const inFlight = new Set();
|
|
38
|
+
const guarded = guard.wrapFetch(app.fetch);
|
|
39
|
+
const server = serve({
|
|
40
|
+
fetch: (request) => {
|
|
41
|
+
const handled = Promise.resolve(guarded(request));
|
|
42
|
+
inFlight.add(handled);
|
|
43
|
+
const forget = () => inFlight.delete(handled);
|
|
44
|
+
handled.then(forget, forget);
|
|
45
|
+
return handled;
|
|
46
|
+
},
|
|
47
|
+
port: config.port,
|
|
48
|
+
hostname: "127.0.0.1",
|
|
49
|
+
});
|
|
50
|
+
server.on("upgrade", guard.wrapUpgrade((request, socket, head) => {
|
|
51
|
+
if (EventSockets.match(request)) {
|
|
52
|
+
events.handleUpgrade(request, socket, head);
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
const terminal = TerminalSockets.match(request);
|
|
56
|
+
if (terminal === undefined) {
|
|
57
|
+
socket.destroy();
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
terminals.handleUpgrade(request, socket, head, terminal);
|
|
61
|
+
}));
|
|
62
|
+
await new Promise((resolve, reject) => {
|
|
63
|
+
server.once("listening", resolve);
|
|
64
|
+
server.once("error", reject);
|
|
65
|
+
});
|
|
66
|
+
let stopping;
|
|
67
|
+
const stop = () => {
|
|
68
|
+
stopping ??= (async () => {
|
|
69
|
+
await bells.stop();
|
|
70
|
+
events.closeAll();
|
|
71
|
+
// From here on no tmux client this server started is running or starting.
|
|
72
|
+
await attachments.stop();
|
|
73
|
+
terminals.closeAll();
|
|
74
|
+
await new Promise((resolve) => {
|
|
75
|
+
server.close(() => resolve());
|
|
76
|
+
server.closeAllConnections();
|
|
77
|
+
});
|
|
78
|
+
// Nothing may read the database once it is closed: let in-flight reads finish first.
|
|
79
|
+
await feed.close();
|
|
80
|
+
await Promise.allSettled([...inFlight]);
|
|
81
|
+
store.close();
|
|
82
|
+
})();
|
|
83
|
+
return stopping;
|
|
84
|
+
};
|
|
85
|
+
return { port: server.address().port, stop };
|
|
86
|
+
}
|