Replicate runs into a database you own
Each run's log lives in that run's actor database. A replica keeps a complete copy of every run in a Postgres or SQLite database you own, so you can set retention, add indexes, run analytics, and rebuild a run without opening its actor. SQLite includes Cloudflare D1.
Attach a replica#
postgresReplica is registered like any other projector. Delivery reads events after blob offload, so the copy stores the payload the actor returned, not a pointer at object storage. The run summary, actors, and reviews are folded in the same transaction.
import { postgresReplica } from '@swirls/looms/replica'const replica = postgresReplica({ url: process.env.DATABASE_URL!, migrate: 'auto',})// Pass `replica` in the host's projector list.migrate: 'auto' applies pending Looms migrations on startup. Postgres takes an advisory lock while it does that. migrate: 'verify' refuses to start when a migration is missing and tells you to generate it. Use verify when your own migration tool owns the database.
sqliteReplica is the same projector for a shared SQLite file or D1. It is not the actor's own SQLite. Pass a D1Database through d1ReplicaDatabase, or any driver that implements the replica's small async SQL surface. One writer per run is assumed: D1 applies the copy as a batch, not an interactive transaction.
import { d1ReplicaDatabase, sqliteReplica } from '@swirls/looms/replica/sqlite'const replica = sqliteReplica({ database: d1ReplicaDatabase(env.REPLICA), migrate: 'verify',})looms replica generate --dialect sqlite --out ./migrationslooms replica migrate --dialect sqlite --database ./replica.sqlitelooms replica status --dialect sqlite --database ./replica.sqliteOn D1, apply the generated file with your own tool (wrangler d1 execute) and keep migrate: 'verify'. --database for the SQLite dialect is a file path. The default dialect is still Postgres.
Migrate, or generate SQL#
Looms owns the looms_* tables. Generating SQL commits them to the folder your migration tool already applies. A second run writes nothing. --check exits non-zero while something is pending, which is what you want in CI.
looms replica generate --out ./migrations --journal drizzlelooms replica generate --out ./migrations --journal drizzle --checklooms replica migrate --database "$DATABASE_URL"looms replica status --database "$DATABASE_URL"Each file starts with -- looms-migration: <id>. The statements use IF NOT EXISTS, and Looms does not drop indexes you add yourself. Columns you add on looms_run_index are left alone.
Columns for your run attributes#
Every run's attributes are stored as JSON on looms_run_index. Looms has no built-in attribute columns. Declare the attributes you filter, secure, or purge on with defineRunAttributes, and pass the same object to the host, the client, and the replica as additionalFields.
// looms.attributes.tsimport { defineRunAttributes } from '@swirls/looms'export const attributes = defineRunAttributes({ tenantId: { required: true, index: true }, project: { index: true }, region: { fieldName: 'home_region' },})const looms = createLooms({ modules, attributes })await looms.start(billing, input, { attributes: { tenantId: 'acme' } })const replica = postgresReplica({ url, migrate: 'auto', additionalFields: attributes })Each attribute becomes a text column named in snake_case (tenantId is tenant_id) unless you set fieldName. index: true adds looms_run_index_tenant_id. A required attribute must be on every start: leaving it out is a type error, and the host refuses it at runtime with InvalidRunAttributesError (400 on POST /runs). Undeclared keys are refused the same way. Launched runs and forks inherit their parent's attributes.
Each column and each index is its own migration, such as column_tenant_id and index_tenant_id. Adding a column fills it in from the attributes JSON of runs already copied. Pass the module to the CLI with --config so the generated SQL matches; it reads an attributes or default export.
looms replica generate --out ./migrations --config ./looms.attributes.tslooms replica migrate --database "$DATABASE_URL" --config ./looms.attributes.tsQuery with Drizzle#
drizzle-orm is optional. Import the tables from @swirls/looms/replica/drizzle. additionalFields adds your attribute columns under their attribute keys, so loomsRunIndex.tenantId is the tenant_id column. Pass runIndex for columns your application owns. Those columns are not part of the Looms migration.
import { jsonb, text, timestamp } from 'drizzle-orm/pg-core'import { loomsReplicaTables } from '@swirls/looms/replica/drizzle'import { attributes } from './looms.attributes'export const { loomsRunIndex, loomsRunEvents } = loomsReplicaTables({ additionalFields: attributes, runIndex: { input: jsonb('input'), error: text('error'), expiredAt: timestamp('expired_at', { withTimezone: true }), },})What freshness means#
status(runId) reports replicatedSeq, whether the run has finished, complete, and purgedAt. A run is complete when it has finished and every event through that finish has been copied. eventStore().tail returns the same sequence. If the delivery cursor is ahead of that copy, delivery rewinds once and reads the missing events before projecting. A batch that would still skip ahead is refused, so there is no silent gap. That covers a replica attached to a run already in flight, and a database restored from backup.
const store = replica.eventStore()const events = await store.read(runId)const state = await replica.loadRun(runId, registry)const freshness = await replica.status(runId)loadRun folds the copied events with the same registry the runtime used. Existing folds and replay run against eventStore() unchanged. The store is read-only.
Retention#
purge deletes events for finished runs older than a cutoff and sets purged_at. The summary row stays unless you pass keepIndex: false. Later deliveries for a purged run are skipped, and bounds reports the log as empty. You can also delete rows yourself.
await replica.purge({ finishedBefore: Date.now() - 30 * 24 * 60 * 60 * 1000,})where limits a purge to runs whose attribute columns match. It accepts only declared attributes, so a typo is a type error rather than a purge of everything. Index the attributes you purge on.
await replica.purge({ finishedBefore: Date.now() - 7 * 24 * 60 * 60 * 1000, where: { tenantId: 'acme' },})Rebuilding history#
rebuild(source) copies each run from an event store into Postgres. Purged runs are left alone. A projector cursor that has moved past the copy is rewound once to position(runId), which is replicated_seq. A purged run returns null, so delivery does not rewind it. Runs that finished before the replica was attached are not listed by an actor host; backfilling those needs a list of run ids from your application.
Projections that are not a full copy still use the projector path. The replica is the copy.