Órbita
- Código
- Arquitetura
- Dados
- Integração
- Resiliência
Quando usar
Auditoria completa, reprocessamento e linha do tempo
Órbita
Quando usar
Auditoria completa, reprocessamento e linha do tempo
Problema
Estado atual sem histórico de como chegou até ali
Quando usar
Auditoria completa, reprocessamento e linha do tempo
event-sourcing
Persiste cada mudança como evento imutável e reconstrói o estado a partir deles.
Relacionados
3Planta de sequência
Reproduzir passo a passoComo funciona
O comando dobra os eventos com accountEventApply, sem I/O
Decide e gera o novo evento
Grava na versão + 1; (aggregate_id, version) única deixa passar só um dos saques simultâneos
Trigger recusa UPDATE e DELETE no log
README.mdpattern/persistence/event-sourcing
thiagoeti/pattern/event-sourcingCada mudança é um evento imutável num log append-only; o saldo é derivado dobrando os eventos com função pura.
Abertura, depósito e saque viram EventAccountOpened, EventAccountMoneyDeposited e EventAccountMoneyWithdrawn; dois saques simultâneos disputam a mesma versão e o saldo sai do replay.
accountEventApply, sem I/O(aggregate_id, version) única deixa passar só um dos saques simultâneosUPDATE e DELETE no logsrc/demo.ts// Demo: every change to the account is an appended, immutable event; the balance is never stored, it is a fold over the stream.
import pg from "pg";
const pool = new pg.Pool({ connectionString: Bun.env.EVENT_SOURCING_DATABASE_URL ?? "postgres://postgres:postgres@localhost:5432/eventsourcing_db" });
type EventAccount = { type: "EventAccountOpened" | "EventAccountMoneyDeposited" | "EventAccountMoneyWithdrawn"; payload: { amountCents?: number; ownerName?: string } };
type AccountState = { balanceCents: number; version: number };
// Pure fold: no I/O and no rule — a past fact is replayed, never refused.
const accountEventApply = (state: AccountState, event: EventAccount): AccountState => {
const signedCents = event.type === "EventAccountMoneyDeposited" ? event.payload.amountCents! : event.type === "EventAccountMoneyWithdrawn" ? -event.payload.amountCents! : 0;
return { balanceCents: state.balanceCents + signedCents, version: state.version + 1 };
};
async function accountLoad(accountId: string): Promise<AccountState> {
const { rows } = await pool.query<{ event_type: EventAccount["type"]; payload: EventAccount["payload"] }>("SELECT event_type, payload FROM event_store WHERE aggregate_id = ## Executar ORDER BY version", [accountId]);
return rows.map((row) => ({ type: row.event_type, payload: row.payload })).reduce(accountEventApply, { balanceCents: 0, version: 0 });
}
// Load, decide against the current state, append at version + 1: a concurrent writer of that version fails on the unique key.
async function eventAppend(accountId: string, state: AccountState, event: EventAccount): Promise<void> {
await pool.query("INSERT INTO event_store (aggregate_id, version, event_type, payload) VALUES (## Executar, $2, $3, $4)", [accountId, state.version + 1, event.type, event.payload]);
console.log(` [STORE] v${state.version + 1} ${event.type} ${JSON.stringify(event.payload)}`);
}
async function accountCommand(accountId: string, decide: (state: AccountState) => EventAccount): Promise<void> {
const state = await accountLoad(accountId);
await eventAppend(accountId, state, decide(state));
}
const accountId = crypto.randomUUID();
await accountCommand(accountId, () => ({ type: "EventAccountOpened", payload: { ownerName: "Ana Lima" } }));
await accountCommand(accountId, () => ({ type: "EventAccountMoneyDeposited", payload: { amountCents: 200_000 } }));
const withdrawalDecide = (state: AccountState): EventAccount => {
if (state.balanceCents < 30_000) throw new Error("balance insufficient");
return { type: "EventAccountMoneyWithdrawn", payload: { amountCents: 30_000 } };
};
// Two tellers withdraw at once: both load v2 before either appends, so both write v3 and the unique key lets exactly one through.
const states = await Promise.all([accountLoad(accountId), accountLoad(accountId)]);
const outcomes = await Promise.allSettled(states.map((state) => eventAppend(accountId, state, withdrawalDecide(state))));
const conflicts = outcomes.filter((outcome) => outcome.status === "rejected");
console.log(` [CONCURRENCY] 2 withdrawals at v2: ${outcomes.length - conflicts.length} appended, ${conflicts.length} rejected (${conflicts.map((outcome) => (outcome.reason as Error).message).join("; ")})`);
const state = await accountLoad(accountId);
console.log(` [LOAD] balance R$ ${(state.balanceCents / 100).toFixed(2)} replayed from ${state.version} events`);
const refused = await pool.query("UPDATE event_store SET payload = '{}' WHERE aggregate_id = ## Executar", [accountId]).catch((error: Error) => error.message);
console.log(` [STORE] UPDATE on the log: ${refused}`);
await pool.end();
./docker.sh
until docker exec event-sourcing-db pg_isready -h 127.0.0.1 -U postgres >/dev/null 2>&1; do sleep 1; done
bun install
bun run demo
docker rm -f event-sourcing-db
Saída: v1 abertura, v2 depósito de 200000; dos dois saques simultâneos de 30000 na v2, 1 grava a v3 e 1 é recusado pela chave única uq_event_store_aggregate_version; o replay de 3 eventos dá R$ 1700.00 e o UPDATE no log é recusado.
| Vantagem | Desvantagem |
|---|---|
| Auditoria imutável por construção | Leitura exige replay ou projeção |
| Saldo em qualquer ponto do histórico | Log cresce e pede snapshot |