fix: unify stream cleanup and configuration response handling
This commit is contained in:
1 parent
38a7c3da63
commit
1faa6c58fa
13 files changed
+463
-247
No files matched your search
@@ -20,6 +20,7 @@ import os from 'os';
|
||||
import path from 'path';
|
||||
import { randomBytes } from 'crypto';
|
||||
import { traceWebuiMutationRequestChunk } from './mutation-trace';
|
||||
import { sseResponse } from './sse-response';
|
||||
|
||||
/** Temp dir for browser→server uploads. Siblings the Stream API's temp root but
|
||||
* kept distinct so the two cleanup stories don't entangle. */
|
||||
@@ -203,70 +204,43 @@ export function buildStreamInvokeResponse(
|
||||
signal: AbortSignal,
|
||||
delay: (ms: number) => Promise<void> = (ms) => new Promise((r) => setTimeout(r, ms)),
|
||||
): Response {
|
||||
const encoder = new TextEncoder();
|
||||
const stream = new ReadableStream<Uint8Array>({
|
||||
async start(controller) {
|
||||
let closed = false;
|
||||
return sseResponse(signal, (channel) => {
|
||||
const isAlive = () => !channel.isClosed();
|
||||
|
||||
const onAbort = () => {
|
||||
closed = true;
|
||||
};
|
||||
const emit = async (json: string): Promise<void> => {
|
||||
if (!isAlive()) {
|
||||
throw new Error('stream transport closed');
|
||||
}
|
||||
|
||||
signal.addEventListener('abort', onAbort);
|
||||
const isAlive = () => !closed && !signal.aborted;
|
||||
// Backpressure WITHOUT dropping: wait for the consumer to catch up.
|
||||
let spins = 0;
|
||||
|
||||
const emit = async (json: string): Promise<void> => {
|
||||
if (!isAlive()) {
|
||||
throw new Error('stream transport closed');
|
||||
}
|
||||
while (isAlive() && (channel.desiredSize() ?? 1) <= 0 && spins < DRAIN_MAX_SPINS) {
|
||||
await delay(DRAIN_WAIT_MS);
|
||||
spins += 1;
|
||||
}
|
||||
|
||||
// Backpressure WITHOUT dropping: wait for the consumer to catch up.
|
||||
let spins = 0;
|
||||
if (!isAlive()) {
|
||||
throw new Error('stream transport closed');
|
||||
}
|
||||
|
||||
while (isAlive() && (controller.desiredSize ?? 1) <= 0 && spins < DRAIN_MAX_SPINS) {
|
||||
await delay(DRAIN_WAIT_MS);
|
||||
spins += 1;
|
||||
}
|
||||
|
||||
if (!isAlive()) {
|
||||
throw new Error('stream transport closed');
|
||||
}
|
||||
|
||||
controller.enqueue(encoder.encode(`data: ${json}\n\n`));
|
||||
};
|
||||
channel.raw(channel.encode(`data: ${json}\n\n`));
|
||||
};
|
||||
|
||||
const run = async () => {
|
||||
try {
|
||||
await driver(rawRequest, emit, isAlive);
|
||||
} catch (err) {
|
||||
if (isAlive()) {
|
||||
const msg = err instanceof Error ? err.message : 'stream error';
|
||||
|
||||
try {
|
||||
controller.enqueue(
|
||||
encoder.encode(
|
||||
`data: ${JSON.stringify({ status: 'failed', retcode: 1400, message: msg, wording: msg })}\n\n`,
|
||||
),
|
||||
);
|
||||
} catch {
|
||||
/* controller already torn down */
|
||||
}
|
||||
channel.send({ status: 'failed', retcode: 1400, message: msg, wording: msg });
|
||||
}
|
||||
} finally {
|
||||
signal.removeEventListener('abort', onAbort);
|
||||
|
||||
try {
|
||||
controller.close();
|
||||
} catch {
|
||||
/* already closed */
|
||||
}
|
||||
channel.close();
|
||||
}
|
||||
},
|
||||
});
|
||||
return new Response(stream, {
|
||||
headers: {
|
||||
'Content-Type': 'text/event-stream',
|
||||
'Cache-Control': 'no-cache',
|
||||
Connection: 'keep-alive',
|
||||
},
|
||||
};
|
||||
|
||||
void run();
|
||||
});
|
||||
}
|
||||
@@ -753,8 +753,8 @@ export async function initWebUI(
|
||||
|
||||
const app = new Hono();
|
||||
const shutdownStreams = new AbortController();
|
||||
const sseResponse = (...args: Parameters<typeof createSseResponse>) =>
|
||||
createSseResponse(args[0], args[1], shutdownStreams.signal);
|
||||
const sseResponse = (c: Context, start: Parameters<typeof createSseResponse>[1]) =>
|
||||
createSseResponse(c.req.raw.signal, start, shutdownStreams.signal);
|
||||
app.use('*', webuiSecurityHeaders);
|
||||
registerLoginRequestSecurity(app);
|
||||
const storageManagement = new StorageManagementService({
|
||||
@@ -1726,7 +1726,7 @@ export async function initWebUI(
|
||||
return buildStreamInvokeResponse(
|
||||
(rq, emit, alive) => inst.invokeStream(rq, emit, alive),
|
||||
rawRequest,
|
||||
c.req.raw.signal,
|
||||
AbortSignal.any([c.req.raw.signal, shutdownStreams.signal]),
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -1,42 +1,25 @@
|
||||
import { type Context } from 'hono';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
|
||||
const log = createLogger('WebUI.SSE');
|
||||
|
||||
/**
|
||||
* The per-connection channel handed to an SSE endpoint's `start` callback.
|
||||
* Everything the endpoint needs to talk to the client, without owning the
|
||||
* transport lifecycle (heartbeat / teardown / abort / headers).
|
||||
*/
|
||||
export interface SseChannel {
|
||||
/** Enqueue a raw chunk. Tears the stream down if the peer is already gone. */
|
||||
raw(chunk: Uint8Array): void;
|
||||
/** Encode a string to bytes (shared TextEncoder). */
|
||||
encode(s: string): Uint8Array;
|
||||
/** Convenience: enqueue one `data: <json>\n\n` frame. */
|
||||
send(payload: unknown): void;
|
||||
/** Register a cleanup to run once on teardown (unsubscribe / dispose). */
|
||||
onClose(fn: () => void): void;
|
||||
/** True after teardown — guard sends from late subscription callbacks. */
|
||||
onClose(cleanup: () => void): void;
|
||||
close(): void;
|
||||
isClosed(): boolean;
|
||||
/** Underlying controller backpressure signal, for `createFramePusher`. */
|
||||
desiredSize(): number | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The SSE HTTP transport shell shared by the WebUI's live endpoints. Owns the
|
||||
* TextEncoder, a `closed` guard, a 15s `: heartbeat` keep-alive, teardown
|
||||
* (clear heartbeat → run registered cleanups → close the controller), safe
|
||||
* enqueue (a throw means the peer dropped → teardown), the abort listener, and
|
||||
* the `text/event-stream` headers. `start` wires up the endpoint-specific
|
||||
* subscription + initial sends via the channel.
|
||||
*
|
||||
* Each of `/api/debug/stream`, `/api/state/stream`, `/api/logs/stream`
|
||||
* previously hand-copied this ~40-line skeleton; a heartbeat-interval /
|
||||
* teardown-order / header change had to be kept in sync across all three.
|
||||
*/
|
||||
/** Owns stream cancellation, subscriptions and the keep-alive timer. */
|
||||
export function sseResponse(
|
||||
c: Context,
|
||||
start: (ch: SseChannel) => void,
|
||||
request: AbortSignal,
|
||||
start: (channel: SseChannel) => void,
|
||||
shutdown?: AbortSignal,
|
||||
): Response {
|
||||
const signal = shutdown ? AbortSignal.any([request, shutdown]) : request;
|
||||
let cancel!: () => void;
|
||||
const stream = new ReadableStream<Uint8Array>({
|
||||
start(controller) {
|
||||
const encoder = new TextEncoder();
|
||||
@@ -44,67 +27,78 @@ export function sseResponse(
|
||||
let heartbeat: ReturnType<typeof setInterval> | undefined;
|
||||
const cleanups: Array<() => void> = [];
|
||||
|
||||
const teardown = () => {
|
||||
const cleanup = (fn: () => void) => {
|
||||
try {
|
||||
fn();
|
||||
} catch (error) {
|
||||
log.warn('stream cleanup failed: %s', error);
|
||||
}
|
||||
};
|
||||
|
||||
const teardown = (closeStream = true) => {
|
||||
if (closed) {
|
||||
return;
|
||||
}
|
||||
|
||||
closed = true;
|
||||
clearInterval(heartbeat);
|
||||
signal.removeEventListener('abort', onAbort);
|
||||
cleanups.splice(0).forEach(cleanup);
|
||||
|
||||
if (heartbeat) {
|
||||
clearInterval(heartbeat);
|
||||
}
|
||||
|
||||
for (const fn of cleanups) {
|
||||
try {
|
||||
fn();
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
if (closeStream) {
|
||||
controller.close();
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
};
|
||||
|
||||
const onAbort = () => teardown();
|
||||
cancel = () => teardown(false);
|
||||
signal.addEventListener('abort', onAbort, { once: true });
|
||||
|
||||
if (signal.aborted) {
|
||||
teardown();
|
||||
return;
|
||||
}
|
||||
|
||||
const raw = (chunk: Uint8Array) => {
|
||||
if (closed) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
if (!closed) {
|
||||
controller.enqueue(chunk);
|
||||
} catch {
|
||||
teardown();
|
||||
}
|
||||
};
|
||||
|
||||
const ch: SseChannel = {
|
||||
const channel: SseChannel = {
|
||||
raw,
|
||||
encode: (s) => encoder.encode(s),
|
||||
send: (payload) => raw(encoder.encode(`data: ${JSON.stringify(payload)}\n\n`)),
|
||||
onClose: (fn) => {
|
||||
cleanups.push(fn);
|
||||
encode: (text) => encoder.encode(text),
|
||||
send: (payload) => {
|
||||
if (!closed) {
|
||||
raw(encoder.encode(`data: ${JSON.stringify(payload)}\n\n`));
|
||||
}
|
||||
},
|
||||
onClose: (fn) => {
|
||||
if (closed) {
|
||||
cleanup(fn);
|
||||
} else {
|
||||
cleanups.push(fn);
|
||||
}
|
||||
},
|
||||
close: () => teardown(),
|
||||
isClosed: () => closed,
|
||||
desiredSize: () => controller.desiredSize,
|
||||
};
|
||||
start(ch);
|
||||
heartbeat = setInterval(() => raw(encoder.encode(': heartbeat\n\n')), 15000);
|
||||
c.req.raw.signal.addEventListener('abort', teardown);
|
||||
shutdown?.addEventListener('abort', teardown, { once: true });
|
||||
cleanups.push(() => {
|
||||
c.req.raw.signal.removeEventListener('abort', teardown);
|
||||
shutdown?.removeEventListener('abort', teardown);
|
||||
});
|
||||
|
||||
if (shutdown?.aborted) {
|
||||
try {
|
||||
start(channel);
|
||||
|
||||
if (!closed) {
|
||||
heartbeat = setInterval(() => raw(encoder.encode(': heartbeat\n\n')), 15000);
|
||||
}
|
||||
} catch (error) {
|
||||
teardown();
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
cancel() {
|
||||
cancel();
|
||||
},
|
||||
});
|
||||
return new Response(stream, {
|
||||
headers: {
|
||||
|
||||
@@ -1,18 +1,75 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { afterEach, describe, it, expect, vi } from 'vitest';
|
||||
import { sseResponse } from '../src/webui/sse-response';
|
||||
|
||||
// A minimal hono-Context stand-in: sseResponse only reads c.req.raw.signal.
|
||||
function fakeCtx(signal: AbortSignal): Parameters<typeof sseResponse>[0] {
|
||||
return { req: { raw: { signal } } } as unknown as Parameters<typeof sseResponse>[0];
|
||||
}
|
||||
|
||||
describe('sseResponse', () => {
|
||||
afterEach(() => {
|
||||
vi.clearAllTimers();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('releases subscriptions immediately when the response body is canceled', async () => {
|
||||
vi.useFakeTimers();
|
||||
const request = new AbortController();
|
||||
const cleanup = vi.fn();
|
||||
let channel!: Parameters<Parameters<typeof sseResponse>[1]>[0];
|
||||
const response = sseResponse(request.signal, (ch) => {
|
||||
channel = ch;
|
||||
ch.onClose(cleanup);
|
||||
});
|
||||
|
||||
await response.body!.cancel();
|
||||
expect(channel.isClosed()).toBe(true);
|
||||
expect(cleanup).toHaveBeenCalledOnce();
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
request.abort();
|
||||
expect(cleanup).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('does not subscribe when the request was already aborted', () => {
|
||||
vi.useFakeTimers();
|
||||
const request = new AbortController();
|
||||
request.abort();
|
||||
const start = vi.fn();
|
||||
sseResponse(request.signal, start);
|
||||
expect(start).not.toHaveBeenCalled();
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
});
|
||||
|
||||
it('releases subscriptions registered before and after an abort during setup', () => {
|
||||
vi.useFakeTimers();
|
||||
const request = new AbortController();
|
||||
const before = vi.fn();
|
||||
const after = vi.fn();
|
||||
sseResponse(request.signal, (channel) => {
|
||||
channel.onClose(before);
|
||||
request.abort();
|
||||
channel.onClose(after);
|
||||
});
|
||||
expect(before).toHaveBeenCalledOnce();
|
||||
expect(after).toHaveBeenCalledOnce();
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
});
|
||||
|
||||
it('releases subscriptions when endpoint setup throws', () => {
|
||||
vi.useFakeTimers();
|
||||
const request = new AbortController();
|
||||
const cleanup = vi.fn();
|
||||
expect(() =>
|
||||
sseResponse(request.signal, (channel) => {
|
||||
channel.onClose(cleanup);
|
||||
throw new Error('setup failed');
|
||||
}),
|
||||
).toThrow('setup failed');
|
||||
expect(cleanup).toHaveBeenCalledOnce();
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
});
|
||||
|
||||
it('finishes active streams and releases subscriptions during server shutdown', async () => {
|
||||
const request = new AbortController();
|
||||
const shutdown = new AbortController();
|
||||
let cleanups = 0;
|
||||
const response = sseResponse(
|
||||
fakeCtx(request.signal),
|
||||
request.signal,
|
||||
(channel) => {
|
||||
channel.onClose(() => {
|
||||
cleanups++;
|
||||
@@ -26,9 +83,10 @@ describe('sseResponse', () => {
|
||||
request.abort();
|
||||
expect(cleanups).toBe(1);
|
||||
});
|
||||
|
||||
it('returns an event-stream Response with the SSE headers', () => {
|
||||
const ac = new AbortController();
|
||||
const res = sseResponse(fakeCtx(ac.signal), () => {
|
||||
const res = sseResponse(ac.signal, () => {
|
||||
/* no-op */
|
||||
});
|
||||
expect(res.headers.get('Content-Type')).toBe('text/event-stream');
|
||||
@@ -39,7 +97,7 @@ describe('sseResponse', () => {
|
||||
|
||||
it('ch.send frames JSON as `data: …` and ch.raw enqueues verbatim', async () => {
|
||||
const ac = new AbortController();
|
||||
const res = sseResponse(fakeCtx(ac.signal), (ch) => {
|
||||
const res = sseResponse(ac.signal, (ch) => {
|
||||
ch.send({ type: 'ready' });
|
||||
ch.raw(ch.encode(': heartbeat\n\n'));
|
||||
});
|
||||
@@ -56,7 +114,7 @@ describe('sseResponse', () => {
|
||||
const cleanupA = vi.fn();
|
||||
const cleanupB = vi.fn();
|
||||
let channel!: Parameters<Parameters<typeof sseResponse>[1]>[0];
|
||||
const res = sseResponse(fakeCtx(ac.signal), (ch) => {
|
||||
const res = sseResponse(ac.signal, (ch) => {
|
||||
channel = ch;
|
||||
ch.onClose(cleanupA);
|
||||
ch.onClose(cleanupB);
|
||||
@@ -75,7 +133,7 @@ describe('sseResponse', () => {
|
||||
it('send after teardown is a silent no-op', () => {
|
||||
const ac = new AbortController();
|
||||
let channel!: Parameters<Parameters<typeof sseResponse>[1]>[0];
|
||||
sseResponse(fakeCtx(ac.signal), (ch) => {
|
||||
sseResponse(ac.signal, (ch) => {
|
||||
channel = ch;
|
||||
});
|
||||
ac.abort();
|
||||
|
||||
@@ -114,6 +114,45 @@ describe('streamUploadToDisk', () => {
|
||||
describe('buildStreamInvokeResponse', () => {
|
||||
const noDelay = async () => {};
|
||||
|
||||
it('cancels delivery while the action is still pending', async () => {
|
||||
let finish!: () => void;
|
||||
const pending = new Promise<void>((resolve) => {
|
||||
finish = resolve;
|
||||
});
|
||||
let isAlive!: () => boolean;
|
||||
const response = buildStreamInvokeResponse(
|
||||
async (_request, _emit, alive) => {
|
||||
isAlive = alive;
|
||||
await pending;
|
||||
},
|
||||
'{}',
|
||||
new AbortController().signal,
|
||||
);
|
||||
const canceled = response.body!.cancel();
|
||||
|
||||
try {
|
||||
expect(isAlive()).toBe(false);
|
||||
} finally {
|
||||
finish();
|
||||
await canceled;
|
||||
}
|
||||
});
|
||||
|
||||
it('does not invoke an action for an already aborted request', async () => {
|
||||
const controller = new AbortController();
|
||||
controller.abort();
|
||||
let invoked = false;
|
||||
const response = buildStreamInvokeResponse(
|
||||
async () => {
|
||||
invoked = true;
|
||||
},
|
||||
'{}',
|
||||
controller.signal,
|
||||
);
|
||||
await readSse(response);
|
||||
expect(invoked).toBe(false);
|
||||
});
|
||||
|
||||
it('relays each emitted frame as one SSE event, in order', async () => {
|
||||
const ac = new AbortController();
|
||||
|
||||
|
||||
Reference in new issue
Block a user