Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169/** * Minimal JSONL socket client for daemon e2e tests (saga tb4593.6, PROTOCOL §12). * * Connects to a real `shardd` unix socket, asserts the `hello` handshake (§9.1), and * exposes `send(cmd)` + `awaitMessage(predicate, timeout)` so tests can drive the protocol * + assert on the event stream. NOT a production client — the TUI/web surfaces are; this * is the thinnest possible harness to prove the proxy against the §12 worked examples. * * Each `awaitMessage` returns the first inbound record matching `predicate`, draining * non-matching records into a buffer (so out-of-order events don't cause spurious * timeouts). All waits race a timer; the caller chooses the timeout (default 2s). */import { createConnection, type Socket } from 'node:net';import { JsonlDecoder } from '@/protocol/framing/jsonl';
export interface SocketClientOptions { /** Per-`awaitMessage` default timeout (ms). Default 2000. */ defaultTimeoutMs?: number; /** Where to log verbose trace (default: nowhere). */ onRecord?: (record: unknown) => void;}
/** A connected test client. */export interface SocketClient { readonly socket: Socket; hello: Record<string, unknown>; /** Send a command (JSONL-encoded). */ send(cmd: Record<string, unknown>): void; /** * Resolve with the first inbound record matching `predicate` (draining non-matches into * a buffer so they're never lost — a later `awaitMessage` will reconsider them). Rejects * on timeout or socket close. */ awaitMessage( predicate: (record: Record<string, unknown>) => boolean, timeoutMs?: number, ): Promise<Record<string, unknown>>; /** Collect every inbound record arriving within `windowMs` (drains the buffer first). */ drain(windowMs: number): Promise<Record<string, unknown>[]>; /** Close the socket. */ close(): Promise<void>;}
/** * Connect to `socketPath`, await + assert `hello`, return the client. Rejects if the * handshake doesn't arrive within `connectTimeoutMs` (default 2s). */export async function connectClient( socketPath: string, opts: SocketClientOptions = {},): Promise<SocketClient> { const defaultTimeoutMs = opts.defaultTimeoutMs ?? 2000; const socket = createConnection({ path: socketPath }); const decoder = new JsonlDecoder(); const buffer: Record<string, unknown>[] = []; /** Resolvers waiting on `awaitMessage`; each gets every inbound record to test. */ const waiters: Array<{ predicate: (r: Record<string, unknown>) => boolean; resolve: (r: Record<string, unknown>) => void; reject: (e: Error) => void; timer: ReturnType<typeof setTimeout>; }> = []; let closed = false;
const dispatch = (record: Record<string, unknown>): void => { opts.onRecord?.(record); // First waiter whose predicate matches consumes; others keep waiting. for (const w of waiters) { if (w.predicate(record)) { clearTimeout(w.timer); waiters.splice(waiters.indexOf(w), 1); w.resolve(record); return; } } buffer.push(record); };
socket.on('data', (chunk: Buffer) => { decoder.write(chunk); for (const rec of decoder.parse()) { if (rec.value === undefined) continue; // skip malformed in the test client dispatch(rec.value as Record<string, unknown>); } }); socket.on('close', () => { closed = true; // Reject every outstanding waiter (the stream ended without a match). for (const w of [...waiters]) { clearTimeout(w.timer); waiters.splice(waiters.indexOf(w), 1); w.reject(new Error('socket closed while awaiting message')); } }); socket.on('error', (err) => { if (!closed) { // Surface the error to outstanding waiters; `close` follows. for (const w of [...waiters]) { clearTimeout(w.timer); waiters.splice(waiters.indexOf(w), 1); w.reject(err); } } });
const awaitMessage = ( predicate: (r: Record<string, unknown>) => boolean, timeoutMs: number | undefined, ): Promise<Record<string, unknown>> => { // Check the buffer first (a previously-drained non-match might satisfy now). for (let i = 0; i < buffer.length; i++) { const rec = buffer[i]; if (rec !== undefined && predicate(rec)) { buffer.splice(i, 1); return Promise.resolve(rec); } } return new Promise<Record<string, unknown>>((resolve, reject) => { const timer = setTimeout(() => { waiters.splice( waiters.findIndex((w) => w.timer === timer), 1, ); reject(new Error(`awaitMessage timed out after ${timeoutMs ?? defaultTimeoutMs}ms`)); }, timeoutMs ?? defaultTimeoutMs); waiters.push({ predicate, resolve, reject, timer }); }); };
// Block until `hello` arrives (§9.1 handshake). const hello = (await awaitMessage( (r) => r.type === 'hello', opts.defaultTimeoutMs ?? 2000, )) as Record<string, unknown>;
return { socket, hello, send: (cmd: Record<string, unknown>) => { socket.write(JSON.stringify(cmd) + '\n'); }, awaitMessage, drain: async (windowMs: number) => { // Drain the buffer synchronously first. const out = [...buffer]; buffer.length = 0; // Then collect everything arriving within the window. const start = Date.now(); while (Date.now() - start < windowMs) { try { const rec = await awaitMessage( () => true, Math.max(1, windowMs - (Date.now() - start)), ); out.push(rec); } catch { break; // timeout or closed — end the window } } return out; }, close: () => new Promise<void>((resolve) => { socket.destroy(); resolve(); }), };}