Pular para o conteúdo

Routing Slip

O itinerário viaja na mensagem: cada etapa executa sua parte e encaminha ao próximo nome, sem orquestrador.

passos
4
arquivos
4
testes
0
tecnologias
3

Cenário

Proposta de crédito passa por KYC, Score, Compliance e Comitê; o itinerário é montado na origem.

Planta

Fluxo
5/5
Origem: montaproposta e itinerárioKYC :8121Score :8122Compliance :8123Comitê :8124replyTo da origempróximo nome no slippróximo nome no slippróximo nome no slipsem próximo nome
5

5 passos — reproduza para seguir o fluxo

Como funciona

4passos

O itinerário viaja na mensagem e cada etapa encaminha ao próximo nome, sem orquestrador

Esconde cada passo: lembre antes de tocar para revelar.

Vocabulário compartilhado

  1. 1

    Proposta com itinerary, stepIndexCurrent = 0 e replyTo

  2. 2

    Etapa fora da posição atual responde 409

  3. 3

    Executa a regra, anota em history e responde 202

  4. 4

    Encaminha ao próximo ou envia a decisão ao replyTo

Trade-offs

O que se ganha, o que se paga

2 vantagenscada ganho tem um preço2 custos

Vantagens

  • Sem orquestrador para cair

  • Caminho por mensagem com os mesmos serviços

Custos

  • Fluxo fixo depois do envio

  • Estado espalhado pelas etapas

Código

pattern/messaging/routing-slip

4 arquivos

./

  • package.jsoninfra
  • README.md
  • tsconfig.jsoninfra

src/

  • demo.tsdemo

Executar só Bun

  1. bun install# dependências
  2. bun run demo# roda o cenário

Saída: envio fora de posição recusado com 409; PROP-001 passa por kyc → score 820 → compliance → committee approved.

Requisitos
Bun

Código

src/demo.ts

// Demo: a credit proposal carries its own itinerary; each Elysia step does its part and forwards the slip to the next name.
import { Elysia } from "elysia";

const CREDIT_STEPS = ["kyc", "score", "compliance", "committee"] as const;
type CreditStep = (typeof CREDIT_STEPS)[number];
// One port per step in CREDIT_STEPS order, starting here; the origin has its own.
const CREDIT_STEP_PORT_FIRST = 8121;
const CREDIT_ORIGIN_PORT = 8120;

type CreditSlip = {
  proposalId: string;
  amountCents: number;
  itinerary: CreditStep[];
  // Position of the step that must handle the slip now.
  stepIndexCurrent: number;
  history: string[];
  replyTo: string;
};

const stepUrl = (step: CreditStep) => `http://localhost:${CREDIT_STEP_PORT_FIRST + CREDIT_STEPS.indexOf(step)}/process`;

const STEP_RULES: Record<CreditStep, (slip: CreditSlip) => string> = {
  kyc: (slip) => (slip.amountCents <= 50_000_000 ? "kyc approved" : "kyc rejected"),
  score: (slip) => `score ${Math.max(300, 900 - Math.round(slip.amountCents / 100_000))}`,
  compliance: () => "compliance clear",
  committee: (slip) => (slip.history.includes("kyc approved") ? "committee approved" : "committee rejected"),
};

async function slipPost(url: string, slip: CreditSlip): Promise<number> {
  return (await fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(slip) })).status;
}

// Each step knows only its own rule: the next hop is read from the slip, never from a central orchestrator.
const steps = CREDIT_STEPS.map((step) =>
  new Elysia()
    .post("/process", ({ body, status }) => {
      const slip = body as CreditSlip;
      if (slip.itinerary[slip.stepIndexCurrent] !== step) return status(409, { error: "slip.step.out_of_position" });
      const result = STEP_RULES[step](slip);
      console.log(`  [${step.toUpperCase()}] ${slip.proposalId}: ${result}`);
      const next = { ...slip, stepIndexCurrent: slip.stepIndexCurrent + 1, history: [...slip.history, result] };
      const nextStep = slip.itinerary[next.stepIndexCurrent];
      queueMicrotask(() => void slipPost(nextStep ? stepUrl(nextStep) : slip.replyTo, next));
      return status(202, { accepted: slip.proposalId });
    })
    .listen(CREDIT_STEP_PORT_FIRST + CREDIT_STEPS.indexOf(step)),
);

const decision = Promise.withResolvers<CreditSlip>();
const origin = new Elysia().post("/decisions", ({ body }) => (decision.resolve(body as CreditSlip), "ok")).listen(CREDIT_ORIGIN_PORT);

// The itinerary is decided once, at the origin, and travels inside the message.
const slip: CreditSlip = { proposalId: "PROP-001", amountCents: 8_000_000, itinerary: ["kyc", "score", "compliance", "committee"], stepIndexCurrent: 0, history: [], replyTo: `http://localhost:${CREDIT_ORIGIN_PORT}/decisions` };
console.log(`  [ORIGIN] ${slip.proposalId} R$ ${(slip.amountCents / 100).toFixed(2)}: ${slip.itinerary.join(" → ")}`);
// A slip sent to a step out of its position is refused; the itinerary, not the sender, says who is next.
console.log(`  [ORIGIN] sent to score out of position → HTTP ${await slipPost(stepUrl("score"), slip)}`);
await slipPost(stepUrl(slip.itinerary[0]!), slip);
console.log(`  [ORIGIN] decision: ${(await decision.promise).history.join(" → ")}`);

for (const app of [...steps, origin]) await app.stop();

Nível

introdutório

1/13

Linhas de TypeScript
51
Tipo
A — código puro

Domínio financeiro

  • Crédito/Empréstimo
  • KYC

Padrões do catálogo que implementa

  • Routing Slip

Parecidos

Por que se relacionam

Teste rápido

Qual destes combina com Routing Slip?

Próximo projeto, Mensageria & EventosScatter-Gather
Esc

↑ ↓ navegarEnter abrir239 resultados