@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,356 @@
1
+ import { DateTime, Effect, Predicate, Stream } from 'effect';
2
+ import createPostgresClient, {} from 'postgres';
3
+ import { EventStoreError, foldRun, } from '@swirls/looms/core';
4
+ import { applyRunIndexOps, eventLogOps, insertRunEvents } from '../event-log.js';
5
+ import { indexOpsFor } from '../index-model.js';
6
+ import { applyIndexOps } from '../postgres.js';
7
+ import { ReplicaGapError } from '../projector.js';
8
+ import { POSTGRES_REPLICA_MIGRATIONS } from './migrations.js';
9
+ const REPLICA_NAME = 'postgres-replica';
10
+ const REPLICA_VERSION = '1';
11
+ const ADVISORY_LOCK_KEY = 814_764;
12
+ const READ_PAGE = 500;
13
+ const terminalStatuses = new Set(['completed', 'failed', 'cancelled']);
14
+ function replicaClient(options) {
15
+ if ('sql' in options) {
16
+ return { sql: options.sql, owned: false };
17
+ }
18
+ return { sql: createPostgresClient(options.url), owned: true };
19
+ }
20
+ function utcDate(millis) {
21
+ return DateTime.toDateUtc(DateTime.makeUnsafe(millis));
22
+ }
23
+ function asNumber(value) {
24
+ if (Predicate.isNumber(value)) {
25
+ return value;
26
+ }
27
+ return Number(value);
28
+ }
29
+ function epoch(value) {
30
+ if (Predicate.isDate(value)) {
31
+ return value.getTime();
32
+ }
33
+ if (Predicate.isNumber(value)) {
34
+ return value;
35
+ }
36
+ return new Date(value).getTime();
37
+ }
38
+ function envelope(row) {
39
+ const event = {
40
+ id: row.event_id,
41
+ runId: row.run_id,
42
+ seq: asNumber(row.seq),
43
+ ts: epoch(row.ts),
44
+ type: row.type,
45
+ payload: row.payload,
46
+ threadId: row.thread_id,
47
+ parentThreadId: row.parent_thread_id,
48
+ origin: row.origin,
49
+ idempotencyKey: row.idempotency_key,
50
+ };
51
+ if (row.causation_id !== null) {
52
+ event.causationId = row.causation_id;
53
+ }
54
+ if (row.correlation_id !== null) {
55
+ event.correlationId = row.correlation_id;
56
+ }
57
+ if (row.effect_id !== null) {
58
+ event.effectId = row.effect_id;
59
+ }
60
+ if (row.ephemeral) {
61
+ event.ephemeral = true;
62
+ }
63
+ return event;
64
+ }
65
+ function groups(events) {
66
+ const byRun = new Map();
67
+ for (const event of events) {
68
+ const batch = byRun.get(event.runId);
69
+ if (batch) {
70
+ batch.push(event);
71
+ }
72
+ else {
73
+ byRun.set(event.runId, [event]);
74
+ }
75
+ }
76
+ for (const batch of byRun.values()) {
77
+ batch.sort((left, right) => left.seq - right.seq);
78
+ }
79
+ return byRun;
80
+ }
81
+ /** Sequence through which `events` extends `replicatedSeq` with no hole. Redelivered seqs are ignored. */
82
+ function contiguousSeq(runId, replicatedSeq, events) {
83
+ let cursor = replicatedSeq;
84
+ for (const event of events) {
85
+ if (event.seq <= cursor) {
86
+ continue;
87
+ }
88
+ if (event.seq !== cursor + 1) {
89
+ throw new ReplicaGapError({ runId, replicatedSeq, batchFrom: event.seq });
90
+ }
91
+ cursor = event.seq;
92
+ }
93
+ return cursor;
94
+ }
95
+ async function appliedMigrationIds(sql) {
96
+ const [table] = await sql `
97
+ SELECT to_regclass('public.looms_schema_migrations') AS name
98
+ `;
99
+ if (!table?.name) {
100
+ return new Set();
101
+ }
102
+ const rows = await sql `SELECT id FROM looms_schema_migrations`;
103
+ return new Set(rows.map((row) => row.id));
104
+ }
105
+ async function readPage(sql, runId, fromSeq, limit) {
106
+ const rows = await sql `
107
+ SELECT run_id, seq, event_id, ts, type, payload, thread_id, parent_thread_id,
108
+ causation_id, correlation_id, effect_id, origin, idempotency_key, ephemeral
109
+ FROM looms_run_events
110
+ WHERE run_id = ${runId} AND seq >= ${fromSeq}
111
+ ORDER BY seq
112
+ LIMIT ${limit}
113
+ `;
114
+ return rows.map(envelope);
115
+ }
116
+ export function postgresReplica(options) {
117
+ const { sql, owned } = replicaClient(options);
118
+ let ready;
119
+ const pendingMigrations = async () => {
120
+ const applied = await appliedMigrationIds(sql);
121
+ return POSTGRES_REPLICA_MIGRATIONS.filter((migration) => !applied.has(migration.id)).map((migration) => migration.id);
122
+ };
123
+ const migrate = async () => {
124
+ await sql.begin(async (tx) => {
125
+ await tx `SELECT pg_advisory_xact_lock(${ADVISORY_LOCK_KEY})`;
126
+ const applied = await appliedMigrationIds(tx);
127
+ for (const migration of POSTGRES_REPLICA_MIGRATIONS) {
128
+ if (!applied.has(migration.id)) {
129
+ await tx.unsafe(migration.sql);
130
+ }
131
+ }
132
+ });
133
+ };
134
+ const init = () => {
135
+ ready ??= (options.migrate === 'verify' ? verify() : migrate()).catch((cause) => {
136
+ ready = undefined;
137
+ throw cause;
138
+ });
139
+ return ready;
140
+ };
141
+ const verify = async () => {
142
+ const pending = await pendingMigrations();
143
+ if (pending.length > 0) {
144
+ throw new Error(`Looms replica is missing migrations: ${pending.join(', ')}. Generate them with \`looms replica generate\` and apply the files before starting.`);
145
+ }
146
+ };
147
+ const project = async (events) => {
148
+ await init();
149
+ if (events.length === 0) {
150
+ return;
151
+ }
152
+ await sql.begin(async (tx) => {
153
+ for (const [runId, batch] of groups(events)) {
154
+ const [progress] = await tx `
155
+ SELECT replicated_seq, purged_at
156
+ FROM looms_run_index
157
+ WHERE run_id = ${runId}
158
+ FOR UPDATE
159
+ `;
160
+ if (progress?.purged_at) {
161
+ continue;
162
+ }
163
+ const replicatedSeq = progress ? asNumber(progress.replicated_seq) : 0;
164
+ const next = contiguousSeq(runId, replicatedSeq, batch);
165
+ const durable = batch.filter((event) => !event.ephemeral);
166
+ const last = batch.at(-1);
167
+ await insertRunEvents(tx, batch);
168
+ await applyRunIndexOps(tx, durable.flatMap((event) => eventLogOps(event)));
169
+ await applyIndexOps(tx, durable.flatMap(indexOpsFor));
170
+ if (next === replicatedSeq || !last) {
171
+ continue;
172
+ }
173
+ await tx `
174
+ INSERT INTO looms_run_index (run_id, status, updated_at, replicated_seq)
175
+ VALUES (${runId}, 'running', ${utcDate(last.ts)}, ${next})
176
+ ON CONFLICT (run_id) DO UPDATE SET
177
+ replicated_seq = GREATEST(looms_run_index.replicated_seq, EXCLUDED.replicated_seq)
178
+ WHERE looms_run_index.purged_at IS NULL
179
+ `;
180
+ }
181
+ });
182
+ };
183
+ const position = async (runId) => {
184
+ const [row] = await sql `
185
+ SELECT replicated_seq, purged_at
186
+ FROM looms_run_index
187
+ WHERE run_id = ${runId}
188
+ `;
189
+ if (!row) {
190
+ return 0;
191
+ }
192
+ if (row.purged_at) {
193
+ return null;
194
+ }
195
+ return asNumber(row.replicated_seq);
196
+ };
197
+ const readEvents = (runId, readOptions) => Effect.tryPromise({
198
+ try: async () => {
199
+ const fromSeq = readOptions?.fromSeq ?? 1;
200
+ const events = [];
201
+ let cursor = fromSeq;
202
+ let remaining = readOptions?.limit;
203
+ while (remaining === undefined || remaining > 0) {
204
+ const take = remaining === undefined ? READ_PAGE : Math.min(READ_PAGE, remaining);
205
+ const page = await readPage(sql, runId, cursor, take);
206
+ events.push(...page);
207
+ if (remaining !== undefined) {
208
+ remaining -= page.length;
209
+ }
210
+ const last = page.at(-1);
211
+ if (!last || page.length < take) {
212
+ break;
213
+ }
214
+ cursor = last.seq + 1;
215
+ }
216
+ return events;
217
+ },
218
+ catch: (cause) => new EventStoreError('Replica read failed', cause),
219
+ });
220
+ const store = {
221
+ append: () => Effect.fail(new EventStoreError('The Postgres replica is read-only')),
222
+ read: readEvents,
223
+ readStream: (runId, readOptions) => Stream.fromIterableEffect(readEvents(runId, readOptions)),
224
+ tail: (runId) => Effect.tryPromise({
225
+ try: async () => {
226
+ const [row] = await sql `
227
+ SELECT replicated_seq FROM looms_run_index WHERE run_id = ${runId}
228
+ `;
229
+ return row ? asNumber(row.replicated_seq) : 0;
230
+ },
231
+ catch: (cause) => new EventStoreError('Replica tail failed', cause),
232
+ }),
233
+ bounds: (runId) => Effect.tryPromise({
234
+ try: async () => {
235
+ const [row] = await sql `
236
+ SELECT replicated_seq,
237
+ (SELECT MIN(seq) FROM looms_run_events event WHERE event.run_id = run.run_id) AS head
238
+ FROM looms_run_index run
239
+ WHERE run.run_id = ${runId}
240
+ `;
241
+ if (!row) {
242
+ return { head: 1, tail: 0 };
243
+ }
244
+ const tail = asNumber(row.replicated_seq);
245
+ const head = row.head === null ? tail + 1 : asNumber(row.head);
246
+ return { head, tail };
247
+ },
248
+ catch: (cause) => new EventStoreError('Replica bounds failed', cause),
249
+ }),
250
+ trim: () => Effect.fail(new EventStoreError('Trim a replica with purge()')),
251
+ subscribe: (runId, readOptions) => Stream.fromIterableEffect(readEvents(runId, readOptions)),
252
+ listRuns: Effect.tryPromise({
253
+ try: async () => {
254
+ const rows = await sql `
255
+ SELECT run_id FROM looms_run_index
256
+ WHERE purged_at IS NULL
257
+ ORDER BY run_id
258
+ `;
259
+ return rows.map((row) => row.run_id);
260
+ },
261
+ catch: (cause) => new EventStoreError('Replica listRuns failed', cause),
262
+ }),
263
+ };
264
+ const loadRun = async (runId, registry) => {
265
+ const events = await Effect.runPromise(readEvents(runId));
266
+ return foldRun(events, registry, { runId });
267
+ };
268
+ const status = async (runId) => {
269
+ const [row] = await sql `
270
+ SELECT run.replicated_seq,
271
+ run.status,
272
+ run.purged_at,
273
+ (SELECT MAX(seq) FROM looms_run_events event WHERE event.run_id = run.run_id) AS max_seq
274
+ FROM looms_run_index run
275
+ WHERE run.run_id = ${runId}
276
+ `;
277
+ if (!row) {
278
+ return null;
279
+ }
280
+ const replicatedSeq = asNumber(row.replicated_seq);
281
+ const finished = terminalStatuses.has(row.status);
282
+ const purgedAt = row.purged_at === null ? null : epoch(row.purged_at);
283
+ const maxSeq = row.max_seq === null ? null : asNumber(row.max_seq);
284
+ const copiedThroughFinish = purgedAt !== null || (maxSeq !== null && maxSeq === replicatedSeq && replicatedSeq > 0);
285
+ return {
286
+ replicatedSeq,
287
+ finished,
288
+ complete: finished && copiedThroughFinish,
289
+ purgedAt,
290
+ };
291
+ };
292
+ const purge = async (purgeOptions) => {
293
+ const cutoff = utcDate(purgeOptions.finishedBefore);
294
+ const keepIndex = purgeOptions.keepIndex !== false;
295
+ return sql.begin(async (tx) => {
296
+ const doomed = await tx `
297
+ UPDATE looms_run_index
298
+ SET purged_at = NOW()
299
+ WHERE purged_at IS NULL
300
+ AND status IN ('completed', 'failed', 'cancelled')
301
+ AND completed_at IS NOT NULL
302
+ AND completed_at < ${cutoff}
303
+ RETURNING run_id
304
+ `;
305
+ const ids = doomed.map((row) => row.run_id);
306
+ if (ids.length === 0) {
307
+ return { runs: 0 };
308
+ }
309
+ await tx `DELETE FROM looms_run_events WHERE run_id IN ${tx(ids)}`;
310
+ if (!keepIndex) {
311
+ await tx `DELETE FROM looms_run_actors WHERE run_id IN ${tx(ids)}`;
312
+ await tx `DELETE FROM looms_run_reviews WHERE run_id IN ${tx(ids)}`;
313
+ await tx `DELETE FROM looms_run_index WHERE run_id IN ${tx(ids)}`;
314
+ }
315
+ return { runs: ids.length };
316
+ });
317
+ };
318
+ const rebuild = async (source) => {
319
+ await init();
320
+ const runIds = await Effect.runPromise(source.listRuns);
321
+ let copied = 0;
322
+ for (const runId of runIds) {
323
+ let fromSeq = 1;
324
+ while (true) {
325
+ const events = await Effect.runPromise(source.read(runId, { fromSeq, limit: READ_PAGE }));
326
+ if (events.length === 0) {
327
+ break;
328
+ }
329
+ await project(events);
330
+ copied += events.length;
331
+ const last = events.at(-1);
332
+ if (!last || events.length < READ_PAGE) {
333
+ break;
334
+ }
335
+ fromSeq = last.seq + 1;
336
+ }
337
+ }
338
+ return copied;
339
+ };
340
+ return {
341
+ name: REPLICA_NAME,
342
+ version: REPLICA_VERSION,
343
+ init,
344
+ position,
345
+ project,
346
+ migrate,
347
+ pendingMigrations,
348
+ eventStore: () => store,
349
+ loadRun,
350
+ status,
351
+ purge,
352
+ rebuild,
353
+ dispose: owned ? () => sql.end() : undefined,
354
+ };
355
+ }
356
+ export { ReplicaGapError };
@@ -1,7 +1,8 @@
1
1
  /**
2
2
  * SQL schema for the optional Looms secondary index.
3
+ * The Postgres statements live with the replica migrations so there is one DDL source.
3
4
  */
4
- export declare const POSTGRES_SCHEMA_SQL: string;
5
+ export { POSTGRES_SCHEMA_SQL } from './replica/migrations';
5
6
  export declare const SQLITE_TABLES_SQL: string;
6
7
  /** Columns added after the first release. SQLite cannot add a column only if it is missing. */
7
8
  export declare const SQLITE_ADDED_ACTOR_COLUMNS: readonly ['launched_by_run_id', 'launched_by_effect_id', 'correlation_id'];
@@ -1,37 +1,8 @@
1
1
  /**
2
2
  * SQL schema for the optional Looms secondary index.
3
+ * The Postgres statements live with the replica migrations so there is one DDL source.
3
4
  */
4
- export const POSTGRES_SCHEMA_SQL = `
5
- CREATE TABLE IF NOT EXISTS looms_run_actors (
6
- run_id TEXT NOT NULL,
7
- actor_id TEXT NOT NULL,
8
- kind TEXT,
9
- status TEXT,
10
- definition_name TEXT,
11
- parent_actor_id TEXT,
12
- launched_by_run_id TEXT,
13
- launched_by_effect_id TEXT,
14
- correlation_id TEXT,
15
- updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
16
- PRIMARY KEY (run_id, actor_id)
17
- );
18
-
19
- ALTER TABLE looms_run_actors ADD COLUMN IF NOT EXISTS launched_by_run_id TEXT;
20
- ALTER TABLE looms_run_actors ADD COLUMN IF NOT EXISTS launched_by_effect_id TEXT;
21
- ALTER TABLE looms_run_actors ADD COLUMN IF NOT EXISTS correlation_id TEXT;
22
-
23
- CREATE INDEX IF NOT EXISTS looms_run_actors_launched_by ON looms_run_actors (launched_by_run_id);
24
- CREATE INDEX IF NOT EXISTS looms_run_actors_correlation ON looms_run_actors (correlation_id);
25
-
26
- CREATE TABLE IF NOT EXISTS looms_run_reviews (
27
- run_id TEXT NOT NULL,
28
- review_id TEXT NOT NULL,
29
- status TEXT NOT NULL,
30
- title TEXT NOT NULL,
31
- updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
32
- PRIMARY KEY (run_id, review_id)
33
- );
34
- `.trim();
5
+ export { POSTGRES_SCHEMA_SQL } from './replica/migrations.js';
35
6
  export const SQLITE_TABLES_SQL = `
36
7
  CREATE TABLE IF NOT EXISTS looms_run_actors (
37
8
  run_id TEXT NOT NULL,
@@ -103,6 +103,15 @@ export function sqliteProjectorCursorStore(exec) {
103
103
  failed_seq = NULL, next_retry_at = NULL, last_error = NULL,
104
104
  updated_at = excluded.updated_at`, [runId, projector.name, projector.version, cursor, now]);
105
105
  }),
106
+ rewind: (runId, projector, cursor, now) => query(() => {
107
+ exec.run(`INSERT INTO looms_projector_delivery
108
+ (run_id, projector_name, projector_version, cursor, state, attempts, updated_at)
109
+ VALUES (?, ?, ?, ?, 'idle', 0, ?)
110
+ ON CONFLICT (run_id, projector_name, projector_version) DO UPDATE
111
+ SET cursor = excluded.cursor, state = 'idle', attempts = 0,
112
+ failed_seq = NULL, next_retry_at = NULL, last_error = NULL,
113
+ updated_at = excluded.updated_at`, [runId, projector.name, projector.version, cursor, now]);
114
+ }),
106
115
  fail: (runId, projector, failure) => query(() => {
107
116
  exec.run(`INSERT INTO looms_projector_delivery
108
117
  (run_id, projector_name, projector_version, state, attempts, failed_seq,
@@ -26,7 +26,7 @@ function planCancellation(input) {
26
26
  !isWorkerEffect({ runId, item, execution, registry, worker: input.worker })) {
27
27
  continue;
28
28
  }
29
- if (execution.status === 'retry_wait') {
29
+ if (execution.status === 'retry_wait' || execution.status === 'dispatch_wait') {
30
30
  effectEvents.push(createEvent(runId, {
31
31
  type: 'runtime.effect.cancelled',
32
32
  payload: { effectId: item.effectId, attempt: execution.attempt },
@@ -1,4 +1,4 @@
1
1
  import type { Context, ManagedRuntime } from 'effect';
2
2
  import { Effect } from 'effect';
3
- import { type ComposedRegistry, type EffectContext, type EventInput, type DefinitionResolver, type RunLauncher, type RuntimeEffect } from '@swirls/looms/core';
4
- export declare function dispatchEffect(registry: ComposedRegistry, services: ManagedRuntime.ManagedRuntime<Context.Service.Any, never>, definitions: DefinitionResolver, launcher: RunLauncher, effect: RuntimeEffect, ctx: EffectContext): Effect.Effect<ReadonlyArray<EventInput>, Error>;
3
+ import { type ComposedRegistry, type LocalEffectContext, type EventInput, type DefinitionResolver, type RunLauncher, type RuntimeEffect } from '@swirls/looms/core';
4
+ export declare function dispatchEffect(registry: ComposedRegistry, services: ManagedRuntime.ManagedRuntime<Context.Service.Any, never>, definitions: DefinitionResolver, launcher: RunLauncher, effect: RuntimeEffect, ctx: LocalEffectContext): Effect.Effect<ReadonlyArray<EventInput>, Error>;
@@ -1,5 +1,5 @@
1
1
  import { Effect, Predicate } from 'effect';
2
- import { asJson, isPrimitiveEffect, isWaitOnTimer, readEffectFailure, RunLauncherTag, } from '@swirls/looms/core';
2
+ import { asJson, EffectFailure, isLocalEffectDefinition, isPrimitiveEffect, isWaitOnTimer, readEffectFailure, RunLauncherTag, } from '@swirls/looms/core';
3
3
  import { threadStartedEvents } from './helpers.js';
4
4
  function causeMessage(cause) {
5
5
  if (Predicate.isString(cause)) {
@@ -108,16 +108,24 @@ export function dispatchEffect(registry, services, definitions, launcher, effect
108
108
  }
109
109
  }
110
110
  }
111
- const handler = registry.effects.get(eff.type);
112
- if (!handler) {
111
+ const definition = registry.effects.get(eff.type);
112
+ if (!definition) {
113
113
  return Effect.succeed([
114
114
  failedAttempt(effCtx.effectId, currentThreadId, `No handler for ${eff.type}`),
115
115
  ]);
116
116
  }
117
+ if (!isLocalEffectDefinition(definition)) {
118
+ return Effect.succeed([
119
+ failedAttempt(effCtx.effectId, currentThreadId, new EffectFailure({
120
+ error: `${eff.type} is worker-placed; the host cannot run it`,
121
+ nonRetryable: true,
122
+ })),
123
+ ]);
124
+ }
117
125
  const input = 'input' in eff ? eff.input : {};
118
126
  const execution = Effect.gen(function* () {
119
127
  const serviceContext = yield* services.contextEffect;
120
- return yield* handler
128
+ return yield* definition
121
129
  .execute(input, effCtx)
122
130
  .pipe(Effect.provideService(RunLauncherTag, launcher), Effect.provide(serviceContext));
123
131
  });
@@ -0,0 +1,45 @@
1
+ import { Effect } from 'effect';
2
+ import { type ComposedRegistry, type EventEnvelope, type OutstandingEffect, type RetryPolicy, type RunAttributes, type SecretContext, type TraceContext } from '@swirls/looms/core';
3
+ import type { RuntimeObservation } from './observer';
4
+ export type AdmissionDecision = {
5
+ readonly _tag: 'admit';
6
+ } | {
7
+ readonly _tag: 'reject';
8
+ readonly error: string;
9
+ readonly nonRetryable: boolean;
10
+ readonly retryAfterMs?: number;
11
+ };
12
+ export type AdmitOrFailResult = {
13
+ readonly _tag: 'admit';
14
+ } | {
15
+ readonly _tag: 'reject';
16
+ readonly event: EventEnvelope;
17
+ readonly retrying: boolean;
18
+ /** Present when the reject schedules another attempt under the retry policy. */
19
+ readonly observation?: RuntimeObservation;
20
+ };
21
+ /**
22
+ * Run every composed admission hook before a local attempt or a worker dispatch.
23
+ * A `failEffect` (or other thrown/failed cause) becomes a reject decision.
24
+ */
25
+ export declare function runEffectAdmission(registry: ComposedRegistry, item: OutstandingEffect, context: {
26
+ readonly runId: string;
27
+ readonly attributes: RunAttributes;
28
+ readonly secrets: SecretContext;
29
+ readonly trace: TraceContext | null;
30
+ }): Effect.Effect<AdmissionDecision>;
31
+ /**
32
+ * Gate an attempt, then turn a reject into the durable failure/retry event both the local
33
+ * executor and the wake engine append. Call sites only append the event (and notify observer).
34
+ */
35
+ export declare function admitOrFailAttempt(input: {
36
+ readonly registry: ComposedRegistry;
37
+ readonly item: OutstandingEffect;
38
+ readonly runId: string;
39
+ readonly attempt: number;
40
+ readonly now: number;
41
+ readonly attributes: RunAttributes;
42
+ readonly secrets: SecretContext;
43
+ readonly trace: TraceContext | null;
44
+ readonly retry: RetryPolicy | undefined;
45
+ }): Effect.Effect<AdmitOrFailResult>;
@@ -0,0 +1,70 @@
1
+ import { Effect } from 'effect';
2
+ import { isPrimitiveEffect, readEffectFailure, } from '@swirls/looms/core';
3
+ import { planAttemptFailure } from './retry-policy.js';
4
+ /**
5
+ * Run every composed admission hook before a local attempt or a worker dispatch.
6
+ * A `failEffect` (or other thrown/failed cause) becomes a reject decision.
7
+ */
8
+ export function runEffectAdmission(registry, item, context) {
9
+ if (isPrimitiveEffect(item.effect) || registry.admission.length === 0) {
10
+ return Effect.succeed({ _tag: 'admit' });
11
+ }
12
+ const admissionCtx = {
13
+ effectId: item.effectId,
14
+ runId: context.runId,
15
+ threadId: item.threadId,
16
+ causingEventId: item.causingEventId,
17
+ attributes: context.attributes,
18
+ secrets: context.secrets,
19
+ trace: context.trace,
20
+ };
21
+ const effect = item.effect;
22
+ return Effect.forEach(registry.admission, (hook) => hook(effect, admissionCtx), {
23
+ discard: true,
24
+ }).pipe(Effect.as({ _tag: 'admit' }), Effect.catch((cause) => {
25
+ const failure = readEffectFailure(cause);
26
+ return Effect.succeed({
27
+ _tag: 'reject',
28
+ error: failure?.error ?? (cause instanceof Error ? cause.message : String(cause)),
29
+ nonRetryable: failure?.nonRetryable === true,
30
+ retryAfterMs: failure?.retryAfterMs,
31
+ });
32
+ }));
33
+ }
34
+ /**
35
+ * Gate an attempt, then turn a reject into the durable failure/retry event both the local
36
+ * executor and the wake engine append. Call sites only append the event (and notify observer).
37
+ */
38
+ export function admitOrFailAttempt(input) {
39
+ return runEffectAdmission(input.registry, input.item, input).pipe(Effect.map((decision) => {
40
+ if (decision._tag === 'admit') {
41
+ return { _tag: 'admit' };
42
+ }
43
+ const failure = planAttemptFailure({
44
+ runId: input.runId,
45
+ item: input.item,
46
+ attempt: input.attempt,
47
+ error: decision.error,
48
+ now: input.now,
49
+ retry: input.retry,
50
+ origin: { type: 'system' },
51
+ nonRetryable: decision.nonRetryable,
52
+ retryAfterMs: decision.retryAfterMs,
53
+ });
54
+ return {
55
+ _tag: 'reject',
56
+ event: failure.event,
57
+ retrying: failure.retrying,
58
+ observation: failure.retrying
59
+ ? {
60
+ type: 'effect.retry',
61
+ runId: input.runId,
62
+ at: input.now,
63
+ effectId: input.item.effectId,
64
+ attempt: input.attempt,
65
+ detail: decision.error,
66
+ }
67
+ : undefined,
68
+ };
69
+ }));
70
+ }
@@ -7,6 +7,9 @@ export interface WorkerTaskExtras {
7
7
  readonly details?: JsonValue | null;
8
8
  readonly secrets?: SecretContext;
9
9
  readonly trace?: TraceContext | null;
10
+ readonly attributes?: {
11
+ readonly [key: string]: string;
12
+ };
10
13
  readonly retry?: RetryPolicy;
11
14
  readonly scheduleToStartAt?: number | null;
12
15
  }
@@ -59,7 +62,9 @@ export declare function createEffectFailedEvent(runId: string, item: {
59
62
  effectId: string;
60
63
  causingEventId: string;
61
64
  threadId: string;
62
- }, error: string): EventEnvelope;
65
+ }, error: string, options?: {
66
+ readonly nonRetryable?: boolean;
67
+ }): EventEnvelope;
63
68
  export declare function materializeEffectOutcome(catalogs: readonly EventCatalog[], runId: string, item: {
64
69
  effectId: string;
65
70
  causingEventId: string;
@@ -7,7 +7,12 @@ export function workerTask(runId, item, attempt, extras = {}) {
7
7
  attempt,
8
8
  type: item.effect.type,
9
9
  input: 'input' in item.effect ? item.effect.input : null,
10
+ threadId: item.threadId,
11
+ causingEventId: item.causingEventId,
10
12
  };
13
+ if (extras.attributes && hasEntries(extras.attributes)) {
14
+ task.attributes = extras.attributes;
15
+ }
11
16
  if (extras.details != null) {
12
17
  task.details = extras.details;
13
18
  }
@@ -266,13 +271,17 @@ export function waitSatisfiedEvents(state, events) {
266
271
  }
267
272
  return produced;
268
273
  }
269
- export function createEffectFailedEvent(runId, item, error) {
274
+ export function createEffectFailedEvent(runId, item, error, options = {}) {
275
+ const payload = {
276
+ effectId: item.effectId,
277
+ error,
278
+ };
279
+ if (options.nonRetryable) {
280
+ payload.nonRetryable = true;
281
+ }
270
282
  return createEvent(runId, {
271
283
  type: 'runtime.effect.failed',
272
- payload: {
273
- effectId: item.effectId,
274
- error,
275
- },
284
+ payload,
276
285
  threadId: item.threadId,
277
286
  effectId: item.effectId,
278
287
  causationId: item.causingEventId,
@@ -1,4 +1,5 @@
1
1
  export { createRuntime, createTimeoutScheduler, DuplicateEffectDispatchError, ForkConflictError, MaxWakeIterationsError, RunNotFinishedError, RunNotFoundError, RunOverloadedError, RunTerminalError, StartRunConflictError, type CreateRuntimeOptions, type EffectWorker, type EffectWorkerDeadlines, type EffectWorkerTask, type LoomsRuntime, type RunOperationalStatus, type RegisteredDefinition, type StartRunArgs, type WakeError, type WakeScheduler, type WorkerCallback, type WorkerCallbackInput, type WorkerCallbackResult, } from './runtime';
2
+ export { listEffectPlacements } from './worker-effect-dispatch';
2
3
  export { createLooms, type Looms, type CreateLoomsOptions, type StartResult } from './looms';
3
4
  export { loadSubscriptionOpening, readSubscriptionBounds } from './subscription';
4
5
  export { serveHttp, createFetchHandler, isLoomsApiPath, type FetchHandlerOptions, authAllowed, authDenied, authResponse, bearerAuth, defaultAuthorize, grantAuth, issueRunGrant, grantSubprotocol, runGrantToken, verifyRunGrant, GrantError, type GrantAuthOptions, type GrantFailure, type RunGrant, runRouteInfo, type AuthDecision, type AuthorizedAccess, type Authorize, type BearerTokens, type RouteAccess, type RouteInfo, type RunningServer, type LoomsFetchResult, } from './server';
@@ -1,4 +1,5 @@
1
1
  export { createRuntime, createTimeoutScheduler, DuplicateEffectDispatchError, ForkConflictError, MaxWakeIterationsError, RunNotFinishedError, RunNotFoundError, RunOverloadedError, RunTerminalError, StartRunConflictError, } from './runtime.js';
2
+ export { listEffectPlacements } from './worker-effect-dispatch.js';
2
3
  export { createLooms } from './looms.js';
3
4
  export { loadSubscriptionOpening, readSubscriptionBounds } from './subscription.js';
4
5
  export { serveHttp, createFetchHandler, isLoomsApiPath, authAllowed, authDenied, authResponse, bearerAuth, defaultAuthorize, grantAuth, issueRunGrant, grantSubprotocol, runGrantToken, verifyRunGrant, GrantError, runRouteInfo, } from './server.js';