Pular para o conteúdo

Wire Tap

Espelha cada mensagem num canal de observação sem alterar nem atrasar o fluxo principal; o broker duplica.

passos
4
arquivos
6
testes
0
tecnologias
5

Cenário

PIX de R$ 89.500,00 é liquidado e, em paralelo, sinalizado pelo tap de compliance (PLD).

Planta

Fluxo
5/5
API de PIXpix.events fanoutpix-settlementpix-compliance-tap,drop-headLiquidaçãoTap de compliance AML1 publishcópiacópia
5

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

  1. 1

    Publicação única na exchange fanout pix.events

  2. 2

    Cópias em pix-settlement e pix-compliance-tap

  3. 3

    A liquidação não sabe do tap

  4. 4

    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

2 vantagenscada ganho tem um preço2 custos

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

./

  • .env.exampleinfra
  • docker.shinfra
  • package.jsoninfra
  • README.md
  • tsconfig.jsoninfra

src/

  • demo.tsdemo

Executar com Docker

  1. ./docker.sh
  2. until docker exec --user rabbitmq wire-tap-broker rabbitmq-diagnostics -q check_port_connectivity >/dev/null 2>&1; do sleep 1; done
  3. bun install# dependências
  4. bun run demo# roda o cenário
  5. docker rm -f wire-tap-broker

Saída: PIX-001 de R$ 89500.00 liquidado e, em paralelo, alerta AML no tap; a ordem entre as duas linhas varia.

Requisitos
BunDocker
Sobe junto
RabbitMQ

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

Linhas de TypeScript
39
Tipo
B — um serviço (docker.sh)

Domínio financeiro

  • PIX
  • Liquidação

Padrões do catálogo que implementa

  • Wire Tap

Infraestrutura

  • RabbitMQmessage broker

    rabbitmq:3-alpine:5672

Variáveis de ambiente

WIRE_TAP_RABBITMQ_URL
amqp://guest:guest@localhost:5672
RabbitMQ of the PIX events.

Parecidos

Por que se relacionam

Teste rápido

Qual destes combina com Wire Tap?

Próximo projeto, Transações & ConsistênciaCoreografia vs Orquestração
Esc

↑ ↓ navegarEnter abrir239 resultados