@vite-hub/workflow 0.1.0 → 0.4.1
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/README.md +173 -55
- package/dist/{app-CzPoP84f.js → app-He0GTrYZ.js} +1 -1
- package/dist/client-DkwOxEiT.js +707 -0
- package/dist/{cloudflare-nF4abPd4.js → cloudflare-BHfClPvT.js} +2 -2
- package/dist/{cloudflare-env-BNrYo29x.js → cloudflare-env-CGLx7lUd.js} +44 -42
- package/dist/cloudflare-env-lookup-CfX6wZKb.d.ts +4 -0
- package/dist/{cloudflare-env-CIjdFTv6.d.ts → cloudflare-shared-CTqh_a2s.d.ts} +2 -2
- package/dist/{config-IJMb0eeZ.js → config-C3DvtjfJ.js} +41 -40
- package/dist/definition.d.ts +18 -0
- package/dist/definition.js +33 -0
- package/dist/delay-D1-nq_VE.js +46 -0
- package/dist/dev-recorder-CTN5Fkao.js +10 -0
- package/dist/durability.d.ts +23 -0
- package/dist/durability.js +62 -0
- package/dist/error-diagnostics-0V2T3JFw.js +317 -0
- package/dist/error-diagnostics-CQ4BUqRe.js +270 -0
- package/dist/errors-DCqRnZpN.js +35 -0
- package/dist/errors-uhP8DZTi.d.ts +67 -0
- package/dist/index.d.ts +35 -63
- package/dist/index.js +15 -19
- package/dist/object-Da1zyPCR.js +11 -0
- package/dist/openworkflow-BhzxV_Y3.d.ts +52 -0
- package/dist/openworkflow-defaults-DDig2M4s.js +26 -0
- package/dist/openworkflow-storage-Dj9zUAsk.js +28 -0
- package/dist/openworkflow.d.ts +2 -0
- package/dist/openworkflow.js +2 -0
- package/dist/{operations-tNUdj3G4.d.ts → operation-definition-nmRu_O3V.d.ts} +42 -15
- package/dist/operations-D_WJwjrS.js +333 -0
- package/dist/operations.d.ts +40 -6
- package/dist/operations.js +163 -736
- package/dist/{out-CsaJxg8m.js → out-DxLKolA0.js} +32 -1430
- package/dist/{rolldown-runtime-CMFfr-1z.js → rolldown-runtime-B4iAMlE-.js} +10 -1
- package/dist/run-error-DBWqiJHH.js +110 -0
- package/dist/run-failed-gVGo1BaF.js +18 -0
- package/dist/runtime/cloudflare-runner.d.ts +3 -5
- package/dist/runtime/cloudflare-runner.js +39 -45
- package/dist/runtime/cloudflare-shared.d.ts +2 -2
- package/dist/runtime/cloudflare-shared.js +1 -1
- package/dist/runtime/cloudflare-vite.d.ts +3 -2
- package/dist/runtime/cloudflare-vite.js +47 -1
- package/dist/runtime/dev-runs.d.ts +4 -0
- package/dist/runtime/dev-runs.js +73 -0
- package/dist/runtime/execute.d.ts +42 -5
- package/dist/runtime/execute.js +216 -17
- package/dist/runtime/openworkflow-worker.d.ts +29 -2
- package/dist/runtime/openworkflow-worker.js +156 -38
- package/dist/runtime/openworkflow.d.ts +2 -21
- package/dist/runtime/openworkflow.js +307 -44
- package/dist/runtime/state.d.ts +3 -1
- package/dist/runtime/state.js +6 -6
- package/dist/runtime/vercel-vite.d.ts +1 -1
- package/dist/runtime/vercel-vite.js +7 -4
- package/dist/types-Dsmwsdlv.d.ts +282 -0
- package/dist/{vercel-D-ZNtB_u.js → vercel-DTvm61iY.js} +53 -24
- package/dist/vite.d.ts +228 -30
- package/dist/vite.js +2640 -1449
- package/package.json +28 -50
- package/dist/client-DsGM3M4U.js +0 -389
- package/dist/cloudflare-shared-CaxrMD1A.d.ts +0 -1
- package/dist/cloudflare-vite-B3IabBsv.js +0 -47
- package/dist/error-diagnostics-A_8Kp-48.js +0 -116
- package/dist/error-diagnostics-pwNFvAHP.js +0 -67
- package/dist/operations-B_rYG71W.js +0 -230
- package/dist/provider-operation-CW2cYfVy.js +0 -65
- package/dist/runtime-type-DBCvIh5x.js +0 -7
- package/dist/types-D82WmfZa.d.ts +0 -180
|
@@ -1,11 +1,17 @@
|
|
|
1
|
-
import { t as workflowErrorDiagnostics } from "../error-diagnostics-
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
1
|
+
import { t as workflowErrorDiagnostics } from "../error-diagnostics-0V2T3JFw.js";
|
|
2
|
+
import { t as resolveOpenWorkflowStorage } from "../openworkflow-storage-Dj9zUAsk.js";
|
|
3
|
+
import { n as createWorkflowError } from "../errors-DCqRnZpN.js";
|
|
4
|
+
import { readNonRetryableStepResult, resolveWorkflowStepOptions, runSerializedWorkflowHandler, toDurationMilliseconds, toNonRetryableStepResult, withWorkflowStepTimeout } from "./execute.js";
|
|
5
|
+
import { r as invariantError, t as defaultOpenWorkflowSqlitePath } from "../openworkflow-defaults-DDig2M4s.js";
|
|
6
|
+
import { i as runWorkflowProviderOperation, n as getWorkflowProviderStatus, t as toWorkflowRunError } from "../run-error-DBWqiJHH.js";
|
|
7
|
+
import { t as emitWorkflowFailed } from "../run-failed-gVGo1BaF.js";
|
|
4
8
|
import { deserializeResponse, isSerializedResponse } from "@vite-hub/runtime";
|
|
5
9
|
//#region src/runtime/openworkflow.ts
|
|
6
|
-
const defaultImporter =
|
|
10
|
+
const defaultImporter = (specifier) => import(
|
|
11
|
+
/* @vite-ignore */
|
|
12
|
+
specifier
|
|
13
|
+
);
|
|
7
14
|
let openWorkflowImporter = defaultImporter;
|
|
8
|
-
const defaultOpenWorkflowSqlitePath = ".vitehub/data/openworkflow.sqlite.db";
|
|
9
15
|
let runtimes = /* @__PURE__ */ new Map();
|
|
10
16
|
async function importOpenWorkflowModule(specifier, importer) {
|
|
11
17
|
return await runWorkflowProviderOperation("openworkflow", "import", () => importer(specifier));
|
|
@@ -37,8 +43,23 @@ async function prepareSqlitePath(path, importer) {
|
|
|
37
43
|
}
|
|
38
44
|
return path;
|
|
39
45
|
}
|
|
46
|
+
let databaseUrlResolver;
|
|
47
|
+
/**
|
|
48
|
+
* Makes OpenWorkflow use the Postgres Default Database of the app when no OpenWorkflow storage is configured. The
|
|
49
|
+
* generated startup plugin installs it when the build has a Postgres Default Database.
|
|
50
|
+
*/
|
|
51
|
+
function setOpenWorkflowDatabaseUrl(resolve) {
|
|
52
|
+
databaseUrlResolver = resolve;
|
|
53
|
+
}
|
|
54
|
+
/** The Postgres URL of the Default Database, when the app has a Postgres Default Database. */
|
|
55
|
+
function readDatabasePostgresUrl() {
|
|
56
|
+
if (!databaseUrlResolver) return void 0;
|
|
57
|
+
const url = databaseUrlResolver()?.trim();
|
|
58
|
+
if (!url) throw workflowErrorDiagnostics.WORKFLOW_OPENWORKFLOW_DATABASE_URL_MISSING();
|
|
59
|
+
return url;
|
|
60
|
+
}
|
|
40
61
|
function getOpenWorkflowConfig(config) {
|
|
41
|
-
if (config.
|
|
62
|
+
if (config.driver !== "openworkflow") throw workflowErrorDiagnostics.WORKFLOW_R0020({ message: `OpenWorkflow runtime requires workflow.driver "openworkflow", received "${config.driver}".` });
|
|
42
63
|
if ("database" in config && config.database !== void 0) throw workflowErrorDiagnostics.WORKFLOW_R0027({ message: "`workflow.database` is not supported. Set `workflow.sqlite.path` or `workflow.postgres.url` explicitly." });
|
|
43
64
|
const sqlite = config.sqlite || {};
|
|
44
65
|
const postgres = config.postgres || {};
|
|
@@ -47,29 +68,120 @@ function getOpenWorkflowConfig(config) {
|
|
|
47
68
|
const explicitPostgresUrl = resolveRuntimeConfigValue(postgres.url)?.trim();
|
|
48
69
|
if (sqlite.path !== void 0 && !explicitSqlitePath?.trim()) throw workflowErrorDiagnostics.WORKFLOW_R0028({ message: "`workflow.sqlite.path` must resolve to a non-empty local SQLite path. Check its runtime environment declaration." });
|
|
49
70
|
if (postgres.url !== void 0 && !explicitPostgresUrl) throw workflowErrorDiagnostics.WORKFLOW_R0029({ message: "`workflow.postgres.url` must resolve to a non-empty Postgres URL. Check its runtime environment declaration." });
|
|
50
|
-
const
|
|
51
|
-
|
|
71
|
+
const storage = resolveOpenWorkflowStorage({
|
|
72
|
+
postgresUrl: explicitPostgresUrl,
|
|
73
|
+
sqlitePath: explicitSqlitePath
|
|
74
|
+
}, readEnv);
|
|
75
|
+
if (storage.backend === "sqlite" && storage.source !== "default") return {
|
|
52
76
|
backend: "sqlite",
|
|
53
77
|
namespaceId: sqlite.namespaceId || readEnv("OPENWORKFLOW_NAMESPACE_ID") || "production",
|
|
54
|
-
path: normalizeSqlitePath(
|
|
55
|
-
runMigrations: sqlite.runMigrations
|
|
78
|
+
path: normalizeSqlitePath(storage.path),
|
|
79
|
+
runMigrations: sqlite.runMigrations,
|
|
80
|
+
source: "configured"
|
|
56
81
|
};
|
|
57
|
-
const
|
|
82
|
+
const configuredUrl = storage.backend === "postgres" ? storage.url : void 0;
|
|
83
|
+
const url = configuredUrl || readDatabasePostgresUrl();
|
|
58
84
|
if (url) return {
|
|
59
85
|
backend: "postgres",
|
|
60
86
|
namespaceId: postgres.namespaceId || readEnv("OPENWORKFLOW_NAMESPACE_ID") || "production",
|
|
61
87
|
runMigrations: postgres.runMigrations,
|
|
62
88
|
schema: postgres.schema || readEnv("OPENWORKFLOW_SCHEMA") || "openworkflow",
|
|
89
|
+
source: configuredUrl ? "configured" : "database",
|
|
63
90
|
url
|
|
64
91
|
};
|
|
92
|
+
if (/^postgres(?:ql)?:\/\//i.test(readEnv("DATABASE_URL") || "")) throw workflowErrorDiagnostics.WORKFLOW_OPENWORKFLOW_DATABASE_URL_IGNORED();
|
|
65
93
|
return {
|
|
66
94
|
backend: "sqlite",
|
|
67
95
|
namespaceId: sqlite.namespaceId || readEnv("OPENWORKFLOW_NAMESPACE_ID") || "production",
|
|
68
96
|
path: defaultOpenWorkflowSqlitePath,
|
|
69
|
-
runMigrations: sqlite.runMigrations
|
|
97
|
+
runMigrations: sqlite.runMigrations,
|
|
98
|
+
source: "default"
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
/** How long a server waits for the setup lock that another server holds, before the worker start tries again. */
|
|
102
|
+
const postgresSetupWaitMs = 12e4;
|
|
103
|
+
/** How long the server that holds the setup lock waits for the second connection that the OpenWorkflow migration needs. */
|
|
104
|
+
const postgresSecondConnectionTimeoutMs = 1e4;
|
|
105
|
+
function sleep(ms) {
|
|
106
|
+
return new Promise((resolve) => setTimeout(resolve, ms).unref?.());
|
|
107
|
+
}
|
|
108
|
+
/** Resolves `true` when `task` settles first, `false` when `ms` passes first. */
|
|
109
|
+
function settlesWithin(task, ms) {
|
|
110
|
+
let timer;
|
|
111
|
+
return Promise.race([task.then(() => true), new Promise((resolve) => {
|
|
112
|
+
timer = setTimeout(() => resolve(false), ms);
|
|
113
|
+
timer.unref?.();
|
|
114
|
+
})]).finally(() => clearTimeout(timer));
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* OpenWorkflow creates its Postgres schema without a lock. When servers start together, all but one fail with
|
|
118
|
+
* `duplicate key value violates unique constraint`, and OpenWorkflow leaves the failed migration connection open in an
|
|
119
|
+
* aborted transaction. So one server at a time sets up the schema, and the others then find it up to date.
|
|
120
|
+
*
|
|
121
|
+
* OpenWorkflow does not export its migrations, so they cannot run on the connection that holds the lock: they run on a
|
|
122
|
+
* connection that `BackendPostgres.connect()` opens.
|
|
123
|
+
* - A server tries the lock with `pg_try_advisory_xact_lock` in a short transaction. A server that does not get it
|
|
124
|
+
* commits at once and tries again later, so a waiting server holds no connection.
|
|
125
|
+
* - The server that gets it first checks that it can open a second connection. A pool of one connection, such as a
|
|
126
|
+
* pooler with one server connection, cannot run the migration while the lock holds that connection, so the server
|
|
127
|
+
* stops with `WORKFLOW_OPENWORKFLOW_SETUP_CONNECTION_UNAVAILABLE` before the setup starts.
|
|
128
|
+
* - Then it holds the lock until OpenWorkflow finished the setup.
|
|
129
|
+
* A transaction lock also works through a pooler in transaction mode, such as PgBouncer.
|
|
130
|
+
* OpenWorkflow 0.11.0 locks its setup with a session lock
|
|
131
|
+
* (https://github.com/openworkflowdev/openworkflow/commit/eb544db), which such a pooler does not keep, so this lock stays.
|
|
132
|
+
*/
|
|
133
|
+
async function withPostgresSetupLock(postgres, url, schema, setup) {
|
|
134
|
+
const sql = postgres.default(url, {
|
|
135
|
+
idle_timeout: 1,
|
|
136
|
+
max: 1,
|
|
137
|
+
onnotice: () => {}
|
|
138
|
+
});
|
|
139
|
+
const key = `vitehub:openworkflow:${schema}`;
|
|
140
|
+
const deadline = Date.now() + postgresSetupWaitMs;
|
|
141
|
+
try {
|
|
142
|
+
for (let attempt = 1;; attempt++) {
|
|
143
|
+
let result;
|
|
144
|
+
await sql.begin(async (transaction) => {
|
|
145
|
+
const [lock] = await transaction`select pg_try_advisory_xact_lock(hashtextextended(${key}, 0)) as locked`;
|
|
146
|
+
if (!lock?.locked) return;
|
|
147
|
+
const probe = postgres.default(url, {
|
|
148
|
+
max: 1,
|
|
149
|
+
onnotice: () => {}
|
|
150
|
+
});
|
|
151
|
+
const answered = Promise.resolve(probe`select 1`).then(() => {}, () => {});
|
|
152
|
+
if (!await settlesWithin(answered, postgresSecondConnectionTimeoutMs)) {
|
|
153
|
+
answered.then(() => probe.end());
|
|
154
|
+
throw workflowErrorDiagnostics.WORKFLOW_OPENWORKFLOW_SETUP_CONNECTION_UNAVAILABLE();
|
|
155
|
+
}
|
|
156
|
+
await probe.end();
|
|
157
|
+
result = { value: await setup() };
|
|
158
|
+
});
|
|
159
|
+
if (result) return result.value;
|
|
160
|
+
if (Date.now() >= deadline) throw workflowErrorDiagnostics.WORKFLOW_OPENWORKFLOW_SETUP_LOCK_TIMEOUT({ seconds: postgresSetupWaitMs / 1e3 });
|
|
161
|
+
await sleep(Math.min(250 * attempt, 2e3));
|
|
162
|
+
}
|
|
163
|
+
} finally {
|
|
164
|
+
await sql.end({ timeout: 5 });
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
/**
|
|
168
|
+
* The backend that the OpenWorkflow client and its workers use. OpenWorkflow retries a failed run by its retry policy, so
|
|
169
|
+
* only `failWorkflowRun()` knows when a run ends as `failed`. This wrapper sends `workflow.failed` then.
|
|
170
|
+
*/
|
|
171
|
+
function reportFailedRuns(backend, definitions) {
|
|
172
|
+
const failWorkflowRun = async (params) => {
|
|
173
|
+
const run = await backend.failWorkflowRun(params);
|
|
174
|
+
if (run.status === "failed") await emitWorkflowFailed(run.workflowName, run.idempotencyKey || run.id, run.error ?? params.error, definitions.get(run.workflowName));
|
|
175
|
+
return run;
|
|
70
176
|
};
|
|
177
|
+
return new Proxy(backend, { get(target, property) {
|
|
178
|
+
if (property === "failWorkflowRun") return failWorkflowRun;
|
|
179
|
+
const value = Reflect.get(target, property);
|
|
180
|
+
return typeof value === "function" ? value.bind(target) : value;
|
|
181
|
+
} });
|
|
71
182
|
}
|
|
72
183
|
async function createOpenWorkflowRuntime(options, importer) {
|
|
184
|
+
const definitions = /* @__PURE__ */ new Map();
|
|
73
185
|
const [{ OpenWorkflow }, backendModule] = await Promise.all([importOpenWorkflowModule("openworkflow", importer), options.backend === "sqlite" ? importOpenWorkflowModule("openworkflow/sqlite", importer) : importOpenWorkflowModule("openworkflow/postgres", importer)]);
|
|
74
186
|
const { backend, client } = await runWorkflowProviderOperation("openworkflow", "connect", async () => {
|
|
75
187
|
let backend;
|
|
@@ -77,22 +189,67 @@ async function createOpenWorkflowRuntime(options, importer) {
|
|
|
77
189
|
namespaceId: options.namespaceId,
|
|
78
190
|
...typeof options.runMigrations === "boolean" ? { runMigrations: options.runMigrations } : {}
|
|
79
191
|
});
|
|
80
|
-
else
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
192
|
+
else {
|
|
193
|
+
const { BackendPostgres } = backendModule;
|
|
194
|
+
const connect = () => BackendPostgres.connect(options.url, {
|
|
195
|
+
namespaceId: options.namespaceId,
|
|
196
|
+
...typeof options.runMigrations === "boolean" ? { runMigrations: options.runMigrations } : {},
|
|
197
|
+
schema: options.schema
|
|
198
|
+
});
|
|
199
|
+
backend = options.runMigrations === false ? await connect() : await withPostgresSetupLock(await importOpenWorkflowModule("postgres", importer), options.url, options.schema, connect);
|
|
200
|
+
}
|
|
85
201
|
return {
|
|
86
202
|
backend,
|
|
87
|
-
client: new OpenWorkflow({ backend })
|
|
203
|
+
client: new OpenWorkflow({ backend: reportFailedRuns(backend, definitions) })
|
|
88
204
|
};
|
|
89
205
|
});
|
|
90
206
|
return {
|
|
91
207
|
backend,
|
|
92
208
|
client,
|
|
209
|
+
definitions,
|
|
210
|
+
findRunId: createRunIdLookup(backend, options),
|
|
93
211
|
workflows: /* @__PURE__ */ new Map()
|
|
94
212
|
};
|
|
95
213
|
}
|
|
214
|
+
function isSqliteHandle(value) {
|
|
215
|
+
return typeof value === "object" && value !== null && typeof Reflect.get(value, "prepare") === "function";
|
|
216
|
+
}
|
|
217
|
+
function isPostgresHandle(value) {
|
|
218
|
+
return typeof value === "function";
|
|
219
|
+
}
|
|
220
|
+
function readRowId(row) {
|
|
221
|
+
if (typeof row !== "object" || row === null) return void 0;
|
|
222
|
+
const id = Reflect.get(row, "id");
|
|
223
|
+
return typeof id === "string" ? id : void 0;
|
|
224
|
+
}
|
|
225
|
+
/**
|
|
226
|
+
* ViteHub starts a run with the caller's id as the OpenWorkflow idempotency key, and OpenWorkflow gives the run its own
|
|
227
|
+
* UUID. The OpenWorkflow API reads runs by UUID only, so this lookup reads the key from the backend connection.
|
|
228
|
+
*/
|
|
229
|
+
function createRunIdLookup(backend, options) {
|
|
230
|
+
const connection = Reflect.get(backend, options.backend === "sqlite" ? "db" : "pg");
|
|
231
|
+
return async (name, key) => {
|
|
232
|
+
if (options.backend === "sqlite" && isSqliteHandle(connection)) return readRowId(connection.prepare(`SELECT "id" FROM "workflow_runs" WHERE "namespace_id" = ? AND "workflow_name" = ? AND "idempotency_key" = ? ORDER BY "created_at" ASC, "id" ASC LIMIT 1`).get(options.namespaceId, name, key));
|
|
233
|
+
if (options.backend === "postgres" && isPostgresHandle(connection)) {
|
|
234
|
+
const [row] = await connection`SELECT "id" FROM ${connection(options.schema)}.${connection("workflow_runs")} WHERE "namespace_id" = ${options.namespaceId} AND "workflow_name" = ${name} AND "idempotency_key" = ${key} ORDER BY "created_at" ASC, "id" ASC LIMIT 1`;
|
|
235
|
+
return readRowId(row);
|
|
236
|
+
}
|
|
237
|
+
throw invariantError(`OpenWorkflow 0.9 backends keep their connection in \`db\` (SQLite) or \`pg\` (Postgres), but the ${options.backend} backend has neither`);
|
|
238
|
+
};
|
|
239
|
+
}
|
|
240
|
+
/** The storage that OpenWorkflow uses for `config` now, without credentials. */
|
|
241
|
+
function describeOpenWorkflowStorage(config) {
|
|
242
|
+
const storage = getOpenWorkflowConfig(config);
|
|
243
|
+
return storage.backend === "sqlite" ? {
|
|
244
|
+
backend: "sqlite",
|
|
245
|
+
location: storage.path,
|
|
246
|
+
source: storage.source
|
|
247
|
+
} : {
|
|
248
|
+
backend: "postgres",
|
|
249
|
+
location: `schema ${storage.schema}`,
|
|
250
|
+
source: storage.source
|
|
251
|
+
};
|
|
252
|
+
}
|
|
96
253
|
async function getOpenWorkflowRuntime(config) {
|
|
97
254
|
const cache = runtimes;
|
|
98
255
|
const options = getOpenWorkflowConfig(config);
|
|
@@ -112,33 +269,52 @@ async function getOpenWorkflowRuntime(config) {
|
|
|
112
269
|
});
|
|
113
270
|
return resolved;
|
|
114
271
|
}
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
272
|
+
/**
|
|
273
|
+
* OpenWorkflow counts attempts, and `limit` counts the retries after the first attempt. OpenWorkflow caps each wait at
|
|
274
|
+
* `maximumInterval`, 100 seconds by default, so the cap is the longest wait that the policy asks for.
|
|
275
|
+
*/
|
|
276
|
+
function toOpenWorkflowRetryPolicy(name, options) {
|
|
277
|
+
const { backoff, delay, limit } = resolveWorkflowStepOptions(name, options).retries;
|
|
278
|
+
const initial = toDurationMilliseconds(delay);
|
|
279
|
+
const coefficient = backoff === "exponential" ? 2 : 1;
|
|
118
280
|
return {
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
281
|
+
backoffCoefficient: coefficient,
|
|
282
|
+
initialInterval: `${initial}ms`,
|
|
283
|
+
maximumAttempts: limit + 1,
|
|
284
|
+
maximumInterval: `${initial * coefficient ** Math.max(limit - 1, 0)}ms`
|
|
122
285
|
};
|
|
123
286
|
}
|
|
124
287
|
function createOpenWorkflowProviderStep(step) {
|
|
125
288
|
return {
|
|
126
289
|
async do(name, options, run) {
|
|
127
|
-
|
|
290
|
+
const output = await step.run({
|
|
128
291
|
name,
|
|
129
|
-
|
|
130
|
-
},
|
|
292
|
+
retryPolicy: toOpenWorkflowRetryPolicy(name, options)
|
|
293
|
+
}, async () => {
|
|
294
|
+
try {
|
|
295
|
+
return await withWorkflowStepTimeout(name, options.timeout, run)();
|
|
296
|
+
} catch (error) {
|
|
297
|
+
const result = toNonRetryableStepResult(error);
|
|
298
|
+
if (result) return result;
|
|
299
|
+
throw error;
|
|
300
|
+
}
|
|
301
|
+
});
|
|
302
|
+
const error = readNonRetryableStepResult(output);
|
|
303
|
+
if (error) throw error;
|
|
304
|
+
return output;
|
|
131
305
|
},
|
|
132
|
-
sleep: async (name,
|
|
306
|
+
sleep: async (name, milliseconds) => await step.sleep(name, `${milliseconds}ms`)
|
|
133
307
|
};
|
|
134
308
|
}
|
|
135
309
|
async function registerOpenWorkflowDefinition(runtime, name, definition) {
|
|
136
310
|
const existing = runtime.workflows.get(name);
|
|
137
311
|
if (existing) return existing;
|
|
138
312
|
const openWorkflowDefinition = definition;
|
|
313
|
+
runtime.definitions.set(name, definition);
|
|
139
314
|
const workflow = runtime.client.defineWorkflow({ name }, async ({ input, run, step }) => {
|
|
315
|
+
const stored = await runtime.backend.getWorkflowRun({ workflowRunId: run.id });
|
|
140
316
|
return await runSerializedWorkflowHandler({
|
|
141
|
-
id: run.id,
|
|
317
|
+
id: stored?.idempotencyKey || run.id,
|
|
142
318
|
name,
|
|
143
319
|
payload: input,
|
|
144
320
|
provider: "openworkflow",
|
|
@@ -167,57 +343,144 @@ function serializeOpenWorkflowRun(run, name) {
|
|
|
167
343
|
status: "unknown"
|
|
168
344
|
};
|
|
169
345
|
const result = isSerializedResponse(run.output) ? deserializeResponse(run.output) : run.output;
|
|
346
|
+
const status = normalizeOpenWorkflowStatus(run.status);
|
|
170
347
|
return {
|
|
171
|
-
|
|
172
|
-
|
|
348
|
+
...status === "failed" ? { error: toWorkflowRunError(run.error) } : {},
|
|
349
|
+
...run.finishedAt ? { completedAt: run.finishedAt } : {},
|
|
350
|
+
createdAt: run.createdAt,
|
|
351
|
+
...run.startedAt ? { startedAt: run.startedAt } : {},
|
|
352
|
+
id: run.idempotencyKey || run.id,
|
|
353
|
+
metadata: {
|
|
173
354
|
namespaceId: run.namespaceId,
|
|
174
355
|
version: run.version,
|
|
175
356
|
workflowName: run.workflowName
|
|
176
357
|
},
|
|
358
|
+
payload: run.input,
|
|
177
359
|
provider: "openworkflow",
|
|
178
360
|
result,
|
|
179
|
-
status
|
|
361
|
+
status
|
|
180
362
|
};
|
|
181
363
|
}
|
|
182
|
-
|
|
183
|
-
|
|
364
|
+
/** OpenWorkflow stores `name`, `message`, and `stack`. The stack has server paths, so the step keeps the message only. */
|
|
365
|
+
function toWorkflowRunStepError(error) {
|
|
366
|
+
const message = typeof error === "object" && error !== null ? Reflect.get(error, "message") : void 0;
|
|
367
|
+
return { message: typeof message === "string" && message ? message : "Workflow step failed." };
|
|
368
|
+
}
|
|
369
|
+
/** OpenWorkflow stores one row per step attempt. A run reports each step once, with its latest attempt. */
|
|
370
|
+
function toWorkflowRunSteps(attempts) {
|
|
371
|
+
const steps = /* @__PURE__ */ new Map();
|
|
372
|
+
for (const attempt of attempts) {
|
|
373
|
+
const nonRetryable = readNonRetryableStepResult(attempt.output);
|
|
374
|
+
steps.set(attempt.stepName, {
|
|
375
|
+
attempt: (steps.get(attempt.stepName)?.attempt ?? 0) + 1,
|
|
376
|
+
...attempt.finishedAt ? { completedAt: attempt.finishedAt } : {},
|
|
377
|
+
...attempt.status === "failed" || nonRetryable ? { error: toWorkflowRunStepError(nonRetryable ?? attempt.error) } : {},
|
|
378
|
+
id: attempt.id,
|
|
379
|
+
name: attempt.stepName,
|
|
380
|
+
...attempt.context?.kind === "sleep" ? { sleepUntil: new Date(attempt.context.resumeAt) } : {},
|
|
381
|
+
...attempt.startedAt ? { startedAt: attempt.startedAt } : {},
|
|
382
|
+
status: nonRetryable ? "failed" : normalizeOpenWorkflowStatus(attempt.status)
|
|
383
|
+
});
|
|
384
|
+
}
|
|
385
|
+
return [...steps.values()];
|
|
386
|
+
}
|
|
387
|
+
async function listOpenWorkflowStepAttempts(backend, workflowRunId) {
|
|
388
|
+
const attempts = [];
|
|
389
|
+
let after;
|
|
390
|
+
do {
|
|
391
|
+
const page = await backend.listStepAttempts({
|
|
392
|
+
workflowRunId,
|
|
393
|
+
limit: 100,
|
|
394
|
+
...after ? { after } : {}
|
|
395
|
+
});
|
|
396
|
+
attempts.push(...page.data);
|
|
397
|
+
after = page.pagination.next ?? void 0;
|
|
398
|
+
} while (after);
|
|
399
|
+
return attempts;
|
|
400
|
+
}
|
|
401
|
+
async function runOpenWorkflow(config, name, payload, definition, options, onDispatch, startAt) {
|
|
402
|
+
const runtime = await getOpenWorkflowRuntime(config);
|
|
403
|
+
const workflow = await registerOpenWorkflowDefinition(runtime, name, definition);
|
|
184
404
|
onDispatch?.();
|
|
185
405
|
let firstAcknowledgementUnknown = false;
|
|
186
406
|
const handle = await runWorkflowProviderOperation("openworkflow", "run", async () => {
|
|
187
|
-
const
|
|
407
|
+
const existingId = options.id ? await runtime.findRunId(name, options.id) ?? options.id : void 0;
|
|
408
|
+
const existing = existingId ? await runtime.backend.getWorkflowRun({ workflowRunId: existingId }) : null;
|
|
409
|
+
if (existing?.workflowName === name) return { workflowRun: existing };
|
|
410
|
+
const runOptions = options.id || startAt !== void 0 ? {
|
|
411
|
+
...options.id ? { idempotencyKey: options.id } : {},
|
|
412
|
+
...startAt === void 0 ? {} : { availableAt: new Date(startAt) }
|
|
413
|
+
} : void 0;
|
|
414
|
+
const start = () => workflow.run(payload, runOptions);
|
|
188
415
|
return await start().catch((error) => {
|
|
189
416
|
if (!options.id) throw error;
|
|
190
417
|
firstAcknowledgementUnknown = getWorkflowProviderStatus(error) === void 0;
|
|
191
418
|
return start();
|
|
192
419
|
});
|
|
193
|
-
}, {
|
|
420
|
+
}, { acknowledgement: (_error, status) => firstAcknowledgementUnknown || status === void 0 ? "unknown" : status < 500 ? "rejected" : void 0 });
|
|
194
421
|
return await runWorkflowProviderOperation("openworkflow", "run", async () => {
|
|
195
|
-
const serialized = serializeOpenWorkflowRun(handle.workflowRun, name);
|
|
196
422
|
return {
|
|
197
|
-
...
|
|
198
|
-
metadata:
|
|
423
|
+
...serializeOpenWorkflowRun(handle.workflowRun, name),
|
|
424
|
+
metadata: {
|
|
199
425
|
...options.id ? { idempotencyKey: options.id } : {},
|
|
200
426
|
workflow: name
|
|
201
427
|
},
|
|
202
|
-
payload
|
|
428
|
+
payload: handle.workflowRun.input
|
|
203
429
|
};
|
|
204
430
|
});
|
|
205
431
|
}
|
|
206
432
|
async function getOpenWorkflowRun(config, name, id) {
|
|
207
433
|
const runtime = await getOpenWorkflowRuntime(config);
|
|
208
434
|
return await runWorkflowProviderOperation("openworkflow", "get", async () => {
|
|
209
|
-
const
|
|
210
|
-
|
|
435
|
+
const run = await runtime.backend.getWorkflowRun({ workflowRunId: await runtime.findRunId(name, id) ?? id });
|
|
436
|
+
if (!run || run.workflowName !== name) return {
|
|
211
437
|
id,
|
|
212
438
|
provider: "openworkflow",
|
|
213
439
|
status: "unknown"
|
|
214
440
|
};
|
|
441
|
+
return {
|
|
442
|
+
...serializeOpenWorkflowRun(run, name),
|
|
443
|
+
steps: toWorkflowRunSteps(await listOpenWorkflowStepAttempts(runtime.backend, run.id))
|
|
444
|
+
};
|
|
215
445
|
});
|
|
216
446
|
}
|
|
447
|
+
const terminalOpenWorkflowStatuses = /* @__PURE__ */ new Set([
|
|
448
|
+
"cancelled",
|
|
449
|
+
"completed",
|
|
450
|
+
"failed"
|
|
451
|
+
]);
|
|
452
|
+
/**
|
|
453
|
+
* Cancels a pending or running OpenWorkflow run of this Workflow and returns its state afterwards. A run of another
|
|
454
|
+
* Workflow, or an unknown run, reports `unknown` without being cancelled. A finished run keeps and reports its status.
|
|
455
|
+
*/
|
|
456
|
+
async function cancelOpenWorkflowRun(config, name, id) {
|
|
457
|
+
const current = await getOpenWorkflowRun(config, name, id);
|
|
458
|
+
if (current.status === "unknown" || terminalOpenWorkflowStatuses.has(current.status)) return current;
|
|
459
|
+
const runtime = await getOpenWorkflowRuntime(config);
|
|
460
|
+
try {
|
|
461
|
+
await runWorkflowProviderOperation("openworkflow", "cancel", async () => await runtime.client.cancelWorkflowRun(await runtime.findRunId(name, id) ?? id));
|
|
462
|
+
} catch (error) {
|
|
463
|
+
const latest = await getOpenWorkflowRun(config, name, id).catch(() => void 0);
|
|
464
|
+
if (latest && terminalOpenWorkflowStatuses.has(latest.status)) return latest;
|
|
465
|
+
throw error;
|
|
466
|
+
}
|
|
467
|
+
return await getOpenWorkflowRun(config, name, id);
|
|
468
|
+
}
|
|
217
469
|
async function resetOpenWorkflowRuntime() {
|
|
470
|
+
openWorkflowImporter = defaultImporter;
|
|
471
|
+
databaseUrlResolver = void 0;
|
|
472
|
+
await detachOpenWorkflowRuntimes()();
|
|
473
|
+
}
|
|
474
|
+
/**
|
|
475
|
+
* Starts a new runtime cache, so the next acquisition opens a fresh backend. Returns a function that closes the
|
|
476
|
+
* backends of the old cache. Call it after the work that still uses them, such as a stopping worker, finishes.
|
|
477
|
+
*/
|
|
478
|
+
function detachOpenWorkflowRuntimes() {
|
|
218
479
|
const closing = runtimes;
|
|
219
480
|
runtimes = /* @__PURE__ */ new Map();
|
|
220
|
-
|
|
481
|
+
return () => closeOpenWorkflowRuntimes(closing);
|
|
482
|
+
}
|
|
483
|
+
async function closeOpenWorkflowRuntimes(closing) {
|
|
221
484
|
const fulfilled = (await Promise.allSettled(closing.values())).flatMap((entry) => entry.status === "fulfilled" ? [entry.value] : []);
|
|
222
485
|
const failures = (await Promise.allSettled(fulfilled.map((runtime) => Promise.resolve().then(() => runtime.backend.stop())))).flatMap((entry) => entry.status === "rejected" ? [createWorkflowError({
|
|
223
486
|
cause: entry.reason,
|
|
@@ -231,4 +494,4 @@ function setOpenWorkflowImporter(importer) {
|
|
|
231
494
|
openWorkflowImporter = importer;
|
|
232
495
|
}
|
|
233
496
|
//#endregion
|
|
234
|
-
export { getOpenWorkflowRun, getOpenWorkflowRuntime, registerOpenWorkflowDefinition, resetOpenWorkflowRuntime, runOpenWorkflow, setOpenWorkflowImporter };
|
|
497
|
+
export { cancelOpenWorkflowRun, describeOpenWorkflowStorage, detachOpenWorkflowRuntimes, getOpenWorkflowRun, getOpenWorkflowRuntime, registerOpenWorkflowDefinition, resetOpenWorkflowRuntime, runOpenWorkflow, setOpenWorkflowDatabaseUrl, setOpenWorkflowImporter };
|
package/dist/runtime/state.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { f as WorkflowDefinition, l as ResolvedWorkflowOptions, m as WorkflowDefinitionRegistry } from "../types-Dsmwsdlv.js";
|
|
2
2
|
//#region src/runtime/state.d.ts
|
|
3
3
|
export interface WorkflowRunState<TResult = unknown> {
|
|
4
4
|
error?: unknown;
|
|
@@ -10,6 +10,8 @@ export interface WorkflowRunState<TResult = unknown> {
|
|
|
10
10
|
error?: unknown;
|
|
11
11
|
}>;
|
|
12
12
|
result?: TResult;
|
|
13
|
+
/** Set while a delayed inline run waits for its start time, in milliseconds. The run reports `queued` until then. */
|
|
14
|
+
startAt?: number;
|
|
13
15
|
status: "running" | "completed" | "failed";
|
|
14
16
|
}
|
|
15
17
|
export declare function setWorkflowRuntimeConfig(config: false | ResolvedWorkflowOptions | undefined): void;
|
package/dist/runtime/state.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { t as workflowErrorDiagnostics } from "../error-diagnostics-
|
|
1
|
+
import { t as workflowErrorDiagnostics } from "../error-diagnostics-0V2T3JFw.js";
|
|
2
|
+
import { n as setWorkflowDevRecorder } from "../dev-recorder-CTN5Fkao.js";
|
|
2
3
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
3
4
|
//#region src/runtime/state.ts
|
|
4
5
|
const RUNS_LIMIT = 1024;
|
|
@@ -60,7 +61,7 @@ function isWorkflowHandle(value) {
|
|
|
60
61
|
if (typeof candidate.name !== "string") return false;
|
|
61
62
|
if (typeof candidate.defer !== "function") return false;
|
|
62
63
|
if (typeof candidate.getRun !== "function") return false;
|
|
63
|
-
return typeof candidate.
|
|
64
|
+
return typeof candidate.start === "function";
|
|
64
65
|
}
|
|
65
66
|
function findExportedInlineWorkflowDefinition(name, loaded, definitions) {
|
|
66
67
|
const namedDefinition = definitions.get(name);
|
|
@@ -149,12 +150,10 @@ async function loadWorkflowDefinition(name) {
|
|
|
149
150
|
}
|
|
150
151
|
if (!loaded || typeof loaded !== "object") return;
|
|
151
152
|
const registeredInlineDefinition = loadingInlineDefinitions.get(name) ?? (generation === runtimeRegistryGeneration ? consumeInlineWorkflowDefinition(name) : void 0);
|
|
152
|
-
if (registeredInlineDefinition)
|
|
153
|
-
consumeInlineWorkflowDefinition(name, registeredInlineDefinition);
|
|
154
|
-
return registeredInlineDefinition;
|
|
155
|
-
}
|
|
153
|
+
if (registeredInlineDefinition) consumeInlineWorkflowDefinition(name, registeredInlineDefinition);
|
|
156
154
|
const definition = "default" in loaded ? loaded.default : loaded;
|
|
157
155
|
if (definition && typeof definition.handler === "function") return definition;
|
|
156
|
+
if (registeredInlineDefinition) return registeredInlineDefinition;
|
|
158
157
|
const exportedInlineDefinition = findExportedInlineWorkflowDefinition(name, loaded, loadingInlineDefinitions);
|
|
159
158
|
if (!exportedInlineDefinition) return void 0;
|
|
160
159
|
consumeInlineWorkflowDefinition(exportedInlineDefinition.name, exportedInlineDefinition.definition);
|
|
@@ -244,6 +243,7 @@ function resetWorkflowRuntime() {
|
|
|
244
243
|
inFlightRuns.clear();
|
|
245
244
|
fallbackRunKeys.clear();
|
|
246
245
|
completedRuns.clear();
|
|
246
|
+
setWorkflowDevRecorder(void 0);
|
|
247
247
|
}
|
|
248
248
|
//#endregion
|
|
249
249
|
export { enterWorkflowRuntimeEvent, getInlineWorkflowDefinitions, getWorkflowRunState, getWorkflowRuntimeConfig, getWorkflowRuntimeEvent, getWorkflowRuntimeRegistry, loadWorkflowDefinition, registerInlineWorkflowDefinition, resetWorkflowRuntime, runWithWorkflowRuntimeEvent, setWorkflowRun, setWorkflowRuntimeConfig, setWorkflowRuntimeRegistry, takeInlineWorkflowDefinition, takeInlineWorkflowDefinitionForModule };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { l as ResolvedWorkflowOptions, m as WorkflowDefinitionRegistry } from "../types-Dsmwsdlv.js";
|
|
2
2
|
import { t as VitehubApp } from "../app-BojnC_yf.js";
|
|
3
3
|
import { IncomingMessage, ServerResponse } from "node:http";
|
|
4
4
|
//#region src/runtime/vercel.d.ts
|
|
@@ -1,23 +1,26 @@
|
|
|
1
1
|
import { runWithWorkflowRuntimeEvent, setWorkflowRuntimeConfig, setWorkflowRuntimeRegistry } from "./state.js";
|
|
2
|
-
import { i as setVercelWorkflowRuntimeModules } from "../vercel-
|
|
3
|
-
import { t as resolveAppFetch } from "../app-
|
|
2
|
+
import { i as setVercelWorkflowRuntimeModules } from "../vercel-DTvm61iY.js";
|
|
3
|
+
import { t as resolveAppFetch } from "../app-He0GTrYZ.js";
|
|
4
4
|
import { waitUntil } from "@vercel/functions";
|
|
5
5
|
import { H3 } from "h3";
|
|
6
6
|
//#region ../internal/src/runtime/vercel-hosted.ts
|
|
7
7
|
function createVercelHostedServer(adapter) {
|
|
8
|
-
const app = new H3();
|
|
9
8
|
const appHandler = resolveAppFetch(adapter.label, adapter.app);
|
|
10
9
|
let nodeHandlerPromise;
|
|
11
10
|
return function hostedVercelServer(req, res) {
|
|
12
11
|
const handle = async () => {
|
|
13
12
|
nodeHandlerPromise ||= (async () => {
|
|
13
|
+
const app = new H3();
|
|
14
14
|
if (appHandler) {
|
|
15
15
|
const { fromWebHandler } = await import("h3");
|
|
16
16
|
app.use(fromWebHandler(async (request, context) => await appHandler(request, context)));
|
|
17
17
|
}
|
|
18
18
|
const { toNodeHandler } = await import("h3/node");
|
|
19
19
|
return toNodeHandler(app);
|
|
20
|
-
})()
|
|
20
|
+
})().catch((error) => {
|
|
21
|
+
nodeHandlerPromise = void 0;
|
|
22
|
+
throw error;
|
|
23
|
+
});
|
|
21
24
|
return (await nodeHandlerPromise)(req, res);
|
|
22
25
|
};
|
|
23
26
|
if (adapter.onRequest) return adapter.onRequest({
|