Pular para o conteúdo

Claim Check

Guarda o payload grande num storage externo e manda pelo broker só a referência para buscá-lo.

passos
4
arquivos
6
testes
0
tecnologias
8

Cenário

Remessa com 20 mil PIX vai para o SeaweedFS; só o comprovante passa pelo RabbitMQ.

Planta

Sequência
4/4
1. upload do arquivo de remessa12. claim check: key, sizeBytes, checksum23. claim check34. download4confere tamanho e checksum, liquidaProducerSeaweedFSRabbitMQWorker de liquidação
4

4 passos — reproduza para seguir o fluxo

Como funciona

4passos

Guarda o payload grande num storage externo e manda pelo broker só a referência para buscá-lo

Esconde cada passo: lembre antes de tocar para revelar.

Vocabulário compartilhado

  1. 1

    O producer grava no SeaweedFS (S3) e só depois publica o claim check

  2. 2

    O claim check leva bucket, key, sizeBytes, checksumSha256, recordCount

  3. 3

    O worker baixa o arquivo pela referência

  4. 4

    Confere tamanho e checksum antes de liquidar; TTL de 7 dias no prefixo batches/ expira o arquivo

Trade-offs

O que se ganha, o que se paga

2 vantagenscada ganho tem um preço2 custos

Vantagens

  • Broker leve, qualquer tamanho de arquivo

  • Download só por quem processa

Custos

  • Storage a mais na rota

  • Ciclos de vida separados

Código

pattern/messaging/claim-check

6 arquivos

./

  • .env.exampleinfra
  • docker-compose.ymlinfra
  • package.jsoninfra
  • README.md
  • tsconfig.jsoninfra

src/

  • demo.tsdemo

Executar com Docker

  1. docker compose up -d --wait# sobe RabbitMQ
  2. bun install# dependências
  3. bun run demo# roda o cenário
  4. docker compose down -v

Saída: arquivo de 356397 bytes no storage e claim check de 200 bytes no broker; REM-001 com 20000 pagamentos e R$ 51994900.00.

Requisitos
BunDocker
Sobe junto
RabbitMQ

Código

src/demo.ts

// Demo: the remittance file goes to S3-compatible storage; only its claim check crosses RabbitMQ, and the worker fetches and verifies it.
import { createHash } from "node:crypto";
import { S3Client } from "bun";
import amqplib from "amqplib";

const SETTLEMENT_QUEUE = "settlement-claim-check";
const bucket = Bun.env.CLAIM_CHECK_S3_BUCKET ?? "settlement-files";

type ClaimCheck = { batchId: string; bucket: string; key: string; sizeBytes: number; checksumSha256: string; recordCount: number };

const storage = new S3Client({
  endpoint: Bun.env.CLAIM_CHECK_S3_ENDPOINT ?? "http://localhost:9000",
  bucket,
  accessKeyId: Bun.env.CLAIM_CHECK_S3_ACCESS_KEY_ID ?? "settlement",
  secretAccessKey: Bun.env.CLAIM_CHECK_S3_SECRET_ACCESS_KEY ?? "settlement-secret",
});
const connection = await amqplib.connect(Bun.env.CLAIM_CHECK_RABBITMQ_URL ?? "amqp://guest:guest@localhost:5672");
const channel = await connection.createChannel();
await channel.assertQueue(SETTLEMENT_QUEUE, { durable: true });
await channel.purgeQueue(SETTLEMENT_QUEUE);
const sha256 = (payload: Uint8Array) => createHash("sha256").update(payload).digest("hex");

// Producer: a remittance file of 20,000 PIX payments, one per line — account|amount in cents.
const lines = Array.from({ length: 20_000 }, (_, index) => `ACC-${100_001 + index}|${10_000 + ((index * 3_701) % 500_000)}`);
const payload = new TextEncoder().encode(lines.join("\n"));
const key = "batches/REM-001.txt";
// Upload before publish: a claim check never points at a file that is not there yet.
await storage.write(key, payload);
const claim: ClaimCheck = { batchId: "REM-001", bucket, key, sizeBytes: payload.byteLength, checksumSha256: sha256(payload), recordCount: lines.length };
channel.sendToQueue(SETTLEMENT_QUEUE, Buffer.from(JSON.stringify(claim)), { persistent: true });
console.log(`  [PRODUCER] file of ${payload.byteLength} bytes in storage, claim check of ${Buffer.byteLength(JSON.stringify(claim))} bytes on the broker`);

// Worker: receives the small reference, fetches the file and verifies it against the claim check before trusting it.
const done = Promise.withResolvers<void>();
await channel.consume(SETTLEMENT_QUEUE, async (message) => {
  if (!message) return;
  const received = JSON.parse(message.content.toString()) as ClaimCheck;
  const file = await storage.file(received.key).bytes();
  if (file.byteLength !== received.sizeBytes || sha256(file) !== received.checksumSha256) throw new Error(`${received.key} does not match its claim check`);
  const totalCents = new TextDecoder().decode(file).split("\n").reduce((sum, line) => sum + Number(line.split("|")[1]), 0);
  console.log(`  [SETTLEMENT] ${received.batchId}: ${received.recordCount} payments, R$ ${(totalCents / 100).toFixed(2)}`);
  channel.ack(message);
  done.resolve();
});

await done.promise;
await connection.close();

Nível

intermediário

7/13

Linhas de TypeScript
41
Tipo
B — dois ou mais serviços (docker compose)

Domínio financeiro

  • PIX
  • Liquidação
  • Remessa

Padrões do catálogo que implementa

  • Claim-Check

Infraestrutura

  • MinIOobject storage S3

    bitnamilegacy/minio:2025.7.23:9000

  • MinIOobject storage S3

    bitnamilegacy/minio:2025.7.23

  • RabbitMQmessage broker

    rabbitmq:3-alpine:5672

Variáveis de ambiente

CLAIM_CHECK_RABBITMQ_URL
amqp://guest:guest@localhost:5672
RabbitMQ carrying only the claim checks.
CLAIM_CHECK_S3_ENDPOINT
http://localhost:9000
S3-compatible storage holding the remittance files; the bucket and its 7-day expiration come from the infrastructure.
CLAIM_CHECK_S3_BUCKET
settlement-files
CLAIM_CHECK_S3_ACCESS_KEY_ID
settlement
Secret: storage credentials.
CLAIM_CHECK_S3_SECRET_ACCESS_KEY
settlement-secret

Por que se relacionam

Teste rápido

Qual destes combina com Claim Check?

Próximo projeto, Mensageria & EventosContent Enricher
Esc

↑ ↓ navegarEnter abrir239 resultados