Documentation menuMenu da documentação

$ cat docs/middleware/timeout.md

TimeoutTimeout

Give each route a time budget and stop the work it started when the budget runs out.Dê a cada rota um orçamento de tempo e pare o trabalho iniciado quando ele acabar.

What it doesO que faz

timeout(options: TimeoutOptions): MiddlewareHandler. It races the downstream pipeline against setTimeout. On expiry it answers 503 TIMEOUT (or 408 REQUEST_TIMEOUT) as RFC 9457 and aborts the signal from getSignal(ctx) with a TimeoutError. Only setTimeout and AbortController are used, so it behaves the same on Node, Bun and Workers.

timeout(options: TimeoutOptions): MiddlewareHandler. Ele disputa o pipeline seguinte contra um setTimeout. Ao expirar, responde 503 TIMEOUT (ou 408 REQUEST_TIMEOUT) em RFC 9457 e aborta o sinal de getSignal(ctx) com um TimeoutError. Só usa setTimeout e AbortController, então se comporta igual em Node, Bun e Workers.

Install and orderInstalar e ordenar

terminal
pnpm add @tupik/middleware

Register it before the middleware and handler you want to bound; pass getSignal(ctx) to fetch, queries and streams.

Registre antes dos middlewares e do handler que quer limitar; passe getSignal(ctx) para fetch, consultas e streams.

ExampleExemplo

timeout.ts
import { createModule } from '@tupik/core';
import { getSignal, timeout } from '@tupik/middleware';

const reports = createModule('/reports')
  .use(timeout({ ms: 5_000 }))
  .get('/big', {
    access: 'authenticated',
    // the upstream call stops when the budget ends
    handler: async (ctx) => (await fetch('https://upstream.example/report', { signal: getSignal(ctx) })).json(),
  });
import { createModule } from '@tupik/core';
import { getSignal, timeout } from '@tupik/middleware';

const reports = createModule('/reports')
  .use(timeout({ ms: 5_000 }))
  .get('/big', {
    access: 'authenticated',
    // a chamada externa para quando o orçamento acaba
    handler: async (ctx) => (await fetch('https://upstream.example/report', { signal: getSignal(ctx) })).json(),
  });

APIAPI

OptionOpçãoTypeTipoDefault / behaviorPadrão / comportamento
ms number Required. Budget in milliseconds (> 0).Obrigatório. Orçamento em milissegundos (> 0).
status 408 | 503 503 TIMEOUT. 408 REQUEST_TIMEOUT when the client is to blame.503 TIMEOUT. 408 REQUEST_TIMEOUT quando a culpa é do cliente.

interface TimeoutOptions { ms: number; status?: 408 | 503 }

interface TimeoutOptions { ms: number; status?: 408 | 503 }

Errors and limitsErros e limites

  • A non-positive ms or another status throws at creation.
  • A late result or error from the handler is ignored after the timeout answer.
  • Work that ignores the signal keeps running until it ends; the timer cannot kill it.
  • ms não positivo ou outro status lança na criação.
  • Resultado ou erro tardio do handler é ignorado depois da resposta de timeout.
  • Trabalho que ignora o sinal continua até terminar; o timer não consegue matá-lo.

When not to use itQuando não usar

Not for streaming responses (SSE, downloads): the clock stops when the Response object is returned, not when the body ends.

Não serve para respostas em stream (SSE, downloads): o relógio para quando o objeto Response é devolvido, não quando o corpo termina.