Pular para o conteúdo

Message History

O envelope acumula o registro de cada componente por onde a mensagem passou; o caminho sai da mensagem final, sem tracing externo.

passos
4
arquivos
6
testes
0
tecnologias
5

Cenário

Proposta de crédito passa por KYC, score e compliance; a mensagem final mostra o caminho e o tempo de cada etapa.

Planta

Sequência
4/4
envelope com 1 entrada1envelope com 2 entradas2envelope com 3 entradas3envelope final com 4 entradas4credit-apikyc-servicescore-servicecompliance-servicecredit-decided
4

4 passos — reproduza para seguir o fluxo

Como funciona

4passos

O envelope acumula o registro de cada componente por onde a mensagem passou

Esconde cada passo: lembre antes de tocar para revelar.

  1. 1

    A API cria o envelope com a primeira entrada em history

  2. 2

    Cada estágio acrescenta só a própria entrada

  3. 3

    O envelope segue ao próximo estágio antes do ack

  4. 4

    receivedAt em ISO 8601 dá a latência entre estágios

Trade-offs

O que se ganha, o que se paga

2 vantagenscada ganho tem um preço2 custos

Vantagens

  • Caminho legível na mensagem

  • Sem backend de tracing

Custos

  • Payload cresce a cada estágio

  • Expõe a arquitetura interna

Código

pattern/messaging/message-history

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 message-history-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 message-history-broker

Saída: histórico com 4 entradas na mensagem: credit-api, kyc-service, score-service (835) e compliance-service aprovado.

Requisitos
BunDocker
Sobe junto
RabbitMQ

Código

src/demo.ts

// Demo: a credit application crosses KYC, score and compliance; each stage appends its entry to the history inside the message.
import amqplib from "amqplib";

type HistoryEntry = { service: string; receivedAt: string; note: string };
type Envelope = { applicationId: string; amountCents: number; history: HistoryEntry[] };

// Each stage consumes one queue and forwards to the next; credit-decided is the end of the line.
const CREDIT_STAGES = [
  { queue: "credit-kyc", next: "credit-score", service: "kyc-service", note: "identity verified" },
  { queue: "credit-score", next: "credit-compliance", service: "score-service", note: "credit score 835" },
  { queue: "credit-compliance", next: "credit-decided", service: "compliance-service", note: "no AML flags, approved" },
];

// Append-only: previous entries stay untouched and this stage's entry goes at the end.
const historyAppend = (envelope: Envelope, service: string, note: string): Envelope => ({
  ...envelope,
  history: [...envelope.history, { service, receivedAt: new Date().toISOString(), note }],
});

const connection = await amqplib.connect(Bun.env.MESSAGE_HISTORY_RABBITMQ_URL ?? "amqp://guest:guest@localhost:5672");
const channel = await connection.createChannel();
for (const queue of [...CREDIT_STAGES.map((stage) => stage.queue), "credit-decided"]) {
  await channel.assertQueue(queue, { durable: true });
  await channel.purgeQueue(queue);
}

for (const stage of CREDIT_STAGES) {
  await channel.consume(stage.queue, (message) => {
    if (!message) return;
    // The whole envelope, history included, goes forward before the consumed message is acked.
    const envelope = historyAppend(JSON.parse(message.content.toString()) as Envelope, stage.service, stage.note);
    channel.sendToQueue(stage.next, Buffer.from(JSON.stringify(envelope)), { persistent: true });
    channel.ack(message);
  });
}

const application: Envelope = { applicationId: "CRED-001", amountCents: 1_500_000, history: [] };
channel.sendToQueue("credit-kyc", Buffer.from(JSON.stringify(historyAppend(application, "credit-api", "application received"))), { persistent: true });

// The path and the latency are read from the final message alone, without a tracing backend.
for (let i = 0; i < 100; i++) {
  const message = await channel.get("credit-decided", { noAck: true });
  if (message) {
    const { history } = JSON.parse(message.content.toString()) as Envelope;
    for (const [index, entry] of history.entries()) {
      const hopMs = index === 0 ? 0 : Date.parse(entry.receivedAt) - Date.parse(history[index - 1]!.receivedAt);
      console.log(`  [HISTORY] ${entry.service.padEnd(19)} +${hopMs}ms  ${entry.note}`);
    }
    break;
  }
  await Bun.sleep(50);
}

await connection.close();

Nível

introdutório

3/13

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

Domínio financeiro

  • Crédito/Empréstimo
  • KYC

Padrões do catálogo que implementa

  • Message History

Infraestrutura

  • RabbitMQmessage broker

    rabbitmq:3-alpine:5672

Variáveis de ambiente

MESSAGE_HISTORY_RABBITMQ_URL
amqp://guest:guest@localhost:5672
RabbitMQ of the credit pipeline.

Por que se relacionam

Teste rápido

Qual destes combina com Message History?

Próximo projeto, Mensageria & EventosMessage Routing
Esc

↑ ↓ navegarEnter abrir239 resultados