pattern/messaging/claim-check
- Bun
- Bun S3Client
- RabbitMQ
- SeaweedFS
- TypeScript
- amqplib
- node:crypto
- Docker
Guarda o payload grande num storage externo e manda pelo broker só a referência para buscá-lo.
pattern/messaging/claim-check
Cenário
Remessa com 20 mil PIX vai para o SeaweedFS; só o comprovante passa pelo RabbitMQ.
Planta
Sequência4 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
O producer grava no SeaweedFS (S3) e só depois publica o claim check
O claim check leva bucket, key, sizeBytes, checksumSha256, recordCount
O worker baixa o arquivo pela referência
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
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./
src/
Executar com Docker
docker compose up -d --wait# sobe RabbitMQbun install# dependênciasbun run demo# roda o cenáriodocker compose down -vSaída: arquivo de 356397 bytes no storage e claim check de 200 bytes no broker; REM-001 com 20000 pagamentos e R$ 51994900.00.
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
Domínio financeiro
Padrões do catálogo que implementa
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
Por que se relacionam
Teste rápido
Qual destes combina com Claim Check?
Tira o pesado da mensagem. Abrir Content Filter
Seu progresso
0/157 estudados
Fica salvo só neste navegador.