@dromio/execution 0.1.41
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +5 -0
- package/dist/memory-store.d.ts +9 -0
- package/dist/memory-store.js +55 -0
- package/dist/postgres-store.d.ts +22 -0
- package/dist/postgres-store.js +79 -0
- package/dist/service.d.ts +40 -0
- package/dist/service.js +346 -0
- package/dist/sqlite-store.d.ts +18 -0
- package/dist/sqlite-store.js +54 -0
- package/dist/types.d.ts +103 -0
- package/dist/types.js +1 -0
- package/package.json +36 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
|
@@ -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
|
+
}
|
package/dist/service.js
ADDED
|
@@ -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,18 @@
|
|
|
1
|
+
import type { ExecutionAttempt, ExecutionRun, ExecutionStore, ExecutionTransaction } from "./types.js";
|
|
2
|
+
export interface SqliteExecutionDatabase {
|
|
3
|
+
exec(sql: string): unknown;
|
|
4
|
+
query(sql: string): {
|
|
5
|
+
all(...parameters: unknown[]): unknown[];
|
|
6
|
+
get(...parameters: unknown[]): unknown;
|
|
7
|
+
run(...parameters: unknown[]): unknown;
|
|
8
|
+
};
|
|
9
|
+
}
|
|
10
|
+
export declare class SqliteExecutionStore implements ExecutionStore {
|
|
11
|
+
private readonly database;
|
|
12
|
+
constructor(database: SqliteExecutionDatabase);
|
|
13
|
+
transaction<Result>(work: (transaction: ExecutionTransaction) => Result): Promise<Result>;
|
|
14
|
+
listRuns(): Promise<readonly ExecutionRun[]>;
|
|
15
|
+
listAttempts(runId: string): Promise<readonly ExecutionAttempt[]>;
|
|
16
|
+
purgeThread(threadId: string): Promise<number>;
|
|
17
|
+
private tx;
|
|
18
|
+
}
|
|
@@ -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; }
|
package/dist/types.d.ts
ADDED
|
@@ -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
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@dromio/execution",
|
|
3
|
+
"version": "0.1.41",
|
|
4
|
+
"dromio": {
|
|
5
|
+
"stability": "beta"
|
|
6
|
+
},
|
|
7
|
+
"private": false,
|
|
8
|
+
"type": "module",
|
|
9
|
+
"types": "./dist/index.d.ts",
|
|
10
|
+
"exports": {
|
|
11
|
+
".": {
|
|
12
|
+
"types": "./dist/index.d.ts",
|
|
13
|
+
"bun": "./dist/index.js",
|
|
14
|
+
"import": "./dist/index.js"
|
|
15
|
+
}
|
|
16
|
+
},
|
|
17
|
+
"files": [
|
|
18
|
+
"dist"
|
|
19
|
+
],
|
|
20
|
+
"scripts": {
|
|
21
|
+
"build": "tsc -p tsconfig.build.json",
|
|
22
|
+
"prepack": "bun run build",
|
|
23
|
+
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
24
|
+
"test": "bun test src",
|
|
25
|
+
"check": "bun run typecheck && bun run test && bun run build"
|
|
26
|
+
},
|
|
27
|
+
"license": "Apache-2.0",
|
|
28
|
+
"repository": {
|
|
29
|
+
"type": "git",
|
|
30
|
+
"url": "https://github.com/Dromio-Labs/workflow.git",
|
|
31
|
+
"directory": "packages/execution"
|
|
32
|
+
},
|
|
33
|
+
"publishConfig": {
|
|
34
|
+
"access": "public"
|
|
35
|
+
}
|
|
36
|
+
}
|