Skip to content

OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.

ralph(M36-001): Stop computing an answer nobody receives: explicit timeout, abort on client disconnect

ralph1218a59e6235
diff --git a/apps/api/src/main.ts b/apps/api/src/main.ts
index 9578f4f5b..9da18c66e 100644
--- a/apps/api/src/main.ts
+++ b/apps/api/src/main.ts
@@ -67,6 +67,7 @@ import {
type QueueProducerHandle,
queueKey,
queues,
+ RPC_DEADLINE_MS,
rawStderrWrite,
registerBufferMetrics,
registerDefaultMetrics,
@@ -105,6 +106,15 @@ const BOOTSTRAP_LOG_LEVEL = 'info';
const CRON_DRAIN_TIMEOUT_MS = 60_000;
const CRON_DRAIN_POLL_MS = 500;
const FATAL_EXIT_DELAY_MS = 1000;
+const MS_PER_SECOND = 1000;
+// Set here because Elysia's Bun adapter otherwise injects `idleTimeout: 30`,
+// which severed slow dashboard calls without a response (M36-001). It must
+// outlast the tRPC deadline so the deadline's error is delivered first; the
+// margin covers the ~1.6 s event-loop stall measured at the end of a large
+// drill-down plus Bun's up-to-1 s timer granularity.
+const HTTP_IDLE_TIMEOUT_MARGIN_SECONDS = 10;
+const HTTP_IDLE_TIMEOUT_SECONDS =
+ RPC_DEADLINE_MS / MS_PER_SECOND + HTTP_IDLE_TIMEOUT_MARGIN_SECONDS;
/**
* `config/env.ts` is the sole `process.env` reader on this path; an invalid
@@ -597,7 +607,11 @@ async function main() {
shutdown('SIGINT');
});
- app.listen(config.listen, () => {
+ const listenOptions = {
+ ...config.listen,
+ idleTimeout: HTTP_IDLE_TIMEOUT_SECONDS,
+ };
+ app.listen(listenOptions, () => {
logger.info(
{
role,
diff --git a/packages/core/src/ch-abortable.test.ts b/packages/core/src/ch-abortable.test.ts
new file mode 100644
index 000000000..5980f1b89
--- /dev/null
+++ b/packages/core/src/ch-abortable.test.ts
@@ -0,0 +1,71 @@
+import { expect, mock, test } from 'bun:test';
+import {
+ bindReadsToSignal,
+ CANCEL_ON_CLIENT_CLOSE_SETTINGS,
+} from './ch-abortable';
+import type { ClickHouseClient } from './context';
+
+function fakeClient() {
+ const query = mock(async (_params: unknown) => 'result');
+ const insert = mock(async (_params: unknown) => 'inserted');
+ const client = { query, insert } as unknown as ClickHouseClient;
+ return { client, query, insert };
+}
+
+test('a read carries the signal and the cancel-on-close settings', async () => {
+ const { client, query } = fakeClient();
+ const controller = new AbortController();
+
+ await bindReadsToSignal(client, controller.signal).query({
+ query: 'SELECT 1',
+ clickhouse_settings: { max_threads: 2 },
+ });
+
+ expect(query).toHaveBeenCalledTimes(1);
+ expect(query.mock.calls[0]?.[0]).toEqual({
+ query: 'SELECT 1',
+ abort_signal: controller.signal,
+ clickhouse_settings: {
+ ...CANCEL_ON_CLIENT_CLOSE_SETTINGS,
+ max_threads: 2,
+ },
+ });
+});
+
+test('a caller setting wins over the defaults', async () => {
+ const { client, query } = fakeClient();
+
+ await bindReadsToSignal(client, new AbortController().signal).query({
+ query: 'SELECT 1',
+ clickhouse_settings: { cancel_http_readonly_queries_on_client_close: 0 },
+ });
+
+ expect(
+ (query.mock.calls[0]?.[0] as { clickhouse_settings: object })
+ .clickhouse_settings
+ ).toMatchObject({ cancel_http_readonly_queries_on_client_close: 0 });
+});
+
+test('a read after the abort never reaches ClickHouse', () => {
+ const { client, query } = fakeClient();
+ const controller = new AbortController();
+ const reason = new Error('gone');
+ controller.abort(reason);
+
+ expect(() =>
+ bindReadsToSignal(client, controller.signal).query({ query: 'SELECT 1' })
+ ).toThrow(reason);
+ expect(query).not.toHaveBeenCalled();
+});
+
+test('writes pass through untouched', async () => {
+ const { client, insert } = fakeClient();
+ const params = { table: 'events', values: [], format: 'JSONEachRow' };
+
+ await bindReadsToSignal(client, new AbortController().signal).insert(
+ params as never
+ );
+
+ expect(insert).toHaveBeenCalledTimes(1);
+ expect(insert.mock.calls[0]?.[0]).toBe(params);
+});
diff --git a/packages/core/src/ch-abortable.ts b/packages/core/src/ch-abortable.ts
new file mode 100644
index 000000000..53b8f6f95
--- /dev/null
+++ b/packages/core/src/ch-abortable.ts
@@ -0,0 +1,49 @@
+// A work scope's ClickHouse reads, bound to that scope's AbortSignal (M36-001),
+// so a read whose answer nobody can receive stops on the server instead of
+// running to completion.
+//
+// Aborting the HTTP call alone does not stop the query: ClickHouse only cancels
+// on client close for a READ-ONLY query with
+// `cancel_http_readonly_queries_on_client_close` set (measured on 26.1).
+// `readonly: 2` still allows per-query settings and temporary tables, which
+// `GLOBAL IN` needs. Only `query` is bound: writes go through `insert` and
+// `command`, and must never be stopped halfway.
+
+import type { ClickHouseSettings } from '@clickhouse/client';
+import type { ClickHouseClient } from './context';
+
+/** Read-only that still permits settings; `1` would reject every SETTINGS clause. */
+const READ_ONLY_ALLOWING_SETTINGS = '2';
+
+export const CANCEL_ON_CLIENT_CLOSE_SETTINGS: ClickHouseSettings = {
+ readonly: READ_ONLY_ALLOWING_SETTINGS,
+ cancel_http_readonly_queries_on_client_close: 1,
+};
+
+type QueryParams = Parameters<ClickHouseClient['query']>[0];
+
+export function bindReadsToSignal(
+ ch: ClickHouseClient,
+ signal: AbortSignal
+): ClickHouseClient {
+ const query = (params: QueryParams) => {
+ // Once abandoned, the remaining reads of the scope never leave the process.
+ signal.throwIfAborted();
+ return ch.query({
+ ...params,
+ abort_signal: signal,
+ clickhouse_settings: {
+ ...CANCEL_ON_CLIENT_CLOSE_SETTINGS,
+ ...params.clickhouse_settings,
+ },
+ });
+ };
+
+ return new Proxy(ch, {
+ get(target, property, receiver) {
+ return property === 'query'
+ ? query
+ : Reflect.get(target, property, receiver);
+ },
+ });
+}
diff --git a/packages/core/src/context.test.ts b/packages/core/src/context.test.ts
index 9e9127b1d..e105c5409 100644
--- a/packages/core/src/context.test.ts
+++ b/packages/core/src/context.test.ts
@@ -166,6 +166,26 @@ test('boot handles are passed through by reference', () => {
expect(ctx.buffers).toBe(deps.buffers);
});
+test('a scope signal binds only the ClickHouse client to it', async () => {
+ const { deps } = stubDeps();
+ const query = mock(async (_params: unknown) => undefined);
+ deps.ch = { query } as unknown as AppDeps['ch'];
+ const controller = new AbortController();
+
+ const ctx = createCtx(deps, {
+ requestId: REQUEST_ID,
+ logger: deps.logger,
+ signal: controller.signal,
+ });
+ await ctx.ch.query({ query: 'SELECT 1' });
+
+ expect(ctx.ch).not.toBe(deps.ch);
+ expect(ctx.db).toBe(deps.db);
+ expect(query.mock.calls[0]?.[0]).toMatchObject({
+ abort_signal: controller.signal,
+ });
+});
+
test('extendCtx adds transport extras without building services', () => {
createServices.mockClear();
diff --git a/packages/core/src/context.ts b/packages/core/src/context.ts
index ac4d77897..de127c0c6 100644
--- a/packages/core/src/context.ts
+++ b/packages/core/src/context.ts
@@ -5,6 +5,7 @@
// (ADR-007 decision 18, ADR-018 R1).
import type { Buffers } from './buffers/create-buffers';
+import { bindReadsToSignal } from './ch-abortable';
import type { CoreConfig } from './config';
import type { QueueProducerHandle, QueueProducers } from './jobs.registry';
import type { Logger } from './logger';
@@ -123,6 +124,12 @@ export interface HttpCtx extends Ctx {
/** Memoized: two guards and a handler asking cost one lookup. */
session: () => Promise<Session | null>;
setCookie(name: string, value: string, options?: CookieOptions): void;
+ /**
+ * Aborting it stops this request's ClickHouse reads. The request-context
+ * derive aborts it when the client disconnects; a transport with a deadline
+ * aborts it when the deadline passes. Set only on read (GET/HEAD) requests.
+ */
+ cancellation?: AbortController;
}
/** What a job run adds. */
@@ -134,6 +141,8 @@ export interface ScopeMeta {
requestId: string;
/** Already child()-bound by the caller — createCtx does not bind it. */
logger: Logger;
+ /** When it aborts, the scope's ClickHouse reads stop (`bindReadsToSignal`). */
+ signal?: AbortSignal;
}
/**
@@ -144,7 +153,7 @@ export function createCtx(deps: AppDeps, scope: ScopeMeta): Ctx {
const ctx: Ctx = {
db: deps.db,
prisma: deps.prisma,
- ch: deps.ch,
+ ch: scope.signal ? bindReadsToSignal(deps.ch, scope.signal) : deps.ch,
redis: deps.redis,
clients: deps.clients,
buffers: deps.buffers,
diff --git a/packages/core/src/http/context.test.ts b/packages/core/src/http/context.test.ts
index e31e9481a..fc73511db 100644
--- a/packages/core/src/http/context.test.ts
+++ b/packages/core/src/http/context.test.ts
@@ -179,6 +179,46 @@ describe('the derived HttpCtx', () => {
});
});
+describe('the request cancellation', () => {
+ const build = () => {
+ const seen: HttpCtx[] = [];
+ const app = new Elysia()
+ .use(requestContext(stubAppDeps().deps))
+ .get('/read', ({ ctx }) => {
+ seen.push(ctx);
+ return 'ok';
+ })
+ .post('/write', ({ ctx }) => {
+ seen.push(ctx);
+ return 'ok';
+ });
+ return { app, seen };
+ };
+
+ test('a read request is cancelled when its client goes away', async () => {
+ const { app, seen } = build();
+ const client = new AbortController();
+
+ await app.handle(
+ new Request('http://localhost/read', { signal: client.signal })
+ );
+ const cancellation = seen[0]?.cancellation;
+ client.abort();
+
+ expect(cancellation).toBeInstanceOf(AbortController);
+ expect(cancellation?.signal.aborted).toBe(true);
+ });
+
+ test('a write request carries no cancellation and keeps its client', async () => {
+ const { app, seen } = build();
+
+ await app.handle(new Request('http://localhost/write', { method: 'POST' }));
+
+ expect(seen).toHaveLength(1);
+ expect(seen[0]?.cancellation).toBeUndefined();
+ });
+});
+
describe('requestLogging', () => {
const build = (verboseClientIds?: string[]) => {
const stub = stubAppDeps();
diff --git a/packages/core/src/http/context.ts b/packages/core/src/http/context.ts
index a07b98704..468840c7f 100644
--- a/packages/core/src/http/context.ts
+++ b/packages/core/src/http/context.ts
@@ -29,6 +29,8 @@ const UNLOGGED_PATH_PREFIXES = [
'/misc',
];
const UNLOGGED_METHODS = ['OPTIONS'];
+/** A write keeps running to completion without its client, as it always did. */
+const CANCELLABLE_METHODS = new Set(['GET', 'HEAD']);
const LOGGED_INGEST_HEADERS = [
'openpanel-client-id',
'openpanel-sdk-name',
@@ -51,19 +53,26 @@ export function requestContext(deps: AppDeps) {
const logger = deps.logger.child({ [REQUEST_ID_LOG_FIELD]: requestId });
const cookies = wrapCookies(cookie);
let session: Promise<Session | null> | undefined;
+ const cancellation = CANCELLABLE_METHODS.has(request.method)
+ ? cancelOnDisconnect(request.signal)
+ : undefined;
// `resolveSession` reads `ctx.services.auth` (ADR-022 R22), so the
// resolver closes over the ctx it is installed on. Safe because it is
// lazy: nothing calls it during the derive.
- const ctx: HttpCtx = extendCtx(createCtx(deps, { requestId, logger }), {
- headers: request.headers,
- ip: clientIp,
- cookies,
- session: () =>
- (session ??= resolveSession(ctx, cookies, request.headers)),
- setCookie: (name: string, value: string, options?: CookieOptions) =>
- writeCookie(cookie, name, value, options),
- });
+ const ctx: HttpCtx = extendCtx(
+ createCtx(deps, { requestId, logger, signal: cancellation?.signal }),
+ {
+ headers: request.headers,
+ ip: clientIp,
+ cookies,
+ session: () =>
+ (session ??= resolveSession(ctx, cookies, request.headers)),
+ setCookie: (name: string, value: string, options?: CookieOptions) =>
+ writeCookie(cookie, name, value, options),
+ cancellation,
+ }
+ );
return { ctx };
}
@@ -144,6 +153,18 @@ export function requestLogging(
);
}
+// Bun aborts `request.signal` when the client goes away — a disconnect, the
+// server's idle timeout, or a closed websocket — but not after a response.
+function cancelOnDisconnect(requestSignal: AbortSignal): AbortController {
+ const cancellation = new AbortController();
+ requestSignal.addEventListener(
+ 'abort',
+ () => cancellation.abort(requestSignal.reason),
+ { once: true, signal: cancellation.signal }
+ );
+ return cancellation;
+}
+
function wrapCookies(cookie: ElysiaCookies): CookieJar {
return {
get(name) {
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 85b9acd81..459cc168e 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -950,6 +950,7 @@ export {
protectedProcedureWithoutAccess,
publicProcedure,
} from './rpc/base';
+export { RPC_DEADLINE_MS } from './rpc/deadline';
export {
TRPCAccessError,
TRPCBadRequestError,
diff --git a/packages/core/src/rpc/base.ts b/packages/core/src/rpc/base.ts
index c7f738b1a..e5b3e77df 100644
--- a/packages/core/src/rpc/base.ts
+++ b/packages/core/src/rpc/base.ts
@@ -17,6 +17,7 @@ import type { Logger } from '../logger';
import { runWithAlsSession } from '../shared/als-session';
import { type CookieOptions, serializeCookie } from '../shared/cookie';
import { EMPTY_SESSION } from '../shared/session';
+import { cancelledCallError, raceCancellation } from './deadline';
import { TRPCForbiddenError } from './errors';
/**
@@ -89,13 +90,31 @@ const t = initTRPC
export const createTRPCRouter = t.router;
export const middleware = t.middleware;
+
+/**
+ * Answers the caller as soon as the request's work is cancelled (deadline or
+ * disconnect), rather than when the work notices.
+ */
+const stopWhenCancelled = t.middleware(async ({ ctx, next }) => {
+ const signal = ctx.cancellation?.signal;
+ if (!signal) {
+ return next();
+ }
+ const result = await raceCancellation(next(), signal);
+ // An aborted read surfaces as a transport error; report why it stopped.
+ if (!result.ok && signal.aborted) {
+ throw cancelledCallError(signal.reason);
+ }
+ return result;
+});
+
/**
* The bare procedure. It authenticates NOTHING. Use one of the three builders
* below unless a procedure's V1 twin was written on `procedure` itself — the
* only ones are the share-aware `chartProcedure`/`overviewProcedure` bases,
* and those are `publicProcedure` plus their own middleware.
*/
-export const procedure = t.procedure;
+export const procedure = t.procedure.use(stopWhenCancelled);
// ---------------------------------------------------------------------------
// The procedure stack (M11-001), ported from packages/trpc/src/trpc.ts:35-155.
diff --git a/packages/core/src/rpc/deadline.test.ts b/packages/core/src/rpc/deadline.test.ts
new file mode 100644
index 000000000..bd6aea242
--- /dev/null
+++ b/packages/core/src/rpc/deadline.test.ts
@@ -0,0 +1,47 @@
+import { expect, test } from 'bun:test';
+import { TRPCError } from '@trpc/server';
+import {
+ cancelledCallError,
+ RpcDeadlineExceededError,
+ raceCancellation,
+} from './deadline';
+
+const DEADLINE_MS = 30_000;
+
+test('a deadline reason becomes TIMEOUT with the explained message', () => {
+ const error = cancelledCallError(new RpcDeadlineExceededError(DEADLINE_MS));
+
+ expect(error).toBeInstanceOf(TRPCError);
+ expect(error.code).toBe('TIMEOUT');
+ expect(error.message).toBe(
+ 'This request took longer than 30 seconds and was stopped. Try a shorter date range or fewer filters.'
+ );
+});
+
+test('any other reason is a closed request', () => {
+ expect(cancelledCallError(new DOMException('x', 'AbortError')).code).toBe(
+ 'CLIENT_CLOSED_REQUEST'
+ );
+});
+
+test('raceCancellation resolves with the work when nothing aborts', async () => {
+ const controller = new AbortController();
+
+ expect(await raceCancellation(Promise.resolve(7), controller.signal)).toBe(7);
+});
+
+test('raceCancellation rejects as soon as the signal aborts', async () => {
+ const controller = new AbortController();
+ const never = new Promise<never>(() => undefined);
+
+ const raced = raceCancellation(never, controller.signal);
+ controller.abort(new RpcDeadlineExceededError(DEADLINE_MS));
+
+ await expect(raced).rejects.toMatchObject({ code: 'TIMEOUT' });
+});
+
+test('raceCancellation rejects immediately on an already-aborted signal', async () => {
+ await expect(
+ raceCancellation(Promise.resolve(), AbortSignal.abort())
+ ).rejects.toMatchObject({ code: 'CLIENT_CLOSED_REQUEST' });
+});
diff --git a/packages/core/src/rpc/deadline.ts b/packages/core/src/rpc/deadline.ts
new file mode 100644
index 000000000..94741c2ab
--- /dev/null
+++ b/packages/core/src/rpc/deadline.ts
@@ -0,0 +1,71 @@
+// How long a tRPC call may run, and what a caller is told when it stops
+// (M36-001).
+//
+// 30 s is the ceiling the dashboard already lived under: Elysia's Bun adapter
+// defaults `idleTimeout` to 30 s, and a non-streamed tRPC response writes no
+// byte before it completes, so nothing that took longer was ever delivered.
+// The deadline keeps that ceiling but turns the silent socket close into an
+// error, and stops the work behind it.
+
+import { TRPCError } from '@trpc/server';
+
+export const RPC_DEADLINE_MS = 30_000;
+
+const MS_PER_SECOND = 1000;
+
+export class RpcDeadlineExceededError extends Error {
+ constructor(deadlineMs: number) {
+ super(
+ `This request took longer than ${deadlineMs / MS_PER_SECOND} seconds and was stopped. Try a shorter date range or fewer filters.`
+ );
+ this.name = 'RpcDeadlineExceededError';
+ }
+}
+
+/** Arms the deadline on a request's cancellation; returns the disarm. */
+export function armDeadline(
+ cancellation: AbortController,
+ deadlineMs: number
+): () => void {
+ const timer = setTimeout(
+ () => cancellation.abort(new RpcDeadlineExceededError(deadlineMs)),
+ deadlineMs
+ );
+ return () => clearTimeout(timer);
+}
+
+/** The error a procedure fails with once its request's work was cancelled. */
+export function cancelledCallError(reason: unknown): TRPCError {
+ if (reason instanceof RpcDeadlineExceededError) {
+ return new TRPCError({
+ code: 'TIMEOUT',
+ message: reason.message,
+ cause: reason,
+ });
+ }
+ return new TRPCError({
+ code: 'CLIENT_CLOSED_REQUEST',
+ message: 'The client closed the request before it completed.',
+ cause: reason,
+ });
+}
+
+/**
+ * Resolves with `work`, or rejects with `cancelledCallError` as soon as
+ * `signal` aborts — the caller is answered even if the work ignores the signal.
+ */
+export function raceCancellation<Result>(
+ work: Promise<Result>,
+ signal: AbortSignal
+): Promise<Result> {
+ if (signal.aborted) {
+ return Promise.reject(cancelledCallError(signal.reason));
+ }
+ return new Promise<Result>((resolve, reject) => {
+ const onAbort = () => reject(cancelledCallError(signal.reason));
+ signal.addEventListener('abort', onAbort, { once: true });
+ work.then(resolve, reject).finally(() => {
+ signal.removeEventListener('abort', onAbort);
+ });
+ });
+}
diff --git a/packages/core/src/rpc/handler.test.ts b/packages/core/src/rpc/handler.test.ts
index 81c812e50..c393f57c4 100644
--- a/packages/core/src/rpc/handler.test.ts
+++ b/packages/core/src/rpc/handler.test.ts
@@ -278,3 +278,94 @@ test('a batched request resolves every procedure in the segment', async () => {
{ result: { data: { json: { pong: true } } } },
]);
});
+
+// ------------------------------------------------- deadline and disconnect
+
+const SHORT_DEADLINE_MS = 20;
+const NEVER_FINISHES_MS = 60_000;
+
+const slowRouter = createTRPCRouter({
+ // Ignores every signal, so only the cancellation race can answer it.
+ stuck: procedure.query(
+ () =>
+ new Promise((resolve) => {
+ setTimeout(resolve, NEVER_FINISHES_MS).unref();
+ })
+ ),
+});
+
+function mountCancellable() {
+ const logger = capturingLogger();
+ const cancellation = new AbortController();
+ const { ctx } = stubHttpCtx({ logger, cancellation });
+ const handler = createTrpcFetchHandler({
+ router: slowRouter,
+ logger,
+ cookieOptions: COOKIE_OPTIONS,
+ ipHeaders: testCoreConfig().ipHeaders,
+ deadlineMs: SHORT_DEADLINE_MS,
+ });
+ return {
+ logger,
+ cancellation,
+ call: () =>
+ handler(new Request('https://api.openpanel.dev/trpc/stuck'), ctx),
+ };
+}
+
+interface ErrorBody {
+ error: {
+ json: { message: string; data: { code: string; httpStatus: number } };
+ };
+}
+
+test('a call past the deadline is answered with an explained TIMEOUT, sent as 504', async () => {
+ const mounted = mountCancellable();
+
+ const response = await mounted.call();
+
+ expect(response.status).toBe(504);
+ const body = (await response.json()) as ErrorBody;
+ expect(body.error.json.data.code).toBe('TIMEOUT');
+ // The dashboard reads this to decide against retrying.
+ expect(body.error.json.data.httpStatus).toBe(408);
+ expect(body.error.json.message).toContain('took longer than 0.02 seconds');
+ expect(mounted.cancellation.signal.aborted).toBe(true);
+ expect(mounted.logger.lines[0]?.level).toBe('error');
+});
+
+test('a client disconnect stops the call and is logged as abandoned', async () => {
+ const mounted = mountCancellable();
+
+ const pending = mounted.call();
+ mounted.cancellation.abort(new DOMException('gone', 'AbortError'));
+ const response = await pending;
+
+ expect(response.status).toBe(499);
+ const body = (await response.json()) as ErrorBody;
+ expect(body.error.json.data.code).toBe('CLIENT_CLOSED_REQUEST');
+ expect(mounted.logger.lines[0]?.level).toBe('warn');
+ expect(mounted.logger.lines[0]?.message).toBe('trpc request abandoned');
+});
+
+test('a call that finishes in time disarms the deadline', async () => {
+ const logger = capturingLogger();
+ const cancellation = new AbortController();
+ const { ctx } = stubHttpCtx({ logger, cancellation });
+ const handler = createTrpcFetchHandler({
+ router,
+ logger,
+ cookieOptions: COOKIE_OPTIONS,
+ ipHeaders: testCoreConfig().ipHeaders,
+ deadlineMs: SHORT_DEADLINE_MS,
+ });
+
+ const response = await handler(
+ new Request('https://api.openpanel.dev/trpc/ping'),
+ ctx
+ );
+ await new Promise((resolve) => setTimeout(resolve, SHORT_DEADLINE_MS * 2));
+
+ expect(response.status).toBe(200);
+ expect(cancellation.signal.aborted).toBe(false);
+});
diff --git a/packages/core/src/rpc/handler.ts b/packages/core/src/rpc/handler.ts
index 52d4a69ee..5fd5ffa31 100644
--- a/packages/core/src/rpc/handler.ts
+++ b/packages/core/src/rpc/handler.ts
@@ -1,11 +1,12 @@
// The tRPC mount: the official fetch adapter, one handler, one `onError`
// (ADR-009).
//
-// The three `onError` branches are V1's (apps/api/src/app.ts:175-206) with one
-// change and no others: the fields come from `ctx` and the `Request`, because
-// under a fetch adapter `req` is a `Request` and has neither `socket` nor a
-// logger. The messages, the levels, the payload keys and the `organization.list`
-// drop are unchanged.
+// Three of the four `onError` branches are V1's (apps/api/src/app.ts:175-206)
+// with one change and no others: the fields come from `ctx` and the `Request`,
+// because under a fetch adapter `req` is a `Request` and has neither `socket`
+// nor a logger. The messages, the levels, the payload keys and the
+// `organization.list` drop are unchanged. The fourth, `CLIENT_CLOSED_REQUEST`,
+// is M36-001's cancellation, which V1 did not have.
import type { AnyRouter, TRPCError } from '@trpc/server';
import { fetchRequestHandler } from '@trpc/server/adapters/fetch';
@@ -18,6 +19,7 @@ import {
type TrpcContext,
type TrpcContextOptions,
} from './base';
+import { armDeadline, RPC_DEADLINE_MS } from './deadline';
/**
* The fetch adapter derives the procedure path with
@@ -39,6 +41,13 @@ export interface TrpcErrorReport {
/** Silenced deliberately: the dashboard probes it while signed out. */
const SILENCED_UNAUTHORIZED_PATH = 'organization.list';
+/**
+ * A deadline is sent as 504, not tRPC's 408: Chromium silently resends a
+ * request that got a 408 on a reused connection, which would run the same
+ * too-slow work twice. The body still says `TIMEOUT` / `httpStatus: 408`.
+ */
+const DEADLINE_HTTP_STATUS = 504;
+
/**
* `bootLogger` is the fallback for when `createContext` itself threw — there is
* no `ctx` then, and a naive `ctx.logger.error(...)` would turn a
@@ -83,6 +92,12 @@ export function createTrpcOnError(
return;
}
+ // Nobody is listening for the answer; the request was abandoned, not failed.
+ if (report.error.code === 'CLIENT_CLOSED_REQUEST') {
+ logger.warn(payload, 'trpc request abandoned');
+ return;
+ }
+
logger.error(payload, 'trpc error');
};
}
@@ -94,6 +109,8 @@ export interface TrpcFetchHandlerOptions extends TrpcContextOptions {
/** `onError` resolves the abuser's IP from trusted headers only. */
ipHeaders: IpHeaderConfig;
endpoint?: string;
+ /** How long one call may run before it is stopped. */
+ deadlineMs?: number;
}
/**
@@ -107,17 +124,30 @@ export function createTrpcFetchHandler(options: TrpcFetchHandlerOptions) {
logger,
ipHeaders,
endpoint = TRPC_ENDPOINT,
+ deadlineMs = RPC_DEADLINE_MS,
...contextOptions
} = options;
const onError = createTrpcOnError(logger, ipHeaders);
- return (request: Request, ctx: HttpCtx): Promise<Response> =>
- fetchRequestHandler({
- endpoint,
- req: request,
- router,
- createContext: ({ resHeaders }) =>
- makeTrpcContext(ctx, resHeaders, contextOptions),
- onError,
- });
+ return async (request: Request, ctx: HttpCtx): Promise<Response> => {
+ const disarmDeadline = ctx.cancellation
+ ? armDeadline(ctx.cancellation, deadlineMs)
+ : undefined;
+ try {
+ return await fetchRequestHandler({
+ endpoint,
+ req: request,
+ router,
+ createContext: ({ resHeaders }) =>
+ makeTrpcContext(ctx, resHeaders, contextOptions),
+ onError,
+ responseMeta: ({ errors }) =>
+ errors.some((error) => error.code === 'TIMEOUT')
+ ? { status: DEADLINE_HTTP_STATUS }
+ : {},
+ });
+ } finally {
+ disarmDeadline?.();
+ }
+ };
}