Documentation menuMenu da documentação

$ cat docs/infra.md

InfraInfra

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 undefined
await sessions.delete('abc');                  // true
await sessions.clear();                        // only "sessions:*"
import { createMemoryStorage, namespaced } from '@tupik/infra';

const storage = createMemoryStorage();
const sessions = namespaced(storage, 'sessions'); // as chaves viram "sessions:<key>"

await sessions.set('abc', { userId: 1 }, { ttlMs: 60_000 });
await sessions.get<{ userId: number }>('abc'); // { userId: 1 } por 60 s, depois undefined
await sessions.delete('abc');                  // true
await sessions.clear();                        // só "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 timers

await 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 timers

await cache.set('token', 't1', { ttlMs: 100 });
now = 99;  await cache.get('token'); // 't1'
now = 100; await cache.get('token'); // undefined, e a entrada é removida
TypeTipoShapeFormato
Storageget<T>(key) · set<T>(key, value, options?) · delete(key): Promise<boolean> · clear() · keys?(prefix?)
StorageEntryOptions{ ttlMs?: number }
MemoryStorageOptions{ now?: () => number }

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.

kv-storage.ts
import type { Storage } from '@tupik/infra';

// Any backend fits the same four methods (KV, Redis, D1...).
export function kvStorage(kv: KVNamespace): Storage {
  return {
    get: async (key) => (await kv.get(key, 'json')) ?? undefined,
    set: async (key, value, options) =>
      kv.put(key, JSON.stringify(value), options?.ttlMs ? { expirationTtl: Math.ceil(options.ttlMs / 1000) } : {}),
    delete: async (key) => (await kv.delete(key), true),
    clear: async () => { throw new Error('not supported'); },
  };
}
import type { Storage } from '@tupik/infra';

// Qualquer backend cabe nos mesmos quatro métodos (KV, Redis, D1...).
export function kvStorage(kv: KVNamespace): Storage {
  return {
    get: async (key) => (await kv.get(key, 'json')) ?? undefined,
    set: async (key, value, options) =>
      kv.put(key, JSON.stringify(value), options?.ttlMs ? { expirationTtl: Math.ceil(options.ttlMs / 1000) } : {}),
    delete: async (key) => (await kv.delete(key), true),
    clear: async () => { throw new Error('not supported'); },
  };
}

Logger

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.

logger.ts
import { createLogger } from '@tupik/infra';

const log = createLogger({
  level: 'info',
  base: { service: 'api' },
  redact: ['password', 'authorization'],
});

const requestLog = log.child({ requestId: 'r-42' });
requestLog.debug('cache miss');                           // below the threshold: not written
requestLog.info('login', { user: 'ana', password: 'x' });
// {"level":"info","time":1764547200000,"msg":"login","service":"api","requestId":"r-42","user":"ana","password":"[redacted]"}
import { createLogger } from '@tupik/infra';

const log = createLogger({
  level: 'info',
  base: { service: 'api' },
  redact: ['password', 'authorization'],
});

const requestLog = log.child({ requestId: 'r-42' });
requestLog.debug('cache miss');                           // abaixo do limiar: não escreve
requestLog.info('login', { user: 'ana', password: 'x' });
// {"level":"info","time":1764547200000,"msg":"login","service":"api","requestId":"r-42","user":"ana","password":"[redacted]"}

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'.

TypeTipoShapeFormato
LogLevel'debug' | 'info' | 'warn' | 'error'
LoggerOptions{ level?; base?; sink?: LogSink; redact?: readonly string[]; maskIp?: boolean; errorDetail?: 'name' | 'message' | 'stack'; now?: () => number }
Loggerdebug · info · warn · error (msg, fields?) · child(bindings)
LogRecord{ level: LogLevel; time: number; msg: string; [key: string]: unknown }
LogSink(line: string) => void

Tracing

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
});
TypeTipoShapeFormato
SpanLikesetAttribute(key, value) · setStatus?(status) · recordException?(error) · end()
TracerLikestartSpan(name, options?: { attributes?; kind?; links? }, context?): SpanLike
TracingOptions{ tracer?: TracerLike; attributes?: Record<string, unknown>; errorDetail?: 'name' | 'message' }
RuntimeTracerspan<T>(name, fn: (span) => T | Promise<T>, options?: { attributes?; kind?; links?; context? }): Promise<T> · readonly enabled
parseTraceparent / formatTraceparent(header) => SpanContextLike | undefined · (spanContext) => string | undefined
createAttributeRedactor({ redact?, maskIp?, sensitive? }) => (attributes) => flat, redacted attributes

All three in a routeOs três numa rota

users.ts
import { createApp, createModule } from '@tupik/core';
import { z } from 'zod';
import { createLogger, createMemoryStorage, createRuntimeTracer, namespaced } from '@tupik/infra';

const log = createLogger({ base: { service: 'users' } });
const tracing = createRuntimeTracer();
const cache = namespaced(createMemoryStorage(), 'users');

const users = createModule('/users').get('/:id', {
  access: 'public',
  schema: { params: z.object({ id: z.string() }) }, // typed id
  handler: (ctx) =>
    tracing.span('users.get', async () => {
      const hit = await cache.get<{ id: string }>(ctx.params.id);
      if (hit !== undefined) return hit;
      const user = { id: ctx.params.id };
      await cache.set(ctx.params.id, user, { ttlMs: 30_000 });
      log.info('user loaded', { id: ctx.params.id });
      return user;
    }),
});

export const app = createApp().register(users);
import { createApp, createModule } from '@tupik/core';
import { z } from 'zod';
import { createLogger, createMemoryStorage, createRuntimeTracer, namespaced } from '@tupik/infra';

const log = createLogger({ base: { service: 'users' } });
const tracing = createRuntimeTracer();
const cache = namespaced(createMemoryStorage(), 'users');

const users = createModule('/users').get('/:id', {
  access: 'public',
  schema: { params: z.object({ id: z.string() }) }, // id tipado
  handler: (ctx) =>
    tracing.span('users.get', async () => {
      const hit = await cache.get<{ id: string }>(ctx.params.id);
      if (hit !== undefined) return hit;
      const user = { id: ctx.params.id };
      await cache.set(ctx.params.id, user, { ttlMs: 30_000 });
      log.info('user loaded', { id: ctx.params.id });
      return user;
    }),
});

export const app = createApp().register(users);

LimitationsLimitações