Documentation menuMenu da documentação

$ cat docs/middleware/idempotency.md

IdempotencyIdempotência

Let clients retry a POST safely: the same key returns the same result instead of charging twice.Deixe o cliente repetir um POST com segurança: a mesma chave devolve o mesmo resultado em vez de cobrar duas vezes.

What it doesO que faz

idempotency(options: IdempotencyOptions): MiddlewareHandler. For POST and PATCH with an Idempotency-Key, the first response (status, headers except set-cookie, body) is kept per key, principal and route, and replayed with idempotent-replayed: true. The same key with another body answers 422 IDEMPOTENCY_KEY_REUSED; a retry while the first request still runs answers 409 IDEMPOTENCY_IN_PROGRESS. Thrown errors and 5xx are not kept, so the client can retry.

idempotency(options: IdempotencyOptions): MiddlewareHandler. Para POST e PATCH com Idempotency-Key, a primeira resposta (status, headers menos set-cookie, corpo) é guardada por chave, principal e rota, e repetida com idempotent-replayed: true. A mesma chave com outro corpo responde 422 IDEMPOTENCY_KEY_REUSED; uma nova tentativa enquanto a primeira roda responde 409 IDEMPOTENCY_IN_PROGRESS. Erros lançados e 5xx não ficam guardados, então o cliente pode tentar de novo.

Install and orderInstalar e ordenar

terminal
pnpm add @tupik/middleware

Register it on the routes with side effects, after the session or JWT middleware that authenticate reads. It runs before access, so principal reads the caller with await ctx.getPrincipal() (the app's authenticate, run once per request and reused by access).

Registre nas rotas com efeitos, depois do middleware de sessão ou JWT que o authenticate lê. Ele roda antes do access, então o principal lê quem chama com await ctx.getPrincipal() (o authenticate do app, rodado uma vez por requisição e reaproveitado pelo access).

ExampleExemplo

idempotency.ts
import { createModule } from '@tupik/core';
import { D1TtlStore, idempotency } from '@tupik/middleware';

const payments = createModule('/payments')
  .use(idempotency({
    store: new D1TtlStore({ database: (env) => (env as Env).DB }), // atomic claim
    principal: async (ctx) => (await ctx.getPrincipal())?.id, // keys never collide across users
    required: true,
  }))
  .post('/', { access: 'authenticated', handler: (ctx) => charge(ctx.body) });
import { createModule } from '@tupik/core';
import { D1TtlStore, idempotency } from '@tupik/middleware';

const payments = createModule('/payments')
  .use(idempotency({
    store: new D1TtlStore({ database: (env) => (env as Env).DB }), // reserva atômica
    principal: async (ctx) => (await ctx.getPrincipal())?.id, // chaves de usuários diferentes nunca colidem
    required: true,
  }))
  .post('/', { access: 'authenticated', handler: (ctx) => charge(ctx.body) });

APIAPI

OptionOpçãoTypeTipoDefault / behaviorPadrão / comportamento
store TtlStore Required. MemoryTtlStore or D1TtlStore are atomic; KVTtlStore can race.Obrigatório. MemoryTtlStore e D1TtlStore são atômicos; KVTtlStore pode ter corrida.
principal (ctx) => Awaitable<string | undefined> Absent. Keys of different callers never collide. May be async.Ausente. Chaves de chamadores diferentes nunca colidem. Pode ser async.
ttlMs number 24 h.24 h.
methods readonly string[] ['POST', 'PATCH'].['POST', 'PATCH'].
required boolean false. true answers 400 IDEMPOTENCY_KEY_REQUIRED without the header.false. true responde 400 IDEMPOTENCY_KEY_REQUIRED sem o header.
maxBytes number 1 MiB for the request fingerprint and the stored response.1 MiB para a impressão do pedido e a resposta guardada.

interface IdempotencyOptions { store; principal?; ttlMs?; methods?; required?; maxBytes? }

interface IdempotencyOptions { store; principal?; ttlMs?; methods?; required?; maxBytes? }

Errors and limitsErros e limites

  • A key outside 1 to 255 visible ASCII characters: 400 IDEMPOTENCY_KEY_INVALID.
  • Streams (text/event-stream) and responses over maxBytes are not stored.
  • If the process dies mid-request, the key stays pending until ttlMs: retries get 409 meanwhile.
  • Chave fora de 1 a 255 caracteres ASCII visíveis: 400 IDEMPOTENCY_KEY_INVALID.
  • Streams (text/event-stream) e respostas acima de maxBytes não são guardadas.
  • Se o processo morrer no meio, a chave fica pendente até ttlMs: novas tentativas recebem 409 nesse tempo.

When not to use itQuando não usar

It does not make the handler itself transactional: a crash after the charge and before the store write can still run twice; keep a unique constraint in your database too.

Não torna o handler transacional: uma queda depois da cobrança e antes da gravação no store ainda pode rodar duas vezes; mantenha também uma restrição única no banco.