@dromio/execution 0.1.42 → 0.1.43

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.
@@ -0,0 +1,5 @@
1
+ export * from "./memory-store.js";
2
+ export * from "./service.js";
3
+ export * from "./types.js";
4
+ export * from "./sqlite-store.js";
5
+ export * from "./postgres-store.js";
package/dist/index.js ADDED
@@ -0,0 +1,5 @@
1
+ export * from "./memory-store.js";
2
+ export * from "./service.js";
3
+ export * from "./types.js";
4
+ export * from "./sqlite-store.js";
5
+ export * from "./postgres-store.js";
@@ -0,0 +1,9 @@
1
+ import type { ExecutionAttempt, ExecutionRun, ExecutionStore, ExecutionTransaction } from "./types.js";
2
+ export declare class MemoryExecutionStore implements ExecutionStore {
3
+ private state;
4
+ private pending;
5
+ transaction<Result>(work: (transaction: ExecutionTransaction) => Result): Promise<Result>;
6
+ listRuns(): Promise<readonly ExecutionRun[]>;
7
+ listAttempts(runId: string): Promise<readonly ExecutionAttempt[]>;
8
+ purgeThread(threadId: string): Promise<number>;
9
+ }
@@ -0,0 +1,55 @@
1
+ export class MemoryExecutionStore {
2
+ state = { runs: new Map(), attempts: new Map(), fencing: new Map() };
3
+ pending = Promise.resolve();
4
+ async transaction(work) {
5
+ const previous = this.pending;
6
+ let release = () => undefined;
7
+ this.pending = new Promise((resolve) => { release = resolve; });
8
+ await previous;
9
+ try {
10
+ const draft = structuredClone(this.state);
11
+ const result = work(transactionFor(draft));
12
+ this.state = draft;
13
+ return result;
14
+ }
15
+ finally {
16
+ release();
17
+ }
18
+ }
19
+ async listRuns() {
20
+ return structuredClone([...this.state.runs.values()]);
21
+ }
22
+ async listAttempts(runId) {
23
+ return structuredClone(this.state.attempts.get(runId) ?? []);
24
+ }
25
+ async purgeThread(threadId) { let count = 0; for (const [id, run] of this.state.runs)
26
+ if (run.payload?.threadId === threadId) {
27
+ this.state.runs.delete(id);
28
+ this.state.attempts.delete(id);
29
+ this.state.fencing.delete(id);
30
+ count += 1;
31
+ } return count; }
32
+ }
33
+ function transactionFor(state) {
34
+ return {
35
+ getRun: (id) => state.runs.get(id),
36
+ findByIdempotency: (tenantId, applicationId, key) => [...state.runs.values()].find((run) => run.tenantId === tenantId && run.applicationId === applicationId && run.idempotencyKey === key),
37
+ listRuns: () => [...state.runs.values()],
38
+ putRun: (run) => state.runs.set(run.id, structuredClone(run)),
39
+ listAttempts: (runId) => structuredClone(state.attempts.get(runId) ?? []),
40
+ putAttempt: (attempt) => {
41
+ const attempts = state.attempts.get(attempt.runId) ?? [];
42
+ const index = attempts.findIndex((candidate) => candidate.id === attempt.id);
43
+ if (index === -1)
44
+ attempts.push(structuredClone(attempt));
45
+ else
46
+ attempts[index] = structuredClone(attempt);
47
+ state.attempts.set(attempt.runId, attempts);
48
+ },
49
+ nextFencingToken: (runId) => {
50
+ const token = (state.fencing.get(runId) ?? 0) + 1;
51
+ state.fencing.set(runId, token);
52
+ return token;
53
+ },
54
+ };
55
+ }
@@ -0,0 +1,22 @@
1
+ import type { ExecutionAttempt, ExecutionRun, ExecutionStore, ExecutionTransaction } from "./types.js";
2
+ type SqlValue = string | number | null;
3
+ export interface ExecutionPostgresClient {
4
+ query<Row extends object = Record<string, never>>(text: string, values?: readonly SqlValue[]): Promise<{
5
+ readonly rows: readonly Row[];
6
+ }>;
7
+ release(): void;
8
+ }
9
+ export interface ExecutionPostgresPool {
10
+ connect(): Promise<ExecutionPostgresClient>;
11
+ query(text: string): Promise<unknown>;
12
+ }
13
+ export declare class PostgresExecutionStore implements ExecutionStore {
14
+ private readonly pool;
15
+ constructor(pool: ExecutionPostgresPool);
16
+ migrate(): Promise<void>;
17
+ transaction<Result>(work: (transaction: ExecutionTransaction) => Result): Promise<Result>;
18
+ listRuns(): Promise<readonly ExecutionRun[]>;
19
+ listAttempts(runId: string): Promise<readonly ExecutionAttempt[]>;
20
+ purgeThread(threadId: string): Promise<number>;
21
+ }
22
+ export {};
@@ -0,0 +1,79 @@
1
+ const migration = `
2
+ CREATE TABLE IF NOT EXISTS execution_runs (id TEXT PRIMARY KEY, tenant_id TEXT NOT NULL, application_id TEXT NOT NULL, idempotency_key TEXT NOT NULL, resource_json TEXT NOT NULL, UNIQUE(tenant_id,application_id,idempotency_key));
3
+ CREATE TABLE IF NOT EXISTS execution_attempts (id TEXT PRIMARY KEY, run_id TEXT NOT NULL, number INTEGER NOT NULL, resource_json TEXT NOT NULL, UNIQUE(run_id,number));
4
+ CREATE TABLE IF NOT EXISTS execution_fencing (run_id TEXT PRIMARY KEY, value INTEGER NOT NULL);
5
+ `;
6
+ export class PostgresExecutionStore {
7
+ pool;
8
+ constructor(pool) {
9
+ this.pool = pool;
10
+ }
11
+ async migrate() { await this.pool.query(migration); }
12
+ async transaction(work) {
13
+ const client = await this.pool.connect();
14
+ await client.query("BEGIN");
15
+ try {
16
+ await client.query("SELECT pg_advisory_xact_lock(hashtext('dromio_execution'))");
17
+ const state = await load(client);
18
+ const result = work(transactionFor(state));
19
+ await persist(client, state);
20
+ await client.query("COMMIT");
21
+ return result;
22
+ }
23
+ catch (error) {
24
+ await client.query("ROLLBACK");
25
+ throw error;
26
+ }
27
+ finally {
28
+ client.release();
29
+ }
30
+ }
31
+ async listRuns() { const client = await this.pool.connect(); try {
32
+ return (await client.query("SELECT resource_json FROM execution_runs ORDER BY id")).rows.map((parse));
33
+ }
34
+ finally {
35
+ client.release();
36
+ } }
37
+ async listAttempts(runId) { const client = await this.pool.connect(); try {
38
+ return (await client.query("SELECT resource_json FROM execution_attempts WHERE run_id=$1 ORDER BY number", [runId])).rows.map((parse));
39
+ }
40
+ finally {
41
+ client.release();
42
+ } }
43
+ async purgeThread(threadId) { const client = await this.pool.connect(); await client.query("BEGIN"); try {
44
+ const runs = await client.query("SELECT id FROM execution_runs WHERE resource_json::jsonb->'payload'->>'threadId'=$1 FOR UPDATE", [threadId]);
45
+ for (const row of runs.rows) {
46
+ await client.query("DELETE FROM execution_attempts WHERE run_id=$1", [row.id]);
47
+ await client.query("DELETE FROM execution_fencing WHERE run_id=$1", [row.id]);
48
+ await client.query("DELETE FROM execution_runs WHERE id=$1", [row.id]);
49
+ }
50
+ await client.query("COMMIT");
51
+ return runs.rows.length;
52
+ }
53
+ catch (error) {
54
+ await client.query("ROLLBACK");
55
+ throw error;
56
+ }
57
+ finally {
58
+ client.release();
59
+ } }
60
+ }
61
+ async function load(client) { const [runs, attempts, fencing] = await Promise.all([client.query("SELECT resource_json FROM execution_runs FOR UPDATE"), client.query("SELECT resource_json FROM execution_attempts FOR UPDATE"), client.query("SELECT run_id,value FROM execution_fencing FOR UPDATE")]); const state = { runs: new Map(), attempts: new Map(), fencing: new Map(fencing.rows.map((row) => [row.run_id, row.value])) }; for (const row of runs.rows) {
62
+ const value = parse(row);
63
+ state.runs.set(value.id, value);
64
+ } for (const row of attempts.rows) {
65
+ const value = parse(row);
66
+ const values = state.attempts.get(value.runId) ?? [];
67
+ values.push(value);
68
+ state.attempts.set(value.runId, values);
69
+ } return state; }
70
+ function transactionFor(state) { return { getRun: (id) => state.runs.get(id), findByIdempotency: (tenantId, applicationId, key) => [...state.runs.values()].find((value) => value.tenantId === tenantId && value.applicationId === applicationId && value.idempotencyKey === key), listRuns: () => [...state.runs.values()], putRun: (value) => { state.runs.set(value.id, value); }, listAttempts: (runId) => state.attempts.get(runId) ?? [], putAttempt: (value) => { const values = state.attempts.get(value.runId) ?? []; const index = values.findIndex((item) => item.id === value.id); if (index < 0)
71
+ values.push(value);
72
+ else
73
+ values[index] = value; state.attempts.set(value.runId, values); }, nextFencingToken: (runId) => { const next = (state.fencing.get(runId) ?? 0) + 1; state.fencing.set(runId, next); return next; } }; }
74
+ async function persist(client, state) { for (const value of state.runs.values())
75
+ await client.query("INSERT INTO execution_runs (id,tenant_id,application_id,idempotency_key,resource_json) VALUES ($1,$2,$3,$4,$5) ON CONFLICT(id) DO UPDATE SET resource_json=EXCLUDED.resource_json", [value.id, value.tenantId, value.applicationId, value.idempotencyKey, JSON.stringify(value)]); for (const values of state.attempts.values())
76
+ for (const value of values)
77
+ await client.query("INSERT INTO execution_attempts (id,run_id,number,resource_json) VALUES ($1,$2,$3,$4) ON CONFLICT(id) DO UPDATE SET resource_json=EXCLUDED.resource_json", [value.id, value.runId, value.number, JSON.stringify(value)]); for (const [runId, value] of state.fencing)
78
+ await client.query("INSERT INTO execution_fencing (run_id,value) VALUES ($1,$2) ON CONFLICT(run_id) DO UPDATE SET value=EXCLUDED.value", [runId, value]); }
79
+ function parse(row) { return JSON.parse(row.resource_json); }
@@ -0,0 +1,40 @@
1
+ import type { ClaimedExecution, EnqueueRunInput, ExecutionAttempt, ExecutionClock, ExecutionIdFactory, ExecutionRun, ExecutionStore, ExecutionWaitpoint, JsonValue } from "./types.js";
2
+ export declare class ExecutionError extends Error {
3
+ readonly code: "not_found" | "stale_fence" | "invalid_state" | "cancellation_requested" | "idempotency_conflict";
4
+ constructor(code: "not_found" | "stale_fence" | "invalid_state" | "cancellation_requested" | "idempotency_conflict", message: string);
5
+ }
6
+ export declare class ExecutionService {
7
+ private readonly store;
8
+ private readonly clock;
9
+ private readonly ids;
10
+ constructor(options: {
11
+ readonly store: ExecutionStore;
12
+ readonly clock?: ExecutionClock;
13
+ readonly ids?: ExecutionIdFactory;
14
+ });
15
+ getRun(runId: string): Promise<ExecutionRun | undefined>;
16
+ listRuns(): Promise<readonly ExecutionRun[]>;
17
+ listAttempts(runId: string): Promise<readonly ExecutionAttempt[]>;
18
+ listSignals(runId: string, after?: number): Promise<readonly import("./types.js").ExecutionSignal[]>;
19
+ purgeThread(threadId: string): Promise<number>;
20
+ enqueue(input: EnqueueRunInput): Promise<ExecutionRun>;
21
+ claim(input: {
22
+ readonly workerId: string;
23
+ readonly queues: readonly string[];
24
+ readonly leaseMs: number;
25
+ }): Promise<ClaimedExecution | undefined>;
26
+ heartbeat(runId: string, attemptId: string, fencingToken: number, leaseMs: number): Promise<ExecutionAttempt>;
27
+ wait(runId: string, attemptId: string, fencingToken: number, waitpoint: ExecutionWaitpoint): Promise<ExecutionRun>;
28
+ resume(runId: string, waitpointKey: string): Promise<ExecutionRun>;
29
+ complete(runId: string, attemptId: string, fencingToken: number, result?: Readonly<Record<string, JsonValue>>): Promise<ExecutionRun>;
30
+ fail(runId: string, attemptId: string, fencingToken: number, errorCode: string, retryable: boolean): Promise<ExecutionRun>;
31
+ acknowledgeCancellation(runId: string, attemptId: string, fencingToken: number): Promise<ExecutionRun>;
32
+ cancel(runId: string): Promise<ExecutionRun>;
33
+ signal(runId: string, input: {
34
+ readonly commandId: string;
35
+ readonly type: "steer";
36
+ readonly payload: Readonly<Record<string, JsonValue>>;
37
+ }): Promise<import("./types.js").ExecutionSignal>;
38
+ retry(runId: string): Promise<ExecutionRun>;
39
+ private updateAttempt;
40
+ }
@@ -0,0 +1,346 @@
1
+ export class ExecutionError extends Error {
2
+ code;
3
+ constructor(code, message) {
4
+ super(message);
5
+ this.code = code;
6
+ this.name = "ExecutionError";
7
+ }
8
+ }
9
+ export class ExecutionService {
10
+ store;
11
+ clock;
12
+ ids;
13
+ constructor(options) {
14
+ this.store = options.store;
15
+ this.clock = options.clock ?? { now: () => new Date() };
16
+ this.ids = options.ids ?? {
17
+ create: (kind) => `${kind}_${crypto.randomUUID()}`,
18
+ };
19
+ }
20
+ async getRun(runId) {
21
+ return (await this.store.listRuns()).find((run) => run.id === runId);
22
+ }
23
+ listRuns() {
24
+ return this.store.listRuns();
25
+ }
26
+ listAttempts(runId) {
27
+ return this.store.listAttempts(runId);
28
+ }
29
+ async listSignals(runId, after = 0) {
30
+ return ((await this.getRun(runId))?.signals?.filter((signal) => signal.ordinal > after) ?? []);
31
+ }
32
+ purgeThread(threadId) {
33
+ return this.store.purgeThread(threadId);
34
+ }
35
+ async enqueue(input) {
36
+ return this.store.transaction((tx) => {
37
+ const existing = tx.findByIdempotency(input.tenantId, input.applicationId, input.idempotencyKey);
38
+ if (existing) {
39
+ if (existing.sourceId !== input.sourceId ||
40
+ existing.sourceType !== input.sourceType) {
41
+ throw new ExecutionError("idempotency_conflict", "The idempotency key belongs to another execution source.");
42
+ }
43
+ return existing;
44
+ }
45
+ const now = this.clock.now().toISOString();
46
+ const run = {
47
+ id: this.ids.create("run"),
48
+ tenantId: input.tenantId,
49
+ applicationId: input.applicationId,
50
+ sourceType: input.sourceType,
51
+ sourceId: input.sourceId,
52
+ idempotencyKey: input.idempotencyKey,
53
+ correlationId: input.correlationId,
54
+ requestId: input.requestId,
55
+ commandId: input.commandId,
56
+ queue: input.queue ?? "default",
57
+ priority: input.priority ?? 0,
58
+ status: "queued",
59
+ maxAttempts: Math.max(1, input.maxAttempts ?? 3),
60
+ attemptCount: 0,
61
+ availableAt: now,
62
+ createdAt: now,
63
+ updatedAt: now,
64
+ ...(input.concurrencyKey
65
+ ? { concurrencyKey: input.concurrencyKey }
66
+ : {}),
67
+ ...(input.payload ? { payload: input.payload } : {}),
68
+ };
69
+ tx.putRun(run);
70
+ return run;
71
+ });
72
+ }
73
+ async claim(input) {
74
+ return this.store.transaction((tx) => {
75
+ const now = this.clock.now();
76
+ expireLeases(tx, now);
77
+ const run = tx
78
+ .listRuns()
79
+ .filter((candidate) => candidate.status === "queued" &&
80
+ input.queues.includes(candidate.queue) &&
81
+ new Date(candidate.availableAt) <= now)
82
+ .filter((candidate) => !candidate.concurrencyKey || concurrencyAvailable(tx, candidate))
83
+ .sort((left, right) => right.priority - left.priority ||
84
+ left.createdAt.localeCompare(right.createdAt))[0];
85
+ if (!run)
86
+ return undefined;
87
+ const attempt = {
88
+ id: this.ids.create("attempt"),
89
+ runId: run.id,
90
+ correlationId: run.correlationId,
91
+ number: run.attemptCount + 1,
92
+ status: "leased",
93
+ workerId: input.workerId,
94
+ fencingToken: tx.nextFencingToken(run.id),
95
+ leaseExpiresAt: new Date(now.getTime() + input.leaseMs).toISOString(),
96
+ startedAt: now.toISOString(),
97
+ heartbeatAt: now.toISOString(),
98
+ };
99
+ const claimed = {
100
+ ...run,
101
+ status: "running",
102
+ attemptCount: attempt.number,
103
+ updatedAt: now.toISOString(),
104
+ };
105
+ tx.putRun(claimed);
106
+ tx.putAttempt(attempt);
107
+ return { run: claimed, attempt };
108
+ });
109
+ }
110
+ async heartbeat(runId, attemptId, fencingToken, leaseMs) {
111
+ return this.updateAttempt(runId, attemptId, fencingToken, (run, attempt, now, tx) => {
112
+ assertNotCancelling(run);
113
+ const updated = {
114
+ ...attempt,
115
+ status: "running",
116
+ heartbeatAt: now.toISOString(),
117
+ leaseExpiresAt: new Date(now.getTime() + leaseMs).toISOString(),
118
+ };
119
+ tx.putAttempt(updated);
120
+ tx.putRun({ ...run, updatedAt: now.toISOString() });
121
+ return updated;
122
+ });
123
+ }
124
+ async wait(runId, attemptId, fencingToken, waitpoint) {
125
+ return this.updateAttempt(runId, attemptId, fencingToken, (run, attempt, now, tx) => {
126
+ assertNotCancelling(run);
127
+ tx.putAttempt({
128
+ ...attempt,
129
+ status: "waiting",
130
+ completedAt: now.toISOString(),
131
+ });
132
+ const updated = {
133
+ ...run,
134
+ status: "waiting",
135
+ waitpoint,
136
+ resumedFrom: undefined,
137
+ updatedAt: now.toISOString(),
138
+ };
139
+ tx.putRun(updated);
140
+ return updated;
141
+ });
142
+ }
143
+ async resume(runId, waitpointKey) {
144
+ return this.store.transaction((tx) => {
145
+ const run = requireRun(tx, runId);
146
+ if (run.status !== "waiting" || run.waitpoint?.key !== waitpointKey)
147
+ throw new ExecutionError("invalid_state", "Run is not waiting at this waitpoint.");
148
+ const now = this.clock.now().toISOString();
149
+ const updated = {
150
+ ...run,
151
+ status: "queued",
152
+ resumedFrom: { waitpoint: run.waitpoint, resumedAt: now },
153
+ waitpoint: undefined,
154
+ availableAt: now,
155
+ updatedAt: now,
156
+ };
157
+ tx.putRun(updated);
158
+ return updated;
159
+ });
160
+ }
161
+ async complete(runId, attemptId, fencingToken, result = {}) {
162
+ return this.updateAttempt(runId, attemptId, fencingToken, (run, attempt, now, tx) => {
163
+ assertNotCancelling(run);
164
+ tx.putAttempt({
165
+ ...attempt,
166
+ status: "completed",
167
+ completedAt: now.toISOString(),
168
+ });
169
+ const updated = {
170
+ ...run,
171
+ status: "completed",
172
+ result,
173
+ updatedAt: now.toISOString(),
174
+ };
175
+ tx.putRun(updated);
176
+ return updated;
177
+ });
178
+ }
179
+ async fail(runId, attemptId, fencingToken, errorCode, retryable) {
180
+ return this.updateAttempt(runId, attemptId, fencingToken, (run, attempt, now, tx) => {
181
+ assertNotCancelling(run);
182
+ tx.putAttempt({
183
+ ...attempt,
184
+ status: "failed",
185
+ completedAt: now.toISOString(),
186
+ });
187
+ const retry = retryable &&
188
+ run.attemptCount < run.maxAttempts &&
189
+ !run.cancellationRequestedAt;
190
+ const delayMs = retry
191
+ ? Math.min(60_000, 1_000 * 2 ** (run.attemptCount - 1))
192
+ : 0;
193
+ const updated = {
194
+ ...run,
195
+ status: retry ? "queued" : "failed",
196
+ availableAt: new Date(now.getTime() + delayMs).toISOString(),
197
+ updatedAt: now.toISOString(),
198
+ errorCode,
199
+ };
200
+ tx.putRun(updated);
201
+ return updated;
202
+ });
203
+ }
204
+ async acknowledgeCancellation(runId, attemptId, fencingToken) {
205
+ return this.updateAttempt(runId, attemptId, fencingToken, (run, attempt, now, tx) => {
206
+ if (run.status !== "cancelling") {
207
+ throw new ExecutionError("invalid_state", "Only a cancelling run can acknowledge cancellation.");
208
+ }
209
+ tx.putAttempt({
210
+ ...attempt,
211
+ status: "cancelled",
212
+ completedAt: now.toISOString(),
213
+ });
214
+ const updated = {
215
+ ...run,
216
+ status: "cancelled",
217
+ updatedAt: now.toISOString(),
218
+ };
219
+ tx.putRun(updated);
220
+ return updated;
221
+ });
222
+ }
223
+ async cancel(runId) {
224
+ return this.store.transaction((tx) => {
225
+ const run = requireRun(tx, runId);
226
+ if (run.status === "completed" ||
227
+ run.status === "failed" ||
228
+ run.status === "cancelled")
229
+ return run;
230
+ const now = this.clock.now().toISOString();
231
+ const immediate = run.status === "queued" || run.status === "waiting";
232
+ const updated = {
233
+ ...run,
234
+ status: immediate ? "cancelled" : "cancelling",
235
+ cancellationRequestedAt: now,
236
+ updatedAt: now,
237
+ };
238
+ tx.putRun(updated);
239
+ return updated;
240
+ });
241
+ }
242
+ async signal(runId, input) {
243
+ return this.store.transaction((tx) => {
244
+ const run = requireRun(tx, runId);
245
+ const existing = run.signals?.find((signal) => signal.commandId === input.commandId);
246
+ if (existing)
247
+ return existing;
248
+ if (run.status !== "running")
249
+ throw new ExecutionError("invalid_state", "Execution signals require a running run.");
250
+ const signals = run.signals ?? [];
251
+ const signal = {
252
+ id: this.ids.create("signal"),
253
+ ordinal: signals.length + 1,
254
+ ...input,
255
+ createdAt: this.clock.now().toISOString(),
256
+ };
257
+ tx.putRun({
258
+ ...run,
259
+ signals: [...signals, signal],
260
+ updatedAt: signal.createdAt,
261
+ });
262
+ return signal;
263
+ });
264
+ }
265
+ async retry(runId) {
266
+ return this.store.transaction((tx) => {
267
+ const run = requireRun(tx, runId);
268
+ if (run.status !== "failed" && run.status !== "cancelled")
269
+ throw new ExecutionError("invalid_state", "Only failed or cancelled runs can be retried manually.");
270
+ const now = this.clock.now().toISOString();
271
+ const updated = {
272
+ ...run,
273
+ status: "queued",
274
+ availableAt: now,
275
+ updatedAt: now,
276
+ cancellationRequestedAt: undefined,
277
+ errorCode: undefined,
278
+ maxAttempts: Math.max(run.maxAttempts, run.attemptCount + 1),
279
+ };
280
+ tx.putRun(updated);
281
+ return updated;
282
+ });
283
+ }
284
+ async updateAttempt(runId, attemptId, fencingToken, work) {
285
+ return this.store.transaction((tx) => {
286
+ const run = requireRun(tx, runId);
287
+ const attempt = tx
288
+ .listAttempts(runId)
289
+ .find((candidate) => candidate.id === attemptId);
290
+ if (!attempt)
291
+ throw new ExecutionError("not_found", `Attempt ${attemptId} was not found.`);
292
+ if (attempt.fencingToken !== fencingToken ||
293
+ tx
294
+ .listAttempts(runId)
295
+ .some((candidate) => candidate.fencingToken > fencingToken)) {
296
+ throw new ExecutionError("stale_fence", "The attempt fencing token is stale.");
297
+ }
298
+ return work(run, attempt, this.clock.now(), tx);
299
+ });
300
+ }
301
+ }
302
+ function assertNotCancelling(run) {
303
+ if (run.status === "cancelling") {
304
+ throw new ExecutionError("cancellation_requested", "Execution cancellation was requested.");
305
+ }
306
+ }
307
+ function expireLeases(tx, now) {
308
+ for (const run of tx.listRuns()) {
309
+ if (run.status !== "running" && run.status !== "cancelling")
310
+ continue;
311
+ const attempt = tx.listAttempts(run.id).at(-1);
312
+ if (!attempt || new Date(attempt.leaseExpiresAt) > now)
313
+ continue;
314
+ tx.putAttempt({
315
+ ...attempt,
316
+ status: "expired",
317
+ completedAt: now.toISOString(),
318
+ });
319
+ const retry = run.attemptCount < run.maxAttempts && !run.cancellationRequestedAt;
320
+ tx.putRun({
321
+ ...run,
322
+ status: retry
323
+ ? "queued"
324
+ : run.cancellationRequestedAt
325
+ ? "cancelled"
326
+ : "failed",
327
+ availableAt: now.toISOString(),
328
+ updatedAt: now.toISOString(),
329
+ ...(retry ? {} : { errorCode: "lease_expired" }),
330
+ });
331
+ }
332
+ }
333
+ function concurrencyAvailable(tx, candidate) {
334
+ return !tx
335
+ .listRuns()
336
+ .some((run) => run.id !== candidate.id &&
337
+ run.tenantId === candidate.tenantId &&
338
+ run.concurrencyKey === candidate.concurrencyKey &&
339
+ (run.status === "running" || run.status === "cancelling"));
340
+ }
341
+ function requireRun(tx, runId) {
342
+ const run = tx.getRun(runId);
343
+ if (!run)
344
+ throw new ExecutionError("not_found", `Run ${runId} was not found.`);
345
+ return run;
346
+ }
@@ -0,0 +1,11 @@
1
+ import { Database } from "bun:sqlite";
2
+ import type { ExecutionAttempt, ExecutionRun, ExecutionStore, ExecutionTransaction } from "./types.js";
3
+ export declare class SqliteExecutionStore implements ExecutionStore {
4
+ private readonly database;
5
+ constructor(database: Database);
6
+ transaction<Result>(work: (transaction: ExecutionTransaction) => Result): Promise<Result>;
7
+ listRuns(): Promise<readonly ExecutionRun[]>;
8
+ listAttempts(runId: string): Promise<readonly ExecutionAttempt[]>;
9
+ purgeThread(threadId: string): Promise<number>;
10
+ private tx;
11
+ }
@@ -0,0 +1,54 @@
1
+ const migration = `
2
+ CREATE TABLE IF NOT EXISTS execution_runs (id TEXT PRIMARY KEY, tenant_id TEXT NOT NULL, application_id TEXT NOT NULL, idempotency_key TEXT NOT NULL, resource_json TEXT NOT NULL, UNIQUE(tenant_id,application_id,idempotency_key));
3
+ CREATE TABLE IF NOT EXISTS execution_attempts (id TEXT PRIMARY KEY, run_id TEXT NOT NULL, number INTEGER NOT NULL, resource_json TEXT NOT NULL, UNIQUE(run_id,number));
4
+ CREATE TABLE IF NOT EXISTS execution_fencing (run_id TEXT PRIMARY KEY, value INTEGER NOT NULL);
5
+ `;
6
+ export class SqliteExecutionStore {
7
+ database;
8
+ constructor(database) {
9
+ this.database = database;
10
+ database.exec("PRAGMA busy_timeout=5000; PRAGMA journal_mode=WAL;");
11
+ database.exec(migration);
12
+ }
13
+ async transaction(work) {
14
+ this.database.exec("BEGIN IMMEDIATE");
15
+ try {
16
+ const result = work(this.tx());
17
+ this.database.exec("COMMIT");
18
+ return result;
19
+ }
20
+ catch (error) {
21
+ this.database.exec("ROLLBACK");
22
+ throw error;
23
+ }
24
+ }
25
+ async listRuns() { return this.database.query("SELECT resource_json FROM execution_runs ORDER BY id").all().map((parse)); }
26
+ async listAttempts(runId) { return this.database.query("SELECT resource_json FROM execution_attempts WHERE run_id=? ORDER BY number").all(runId).map((parse)); }
27
+ async purgeThread(threadId) { const ids = (await this.listRuns()).filter((run) => run.payload?.threadId === threadId).map((run) => run.id); this.database.exec("BEGIN IMMEDIATE"); try {
28
+ for (const id of ids) {
29
+ this.database.query("DELETE FROM execution_attempts WHERE run_id=?").run(id);
30
+ this.database.query("DELETE FROM execution_fencing WHERE run_id=?").run(id);
31
+ this.database.query("DELETE FROM execution_runs WHERE id=?").run(id);
32
+ }
33
+ this.database.exec("COMMIT");
34
+ return ids.length;
35
+ }
36
+ catch (error) {
37
+ this.database.exec("ROLLBACK");
38
+ throw error;
39
+ } }
40
+ tx() {
41
+ return {
42
+ getRun: (id) => optional(this.database.query("SELECT resource_json FROM execution_runs WHERE id=?").get(id)),
43
+ findByIdempotency: (tenantId, applicationId, key) => optional(this.database.query("SELECT resource_json FROM execution_runs WHERE tenant_id=? AND application_id=? AND idempotency_key=?").get(tenantId, applicationId, key)),
44
+ listRuns: () => this.database.query("SELECT resource_json FROM execution_runs ORDER BY id").all().map((parse)),
45
+ putRun: (value) => { this.database.query("INSERT INTO execution_runs (id,tenant_id,application_id,idempotency_key,resource_json) VALUES (?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET resource_json=excluded.resource_json").run(value.id, value.tenantId, value.applicationId, value.idempotencyKey, JSON.stringify(value)); },
46
+ listAttempts: (runId) => this.database.query("SELECT resource_json FROM execution_attempts WHERE run_id=? ORDER BY number").all(runId).map((parse)),
47
+ putAttempt: (value) => { this.database.query("INSERT INTO execution_attempts (id,run_id,number,resource_json) VALUES (?,?,?,?) ON CONFLICT(id) DO UPDATE SET resource_json=excluded.resource_json").run(value.id, value.runId, value.number, JSON.stringify(value)); },
48
+ nextFencingToken: (runId) => this.database.query("INSERT INTO execution_fencing (run_id,value) VALUES (?,1) ON CONFLICT(run_id) DO UPDATE SET value=value+1 RETURNING value").get(runId).value,
49
+ };
50
+ }
51
+ }
52
+ function parse(row) { if (!row || typeof row !== "object" || !("resource_json" in row) || typeof row.resource_json !== "string")
53
+ throw new Error("Execution row is invalid."); return JSON.parse(row.resource_json); }
54
+ function optional(row) { return row ? parse(row) : undefined; }
@@ -0,0 +1,103 @@
1
+ export type ExecutionRunStatus = "queued" | "running" | "waiting" | "cancelling" | "completed" | "failed" | "cancelled";
2
+ export type ExecutionAttemptStatus = "leased" | "running" | "waiting" | "completed" | "failed" | "cancelled" | "expired";
3
+ export interface ExecutionRun {
4
+ readonly id: string;
5
+ readonly tenantId: string;
6
+ readonly applicationId: string;
7
+ readonly sourceType: "thread_turn" | "workflow" | "task";
8
+ readonly sourceId: string;
9
+ readonly idempotencyKey: string;
10
+ readonly correlationId: string;
11
+ readonly requestId: string;
12
+ readonly commandId: string;
13
+ readonly queue: string;
14
+ readonly priority: number;
15
+ readonly status: ExecutionRunStatus;
16
+ readonly maxAttempts: number;
17
+ readonly attemptCount: number;
18
+ readonly availableAt: string;
19
+ readonly createdAt: string;
20
+ readonly updatedAt: string;
21
+ readonly concurrencyKey?: string;
22
+ readonly waitpoint?: ExecutionWaitpoint;
23
+ readonly resumedFrom?: ExecutionResumePoint;
24
+ readonly cancellationRequestedAt?: string;
25
+ readonly result?: Readonly<Record<string, JsonValue>>;
26
+ readonly errorCode?: string;
27
+ readonly payload?: Readonly<Record<string, JsonValue>>;
28
+ readonly signals?: readonly ExecutionSignal[];
29
+ }
30
+ export interface ExecutionSignal {
31
+ readonly id: string;
32
+ readonly ordinal: number;
33
+ readonly type: "steer";
34
+ readonly commandId: string;
35
+ readonly payload: Readonly<Record<string, JsonValue>>;
36
+ readonly createdAt: string;
37
+ }
38
+ export interface ExecutionAttempt {
39
+ readonly id: string;
40
+ readonly runId: string;
41
+ readonly correlationId: string;
42
+ readonly number: number;
43
+ readonly status: ExecutionAttemptStatus;
44
+ readonly workerId: string;
45
+ readonly fencingToken: number;
46
+ readonly leaseExpiresAt: string;
47
+ readonly startedAt: string;
48
+ readonly heartbeatAt: string;
49
+ readonly completedAt?: string;
50
+ }
51
+ export interface ExecutionWaitpoint {
52
+ readonly type: "approval" | "input" | "timer" | "external_event";
53
+ readonly key: string;
54
+ readonly resumeAfter?: string;
55
+ readonly continuationToken?: string;
56
+ }
57
+ export interface ExecutionResumePoint {
58
+ readonly waitpoint: ExecutionWaitpoint;
59
+ readonly resumedAt: string;
60
+ }
61
+ export interface EnqueueRunInput {
62
+ readonly tenantId: string;
63
+ readonly applicationId: string;
64
+ readonly sourceType: ExecutionRun["sourceType"];
65
+ readonly sourceId: string;
66
+ readonly idempotencyKey: string;
67
+ readonly correlationId: string;
68
+ readonly requestId: string;
69
+ readonly commandId: string;
70
+ readonly queue?: string;
71
+ readonly priority?: number;
72
+ readonly maxAttempts?: number;
73
+ readonly concurrencyKey?: string;
74
+ readonly payload?: Readonly<Record<string, JsonValue>>;
75
+ }
76
+ export interface ClaimedExecution {
77
+ readonly run: ExecutionRun;
78
+ readonly attempt: ExecutionAttempt;
79
+ }
80
+ export type JsonValue = string | number | boolean | null | readonly JsonValue[] | {
81
+ readonly [key: string]: JsonValue;
82
+ };
83
+ export interface ExecutionStore {
84
+ transaction<Result>(work: (transaction: ExecutionTransaction) => Result): Promise<Result>;
85
+ listRuns(): Promise<readonly ExecutionRun[]>;
86
+ listAttempts(runId: string): Promise<readonly ExecutionAttempt[]>;
87
+ purgeThread(threadId: string): Promise<number>;
88
+ }
89
+ export interface ExecutionTransaction {
90
+ getRun(id: string): ExecutionRun | undefined;
91
+ findByIdempotency(tenantId: string, applicationId: string, key: string): ExecutionRun | undefined;
92
+ listRuns(): readonly ExecutionRun[];
93
+ putRun(run: ExecutionRun): void;
94
+ listAttempts(runId: string): readonly ExecutionAttempt[];
95
+ putAttempt(attempt: ExecutionAttempt): void;
96
+ nextFencingToken(runId: string): number;
97
+ }
98
+ export interface ExecutionClock {
99
+ now(): Date;
100
+ }
101
+ export interface ExecutionIdFactory {
102
+ create(kind: "run" | "attempt" | "signal"): string;
103
+ }
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dromio/execution",
3
- "version": "0.1.42",
3
+ "version": "0.1.43",
4
4
  "dromio": {
5
5
  "stability": "beta"
6
6
  },