@swirls/looms 0.6.1 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/dist/actor/cell.d.ts +1 -1
  3. package/dist/actor/routing.d.ts +5 -1
  4. package/dist/actor/routing.js +14 -3
  5. package/dist/agent/effects.d.ts +20 -2
  6. package/dist/agent/effects.js +2 -0
  7. package/dist/agent/module.d.ts +40 -4
  8. package/dist/approval/effects.d.ts +10 -1
  9. package/dist/approval/effects.js +1 -0
  10. package/dist/approval/module.d.ts +20 -2
  11. package/dist/cli/commands.js +65 -1
  12. package/dist/client/client.d.ts +38 -10
  13. package/dist/client/client.js +2 -1
  14. package/dist/cloudflare/durable-object.d.ts +1 -1
  15. package/dist/cloudflare/index.d.ts +1 -1
  16. package/dist/cloudflare/index.js +1 -1
  17. package/dist/cloudflare/queue-consumer.d.ts +17 -10
  18. package/dist/cloudflare/queue-consumer.js +63 -27
  19. package/dist/cloudflare/queue-message.d.ts +4 -1
  20. package/dist/cloudflare/queue-message.js +4 -1
  21. package/dist/cloudflare/queue-worker.d.ts +7 -3
  22. package/dist/cloudflare/queue-worker.js +7 -2
  23. package/dist/cloudflare/queues.d.ts +1 -1
  24. package/dist/cloudflare/queues.js +1 -1
  25. package/dist/core/compose.d.ts +2 -1
  26. package/dist/core/compose.js +5 -0
  27. package/dist/core/effects.d.ts +84 -39
  28. package/dist/core/effects.js +29 -8
  29. package/dist/core/fold.js +34 -0
  30. package/dist/core/module-scope.d.ts +22 -8
  31. package/dist/core/module-scope.js +3 -0
  32. package/dist/core/module.d.ts +40 -9
  33. package/dist/core/module.js +25 -6
  34. package/dist/core/protocol.d.ts +12 -1
  35. package/dist/core/protocol.js +12 -0
  36. package/dist/core/published.d.ts +52 -0
  37. package/dist/core/published.js +45 -0
  38. package/dist/core/replay.d.ts +4 -2
  39. package/dist/core/state.d.ts +8 -2
  40. package/dist/core/state.js +2 -0
  41. package/dist/debugger/app/assets/{index-CUO1xyYW.js → index-CMRl_aWQ.js} +2 -2
  42. package/dist/debugger/app/assets/routes-CfXxKG45.js +47 -0
  43. package/dist/debugger/app/index.html +1 -1
  44. package/dist/debugger/events/protocol-summarize.js +2 -0
  45. package/dist/evaluator/effects.d.ts +10 -1
  46. package/dist/evaluator/effects.js +1 -0
  47. package/dist/evaluator/module.d.ts +20 -2
  48. package/dist/projectors/delivery.d.ts +8 -3
  49. package/dist/projectors/delivery.js +29 -2
  50. package/dist/projectors/event-log.d.ts +8 -2
  51. package/dist/projectors/event-log.js +47 -61
  52. package/dist/projectors/index.d.ts +1 -0
  53. package/dist/projectors/index.js +1 -0
  54. package/dist/projectors/postgres.d.ts +4 -1
  55. package/dist/projectors/postgres.js +6 -4
  56. package/dist/projectors/projector.d.ts +16 -0
  57. package/dist/projectors/projector.js +3 -0
  58. package/dist/projectors/replica/drizzle.d.ts +1192 -0
  59. package/dist/projectors/replica/drizzle.js +119 -0
  60. package/dist/projectors/replica/migrations.d.ts +35 -0
  61. package/dist/projectors/replica/migrations.js +230 -0
  62. package/dist/projectors/replica/postgres.d.ts +57 -0
  63. package/dist/projectors/replica/postgres.js +356 -0
  64. package/dist/projectors/schema.d.ts +2 -1
  65. package/dist/projectors/schema.js +2 -31
  66. package/dist/projectors/sqlite-delivery.js +9 -0
  67. package/dist/runtime/cancellation.js +1 -1
  68. package/dist/runtime/dispatch-effect.d.ts +2 -2
  69. package/dist/runtime/dispatch-effect.js +12 -4
  70. package/dist/runtime/effect-admission.d.ts +45 -0
  71. package/dist/runtime/effect-admission.js +70 -0
  72. package/dist/runtime/helpers.d.ts +6 -1
  73. package/dist/runtime/helpers.js +14 -5
  74. package/dist/runtime/index.d.ts +1 -0
  75. package/dist/runtime/index.js +1 -0
  76. package/dist/runtime/local-effect-executor.js +25 -3
  77. package/dist/runtime/retry-policy.js +6 -1
  78. package/dist/runtime/runtime.js +7 -2
  79. package/dist/runtime/server/routes/definitions.js +8 -1
  80. package/dist/runtime/types.d.ts +20 -5
  81. package/dist/runtime/wake-engine.js +20 -0
  82. package/dist/runtime/worker-callbacks.js +2 -2
  83. package/dist/runtime/worker-effect-dispatch.d.ts +35 -9
  84. package/dist/runtime/worker-effect-dispatch.js +105 -26
  85. package/dist/schedule/effects.d.ts +20 -2
  86. package/dist/schedule/effects.js +2 -0
  87. package/dist/schedule/module.d.ts +76 -40
  88. package/dist/testing/corpus-module.d.ts +2 -2
  89. package/dist/testing/corpus-module.js +27 -19
  90. package/dist/testing/index.js +12 -23
  91. package/dist/workflow/effects.d.ts +20 -2
  92. package/dist/workflow/effects.js +2 -0
  93. package/dist/workflow/module.d.ts +40 -4
  94. package/package.json +29 -1
  95. package/dist/debugger/app/assets/routes-lt_6J025.js +0 -47
@@ -0,0 +1,119 @@
1
+ import { sql } from 'drizzle-orm';
2
+ import { bigint, boolean, index, jsonb, pgTable, primaryKey, text, timestamp, } from 'drizzle-orm/pg-core';
3
+ /** Column builders for `looms_run_index`. Call again for each table; do not reuse the result. */
4
+ export function loomsRunIndexColumns() {
5
+ return {
6
+ runId: text('run_id').primaryKey(),
7
+ status: text('status').notNull(),
8
+ kind: text('kind'),
9
+ definitionName: text('definition_name'),
10
+ definitionVersion: text('definition_version'),
11
+ rootThreadId: text('root_thread_id'),
12
+ parentRunId: text('parent_run_id'),
13
+ launchedByEffectId: text('launched_by_effect_id'),
14
+ correlationId: text('correlation_id'),
15
+ attributes: jsonb('attributes')
16
+ .$type()
17
+ .notNull()
18
+ .default(sql `'{}'::jsonb`),
19
+ tenant: text('tenant'),
20
+ project: text('project'),
21
+ org: text('org'),
22
+ startedAt: timestamp('started_at', { withTimezone: true }),
23
+ updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
24
+ completedAt: timestamp('completed_at', { withTimezone: true }),
25
+ replicatedSeq: bigint('replicated_seq', { mode: 'number' }).notNull().default(0),
26
+ purgedAt: timestamp('purged_at', { withTimezone: true }),
27
+ };
28
+ }
29
+ /** Column builders for `looms_run_events`. */
30
+ export function loomsRunEventsColumns() {
31
+ return {
32
+ runId: text('run_id').notNull(),
33
+ seq: bigint('seq', { mode: 'number' }).notNull(),
34
+ eventId: text('event_id').notNull(),
35
+ ts: timestamp('ts', { withTimezone: true }).notNull(),
36
+ type: text('type').notNull(),
37
+ payload: jsonb('payload').notNull(),
38
+ threadId: text('thread_id'),
39
+ parentThreadId: text('parent_thread_id'),
40
+ causationId: text('causation_id'),
41
+ correlationId: text('correlation_id'),
42
+ effectId: text('effect_id'),
43
+ origin: jsonb('origin').notNull(),
44
+ idempotencyKey: text('idempotency_key'),
45
+ ephemeral: boolean('ephemeral').notNull().default(false),
46
+ };
47
+ }
48
+ /** Column builders for `looms_run_actors`. */
49
+ export function loomsRunActorsColumns() {
50
+ return {
51
+ runId: text('run_id').notNull(),
52
+ actorId: text('actor_id').notNull(),
53
+ kind: text('kind'),
54
+ status: text('status'),
55
+ definitionName: text('definition_name'),
56
+ parentActorId: text('parent_actor_id'),
57
+ launchedByRunId: text('launched_by_run_id'),
58
+ launchedByEffectId: text('launched_by_effect_id'),
59
+ correlationId: text('correlation_id'),
60
+ updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
61
+ };
62
+ }
63
+ /** Column builders for `looms_run_reviews`. */
64
+ export function loomsRunReviewsColumns() {
65
+ return {
66
+ runId: text('run_id').notNull(),
67
+ reviewId: text('review_id').notNull(),
68
+ status: text('status').notNull(),
69
+ title: text('title').notNull(),
70
+ updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
71
+ };
72
+ }
73
+ export const loomsSchemaMigrations = pgTable('looms_schema_migrations', {
74
+ id: text('id').primaryKey(),
75
+ appliedAt: timestamp('applied_at', { withTimezone: true }).notNull().defaultNow(),
76
+ });
77
+ /**
78
+ * Drizzle tables for the replica. Pass `runIndex` to add columns the host owns
79
+ * (`input`, `error`, and so on). Those columns are not in Looms migrations.
80
+ */
81
+ export function loomsReplicaTables(options) {
82
+ const columns = {
83
+ ...loomsRunIndexColumns(),
84
+ ...options?.runIndex,
85
+ };
86
+ const loomsRunIndex = pgTable('looms_run_index', columns, (table) => [
87
+ index('looms_run_index_tenant').on(table.tenant),
88
+ index('looms_run_index_project').on(table.project),
89
+ index('looms_run_index_org').on(table.org),
90
+ index('looms_run_index_parent').on(table.parentRunId),
91
+ index('looms_run_index_status').on(table.status),
92
+ ]);
93
+ // SAFETY: BuildColumns maps the same builder object, including host columns, to Postgres columns.
94
+ const runIndex = loomsRunIndex;
95
+ const loomsRunEvents = pgTable('looms_run_events', loomsRunEventsColumns(), (table) => [
96
+ primaryKey({ columns: [table.runId, table.seq] }),
97
+ index('looms_run_events_type_ts').on(table.type, table.ts),
98
+ ]);
99
+ const loomsRunActors = pgTable('looms_run_actors', loomsRunActorsColumns(), (table) => [
100
+ primaryKey({ columns: [table.runId, table.actorId] }),
101
+ index('looms_run_actors_launched_by').on(table.launchedByRunId),
102
+ index('looms_run_actors_correlation').on(table.correlationId),
103
+ ]);
104
+ const loomsRunReviews = pgTable('looms_run_reviews', loomsRunReviewsColumns(), (table) => [
105
+ primaryKey({ columns: [table.runId, table.reviewId] }),
106
+ ]);
107
+ return {
108
+ loomsRunIndex: runIndex,
109
+ loomsRunEvents,
110
+ loomsRunActors,
111
+ loomsRunReviews,
112
+ loomsSchemaMigrations,
113
+ };
114
+ }
115
+ const defaultTables = loomsReplicaTables();
116
+ export const loomsRunIndex = defaultTables.loomsRunIndex;
117
+ export const loomsRunEvents = defaultTables.loomsRunEvents;
118
+ export const loomsRunActors = defaultTables.loomsRunActors;
119
+ export const loomsRunReviews = defaultTables.loomsRunReviews;
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Actors and reviews. Same statements the Postgres index projector has always
3
+ * applied, so a database created by an older Looms keeps working.
4
+ */
5
+ export declare const POSTGRES_SCHEMA_SQL: string;
6
+ /**
7
+ * The event copy and the run summary. `CREATE TABLE IF NOT EXISTS` does not add
8
+ * columns to a table that already exists, so each new column is also an
9
+ * `ADD COLUMN IF NOT EXISTS`.
10
+ */
11
+ export declare const POSTGRES_EVENT_LOG_SCHEMA_SQL: string;
12
+ export interface ReplicaMigration {
13
+ readonly id: string;
14
+ readonly sql: string;
15
+ }
16
+ /** Versioned DDL for the Postgres replica. Looms only creates and alters `looms_*` objects. */
17
+ export declare const POSTGRES_REPLICA_MIGRATIONS: readonly ReplicaMigration[];
18
+ export interface GenerateReplicaMigrationsOptions {
19
+ /** Directory of SQL migrations the host already applies. */
20
+ readonly out: string;
21
+ /** Append a Drizzle `_journal.json` entry for each file written. */
22
+ readonly journal?: 'drizzle';
23
+ /** Report pending migrations and write nothing. */
24
+ readonly check?: boolean;
25
+ }
26
+ export interface GenerateReplicaMigrationsResult {
27
+ readonly written: readonly string[];
28
+ readonly pending: readonly string[];
29
+ }
30
+ /**
31
+ * Writes each migration the host does not already have.
32
+ * A file counts as applied when it contains `-- looms-migration: <id>`.
33
+ * The numeric prefix continues after the highest `NNNN_` file already in `out`.
34
+ */
35
+ export declare function generateReplicaMigrations(options: GenerateReplicaMigrationsOptions): Promise<GenerateReplicaMigrationsResult>;
@@ -0,0 +1,230 @@
1
+ import { readdir, readFile, writeFile, mkdir } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ import { Predicate } from 'effect';
4
+ /**
5
+ * Actors and reviews. Same statements the Postgres index projector has always
6
+ * applied, so a database created by an older Looms keeps working.
7
+ */
8
+ export const POSTGRES_SCHEMA_SQL = `
9
+ CREATE TABLE IF NOT EXISTS looms_run_actors (
10
+ run_id TEXT NOT NULL,
11
+ actor_id TEXT NOT NULL,
12
+ kind TEXT,
13
+ status TEXT,
14
+ definition_name TEXT,
15
+ parent_actor_id TEXT,
16
+ launched_by_run_id TEXT,
17
+ launched_by_effect_id TEXT,
18
+ correlation_id TEXT,
19
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
20
+ PRIMARY KEY (run_id, actor_id)
21
+ );
22
+
23
+ ALTER TABLE looms_run_actors ADD COLUMN IF NOT EXISTS launched_by_run_id TEXT;
24
+ ALTER TABLE looms_run_actors ADD COLUMN IF NOT EXISTS launched_by_effect_id TEXT;
25
+ ALTER TABLE looms_run_actors ADD COLUMN IF NOT EXISTS correlation_id TEXT;
26
+
27
+ CREATE INDEX IF NOT EXISTS looms_run_actors_launched_by ON looms_run_actors (launched_by_run_id);
28
+ CREATE INDEX IF NOT EXISTS looms_run_actors_correlation ON looms_run_actors (correlation_id);
29
+
30
+ CREATE TABLE IF NOT EXISTS looms_run_reviews (
31
+ run_id TEXT NOT NULL,
32
+ review_id TEXT NOT NULL,
33
+ status TEXT NOT NULL,
34
+ title TEXT NOT NULL,
35
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
36
+ PRIMARY KEY (run_id, review_id)
37
+ );
38
+ `.trim();
39
+ /**
40
+ * The event copy and the run summary. `CREATE TABLE IF NOT EXISTS` does not add
41
+ * columns to a table that already exists, so each new column is also an
42
+ * `ADD COLUMN IF NOT EXISTS`.
43
+ */
44
+ export const POSTGRES_EVENT_LOG_SCHEMA_SQL = `
45
+ CREATE TABLE IF NOT EXISTS looms_run_events (
46
+ run_id TEXT NOT NULL,
47
+ seq BIGINT NOT NULL,
48
+ event_id TEXT NOT NULL,
49
+ ts TIMESTAMPTZ NOT NULL,
50
+ type TEXT NOT NULL,
51
+ payload JSONB NOT NULL,
52
+ thread_id TEXT,
53
+ parent_thread_id TEXT,
54
+ causation_id TEXT,
55
+ correlation_id TEXT,
56
+ effect_id TEXT,
57
+ origin JSONB NOT NULL,
58
+ idempotency_key TEXT,
59
+ ephemeral BOOLEAN NOT NULL DEFAULT FALSE,
60
+ PRIMARY KEY (run_id, seq)
61
+ );
62
+
63
+ ALTER TABLE looms_run_events ADD COLUMN IF NOT EXISTS ephemeral BOOLEAN NOT NULL DEFAULT FALSE;
64
+
65
+ CREATE INDEX IF NOT EXISTS looms_run_events_type_ts ON looms_run_events (type, ts);
66
+
67
+ CREATE TABLE IF NOT EXISTS looms_run_index (
68
+ run_id TEXT PRIMARY KEY,
69
+ status TEXT NOT NULL,
70
+ kind TEXT,
71
+ definition_name TEXT,
72
+ definition_version TEXT,
73
+ root_thread_id TEXT,
74
+ parent_run_id TEXT,
75
+ launched_by_effect_id TEXT,
76
+ correlation_id TEXT,
77
+ attributes JSONB NOT NULL DEFAULT '{}'::jsonb,
78
+ tenant TEXT,
79
+ project TEXT,
80
+ org TEXT,
81
+ started_at TIMESTAMPTZ,
82
+ updated_at TIMESTAMPTZ NOT NULL,
83
+ completed_at TIMESTAMPTZ,
84
+ replicated_seq BIGINT NOT NULL DEFAULT 0,
85
+ purged_at TIMESTAMPTZ
86
+ );
87
+
88
+ ALTER TABLE looms_run_index ADD COLUMN IF NOT EXISTS replicated_seq BIGINT NOT NULL DEFAULT 0;
89
+ ALTER TABLE looms_run_index ADD COLUMN IF NOT EXISTS purged_at TIMESTAMPTZ;
90
+
91
+ CREATE INDEX IF NOT EXISTS looms_run_index_tenant ON looms_run_index (tenant);
92
+ CREATE INDEX IF NOT EXISTS looms_run_index_project ON looms_run_index (project);
93
+ CREATE INDEX IF NOT EXISTS looms_run_index_org ON looms_run_index (org);
94
+ CREATE INDEX IF NOT EXISTS looms_run_index_parent ON looms_run_index (parent_run_id);
95
+ CREATE INDEX IF NOT EXISTS looms_run_index_status ON looms_run_index (status);
96
+ `.trim();
97
+ const POSTGRES_REPLICA_BOOKKEEPING_SQL = `
98
+ CREATE TABLE IF NOT EXISTS looms_schema_migrations (
99
+ id TEXT PRIMARY KEY,
100
+ applied_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
101
+ );
102
+ `.trim();
103
+ function replicaMigration(id, statements) {
104
+ return {
105
+ id,
106
+ sql: [
107
+ ...statements,
108
+ `INSERT INTO looms_schema_migrations (id) VALUES ('${id}') ON CONFLICT (id) DO NOTHING;`,
109
+ ].join('\n\n'),
110
+ };
111
+ }
112
+ /** Versioned DDL for the Postgres replica. Looms only creates and alters `looms_*` objects. */
113
+ export const POSTGRES_REPLICA_MIGRATIONS = [
114
+ replicaMigration('0001_replica', [
115
+ POSTGRES_SCHEMA_SQL,
116
+ POSTGRES_EVENT_LOG_SCHEMA_SQL,
117
+ POSTGRES_REPLICA_BOOKKEEPING_SQL,
118
+ ]),
119
+ ];
120
+ const MIGRATION_HEADER = /^-- looms-migration:\s+(\S+)/m;
121
+ async function recordedMigrationIds(directory) {
122
+ let names;
123
+ try {
124
+ names = await readdir(directory);
125
+ }
126
+ catch (cause) {
127
+ if (cause instanceof Error && 'code' in cause && cause.code === 'ENOENT') {
128
+ return new Set();
129
+ }
130
+ throw cause;
131
+ }
132
+ const ids = new Set();
133
+ for (const name of names) {
134
+ if (!name.endsWith('.sql')) {
135
+ continue;
136
+ }
137
+ const header = MIGRATION_HEADER.exec(await readFile(join(directory, name), 'utf8'));
138
+ if (header?.[1]) {
139
+ ids.add(header[1]);
140
+ }
141
+ }
142
+ return ids;
143
+ }
144
+ function nextMigrationNumber(names) {
145
+ let max = -1;
146
+ for (const name of names) {
147
+ const match = /^(\d{4})_/.exec(name);
148
+ if (match?.[1]) {
149
+ max = Math.max(max, Number(match[1]));
150
+ }
151
+ }
152
+ return max + 1;
153
+ }
154
+ function isDrizzleJournal(value) {
155
+ if (!Predicate.isObject(value)) {
156
+ return false;
157
+ }
158
+ if (!('entries' in value) || !Array.isArray(value.entries)) {
159
+ return false;
160
+ }
161
+ if (!('version' in value) || value.version !== '7') {
162
+ return false;
163
+ }
164
+ return 'dialect' in value && value.dialect === 'postgresql';
165
+ }
166
+ async function appendDrizzleJournal(directory, tags) {
167
+ if (tags.length === 0) {
168
+ return;
169
+ }
170
+ const journalPath = join(directory, 'meta', '_journal.json');
171
+ let journal;
172
+ try {
173
+ const parsed = JSON.parse(await readFile(journalPath, 'utf8'));
174
+ if (!isDrizzleJournal(parsed)) {
175
+ throw new Error(`Drizzle journal at ${journalPath} is not the expected shape`);
176
+ }
177
+ journal = parsed;
178
+ }
179
+ catch (cause) {
180
+ if (!(cause instanceof Error) || !('code' in cause) || cause.code !== 'ENOENT') {
181
+ throw cause;
182
+ }
183
+ journal = { version: '7', dialect: 'postgresql', entries: [] };
184
+ }
185
+ const when = Date.now();
186
+ for (const tag of tags) {
187
+ journal.entries.push({
188
+ idx: journal.entries.length,
189
+ version: '7',
190
+ when,
191
+ tag,
192
+ breakpoints: true,
193
+ });
194
+ }
195
+ await mkdir(join(directory, 'meta'), { recursive: true });
196
+ await writeFile(journalPath, `${JSON.stringify(journal, null, 2)}\n`);
197
+ }
198
+ /**
199
+ * Writes each migration the host does not already have.
200
+ * A file counts as applied when it contains `-- looms-migration: <id>`.
201
+ * The numeric prefix continues after the highest `NNNN_` file already in `out`.
202
+ */
203
+ export async function generateReplicaMigrations(options) {
204
+ const recorded = await recordedMigrationIds(options.out);
205
+ const pending = POSTGRES_REPLICA_MIGRATIONS.filter((migration) => !recorded.has(migration.id));
206
+ if (options.check || pending.length === 0) {
207
+ return { written: [], pending: pending.map((migration) => migration.id) };
208
+ }
209
+ await mkdir(options.out, { recursive: true });
210
+ let names;
211
+ try {
212
+ names = await readdir(options.out);
213
+ }
214
+ catch {
215
+ names = [];
216
+ }
217
+ let number = nextMigrationNumber(names);
218
+ const written = [];
219
+ for (const migration of pending) {
220
+ const tag = `${String(number).padStart(4, '0')}_looms_${migration.id}`;
221
+ const filename = `${tag}.sql`;
222
+ await writeFile(join(options.out, filename), `-- looms-migration: ${migration.id}\n\n${migration.sql.trim()}\n`);
223
+ written.push(filename);
224
+ number += 1;
225
+ }
226
+ if (options.journal === 'drizzle') {
227
+ await appendDrizzleJournal(options.out, written.map((filename) => filename.replace(/\.sql$/, '')));
228
+ }
229
+ return { written, pending: pending.map((migration) => migration.id) };
230
+ }
@@ -0,0 +1,57 @@
1
+ import { type Sql } from 'postgres';
2
+ import { type EventStore, type FoldRegistry, type RunState } from '@swirls/looms/core';
3
+ import { ReplicaGapError, type Projector } from '../projector';
4
+ export interface ReplicaStatus {
5
+ /** Highest sequence copied with no hole in front of it. */
6
+ readonly replicatedSeq: number;
7
+ /** The run summary says the run has finished. */
8
+ readonly finished: boolean;
9
+ /** Finished, and every event through that finish has been copied. */
10
+ readonly complete: boolean;
11
+ /** Set once retention has deleted the event copy. */
12
+ readonly purgedAt: number | null;
13
+ }
14
+ export interface ReplicaPurgeOptions {
15
+ /** Delete event copies for runs that finished before this epoch millisecond. */
16
+ readonly finishedBefore: number;
17
+ /** Keep the run summary row. Defaults to true. */
18
+ readonly keepIndex?: boolean;
19
+ }
20
+ export interface ReplicaPurgeResult {
21
+ readonly runs: number;
22
+ }
23
+ export type PostgresReplicaMigrate = 'auto' | 'verify';
24
+ export type PostgresReplicaOptions = ({
25
+ readonly url: string;
26
+ } | {
27
+ readonly sql: Sql;
28
+ }) & {
29
+ /**
30
+ * `auto` applies pending migrations on init.
31
+ * `verify` refuses to start when a migration has not been applied, and names
32
+ * `looms replica generate` so the host can commit the SQL.
33
+ */
34
+ readonly migrate: PostgresReplicaMigrate;
35
+ };
36
+ /**
37
+ * A complete, gap-checked copy of every run, plus the run summary folded in the same transaction.
38
+ * Reading an event back returns the envelope the source returned.
39
+ */
40
+ export interface PostgresReplica extends Projector {
41
+ readonly position: (runId: string) => Promise<number | null>;
42
+ /** Apply pending migrations. `init` does this only when `migrate` is `auto`. */
43
+ readonly migrate: () => Promise<void>;
44
+ readonly pendingMigrations: () => Promise<readonly string[]>;
45
+ /** Read-only view of the event copy. Folds and replay run against it unchanged. */
46
+ readonly eventStore: () => EventStore;
47
+ /** Fold the copied events with the same registry the runtime used. */
48
+ readonly loadRun: (runId: string, registry: FoldRegistry) => Promise<RunState>;
49
+ /** How far the copy has got, and whether it is safe to treat as complete. */
50
+ readonly status: (runId: string) => Promise<ReplicaStatus | null>;
51
+ /** Delete event copies for finished runs. Later deliveries for those runs are skipped. */
52
+ readonly purge: (options: ReplicaPurgeOptions) => Promise<ReplicaPurgeResult>;
53
+ /** Copy every run in `source`. Purged runs are left alone. */
54
+ readonly rebuild: (source: EventStore) => Promise<number>;
55
+ }
56
+ export declare function postgresReplica(options: PostgresReplicaOptions): PostgresReplica;
57
+ export { ReplicaGapError };