pattern/architecture/microkernel
- Bun
- PostgreSQL
- TypeScript
- node-postgres
- Docker
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.
pattern/architecture/microkernel
Cenário
PIX de R$ 1.500,00: plugin pix valida limite e chave, settlement grava. TED ou boleto entram como plugin novo.
Planta
Fluxo4 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
Plugin declara nome, fase (validate, settle) e tipos (ou *)
O núcleo filtra por tipo e executa por fase, sem if por tipo
Tipo sem plugin próprio é recusado
Plugins conversam só pelo contexto compartilhado
Trade-offs
O que se ganha, o que se paga
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./
sql/
src/
Executar com Docker
./docker.shuntil docker exec microkernel-db pg_isready -h 127.0.0.1 -U postgres >/dev/null 2>&1; do sleep 1; donebun install# dependênciasbun run demo# roda o cenáriodocker rm -f microkernel-dbSaída: PIX de R$ 1500.00 liquidado, plugins na ordem pix → settlement apesar do registro inverso.
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
Domínio financeiro
Padrões do catálogo que implementa
Infraestrutura
PostgreSQLbanco relacional
postgres:16-alpine:5432
Banco
sql/01_schema.sql
Variáveis de ambiente
Por que se relacionam
Teste rápido
Qual destes combina com Microkernel?
O plugin escolhe o comportamento. Abrir Strategy
Seu progresso
0/157 estudados
Fica salvo só neste navegador.