@swirls/looms 0.10.0 → 0.11.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 (45) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/dist/actor/cell.d.ts +3 -1
  3. package/dist/actor/cell.js +1 -0
  4. package/dist/actor/host.d.ts +3 -1
  5. package/dist/actor/host.js +1 -0
  6. package/dist/agent/module.d.ts +512 -512
  7. package/dist/cli/commands.d.ts +1 -1
  8. package/dist/cli/commands.js +47 -12
  9. package/dist/client/client.d.ts +20 -21
  10. package/dist/client/client.js +2 -1
  11. package/dist/cloudflare/delete-terminal-run-storage.d.ts +39 -0
  12. package/dist/cloudflare/delete-terminal-run-storage.js +98 -0
  13. package/dist/cloudflare/durable-object.d.ts +11 -1
  14. package/dist/cloudflare/durable-object.js +23 -0
  15. package/dist/cloudflare/index.d.ts +1 -0
  16. package/dist/cloudflare/index.js +1 -0
  17. package/dist/core/run-context.d.ts +50 -0
  18. package/dist/core/run-context.js +21 -1
  19. package/dist/debugger/app/assets/{index-D-2Q7ecG.js → index-VTotlHcm.js} +2 -2
  20. package/dist/debugger/app/assets/{routes-lvmllT60.js → routes-CEdsN9DO.js} +2 -2
  21. package/dist/debugger/app/index.html +1 -1
  22. package/dist/projectors/event-log-ops.d.ts +0 -6
  23. package/dist/projectors/event-log-ops.js +2 -12
  24. package/dist/projectors/event-log.d.ts +10 -5
  25. package/dist/projectors/event-log.js +26 -22
  26. package/dist/projectors/replica/columns.d.ts +41 -0
  27. package/dist/projectors/replica/columns.js +77 -0
  28. package/dist/projectors/replica/drizzle.d.ts +328 -57
  29. package/dist/projectors/replica/drizzle.js +18 -14
  30. package/dist/projectors/replica/migrations.d.ts +25 -5
  31. package/dist/projectors/replica/migrations.js +62 -14
  32. package/dist/projectors/replica/postgres.d.ts +12 -11
  33. package/dist/projectors/replica/postgres.js +12 -26
  34. package/dist/projectors/replica/sqlite-bun.d.ts +3 -1
  35. package/dist/projectors/replica/sqlite-bun.js +6 -2
  36. package/dist/projectors/replica/sqlite-migrations.d.ts +5 -5
  37. package/dist/projectors/replica/sqlite-migrations.js +22 -9
  38. package/dist/projectors/replica/sqlite.d.ts +12 -11
  39. package/dist/projectors/replica/sqlite.js +23 -16
  40. package/dist/runtime/looms.d.ts +27 -36
  41. package/dist/runtime/looms.js +1 -0
  42. package/dist/runtime/runtime.js +7 -1
  43. package/dist/runtime/server/http.js +4 -2
  44. package/dist/runtime/types.d.ts +6 -1
  45. package/package.json +1 -1
@@ -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-D-2Q7ecG.js"></script>
7
+ <script type="module" crossorigin src="./assets/index-VTotlHcm.js"></script>
8
8
  <link rel="modulepreload" crossorigin href="./assets/rolldown-runtime-CbXtAM7H.js">
9
9
  <link rel="stylesheet" crossorigin href="./assets/index-CO5gIvV8.css">
10
10
  </head>
@@ -27,9 +27,6 @@ export interface RunLogRow {
27
27
  readonly attributes: {
28
28
  readonly [key: string]: string;
29
29
  };
30
- readonly tenant: string | null;
31
- readonly project: string | null;
32
- readonly org: string | null;
33
30
  readonly startedAt: number | null;
34
31
  readonly updatedAt: number;
35
32
  readonly completedAt: number | null;
@@ -50,9 +47,6 @@ export type EventLogOp = {
50
47
  readonly attributes: {
51
48
  readonly [key: string]: string;
52
49
  };
53
- readonly tenant: string | null;
54
- readonly project: string | null;
55
- readonly org: string | null;
56
50
  readonly at: number;
57
51
  } | {
58
52
  readonly type: 'finish';
@@ -1,6 +1,5 @@
1
- import { Option, Predicate, Schema } from 'effect';
2
- import { completedRunStatus, isJsonObject, readRunLaunchSource, } from '@swirls/looms/core';
3
- const decodeAttributes = Schema.decodeUnknownOption(Schema.Record(Schema.String, Schema.String));
1
+ import { Predicate } from 'effect';
2
+ import { completedRunStatus, isJsonObject, readAttributes, readRunLaunchSource, } from '@swirls/looms/core';
4
3
  /** Fold one durable event into event-row and run-summary operations. Ephemeral events produce nothing. */
5
4
  export function eventLogOps(event) {
6
5
  if (event.ephemeral) {
@@ -61,9 +60,6 @@ function startOp(event, payload) {
61
60
  launchedByEffectId: launchedBy?.effectId ?? null,
62
61
  correlationId: event.correlationId ?? null,
63
62
  attributes,
64
- tenant: attributes.tenant ?? null,
65
- project: attributes.project ?? null,
66
- org: attributes.org ?? null,
67
63
  at: event.ts,
68
64
  };
69
65
  }
@@ -71,9 +67,3 @@ function readString(payload, key) {
71
67
  const value = payload[key];
72
68
  return Predicate.isString(value) ? value : null;
73
69
  }
74
- function readAttributes(value) {
75
- if (value === undefined) {
76
- return {};
77
- }
78
- return Option.getOrElse(decodeAttributes(value), () => ({}));
79
- }
@@ -1,7 +1,8 @@
1
1
  import { type Sql, type TransactionSql } from 'postgres';
2
- import { type EventEnvelope, type EventStore } from '@swirls/looms/core';
2
+ import { type EventEnvelope, type EventStore, type RunAttributeFields } from '@swirls/looms/core';
3
3
  import { eventLogOps, type EventLogEntry, type EventLogOp, type RunLogRow } from './event-log-ops';
4
4
  import type { Projector } from './projector';
5
+ import { type ResolvedReplicaColumn } from './replica/columns';
5
6
  import { POSTGRES_EVENT_LOG_SCHEMA_SQL } from './replica/migrations';
6
7
  export { POSTGRES_EVENT_LOG_SCHEMA_SQL, eventLogOps };
7
8
  export type { EventLogEntry, EventLogOp, RunLogRow };
@@ -17,13 +18,17 @@ export interface MemoryEventLog extends EventLogProjector {
17
18
  run(runId: string): RunLogRow | null;
18
19
  }
19
20
  export declare function memoryEventLog(): MemoryEventLog;
20
- export declare function postgresEventLog(options: {
21
+ export type PostgresEventLogOptions = ({
21
22
  url: string;
22
23
  } | {
23
24
  sql: Sql;
24
- }): EventLogProjector;
25
- export declare function applySqlOps(sql: TransactionSql, ops: readonly EventLogOp[]): Promise<void>;
25
+ }) & {
26
+ /** Declared run attributes. Each one is a `looms_run_index` column. */
27
+ readonly additionalFields?: RunAttributeFields;
28
+ };
29
+ export declare function postgresEventLog(options: PostgresEventLogOptions): EventLogProjector;
30
+ export declare function applySqlOps(sql: TransactionSql, ops: readonly EventLogOp[], columns?: readonly ResolvedReplicaColumn[]): Promise<void>;
26
31
  /** Fold run-summary ops. Event rows are written by {@link insertRunEvents}. */
27
- export declare function applyRunIndexOps(sql: TransactionSql, ops: readonly EventLogOp[]): Promise<void>;
32
+ export declare function applyRunIndexOps(sql: TransactionSql, ops: readonly EventLogOp[], columns?: readonly ResolvedReplicaColumn[]): Promise<void>;
28
33
  /** Insert event envelopes, including ephemeral ones. Durable callers pass events that are already filtered. */
29
34
  export declare function insertRunEvents(sql: TransactionSql, events: readonly EventEnvelope[]): Promise<void>;
@@ -3,7 +3,8 @@ import createPostgresClient, {} from 'postgres';
3
3
  import {} from '@swirls/looms/core';
4
4
  import { eventLogOps } from './event-log-ops.js';
5
5
  import { runProjectorPromise } from './projector.js';
6
- import { POSTGRES_EVENT_LOG_SCHEMA_SQL } from './replica/migrations.js';
6
+ import { columnValues, resolveReplicaColumns } from './replica/columns.js';
7
+ import { applyPostgresMigrations, POSTGRES_EVENT_LOG_SCHEMA_SQL, POSTGRES_SCHEMA_MIGRATIONS_SQL, postgresAttributeMigrations, } from './replica/migrations.js';
7
8
  export { POSTGRES_EVENT_LOG_SCHEMA_SQL, eventLogOps };
8
9
  const terminal = new Set(['completed', 'failed', 'cancelled']);
9
10
  export function memoryEventLog() {
@@ -34,7 +35,7 @@ export function memoryEventLog() {
34
35
  export function postgresEventLog(options) {
35
36
  const created = 'url' in options;
36
37
  const connected = created ? createPostgresClient(options.url) : options.sql;
37
- return createEventLogProjector('postgres-event-log', postgresStore(connected, created));
38
+ return createEventLogProjector('postgres-event-log', postgresStore(connected, created, options.additionalFields));
38
39
  }
39
40
  function createEventLogProjector(name, store) {
40
41
  return {
@@ -108,9 +109,6 @@ function mergeStart(existing, op) {
108
109
  attributes: existing && Object.keys(existing.attributes).length > 0
109
110
  ? existing.attributes
110
111
  : { ...op.attributes },
111
- tenant: existing?.tenant ?? op.tenant,
112
- project: existing?.project ?? op.project,
113
- org: existing?.org ?? op.org,
114
112
  startedAt: existing?.startedAt ?? op.at,
115
113
  updatedAt: Math.max(existing?.updatedAt ?? 0, op.at),
116
114
  completedAt: existing?.completedAt ?? null,
@@ -128,9 +126,6 @@ function mergeFinish(existing, op) {
128
126
  launchedByEffectId: existing?.launchedByEffectId ?? null,
129
127
  correlationId: existing?.correlationId ?? null,
130
128
  attributes: existing?.attributes ?? {},
131
- tenant: existing?.tenant ?? null,
132
- project: existing?.project ?? null,
133
- org: existing?.org ?? null,
134
129
  startedAt: existing?.startedAt ?? null,
135
130
  updatedAt: Math.max(existing?.updatedAt ?? 0, op.at),
136
131
  completedAt: existing?.completedAt ?? op.at,
@@ -139,15 +134,24 @@ function mergeFinish(existing, op) {
139
134
  function utcDate(ms) {
140
135
  return DateTime.toDateUtc(DateTime.makeUnsafe(ms));
141
136
  }
142
- function postgresStore(sql, ownsClient) {
137
+ /** Applied on every init; each statement is idempotent. */
138
+ const POSTGRES_EVENT_LOG_INIT_SQL = [
139
+ POSTGRES_EVENT_LOG_SCHEMA_SQL,
140
+ POSTGRES_SCHEMA_MIGRATIONS_SQL,
141
+ ].join('\n\n');
142
+ function postgresStore(sql, ownsClient, additionalFields) {
143
+ const columns = resolveReplicaColumns(additionalFields);
144
+ const attributeMigrations = postgresAttributeMigrations(additionalFields);
143
145
  return {
144
- init: () => runProjectorPromise('postgres-event-log', () => sql.unsafe(POSTGRES_EVENT_LOG_SCHEMA_SQL)).then(() => undefined),
146
+ init: () => runProjectorPromise('postgres-event-log', () => sql
147
+ .unsafe(POSTGRES_EVENT_LOG_INIT_SQL)
148
+ .then(() => applyPostgresMigrations(sql, attributeMigrations))),
145
149
  apply: (events) => {
146
150
  const ops = events.flatMap(eventLogOps);
147
151
  if (ops.length === 0) {
148
152
  return Promise.resolve();
149
153
  }
150
- return runProjectorPromise('postgres-event-log', () => sql.begin((tx) => applySqlOps(tx, ops))).then(() => undefined);
154
+ return runProjectorPromise('postgres-event-log', () => sql.begin((tx) => applySqlOps(tx, ops, columns))).then(() => undefined);
151
155
  },
152
156
  dispose: () => ownsClient
153
157
  ? runProjectorPromise('postgres-event-log', () => sql.end({ timeout: 5 })).then(() => undefined)
@@ -181,18 +185,18 @@ function runIndexPatches(ops) {
181
185
  }
182
186
  return [...patches.values()];
183
187
  }
184
- export function applySqlOps(sql, ops) {
188
+ export function applySqlOps(sql, ops, columns = []) {
185
189
  const events = ops.flatMap((op) => (op.type === 'insert' ? [envelopeFromEntry(op.entry)] : []));
186
- return Promise.all([insertRunEvents(sql, events), applyRunIndexOps(sql, ops)]).then(() => undefined);
190
+ return Promise.all([insertRunEvents(sql, events), applyRunIndexOps(sql, ops, columns)]).then(() => undefined);
187
191
  }
188
192
  /** Fold run-summary ops. Event rows are written by {@link insertRunEvents}. */
189
- export function applyRunIndexOps(sql, ops) {
193
+ export function applyRunIndexOps(sql, ops, columns = []) {
190
194
  const patches = runIndexPatches(ops);
191
195
  const upserts = patches.filter((patch) => patch.start !== null || patch.finish !== null);
192
196
  const touches = patches.filter((patch) => patch.start === null && patch.finish === null);
193
197
  const statements = [];
194
198
  if (upserts.length > 0) {
195
- statements.push(upsertRuns(sql, upserts));
199
+ statements.push(upsertRuns(sql, upserts, columns));
196
200
  }
197
201
  if (touches.length > 0) {
198
202
  statements.push(touchRuns(sql, touches));
@@ -248,8 +252,9 @@ function insertEventChunk(sql, events) {
248
252
  }
249
253
  // A finish in the batch sets the status; otherwise a finished run keeps its status and a
250
254
  // started run becomes running. Start fields fill only columns that are still empty.
251
- function upsertRuns(sql, patches) {
255
+ function upsertRuns(sql, patches, columns) {
252
256
  const rows = patches.map(({ runId, start, finish, completedAt, updatedAt }) => ({
257
+ ...hostColumnRow(columns, start?.attributes),
253
258
  run_id: runId,
254
259
  status: finish?.status ?? 'running',
255
260
  kind: start?.kind ?? null,
@@ -260,9 +265,6 @@ function upsertRuns(sql, patches) {
260
265
  launched_by_effect_id: start?.launchedByEffectId ?? null,
261
266
  correlation_id: start?.correlationId ?? null,
262
267
  attributes: sql.json(start?.attributes ?? {}),
263
- tenant: start?.tenant ?? null,
264
- project: start?.project ?? null,
265
- org: start?.org ?? null,
266
268
  started_at: start ? utcDate(start.at) : null,
267
269
  updated_at: utcDate(updatedAt),
268
270
  completed_at: completedAt === null ? null : utcDate(completedAt),
@@ -286,14 +288,16 @@ function upsertRuns(sql, patches) {
286
288
  WHEN looms_run_index.attributes = '{}'::jsonb THEN EXCLUDED.attributes
287
289
  ELSE looms_run_index.attributes
288
290
  END,
289
- tenant = COALESCE(looms_run_index.tenant, EXCLUDED.tenant),
290
- project = COALESCE(looms_run_index.project, EXCLUDED.project),
291
- org = COALESCE(looms_run_index.org, EXCLUDED.org),
291
+ ${columns.reduce((set, column) => sql `${set} ${sql(column.name)} = COALESCE(looms_run_index.${sql(column.name)}, EXCLUDED.${sql(column.name)}),`, sql ``)}
292
292
  started_at = COALESCE(looms_run_index.started_at, EXCLUDED.started_at),
293
293
  updated_at = GREATEST(looms_run_index.updated_at, EXCLUDED.updated_at),
294
294
  completed_at = COALESCE(looms_run_index.completed_at, EXCLUDED.completed_at)
295
295
  `.then(() => undefined);
296
296
  }
297
+ function hostColumnRow(columns, attributes) {
298
+ const values = columnValues(columns, attributes);
299
+ return Object.fromEntries(columns.map((column, index) => [column.name, values[index] ?? null]));
300
+ }
297
301
  function touchRuns(sql, patches) {
298
302
  const runIds = patches.map((patch) => patch.runId);
299
303
  const touchedAt = patches.map((patch) => DateTime.formatIso(DateTime.makeUnsafe(patch.updatedAt)));
@@ -0,0 +1,41 @@
1
+ import type { RunAttributeFields, RunAttributes } from '@swirls/looms/core';
2
+ /** Declared attributes with no fields. */
3
+ export type NoAdditionalFields = Record<never, never>;
4
+ export interface ReplicaPurgeOptions<Fields extends RunAttributeFields = RunAttributeFields> {
5
+ /** Delete event copies for runs that finished before this epoch millisecond. */
6
+ readonly finishedBefore: number;
7
+ /** Keep the run summary row. Defaults to true. */
8
+ readonly keepIndex?: boolean;
9
+ /** Only purge runs whose declared attributes equal these values. */
10
+ readonly where?: {
11
+ readonly [Key in keyof Fields & string]?: string;
12
+ };
13
+ }
14
+ /** A declared attribute and the `looms_run_index` column that stores it. */
15
+ export interface ResolvedReplicaColumn {
16
+ /** Attribute name, and the property name on the Drizzle table. */
17
+ readonly key: string;
18
+ /** SQL column name. */
19
+ readonly name: string;
20
+ readonly index: boolean;
21
+ }
22
+ export declare function resolveReplicaColumns(fields: RunAttributeFields | undefined): readonly ResolvedReplicaColumn[];
23
+ /** The `where` entries that are set, as columns, in declaration order. Undeclared keys are refused. */
24
+ export declare function purgeFilters(columns: readonly ResolvedReplicaColumn[], where: {
25
+ readonly [key: string]: string | undefined;
26
+ } | undefined): readonly {
27
+ readonly column: string;
28
+ readonly value: string;
29
+ }[];
30
+ /** Value for each declared column from a run's attributes, or null when the run lacks it. */
31
+ export declare function columnValues(columns: readonly ResolvedReplicaColumn[], attributes: RunAttributes | undefined): readonly (string | null)[];
32
+ export declare function sqlStringLiteral(value: string): string;
33
+ export interface ReplicaMigration {
34
+ readonly id: string;
35
+ readonly sql: string;
36
+ }
37
+ /**
38
+ * Migrations for declared attribute columns, after the Looms tables.
39
+ * Each column and each index is its own migration, so declaring one later only adds that file.
40
+ */
41
+ export declare function columnMigrations(fields: RunAttributeFields | undefined, migration: (id: string, sql: string) => ReplicaMigration, columnSql: (column: ResolvedReplicaColumn) => string, indexSql: (column: ResolvedReplicaColumn) => string): readonly ReplicaMigration[];
@@ -0,0 +1,77 @@
1
+ /** Postgres caps identifiers at 63 bytes, and the index name adds `looms_run_index_`. */
2
+ const COLUMN_NAME = /^[a-z_][a-z0-9_]{0,46}$/;
3
+ const LOOMS_COLUMNS = new Set([
4
+ 'run_id',
5
+ 'status',
6
+ 'kind',
7
+ 'definition_name',
8
+ 'definition_version',
9
+ 'root_thread_id',
10
+ 'parent_run_id',
11
+ 'launched_by_effect_id',
12
+ 'correlation_id',
13
+ 'attributes',
14
+ 'started_at',
15
+ 'updated_at',
16
+ 'completed_at',
17
+ 'replicated_seq',
18
+ 'purged_at',
19
+ ]);
20
+ function snakeCase(key) {
21
+ return key
22
+ .replaceAll(/([A-Z]+)([A-Z][a-z])/g, '$1_$2')
23
+ .replaceAll(/([a-z0-9])([A-Z])/g, '$1_$2')
24
+ .replaceAll(/[^A-Za-z0-9_]/g, '_')
25
+ .toLowerCase();
26
+ }
27
+ export function resolveReplicaColumns(fields) {
28
+ const names = new Map();
29
+ return Object.entries(fields ?? {}).map(([key, field]) => {
30
+ const name = field.fieldName ?? snakeCase(key);
31
+ if (!COLUMN_NAME.test(name)) {
32
+ throw new Error(`Attribute "${key}" maps to column "${name}". Column names are lowercase snake_case, start with a letter or underscore, and are at most 47 characters; set fieldName.`);
33
+ }
34
+ if (LOOMS_COLUMNS.has(name)) {
35
+ throw new Error(`Attribute "${key}" maps to column "${name}", which Looms owns. Set fieldName.`);
36
+ }
37
+ const clash = names.get(name);
38
+ if (clash !== undefined) {
39
+ throw new Error(`Attributes "${clash}" and "${key}" both map to column "${name}".`);
40
+ }
41
+ names.set(name, key);
42
+ return { key, name, index: field.index === true };
43
+ });
44
+ }
45
+ /** The `where` entries that are set, as columns, in declaration order. Undeclared keys are refused. */
46
+ export function purgeFilters(columns, where) {
47
+ if (where === undefined) {
48
+ return [];
49
+ }
50
+ const declared = new Set(columns.map((column) => column.key));
51
+ for (const key of Object.keys(where)) {
52
+ if (!declared.has(key)) {
53
+ throw new Error(`purge where.${key} is not a declared attribute.`);
54
+ }
55
+ }
56
+ return columns.flatMap((column) => {
57
+ const value = where[column.key];
58
+ return value === undefined ? [] : [{ column: column.name, value }];
59
+ });
60
+ }
61
+ /** Value for each declared column from a run's attributes, or null when the run lacks it. */
62
+ export function columnValues(columns, attributes) {
63
+ return columns.map((column) => attributes?.[column.key] ?? null);
64
+ }
65
+ export function sqlStringLiteral(value) {
66
+ return `'${value.replaceAll("'", "''")}'`;
67
+ }
68
+ /**
69
+ * Migrations for declared attribute columns, after the Looms tables.
70
+ * Each column and each index is its own migration, so declaring one later only adds that file.
71
+ */
72
+ export function columnMigrations(fields, migration, columnSql, indexSql) {
73
+ return resolveReplicaColumns(fields).flatMap((column) => {
74
+ const added = migration(`column_${column.name}`, columnSql(column));
75
+ return column.index ? [added, migration(`index_${column.name}`, indexSql(column))] : [added];
76
+ });
77
+ }