Introduce backend app for WebSocket terminal sessions and sandbox orchestration.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
7b1df2607e
commit
91049379f7
22 files changed
+808
-11
No files matched your search
@@ -0,0 +1,156 @@
|
||||
import { randomBytes } from 'node:crypto';
|
||||
import type { Duplex } from 'node:stream';
|
||||
import type { ExitReason, ServerMessage, TerminalSize } from '@homepage/protocol/terminal';
|
||||
import type { WebSocket } from 'ws';
|
||||
import { TokenBucket } from './throttle.ts';
|
||||
|
||||
export type Spawner = {
|
||||
spawn(sessionId: string, expiresAt: number): Promise<string>;
|
||||
attach(containerId: string): Promise<Duplex>;
|
||||
resize(containerId: string, cols: number, rows: number): Promise<void>;
|
||||
kill(containerId: string): Promise<void>;
|
||||
};
|
||||
|
||||
export type SessionOptions = {
|
||||
sessionSeconds: number;
|
||||
outputRate: number;
|
||||
log: (message: string) => void;
|
||||
};
|
||||
|
||||
/** Output pauses above the high mark of unsent WebSocket bytes and resumes below the low mark. */
|
||||
const HIGH_WATER_MARK = 256 * 1024;
|
||||
const LOW_WATER_MARK = 64 * 1024;
|
||||
const RECHECK_MS = 25;
|
||||
|
||||
/** One visitor's terminal: a WebSocket bridged to one sandbox container. */
|
||||
export class Session
|
||||
{
|
||||
readonly id = randomBytes(12).toString('base64url');
|
||||
|
||||
private readonly socket: WebSocket;
|
||||
private readonly spawner: Spawner;
|
||||
private readonly options: SessionOptions;
|
||||
private readonly bucket: TokenBucket;
|
||||
|
||||
private containerId?: string;
|
||||
private stream?: Duplex;
|
||||
private expiryTimer?: NodeJS.Timeout;
|
||||
private recheckTimer?: NodeJS.Timeout;
|
||||
private ended = false;
|
||||
|
||||
constructor(socket: WebSocket, spawner: Spawner, options: SessionOptions) {
|
||||
this.socket = socket;
|
||||
this.spawner = spawner;
|
||||
this.options = options;
|
||||
this.bucket = new TokenBucket(options.outputRate);
|
||||
}
|
||||
|
||||
get started(): boolean {
|
||||
return this.stream !== undefined;
|
||||
}
|
||||
|
||||
async start(size: TerminalSize): Promise<void>
|
||||
{
|
||||
const expiresAt = Math.floor(Date.now() / 1000) + this.options.sessionSeconds;
|
||||
this.containerId = await this.spawner.spawn(this.id, expiresAt);
|
||||
if (this.ended) return this.release();
|
||||
|
||||
const stream = await this.spawner.attach(this.containerId);
|
||||
if (this.ended)
|
||||
{
|
||||
stream.destroy();
|
||||
return this.release();
|
||||
}
|
||||
|
||||
this.stream = stream;
|
||||
stream.on('data', (chunk: Buffer) => this.forward(chunk));
|
||||
stream.on('end', () => this.end('closed'));
|
||||
stream.on('close', () => this.end('closed'));
|
||||
stream.on('error', () => this.end('error'));
|
||||
|
||||
this.send({ type: 'ready' });
|
||||
this.resize(size);
|
||||
stream.resume();
|
||||
|
||||
this.expiryTimer = setTimeout(() => this.end('expired'), this.options.sessionSeconds * 1000);
|
||||
this.options.log(`session ${this.id} started`);
|
||||
}
|
||||
|
||||
input(data: Buffer): void {
|
||||
this.stream?.write(data);
|
||||
}
|
||||
|
||||
resize({ cols, rows }: TerminalSize): void
|
||||
{
|
||||
if (!this.containerId || this.ended) return;
|
||||
this.spawner.resize(this.containerId, cols, rows).catch(() => {});
|
||||
}
|
||||
|
||||
/** Ends the session, tells the visitor why, and removes the container. */
|
||||
end(reason: ExitReason): void
|
||||
{
|
||||
if (this.ended) return;
|
||||
this.ended = true;
|
||||
|
||||
this.send({ type: 'exit', reason });
|
||||
this.socket.close(1000);
|
||||
this.release();
|
||||
this.options.log(`session ${this.id} ended (${reason})`);
|
||||
}
|
||||
|
||||
/** Cleans up after the WebSocket is already gone. */
|
||||
dispose(): void
|
||||
{
|
||||
if (this.ended) return;
|
||||
this.ended = true;
|
||||
|
||||
this.release();
|
||||
this.options.log(`session ${this.id} disconnected`);
|
||||
}
|
||||
|
||||
private forward(chunk: Buffer): void
|
||||
{
|
||||
if (this.ended) return;
|
||||
|
||||
this.socket.send(chunk, { binary: true });
|
||||
this.bucket.take(chunk.length);
|
||||
|
||||
if (this.socket.bufferedAmount > HIGH_WATER_MARK || this.bucket.available() <= 0)
|
||||
{
|
||||
this.stream?.pause();
|
||||
this.scheduleRecheck();
|
||||
}
|
||||
}
|
||||
|
||||
private scheduleRecheck(): void
|
||||
{
|
||||
clearTimeout(this.recheckTimer);
|
||||
this.recheckTimer = setTimeout(() =>
|
||||
{
|
||||
if (this.ended) return;
|
||||
|
||||
if (this.socket.bufferedAmount < LOW_WATER_MARK && this.bucket.available() > 0) this.stream?.resume();
|
||||
else this.scheduleRecheck();
|
||||
}, Math.max(RECHECK_MS, this.bucket.millisecondsUntilAvailable()));
|
||||
}
|
||||
|
||||
private send(message: ServerMessage): void
|
||||
{
|
||||
if (this.socket.readyState === this.socket.OPEN) this.socket.send(JSON.stringify(message));
|
||||
}
|
||||
|
||||
private release(): void
|
||||
{
|
||||
clearTimeout(this.expiryTimer);
|
||||
clearTimeout(this.recheckTimer);
|
||||
this.stream?.destroy();
|
||||
|
||||
if (this.containerId)
|
||||
{
|
||||
const containerId = this.containerId;
|
||||
this.spawner.kill(containerId).catch((error: unknown) =>
|
||||
this.options.log(`could not remove ${containerId.slice(0, 12)}: ${String(error)}`),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user