pattern/architecture/soa
- Bun
- ElysiaJS
- PostgreSQL
- RabbitMQ
- TypeScript
- amqplib
- node-postgres
- Docker
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.
pattern/architecture/soa
Cenário
Transferência de R$ 3.000,00 no modelo canônico; compliance fala JSON, o core legado só largura fixa.
Planta
Sequência7 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
O ESB expõe POST /v1/transfers e valida o canônico
Cada chamada vai à exchange soa.bus com a versão na chave; resposta pela fila exclusiva com o correlationId
Compliance aprova antes do core
O ESB traduz JSON ↔ largura fixa
Trade-offs
O que se ganha, o que se paga
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./
sql/
src/
Executar com Docker
./docker.shuntil docker exec --user rabbitmq soa-broker rabbitmq-diagnostics -q check_port_connectivity >/dev/null 2>&1; do sleep 1; doneuntil 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; donebun install# dependênciasbun run demo# roda o cenáriodocker rm -f soa-broker soa-core-dbSaída: o core legado responde OK000000002200000; o canal recebe 201 approved com sourceBalanceCents 2200000.
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
Domínio financeiro
Padrões do catálogo que implementa
Infraestrutura
RabbitMQmessage broker
rabbitmq:3-alpine:5672
PostgreSQLbanco relacional
postgres:16-alpine:5432
Banco
sql/01_schema.sql
Variáveis de ambiente
Parecidos
Por que se relacionam
Teste rápido
Qual destes combina com SOA?
ESB como barramento corporativo. Abrir Message Broker
Seu progresso
0/157 estudados
Fica salvo só neste navegador.