Pular para o conteúdo

SOA (Arquitetura Orientada a Serviços)

Serviços com contrato explícito falam por um ESB que recebe o modelo canônico, orquestra e traduz para cada serviço, inclusive legados. Use com sistemas heterogêneos e muitos canais.

passos
4
arquivos
7
testes
0
tecnologias
8

Cenário

Transferência de R$ 3.000,00 no modelo canônico; compliance fala JSON, o core legado só largura fixa.

Planta

Sequência
7/7
POST /v1/transfers (modelo canônico)1compliance.transfer.validate.v12aprovado3corebanking.transfer.execute.v1 (TRF...)4débito e crédito5OK + saldo (largura fixa)6201 aprovado7CanalESB (HTTP para AMQP)Compliance (JSON)Core legado (largura fixa)PostgreSQL do core
7

7 passos — reproduza para seguir o fluxo

Como funciona

4passos

Serviços com contrato explícito falam por um ESB que recebe o modelo canônico, orquestra e traduz para cada serviço, inclusive legados

Esconde cada passo: lembre antes de tocar para revelar.

Vocabulário compartilhado

  1. 1

    O ESB expõe POST /v1/transfers e valida o canônico

  2. 2

    Cada chamada vai à exchange soa.bus com a versão na chave; resposta pela fila exclusiva com o correlationId

  3. 3

    Compliance aprova antes do core

  4. 4

    O ESB traduz JSON ↔ largura fixa

Trade-offs

O que se ganha, o que se paga

2 vantagenscada ganho tem um preço2 custos

Vantagens

  • Desacoplamento por contrato versionado

  • Legado integrado sem expor o formato

Custos

  • ESB concentra lógica e falha

  • Salto pelo barramento em toda chamada

Código

pattern/architecture/soa

7 arquivos

./

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

sql/

  • 01_schema.sqlschema

src/

  • demo.tsdemo

Executar com Docker

  1. ./docker.sh
  2. until docker exec --user rabbitmq soa-broker rabbitmq-diagnostics -q check_port_connectivity >/dev/null 2>&1; do sleep 1; done
  3. until docker exec soa-core-db pg_isready -h 127.0.0.1 -U postgres -d core_banking_db >/dev/null 2>&1; do sleep 1; done
  4. bun install# dependências
  5. bun run demo# roda o cenário
  6. docker rm -f soa-broker soa-core-db

Saída: o core legado responde OK000000002200000; o canal recebe 201 approved com sourceBalanceCents 2200000.

Requisitos
BunDocker
Sobe junto
PostgreSQLRabbitMQ

Código

src/demo.ts

// Demo: a channel sends a canonical transfer to the ESB; the ESB orchestrates compliance (JSON) and a legacy core (fixed width) over RabbitMQ.
import amqplib, { type Channel } from "amqplib";
import { Elysia, t } from "elysia";
import pg from "pg";

const EXCHANGE = "soa.bus";
// Contract version in the key: a v2 of a service can run beside v1 while consumers migrate.
const ROUTE_COMPLIANCE = "compliance.transfer.validate.v1";
const ROUTE_CORE = "corebanking.transfer.execute.v1";
const COMPLIANCE_LIMIT_CENTS = 5_000_000;

const connection = await amqplib.connect(Bun.env.SOA_AMQP_URL ?? "amqp://guest:guest@localhost:5672");
const pool = new pg.Pool({ connectionString: Bun.env.SOA_CORE_DATABASE_URL ?? "postgres://postgres:postgres@localhost:5432/core_banking_db" });
const channel = await connection.createChannel();
await channel.assertExchange(EXCHANGE, "topic", { durable: false });

// A service binds its queue to its contract key and answers on the caller's reply queue with the same correlationId.
async function serviceServe(queue: string, routingKey: string, handle: (content: string) => Promise<string>, service: Channel = channel) {
  await service.assertQueue(queue, { exclusive: true });
  await service.bindQueue(queue, EXCHANGE, routingKey);
  await service.consume(queue, async (message) => {
    if (!message) return;
    service.sendToQueue(message.properties.replyTo, Buffer.from(await handle(message.content.toString())), { correlationId: message.properties.correlationId });
    service.ack(message);
  });
}

// Compliance service: speaks the canonical JSON.
await serviceServe("compliance.service", ROUTE_COMPLIANCE, async (content) => JSON.stringify({ approved: (JSON.parse(content) as { amountCents: number }).amountCents <= COMPLIANCE_LIMIT_CENTS }));

// Legacy core: speaks only "TRF" + source (12) + target (12) + amount (15), replies "OK"/"NK" + balance (15), owns its database.
await serviceServe("corebanking.service", ROUTE_CORE, async (line) => {
  const [source, target, amountCents] = [line.slice(3, 15), line.slice(15, 27), Number(line.slice(27, 42))];
  const { rows } = await pool.query<{ balance_cents: string }>(
    `WITH debit AS (UPDATE accounts SET balance_cents = balance_cents - $3 WHERE id = $1 AND balance_cents >= $3 RETURNING balance_cents),
     credit AS (UPDATE accounts SET balance_cents = balance_cents + $3 WHERE id = $2 AND EXISTS (SELECT 1 FROM debit))
     SELECT balance_cents FROM debit`,
    [source, target, amountCents],
  );
  return `${rows[0] ? "OK" : "NK"}${String(rows[0]?.balance_cents ?? 0).padStart(15, "0")}`;
});

// The ESB's request-reply: an exclusive reply queue, matched by correlationId.
const { queue: replyQueue } = await channel.assertQueue("", { exclusive: true });
const pending = new Map<string, (body: string) => void>();
await channel.consume(replyQueue, (message) => message && pending.get(message.properties.correlationId)?.(message.content.toString()), { noAck: true });
const busCall = (routingKey: string, body: string) =>
  new Promise<string>((resolve) => {
    const correlationId = crypto.randomUUID();
    pending.set(correlationId, resolve);
    channel.publish(EXCHANGE, routingKey, Buffer.from(body), { replyTo: replyQueue, correlationId });
  });

// ESB: HTTP → AMQP mediation, orchestration and translation from the canonical model to the legacy layout.
const legacyAccount = (id: string) => id.replace("-", "").padStart(12, "0");
const esb = new Elysia().post("/v1/transfers", async ({ body, status }) => {
  const decision = JSON.parse(await busCall(ROUTE_COMPLIANCE, JSON.stringify(body))) as { approved: boolean };
  if (!decision.approved) return status(422, { status: "rejected", reason: "compliance" });
  const reply = await busCall(ROUTE_CORE, `TRF${legacyAccount(body.sourceAccountId)}${legacyAccount(body.targetAccountId)}${String(body.amountCents).padStart(15, "0")}`);
  console.log(`  [ESB] legacy reply "${reply}"`);
  return reply.startsWith("OK") ? status(201, { status: "approved", sourceBalanceCents: Number(reply.slice(2)) }) : status(422, { status: "rejected", reason: "core" });
}, { body: t.Object({ sourceAccountId: t.String({ pattern: "^[0-9]{4}-[0-9]{7}$" }), targetAccountId: t.String({ pattern: "^[0-9]{4}-[0-9]{7}$" }), amountCents: t.Integer({ minimum: 1 }) }) });

const [alice, bruno] = ["1", "2"].map((digit) => `0001-${String(Date.now()).slice(-6)}${digit}`) as [string, string];
await pool.query("INSERT INTO accounts (id, holder_name, balance_cents) VALUES ($1, 'Alice Ferreira', 2500000), ($2, 'Bruno Martins', 1200000)", [legacyAccount(alice), legacyAccount(bruno)]);
const response = await esb.handle(new Request("http://localhost/v1/transfers", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ sourceAccountId: alice, targetAccountId: bruno, amountCents: 300_000 }) }));
console.log(`  [CHANNEL] R$ 3000.00 Alice → Bruno → ${response.status} ${await response.text()}`);
await connection.close();
await pool.end();

Nível

intermediário

6/13

Linhas de TypeScript
61
Tipo
B — dois ou mais serviços (docker compose)

Domínio financeiro

  • Saldo

Padrões do catálogo que implementa

  • Service-Oriented Architecture (SOA)

Infraestrutura

  • RabbitMQmessage broker

    rabbitmq:3-alpine:5672

  • PostgreSQLbanco relacional

    postgres:16-alpine:5432

Banco

sql/01_schema.sql

  • accounts

Variáveis de ambiente

SOA_AMQP_URL
amqp://guest:guest@localhost:5672
SOA_CORE_DATABASE_URL
postgres://postgres:postgres@localhost:5432/core_banking_db

Parecidos

Por que se relacionam

Teste rápido

Qual destes combina com SOA?

Próximo projeto, ArquiteturaVertical Slice Architecture
Esc

↑ ↓ navegarEnter abrir239 resultados