@openchamber/web 2.0.1 → 2.0.2
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/dist/assets/{CodeMirrorCommentWidgets-zm3C1FvM.js → CodeMirrorCommentWidgets-CmKmyb9T.js} +1 -1
- package/dist/assets/{DiffView-DNExNi1z.js → DiffView-8-PFpZ2p.js} +1 -1
- package/dist/assets/{FilesView-DUCLmHBi.js → FilesView-0Ie20mEk.js} +9 -9
- package/dist/assets/{GitView-Bz9z6gZA.js → GitView-DNUSu00w.js} +1 -1
- package/dist/assets/{GuestAttachDialog-UGp4KDlK.js → GuestAttachDialog-Cv6QzjHC.js} +1 -1
- package/dist/assets/{GuestSurfacePane-B3pdB_2u.js → GuestSurfacePane-Bt3jB_Ye.js} +1 -1
- package/dist/assets/{JsonTreeView-7lVecnZl.js → JsonTreeView-BlyHTRhM.js} +1 -1
- package/dist/assets/{LinearIssuesView-CTGRS9Vq.js → LinearIssuesView-CSl2MUfA.js} +1 -1
- package/dist/assets/MarkdownImageGallery-2UXJF-5B.js +1 -0
- package/dist/assets/MarkdownRendererImpl-DVHqZoug.js +12 -0
- package/dist/assets/{OnboardingScreen-CBx6cXPP.js → OnboardingScreen-CIdXJpfc.js} +1 -1
- package/dist/assets/{PatchDiff-D7VVpR_l.js → PatchDiff-ByvnbG5T.js} +1 -1
- package/dist/assets/{PierreDiffViewer-Gbfks1pk.js → PierreDiffViewer-BXieg0mH.js} +1 -1
- package/dist/assets/{PlanView-CPSK0x97.js → PlanView-DEIi3Q7M.js} +3 -3
- package/dist/assets/PluginPane-BEPUWVho.js +3 -0
- package/dist/assets/{SettingsView-Dql7z6Ww.js → SettingsView-CiNh-RbW.js} +16 -16
- package/dist/assets/{SettingsWindow-D6oi-UmV.js → SettingsWindow-BIz224xs.js} +1 -1
- package/dist/assets/{SubmoduleDiffSummary-BXA0FAWj.js → SubmoduleDiffSummary-CXKmlps9.js} +1 -1
- package/dist/assets/{ToolOutputDialog-BQJsSbDm.js → ToolOutputDialog-BsgAK8xu.js} +6 -6
- package/dist/assets/{ToolPartDiffPreview-FY9w0TVT.js → ToolPartDiffPreview-vdPObXOf.js} +1 -1
- package/dist/assets/{VirtualizedFileDiff-B9YhAya5.js → VirtualizedFileDiff-BkFNKWS5.js} +1 -1
- package/dist/assets/{WalkthroughView-CmFgOUFN.js → WalkthroughView-6oE-MuDL.js} +2 -2
- package/dist/assets/{appThemeRegistry-BebxalUt.js → appThemeRegistry-aHUNHoqP.js} +1 -1
- package/dist/assets/{commitAndPush-Wfxng_IK.js → commitAndPush-Bon9r94r.js} +1 -1
- package/dist/assets/{computeVirtualFileMetrics-BCOqgixN.js → computeVirtualFileMetrics-DKqr_1AQ.js} +1 -1
- package/dist/assets/de-CgAJ51z7.js +10 -0
- package/dist/assets/es-zGi_ravM.js +16 -0
- package/dist/assets/fr-CPfogrWx.js +14 -0
- package/dist/assets/index-CHfphYL3.js +41 -0
- package/dist/assets/{index-3TiDNtfN.js → index-DpFttslC.js} +1 -1
- package/dist/assets/index-DvMJ3w6V.css +1 -0
- package/dist/assets/{isDiffPlainText-DnDYQmWK.js → isDiffPlainText-kzAgpIgi.js} +1 -1
- package/dist/assets/{isFilePlainText-BA_AHX7d.js → isFilePlainText-Uj6y-jzz.js} +1 -1
- package/dist/assets/ja-DMk6wd-U.js +16 -0
- package/dist/assets/ko-BFpzJ8jc.js +16 -0
- package/dist/assets/{main-DtUmJp9B.js → main-CbfMxn-I.js} +2 -2
- package/dist/assets/main-anyZFMIs.js +896 -0
- package/dist/assets/{markdownCore-BSnlUXBf.js → markdownCore-CmM47cAE.js} +5 -5
- package/dist/assets/{miniChat-BYfLUnDK.js → miniChat-CiAKBC10.js} +2 -2
- package/dist/assets/{mobile-DH3hI6gd.js → mobile-CsT4sJwC.js} +2 -2
- package/dist/assets/{patchFileDiff--L7lt_GZ.js → patchFileDiff-DeaE08W0.js} +1 -1
- package/dist/assets/{pl-BkI_xHqz.js → pl-VdRPcZrB.js} +5 -5
- package/dist/assets/pt-BR-BRys_lOW.js +16 -0
- package/dist/assets/{renderElectronMiniChatApp-C7kpNW_-.js → renderElectronMiniChatApp-C5677jy0.js} +2 -2
- package/dist/assets/{renderMobileApp-i0nq7Dwy.js → renderMobileApp-D4dBBAqQ.js} +7 -7
- package/dist/assets/runtimeEndpointReset-5r0hkd-2.js +27 -0
- package/dist/assets/{scheduledTasksApi-Cy7uZCaI.js → scheduledTasksApi-BZCNJ588.js} +1 -1
- package/dist/assets/{shikiHighlight-D4vxipfr.js → shikiHighlight-BSUEa3yF.js} +1 -1
- package/dist/assets/{textMateThemeFromAppTheme-BYAHtJwQ.js → textMateThemeFromAppTheme-CsATFZIV.js} +1 -1
- package/dist/assets/tr-CA9ckNnm.js +7 -0
- package/dist/assets/uk-byjR-y8D.js +16 -0
- package/dist/assets/{useAppFontEffects-DHZ9-L30.js → useAppFontEffects-BWQZ5DeI.js} +153 -150
- package/dist/assets/{useInlineCommentController-CvpOMK-R.js → useInlineCommentController-DlFyVfBu.js} +1 -1
- package/dist/assets/{useRootScrollLock-DzNFi-fn.js → useRootScrollLock-Cp1eFoM2.js} +2 -2
- package/dist/assets/{vendor-codemirror-language-data-j3fhlwUM.js → vendor-codemirror-language-data-BwwommM0.js} +2 -2
- package/dist/assets/{web-components-BvHNFSEG.js → web-components-D3Yjr4Zx.js} +1 -1
- package/dist/assets/zh-CN-DRabgxdG.js +16 -0
- package/dist/assets/zh-TW-rbY5c9UK.js +16 -0
- package/dist/index.html +3 -3
- package/dist/mini-chat.html +3 -3
- package/dist/mobile.html +3 -3
- package/package.json +2 -2
- package/server/index.js +64 -0
- package/server/lib/event-stream/global-hub.js +23 -1
- package/server/lib/event-stream/global-hub.test.js +35 -0
- package/server/lib/event-stream/global-ws-bridge.js +3 -1
- package/server/lib/event-stream/upstream-reader.js +3 -2
- package/server/lib/opencode/DOCUMENTATION.md +6 -2
- package/server/lib/opencode/bootstrap-runtime.js +2 -1
- package/server/lib/opencode/config-entity-v2.test.js +27 -0
- package/server/lib/opencode/config-paths.test.js +12 -0
- package/server/lib/opencode/core-routes.js +17 -4
- package/server/lib/opencode/core-routes.test.js +26 -0
- package/server/lib/opencode/mcp.js +7 -2
- package/server/lib/opencode/project-directory-runtime.js +8 -0
- package/server/lib/opencode/project-directory-runtime.test.js +13 -0
- package/server/lib/opencode/proxy.js +38 -2
- package/server/lib/opencode/routes.js +18 -0
- package/server/lib/opencode/server-utils-runtime.js +5 -0
- package/server/lib/opencode/settings-helpers.js +3 -0
- package/server/lib/opencode/settings-helpers.test.js +1 -1
- package/server/lib/opencode/settings-registry.json +3 -0
- package/server/lib/opencode/shared.js +17 -2
- package/server/lib/opencode/shutdown-runtime.js +3 -0
- package/server/lib/opencode/watcher.js +3 -1
- package/server/lib/realtime-proxy.js +5 -1
- package/server/lib/realtime-proxy.test.js +29 -0
- package/server/lib/relay/tunnel-host.js +4 -1
- package/server/lib/relay/tunnel-host.test.js +11 -0
- package/server/lib/small-model/DOCUMENTATION.md +11 -10
- package/server/lib/small-model/index.js +27 -32
- package/server/lib/small-model/index.test.js +28 -16
- package/server/lib/spaces/DOCUMENTATION.md +381 -20
- package/server/lib/spaces/code-in-bait.js +145 -6
- package/server/lib/spaces/code-in.js +10 -150
- package/server/lib/spaces/code-in.test.js +7 -83
- package/server/lib/spaces/code-out.js +1819 -0
- package/server/lib/spaces/code-out.test.js +3945 -0
- package/server/lib/spaces/code-transfer.js +173 -0
- package/server/lib/spaces/command-stream.test.js +181 -0
- package/server/lib/spaces/dispatcher.js +670 -0
- package/server/lib/spaces/dispatcher.test.js +582 -0
- package/server/lib/spaces/gatekeeper-channel.js +2 -0
- package/server/lib/spaces/gatekeeper-channel.test.js +9 -3
- package/server/lib/spaces/gatekeeper-program.cjs +4 -1
- package/server/lib/spaces/gatekeeper-program.test.js +3 -0
- package/server/lib/spaces/hardening.js +20 -4
- package/server/lib/spaces/hardening.test.js +18 -3
- package/server/lib/spaces/host-git.js +7 -4
- package/server/lib/spaces/host-git.test.js +6 -2
- package/server/lib/spaces/host.js +304 -0
- package/server/lib/spaces/host.test.js +273 -0
- package/server/lib/spaces/journey.js +393 -0
- package/server/lib/spaces/journey.test.js +384 -0
- package/server/lib/spaces/layout.js +26 -2
- package/server/lib/spaces/manager.js +4 -3
- package/server/lib/spaces/manager.test.js +6 -0
- package/server/lib/spaces/places/code-out.docker.live.test.js +412 -0
- package/server/lib/spaces/places/contract-suite.js +36 -0
- package/server/lib/spaces/places/dispatcher.docker.live.test.js +296 -0
- package/server/lib/spaces/places/docker.js +15 -3
- package/server/lib/spaces/places/docker.test.js +33 -2
- package/server/lib/spaces/places/escape-suite.js +86 -14
- package/server/lib/spaces/places/memory-place.js +24 -1
- package/server/lib/spaces/places/registry.js +1 -1
- package/server/lib/spaces/places/server.docker.live.test.js +69 -33
- package/server/lib/spaces/places/sessions.docker.live.test.js +220 -0
- package/server/lib/spaces/routes.js +207 -0
- package/server/lib/spaces/routes.test.js +211 -0
- package/server/lib/spaces/run-command.js +261 -8
- package/server/lib/spaces/run-command.test.js +193 -3
- package/server/lib/spaces/space-events.js +153 -0
- package/server/lib/spaces/space-events.test.js +160 -0
- package/server/lib/spaces/space-records.js +98 -0
- package/server/lib/spaces/space-records.test.js +73 -0
- package/server/lib/spaces/space-sessions.js +210 -0
- package/server/lib/spaces/space-sessions.test.js +161 -0
- package/server/lib/spaces/websocket.js +329 -0
- package/server/lib/spaces/websocket.test.js +345 -0
- package/server/lib/ui-auth/ui-auth.js +8 -2
- package/server/lib/ui-auth/ui-auth.test.js +29 -0
- package/server/opencode-proxy.test.js +113 -0
- package/dist/assets/MarkdownImageGallery-DQk5adUs.js +0 -1
- package/dist/assets/MarkdownRendererImpl-DPF8fZpX.js +0 -12
- package/dist/assets/PluginPane-BIGsUx69.js +0 -3
- package/dist/assets/de-CMA45TC-.js +0 -10
- package/dist/assets/es-DPL4fBtl.js +0 -16
- package/dist/assets/fr-OHBKBseP.js +0 -14
- package/dist/assets/index-BLUZa5u0.js +0 -41
- package/dist/assets/index-Cm2rrq69.css +0 -1
- package/dist/assets/ja-DvX4WSRf.js +0 -16
- package/dist/assets/ko-BUcLd8YZ.js +0 -16
- package/dist/assets/main-B_jri4i-.js +0 -896
- package/dist/assets/pt-BR-7wFtQlV9.js +0 -16
- package/dist/assets/runtimeEndpointReset-CfEYbcCc.js +0 -27
- package/dist/assets/tr-TsD-AqEH.js +0 -7
- package/dist/assets/uk-B-qspCmD.js +0 -16
- package/dist/assets/zh-CN-DYuPJV5i.js +0 -16
- package/dist/assets/zh-TW-BX_2D_lV.js +0 -16
|
@@ -1,10 +1,12 @@
|
|
|
1
|
-
import { spawn } from 'node:child_process';
|
|
1
|
+
import { spawn, spawnSync } from 'node:child_process';
|
|
2
|
+
import { getEventListeners } from 'node:events';
|
|
2
3
|
import fs from 'node:fs';
|
|
3
4
|
import os from 'node:os';
|
|
4
5
|
import path from 'node:path';
|
|
5
6
|
|
|
6
7
|
import { afterEach, describe, expect, it } from 'vitest';
|
|
7
8
|
|
|
9
|
+
import { SpaceError } from './errors.js';
|
|
8
10
|
import { killLiveTrees, killProcessTree, liveTreeCount, runCommand } from './run-command.js';
|
|
9
11
|
|
|
10
12
|
const node = process.execPath;
|
|
@@ -96,6 +98,16 @@ describe('runCommand', () => {
|
|
|
96
98
|
});
|
|
97
99
|
});
|
|
98
100
|
|
|
101
|
+
// A failing `git apply --check` prints a line or two per path; its exit code is the answer.
|
|
102
|
+
it('keeps only the last bytes of each stream past the cap with keepTail, and still answers with the exit code', async () => {
|
|
103
|
+
const flood = 'for (let i = 0; i < 4000; i += 1) process.stderr.write(`line ${i}\\n`.padStart(100, "x")); process.stdout.write("out"); process.exitCode = 3;';
|
|
104
|
+
const done = await runCommand(node, ['-e', flood], { maxOutputBytes: 10_000, keepTail: true, timeoutMs: 20_000 });
|
|
105
|
+
expect(done.code).toBe(3);
|
|
106
|
+
expect(done.stdout).toBe('out');
|
|
107
|
+
expect(Buffer.byteLength(done.stderr)).toBe(10_000);
|
|
108
|
+
expect(done.stderr.endsWith(`${'line 3999\n'.padStart(100, 'x')}`)).toBe(true);
|
|
109
|
+
});
|
|
110
|
+
|
|
99
111
|
it('rejects when the executable does not exist', async () => {
|
|
100
112
|
await expect(runCommand('/nonexistent/openchamber-no-such-binary', ['version'])).rejects.toMatchObject({
|
|
101
113
|
code: 'command_spawn_failed',
|
|
@@ -230,11 +242,11 @@ const [pidFile, mode] = process.argv.slice(2);
|
|
|
230
242
|
if (mode === 'sigint') process.on('SIGINT', () => process.exit(130));
|
|
231
243
|
// An exit listener registered before ours that throws, as the serve command registers one earlier.
|
|
232
244
|
if (mode === 'throwing') process.on('exit', () => { throw new Error('an earlier exit listener'); });
|
|
233
|
-
runCommand(process.execPath, ['-e', ${JSON.stringify(parentScript)}], { killTree: true, timeoutMs: 120000 }).catch(() => {});
|
|
245
|
+
runCommand(process.execPath, ['-e', ${JSON.stringify(parentScript)}], { killTree: true, keepAtExit: mode === 'keep', timeoutMs: 120000 }).catch(() => {});
|
|
234
246
|
const ready = setInterval(() => {
|
|
235
247
|
if (!fs.existsSync(pidFile)) return;
|
|
236
248
|
clearInterval(ready);
|
|
237
|
-
if (mode === 'exit' || mode === 'throwing') process.exit(0);
|
|
249
|
+
if (mode === 'exit' || mode === 'throwing' || mode === 'keep') process.exit(0);
|
|
238
250
|
fs.writeFileSync(pidFile + '.ready', '');
|
|
239
251
|
setInterval(() => {}, 1000);
|
|
240
252
|
}, 50);
|
|
@@ -271,6 +283,77 @@ const ready = setInterval(() => {
|
|
|
271
283
|
expect(await waitFor(() => !isAlive(child) && !isAlive(grandchild), 5000)).toBe(true);
|
|
272
284
|
});
|
|
273
285
|
|
|
286
|
+
// `keepAtExit`, for `git apply`: killed in the middle it leaves a part written, so an exit leaves it.
|
|
287
|
+
// Windows has no such test: there libuv's job object ends the child with this process whatever we do.
|
|
288
|
+
it.skipIf(process.platform === 'win32')('leaves the tree of a keepAtExit child alive when the process leaves with process.exit', async () => {
|
|
289
|
+
const { child, grandchild } = await runWrapper('keep');
|
|
290
|
+
expect(isRealPid(child) && isRealPid(grandchild)).toBe(true);
|
|
291
|
+
expect(await waitFor(() => !isAlive(child) || !isAlive(grandchild), 1500)).toBe(false);
|
|
292
|
+
});
|
|
293
|
+
|
|
294
|
+
// The reviewer's probe: a `git apply` kept at exit whose smudge filter prints on stderr after the host
|
|
295
|
+
// left. Through a pipe to the dead host the print was SIGPIPE, and the apply stopped with files
|
|
296
|
+
// deleted; with the output in a file of its own it finishes, every file changed.
|
|
297
|
+
it.skipIf(process.platform === 'win32')('lets a keepAtExit git apply finish after the process left, while its filter prints', { timeout: 40_000 }, async () => {
|
|
298
|
+
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'openchamber-kept-apply-'));
|
|
299
|
+
try {
|
|
300
|
+
const repo = path.join(directory, 'repo');
|
|
301
|
+
const env = { ...process.env, GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_NOSYSTEM: '1', GIT_AUTHOR_NAME: 't', GIT_AUTHOR_EMAIL: 't@example.invalid', GIT_COMMITTER_NAME: 't', GIT_COMMITTER_EMAIL: 't@example.invalid' };
|
|
302
|
+
const git = (args) => {
|
|
303
|
+
const done = spawnSync('git', ['-C', repo, ...args], { env, encoding: 'utf8' });
|
|
304
|
+
if (done.status !== 0) throw new Error(`git ${args.join(' ')}: ${done.stderr}`);
|
|
305
|
+
return done.stdout;
|
|
306
|
+
};
|
|
307
|
+
fs.mkdirSync(repo);
|
|
308
|
+
git(['init', '--quiet']);
|
|
309
|
+
const names = Array.from({ length: 20 }, (_, index) => `f${String(index).padStart(2, '0')}.txt`);
|
|
310
|
+
for (const name of names) fs.writeFileSync(path.join(repo, name), 'as it was\n');
|
|
311
|
+
git(['add', '.']);
|
|
312
|
+
git(['commit', '--quiet', '-m', 'files']);
|
|
313
|
+
for (const name of names) fs.writeFileSync(path.join(repo, name), 'changed\n');
|
|
314
|
+
const patch = path.join(directory, 'change.patch');
|
|
315
|
+
fs.writeFileSync(patch, git(['diff', '--binary']));
|
|
316
|
+
git(['checkout', '--quiet', '--', '.']);
|
|
317
|
+
const noisy = path.join(directory, 'noisy-smudge.sh');
|
|
318
|
+
fs.writeFileSync(noisy, '#!/bin/sh\nsleep 0.2\necho "a smudge filter that talks" >&2\ncat\n', { mode: 0o755 });
|
|
319
|
+
git(['config', 'filter.noisy.smudge', noisy]);
|
|
320
|
+
git(['config', 'filter.noisy.clean', 'cat']);
|
|
321
|
+
fs.writeFileSync(path.join(repo, '.git', 'info', 'attributes'), '*.txt filter=noisy\n');
|
|
322
|
+
const wrapper = path.join(directory, 'host.mjs');
|
|
323
|
+
fs.writeFileSync(wrapper, `
|
|
324
|
+
import { runCommand } from ${JSON.stringify(new URL('./run-command.js', import.meta.url).href)};
|
|
325
|
+
runCommand('git', ['-C', ${JSON.stringify(repo)}, 'apply', '--binary', ${JSON.stringify(patch)}], { env: ${JSON.stringify(env)}, killTree: true, keepAtExit: true, keepTail: true, maxOutputBytes: 65536, timeoutMs: 60000 }).catch(() => {});
|
|
326
|
+
setTimeout(() => process.exit(0), 1000);
|
|
327
|
+
`);
|
|
328
|
+
const host = spawn(node, [wrapper], { stdio: 'ignore' });
|
|
329
|
+
await new Promise((resolve) => { host.on('exit', resolve); });
|
|
330
|
+
const holds = (name) => fs.existsSync(path.join(repo, name)) && fs.readFileSync(path.join(repo, name), 'utf8') === 'changed\n';
|
|
331
|
+
// Four seconds of smudging in all, most of it after the host left.
|
|
332
|
+
expect(await waitFor(() => names.every(holds), 20_000)).toBe(true);
|
|
333
|
+
expect(git(['status', '--porcelain']).split('\n').filter(Boolean)).toEqual(names.map((name) => ` M ${name}`));
|
|
334
|
+
} finally {
|
|
335
|
+
fs.rmSync(directory, { recursive: true, force: true });
|
|
336
|
+
}
|
|
337
|
+
});
|
|
338
|
+
|
|
339
|
+
it('reads the stderr of a keepAtExit child back, its last maxOutputBytes with keepTail, and refuses more without it', async () => {
|
|
340
|
+
const script = 'process.stderr.write("x".repeat(5000) + "end"); process.stdout.write("gone"); process.exitCode = 2;';
|
|
341
|
+
expect(await runCommand(node, ['-e', script], { killTree: true, keepAtExit: true, keepTail: true, maxOutputBytes: 10 })).toEqual({ code: 2, stdout: '', stderr: 'xxxxxxxend' });
|
|
342
|
+
await expect(runCommand(node, ['-e', script], { killTree: true, keepAtExit: true, maxOutputBytes: 10 })).rejects.toMatchObject({ code: 'command_output_too_large' });
|
|
343
|
+
expect(await runCommand(node, ['-e', script], { killTree: true, keepAtExit: true })).toMatchObject({ code: 2, stderr: `${'x'.repeat(5000)}end` });
|
|
344
|
+
expect(fs.readdirSync(os.tmpdir()).filter((name) => name.startsWith('openchamber-stderr-'))).toEqual([]);
|
|
345
|
+
});
|
|
346
|
+
|
|
347
|
+
it('keeps a keepAtExit child out of the live set, and still kills its tree at the timeout', async () => {
|
|
348
|
+
const running = runCommand(node, ['-e', 'setInterval(() => {}, 1000)'], { killTree: true, keepAtExit: true, timeoutMs: 1500 }).catch((error) => error);
|
|
349
|
+
try {
|
|
350
|
+
expect(liveTreeCount()).toBe(0);
|
|
351
|
+
} finally {
|
|
352
|
+
// Out of the set, only its timeout ends it: waited for even when the assertion failed.
|
|
353
|
+
expect(await running).toMatchObject({ code: 'command_timeout' });
|
|
354
|
+
}
|
|
355
|
+
});
|
|
356
|
+
|
|
274
357
|
it('still kills the tree when an exit listener registered before ours throws', async () => {
|
|
275
358
|
const { child, grandchild } = await runWrapper('throwing');
|
|
276
359
|
expect(isRealPid(child) && isRealPid(grandchild)).toBe(true);
|
|
@@ -394,3 +477,110 @@ setTimeout(() => process.exit(0), 200);
|
|
|
394
477
|
}, 20_000);
|
|
395
478
|
});
|
|
396
479
|
|
|
480
|
+
|
|
481
|
+
// The caller stops a running child from outside, as code out does when the quarantine passes its
|
|
482
|
+
// size cap. The rejection is the caller's own reason, whatever the child's exit looked like.
|
|
483
|
+
describe('runCommand with an abort signal', () => {
|
|
484
|
+
const leftovers = [];
|
|
485
|
+
afterEach(() => {
|
|
486
|
+
for (const pid of leftovers.splice(0)) {
|
|
487
|
+
if (isRealPid(pid) && isAlive(pid)) process.kill(pid, 'SIGKILL');
|
|
488
|
+
}
|
|
489
|
+
});
|
|
490
|
+
const abortListeners = (signal) => getEventListeners(signal, 'abort').length;
|
|
491
|
+
const stopReason = () => new SpaceError('stopped_by_caller', 'the caller stopped it');
|
|
492
|
+
|
|
493
|
+
it('starts nothing when the signal is already aborted, and rejects with its reason', async () => {
|
|
494
|
+
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'openchamber-abort-before-'));
|
|
495
|
+
const marker = path.join(directory, 'started');
|
|
496
|
+
try {
|
|
497
|
+
const reason = stopReason();
|
|
498
|
+
const error = await runCommand(node, ['-e', `require('node:fs').writeFileSync(${JSON.stringify(marker)}, '')`], { killTree: true, signal: AbortSignal.abort(reason) }).catch((caught) => caught);
|
|
499
|
+
expect(error).toBe(reason);
|
|
500
|
+
// The control: the same command without the signal does start and leave its marker.
|
|
501
|
+
await new Promise((resolve) => { setTimeout(resolve, 300); });
|
|
502
|
+
expect(fs.existsSync(marker)).toBe(false);
|
|
503
|
+
expect(liveTreeCount()).toBe(0);
|
|
504
|
+
await runCommand(node, ['-e', `require('node:fs').writeFileSync(${JSON.stringify(marker)}, '')`]);
|
|
505
|
+
expect(fs.existsSync(marker)).toBe(true);
|
|
506
|
+
} finally {
|
|
507
|
+
fs.rmSync(directory, { recursive: true, force: true });
|
|
508
|
+
}
|
|
509
|
+
});
|
|
510
|
+
|
|
511
|
+
// On Windows this runs the real `taskkill /T`, whose child exits with code 1 and no signal.
|
|
512
|
+
it('kills the whole tree while it runs, rejects with the reason once the child is gone, and forgets the tree', async () => {
|
|
513
|
+
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'openchamber-abort-during-'));
|
|
514
|
+
const pidFile = path.join(directory, 'pids.json');
|
|
515
|
+
try {
|
|
516
|
+
const controller = new AbortController();
|
|
517
|
+
const reason = stopReason();
|
|
518
|
+
const started = Date.now();
|
|
519
|
+
const running = runCommand(node, ['-e', parentOfSleeper(pidFile)], { killTree: true, timeoutMs: 60_000, signal: controller.signal }).catch((caught) => caught);
|
|
520
|
+
expect(await waitFor(() => fs.existsSync(pidFile) && fs.statSync(pidFile).size > 0)).toBe(true);
|
|
521
|
+
const pids = JSON.parse(fs.readFileSync(pidFile, 'utf8'));
|
|
522
|
+
leftovers.push(pids.grandchild, pids.child);
|
|
523
|
+
expect(isAlive(pids.child) && isAlive(pids.grandchild)).toBe(true);
|
|
524
|
+
expect(abortListeners(controller.signal)).toBe(1);
|
|
525
|
+
controller.abort(reason);
|
|
526
|
+
expect(await running).toBe(reason);
|
|
527
|
+
expect(isAlive(pids.child)).toBe(false);
|
|
528
|
+
expect(await waitFor(() => !isAlive(pids.grandchild))).toBe(true);
|
|
529
|
+
expect(Date.now() - started).toBeLessThan(30_000);
|
|
530
|
+
expect(liveTreeCount()).toBe(0);
|
|
531
|
+
expect(abortListeners(controller.signal)).toBe(0);
|
|
532
|
+
} finally {
|
|
533
|
+
fs.rmSync(directory, { recursive: true, force: true });
|
|
534
|
+
}
|
|
535
|
+
});
|
|
536
|
+
|
|
537
|
+
it('kills the child alone without killTree, and rejects with the reason', async () => {
|
|
538
|
+
const controller = new AbortController();
|
|
539
|
+
const reason = stopReason();
|
|
540
|
+
const running = runCommand(node, ['-e', 'process.stdout.write("up"); setInterval(() => {}, 1000)'], { timeoutMs: 60_000, signal: controller.signal }).catch((caught) => caught);
|
|
541
|
+
await new Promise((resolve) => { setTimeout(resolve, 300); });
|
|
542
|
+
controller.abort(reason);
|
|
543
|
+
expect(await running).toBe(reason);
|
|
544
|
+
expect(abortListeners(controller.signal)).toBe(0);
|
|
545
|
+
});
|
|
546
|
+
|
|
547
|
+
it('changes nothing about a run that already closed, and leaves no listener behind', async () => {
|
|
548
|
+
const controller = new AbortController();
|
|
549
|
+
expect(await runCommand(node, ['-e', 'process.stdout.write("ok")'], { killTree: true, signal: controller.signal })).toEqual({ code: 0, stdout: 'ok', stderr: '' });
|
|
550
|
+
expect(abortListeners(controller.signal)).toBe(0);
|
|
551
|
+
controller.abort(stopReason());
|
|
552
|
+
expect(liveTreeCount()).toBe(0);
|
|
553
|
+
});
|
|
554
|
+
|
|
555
|
+
// The timeout came first: its kill is the only one, and a late abort neither kills again nor
|
|
556
|
+
// replaces the error.
|
|
557
|
+
it('keeps the timeout as the error when the abort comes after it', async () => {
|
|
558
|
+
const controller = new AbortController();
|
|
559
|
+
const running = runCommand(node, ['-e', 'setInterval(() => {}, 1000)'], { killTree: true, timeoutMs: 500, signal: controller.signal }).catch((caught) => caught);
|
|
560
|
+
await new Promise((resolve) => { setTimeout(resolve, 700); });
|
|
561
|
+
expect(abortListeners(controller.signal)).toBe(0);
|
|
562
|
+
controller.abort(stopReason());
|
|
563
|
+
expect(await running).toMatchObject({ code: 'command_timeout' });
|
|
564
|
+
expect(liveTreeCount()).toBe(0);
|
|
565
|
+
});
|
|
566
|
+
|
|
567
|
+
// Whatever the caller aborts with, the rejection is a SpaceError: a string, null or nothing at all
|
|
568
|
+
// would otherwise reach a caller that catches SpaceErrors.
|
|
569
|
+
it.each([['a string', 'stopped'], ['null', null], ['nothing', undefined]])('rejects with a SpaceError when the reason is %s', async (_, reason) => {
|
|
570
|
+
const controller = new AbortController();
|
|
571
|
+
const running = runCommand(node, ['-e', 'setInterval(() => {}, 1000)'], { killTree: true, timeoutMs: 60_000, signal: controller.signal }).catch((caught) => caught);
|
|
572
|
+
await new Promise((resolve) => { setTimeout(resolve, 200); });
|
|
573
|
+
if (reason === undefined) controller.abort(); else controller.abort(reason);
|
|
574
|
+
const error = await running;
|
|
575
|
+
expect(error).toBeInstanceOf(SpaceError);
|
|
576
|
+
expect(error).toMatchObject({ code: 'command_aborted' });
|
|
577
|
+
expect(await runCommand(node, ['-e', ''], { signal: AbortSignal.abort(reason) }).catch((caught) => caught)).toMatchObject({ code: 'command_aborted' });
|
|
578
|
+
});
|
|
579
|
+
|
|
580
|
+
it('leaves no listener after a spawn failure', async () => {
|
|
581
|
+
const controller = new AbortController();
|
|
582
|
+
await expect(runCommand('/nonexistent/openchamber-no-such-binary', [], { killTree: true, signal: controller.signal })).rejects.toMatchObject({ code: 'command_spawn_failed' });
|
|
583
|
+
expect(abortListeners(controller.signal)).toBe(0);
|
|
584
|
+
expect(liveTreeCount()).toBe(0);
|
|
585
|
+
});
|
|
586
|
+
});
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
// One event connection per space, with its own state and its own backoff, attached to the
|
|
2
|
+
// host's event hub after the v2 translation layer: a space's events enter the hub as the
|
|
3
|
+
// host's do, numbered, coalesced, replayed and fanned out, marked with the space's id. They
|
|
4
|
+
// feed the same watcher, so live status, unread marks and notifications work for a space's
|
|
5
|
+
// sessions, and the same browser streams, so a client keeps one cursor for everything.
|
|
6
|
+
//
|
|
7
|
+
// Every event is untrusted and passes the session index first: a directory outside the
|
|
8
|
+
// space's root or a session id of the host's drops it. When a connection is made the host
|
|
9
|
+
// asks the space for its live status and enters it the same way. A gap is reported to the
|
|
10
|
+
// clients as `openchamber:space-stream`, so a client re-reads that one space.
|
|
11
|
+
|
|
12
|
+
import { Readable } from 'node:stream';
|
|
13
|
+
|
|
14
|
+
import { z } from 'zod';
|
|
15
|
+
|
|
16
|
+
import { createUpstreamSseReader } from '../event-stream/upstream-reader.js';
|
|
17
|
+
|
|
18
|
+
const EVENT_PATH = '/api/event';
|
|
19
|
+
const STATUS_PATH = '/api/sessions/status';
|
|
20
|
+
const STATUS_TIMEOUT_MS = 10_000;
|
|
21
|
+
const MAX_STATUS_BYTES = 4 * 1024 * 1024;
|
|
22
|
+
|
|
23
|
+
// Backoff between attempts: doubling from one second to a minute, reset by a connection.
|
|
24
|
+
const RECONNECT_BASE_MS = 1_000;
|
|
25
|
+
export const RECONNECT_CAP_MS = 60_000;
|
|
26
|
+
export const reconnectDelayAfter = (failures) => Math.min(RECONNECT_CAP_MS, RECONNECT_BASE_MS * 2 ** Math.max(0, failures - 1));
|
|
27
|
+
|
|
28
|
+
// What the host reads of an answer from inside; the rest is carried, not read.
|
|
29
|
+
const liveStatusSchema = z.object({ status: z.enum(['busy', 'idle']) });
|
|
30
|
+
const statusSchema = z.object({ sessions: z.record(z.string(), z.unknown()).default({}) }).passthrough();
|
|
31
|
+
const eventPayloadSchema = z.object({ location: z.object({ directory: z.string() }).passthrough().optional() }).passthrough();
|
|
32
|
+
|
|
33
|
+
/** Reads a whole body up to a cap, as text. */
|
|
34
|
+
const readBody = (response, cap) => new Promise((resolve, reject) => {
|
|
35
|
+
const chunks = [];
|
|
36
|
+
let size = 0;
|
|
37
|
+
response.on('data', (chunk) => {
|
|
38
|
+
size += chunk.length;
|
|
39
|
+
if (size > cap) {
|
|
40
|
+
response.destroy();
|
|
41
|
+
reject(new Error(`the answer exceeds ${cap} bytes`));
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
chunks.push(chunk);
|
|
45
|
+
});
|
|
46
|
+
response.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
|
|
47
|
+
response.on('error', reject);
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* `requestInside(spaceId, { path, headers, timeoutMs })` is the dispatcher's; `index` the
|
|
52
|
+
* session index; `hub` the global event hub. `stallTimeoutMs` and `now` are for the tests.
|
|
53
|
+
*/
|
|
54
|
+
export function createSpaceEventSources({ requestInside, index, hub, logger = console, stallTimeoutMs, now = Date.now }) {
|
|
55
|
+
const sources = new Map();
|
|
56
|
+
|
|
57
|
+
const inject = (spaceId, payload, directory) => hub.injectEvent({ payload, directory, spaceId });
|
|
58
|
+
|
|
59
|
+
const announce = (spaceId, status, wasReady) => {
|
|
60
|
+
inject(spaceId, { type: 'openchamber:space-stream', properties: { spaceId, status, wasReady, timestamp: now() } }, 'global');
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
/** The live status inside, entered as status events, so a busy session shows busy from the first moment. */
|
|
64
|
+
const seedStatus = async (spaceId) => {
|
|
65
|
+
const response = await requestInside(spaceId, { path: STATUS_PATH, headers: { accept: 'application/json' }, timeoutMs: STATUS_TIMEOUT_MS });
|
|
66
|
+
if (response.statusCode !== 200) {
|
|
67
|
+
response.resume();
|
|
68
|
+
throw new Error(`status ${response.statusCode}`);
|
|
69
|
+
}
|
|
70
|
+
const parsed = statusSchema.safeParse(JSON.parse(await readBody(response, MAX_STATUS_BYTES)));
|
|
71
|
+
if (!parsed.success) return;
|
|
72
|
+
for (const [sessionID, state] of Object.entries(parsed.data.sessions)) {
|
|
73
|
+
const live = liveStatusSchema.safeParse(state);
|
|
74
|
+
if (!live.success) continue;
|
|
75
|
+
const payload = { type: 'session.status', data: { sessionID, status: { type: live.data.status } } };
|
|
76
|
+
if (index.acceptSpaceEvent(spaceId, payload)) inject(spaceId, payload, '');
|
|
77
|
+
}
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
/** The event stream inside, over the dispatcher's channel, in the shape the reader expects. */
|
|
81
|
+
const fetchInside = (spaceId) => async (_url, { headers, signal }) => {
|
|
82
|
+
const response = await requestInside(spaceId, { path: EVENT_PATH, headers });
|
|
83
|
+
const stop = () => response.destroy();
|
|
84
|
+
if (signal?.aborted) { stop(); throw new Error('aborted'); }
|
|
85
|
+
signal?.addEventListener('abort', stop, { once: true });
|
|
86
|
+
const contentType = String(response.headers['content-type'] ?? '');
|
|
87
|
+
const ok = response.statusCode === 200 && contentType.includes('text/event-stream');
|
|
88
|
+
return { ok, status: response.statusCode, body: ok ? Readable.toWeb(response) : null };
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
const start = (spaceId) => {
|
|
92
|
+
if (sources.has(spaceId)) return;
|
|
93
|
+
const controller = new AbortController();
|
|
94
|
+
const source = { failures: 0, everConnected: false, reader: null, controller };
|
|
95
|
+
source.reader = createUpstreamSseReader({
|
|
96
|
+
signal: controller.signal,
|
|
97
|
+
fetchImpl: fetchInside(spaceId),
|
|
98
|
+
stallTimeoutMs,
|
|
99
|
+
reconnectDelayMs: () => reconnectDelayAfter(source.failures),
|
|
100
|
+
buildUrl: () => new URL(`http://space${EVENT_PATH}`),
|
|
101
|
+
onConnect() {
|
|
102
|
+
source.failures = 0;
|
|
103
|
+
const wasReady = source.everConnected;
|
|
104
|
+
source.everConnected = true;
|
|
105
|
+
announce(spaceId, 'connected', wasReady);
|
|
106
|
+
seedStatus(spaceId).catch((error) => logger.warn?.(`[spaces] could not read the status of space ${spaceId}: ${error?.code ?? error?.message ?? error}`));
|
|
107
|
+
},
|
|
108
|
+
onDisconnect({ reason }) {
|
|
109
|
+
source.failures += 1;
|
|
110
|
+
if (source.everConnected && reason !== 'stopped') announce(spaceId, 'disconnected', true);
|
|
111
|
+
},
|
|
112
|
+
onEvent({ payload }) {
|
|
113
|
+
const parsed = eventPayloadSchema.safeParse(payload);
|
|
114
|
+
if (!parsed.success || !index.acceptSpaceEvent(spaceId, payload)) return;
|
|
115
|
+
inject(spaceId, payload, parsed.data.location?.directory ?? '');
|
|
116
|
+
},
|
|
117
|
+
// Every failed attempt ends in `onDisconnect`, which is where it is counted.
|
|
118
|
+
onError(error) {
|
|
119
|
+
if (controller.signal.aborted) return;
|
|
120
|
+
logger.warn?.(`[spaces] event stream of space ${spaceId}: ${error?.type ?? 'error'} ${error?.status ?? error?.error?.code ?? ''}`.trim());
|
|
121
|
+
},
|
|
122
|
+
});
|
|
123
|
+
sources.set(spaceId, source);
|
|
124
|
+
void source.reader.start();
|
|
125
|
+
};
|
|
126
|
+
|
|
127
|
+
const stop = (spaceId) => {
|
|
128
|
+
const source = sources.get(spaceId);
|
|
129
|
+
if (!source) return;
|
|
130
|
+
sources.delete(spaceId);
|
|
131
|
+
source.controller.abort();
|
|
132
|
+
source.reader.stop();
|
|
133
|
+
};
|
|
134
|
+
|
|
135
|
+
return {
|
|
136
|
+
/** Follows the list of spaces: a connection for each new one, none for one that is gone. */
|
|
137
|
+
sync(spaceIds) {
|
|
138
|
+
const wanted = new Set(spaceIds);
|
|
139
|
+
for (const spaceId of Array.from(sources.keys())) {
|
|
140
|
+
if (!wanted.has(spaceId)) {
|
|
141
|
+
stop(spaceId);
|
|
142
|
+
index.forget(spaceId);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
for (const spaceId of wanted) start(spaceId);
|
|
146
|
+
},
|
|
147
|
+
/** For the tests: whether a space has a connection right now. */
|
|
148
|
+
has: (spaceId) => sources.has(spaceId),
|
|
149
|
+
close() {
|
|
150
|
+
for (const spaceId of Array.from(sources.keys())) stop(spaceId);
|
|
151
|
+
},
|
|
152
|
+
};
|
|
153
|
+
}
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
// The event connection of a space against a stand-in for the server inside, and the real hub.
|
|
2
|
+
|
|
3
|
+
import { PassThrough } from 'node:stream';
|
|
4
|
+
|
|
5
|
+
import { afterEach, describe, expect, it } from 'vitest';
|
|
6
|
+
|
|
7
|
+
import { createGlobalMessageStreamHub } from '../event-stream/global-hub.js';
|
|
8
|
+
import { SpaceError } from './errors.js';
|
|
9
|
+
import { RECONNECT_CAP_MS, createSpaceEventSources, reconnectDelayAfter } from './space-events.js';
|
|
10
|
+
import { createSpaceSessionIndex } from './space-sessions.js';
|
|
11
|
+
|
|
12
|
+
const ID = 'a1b2c3d4e5f6';
|
|
13
|
+
const OTHER = '0f0f0f0f0f0f';
|
|
14
|
+
const sleep = (ms) => new Promise((resolve) => { setTimeout(resolve, ms); });
|
|
15
|
+
const until = async (check, timeoutMs = 3_000) => {
|
|
16
|
+
const deadline = Date.now() + timeoutMs;
|
|
17
|
+
while (!check() && Date.now() < deadline) await sleep(10);
|
|
18
|
+
return check();
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
/** A response of the server inside: an SSE stream that the test writes to, or a JSON answer. */
|
|
22
|
+
const sseResponse = () => {
|
|
23
|
+
const stream = new PassThrough();
|
|
24
|
+
stream.statusCode = 200;
|
|
25
|
+
stream.headers = { 'content-type': 'text/event-stream' };
|
|
26
|
+
return stream;
|
|
27
|
+
};
|
|
28
|
+
const jsonResponse = (status, body) => {
|
|
29
|
+
const stream = new PassThrough();
|
|
30
|
+
stream.statusCode = status;
|
|
31
|
+
stream.headers = { 'content-type': 'application/json' };
|
|
32
|
+
stream.end(JSON.stringify(body));
|
|
33
|
+
return stream;
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
const makeHub = () => createGlobalMessageStreamHub({
|
|
37
|
+
buildOpenCodeUrl: (path) => `http://127.0.0.1:1${path}`,
|
|
38
|
+
getOpenCodeAuthHeaders: () => ({}),
|
|
39
|
+
deltaCoalesceWindowMs: 0,
|
|
40
|
+
fetchImpl: async () => { throw new Error('the host upstream is not part of this test'); },
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
describe('reconnectDelayAfter', () => {
|
|
44
|
+
it('doubles from one second and stops at a minute', () => {
|
|
45
|
+
expect([0, 1, 2, 3, 4].map(reconnectDelayAfter)).toEqual([1_000, 1_000, 2_000, 4_000, 8_000]);
|
|
46
|
+
expect(reconnectDelayAfter(20)).toBe(RECONNECT_CAP_MS);
|
|
47
|
+
});
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
describe('createSpaceEventSources', () => {
|
|
51
|
+
const streams = { [ID]: [], [OTHER]: [] };
|
|
52
|
+
const requests = [];
|
|
53
|
+
let status = { sessions: {} };
|
|
54
|
+
let refuse = null;
|
|
55
|
+
const requestInside = async (spaceId, request) => {
|
|
56
|
+
requests.push({ spaceId, path: request.path, headers: request.headers });
|
|
57
|
+
if (refuse) throw refuse;
|
|
58
|
+
if (request.path === '/api/sessions/status') return jsonResponse(200, status);
|
|
59
|
+
const stream = sseResponse();
|
|
60
|
+
streams[spaceId].push(stream);
|
|
61
|
+
return stream;
|
|
62
|
+
};
|
|
63
|
+
const logs = [];
|
|
64
|
+
const logger = { warn: (line) => logs.push(line) };
|
|
65
|
+
let hub;
|
|
66
|
+
let index;
|
|
67
|
+
let sources;
|
|
68
|
+
let received;
|
|
69
|
+
|
|
70
|
+
const start = () => {
|
|
71
|
+
hub = makeHub();
|
|
72
|
+
index = createSpaceSessionIndex({ logger });
|
|
73
|
+
received = [];
|
|
74
|
+
hub.subscribeEvent((event) => received.push(event), { spaces: true });
|
|
75
|
+
sources = createSpaceEventSources({ requestInside, index, hub, logger, stallTimeoutMs: 0 });
|
|
76
|
+
};
|
|
77
|
+
|
|
78
|
+
afterEach(() => {
|
|
79
|
+
sources?.close();
|
|
80
|
+
streams[ID].length = 0;
|
|
81
|
+
streams[OTHER].length = 0;
|
|
82
|
+
requests.length = 0;
|
|
83
|
+
logs.length = 0;
|
|
84
|
+
status = { sessions: {} };
|
|
85
|
+
refuse = null;
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
it('opens one connection per space, announces it, seeds the live status, and enters the events with the space id', async () => {
|
|
89
|
+
start();
|
|
90
|
+
status = { sessions: { busy1: { status: 'busy' }, idle1: { status: 'idle' }, odd: { status: 'retry' } } };
|
|
91
|
+
sources.sync([ID]);
|
|
92
|
+
expect(await until(() => streams[ID].length === 1)).toBe(true);
|
|
93
|
+
expect(requests[0]).toMatchObject({ spaceId: ID, path: '/api/event', headers: expect.objectContaining({ Accept: 'text/event-stream' }) });
|
|
94
|
+
expect(await until(() => received.length >= 3)).toBe(true);
|
|
95
|
+
expect(received[0].payload).toMatchObject({ type: 'openchamber:space-stream', properties: { spaceId: ID, status: 'connected', wasReady: false } });
|
|
96
|
+
expect(received.slice(1).map((event) => [event.payload.type, event.payload.data.sessionID, event.payload.data.status.type])).toEqual([
|
|
97
|
+
['session.status', 'busy1', 'busy'],
|
|
98
|
+
['session.status', 'idle1', 'idle'],
|
|
99
|
+
]);
|
|
100
|
+
|
|
101
|
+
streams[ID][0].write(`data: ${JSON.stringify({ id: 'e1', type: 'session.execution.started', data: { sessionID: 's1' }, location: { directory: `/spaces/${ID}/repo` } })}\n\n`);
|
|
102
|
+
expect(await until(() => received.length === 4)).toBe(true);
|
|
103
|
+
expect(received[3]).toMatchObject({ spaceId: ID, directory: `/spaces/${ID}/repo`, payload: { id: 'e1' } });
|
|
104
|
+
expect(received[3].translated()).toEqual([expect.objectContaining({ type: 'session.status', properties: expect.objectContaining({ sessionID: 's1', directory: `/spaces/${ID}/repo` }) })]);
|
|
105
|
+
expect(sources.has(ID)).toBe(true);
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
it('drops an event that claims a directory outside the space or a session of the host', async () => {
|
|
109
|
+
start();
|
|
110
|
+
index.observeHostRecords([{ id: 'host-1' }]);
|
|
111
|
+
sources.sync([ID]);
|
|
112
|
+
expect(await until(() => streams[ID].length === 1)).toBe(true);
|
|
113
|
+
const stream = streams[ID][0];
|
|
114
|
+
const write = (payload) => stream.write(`data: ${JSON.stringify(payload)}\n\n`);
|
|
115
|
+
write({ id: 'bad1', type: 'session.execution.started', data: { sessionID: 's1' }, location: { directory: '/home/me/project' } });
|
|
116
|
+
write({ id: 'bad2', type: 'session.created', data: { sessionID: 's2', location: { directory: `/spaces/${OTHER}/repo` } }, location: { directory: `/spaces/${ID}/repo` } });
|
|
117
|
+
write({ id: 'bad3', type: 'session.execution.started', data: { sessionID: 'host-1' } });
|
|
118
|
+
write({ id: 'good', type: 'session.execution.started', data: { sessionID: 's1' } });
|
|
119
|
+
expect(await until(() => received.some((event) => event.payload.id === 'good'))).toBe(true);
|
|
120
|
+
expect(received.map((event) => event.payload.id).filter((id) => id?.startsWith('bad'))).toEqual([]);
|
|
121
|
+
expect(logs.filter((line) => line.includes('dropped an event'))).toHaveLength(3);
|
|
122
|
+
expect(logs.join('\n')).not.toContain('/home/me/project');
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
it('reconnects with backoff after the stream inside ends, announces the gap, and stops for a space that is gone', async () => {
|
|
126
|
+
start();
|
|
127
|
+
sources.sync([ID, OTHER]);
|
|
128
|
+
expect(await until(() => streams[ID].length === 1 && streams[OTHER].length === 1)).toBe(true);
|
|
129
|
+
expect(await until(() => received.filter((event) => event.payload.type === 'openchamber:space-stream').length === 2)).toBe(true);
|
|
130
|
+
streams[ID][0].end();
|
|
131
|
+
expect(await until(() => received.some((event) => event.payload.properties?.status === 'disconnected' && event.payload.properties?.spaceId === ID))).toBe(true);
|
|
132
|
+
// The first attempt after the gap waits a second, so it is not there at once.
|
|
133
|
+
await sleep(300);
|
|
134
|
+
expect(streams[ID]).toHaveLength(1);
|
|
135
|
+
expect(await until(() => streams[ID].length === 2, 3_000)).toBe(true);
|
|
136
|
+
expect(received.filter((event) => event.payload.properties?.spaceId === ID && event.payload.properties?.status === 'connected').at(-1).payload.properties.wasReady).toBe(true);
|
|
137
|
+
// A second drop in a row waits two seconds, not four: one failure is counted once.
|
|
138
|
+
const secondDropAt = Date.now();
|
|
139
|
+
streams[ID][1].end();
|
|
140
|
+
expect(await until(() => streams[ID].length === 3, 3_500)).toBe(true);
|
|
141
|
+
expect(Date.now() - secondDropAt).toBeLessThan(3_000);
|
|
142
|
+
|
|
143
|
+
index.acceptSpaceList(OTHER, [{ id: 'o1', location: { directory: `/spaces/${OTHER}/repo` } }], { complete: true });
|
|
144
|
+
sources.sync([ID]);
|
|
145
|
+
expect(sources.has(OTHER)).toBe(false);
|
|
146
|
+
expect(index.snapshot().map((entry) => entry.spaceId)).toEqual([]);
|
|
147
|
+
expect(streams[OTHER][0].destroyed).toBe(true);
|
|
148
|
+
}, 15_000);
|
|
149
|
+
|
|
150
|
+
it('keeps trying, quietly, while the space refuses the connection', async () => {
|
|
151
|
+
start();
|
|
152
|
+
refuse = new SpaceError('space_not_running', 'stopped');
|
|
153
|
+
sources.sync([ID]);
|
|
154
|
+
expect(await until(() => requests.length >= 1)).toBe(true);
|
|
155
|
+
await sleep(200);
|
|
156
|
+
expect(received).toEqual([]);
|
|
157
|
+
expect(requests.length).toBeLessThanOrEqual(2);
|
|
158
|
+
expect(logs.some((line) => line.includes(`event stream of space ${ID}`))).toBe(true);
|
|
159
|
+
});
|
|
160
|
+
});
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
// What the host remembers about a space beside the runtime's labels: the network choice the user
|
|
2
|
+
// made, so the host can say it again to a gatekeeper that starts with an empty memory, and where
|
|
3
|
+
// the code went in, so the history and the result find the same repository later.
|
|
4
|
+
//
|
|
5
|
+
// The labels stay the source of truth about which spaces exist: a record without a space is
|
|
6
|
+
// forgotten, and a space without a record is listed with nothing known about it. No secret is
|
|
7
|
+
// ever in a record; the design keeps secret values out of the host's disk.
|
|
8
|
+
|
|
9
|
+
import fs from 'node:fs';
|
|
10
|
+
import path from 'node:path';
|
|
11
|
+
|
|
12
|
+
import { z } from 'zod';
|
|
13
|
+
|
|
14
|
+
import { requireSpaceId } from './labels.js';
|
|
15
|
+
|
|
16
|
+
const RECORDS_DIRECTORY = path.join('spaces', 'records');
|
|
17
|
+
|
|
18
|
+
const NETWORK_MODES = Object.freeze(['allowlist', 'open']);
|
|
19
|
+
// The allowlist's own rule for a name: labels of letters, digits and hyphens, with a real last label.
|
|
20
|
+
const DOMAIN_PATTERN = /^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z][a-z0-9-]{0,61}[a-z0-9]$/;
|
|
21
|
+
const MAX_DOMAINS = 200;
|
|
22
|
+
|
|
23
|
+
export const networkSchema = z.object({
|
|
24
|
+
mode: z.enum(NETWORK_MODES),
|
|
25
|
+
domains: z.array(z.string().regex(DOMAIN_PATTERN)).max(MAX_DOMAINS).default([]),
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
const historySchema = z.enum(['pending', 'sent', 'already_complete', 'host_shallow', 'failed']);
|
|
29
|
+
|
|
30
|
+
const recordSchema = z.object({
|
|
31
|
+
version: z.literal(1),
|
|
32
|
+
network: networkSchema,
|
|
33
|
+
/** The host repository the code came from, as the user's project names it. */
|
|
34
|
+
repository: z.string().min(1).nullable().default(null),
|
|
35
|
+
/** The project path inside the space that code in returned. */
|
|
36
|
+
spacePath: z.string().min(1).nullable().default(null),
|
|
37
|
+
/** The commit the snapshot was taken from, which the history is sent behind. */
|
|
38
|
+
base: z.string().regex(/^[0-9a-f]{40}$|^[0-9a-f]{64}$/).nullable().default(null),
|
|
39
|
+
history: historySchema.default('pending'),
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Per-space records under the host's data directory, one JSON file each, readable by the user only.
|
|
44
|
+
* A record that cannot be read as one is reported as `null` with a warning, never as a fresh one:
|
|
45
|
+
* a bad file must not make the host forget a network choice and leave a space more open than asked.
|
|
46
|
+
*/
|
|
47
|
+
export function createSpaceRecords({ dataDir, logger = console }) {
|
|
48
|
+
const directory = path.join(dataDir, RECORDS_DIRECTORY);
|
|
49
|
+
const fileOf = (spaceId) => path.join(directory, `${requireSpaceId(spaceId)}.json`);
|
|
50
|
+
|
|
51
|
+
const read = (spaceId) => {
|
|
52
|
+
const file = fileOf(spaceId);
|
|
53
|
+
let text;
|
|
54
|
+
try {
|
|
55
|
+
text = fs.readFileSync(file, 'utf8');
|
|
56
|
+
} catch (error) {
|
|
57
|
+
if (error?.code === 'ENOENT') return { status: 'missing', record: null };
|
|
58
|
+
logger.warn?.(`[spaces] could not read the record of space ${spaceId}: ${error?.code ?? error?.message ?? error}`);
|
|
59
|
+
return { status: 'unreadable', record: null };
|
|
60
|
+
}
|
|
61
|
+
try {
|
|
62
|
+
const parsed = recordSchema.safeParse(JSON.parse(text));
|
|
63
|
+
if (parsed.success) return { status: 'ok', record: parsed.data };
|
|
64
|
+
} catch {
|
|
65
|
+
// Reported below.
|
|
66
|
+
}
|
|
67
|
+
logger.warn?.(`[spaces] the record of space ${spaceId} is not one this host wrote`);
|
|
68
|
+
return { status: 'unreadable', record: null };
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
const write = (spaceId, record) => {
|
|
72
|
+
const checked = recordSchema.parse({ version: 1, ...record });
|
|
73
|
+
fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
74
|
+
const file = fileOf(spaceId);
|
|
75
|
+
// Through a temporary name, so a crash in the middle never leaves half a record.
|
|
76
|
+
const temporary = `${file}.${process.pid}.tmp`;
|
|
77
|
+
fs.writeFileSync(temporary, `${JSON.stringify(checked, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 });
|
|
78
|
+
fs.renameSync(temporary, file);
|
|
79
|
+
return checked;
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
/** Changes some fields of a record that exists. A record that is missing or unreadable is not written. */
|
|
83
|
+
const update = (spaceId, changes) => {
|
|
84
|
+
const current = read(spaceId);
|
|
85
|
+
if (current.status !== 'ok') return current;
|
|
86
|
+
return { status: 'ok', record: write(spaceId, { ...current.record, ...changes }) };
|
|
87
|
+
};
|
|
88
|
+
|
|
89
|
+
const remove = (spaceId) => {
|
|
90
|
+
try {
|
|
91
|
+
fs.rmSync(fileOf(spaceId), { force: true });
|
|
92
|
+
} catch (error) {
|
|
93
|
+
logger.warn?.(`[spaces] could not remove the record of space ${spaceId}: ${error?.code ?? error?.message ?? error}`);
|
|
94
|
+
}
|
|
95
|
+
};
|
|
96
|
+
|
|
97
|
+
return { read, write, update, remove };
|
|
98
|
+
}
|