@swirls/looms 0.7.0 → 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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,13 @@
1
1
  # @swirls/looms
2
2
 
3
+ ## 0.8.0
4
+
5
+ ### Minor Changes
6
+
7
+ - ef94314: A Postgres replica copies every run into a database you own. `postgresReplica` stores the full event envelope, folds the run summary in the same transaction, and records `replicated_seq` only through a contiguous prefix, so a restored database or a replica attached mid-run catches up instead of leaving a hole. `status` reports whether that copy is complete. `purge` deletes event copies for finished runs and later deliveries skip them.
8
+
9
+ `looms replica generate` writes the versioned SQL into your migration folder (and a Drizzle journal, when you ask). `looms replica migrate` applies it. `@swirls/looms/replica/drizzle` exports the tables, and `loomsReplicaTables` adds columns your application owns.
10
+
3
11
  ## 0.7.0
4
12
 
5
13
  ### Minor Changes
@@ -5,6 +5,8 @@ import { steer as steerEvent } from '@swirls/looms/agent';
5
5
  import { decision } from '@swirls/looms/approval';
6
6
  import { createLoomsClient } from '@swirls/looms/client';
7
7
  import { stringifyJson, stringifyJsonPretty } from '@swirls/looms/core';
8
+ import { postgresReplica } from '@swirls/looms/projectors/replica';
9
+ import { generateReplicaMigrations } from '@swirls/looms/projectors/replica/migrations';
8
10
  import { createLooms } from '@swirls/looms/runtime';
9
11
  const VERSION = '0.0.1';
10
12
  const urlFlag = Flag.string('url').pipe(Flag.withDescription('Looms host base URL (env LOOMS_URL)'), Flag.withFallbackConfig(Config.string('LOOMS_URL')), Flag.withDefault('http://127.0.0.1:8787'), Flag.map((url) => url.replace(/\/$/, '')));
@@ -116,7 +118,69 @@ const tail = Command.make('tail', {
116
118
  yield* Stream.fromQueue(queue).pipe(Stream.runForEach((line) => Console.log(line)));
117
119
  }));
118
120
  })).pipe(Command.withDescription('Stream events for a run'), Command.withShortDescription('Tail run events'));
119
- export const looms = loomsBase.pipe(Command.withSubcommands([serve, start, events, state, approve, replay, signal, steer, tail]));
121
+ const databaseFlag = Flag.string('database').pipe(Flag.withDescription('Postgres connection string for the replica (env DATABASE_URL)'), Flag.withFallbackConfig(Config.string('DATABASE_URL')));
122
+ const generate = Command.make('generate', {
123
+ out: Flag.string('out').pipe(Flag.withDescription('Directory of SQL migrations to write into')),
124
+ journal: Flag.optional(Flag.string('journal').pipe(Flag.withDescription('Also update a migration journal. Only `drizzle` is supported'))),
125
+ check: Flag.boolean('check').pipe(Flag.withDescription('Exit non-zero when a migration is pending, and write nothing'), Flag.withDefault(false)),
126
+ }, Effect.fn('replica.generate')(function* ({ out, journal, check }) {
127
+ if (Option.isSome(journal) && journal.value !== 'drizzle') {
128
+ return yield* new CliError.UserError({
129
+ cause: journal.value,
130
+ userMessage: `Unknown journal "${journal.value}". Only "drizzle" is supported.`,
131
+ });
132
+ }
133
+ const generateOptions = Option.isSome(journal)
134
+ ? { out, check, journal: 'drizzle' }
135
+ : { out, check };
136
+ const result = yield* tryClient(() => generateReplicaMigrations(generateOptions));
137
+ if (check && result.pending.length > 0) {
138
+ return yield* new CliError.UserError({
139
+ cause: result.pending,
140
+ userMessage: `Pending Looms replica migrations: ${result.pending.join(', ')}`,
141
+ });
142
+ }
143
+ if (result.written.length === 0) {
144
+ return yield* Console.log('Looms replica migrations are up to date');
145
+ }
146
+ for (const filename of result.written) {
147
+ yield* Console.log(filename);
148
+ }
149
+ return yield* Effect.void;
150
+ })).pipe(Command.withDescription('Write replica migrations the host does not already have'), Command.withShortDescription('Write replica SQL'));
151
+ const migrate = Command.make('migrate', { database: databaseFlag }, Effect.fn('replica.migrate')(function* ({ database }) {
152
+ const replica = postgresReplica({ url: database, migrate: 'auto' });
153
+ yield* tryClient(() => replica.migrate().then(() => replica.dispose?.()));
154
+ yield* Console.log('Looms replica migrations applied');
155
+ })).pipe(Command.withDescription('Apply pending replica migrations'), Command.withShortDescription('Apply replica SQL'));
156
+ const status = Command.make('status', {
157
+ database: databaseFlag,
158
+ run: Flag.optional(Flag.string('run').pipe(Flag.withDescription('Also print freshness for this run id'))),
159
+ }, Effect.fn('replica.status')(function* ({ database, run }) {
160
+ const replica = postgresReplica({ url: database, migrate: 'verify' });
161
+ const pending = yield* tryClient(() => replica.pendingMigrations());
162
+ yield* Console.log(pending.length === 0
163
+ ? 'Looms replica schema is up to date'
164
+ : `Pending Looms replica migrations: ${pending.join(', ')}`);
165
+ if (Option.isSome(run)) {
166
+ const row = yield* tryClient(() => replica.status(run.value));
167
+ yield* Console.log(row ? stringifyJson(row) : `No replica row for ${run.value}`);
168
+ }
169
+ yield* tryClient(() => replica.dispose?.() ?? Promise.resolve());
170
+ })).pipe(Command.withDescription('Show which replica migrations are applied'), Command.withShortDescription('Replica schema status'));
171
+ const replica = Command.make('replica').pipe(Command.withDescription('Copy runs into a Postgres database you own'), Command.withShortDescription('Postgres replica'), Command.withSubcommands([generate, migrate, status]));
172
+ export const looms = loomsBase.pipe(Command.withSubcommands([
173
+ serve,
174
+ start,
175
+ events,
176
+ state,
177
+ approve,
178
+ replay,
179
+ signal,
180
+ steer,
181
+ tail,
182
+ replica,
183
+ ]));
120
184
  export const cliTestLayer = Layer.mergeAll(FileSystem.layerNoop({}), Path.layer, Stdio.layerTest({}), Layer.succeed(Terminal.Terminal, Terminal.make({
121
185
  columns: Effect.succeed(80),
122
186
  rows: Effect.succeed(24),
@@ -1,4 +1,4 @@
1
- import { Effect } from 'effect';
1
+ import { Cause, Effect } from 'effect';
2
2
  import type { EventStore, EventStoreError } from '@swirls/looms/core';
3
3
  import { type Projector } from './projector';
4
4
  export type ProjectorDeliveryState = 'idle' | 'retrying' | 'dead-letter';
@@ -14,7 +14,7 @@ export interface ProjectorDeliveryStatus {
14
14
  readonly lastError: string | null;
15
15
  readonly updatedAt: number;
16
16
  }
17
- declare const ProjectorCursorError_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("effect/Cause").YieldableError & {
17
+ declare const ProjectorCursorError_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => Cause.YieldableError & {
18
18
  readonly _tag: "ProjectorCursorError";
19
19
  } & Readonly<A>;
20
20
  export declare class ProjectorCursorError extends ProjectorCursorError_base<{
@@ -24,6 +24,11 @@ export declare class ProjectorCursorError extends ProjectorCursorError_base<{
24
24
  export interface ProjectorCursorStore {
25
25
  get(runId: string, projector: Projector): Effect.Effect<ProjectorDeliveryStatus, ProjectorCursorError>;
26
26
  advance(runId: string, projector: Projector, cursor: number, now: number): Effect.Effect<void, ProjectorCursorError>;
27
+ /**
28
+ * Set the cursor to an earlier sequence. `advance` never moves backwards, so a
29
+ * projector whose copy is behind the saved cursor uses this to catch up.
30
+ */
31
+ rewind(runId: string, projector: Projector, cursor: number, now: number): Effect.Effect<void, ProjectorCursorError>;
27
32
  fail(runId: string, projector: Projector, failure: {
28
33
  readonly attempts: number;
29
34
  readonly failedSeq: number;
@@ -34,7 +39,7 @@ export interface ProjectorCursorStore {
34
39
  requeue(runId: string, projector: Projector, now: number): Effect.Effect<void, ProjectorCursorError>;
35
40
  list(runId?: string): Effect.Effect<readonly ProjectorDeliveryStatus[], ProjectorCursorError>;
36
41
  }
37
- declare const UnknownProjectorError_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("effect/Cause").YieldableError & {
42
+ declare const UnknownProjectorError_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => Cause.YieldableError & {
38
43
  readonly _tag: "UnknownProjectorError";
39
44
  } & Readonly<A>;
40
45
  export declare class UnknownProjectorError extends UnknownProjectorError_base<{
@@ -1,4 +1,4 @@
1
- import { Data, Effect, Semaphore } from 'effect';
1
+ import { Cause, Data, Effect, Semaphore } from 'effect';
2
2
  import { runProjectorEffect } from './projector.js';
3
3
  export class ProjectorCursorError extends Data.TaggedError('ProjectorCursorError') {
4
4
  }
@@ -10,10 +10,22 @@ function projectorIdentity(projector) {
10
10
  class ProjectorDeliveryError extends Data.TaggedError('ProjectorDeliveryError') {
11
11
  }
12
12
  function normalizeError(cause) {
13
+ const error = Cause.isCause(cause) ? Cause.squash(cause) : cause;
13
14
  return new ProjectorDeliveryError({
14
- message: cause instanceof Error ? cause.message : String(cause),
15
+ message: error instanceof Error ? error.message : String(error),
15
16
  });
16
17
  }
18
+ function idleStatus(status, cursor) {
19
+ return {
20
+ ...status,
21
+ cursor,
22
+ state: 'idle',
23
+ attempts: 0,
24
+ failedSeq: null,
25
+ nextRetryAt: null,
26
+ lastError: null,
27
+ };
28
+ }
17
29
  export function createProjectorDelivery(source, projectors, cursors, options = {}) {
18
30
  const batchSize = options.batchSize ?? 100;
19
31
  const initialRetryMs = options.initialRetryMs ?? 1_000;
@@ -86,6 +98,21 @@ export function createProjectorDelivery(source, projectors, cursors, options = {
86
98
  yield* recordFailure(runId, projector, status, status.cursor + 1, normalizeError(initialization.cause));
87
99
  return;
88
100
  }
101
+ const readPosition = projector.position;
102
+ if (readPosition) {
103
+ const aligned = yield* Effect.tryPromise({
104
+ try: () => readPosition(runId),
105
+ catch: normalizeError,
106
+ }).pipe(Effect.exit);
107
+ if (aligned._tag === 'Failure') {
108
+ yield* recordFailure(runId, projector, status, status.cursor + 1, normalizeError(aligned.cause));
109
+ return;
110
+ }
111
+ if (aligned.value !== null && aligned.value < status.cursor) {
112
+ yield* cursors.rewind(runId, projector, aligned.value, now());
113
+ status = idleStatus(status, aligned.value);
114
+ }
115
+ }
89
116
  while (true) {
90
117
  const events = yield* source.read(runId, {
91
118
  fromSeq: status.cursor + 1,
@@ -1,7 +1,8 @@
1
- import { type Sql } from 'postgres';
1
+ import { type Sql, type TransactionSql } from 'postgres';
2
2
  import { type EventEnvelope, type EventOrigin, type EventStore, type JsonValue, type RunStatus } from '@swirls/looms/core';
3
3
  import type { Projector } from './projector';
4
- export declare const POSTGRES_EVENT_LOG_SCHEMA_SQL: string;
4
+ import { POSTGRES_EVENT_LOG_SCHEMA_SQL } from './replica/migrations';
5
+ export { POSTGRES_EVENT_LOG_SCHEMA_SQL };
5
6
  export interface EventLogEntry {
6
7
  readonly runId: string;
7
8
  readonly seq: number;
@@ -85,3 +86,8 @@ export declare function postgresEventLog(options: {
85
86
  } | {
86
87
  sql: Sql;
87
88
  }): EventLogProjector;
89
+ export declare function applySqlOps(sql: TransactionSql, ops: readonly EventLogOp[]): Promise<void>;
90
+ /** Fold run-summary ops. Event rows are written by {@link insertRunEvents}. */
91
+ export declare function applyRunIndexOps(sql: TransactionSql, ops: readonly EventLogOp[]): Promise<void>;
92
+ /** Insert event envelopes, including ephemeral ones. Durable callers pass events that are already filtered. */
93
+ export declare function insertRunEvents(sql: TransactionSql, events: readonly EventEnvelope[]): Promise<void>;
@@ -2,50 +2,9 @@ import { DateTime, Effect, Option, Predicate, Schema } from 'effect';
2
2
  import createPostgresClient, {} from 'postgres';
3
3
  import { completedRunStatus, isJsonObject, readRunLaunchSource, } from '@swirls/looms/core';
4
4
  import { runProjectorPromise } from './projector.js';
5
+ import { POSTGRES_EVENT_LOG_SCHEMA_SQL } from './replica/migrations.js';
6
+ export { POSTGRES_EVENT_LOG_SCHEMA_SQL };
5
7
  const decodeAttributes = Schema.decodeUnknownOption(Schema.Record(Schema.String, Schema.String));
6
- export const POSTGRES_EVENT_LOG_SCHEMA_SQL = `
7
- CREATE TABLE IF NOT EXISTS looms_run_events (
8
- run_id TEXT NOT NULL,
9
- seq BIGINT NOT NULL,
10
- event_id TEXT NOT NULL,
11
- ts TIMESTAMPTZ NOT NULL,
12
- type TEXT NOT NULL,
13
- payload JSONB NOT NULL,
14
- thread_id TEXT,
15
- parent_thread_id TEXT,
16
- causation_id TEXT,
17
- correlation_id TEXT,
18
- effect_id TEXT,
19
- origin JSONB NOT NULL,
20
- idempotency_key TEXT,
21
- PRIMARY KEY (run_id, seq)
22
- );
23
-
24
- CREATE TABLE IF NOT EXISTS looms_run_index (
25
- run_id TEXT PRIMARY KEY,
26
- status TEXT NOT NULL,
27
- kind TEXT,
28
- definition_name TEXT,
29
- definition_version TEXT,
30
- root_thread_id TEXT,
31
- parent_run_id TEXT,
32
- launched_by_effect_id TEXT,
33
- correlation_id TEXT,
34
- attributes JSONB NOT NULL DEFAULT '{}'::jsonb,
35
- tenant TEXT,
36
- project TEXT,
37
- org TEXT,
38
- started_at TIMESTAMPTZ,
39
- updated_at TIMESTAMPTZ NOT NULL,
40
- completed_at TIMESTAMPTZ
41
- );
42
-
43
- CREATE INDEX IF NOT EXISTS looms_run_index_tenant ON looms_run_index (tenant);
44
- CREATE INDEX IF NOT EXISTS looms_run_index_project ON looms_run_index (project);
45
- CREATE INDEX IF NOT EXISTS looms_run_index_org ON looms_run_index (org);
46
- CREATE INDEX IF NOT EXISTS looms_run_index_parent ON looms_run_index (parent_run_id);
47
- CREATE INDEX IF NOT EXISTS looms_run_index_status ON looms_run_index (status);
48
- `.trim();
49
8
  const terminal = new Set(['completed', 'failed', 'cancelled']);
50
9
  export function eventLogOps(event) {
51
10
  if (event.ephemeral) {
@@ -297,15 +256,16 @@ function runIndexPatches(ops) {
297
256
  }
298
257
  return [...patches.values()];
299
258
  }
300
- function applySqlOps(sql, ops) {
301
- const entries = ops.flatMap((op) => (op.type === 'insert' ? [op.entry] : []));
259
+ export function applySqlOps(sql, ops) {
260
+ const events = ops.flatMap((op) => (op.type === 'insert' ? [envelopeFromEntry(op.entry)] : []));
261
+ return Promise.all([insertRunEvents(sql, events), applyRunIndexOps(sql, ops)]).then(() => undefined);
262
+ }
263
+ /** Fold run-summary ops. Event rows are written by {@link insertRunEvents}. */
264
+ export function applyRunIndexOps(sql, ops) {
302
265
  const patches = runIndexPatches(ops);
303
266
  const upserts = patches.filter((patch) => patch.start !== null || patch.finish !== null);
304
267
  const touches = patches.filter((patch) => patch.start === null && patch.finish === null);
305
268
  const statements = [];
306
- for (let index = 0; index < entries.length; index += INSERT_CHUNK_ROWS) {
307
- statements.push(insertEvents(sql, entries.slice(index, index + INSERT_CHUNK_ROWS)));
308
- }
309
269
  if (upserts.length > 0) {
310
270
  statements.push(upsertRuns(sql, upserts));
311
271
  }
@@ -314,21 +274,47 @@ function applySqlOps(sql, ops) {
314
274
  }
315
275
  return Promise.all(statements).then(() => undefined);
316
276
  }
317
- function insertEvents(sql, entries) {
318
- const rows = entries.map((entry) => ({
319
- run_id: entry.runId,
277
+ /** Insert event envelopes, including ephemeral ones. Durable callers pass events that are already filtered. */
278
+ export function insertRunEvents(sql, events) {
279
+ const statements = [];
280
+ for (let index = 0; index < events.length; index += INSERT_CHUNK_ROWS) {
281
+ statements.push(insertEventChunk(sql, events.slice(index, index + INSERT_CHUNK_ROWS)));
282
+ }
283
+ return Promise.all(statements).then(() => undefined);
284
+ }
285
+ function envelopeFromEntry(entry) {
286
+ return {
287
+ id: entry.eventId,
288
+ runId: entry.runId,
320
289
  seq: entry.seq,
321
- event_id: entry.eventId,
322
- ts: utcDate(entry.ts),
290
+ ts: entry.ts,
323
291
  type: entry.type,
324
- payload: sql.json(entry.payload),
325
- thread_id: entry.threadId,
326
- parent_thread_id: entry.parentThreadId,
327
- causation_id: entry.causationId,
328
- correlation_id: entry.correlationId,
329
- effect_id: entry.effectId,
330
- origin: sql.json(entry.origin),
331
- idempotency_key: entry.idempotencyKey,
292
+ payload: entry.payload,
293
+ threadId: entry.threadId,
294
+ parentThreadId: entry.parentThreadId,
295
+ causationId: entry.causationId,
296
+ correlationId: entry.correlationId,
297
+ effectId: entry.effectId,
298
+ origin: entry.origin,
299
+ idempotencyKey: entry.idempotencyKey,
300
+ };
301
+ }
302
+ function insertEventChunk(sql, events) {
303
+ const rows = events.map((event) => ({
304
+ run_id: event.runId,
305
+ seq: event.seq,
306
+ event_id: event.id,
307
+ ts: utcDate(event.ts),
308
+ type: event.type,
309
+ payload: sql.json(event.payload),
310
+ thread_id: event.threadId,
311
+ parent_thread_id: event.parentThreadId ?? null,
312
+ causation_id: event.causationId ?? null,
313
+ correlation_id: event.correlationId ?? null,
314
+ effect_id: event.effectId ?? null,
315
+ origin: sql.json(event.origin),
316
+ idempotency_key: event.idempotencyKey ?? null,
317
+ ephemeral: event.ephemeral === true,
332
318
  }));
333
319
  return sql `
334
320
  INSERT INTO looms_run_events ${sql(rows)}
@@ -1,4 +1,5 @@
1
1
  export type { Projector, ProjectorErrorHandler } from './projector';
2
+ export { ReplicaGapError } from './projector';
2
3
  export { createProjectorDelivery, ProjectorCursorError, UnknownProjectorError, type ProjectorCursorStore, type ProjectorDeliveryFailure, type ProjectorDelivery, type ProjectorDeliveryOptions, type ProjectorDeliveryState, type ProjectorDeliveryStatus, type ProjectorObservation, type ProjectorObserver, type ProjectorOperationalStatus, } from './delivery';
3
4
  export { sqliteProjectorCursorStore, SQLITE_PROJECTOR_DELIVERY_SCHEMA } from './sqlite-delivery';
4
5
  export { withProjectors, projectEvents, ProjectorsStoreLive, type WithProjectorsOptions, } from './with-projectors';
@@ -1,3 +1,4 @@
1
+ export { ReplicaGapError } from './projector.js';
1
2
  export { createProjectorDelivery, ProjectorCursorError, UnknownProjectorError, } from './delivery.js';
2
3
  export { sqliteProjectorCursorStore, SQLITE_PROJECTOR_DELIVERY_SCHEMA } from './sqlite-delivery.js';
3
4
  export { withProjectors, projectEvents, ProjectorsStoreLive, } from './with-projectors.js';
@@ -1,5 +1,5 @@
1
1
  import { type Sql } from 'postgres';
2
- import { type IndexProjector } from './index-model';
2
+ import { type IndexOp, type IndexProjector } from './index-model';
3
3
  export { POSTGRES_SCHEMA_SQL } from './schema';
4
4
  export { memoryEventLog, postgresEventLog, POSTGRES_EVENT_LOG_SCHEMA_SQL, type EventLogEntry, type EventLogProjector, type MemoryEventLog, type RunLogRow, } from './event-log';
5
5
  export type PostgresProjectorOptions = {
@@ -7,4 +7,7 @@ export type PostgresProjectorOptions = {
7
7
  } | {
8
8
  sql: Sql;
9
9
  };
10
+ type SqlTag = (strings: TemplateStringsArray, ...values: readonly any[]) => PromiseLike<void>;
11
+ /** Apply actor and review index operations on an existing connection or transaction. */
12
+ export declare function applyIndexOps(sql: SqlTag, ops: readonly IndexOp[]): Promise<void>;
10
13
  export declare function postgres(options: PostgresProjectorOptions): IndexProjector;
@@ -1,4 +1,4 @@
1
- import { DateTime, Effect } from 'effect';
1
+ import { DateTime } from 'effect';
2
2
  import createPostgresClient, {} from 'postgres';
3
3
  import { createIndexProjector, } from './index-model.js';
4
4
  import { runProjectorPromise } from './projector.js';
@@ -72,14 +72,16 @@ function applyOp(sql, op) {
72
72
  }
73
73
  }
74
74
  }
75
+ /** Apply actor and review index operations on an existing connection or transaction. */
76
+ export function applyIndexOps(sql, ops) {
77
+ return ops.reduce((chain, op) => chain.then(() => Promise.resolve(applyOp(sql, op)).then(() => undefined)), Promise.resolve());
78
+ }
75
79
  export function postgres(options) {
76
80
  const createdClient = ownsClient(options);
77
81
  const sql = createdClient ? createPostgresClient(options.url) : options.sql;
78
82
  const backend = {
79
83
  init: () => runProjectorPromise('postgres', () => sql.unsafe(POSTGRES_SCHEMA_SQL)).then(() => undefined),
80
- applyOps: (ops) => runProjectorPromise('postgres', () => sql.begin((tx) => Effect.runPromise(Effect.forEach(ops, (op) => Effect.promise(() => Promise.resolve(applyOp(tx, op))), {
81
- discard: true,
82
- })))).then(() => undefined),
84
+ applyOps: (ops) => runProjectorPromise('postgres', () => sql.begin((tx) => applyIndexOps(tx, ops))).then(() => undefined),
83
85
  getActor: (runId, actorId) => runProjectorPromise('postgres', () => sql `
84
86
  SELECT * FROM looms_run_actors WHERE run_id = ${runId} AND actor_id = ${actorId}
85
87
  `).then((rows) => {
@@ -13,6 +13,16 @@ export declare class ProjectorError extends ProjectorError_base<{
13
13
  export declare function runProjectorEffect<A>(projector: string, operation: () => PromiseLike<A>): Effect.Effect<A, ProjectorError>;
14
14
  export declare function runProjectorSync<A>(projector: string, operation: () => A): Promise<A>;
15
15
  export declare function runProjectorPromise<A>(projector: string, operation: () => PromiseLike<A>): Promise<A>;
16
+ declare const ReplicaGapError_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("effect/Cause").YieldableError & {
17
+ readonly _tag: "ReplicaGapError";
18
+ } & Readonly<A>;
19
+ /** A replica batch started after a hole. `project` refuses it and leaves the copy unchanged. */
20
+ export declare class ReplicaGapError extends ReplicaGapError_base<{
21
+ readonly runId: string;
22
+ readonly replicatedSeq: number;
23
+ readonly batchFrom: number;
24
+ }> {
25
+ }
16
26
  export interface Projector {
17
27
  /** Used in error reporting / diagnostics. */
18
28
  readonly name: string;
@@ -20,6 +30,12 @@ export interface Projector {
20
30
  readonly version: string;
21
31
  /** Optional one-time setup (open connection, create tables). Runtime calls this before the first `project`. */
22
32
  readonly init?: () => Promise<void>;
33
+ /**
34
+ * How far this projector has applied `runId` with no hole in front of it.
35
+ * When the number is behind the delivery cursor, delivery rewinds once and catches up.
36
+ * `null` means the run is closed and delivery must not rewind it.
37
+ */
38
+ readonly position?: (runId: string) => Promise<number | null>;
23
39
  /** Apply a batch of events in log order. Must be idempotent (a batch may be redelivered). */
24
40
  readonly project: (events: ReadonlyArray<EventEnvelope>) => Promise<void>;
25
41
  readonly dispose?: () => Promise<void>;
@@ -24,3 +24,6 @@ export function runProjectorSync(projector, operation) {
24
24
  export function runProjectorPromise(projector, operation) {
25
25
  return Effect.runPromise(runProjectorEffect(projector, operation));
26
26
  }
27
+ /** A replica batch started after a hole. `project` refuses it and leaves the copy unchanged. */
28
+ export class ReplicaGapError extends Data.TaggedError('ReplicaGapError') {
29
+ }