pattern/messaging/wire-tap
- Bun
- RabbitMQ
- TypeScript
- amqplib
- Docker
Espelha cada mensagem num canal de observação sem alterar nem atrasar o fluxo principal; o broker duplica.
pattern/messaging/wire-tap
Cenário
PIX de R$ 89.500,00 é liquidado e, em paralelo, sinalizado pelo tap de compliance (PLD).
Planta
Fluxo5 passos — reproduza para seguir o fluxo
Como funciona
4passos
Espelha cada mensagem num canal de observação sem alterar nem atrasar o fluxo principal
Esconde cada passo: lembre antes de tocar para revelar.
Publicação única na exchange fanout pix.events
Cópias em pix-settlement e pix-compliance-tap
A liquidação não sabe do tap
O tap sinaliza PIX > R$ 50.000,00; parado, guarda só as cópias mais novas
Trade-offs
O que se ganha, o que se paga
Vantagens
Observação sem tocar no fluxo
Tap parado não atrasa o fluxo
Custos
Tap best-effort: cópias podem cair
Cada cópia ocupa o broker
Código
pattern/messaging/wire-tap
6 arquivos./
src/
Executar com Docker
./docker.shuntil docker exec --user rabbitmq wire-tap-broker rabbitmq-diagnostics -q check_port_connectivity >/dev/null 2>&1; do sleep 1; donebun install# dependênciasbun run demo# roda o cenáriodocker rm -f wire-tap-brokerSaída: PIX-001 de R$ 89500.00 liquidado e, em paralelo, alerta AML no tap; a ordem entre as duas linhas varia.
Código
src/demo.ts// Demo: a PIX is published once; the fanout exchange gives settlement its copy and the compliance tap another, unknown to the producer.
import amqplib from "amqplib";
const PIX_EVENTS_EXCHANGE = "pix.events";
const PIX_SETTLEMENT_QUEUE = "pix-settlement";
const PIX_TAP_QUEUE = "pix-compliance-tap";
// Above R$ 50,000.00 a PIX is flagged for the AML analysts.
const AML_THRESHOLD_CENTS = 5_000_000;
const PIX_TAP_LENGTH_MAX = 10_000;
const connection = await amqplib.connect(Bun.env.WIRE_TAP_RABBITMQ_URL ?? "amqp://guest:guest@localhost:5672");
const channel = await connection.createConfirmChannel();
await channel.assertExchange(PIX_EVENTS_EXCHANGE, "fanout", { durable: true });
await channel.assertQueue(PIX_SETTLEMENT_QUEUE, { durable: true });
// The tap is best-effort: with the observer down, it keeps only the newest copies instead of growing the broker without end.
await channel.assertQueue(PIX_TAP_QUEUE, { durable: true, maxLength: PIX_TAP_LENGTH_MAX, arguments: { "x-overflow": "drop-head" } });
for (const queue of [PIX_SETTLEMENT_QUEUE, PIX_TAP_QUEUE]) {
await channel.purgeQueue(queue);
await channel.bindQueue(queue, PIX_EVENTS_EXCHANGE, "");
}
const stats = { consumed: 0 };
await channel.consume(PIX_SETTLEMENT_QUEUE, (message) => {
if (!message) return;
const pix = JSON.parse(message.content.toString()) as { transferId: string; amountCents: number };
console.log(` [SETTLEMENT] ${pix.transferId} R$ ${(pix.amountCents / 100).toFixed(2)} settled`);
channel.ack(message);
stats.consumed++;
});
// Its own queue, never the settlement one: sharing a queue would make the two consumers compete and split the messages.
await channel.consume(PIX_TAP_QUEUE, (message) => {
if (!message) return;
const pix = JSON.parse(message.content.toString()) as { transferId: string; amountCents: number };
console.log(` [TAP] ${pix.transferId} ${pix.amountCents > AML_THRESHOLD_CENTS ? "AML alert" : "clear"}`);
channel.ack(message);
stats.consumed++;
});
// Published once: the broker makes the copies; the producer does not know the tap exists.
channel.publish(PIX_EVENTS_EXCHANGE, "", Buffer.from(JSON.stringify({ transferId: "PIX-001", amountCents: 8_950_000 })), { persistent: true });
await channel.waitForConfirms();
for (let i = 0; i < 100 && stats.consumed < 2; i++) await Bun.sleep(50);
await connection.close();
Nível
introdutório
3/13
Domínio financeiro
Padrões do catálogo que implementa
Infraestrutura
RabbitMQmessage broker
rabbitmq:3-alpine:5672
Variáveis de ambiente
Parecidos
Por que se relacionam
Combina com
Teste rápido
Qual destes combina com Wire Tap?
Rastreio sem tocar no fluxo. Abrir Message History
Seu progresso
0/157 estudados
Fica salvo só neste navegador.