$ cat docs/middleware/tracing.md
TracingTracing
Trace every request without sending ids, tokens or personal data to the trace backend.Rastreie cada requisição sem mandar ids, tokens ou dados pessoais para o backend de traces.
What it doesO que faz
tracing(options: TracingMiddlewareOptions): MiddlewareHandler. It opens one SERVER span named after the route template (GET /users/:id; unmatched requests use the method only) with http.request.method (unknown methods as _OTHER), http.route, url.scheme and http.response.status_code, plus tenant.id when the tenant middleware verified one. With principal: { salt } it adds user.hash, the SHA-256 of salt:id, never the id. A 5xx or a thrown error sets the ERROR status with error.type only; a thrown 4xx (HttpError, ctx.fail) is recorded as its status. The raw URL, the query string, the body, the request headers and error messages never go into the span. Any object with startSpan works: there is no @opentelemetry/* dependency.
tracing(options: TracingMiddlewareOptions): MiddlewareHandler. Ele abre um span SERVER com o nome do modelo da rota (GET /users/:id; requisição sem rota usa só o método) com http.request.method (método desconhecido vira _OTHER), http.route, url.scheme e http.response.status_code, mais tenant.id quando o middleware tenant conferiu um. Com principal: { salt } ele acrescenta user.hash, o SHA-256 de salt:id, nunca o id. Um 5xx ou um erro lançado marca o status ERROR só com error.type; um 4xx lançado (HttpError, ctx.fail) entra como o seu status. A URL crua, a query string, o corpo, os headers da requisição e as mensagens de erro nunca entram no span. Qualquer objeto com startSpan serve: não há dependência de @opentelemetry/*.
Install and orderInstalar e ordenar
pnpm add @tupik/middleware Register it first with app.use, so it wraps the other middleware. setTraceAttributes(ctx, attrs) adds your attributes after the shared redaction of @tupik/infra (authorization, cookie, password, token, secret, cpf... plus redact), masks IPs and turns every field classified pii, health or secret in the route schemas into '[redacted]'. getTraceparent(ctx) gives the W3C header for outgoing calls.
Registre primeiro com app.use, para envolver os outros middlewares. setTraceAttributes(ctx, attrs) acrescenta os seus atributos depois da redação compartilhada do @tupik/infra (authorization, cookie, password, token, secret, cpf... mais redact), mascara IPs e troca por '[redacted]' todo campo classificado como pii, health ou secret nos schemas da rota. getTraceparent(ctx) devolve o header W3C para chamadas de saída.
ExampleExemplo
import { trace } from '@opentelemetry/api';
import { createApp, createModule } from '@tupik/core';
import { getTraceparent, setTraceAttributes, tracing } from '@tupik/middleware';
const app = createApp({ authenticate: (ctx) => findUser(ctx) });
// first, so it wraps the other middleware
app.use(tracing({ tracer: trace.getTracer('api'), app, principal: { salt: env.TRACE_SALT } }));
app.register(
createModule('/orders').post('/', {
access: 'authenticated',
handler: async (ctx) => {
const account = await loadAccount(ctx);
setTraceAttributes(ctx, { 'app.plan': account.plan, 'user.email': account.email }); // email → '[redacted]'
await fetch('https://billing.example/charge', { method: 'POST', headers: { traceparent: getTraceparent(ctx) ?? '' } });
return { ok: true };
},
}),
);import { trace } from '@opentelemetry/api';
import { createApp, createModule } from '@tupik/core';
import { getTraceparent, setTraceAttributes, tracing } from '@tupik/middleware';
const app = createApp({ authenticate: (ctx) => findUser(ctx) });
// primeiro, para envolver os outros middlewares
app.use(tracing({ tracer: trace.getTracer('api'), app, principal: { salt: env.TRACE_SALT } }));
app.register(
createModule('/orders').post('/', {
access: 'authenticated',
handler: async (ctx) => {
const account = await loadAccount(ctx);
setTraceAttributes(ctx, { 'app.plan': account.plan, 'user.email': account.email }); // email → '[redacted]'
await fetch('https://billing.example/charge', { method: 'POST', headers: { traceparent: getTraceparent(ctx) ?? '' } });
return { ok: true };
},
}),
); APIAPI
| OptionOpção | TypeTipo | Default / behaviorPadrão / comportamento |
|---|---|---|
app | { routes } | Required. Read on the first request: route templates and data classes.Obrigatório. Lido na primeira requisição: modelos de rota e classes de dado. |
tracer | TracerLike | trace.getTracer(...) or any object with startSpan. Without it the middleware only calls next.trace.getTracer(...) ou qualquer objeto com startSpan. Sem ele o middleware só chama o next. |
principal | { salt, id? } | Off. Adds user.hash = SHA-256 of salt:id; id defaults to principal.id.Desligado. Acrescenta user.hash = SHA-256 de salt:id; o id padrão é principal.id. |
redact | readonly string[] | Extra keys redacted from added attributes, on top of DEFAULT_REDACT_KEYS.Chaves extras redigidas dos atributos acrescentados, além de DEFAULT_REDACT_KEYS. |
parentContext | (parent) => Context | Without it the incoming traceparent becomes a span link; with it, the real parent.Sem ele o traceparent recebido vira um link do span; com ele, o pai de verdade. |
interface TracingMiddlewareOptions { app; tracer?; principal?; redact?; parentContext? }
interface TracingMiddlewareOptions { app; tracer?; principal?; redact?; parentContext? }
Errors and limitsErros e limites
- A request that fails schema validation (400) is answered before app middleware runs, so it produces no span.
- The incoming
traceparentis validated; an invalid one is ignored. To make it the real parent, passparentContext: (parent) => trace.setSpanContext(context.active(), parent). getTraceparentreturnsundefinedwhen the tracer gives nospanContext(). A secret read on its own and set as an attribute under a neutral key is not detected: name keys honestly.
- Requisição que falha na validação do schema (400) é respondida antes dos middlewares do app, então não gera span.
- O
traceparentrecebido é validado; um inválido é ignorado. Para torná-lo o pai de verdade, passeparentContext: (parent) => trace.setSpanContext(context.active(), parent). getTraceparentdevolveundefinedquando o tracer não dáspanContext(). Um segredo posto como atributo sob uma chave neutra não é detectado: dê nomes honestos às chaves.
When not to use itQuando não usar
Skip it when no one reads the traces. For a span around one piece of code (a query, a call), use createRuntimeTracer from @tupik/infra.
Dispense quando ninguém lê os traces. Para um span em volta de um trecho (uma consulta, uma chamada), use o createRuntimeTracer do @tupik/infra.