Pular para o conteúdo

Event Notification

O evento traz só o id do que mudou; quem precisa do detalhe chama a origem. Payload mínimo, dado sempre atual.

passos
4
arquivos
6
testes
0
tecnologias
6

Cenário

Pagamentos aprova um PIX e publica só o id; o notificador busca valor e contas na API antes de avisar o cliente.

Planta

Sequência
4/4
Lua: HSET pagamento + XADD notificação (só o id)1XREADGROUP customer-notifier2GET /payments/PAY-0013pagamento atual4Serviço de pagamentosRedisNotificador do clienteAPI de pagamentos
4

4 passos — reproduza para seguir o fluxo

Como funciona

4passos

O evento traz só o id do que mudou e quem precisa do detalhe chama a origem

Esconde cada passo: lembre antes de tocar para revelar.

  1. 1

    Script Lua grava o pagamento e faz XADD no mesmo passo

  2. 2

    A notificação traz só tipo e paymentId

  3. 3

    O notificador lê pelo consumer group e chama GET /payments/:id

  4. 4

    Avisa o cliente e confirma com XACK

Trade-offs

O que se ganha, o que se paga

2 vantagenscada ganho tem um preço2 custos

Vantagens

  • Payload pequeno e estável

  • Dado sempre atual

Custos

  • Receptor depende da origem no ar

  • Uma chamada extra por evento

Código

pattern/messaging/event-notification

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 event-notification-cache redis-cli ping >/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 event-notification-cache

Saída: evento só com tipo e paymentId, sem valor nem contas; notificação de ACC-1001: PIX de R$ 1500.00 para ACC-2002 aprovado.

Requisitos
BunDocker
Sobe junto
Redis

Código

src/demo.ts

// Demo: the event says only which payment changed; the customer notifier calls the payments API back for the details.
import { RedisClient } from "bun";
import { Elysia } from "elysia";

const PAYMENT_STREAM = "payment:v1:notifications";
const NOTIFIER_GROUP = "customer-notifier";
const PAYMENT_API_PORT = Number(Bun.env.EVENT_NOTIFICATION_API_PORT ?? 8118);

const redis = new RedisClient(Bun.env.EVENT_NOTIFICATION_REDIS_URL ?? "redis://localhost:6379");
await redis.send("DEL", [PAYMENT_STREAM, "payment:v1:PAY-001"]);
await redis.send("XGROUP", ["CREATE", PAYMENT_STREAM, NOTIFIER_GROUP, "0", "MKSTREAM"]);

// State and notification in one Lua step: never an event for a payment that was not written.
const PAYMENT_WRITE_SCRIPT = `
redis.call('HSET', KEYS[1], unpack(ARGV, 2))
redis.call('XADD', KEYS[2], '*', 'type', 'com.bank.payment.approved', 'paymentId', ARGV[1])`;
await redis.send("EVAL", [PAYMENT_WRITE_SCRIPT, "2", "payment:v1:PAY-001", PAYMENT_STREAM, "PAY-001", "accountFromId", "ACC-1001", "accountToId", "ACC-2002", "amountCents", "150000"]);

// The source of truth the receiver asks for the details.
const api = new Elysia()
  .get("/payments/:paymentId", async ({ params }) => (await redis.send("HGETALL", [`payment:v1:${params.paymentId}`])) as Record<string, string>)
  .listen(PAYMENT_API_PORT);

const reply = (await redis.send("XREADGROUP", ["GROUP", NOTIFIER_GROUP, "notifier-1", "COUNT", "10", "STREAMS", PAYMENT_STREAM, ">"])) as Record<string, [string, string[]][]>;
for (const [entryId, fields] of reply[PAYMENT_STREAM] ?? []) {
  console.log(`  [EVENT]  ${JSON.stringify(fields)} (no amount, no accounts)`);
  const paymentId = fields[fields.indexOf("paymentId") + 1]!;
  // The price of the small event: one callback to the source, which always returns the current state.
  const payment = (await (await fetch(`http://localhost:${PAYMENT_API_PORT}/payments/${paymentId}`)).json()) as Record<string, string>;
  console.log(`  [NOTIFY] ${payment.accountFromId}: PIX R$ ${(Number(payment.amountCents) / 100).toFixed(2)} to ${payment.accountToId} approved`);
  await redis.send("XACK", [PAYMENT_STREAM, NOTIFIER_GROUP, entryId]);
}

await api.stop();
redis.close();

Nível

introdutório

2/13

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

Domínio financeiro

  • PIX
  • Conta corrente

Padrões do catálogo que implementa

Infraestrutura

  • Rediscache / estrutura de dados

    redis:7-alpine:6379

Variáveis de ambiente

EVENT_NOTIFICATION_REDIS_URL
redis://localhost:6379
Redis holding the payments and the notification stream.
EVENT_NOTIFICATION_API_PORT
8118
Port of the payments API the notifier calls back (GET /payments/:paymentId).

Trilhapasso 3 de 7

Event-driven

  1. 1Message Broker
  2. 2Pub/Sub
  3. 3Event Notification
  4. 4Event-Carried State Transfer
  5. 5Event Sourcing
  6. 6Snapshot
  7. 7CQRS (Command Query Responsibility Segregation)

Parecidos

Por que se relacionam

Teste rápido

Qual é o próximo passo depois de Event Notification?

Próximo projeto, Mensageria & EventosEvent Streaming
Esc

↑ ↓ navegarEnter abrir239 resultados