Pular para o conteúdo

SNS Multi-Channel Alerts

Um único Publish no tópico AWS SNS chega a todas as subscriptions, cada uma num canal.

passos
4
arquivos
7
testes
0
tecnologias
6

Cenário

Compra de R$ 8.500,00 às 3h na Nigéria: o alerta transaction.suspicious vai ao cliente (e-mail), ao analista (SQS) e ao app (webhook).

Planta

Fluxo
5/5
Transação suspeitaPublisherTópico SNSClienteFila do analista de fraudeWebhook do appPublish comeventTypee-mailSQSHTTPS
5

5 passos — reproduza para seguir o fluxo

Como funciona

4passos

Um único Publish no tópico AWS SNS chega a todas as subscriptions, cada uma num canal

Esconde cada passo: lembre antes de tocar para revelar.

Vocabulário compartilhado

  1. 1

    FraudeValor > R$ 5.000,00, horário 00:00–05:59 ou país diferente

  2. 2

    Um Publish no tópico

  3. 3

    Tipo do evento em MessageAttributes para as filter policies

  4. 4

    O SNS entrega uma cópia por subscription; a demo confere a do analista no SQS

Trade-offs

O que se ganha, o que se paga

2 vantagenscada ganho tem um preço2 custos

Vantagens

  • Novo canal = nova subscription

  • Publisher desacoplado dos canais

Custos

  • Sem ordem nem entrega única por canal

  • Webhook precisa verificar a assinatura do SNS

Código

pattern/messaging/sns-multi-channel-alerts

7 arquivos

./

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

localstack/

  • init.shinfra

src/

  • demo.tsdemo

Executar com Docker

  1. ./docker.sh
  2. until curl -s localhost:4566/_localstack/init/ready | grep -q '"completed": true'; do sleep 1; done
  3. cp .env.example .env# variáveis de ambiente
  4. bun install# dependências
  5. bun run demo# roda o cenário
  6. docker rm -f sns-multi-channel-alerts-broker

Roda local no LocalStack (emulador AWS), que o docker.sh sobe; localstack/init.sh cria os recursos quando ele fica pronto. Na AWS real, remova AWS_ENDPOINT_URL do .env.

Saída: alerta de ACC-1001 com R$ 8500.00 publicado no SNS e lido na fila SQS do analista com os 3 motivos.

Requisitos
BunDocker

Código

src/demo.ts

// Demo: one suspicious card transaction becomes one SNS Publish; SNS fans it out to e-mail, the fraud SQS queue and the app webhook.
import { PublishCommand, SNSClient } from "@aws-sdk/client-sns";
import { DeleteMessageCommand, ReceiveMessageCommand, SQSClient } from "@aws-sdk/client-sqs";

// Above R$ 5,000.00, between 00:00 and 05:59, or abroad: any reason raises the alert.
const ALERT_AMOUNT_CENTS = 500_000;
const ALERT_TOPIC_ARN = Bun.env.SNS_MULTI_CHANNEL_ALERTS_TOPIC_ARN ?? "arn:aws:sns:sa-east-1:000000000000:transaction-suspicious";
const ALERT_ANALYST_QUEUE_URL = Bun.env.SNS_MULTI_CHANNEL_ALERTS_ANALYST_QUEUE_URL ?? "http://localhost:4566/queue/sa-east-1/000000000000/transaction-fraud-analyst";
const region = Bun.env.AWS_REGION ?? "sa-east-1";

const transaction = { accountId: "ACC-1001", amountCents: 850_000, country: "NG", hourLocal: 3, accountHomeCountry: "BR" };
const reasons = [
  transaction.amountCents > ALERT_AMOUNT_CENTS ? "amount above limit" : "",
  transaction.hourLocal < 6 ? "unusual hour" : "",
  transaction.country === transaction.accountHomeCountry ? "" : "foreign location",
].filter(Boolean);
const alert = { alertId: crypto.randomUUID(), ...transaction, reasons, detectedAt: new Date().toISOString() };

// The publisher knows only the topic; each subscription's filter policy routes on the eventType attribute, not on the body.
const { MessageId } = await new SNSClient({ region }).send(
  new PublishCommand({
    TopicArn: ALERT_TOPIC_ARN,
    Subject: "transaction.suspicious",
    Message: JSON.stringify(alert),
    MessageAttributes: { eventType: { DataType: "String", StringValue: "transaction.suspicious" } },
  }),
);
console.log(`  [PUBLISHER] ${alert.accountId} R$ ${(alert.amountCents / 100).toFixed(2)} (${reasons.join(", ")}) → SNS message ${MessageId}`);

// The SQS channel proves the fan-out: the analyst's queue holds the SNS envelope with the alert inside Message.
const sqs = new SQSClient({ region });
const { Messages = [] } = await sqs.send(new ReceiveMessageCommand({ QueueUrl: ALERT_ANALYST_QUEUE_URL, MaxNumberOfMessages: 1, WaitTimeSeconds: 10 }));
for (const message of Messages) {
  const received = JSON.parse((JSON.parse(message.Body ?? "{}") as { Message: string }).Message) as typeof alert;
  console.log(`  [FRAUD ANALYST] ${received.accountId} R$ ${(received.amountCents / 100).toFixed(2)} ${received.country}: ${received.reasons.join(", ")}`);
  await sqs.send(new DeleteMessageCommand({ QueueUrl: ALERT_ANALYST_QUEUE_URL, ReceiptHandle: message.ReceiptHandle }));
}

Nível

introdutório

2/13

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

Domínio financeiro

  • Cartão
  • Antifraude

Padrões do catálogo que implementa

Infraestrutura

  • localstack/localstack:3.8container

    localstack/localstack:3.8:4566

Variáveis de ambiente

AWS_ENDPOINT_URL
http://localhost:4566
LocalStack started by docker.sh; in real AWS remove AWS_ENDPOINT_URL and use the SDK default credential chain.
AWS_REGION
sa-east-1
AWS_ACCESS_KEY_ID
test
LocalStack accepts any credentials; never commit real ones.
AWS_SECRET_ACCESS_KEY
test
SNS_MULTI_CHANNEL_ALERTS_TOPIC_ARN
arn:aws:sns:sa-east-1:000000000000:transaction-suspicious
Topic with the three subscriptions: e-mail (customer), SQS (fraud analyst) and HTTPS (mobile app).
SNS_MULTI_CHANNEL_ALERTS_ANALYST_QUEUE_URL
http://localhost:4566/queue/sa-east-1/000000000000/transaction-fraud-analyst
Queue of the fraud analyst, subscribed to the topic; the demo reads it to show the fan-out arrived.

Parecidos

Por que se relacionam

Teste rápido

Qual destes combina com SNS Multi-Channel Alerts?

Próximo projeto, Mensageria & EventosSNS-SQS Fanout Notifications
Esc

↑ ↓ navegarEnter abrir239 resultados