Pular para o conteúdo

Microkernel (Arquitetura de Plugins)

Núcleo mínimo registra plugins e despacha a requisição aos que tratam aquele tipo; a regra mora nos plugins. Use em motores com modalidades que crescem, como meios de pagamento.

passos
4
arquivos
7
testes
0
tecnologias
5

Cenário

PIX de R$ 1.500,00: plugin pix valida limite e chave, settlement grava. TED ou boleto entram como plugin novo.

Planta

Fluxo
4/4
pagamento pixKernelPaymentregistro e despachopixsettlement *grava paymentsPostgreSQLvalidatesettle
4

4 passos — reproduza para seguir o fluxo

Como funciona

4passos

Núcleo mínimo registra plugins e despacha a requisição aos que tratam aquele tipo

Esconde cada passo: lembre antes de tocar para revelar.

Vocabulário compartilhado

  1. 1

    Plugin declara nome, fase (validate, settle) e tipos (ou *)

  2. 2

    O núcleo filtra por tipo e executa por fase, sem if por tipo

  3. 3

    Tipo sem plugin próprio é recusado

  4. 4

    Plugins conversam só pelo contexto compartilhado

Trade-offs

O que se ganha, o que se paga

2 vantagenscada ganho tem um preço2 custos

Vantagens

  • Núcleo estável, tipo novo sem tocar no existente

  • Fase independe da ordem de registro

Custos

  • Contexto compartilhado acopla plugins

  • Só o registro diz o que está ativo

Código

pattern/architecture/microkernel

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 microkernel-db pg_isready -h 127.0.0.1 -U postgres >/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 microkernel-db

Saída: PIX de R$ 1500.00 liquidado, plugins na ordem pix → settlement apesar do registro inverso.

Requisitos
BunDocker
Sobe junto
PostgreSQL

Código

src/demo.ts

// Demo: a PIX through a minimal kernel; the kernel only registers and dispatches, every payment rule is a plugin.
import pg from "pg";

const pool = new pg.Pool({ connectionString: Bun.env.MICROKERNEL_DATABASE_URL ?? "postgres://postgres:postgres@localhost:5432/microkernel_db" });

// Plugins communicate only through the context: a plugin never imports or calls another one.
type ContextPayment = { readonly paymentId: string; readonly type: string; readonly data: { amountCents: number; pixKey?: string }; result: { feeCents?: number }; pluginsRun: string[] };

// Phases run in this order; inside a phase, in registration order.
const PHASES = ["validate", "settle"] as const;
interface InterfacePaymentPlugin {
  readonly name: string;
  readonly phase: (typeof PHASES)[number];
  // The payment types it handles, or "*" for every type.
  readonly types: readonly string[];
  execute(context: ContextPayment): Promise<void>;
}

// The kernel holds no business rule and no condition on a payment type: a new type is a new plugin.
class KernelPayment {
  private readonly plugins: InterfacePaymentPlugin[] = [];

  register(plugin: InterfacePaymentPlugin): this {
    this.plugins.push(plugin);
    return this;
  }

  async process(type: string, data: ContextPayment["data"]): Promise<ContextPayment> {
    const eligible = this.plugins.filter((plugin) => plugin.types.includes(type) || plugin.types.includes("*")).toSorted((a, b) => PHASES.indexOf(a.phase) - PHASES.indexOf(b.phase));
    // A type with no plugin of its own is unsupported: "*" plugins alone do not make it valid.
    if (!eligible.some((plugin) => plugin.types.includes(type))) throw new Error(`payment type ${type} not supported`);
    const context: ContextPayment = { paymentId: crypto.randomUUID(), type, data, result: {}, pluginsRun: [] };
    for (const plugin of eligible) {
      await plugin.execute(context);
      context.pluginsRun.push(plugin.name);
    }
    return context;
  }
}

const PIX_LIMIT_CENTS = 500_000;
const pluginPix: InterfacePaymentPlugin = {
  name: "pix",
  phase: "validate",
  types: ["pix"],
  execute: async (context) => {
    if (context.data.amountCents > PIX_LIMIT_CENTS) throw new Error("pix above R$ 5000.00");
    if (!context.data.pixKey) throw new Error("pix key required");
    context.result.feeCents = 0;
  },
};

// Settlement writes the payment in the settle phase: after every validation, whatever the registration order.
const pluginSettlement: InterfacePaymentPlugin = {
  name: "settlement",
  phase: "settle",
  types: ["*"],
  execute: async (context) => {
    await pool.query("INSERT INTO payments (id, type, amount_cents, fee_cents, details) VALUES ($1, $2, $3, $4, $5)", [context.paymentId, context.type, context.data.amountCents, context.result.feeCents ?? 0, context.data]);
  },
};

// The composition: the only place that knows which plugins exist.
const kernel = new KernelPayment().register(pluginSettlement).register(pluginPix);
const context = await kernel.process("pix", { amountCents: 150_000, pixKey: "maria@banco.example" });
console.log(`  [KERNEL] PIX R$ 1500.00 settled, plugins run: ${context.pluginsRun.join(" → ")}`);
await pool.end();

Nível

intermediário

4/13

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

Domínio financeiro

  • PIX
  • TED
  • Boleto
  • Limite

Padrões do catálogo que implementa

  • Microkernel (Plugin Architecture)

Infraestrutura

  • PostgreSQLbanco relacional

    postgres:16-alpine:5432

Banco

sql/01_schema.sql

  • payments

Variáveis de ambiente

MICROKERNEL_DATABASE_URL
postgres://postgres:postgres@localhost:5432/microkernel_db

Por que se relacionam

Teste rápido

Qual destes combina com Microkernel?

Próximo projeto, ArquiteturaMicrosserviços
Esc

↑ ↓ navegarEnter abrir239 resultados