@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
@@ -4,7 +4,7 @@
4
4
  <meta charset="UTF-8" />
5
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
6
  <title>Looms debugger</title>
7
- <script type="module" crossorigin src="./assets/index-CUO1xyYW.js"></script>
7
+ <script type="module" crossorigin src="./assets/index-CMRl_aWQ.js"></script>
8
8
  <link rel="modulepreload" crossorigin href="./assets/rolldown-runtime-CbXtAM7H.js">
9
9
  <link rel="stylesheet" crossorigin href="./assets/index-B7GdT1UA.css">
10
10
  </head>
@@ -94,6 +94,8 @@ export function summarizeProtocolEvent(event) {
94
94
  return { title: 'effect timed out', detail: jsonText(payload.timeout) };
95
95
  case 'runtime.effect.ambiguous':
96
96
  return { title: 'effect outcome ambiguous', detail: jsonText(payload.error) };
97
+ case 'runtime.effect.dispatch.deferred':
98
+ return { title: 'effect dispatch deferred', detail: jsonText(payload.error) };
97
99
  case 'runtime.effect.retry.scheduled':
98
100
  return { title: 'effect retry scheduled', detail: jsonText(payload.error) };
99
101
  case 'runtime.snapshot.taken':
@@ -1,7 +1,7 @@
1
1
  import { Schema } from 'effect';
2
2
  import { EvaluatorDefinitionsTag } from './definitions-store';
3
3
  import { EvaluatorTag } from './evaluator';
4
- export declare const evaluateEffect: NoInfer<import("@swirls/looms/core").EffectDefinition<{
4
+ export declare const evaluateEffect: NoInfer<import("@swirls/looms/core").LocalEffectDefinition<{
5
5
  readonly evaluationId: string;
6
6
  readonly definitionName?: string | undefined;
7
7
  readonly definitionVersion?: string | undefined;
@@ -84,6 +84,15 @@ export declare const evaluateEffect: NoInfer<import("@swirls/looms/core").Effect
84
84
  readonly effectId: string;
85
85
  readonly attempt: number;
86
86
  };
87
+ }) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
88
+ readonly type: "runtime.effect.dispatch.deferred";
89
+ readonly payload: {
90
+ readonly effectId: string;
91
+ readonly attempt: number;
92
+ readonly retryAt: number;
93
+ readonly error: string;
94
+ readonly try: number;
95
+ };
87
96
  }) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
88
97
  readonly type: "runtime.effect.dispatched";
89
98
  readonly payload: {
@@ -32,6 +32,7 @@ function failed(threadId, error) {
32
32
  }
33
33
  export const evaluateEffect = evaluatorModule.effect({
34
34
  type: 'evaluator.evaluate',
35
+ placement: 'local',
35
36
  input: EvaluateInput,
36
37
  execute: (input, ctx) => Effect.gen(function* () {
37
38
  const threadId = ctx.threadId;
@@ -36,7 +36,7 @@ export declare function evaluator(options?: EvaluatorModuleOptions): import("@sw
36
36
  }>>;
37
37
  }>;
38
38
  }>, {
39
- evaluate: import("@swirls/looms/core").EffectDefinition<{
39
+ evaluate: import("@swirls/looms/core").LocalEffectDefinition<{
40
40
  readonly evaluationId: string;
41
41
  readonly definitionName?: string | undefined;
42
42
  readonly definitionVersion?: string | undefined;
@@ -119,6 +119,15 @@ export declare function evaluator(options?: EvaluatorModuleOptions): import("@sw
119
119
  readonly effectId: string;
120
120
  readonly attempt: number;
121
121
  };
122
+ }) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
123
+ readonly type: "runtime.effect.dispatch.deferred";
124
+ readonly payload: {
125
+ readonly effectId: string;
126
+ readonly attempt: number;
127
+ readonly retryAt: number;
128
+ readonly error: string;
129
+ readonly try: number;
130
+ };
122
131
  }) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
123
132
  readonly type: "runtime.effect.dispatched";
124
133
  readonly payload: {
@@ -373,7 +382,7 @@ export declare function evaluator(options?: EvaluatorModuleOptions): import("@sw
373
382
  }>;
374
383
  }, import("effect/Context").Service.Any> & {
375
384
  readonly effects: {
376
- evaluate: import("@swirls/looms/core").EffectDefinition<{
385
+ evaluate: import("@swirls/looms/core").LocalEffectDefinition<{
377
386
  readonly evaluationId: string;
378
387
  readonly definitionName?: string | undefined;
379
388
  readonly definitionVersion?: string | undefined;
@@ -456,6 +465,15 @@ export declare function evaluator(options?: EvaluatorModuleOptions): import("@sw
456
465
  readonly effectId: string;
457
466
  readonly attempt: number;
458
467
  };
468
+ }) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
469
+ readonly type: "runtime.effect.dispatch.deferred";
470
+ readonly payload: {
471
+ readonly effectId: string;
472
+ readonly attempt: number;
473
+ readonly retryAt: number;
474
+ readonly error: string;
475
+ readonly try: number;
476
+ };
459
477
  }) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
460
478
  readonly type: "runtime.effect.dispatched";
461
479
  readonly payload: {
@@ -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
+ }