Documentation menuMenu da documentação

$ cat docs/middleware/timing.md

Server-TimingServer-Timing

Add one Server-Timing entry with the duration of the matched route, visible in the browser Network panel and in any client that reads the response headers.Adicione uma entrada Server-Timing com a duração da rota casada, visível no painel Network do navegador e em qualquer cliente que leia os headers da resposta.

What it doesO que faz

timing(options?: TimingOptions): MiddlewareHandler. It reads the clock with performance.now() before next(), waits for the downstream pipeline to settle and writes one entry as metric;dur=<milliseconds> with one decimal. The default metric is app; with description set, the entry ends with ;desc="...". The default response header is server-timing. A value already present on that header is preserved: the new entry is appended after a comma and a space, so a handler or an earlier middleware can publish its own timings.

timing(options?: TimingOptions): MiddlewareHandler. Ele lê o relógio com performance.now() antes de next(), espera o pipeline seguinte terminar e escreve uma entrada como metric;dur=<milissegundos> com uma casa decimal. A métrica padrão é app; com description, a entrada termina em ;desc="...". O header de resposta padrão é server-timing. Um valor já presente nesse header é mantido: a nova entrada é anexada depois de uma vírgula e um espaço, então um handler ou um middleware anterior pode publicar as próprias medições.

Install and orderInstalar e ordenar

terminal
pnpm add @tupik/middleware

Register it with app.use(timing()) to cover every route, including module middleware and the handler, or with createModule().use(timing()) to start the clock after app middleware. Put it as early as you want to measure. Body parsing, schema validation and preHandler run before middleware, and onSend runs after it, so none of that work is inside the duration. It decorates matched routes only: engine-generated 404, 413 and validation errors never reach it.

Registre com app.use(timing()) para cobrir todas as rotas, incluindo middleware de módulo e o handler, ou com createModule().use(timing()) para começar o relógio depois dos middlewares do app. Coloque-o tão cedo quanto quiser medir. Leitura de body, validação de schema e preHandler rodam antes do middleware, e onSend roda depois, então nada disso entra na duração. Ele decora só rotas casadas: 404, 413 e erros de validação gerados pelo engine nunca chegam até ele.

ExampleExemplo

timing.ts
import { createApp, createModule } from '@tupik/core';
import { timing } from '@tupik/middleware';

const app = createApp();

// one Server-Timing entry per matched route
app.use(timing({ metric: 'render', description: 'home page' }));

app.register(
  createModule('/api').get('/health', {
    access: 'public',
    handler: () => ({ ok: true }),
  }),
);

const response = await app.fetch(new Request('http://localhost/api/health'));
console.log(response.headers.get('server-timing')); // render;dur=0.2;desc="home page" (varies per request)
import { createApp, createModule } from '@tupik/core';
import { timing } from '@tupik/middleware';

const app = createApp();

// uma entrada Server-Timing por rota casada
app.use(timing({ metric: 'render', description: 'home page' }));

app.register(
  createModule('/api').get('/health', {
    access: 'public',
    handler: () => ({ ok: true }),
  }),
);

const response = await app.fetch(new Request('http://localhost/api/health'));
console.log(response.headers.get('server-timing')); // render;dur=0.2;desc="home page" (varies per request)

APIAPI

OptionOpçãoTypeTipoDefault / behaviorPadrão / comportamento
metricstringapp. Name of the entry; must be a non-empty HTTP token.app. Nome da entrada; precisa ser um token HTTP não vazio.
headerstringserver-timing. Response header written; must be a non-empty HTTP token. An existing value is appended, not replaced.server-timing. Header de resposta escrito; precisa ser um token HTTP não vazio. Um valor existente é anexado, não substituído.
descriptionstringAbsent. Appended as desc="..."; double quotes and backslashes are escaped. Control characters are rejected; a tab is allowed.Ausente. Anexado como desc="..."; aspas duplas e barras invertidas são escapadas. Caracteres de controle são rejeitados; um tab é permitido.

interface TimingOptions { metric?, header?, description? }

interface TimingOptions { metric?, header?, description? }

Errors and limitsErros e limites

  • An empty, non-string or non-token metric or header throws TypeError when the factory is called. A non-string description, or one containing a control character (C0 except tab, or DEL), throws too.
  • A handler that throws is answered by the engine (500): the error bypasses this middleware, so that response carries no server-timing header. Engine-generated 404, 413 and validation responses behave the same way.
  • A raw Response keeps its status, body and other headers; applyHeaders copies it only when its headers are immutable. A status-0 network error response is returned untouched.
  • The entry is appended to an existing value on the same header, separated by , ; the middleware never replaces what the app already published.
  • description is sent to every client that reads the response: never put secrets or personal data in it. Quotes and backslashes are escaped; control characters are rejected.
  • The duration is rounded to one decimal of a millisecond, so very fast handlers can read 0.0. It is elapsed wall time around next(), not CPU time, and it includes downstream middleware and the handler.
  • Um metric ou header vazio, que não seja string ou que não seja token lança TypeError quando a factory é chamada. Uma description que não seja string, ou que contenha um caractere de controle (C0 exceto tab, ou DEL), também lança.
  • Um handler que lança é respondido pelo engine (500): o erro passa por fora deste middleware, então essa resposta não leva o header server-timing. Respostas 404, 413 e de validação geradas pelo engine se comportam do mesmo jeito.
  • Uma Response crua mantém status, body e os outros headers; applyHeaders só a copia quando os headers são imutáveis. Uma resposta de erro de rede com status 0 é devolvida intacta.
  • A entrada é anexada a um valor existente no mesmo header, separada por , ; o middleware nunca substitui o que a app já publicou.
  • A description vai para todo cliente que lê a resposta: nunca coloque segredos ou dados pessoais nela. Aspas e barras invertidas são escapadas; caracteres de controle são rejeitados.
  • A duração é arredondada para uma casa decimal de milissegundo, então handlers muito rápidos podem ler 0.0. É tempo de parede ao redor de next(), não tempo de CPU, e inclui middleware seguinte e o handler.

When not to use itQuando não usar

Use it for a coarse, client-visible breakdown of a route, not as your observability system. For spans, trace context, per-middleware timing or metrics aggregated on the server, use @tupik/infra's runtime tracer (OpenTelemetry) and your own logger. Proxies and CDNs may strip or rewrite response headers, so do not base SLOs or billing on Server-Timing. If you need several phases, register more than one timing() call with distinct metric names, or publish your own entries and let this middleware append its own.

Use para uma visão grosseira e visível ao cliente de uma rota, não como seu sistema de observabilidade. Para spans, contexto de trace, tempo por middleware ou métricas agregadas no servidor, use o tracer de runtime do @tupik/infra (OpenTelemetry) e o seu logger. Proxies e CDNs podem remover ou reescrever headers de resposta, então não baseie SLOs nem cobrança em Server-Timing. Se precisar de várias fases, registre mais de uma chamada timing() com métricas distintas, ou publique as próprias entradas e deixe este middleware anexar a dele.