Skip to content

Domain.Compaction reference

Source: packages/domain/src/Compaction.ts

Replaces an instance’s history with a few events that carry its state, so its log stops growing. The declaration says what the roll-up is; its Layer says where the replaced events go and when an instance compacts.

Views and projections keep what they already built: a compaction tells them nothing but the roll-up events themselves, which they receive like any other. Commands keep flowing while it runs.

import * as Domain from "@alchemy.run/domain";
import { Account, AccountBroughtForward } from "./Account.ts";
export class BringForward extends Domain.Compaction("BringForward", {
of: Account,
rollup: (account) => [new AccountBroughtForward({ state: account })],
}) {}

The handler gets each run of events before they are removed. Build it with any binding.

import * as Cloudflare from "@alchemy.run/cloudflare";
import * as Effect from "effect/Effect";
import { Archive } from "./Archive.ts";
import { BringForward } from "./BringForward.ts";
export const BringForwardLive = BringForward.toLayer(
Effect.gen(function* () {
const archive = yield* Cloudflare.R2.WriteBucket(Archive);
return Effect.fn(function* ({ stream, events }) {
const first = events[0].envelope.seq;
const last = events[events.length - 1].envelope.seq;
yield* archive.put(`${stream}/${first}-${last}.json`, JSON.stringify(events)).pipe(Effect.orDie);
});
}).pipe(Effect.provide(Cloudflare.R2.WriteBucketBinding)),
{ after: { events: 1_000 } },
);

Compaction: Compacting at a moment of your choosing

Section titled “Compaction: Compacting at a moment of your choosing”
const accounts = yield* Account;
yield* accounts.compact(accountId, BringForward);