@myrialabs/clopen 0.4.34 → 0.4.36

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.
Files changed (125) hide show
  1. package/backend/artifacts/sync.test.ts +63 -0
  2. package/backend/artifacts/sync.ts +56 -3
  3. package/backend/auth/permissions.ts +7 -0
  4. package/backend/containers/actions.ts +316 -0
  5. package/backend/containers/disk-usage.test.ts +68 -0
  6. package/backend/containers/disk-usage.ts +170 -0
  7. package/backend/containers/logs.ts +335 -0
  8. package/backend/containers/monitor.ts +410 -0
  9. package/backend/containers/parse.test.ts +599 -0
  10. package/backend/containers/parse.ts +905 -0
  11. package/backend/containers/port-index.test.ts +91 -0
  12. package/backend/containers/port-index.ts +198 -0
  13. package/backend/containers/prune-job.test.ts +148 -0
  14. package/backend/containers/prune-job.ts +129 -0
  15. package/backend/containers/pty-backend.ts +337 -0
  16. package/backend/containers/pty.ts +114 -0
  17. package/backend/containers/runtime.ts +218 -0
  18. package/backend/containers/scan.ts +293 -0
  19. package/backend/database/migrations/070_create_worktrees_table.ts +67 -0
  20. package/backend/database/migrations/index.ts +7 -0
  21. package/backend/database/queries/index.ts +1 -0
  22. package/backend/database/queries/session-queries.ts +50 -11
  23. package/backend/database/queries/worktree-queries.ts +148 -0
  24. package/backend/engine/adapters/opencode/server.ts +389 -83
  25. package/backend/engine/adapters/opencode/stream.ts +14 -14
  26. package/backend/engine/hot-reload.ts +25 -10
  27. package/backend/files/file-watcher.test.ts +105 -0
  28. package/backend/files/file-watcher.ts +80 -10
  29. package/backend/git/git-service.test.ts +33 -0
  30. package/backend/git/git-service.ts +7 -3
  31. package/backend/git/nested-repos.test.ts +292 -1
  32. package/backend/git/nested-repos.ts +330 -17
  33. package/backend/host/metrics.test.ts +110 -0
  34. package/backend/host/metrics.ts +235 -0
  35. package/backend/{ports → host}/runner.ts +19 -10
  36. package/backend/index.ts +16 -4
  37. package/backend/mcp/internal/servers/browser-automation/context.ts +16 -2
  38. package/backend/ports/attribute.test.ts +3 -2
  39. package/backend/ports/attribute.ts +6 -45
  40. package/backend/ports/kill.ts +1 -1
  41. package/backend/ports/monitor.ts +1 -1
  42. package/backend/ports/processes.ts +1 -1
  43. package/backend/ports/scan-host.ts +77 -8
  44. package/backend/ports/scan.test.ts +1 -1
  45. package/backend/ports/scan.ts +1 -1
  46. package/backend/ports/ssh-lineage.ts +1 -1
  47. package/backend/preview/browser/browser-pool.ts +81 -0
  48. package/backend/preview/browser/browser-preview-service.ts +142 -32
  49. package/backend/preview/browser/browser-tab-manager.ts +350 -113
  50. package/backend/preview/browser/browser-video-capture.ts +84 -31
  51. package/backend/preview/browser/types.ts +9 -0
  52. package/backend/projects/project-cleanup.integration.test.ts +1 -1
  53. package/backend/projects/project-cleanup.ts +7 -1
  54. package/backend/projects/shell-ownership.ts +65 -0
  55. package/backend/snapshot/snapshot-service.ts +6 -2
  56. package/backend/terminal/ptykit.ts +35 -6
  57. package/backend/utils/ws.ts +21 -1
  58. package/backend/worktrees/clone.ts +222 -0
  59. package/backend/worktrees/index.ts +29 -0
  60. package/backend/worktrees/merge.test.ts +93 -0
  61. package/backend/worktrees/merge.ts +232 -0
  62. package/backend/worktrees/paths.test.ts +60 -0
  63. package/backend/worktrees/paths.ts +60 -0
  64. package/backend/worktrees/resolve.ts +67 -0
  65. package/backend/worktrees/service.ts +315 -0
  66. package/backend/worktrees/tree.ts +59 -0
  67. package/backend/ws/access.ts +18 -0
  68. package/backend/ws/artifacts/generate.ts +2 -2
  69. package/backend/ws/chat/stream.ts +9 -2
  70. package/backend/ws/containers/actions.ts +156 -0
  71. package/backend/ws/containers/index.ts +43 -0
  72. package/backend/ws/containers/list.ts +146 -0
  73. package/backend/ws/containers/logs.ts +43 -0
  74. package/backend/ws/containers/tunnel.ts +101 -0
  75. package/backend/ws/files/panel-state-scope.test.ts +102 -0
  76. package/backend/ws/files/path-access.test.ts +93 -1
  77. package/backend/ws/files/path-access.ts +54 -5
  78. package/backend/ws/files/read.ts +15 -10
  79. package/backend/ws/files/search.ts +7 -7
  80. package/backend/ws/files/state.ts +70 -8
  81. package/backend/ws/files/watch.ts +16 -14
  82. package/backend/ws/git/branch-name.ts +3 -3
  83. package/backend/ws/git/branch.ts +15 -15
  84. package/backend/ws/git/commit-message.ts +3 -3
  85. package/backend/ws/git/commit.ts +17 -17
  86. package/backend/ws/git/conflict.ts +10 -10
  87. package/backend/ws/git/diff.ts +9 -9
  88. package/backend/ws/git/ignored.ts +9 -9
  89. package/backend/ws/git/log.ts +6 -4
  90. package/backend/ws/git/remote.ts +43 -43
  91. package/backend/ws/git/staging.ts +16 -16
  92. package/backend/ws/git/status.ts +47 -37
  93. package/backend/ws/index.ts +6 -0
  94. package/backend/ws/message-rate-limiter.test.ts +45 -0
  95. package/backend/ws/message-rate-limiter.ts +34 -3
  96. package/backend/ws/preview/access.ts +11 -3
  97. package/backend/ws/projects/index.ts +5 -1
  98. package/backend/ws/projects/info.test.ts +54 -0
  99. package/backend/ws/projects/info.ts +398 -0
  100. package/backend/ws/sessions/crud.ts +21 -6
  101. package/backend/ws/snapshot/restore.ts +11 -14
  102. package/backend/ws/ssh/connections.ts +8 -0
  103. package/backend/ws/system/device-info.ts +70 -96
  104. package/backend/ws/worktrees/crud.ts +187 -0
  105. package/backend/ws/worktrees/index.ts +33 -0
  106. package/backend/ws/worktrees/transfer.ts +88 -0
  107. package/dist/assets/{index-vW2RpdHu.js → index-Bg-SUCFg.js} +1 -1
  108. package/dist/assets/{index-gGTMFUa8.js → index-Cz4YpHVi.js} +1 -1
  109. package/dist/assets/main-9G7IpQpK.css +1 -0
  110. package/dist/assets/main-BofFsH8E.js +1085 -0
  111. package/dist/index.html +2 -2
  112. package/dist/manifest.json +9 -2
  113. package/package.json +1 -1
  114. package/shared/types/containers/container.ts +366 -0
  115. package/shared/types/containers/index.ts +5 -0
  116. package/shared/types/database/schema.ts +26 -0
  117. package/shared/types/host/index.ts +18 -0
  118. package/shared/types/ports/port.ts +47 -9
  119. package/shared/utils/logger.ts +3 -0
  120. package/shared/utils/workspace-scope.test.ts +80 -0
  121. package/shared/utils/workspace-scope.ts +57 -0
  122. package/shared/utils/ws-client.ts +92 -17
  123. package/shared/utils/ws-server.ts +83 -16
  124. package/dist/assets/main-CYCMEbXB.css +0 -1
  125. package/dist/assets/main-ZCojSzvW.js +0 -1060
@@ -0,0 +1,170 @@
1
+ /**
2
+ * Containers — what the host is holding, measured off the request path.
3
+ *
4
+ * `system df` is the one container command whose cost is set by how much disk
5
+ * the host holds rather than by how many containers it runs. The daemon walks
6
+ * every image layer and stats every file in every volume to answer it. On a
7
+ * developer machine with a few hundred volumes on a virtualised filesystem that
8
+ * is over a minute, and the volumes are almost all of it — measured on one such
9
+ * host: images 2.6s, containers 0.4s, build cache 0.3s, volumes 47s.
10
+ *
11
+ * That is too long to hold a request open for, and there is no shorter way to
12
+ * ask: the runtimes' own CLIs expose no way to measure part of it, and reaching
13
+ * for the Engine API's type filter would mean talking to a unix socket directly
14
+ * rather than through the one CommandRunner that makes a local host and an SSH
15
+ * host the same code.
16
+ *
17
+ * So the measurement is a background job. Asking for it returns whatever was
18
+ * last measured — immediately, however old — and starts a fresh reading only if
19
+ * the old one has gone stale. The fresh reading is pushed to whoever asked when
20
+ * it lands. Nothing ever waits on a command whose duration is set by someone
21
+ * else's disk.
22
+ *
23
+ * A host's reading outlives its connection. Clearing it on teardown would mean
24
+ * the monitor importing this module while this one imports the monitor, to save
25
+ * one small object per host that has ever been opened — and a reading that
26
+ * survives a reconnect is re-measured by the staleness check anyway.
27
+ */
28
+
29
+ import type { ContainerDiskUsage } from '$shared/types/containers';
30
+ import { DISK_USAGE_STALE_MS, DISK_USAGE_TIMEOUT_MS } from '$shared/types/containers';
31
+ import { containerMonitor } from './monitor';
32
+ import { containerArgv, detectRuntime, firstProblem, tryRun } from './runtime';
33
+ import { parseDiskUsage } from './parse';
34
+ import { ws } from '../utils/ws';
35
+ import { debug } from '$shared/utils/logger';
36
+
37
+ interface HostUsage {
38
+ /** The last completed reading, kept until something invalidates it. */
39
+ last: ContainerDiskUsage | null;
40
+ /** Users to push the in-flight reading to when it lands. */
41
+ waiting: Set<string>;
42
+ measuring: boolean;
43
+ }
44
+
45
+ const hosts = new Map<string, HostUsage>();
46
+
47
+ function stateFor(hostId: string): HostUsage {
48
+ const existing = hosts.get(hostId);
49
+ if (existing) return existing;
50
+ const created: HostUsage = { last: null, waiting: new Set(), measuring: false };
51
+ hosts.set(hostId, created);
52
+ return created;
53
+ }
54
+
55
+ /**
56
+ * Whether a reading is old enough to be worth paying for another one.
57
+ *
58
+ * A reading with no usable stamp counts as stale: it came from somewhere that
59
+ * did not say when it was taken, and guessing that it is current would pin a
60
+ * wrong number on screen until something invalidated it.
61
+ */
62
+ export function isDiskUsageStale(usage: ContainerDiskUsage | null, now: number): boolean {
63
+ if (!usage?.measuredAt) return true;
64
+ const measuredAt = Date.parse(usage.measuredAt);
65
+ if (Number.isNaN(measuredAt)) return true;
66
+ return now - measuredAt >= DISK_USAGE_STALE_MS;
67
+ }
68
+
69
+ /** Run the measurement itself. Slow by nature, so nothing calls this directly. */
70
+ async function measure(hostId: string): Promise<ContainerDiskUsage> {
71
+ const measuredAt = new Date().toISOString();
72
+
73
+ return containerMonitor.withHost(hostId, async (runner, platform) => {
74
+ const info = await detectRuntime(hostId, runner, platform);
75
+ if (info.problem !== 'none' || !info.runtime) {
76
+ return {
77
+ rows: [],
78
+ error: 'This host has no container runtime available right now.',
79
+ measuredAt
80
+ };
81
+ }
82
+
83
+ const result = await tryRun(
84
+ runner,
85
+ containerArgv(info.runtime, platform, [
86
+ 'system',
87
+ 'df',
88
+ '--format',
89
+ info.runtime === 'docker' ? '{{json .}}' : 'json'
90
+ ]),
91
+ DISK_USAGE_TIMEOUT_MS
92
+ );
93
+ if (result.code !== 0) {
94
+ return {
95
+ rows: [],
96
+ error: firstProblem(result.stderr, result.stdout, result.code),
97
+ measuredAt
98
+ };
99
+ }
100
+ return { ...parseDiskUsage(result.stdout, info.runtime), measuredAt };
101
+ });
102
+ }
103
+
104
+ /**
105
+ * Start a reading if one is warranted, and register the caller for the result.
106
+ *
107
+ * A second caller arriving while a reading is in flight joins that one rather
108
+ * than starting a second: two dialogs open on the same host must not make the
109
+ * daemon walk the same disk twice.
110
+ */
111
+ function startMeasuring(hostId: string, userId: string): void {
112
+ const state = stateFor(hostId);
113
+ state.waiting.add(userId);
114
+ if (state.measuring) return;
115
+ state.measuring = true;
116
+
117
+ void (async () => {
118
+ let usage: ContainerDiskUsage;
119
+ try {
120
+ usage = await measure(hostId);
121
+ } catch (error) {
122
+ debug.warn('containers', `could not measure disk usage on ${hostId}:`, error);
123
+ usage = {
124
+ rows: [],
125
+ error: error instanceof Error ? error.message : String(error),
126
+ measuredAt: new Date().toISOString()
127
+ };
128
+ }
129
+
130
+ // A reading that failed is still a reading: caching it stops a broken host
131
+ // being re-measured on every open. An invalidate clears it either way.
132
+ state.last = usage;
133
+ state.measuring = false;
134
+
135
+ const waiting = [...state.waiting];
136
+ state.waiting.clear();
137
+ for (const id of waiting) {
138
+ ws.emit.user(id, 'containers:disk-usage-measured', { hostId, usage });
139
+ }
140
+ })();
141
+ }
142
+
143
+ /**
144
+ * What the dialog gets when it opens: the last reading, and whether a fresh one
145
+ * is on its way.
146
+ *
147
+ * `force` is the Re-check button — the one case where someone has decided the
148
+ * cached answer is not good enough and is willing to wait for a new one.
149
+ */
150
+ export function requestDiskUsage(
151
+ hostId: string,
152
+ userId: string,
153
+ force = false
154
+ ): { usage: ContainerDiskUsage | null; measuring: boolean } {
155
+ const state = stateFor(hostId);
156
+ if (force || isDiskUsageStale(state.last, Date.now())) startMeasuring(hostId, userId);
157
+ return { usage: state.last, measuring: state.measuring };
158
+ }
159
+
160
+ /**
161
+ * Drop a host's reading, because something changed what it would say.
162
+ *
163
+ * Called after a prune or a removal: that is exactly when these numbers move,
164
+ * and showing the figures the sweep was meant to fix would read as the sweep
165
+ * having done nothing.
166
+ */
167
+ export function invalidateDiskUsage(hostId: string): void {
168
+ const state = hosts.get(hostId);
169
+ if (state) state.last = null;
170
+ }
@@ -0,0 +1,335 @@
1
+ /**
2
+ * Containers — following a container's output.
3
+ *
4
+ * `docker logs -f` never returns, which is the one thing the shared
5
+ * `CommandRunner` cannot carry: locally it buffers a command to completion, and
6
+ * remotely it queues commands one at a time on a connection the terminal and
7
+ * file browser share — a follow would sit at the head of that queue forever. So
8
+ * a stream gets its own channel on both transports, and pays for it with hard
9
+ * limits: a bounded number of streams per host, and a bounded ring buffer per
10
+ * stream so a container writing a megabyte a second cannot grow this process's
11
+ * memory without limit.
12
+ *
13
+ * Output is coalesced and flushed on a short interval rather than pushed per
14
+ * chunk. A build log arrives in hundreds of tiny writes, and one WebSocket
15
+ * frame each would cost more than the log is worth.
16
+ */
17
+
18
+ import type { Client as SshClient, ClientChannel } from 'ssh2';
19
+ import { CONTAINER_LOG_BUFFER_LINES } from '$shared/types/containers';
20
+ import { LOCAL_HOST_ID } from '$shared/types/host';
21
+ import { containerMonitor } from './monitor';
22
+ import { assertContainerId } from './actions';
23
+ import { containerArgv, detectRuntime } from './runtime';
24
+ import { localPlatform, type ProbePlatform } from '../host/runner';
25
+ import { detectRemotePlatform } from '../host/runner';
26
+ import { shellQuote } from '../ssh/connect';
27
+ import { sshClientPool, type SshLease } from '../ssh/client-pool';
28
+ import { sshConnectionQueries } from '../database/queries';
29
+ import { ws } from '../utils/ws';
30
+ import { debug } from '$shared/utils/logger';
31
+
32
+ /** Lines asked for when a stream opens, so the view is not blank. */
33
+ const TAIL_LINES = 500;
34
+ /**
35
+ * Streams a single host may have open at once.
36
+ *
37
+ * Bounded for SSH's sake: every follow holds an exec channel, and sshd's
38
+ * `MaxSessions` is ten by default — shared with the terminal, the file browser
39
+ * and the port scan. Three leaves room for all of them.
40
+ */
41
+ const MAX_STREAMS_PER_HOST = 3;
42
+ /** How often buffered output is pushed to the client. */
43
+ const FLUSH_INTERVAL_MS = 120;
44
+
45
+ interface LogStream {
46
+ id: string;
47
+ hostId: string;
48
+ containerId: string;
49
+ userId: string;
50
+ /** The last N lines, so a reopened view is not empty while it waits. */
51
+ buffer: string[];
52
+ pending: string;
53
+ flushTimer: ReturnType<typeof setInterval> | null;
54
+ stop: () => void;
55
+ stopped: boolean;
56
+ }
57
+
58
+ const streams = new Map<string, LogStream>();
59
+
60
+ /** One stream per user per container: a second tab joins the first. */
61
+ function streamIdFor(userId: string, hostId: string, containerId: string): string {
62
+ return `${userId}:${hostId}:${containerId}`;
63
+ }
64
+
65
+ function countForHost(hostId: string): number {
66
+ let count = 0;
67
+ for (const stream of streams.values()) if (stream.hostId === hostId) count++;
68
+ return count;
69
+ }
70
+
71
+ /**
72
+ * Keep the ring bounded, counting lines rather than bytes so a trim never cuts
73
+ * a line in half. The buffer holds lines without their newlines, so a chunk's
74
+ * first piece continues whatever line the previous chunk left open — output
75
+ * arrives in arbitrary slices, not conveniently at line boundaries.
76
+ */
77
+ function appendToBuffer(stream: LogStream, text: string): void {
78
+ const lines = text.split('\n');
79
+ if (stream.buffer.length > 0) {
80
+ stream.buffer[stream.buffer.length - 1] += lines.shift() ?? '';
81
+ }
82
+ for (const line of lines) stream.buffer.push(line);
83
+ if (stream.buffer.length > CONTAINER_LOG_BUFFER_LINES) {
84
+ stream.buffer.splice(0, stream.buffer.length - CONTAINER_LOG_BUFFER_LINES);
85
+ }
86
+ }
87
+
88
+ function push(stream: LogStream, text: string): void {
89
+ if (!text) return;
90
+ appendToBuffer(stream, text);
91
+ stream.pending += text;
92
+ }
93
+
94
+ function flush(stream: LogStream): void {
95
+ if (!stream.pending) return;
96
+ const data = stream.pending;
97
+ stream.pending = '';
98
+ ws.emit.user(stream.userId, 'containers:log-chunk', {
99
+ streamId: stream.id,
100
+ hostId: stream.hostId,
101
+ containerId: stream.containerId,
102
+ data
103
+ });
104
+ }
105
+
106
+ function finish(stream: LogStream, error: string | null): void {
107
+ if (stream.stopped) return;
108
+ stream.stopped = true;
109
+ flush(stream);
110
+ if (stream.flushTimer) clearInterval(stream.flushTimer);
111
+ streams.delete(stream.id);
112
+ ws.emit.user(stream.userId, 'containers:log-chunk', {
113
+ streamId: stream.id,
114
+ hostId: stream.hostId,
115
+ containerId: stream.containerId,
116
+ data: '',
117
+ done: true,
118
+ error
119
+ });
120
+ }
121
+
122
+ export interface StartedLogStream {
123
+ streamId: string;
124
+ /** Whatever the ring already holds, for a view that is joining late. */
125
+ backlog: string;
126
+ }
127
+
128
+ /**
129
+ * Start following a container, or join the stream already following it.
130
+ *
131
+ * The container is verified against a fresh listing first: the id arrived from
132
+ * a client, and a stream is a process held open on someone's machine.
133
+ */
134
+ export async function startLogStream(
135
+ hostId: string,
136
+ containerId: string,
137
+ userId: string
138
+ ): Promise<StartedLogStream> {
139
+ assertContainerId(containerId);
140
+
141
+ const id = streamIdFor(userId, hostId, containerId);
142
+ const existing = streams.get(id);
143
+ // Rejoined with the newlines the buffer strips, or the whole backlog would
144
+ // arrive as one enormous line.
145
+ if (existing) return { streamId: id, backlog: existing.buffer.join('\n') };
146
+
147
+ const container = await containerMonitor.findContainer(hostId, containerId);
148
+ if (!container) throw new Error('That container no longer exists on this host.');
149
+
150
+ if (countForHost(hostId) >= MAX_STREAMS_PER_HOST) {
151
+ throw new Error(
152
+ `Already following ${MAX_STREAMS_PER_HOST} logs on this host. Close one before opening another.`
153
+ );
154
+ }
155
+
156
+ const stream: LogStream = {
157
+ id,
158
+ hostId,
159
+ containerId,
160
+ userId,
161
+ buffer: [],
162
+ pending: '',
163
+ flushTimer: null,
164
+ stop: () => undefined,
165
+ stopped: false
166
+ };
167
+ streams.set(id, stream);
168
+
169
+ stream.flushTimer = setInterval(() => flush(stream), FLUSH_INTERVAL_MS);
170
+ stream.flushTimer.unref?.();
171
+
172
+ try {
173
+ if (hostId === LOCAL_HOST_ID) await followLocal(stream);
174
+ else await followRemote(stream);
175
+ } catch (error) {
176
+ finish(stream, error instanceof Error ? error.message : String(error));
177
+ throw error;
178
+ }
179
+
180
+ debug.log('containers', `following logs for ${container.name} on ${hostId}`);
181
+ return { streamId: id, backlog: '' };
182
+ }
183
+
184
+ /** The argv both transports run, once the runtime is known. */
185
+ async function logArgv(
186
+ hostId: string,
187
+ containerId: string,
188
+ platform: ProbePlatform
189
+ ): Promise<string[]> {
190
+ const info = await containerMonitor.withHost(hostId, (runner) =>
191
+ detectRuntime(hostId, runner, platform)
192
+ );
193
+ if (info.problem !== 'none' || !info.runtime) {
194
+ throw new Error('This host has no container runtime available right now.');
195
+ }
196
+ return containerArgv(info.runtime, platform, [
197
+ 'logs',
198
+ '--follow',
199
+ '--tail',
200
+ String(TAIL_LINES),
201
+ containerId
202
+ ]);
203
+ }
204
+
205
+ async function followLocal(stream: LogStream): Promise<void> {
206
+ const platform = localPlatform();
207
+ const argv = await logArgv(stream.hostId, stream.containerId, platform);
208
+
209
+ const child = Bun.spawn(argv, { stdout: 'pipe', stderr: 'pipe', stdin: 'ignore' });
210
+ stream.stop = () => {
211
+ try {
212
+ child.kill();
213
+ } catch {
214
+ // Already gone.
215
+ }
216
+ };
217
+
218
+ // `docker logs` writes a container's stdout and stderr to its own two
219
+ // streams; a reader wants them interleaved exactly as the container wrote
220
+ // them, so both are pumped into the same buffer.
221
+ void pump(child.stdout, stream);
222
+ void pump(child.stderr, stream);
223
+ void child.exited.then((code) => {
224
+ finish(stream, code === 0 || stream.stopped ? null : `The log command exited with status ${code}.`);
225
+ });
226
+ }
227
+
228
+ async function pump(readable: ReadableStream<Uint8Array> | null, stream: LogStream): Promise<void> {
229
+ if (!readable) return;
230
+ const decoder = new TextDecoder();
231
+ const reader = readable.getReader();
232
+ try {
233
+ for (;;) {
234
+ const { done, value } = await reader.read();
235
+ if (done || stream.stopped) return;
236
+ if (value) push(stream, decoder.decode(value, { stream: true }));
237
+ }
238
+ } catch (error) {
239
+ debug.log('containers', 'log stream ended:', error);
240
+ } finally {
241
+ reader.releaseLock();
242
+ }
243
+ }
244
+
245
+ async function followRemote(stream: LogStream): Promise<void> {
246
+ const connection = sshConnectionQueries.get(stream.hostId);
247
+ if (!connection) throw new Error('That SSH host no longer exists.');
248
+
249
+ const platform = await containerMonitor.withHost(stream.hostId, (runner) =>
250
+ detectRemotePlatform(stream.hostId, runner)
251
+ );
252
+ const argv = await logArgv(stream.hostId, stream.containerId, platform);
253
+ // Its own lease, not the shared queued runner: this channel never closes on
254
+ // its own, and everything behind it in that queue would wait forever.
255
+ const lease = await sshClientPool.acquire(stream.hostId);
256
+
257
+ try {
258
+ const channel = await openExec(lease.client, argv.map(shellQuote).join(' '));
259
+ let released = false;
260
+ const release = (): void => {
261
+ if (released) return;
262
+ released = true;
263
+ lease.release();
264
+ };
265
+
266
+ stream.stop = () => {
267
+ try {
268
+ channel.close();
269
+ } catch {
270
+ // Already gone.
271
+ }
272
+ release();
273
+ };
274
+
275
+ const decoder = new TextDecoder();
276
+ channel.on('data', (chunk: Buffer) => push(stream, decoder.decode(chunk, { stream: true })));
277
+ channel.stderr.on('data', (chunk: Buffer) => push(stream, decoder.decode(chunk, { stream: true })));
278
+ channel.on('close', () => {
279
+ release();
280
+ finish(stream, null);
281
+ });
282
+ channel.on('error', (error: Error) => {
283
+ release();
284
+ finish(stream, error.message);
285
+ });
286
+ } catch (error) {
287
+ lease.release();
288
+ throw error;
289
+ }
290
+ }
291
+
292
+ function openExec(client: SshClient, command: string): Promise<ClientChannel> {
293
+ return new Promise((resolve, reject) => {
294
+ client.exec(command, (error, channel) => {
295
+ if (error) reject(error);
296
+ else resolve(channel);
297
+ });
298
+ });
299
+ }
300
+
301
+ /** Stop one stream, if it belongs to this user. */
302
+ export function stopLogStream(streamId: string, userId: string): void {
303
+ const stream = streams.get(streamId);
304
+ if (!stream || stream.userId !== userId) return;
305
+ stream.stop();
306
+ finish(stream, null);
307
+ }
308
+
309
+ /** Stop every stream a user holds, when their socket goes away. */
310
+ export function stopLogStreamsForUser(userId: string): void {
311
+ for (const stream of [...streams.values()]) {
312
+ if (stream.userId === userId) {
313
+ stream.stop();
314
+ finish(stream, null);
315
+ }
316
+ }
317
+ }
318
+
319
+ /** Stop everything, when the process is shutting down. */
320
+ export function stopAllLogStreams(): void {
321
+ for (const stream of [...streams.values()]) {
322
+ stream.stop();
323
+ finish(stream, null);
324
+ }
325
+ }
326
+
327
+ /** Stop every stream on a host, when its connection is edited or deleted. */
328
+ export function stopLogStreamsForHost(hostId: string): void {
329
+ for (const stream of [...streams.values()]) {
330
+ if (stream.hostId === hostId) {
331
+ stream.stop();
332
+ finish(stream, null);
333
+ }
334
+ }
335
+ }