@vite-hub/workflow 0.6.1 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/README.md +33 -9
  2. package/dist/{app-DXUHElAz.js → app-Cpa9qCXr.js} +1 -1
  3. package/dist/{client-CbBg4HlH.js → client-T41cNf3k.js} +41 -52
  4. package/dist/cloudflare-concurrency-counter-CDHHiMfn.js +136 -0
  5. package/dist/{config-CizNRTMi.js → config-G0z9jHLM.js} +6 -6
  6. package/dist/definition.d.ts +1 -1
  7. package/dist/definition.js +4 -1
  8. package/dist/{delay-CtT3442d.js → delay-B4azP18B.js} +7 -5
  9. package/dist/durability.d.ts +3 -1
  10. package/dist/durability.js +7 -1
  11. package/dist/{error-diagnostics--2cV_ER1.js → error-diagnostics-35AEmfve.js} +25 -5
  12. package/dist/{error-diagnostics-kKXseq8d.js → error-diagnostics-CsiNo_oI.js} +3 -3
  13. package/dist/{errors-CJZuvOcx.d.ts → errors-DwKy5MQ8.d.ts} +1 -1
  14. package/dist/execute-zu08sWGG.js +353 -0
  15. package/dist/index.d.ts +12 -10
  16. package/dist/index.js +3 -3
  17. package/dist/{openworkflow-defaults-DfQWtSRU.js → invariant-Dj2R1eMr.js} +1 -4
  18. package/dist/{openworkflow-CdKbUGGa.d.ts → openworkflow-DHuxMJQB.d.ts} +23 -4
  19. package/dist/openworkflow-defaults-1n0DbLdb.js +4 -0
  20. package/dist/openworkflow-zD8luED5.js +749 -0
  21. package/dist/{operation-definition-CqZkx1Rm.d.ts → operations-Blwi3jQF.d.ts} +1 -0
  22. package/dist/{operations-BBTmDm2H.js → operations-C2XbDDDV.js} +71 -15
  23. package/dist/operations.d.ts +3 -59
  24. package/dist/operations.js +5 -5
  25. package/dist/results-DqbEUMCH.d.ts +60 -0
  26. package/dist/{run-error-8p4BtTMv.js → run-error-zZh1_IBo.js} +5 -21
  27. package/dist/runtime/cloudflare-concurrency.d.ts +21 -0
  28. package/dist/runtime/cloudflare-concurrency.js +21 -0
  29. package/dist/runtime/cloudflare-runner.d.ts +1 -1
  30. package/dist/runtime/cloudflare-runner.js +7 -3
  31. package/dist/runtime/cloudflare-vite.d.ts +1 -1
  32. package/dist/runtime/cloudflare-vite.js +2 -2
  33. package/dist/runtime/execute.d.ts +8 -2
  34. package/dist/runtime/execute.js +1 -278
  35. package/dist/runtime/openworkflow-worker.d.ts +2 -2
  36. package/dist/runtime/openworkflow-worker.js +5 -6
  37. package/dist/runtime/openworkflow.d.ts +2 -2
  38. package/dist/runtime/openworkflow.js +1 -481
  39. package/dist/runtime/state.d.ts +1 -1
  40. package/dist/runtime/state.js +2 -2
  41. package/dist/runtime/vercel-vite.d.ts +1 -1
  42. package/dist/runtime/vercel-vite.js +2 -2
  43. package/dist/{signals-BHQdxoJo.js → signals-CdaxRNjN.js} +1 -1
  44. package/dist/{types-DvYcvbPG.d.ts → types-DrhUXMsE.d.ts} +34 -4
  45. package/dist/{vercel-Cw_Z9-j4.js → vercel-DRezYOUp.js} +8 -6
  46. package/dist/vite.d.ts +19 -4
  47. package/dist/vite.js +970 -212
  48. package/package.json +3 -3
  49. package/dist/cloudflare-Sgywkm1N.js +0 -57
@@ -0,0 +1,749 @@
1
+ import { n as invariantError } from "./invariant-Dj2R1eMr.js";
2
+ import { d as toNonRetryableStepResult, i as resolveWorkflowStepOptions, n as readNonRetryableStepResult, o as runSerializedWorkflowHandler, p as withWorkflowStepTimeout, u as toDurationMilliseconds } from "./execute-zu08sWGG.js";
3
+ import { n as createWorkflowError } from "./errors-CZf7oz4k.js";
4
+ import { i as runWorkflowProviderOperation, n as getWorkflowProviderStatus, t as toWorkflowRunError } from "./run-error-zZh1_IBo.js";
5
+ import { t as emitWorkflowFailed } from "./run-failed-BcSjSU2t.js";
6
+ import { t as resolveOpenWorkflowStorage } from "./openworkflow-storage-Dde_f0es.js";
7
+ import { t as workflowErrorDiagnostics } from "./error-diagnostics-35AEmfve.js";
8
+ import { t as defaultOpenWorkflowSqlitePath } from "./openworkflow-defaults-1n0DbLdb.js";
9
+ import { deserializeResponse, isSerializedResponse } from "@vite-hub/runtime/internal/response";
10
+ // src/runtime/openworkflow-slots.ts
11
+ const table = "vitehub_workflow_slots";
12
+ const endedStatuses = [
13
+ "completed",
14
+ "succeeded",
15
+ "failed",
16
+ "canceled"
17
+ ];
18
+ function isSqliteConnection(value) {
19
+ return typeof value === "object" && value !== null && typeof Reflect.get(value, "prepare") === "function" && typeof Reflect.get(value, "exec") === "function";
20
+ }
21
+ function isPostgresConnection(value) {
22
+ return typeof value === "function" && typeof Reflect.get(value, "begin") === "function";
23
+ }
24
+ function readCount(row) {
25
+ const count = typeof row === "object" && row !== null ? Reflect.get(row, "count") : void 0;
26
+ return Number(count ?? 0);
27
+ }
28
+ function createSqliteSlots(db, namespaceId) {
29
+ let ready = false;
30
+ const prepare = () => {
31
+ if (ready) return;
32
+ db.exec(`CREATE TABLE IF NOT EXISTS "${table}" ("namespace_id" TEXT NOT NULL, "workflow_name" TEXT NOT NULL, "workflow_run_id" TEXT NOT NULL, "acquired_at" TEXT NOT NULL, PRIMARY KEY ("namespace_id", "workflow_name", "workflow_run_id"))`);
33
+ ready = true;
34
+ };
35
+ const transaction = (run) => {
36
+ prepare();
37
+ db.exec("BEGIN IMMEDIATE");
38
+ try {
39
+ const value = run();
40
+ db.exec("COMMIT");
41
+ return value;
42
+ } catch (error) {
43
+ db.exec("ROLLBACK");
44
+ throw error;
45
+ }
46
+ };
47
+ const ended = endedStatuses.map((status) => `'${status}'`).join(", ");
48
+ return (workflow, run) => ({
49
+ acquire: async (limit) => transaction(() => {
50
+ db.prepare(`DELETE FROM "${table}" WHERE "namespace_id" = ? AND "workflow_name" = ? AND NOT EXISTS (SELECT 1 FROM "workflow_runs" WHERE "workflow_runs"."namespace_id" = "${table}"."namespace_id" AND "workflow_runs"."id" = "${table}"."workflow_run_id" AND "workflow_runs"."status" NOT IN (${ended}))`).run(namespaceId, workflow);
51
+ if (db.prepare(`SELECT 1 AS "held" FROM "${table}" WHERE "namespace_id" = ? AND "workflow_name" = ? AND "workflow_run_id" = ?`).get(namespaceId, workflow, run)) return true;
52
+ if (readCount(db.prepare(`SELECT COUNT(*) AS "count" FROM "${table}" WHERE "namespace_id" = ? AND "workflow_name" = ?`).get(namespaceId, workflow)) >= limit) return false;
53
+ db.prepare(`INSERT INTO "${table}" ("namespace_id", "workflow_name", "workflow_run_id", "acquired_at") VALUES (?, ?, ?, ?)`).run(namespaceId, workflow, run, (/* @__PURE__ */ new Date()).toISOString());
54
+ return true;
55
+ }),
56
+ release: async () => {
57
+ prepare();
58
+ db.prepare(`DELETE FROM "${table}" WHERE "namespace_id" = ? AND "workflow_name" = ? AND "workflow_run_id" = ?`).run(namespaceId, workflow, run);
59
+ }
60
+ });
61
+ }
62
+ function createPostgresSlots(sql, namespaceId, schema) {
63
+ let ready;
64
+ const slots = () => sql(schema);
65
+ const runs = () => sql("workflow_runs");
66
+ const slotTable = () => sql(table);
67
+ const prepare = () => ready ??= sql.begin(async (tx) => {
68
+ await tx`SELECT pg_advisory_xact_lock(hashtext(${`${schema}.${table}`}))`;
69
+ await tx`CREATE TABLE IF NOT EXISTS ${slots()}.${slotTable()} ("namespace_id" TEXT NOT NULL, "workflow_name" TEXT NOT NULL, "workflow_run_id" TEXT NOT NULL, "acquired_at" TIMESTAMPTZ NOT NULL DEFAULT now(), PRIMARY KEY ("namespace_id", "workflow_name", "workflow_run_id"))`;
70
+ }).catch((error) => {
71
+ ready = void 0;
72
+ throw error;
73
+ });
74
+ return (workflow, run) => ({
75
+ acquire: async (limit) => {
76
+ await prepare();
77
+ return await sql.begin(async (tx) => {
78
+ await tx`SELECT pg_advisory_xact_lock(hashtext(${`${schema}.${table}:${namespaceId}:${workflow}`}))`;
79
+ await tx`DELETE FROM ${slots()}.${slotTable()} AS "slot" WHERE "namespace_id" = ${namespaceId} AND "workflow_name" = ${workflow} AND NOT EXISTS (SELECT 1 FROM ${slots()}.${runs()} AS "run" WHERE "run"."namespace_id" = "slot"."namespace_id" AND "run"."id"::text = "slot"."workflow_run_id" AND "run"."status"::text <> ALL(${endedStatuses}::text[]))`;
80
+ const [held] = await tx`SELECT 1 AS "held" FROM ${slots()}.${slotTable()} WHERE "namespace_id" = ${namespaceId} AND "workflow_name" = ${workflow} AND "workflow_run_id" = ${run}`;
81
+ if (held) return true;
82
+ const [row] = await tx`SELECT COUNT(*) AS "count" FROM ${slots()}.${slotTable()} WHERE "namespace_id" = ${namespaceId} AND "workflow_name" = ${workflow}`;
83
+ if (readCount(row) >= limit) return false;
84
+ await tx`INSERT INTO ${slots()}.${slotTable()} ("namespace_id", "workflow_name", "workflow_run_id") VALUES (${namespaceId}, ${workflow}, ${run})`;
85
+ return true;
86
+ });
87
+ },
88
+ release: async () => {
89
+ await prepare();
90
+ await sql`DELETE FROM ${slots()}.${slotTable()} WHERE "namespace_id" = ${namespaceId} AND "workflow_name" = ${workflow} AND "workflow_run_id" = ${run}`;
91
+ }
92
+ });
93
+ }
94
+ /**
95
+ * Keeps the places of the Workflows that set `concurrency` in the OpenWorkflow database, next to `workflow_runs`, through
96
+ * the connection that the backend keeps in `db` (SQLite) or `pg` (Postgres). A place belongs to a run id. Each count first
97
+ * drops the places of runs that ended or no longer exist, so a run that failed without `release()` frees its place.
98
+ *
99
+ * SQLite is synchronous, so no other code of this process runs inside a transaction, and `BEGIN IMMEDIATE` keeps out the
100
+ * other processes that share the file. Postgres takes an advisory lock per Workflow, and one more around `CREATE TABLE`,
101
+ * because two servers that create the table at the same time can both fail on its type name.
102
+ */
103
+ function createOpenWorkflowSlots(backend, storage) {
104
+ const connection = Reflect.get(backend, storage.backend === "sqlite" ? "db" : "pg");
105
+ if (storage.backend === "sqlite" && isSqliteConnection(connection)) return createSqliteSlots(connection, storage.namespaceId);
106
+ if (storage.backend === "postgres" && isPostgresConnection(connection)) return createPostgresSlots(connection, storage.namespaceId, storage.schema);
107
+ throw invariantError(`OpenWorkflow backends keep their connection in \`db\` (SQLite) or \`pg\` (Postgres), but the ${storage.backend} backend has no connection that can count Workflow runs`);
108
+ }
109
+ // src/runtime/openworkflow.ts
110
+ const defaultImporter = (specifier) => import(
111
+ /* @vite-ignore */
112
+ specifier
113
+ );
114
+ let openWorkflowImporter = defaultImporter;
115
+ let runtimes = /* @__PURE__ */ new Map();
116
+ async function importOpenWorkflowModule(specifier, importer) {
117
+ return await runWorkflowProviderOperation("openworkflow", "import", () => importer(specifier));
118
+ }
119
+ function readEnv(name) {
120
+ const value = (globalThis.process?.env)?.[name];
121
+ return typeof value === "string" && value.trim() ? value.trim() : void 0;
122
+ }
123
+ function resolveRuntimeConfigValue(value) {
124
+ if (typeof value === "string" || typeof value === "undefined") return value;
125
+ for (const name of getRuntimeEnvNames(value)) {
126
+ const resolved = readEnv(name);
127
+ if (resolved) return resolved;
128
+ }
129
+ return typeof value.default === "string" && value.default.trim() ? value.default.trim() : void 0;
130
+ }
131
+ function getRuntimeEnvNames(value) {
132
+ return value.source?.names ?? (value.source?.name ? [value.source.name] : []);
133
+ }
134
+ function normalizeSqlitePath(path) {
135
+ if (/^(?:libsql:|https?:\/\/)/i.test(path)) throw workflowErrorDiagnostics.WORKFLOW_R0018({ message: `OpenWorkflow SQLite storage requires a local SQLite file path, received ${JSON.stringify(path)}.` });
136
+ if (/^[a-z][a-z0-9+.-]*:/i.test(path) && !path.startsWith("file:")) throw workflowErrorDiagnostics.WORKFLOW_R0019({ message: `OpenWorkflow SQLite storage received unsupported storage URL ${JSON.stringify(path)}.` });
137
+ return path.startsWith("file:") ? path.slice(5) : path;
138
+ }
139
+ async function prepareSqlitePath(path, importer) {
140
+ if (path !== ":memory:") {
141
+ const [{ mkdirSync }, { dirname }] = await Promise.all([importOpenWorkflowModule("node:fs", importer), importOpenWorkflowModule("node:path", importer)]);
142
+ mkdirSync(dirname(path), { recursive: true });
143
+ }
144
+ return path;
145
+ }
146
+ let databaseUrlResolver;
147
+ /**
148
+ * Makes OpenWorkflow use the Postgres Default Database of the app when no OpenWorkflow storage is configured. The
149
+ * generated startup plugin installs it when the build has a Postgres Default Database.
150
+ */
151
+ function setOpenWorkflowDatabaseUrl(resolve) {
152
+ databaseUrlResolver = resolve;
153
+ }
154
+ function readDatabasePostgresUrl() {
155
+ if (!databaseUrlResolver) return void 0;
156
+ const url = databaseUrlResolver()?.trim();
157
+ if (!url) throw workflowErrorDiagnostics.WORKFLOW_OPENWORKFLOW_DATABASE_URL_MISSING();
158
+ return url;
159
+ }
160
+ function getOpenWorkflowConfig(config) {
161
+ if (config.driver !== "openworkflow") throw workflowErrorDiagnostics.WORKFLOW_R0020({ message: `OpenWorkflow runtime requires workflow.driver "openworkflow", received "${config.driver}".` });
162
+ 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." });
163
+ const sqlite = config.sqlite || {};
164
+ const postgres = config.postgres || {};
165
+ if (postgres.url !== void 0 && sqlite.path !== void 0) throw workflowErrorDiagnostics.WORKFLOW_R0030({ message: "`workflow.postgres.url` and `workflow.sqlite.path` cannot both configure OpenWorkflow storage." });
166
+ const explicitSqlitePath = resolveRuntimeConfigValue(sqlite.path);
167
+ const explicitPostgresUrl = resolveRuntimeConfigValue(postgres.url)?.trim();
168
+ 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." });
169
+ 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." });
170
+ const storage = resolveOpenWorkflowStorage({
171
+ postgresUrl: explicitPostgresUrl,
172
+ sqlitePath: explicitSqlitePath
173
+ }, readEnv);
174
+ if (storage.backend === "sqlite" && storage.source !== "default") return {
175
+ backend: "sqlite",
176
+ namespaceId: sqlite.namespaceId || readEnv("OPENWORKFLOW_NAMESPACE_ID") || "production",
177
+ path: normalizeSqlitePath(storage.path),
178
+ runMigrations: sqlite.runMigrations,
179
+ source: "configured"
180
+ };
181
+ const configuredUrl = storage.backend === "postgres" ? storage.url : void 0;
182
+ const url = configuredUrl || readDatabasePostgresUrl();
183
+ if (url) return {
184
+ backend: "postgres",
185
+ namespaceId: postgres.namespaceId || readEnv("OPENWORKFLOW_NAMESPACE_ID") || "production",
186
+ runMigrations: postgres.runMigrations,
187
+ schema: postgres.schema || readEnv("OPENWORKFLOW_SCHEMA") || "openworkflow",
188
+ source: configuredUrl ? "configured" : "database",
189
+ url
190
+ };
191
+ if (/^postgres(?:ql)?:\/\//i.test(readEnv("DATABASE_URL") || "")) throw workflowErrorDiagnostics.WORKFLOW_OPENWORKFLOW_DATABASE_URL_IGNORED();
192
+ return {
193
+ backend: "sqlite",
194
+ namespaceId: sqlite.namespaceId || readEnv("OPENWORKFLOW_NAMESPACE_ID") || "production",
195
+ path: defaultOpenWorkflowSqlitePath,
196
+ runMigrations: sqlite.runMigrations,
197
+ source: "default"
198
+ };
199
+ }
200
+ const postgresSetupWaitMs = 12e4;
201
+ const postgresSecondConnectionTimeoutMs = 1e4;
202
+ function sleep(ms) {
203
+ return new Promise((resolve) => setTimeout(resolve, ms).unref?.());
204
+ }
205
+ function settlesWithin(task, ms) {
206
+ let timer;
207
+ return Promise.race([task.then(() => true), new Promise((resolve) => {
208
+ timer = setTimeout(() => resolve(false), ms);
209
+ timer.unref?.();
210
+ })]).finally(() => clearTimeout(timer));
211
+ }
212
+ async function withPostgresSetupLock(postgres, url, schema, setup) {
213
+ const sql = postgres.default(url, {
214
+ idle_timeout: 1,
215
+ max: 1,
216
+ onnotice: () => {}
217
+ });
218
+ const key = `vitehub:openworkflow:${schema}`;
219
+ const deadline = Date.now() + postgresSetupWaitMs;
220
+ try {
221
+ for (let attempt = 1;; attempt++) {
222
+ let result;
223
+ await sql.begin(async (transaction) => {
224
+ const [lock] = await transaction`select pg_try_advisory_xact_lock(hashtextextended(${key}, 0)) as locked`;
225
+ if (!lock?.locked) return;
226
+ const probe = postgres.default(url, {
227
+ max: 1,
228
+ onnotice: () => {}
229
+ });
230
+ const answered = Promise.resolve(probe`select 1`).then(() => {}, () => {});
231
+ if (!await settlesWithin(answered, postgresSecondConnectionTimeoutMs)) {
232
+ answered.then(() => probe.end());
233
+ throw workflowErrorDiagnostics.WORKFLOW_OPENWORKFLOW_SETUP_CONNECTION_UNAVAILABLE();
234
+ }
235
+ await probe.end();
236
+ result = { value: await setup() };
237
+ });
238
+ if (result) return result.value;
239
+ if (Date.now() >= deadline) throw workflowErrorDiagnostics.WORKFLOW_OPENWORKFLOW_SETUP_LOCK_TIMEOUT({ seconds: postgresSetupWaitMs / 1e3 });
240
+ await sleep(Math.min(250 * attempt, 2e3));
241
+ }
242
+ } finally {
243
+ await sql.end({ timeout: 5 });
244
+ }
245
+ }
246
+ function reportFailedRuns(backend, definitions) {
247
+ const failWorkflowRun = async (params) => {
248
+ const run = await backend.failWorkflowRun(params);
249
+ if (run.status === "failed") await emitWorkflowFailed(run.workflowName, run.idempotencyKey || run.id, run.error ?? params.error, definitions.get(run.workflowName));
250
+ return run;
251
+ };
252
+ return new Proxy(backend, { get(target, property) {
253
+ if (property === "failWorkflowRun") return failWorkflowRun;
254
+ const value = Reflect.get(target, property);
255
+ return typeof value === "function" ? value.bind(target) : value;
256
+ } });
257
+ }
258
+ async function createOpenWorkflowRuntime(options, importer) {
259
+ const definitions = /* @__PURE__ */ new Map();
260
+ const [{ OpenWorkflow }, backendModule] = await Promise.all([importOpenWorkflowModule("openworkflow", importer), options.backend === "sqlite" ? importOpenWorkflowModule("openworkflow/sqlite", importer) : importOpenWorkflowModule("openworkflow/postgres", importer)]);
261
+ const { backend, client } = await runWorkflowProviderOperation("openworkflow", "connect", async () => {
262
+ let backend;
263
+ if (options.backend === "sqlite") backend = await backendModule.BackendSqlite.connect(await prepareSqlitePath(options.path, importer), {
264
+ namespaceId: options.namespaceId,
265
+ ...typeof options.runMigrations === "boolean" ? { runMigrations: options.runMigrations } : {}
266
+ });
267
+ else {
268
+ const { BackendPostgres } = backendModule;
269
+ const connect = () => BackendPostgres.connect(options.url, {
270
+ namespaceId: options.namespaceId,
271
+ ...typeof options.runMigrations === "boolean" ? { runMigrations: options.runMigrations } : {},
272
+ schema: options.schema
273
+ });
274
+ backend = options.runMigrations === false ? await connect() : await withPostgresSetupLock(await importOpenWorkflowModule("postgres", importer), options.url, options.schema, connect);
275
+ }
276
+ return {
277
+ backend,
278
+ client: new OpenWorkflow({ backend: reportFailedRuns(backend, definitions) })
279
+ };
280
+ });
281
+ let slots;
282
+ return {
283
+ backend,
284
+ client,
285
+ definitions,
286
+ findRunId: createRunIdLookup(backend, options),
287
+ findRuns: createStoredRunLookup(backend, options),
288
+ slots: (workflow, run) => (slots ??= createOpenWorkflowSlots(backend, options.backend === "sqlite" ? {
289
+ backend: "sqlite",
290
+ namespaceId: options.namespaceId
291
+ } : {
292
+ backend: "postgres",
293
+ namespaceId: options.namespaceId,
294
+ schema: options.schema
295
+ }))(workflow, run),
296
+ workflows: /* @__PURE__ */ new Map()
297
+ };
298
+ }
299
+ function isSqliteHandle(value) {
300
+ return typeof value === "object" && value !== null && "prepare" in value && typeof value.prepare === "function";
301
+ }
302
+ function isPostgresHandle(value) {
303
+ return typeof value === "function";
304
+ }
305
+ function readRowId(row) {
306
+ if (typeof row !== "object" || row === null) return void 0;
307
+ return "id" in row && typeof row.id === "string" ? row.id : void 0;
308
+ }
309
+ function missingBackendConnection(backend) {
310
+ throw invariantError(`OpenWorkflow backends keep their connection in \`db\` (SQLite) or \`pg\` (Postgres), but the ${backend} backend has neither`);
311
+ }
312
+ function createRunIdLookup(backend, options) {
313
+ const connection = Reflect.get(backend, options.backend === "sqlite" ? "db" : "pg");
314
+ return async (name, key) => {
315
+ 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));
316
+ if (options.backend === "postgres" && isPostgresHandle(connection)) {
317
+ 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`;
318
+ return readRowId(row);
319
+ }
320
+ return missingBackendConnection(options.backend);
321
+ };
322
+ }
323
+ function readStoredRunIdentity(row) {
324
+ if (typeof row !== "object" || row === null) return void 0;
325
+ const id = readRowId(row);
326
+ return id !== void 0 && "workflowName" in row && typeof row.workflowName === "string" ? {
327
+ id,
328
+ workflow: row.workflowName
329
+ } : void 0;
330
+ }
331
+ function createStoredRunLookup(backend, options) {
332
+ const connection = Reflect.get(backend, options.backend === "sqlite" ? "db" : "pg");
333
+ return async (id, name) => {
334
+ let rows;
335
+ if (options.backend === "sqlite" && isSqliteHandle(connection)) rows = connection.prepare(`SELECT "id", "workflow_name" AS "workflowName" FROM "workflow_runs" WHERE "namespace_id" = ? AND "workflow_name" = COALESCE(?, "workflow_name") AND ("id" = ? OR "idempotency_key" = ?) ORDER BY "workflow_name", ("id" = ?) DESC, "created_at", "id"`).all(options.namespaceId, name ?? null, id, id, id);
336
+ else if (options.backend === "postgres" && isPostgresHandle(connection)) rows = await connection`SELECT "id", "workflow_name" AS "workflowName" FROM ${connection(options.schema)}.${connection("workflow_runs")} WHERE "namespace_id" = ${options.namespaceId} AND "workflow_name" = COALESCE(${name ?? null}, "workflow_name") AND ("id"::text = ${id} OR "idempotency_key" = ${id}) ORDER BY "workflow_name", ("id"::text = ${id}) DESC, "created_at", "id"`;
337
+ else return missingBackendConnection(options.backend);
338
+ const matches = /* @__PURE__ */ new Map();
339
+ for (const row of rows) {
340
+ const run = readStoredRunIdentity(row);
341
+ if (run && !matches.has(run.workflow)) matches.set(run.workflow, run);
342
+ }
343
+ return [...matches.values()];
344
+ };
345
+ }
346
+ /** The storage that OpenWorkflow uses for `config` now, without credentials. */
347
+ function describeOpenWorkflowStorage(config) {
348
+ const storage = getOpenWorkflowConfig(config);
349
+ return storage.backend === "sqlite" ? {
350
+ backend: "sqlite",
351
+ location: storage.path,
352
+ source: storage.source
353
+ } : {
354
+ backend: "postgres",
355
+ location: `schema ${storage.schema}`,
356
+ source: storage.source
357
+ };
358
+ }
359
+ async function getOpenWorkflowRuntime(config) {
360
+ const cache = runtimes;
361
+ const options = getOpenWorkflowConfig(config);
362
+ const key = JSON.stringify(options);
363
+ let runtime = cache.get(key);
364
+ if (!runtime) {
365
+ runtime = createOpenWorkflowRuntime(options, openWorkflowImporter);
366
+ cache.set(key, runtime);
367
+ runtime.catch(() => {
368
+ if (cache.get(key) === runtime) cache.delete(key);
369
+ });
370
+ }
371
+ const resolved = await runtime;
372
+ if (cache !== runtimes) throw createWorkflowError({
373
+ code: "OPENWORKFLOW_RUNTIME_RESET",
374
+ details: { provider: "openworkflow" }
375
+ });
376
+ return resolved;
377
+ }
378
+ const maximumRetryIntervalMs = 31536e6;
379
+ function openWorkflowRetry(name, options) {
380
+ const { backoff, delay, limit } = resolveWorkflowStepOptions(name, options).retries;
381
+ const initial = Math.min(toDurationMilliseconds(delay), maximumRetryIntervalMs);
382
+ const coefficient = backoff === "exponential" ? 2 : 1;
383
+ const delayAfter = (attempt) => initial === 0 ? 0 : Math.min(initial * coefficient ** (attempt - 1), maximumRetryIntervalMs);
384
+ return {
385
+ limit,
386
+ policy: {
387
+ backoffCoefficient: coefficient,
388
+ initialInterval: `${initial}ms`,
389
+ maximumAttempts: limit + 1,
390
+ maximumInterval: `${delayAfter(Math.max(limit, 1))}ms`
391
+ },
392
+ delayAfter
393
+ };
394
+ }
395
+ const openWorkflowControlErrorNames = /* @__PURE__ */ new Set([
396
+ "SleepSignal",
397
+ "StaleExecutionBranchError",
398
+ "StepError",
399
+ "StepLimitExceededError"
400
+ ]);
401
+ function isOpenWorkflowControlError(error) {
402
+ return error instanceof Error && openWorkflowControlErrorNames.has(error.name);
403
+ }
404
+ function toFailedStepResult(error) {
405
+ if (!(error instanceof Error)) return { "~vitehubStepError": {
406
+ message: String(error),
407
+ name: "Error"
408
+ } };
409
+ return { "~vitehubStepError": {
410
+ ..."code" in error && typeof error.code === "string" ? { code: error.code } : {},
411
+ message: error.message,
412
+ name: error.name
413
+ } };
414
+ }
415
+ function readFailedStepResult(value) {
416
+ if (typeof value !== "object" || value === null || !("~vitehubStepError" in value)) return void 0;
417
+ const payload = value["~vitehubStepError"];
418
+ if (typeof payload !== "object" || payload === null || !("message" in payload) || !("name" in payload)) return void 0;
419
+ const { message, name } = payload;
420
+ const code = "code" in payload ? payload.code : void 0;
421
+ if (typeof message !== "string" || typeof name !== "string" || code !== void 0 && typeof code !== "string") return void 0;
422
+ const error = new Error(message);
423
+ error.name = name;
424
+ return code === void 0 ? error : Object.assign(error, { code });
425
+ }
426
+ function createOpenWorkflowStepNames() {
427
+ const used = /* @__PURE__ */ new Set();
428
+ const nextIndex = /* @__PURE__ */ new Map();
429
+ return (name) => {
430
+ if (!used.has(name)) {
431
+ used.add(name);
432
+ return name;
433
+ }
434
+ for (let index = nextIndex.get(name) ?? 1;; index++) {
435
+ const resolved = `${name}:${index}`;
436
+ if (used.has(resolved)) continue;
437
+ nextIndex.set(name, index + 1);
438
+ used.add(resolved);
439
+ return resolved;
440
+ }
441
+ };
442
+ }
443
+ function createOpenWorkflowExecution(step, workflow, attempts) {
444
+ let pending;
445
+ let retryWait;
446
+ const names = createOpenWorkflowStepNames();
447
+ const latest = /* @__PURE__ */ new Map();
448
+ const failures = /* @__PURE__ */ new Map();
449
+ for (const attempt of attempts) {
450
+ latest.set(attempt.stepName, attempt);
451
+ if (attempt.status === "failed") failures.set(attempt.stepName, (failures.get(attempt.stepName) ?? 0) + 1);
452
+ }
453
+ function throwPending() {
454
+ if (pending) throw pending;
455
+ }
456
+ async function control(operation) {
457
+ if (retryWait) await retryWait;
458
+ throwPending();
459
+ try {
460
+ return await operation();
461
+ } catch (error) {
462
+ if (isOpenWorkflowControlError(error)) pending ??= error;
463
+ throw error;
464
+ }
465
+ }
466
+ return {
467
+ async settle(handler) {
468
+ const outcome = await handler.then((value) => ({ value }), (error) => ({ error }));
469
+ if (retryWait) await retryWait;
470
+ throwPending();
471
+ if ("error" in outcome) throw outcome.error;
472
+ return outcome.value;
473
+ },
474
+ step: {
475
+ do: async (name, options, run) => {
476
+ const output = await control(async () => {
477
+ const stepName = names(name);
478
+ const { delayAfter, limit, policy } = openWorkflowRetry(name, options);
479
+ const failed = failures.get(stepName) ?? 0;
480
+ const last = latest.get(stepName);
481
+ if (last?.status === "failed" && last.finishedAt && failed <= limit) {
482
+ const remaining = Math.ceil(last.finishedAt.getTime() + delayAfter(failed) - Date.now());
483
+ if (remaining > 0) {
484
+ retryWait = step.sleep(`~vitehubRetry:${last.id}`, `${remaining}ms`);
485
+ await retryWait;
486
+ }
487
+ }
488
+ return await step.run({
489
+ name,
490
+ retryPolicy: policy
491
+ }, async () => {
492
+ try {
493
+ return await withWorkflowStepTimeout(name, options.timeout, run)();
494
+ } catch (error) {
495
+ const result = toNonRetryableStepResult(error);
496
+ if (result) return result;
497
+ if (failed >= limit) return toFailedStepResult(error);
498
+ throw error;
499
+ }
500
+ });
501
+ });
502
+ const error = readNonRetryableStepResult(output) ?? readFailedStepResult(output);
503
+ if (error) throw error;
504
+ return output;
505
+ },
506
+ sleep: async (name, milliseconds) => await control(async () => {
507
+ names(name);
508
+ await step.sleep(name, `${milliseconds}ms`);
509
+ }),
510
+ waitForSignal: async (name, token) => await control(async () => {
511
+ names(name);
512
+ const received = await step.waitForSignal({
513
+ name,
514
+ signal: token
515
+ });
516
+ if (received === null) throw workflowErrorDiagnostics.WORKFLOW_SIGNAL_TIMEOUT({ name: workflow });
517
+ return received.data;
518
+ })
519
+ }
520
+ };
521
+ }
522
+ /**
523
+ * Sends `value` to a live run that waits for the signal `token`. OpenWorkflow drops early signals and can match
524
+ * a wait left behind by cancellation, so check the run before sending.
525
+ */
526
+ async function resumeOpenWorkflowSignal(config, workflow, id, token, value) {
527
+ const runtime = await getOpenWorkflowRuntime(config);
528
+ return await runWorkflowProviderOperation("openworkflow", "resume-signal", async () => {
529
+ const run = await runtime.backend.getWorkflowRun({ workflowRunId: await runtime.findRunId(workflow, id) ?? id });
530
+ if (!run || run.workflowName !== workflow || terminalOpenWorkflowStatuses.has(normalizeOpenWorkflowStatus(run.status))) return false;
531
+ const { workflowRunIds } = await runtime.client.sendSignal({
532
+ data: value,
533
+ signal: token
534
+ });
535
+ return workflowRunIds.includes(run.id);
536
+ });
537
+ }
538
+ async function registerOpenWorkflowDefinition(runtime, name, definition) {
539
+ const existing = runtime.workflows.get(name);
540
+ if (existing) return existing;
541
+ const openWorkflowDefinition = definition;
542
+ runtime.definitions.set(name, definition);
543
+ const workflow = runtime.client.defineWorkflow({ name }, async ({ input, run, step }) => {
544
+ const stored = await runtime.backend.getWorkflowRun({ workflowRunId: run.id });
545
+ const execution = createOpenWorkflowExecution(step, name, await listOpenWorkflowStepAttempts(runtime.backend, run.id));
546
+ return await execution.settle(runSerializedWorkflowHandler({
547
+ id: stored?.idempotencyKey || run.id,
548
+ name,
549
+ payload: input,
550
+ provider: "openworkflow",
551
+ ...definition.concurrency === void 0 ? {} : { slots: runtime.slots(name, run.id) },
552
+ step: execution.step
553
+ }, openWorkflowDefinition));
554
+ });
555
+ runtime.workflows.set(name, workflow);
556
+ return workflow;
557
+ }
558
+ function normalizeOpenWorkflowStatus(status) {
559
+ switch (String(status || "").toLowerCase()) {
560
+ case "completed":
561
+ case "succeeded": return "completed";
562
+ case "canceled": return "cancelled";
563
+ case "failed": return "failed";
564
+ case "pending": return "queued";
565
+ case "running":
566
+ case "sleeping": return "running";
567
+ default: return "unknown";
568
+ }
569
+ }
570
+ function serializeOpenWorkflowRun(run, name) {
571
+ if (!run || run.workflowName !== name) return {
572
+ id: run?.id || "",
573
+ provider: "openworkflow",
574
+ status: "unknown"
575
+ };
576
+ const result = isSerializedResponse(run.output) ? deserializeResponse(run.output) : run.output;
577
+ const status = normalizeOpenWorkflowStatus(run.status);
578
+ return {
579
+ ...status === "failed" ? { error: toWorkflowRunError(run.error) } : {},
580
+ ...run.finishedAt ? { completedAt: run.finishedAt } : {},
581
+ createdAt: run.createdAt,
582
+ ...run.startedAt ? { startedAt: run.startedAt } : {},
583
+ id: run.idempotencyKey || run.id,
584
+ metadata: {
585
+ namespaceId: run.namespaceId,
586
+ version: run.version,
587
+ workflowName: run.workflowName
588
+ },
589
+ payload: run.input,
590
+ provider: "openworkflow",
591
+ result,
592
+ status
593
+ };
594
+ }
595
+ function toWorkflowRunStepError(error) {
596
+ const message = typeof error === "object" && error !== null && "message" in error ? error.message : void 0;
597
+ return { message: typeof message === "string" && message ? message : "Workflow step failed." };
598
+ }
599
+ function toWorkflowRunSteps(attempts) {
600
+ const steps = /* @__PURE__ */ new Map();
601
+ for (const attempt of attempts) {
602
+ const nonRetryable = readNonRetryableStepResult(attempt.output) ?? readFailedStepResult(attempt.output);
603
+ steps.set(attempt.stepName, {
604
+ attempt: (steps.get(attempt.stepName)?.attempt ?? 0) + 1,
605
+ ...attempt.finishedAt ? { completedAt: attempt.finishedAt } : {},
606
+ ...attempt.status === "failed" || nonRetryable ? { error: toWorkflowRunStepError(nonRetryable ?? attempt.error) } : {},
607
+ id: attempt.id,
608
+ name: attempt.stepName,
609
+ ...attempt.context?.kind === "sleep" ? { sleepUntil: new Date(attempt.context.resumeAt) } : {},
610
+ ...attempt.startedAt ? { startedAt: attempt.startedAt } : {},
611
+ status: nonRetryable ? "failed" : normalizeOpenWorkflowStatus(attempt.status)
612
+ });
613
+ }
614
+ return [...steps.values()];
615
+ }
616
+ async function listOpenWorkflowStepAttempts(backend, workflowRunId) {
617
+ const attempts = [];
618
+ let after;
619
+ do {
620
+ const page = await backend.listStepAttempts({
621
+ workflowRunId,
622
+ limit: 100,
623
+ ...after ? { after } : {}
624
+ });
625
+ attempts.push(...page.data);
626
+ after = page.pagination.next ?? void 0;
627
+ } while (after);
628
+ return attempts;
629
+ }
630
+ async function runOpenWorkflow(config, name, payload, definition, options, onDispatch, startAt) {
631
+ const runtime = await getOpenWorkflowRuntime(config);
632
+ const workflow = await registerOpenWorkflowDefinition(runtime, name, definition);
633
+ onDispatch?.();
634
+ let firstAcknowledgementUnknown = false;
635
+ const handle = await runWorkflowProviderOperation("openworkflow", "run", async () => {
636
+ const existingId = options.id ? await runtime.findRunId(name, options.id) ?? options.id : void 0;
637
+ const existing = existingId ? await runtime.backend.getWorkflowRun({ workflowRunId: existingId }) : null;
638
+ if (existing?.workflowName === name) return { workflowRun: existing };
639
+ const runOptions = options.id || startAt !== void 0 ? {
640
+ ...options.id ? { idempotencyKey: options.id } : {},
641
+ ...startAt === void 0 ? {} : { availableAt: new Date(startAt) }
642
+ } : void 0;
643
+ const start = () => workflow.run(payload, runOptions);
644
+ return await start().catch((error) => {
645
+ if (!options.id) throw error;
646
+ firstAcknowledgementUnknown = getWorkflowProviderStatus(error) === void 0;
647
+ return start();
648
+ });
649
+ }, { acknowledgement: (_error, status) => firstAcknowledgementUnknown || status === void 0 ? "unknown" : status < 500 ? "rejected" : void 0 });
650
+ return await runWorkflowProviderOperation("openworkflow", "run", async () => {
651
+ return {
652
+ ...serializeOpenWorkflowRun(handle.workflowRun, name),
653
+ metadata: {
654
+ ...options.id ? { idempotencyKey: options.id } : {},
655
+ workflow: name
656
+ },
657
+ payload: handle.workflowRun.input
658
+ };
659
+ });
660
+ }
661
+ async function getOpenWorkflowRun(config, name, id, lookup = "key-or-id") {
662
+ const runtime = await getOpenWorkflowRuntime(config);
663
+ return await runWorkflowProviderOperation("openworkflow", "get", async () => {
664
+ const workflowRunId = lookup === "provider-id" ? id : await runtime.findRunId(name, id) ?? id;
665
+ const run = await runtime.backend.getWorkflowRun({ workflowRunId });
666
+ if (!run || run.workflowName !== name) return {
667
+ id,
668
+ provider: "openworkflow",
669
+ status: "unknown"
670
+ };
671
+ return {
672
+ ...serializeOpenWorkflowRun(run, name),
673
+ steps: toWorkflowRunSteps(await listOpenWorkflowStepAttempts(runtime.backend, run.id))
674
+ };
675
+ });
676
+ }
677
+ async function findOpenWorkflowRuns(config, id, name) {
678
+ const runtime = await getOpenWorkflowRuntime(config);
679
+ return await runWorkflowProviderOperation("openworkflow", "get-run", async () => await runtime.findRuns(id, name));
680
+ }
681
+ const openWorkflowRunStatuses = {
682
+ completed: ["completed", "succeeded"],
683
+ failed: ["failed"],
684
+ queued: ["pending"],
685
+ running: ["running", "sleeping"]
686
+ };
687
+ /** Lists the stored OpenWorkflow runs, newest first, with the number of steps of each run. */
688
+ async function listOpenWorkflowRuns(config, input) {
689
+ const runtime = await getOpenWorkflowRuntime(config);
690
+ return await runWorkflowProviderOperation("openworkflow", "list-runs", async () => {
691
+ const statuses = input.status ? openWorkflowRunStatuses[input.status] : [void 0];
692
+ const runs = (await Promise.all(statuses.map(async (status) => await runtime.backend.listWorkflowRuns({
693
+ limit: input.limit,
694
+ ...status ? { status } : {},
695
+ ...input.workflow ? { workflowName: input.workflow } : {}
696
+ })))).flatMap((page) => page.data).sort((left, right) => right.createdAt.getTime() - left.createdAt.getTime()).slice(0, input.limit);
697
+ return await Promise.all(runs.map(async (run) => ({
698
+ run: serializeOpenWorkflowRun(run, run.workflowName),
699
+ stepCount: toWorkflowRunSteps(await listOpenWorkflowStepAttempts(runtime.backend, run.id)).length,
700
+ workflow: run.workflowName
701
+ })));
702
+ });
703
+ }
704
+ const terminalOpenWorkflowStatuses = /* @__PURE__ */ new Set([
705
+ "cancelled",
706
+ "completed",
707
+ "failed"
708
+ ]);
709
+ async function cancelOpenWorkflowRun(config, name, id, lookup = "key-or-id") {
710
+ const current = await getOpenWorkflowRun(config, name, id, lookup);
711
+ if (current.status === "unknown" || terminalOpenWorkflowStatuses.has(current.status)) return current;
712
+ const runtime = await getOpenWorkflowRuntime(config);
713
+ try {
714
+ await runWorkflowProviderOperation("openworkflow", "cancel", async () => await runtime.client.cancelWorkflowRun(lookup === "provider-id" ? id : await runtime.findRunId(name, id) ?? id));
715
+ } catch (error) {
716
+ const latest = await getOpenWorkflowRun(config, name, id, lookup).catch(() => void 0);
717
+ if (latest && terminalOpenWorkflowStatuses.has(latest.status)) return latest;
718
+ throw error;
719
+ }
720
+ return await getOpenWorkflowRun(config, name, id, lookup);
721
+ }
722
+ async function resetOpenWorkflowRuntime() {
723
+ openWorkflowImporter = defaultImporter;
724
+ databaseUrlResolver = void 0;
725
+ await detachOpenWorkflowRuntimes()();
726
+ }
727
+ /**
728
+ * Starts a new runtime cache, so the next acquisition opens a fresh backend. Returns a function that closes the
729
+ * backends of the old cache. Call it after the work that still uses them, such as a stopping worker, finishes.
730
+ */
731
+ function detachOpenWorkflowRuntimes() {
732
+ const closing = runtimes;
733
+ runtimes = /* @__PURE__ */ new Map();
734
+ return () => closeOpenWorkflowRuntimes(closing);
735
+ }
736
+ async function closeOpenWorkflowRuntimes(closing) {
737
+ const fulfilled = (await Promise.allSettled(closing.values())).flatMap((entry) => entry.status === "fulfilled" ? [entry.value] : []);
738
+ const failures = (await Promise.allSettled(fulfilled.map((runtime) => Promise.resolve().then(() => runtime.backend.stop())))).flatMap((entry) => entry.status === "rejected" ? [createWorkflowError({
739
+ cause: entry.reason,
740
+ code: "OPENWORKFLOW_BACKEND_CLOSE_FAILED",
741
+ details: { provider: "openworkflow" }
742
+ })] : []);
743
+ if (failures.length === 1) throw failures[0];
744
+ if (failures.length > 1) throw new AggregateError(failures, "OpenWorkflow backend cleanup failed for multiple runtimes.");
745
+ }
746
+ function setOpenWorkflowImporter(importer) {
747
+ openWorkflowImporter = importer;
748
+ }
749
+ export { getOpenWorkflowRun as a, registerOpenWorkflowDefinition as c, runOpenWorkflow as d, setOpenWorkflowDatabaseUrl as f, findOpenWorkflowRuns as i, resetOpenWorkflowRuntime as l, describeOpenWorkflowStorage as n, getOpenWorkflowRuntime as o, setOpenWorkflowImporter as p, detachOpenWorkflowRuntimes as r, listOpenWorkflowRuns as s, cancelOpenWorkflowRun as t, resumeOpenWorkflowSignal as u };