Production building blocks with zero dependencies and no node:* imports: pluggable storage, a structured JSON logger and OpenTelemetry-compatible tracing.Blocos de produção sem dependências e sem imports node:*: storage plugável, logger JSON estruturado e tracing compatível com OpenTelemetry.
InstallInstalar
@tupik/infra runs on Node.js, Bun, Deno and Cloudflare Workers. The three modules are independent:
use one without the others.
@tupik/infra roda em Node.js, Bun, Deno e Cloudflare Workers. Os três módulos são independentes:
use um sem os outros.
terminal
pnpm add @tupik/infra
Storage
createMemoryStorage(options?: MemoryStorageOptions): Storage is an in-memory key/value store with
per-entry TTL. Expired entries read as undefined and are dropped on access.
namespaced(storage, prefix) stores keys as prefix + ':' + key, and its
clear() only clears that namespace.
createMemoryStorage(options?: MemoryStorageOptions): Storage é um armazenamento chave/valor em memória
com TTL por entrada. Entradas expiradas são lidas como undefined e removidas no acesso.
namespaced(storage, prefix) grava as chaves como prefix + ':' + key, e o
clear() dele limpa só aquele namespace.
storage.ts
import { createMemoryStorage, namespaced } from'@tupik/infra';
const storage = createMemoryStorage();
const sessions = namespaced(storage, 'sessions'); // keys become "sessions:<key>"await sessions.set('abc', { userId: 1 }, { ttlMs: 60_000 });
await sessions.get<{ userId: number }>('abc'); // { userId: 1 } for 60 s, then undefinedawait sessions.delete('abc'); // trueawait sessions.clear(); // only "sessions:*"
The clock is injectable, so TTL is testable without timers:
O relógio é injetável, então o TTL é testável sem timers:
ttl.test.ts
let now = 0;
const cache = createMemoryStorage({ now: () => now }); // injected clock, no timersawait cache.set('token', 't1', { ttlMs: 100 });
now = 99; await cache.get('token'); // 't1'
now = 100; await cache.get('token'); // undefined, and the entry is dropped
let now = 0;
const cache = createMemoryStorage({ now: () => now }); // relógio injetado, sem timersawait cache.set('token', 't1', { ttlMs: 100 });
now = 99; await cache.get('token'); // 't1'
now = 100; await cache.get('token'); // undefined, e a entrada é removida
To use another backend, implement Storage. The optional keys(prefix?) method is what lets
namespaced(...).clear() find the namespace's keys; without it, that clear() rejects with
a TypeError instead of clearing nothing or everything.
Para usar outro backend, implemente Storage. O método opcional keys(prefix?) é o que permite
a namespaced(...).clear() achar as chaves do namespace; sem ele, esse clear() rejeita com
TypeError em vez de não limpar nada ou limpar tudo.
createLogger(options?: LoggerOptions): Logger writes one JSON object per call to the sink (default
console.log). Records below level (default info) are skipped. Fields are
merged in order: base, then child bindings, then per-call fields, and the per-call fields
win. level, time and msg cannot be overridden.
createLogger(options?: LoggerOptions): Logger escreve um objeto JSON por chamada no sink (padrão
console.log). Registros abaixo de level (padrão info) são ignorados. Os
campos são mesclados nesta ordem: base, depois os bindings de child, depois os campos da
chamada, e os campos da chamada vencem. level, time e msg não podem ser
sobrescritos.
DEFAULT_REDACT_KEYS (authorization, cookie, set-cookie,
x-csrf-token, x-api-key, x-auth-token, proxy-authorization,
password, senha, token, secret, cpf) plus your
redact keys (case-insensitive) become '[redacted]' at any depth up to 8 levels; deeper
values become '[truncated]' and cycles '[circular]'. IP fields (ip,
cf-connecting-ip, x-forwarded-for, x-real-ip) are masked unless
maskIp: false. Error values keep name and message
(errorDetail: 'name' drops the message; 'stack' adds the stack, for non-production only).
The logger never throws: a failing sink or clock is ignored, and fields that cannot be serialized become
logError: 'unserializable fields'.
DEFAULT_REDACT_KEYS (authorization, cookie, set-cookie,
x-csrf-token, x-api-key, x-auth-token, proxy-authorization,
password, senha, token, secret, cpf) mais as chaves
de redact (sem diferenciar maiúsculas) viram '[redacted]' em qualquer profundidade até 8
níveis; o que passar disso vira '[truncated]' e ciclos viram '[circular]'. Campos de IP
(ip, cf-connecting-ip, x-forwarded-for, x-real-ip) são
mascarados, salvo maskIp: false. Valores Error mantêm name e
message (errorDetail: 'name' tira a mensagem; 'stack' inclui a stack, só fora
de produção). O
logger nunca lança: falha do sink ou do relógio é ignorada, e campos que não serializam viram
logError: 'unserializable fields'.
createRuntimeTracer(options?: TracingOptions): RuntimeTracer accepts any tracer shaped like
OpenTelemetry's (TracerLike), so @tupik/infra does not depend on the SDK. Without a
tracer, enabled is false and span() still runs the function with a no-op span.
With one, the span ends on success and on error; on error it records the exception, sets the error status
(code 2) and rethrows the same error. With errorDetail: 'name', only error.type reaches the
trace, never the message. For one span per request that respects the route's data classes, use the
tracing middleware.
createRuntimeTracer(options?: TracingOptions): RuntimeTracer aceita qualquer tracer no formato do
OpenTelemetry (TracerLike), então o @tupik/infra não depende do SDK. Sem tracer,
enabled é false e span() ainda roda a função com um span no-op. Com tracer, o
span termina no sucesso e no erro; no erro ele registra a exceção, marca o status de erro (código 2) e relança o
mesmo erro. Com errorDetail: 'name', só o error.type vai para o trace, nunca a mensagem.
Para um span por requisição com as classes de dado da rota, use o middleware
tracing.
tracing.ts
import { trace } from'@opentelemetry/api';
import { createRuntimeTracer } from'@tupik/infra';
const tracing = createRuntimeTracer({
tracer: trace.getTracer('api'), // optional: without it every span is a no-op
attributes: { 'service.name': 'api' },
});
const user = await tracing.span('db.find-user', async (span) => {
span.setAttribute('db.table', 'users');
return db.users.find(1); // throws? exception recorded, span ended, same error rethrown
});
import { trace } from'@opentelemetry/api';
import { createRuntimeTracer } from'@tupik/infra';
const tracing = createRuntimeTracer({
tracer: trace.getTracer('api'), // opcional: sem ele todo span é no-op
attributes: { 'service.name': 'api' },
});
const user = await tracing.span('db.find-user', async (span) => {
span.setAttribute('db.table', 'users');
return db.users.find(1); // lançou? exceção registrada, span encerrado, mesmo erro relançado
});