@vite-hub/workflow 0.1.0 → 0.3.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.
Files changed (64) hide show
  1. package/README.md +144 -43
  2. package/dist/{app-CzPoP84f.js → app-CmMq8l4t.js} +1 -1
  3. package/dist/client-CU5rELC0.js +658 -0
  4. package/dist/{cloudflare-nF4abPd4.js → cloudflare-BfFnNWB0.js} +2 -2
  5. package/dist/{cloudflare-env-BNrYo29x.js → cloudflare-env-CGLx7lUd.js} +44 -42
  6. package/dist/cloudflare-env-lookup-CfX6wZKb.d.ts +4 -0
  7. package/dist/{cloudflare-env-CIjdFTv6.d.ts → cloudflare-shared-CTqh_a2s.d.ts} +2 -2
  8. package/dist/{config-IJMb0eeZ.js → config-DCvRDlxA.js} +41 -40
  9. package/dist/definition.d.ts +19 -0
  10. package/dist/definition.js +31 -0
  11. package/dist/delay--ESDybVT.js +81 -0
  12. package/dist/dev-recorder-CTN5Fkao.js +10 -0
  13. package/dist/durability.d.ts +23 -0
  14. package/dist/durability.js +62 -0
  15. package/dist/error-diagnostics-8YNJ37rP.js +286 -0
  16. package/dist/error-diagnostics-DSkCJC_L.js +266 -0
  17. package/dist/errors-DCqRnZpN.js +35 -0
  18. package/dist/errors-DVwFb6Fd.d.ts +56 -0
  19. package/dist/index.d.ts +13 -60
  20. package/dist/index.js +6 -17
  21. package/dist/object-Da1zyPCR.js +11 -0
  22. package/dist/openworkflow-TEaNk0LV.d.ts +50 -0
  23. package/dist/openworkflow-defaults-DDig2M4s.js +26 -0
  24. package/dist/openworkflow-storage-Dj9zUAsk.js +28 -0
  25. package/dist/openworkflow.d.ts +2 -0
  26. package/dist/openworkflow.js +2 -0
  27. package/dist/{operations-tNUdj3G4.d.ts → operation-definition-8gOe-ubD.d.ts} +37 -15
  28. package/dist/operations-B0L8kV5s.js +329 -0
  29. package/dist/operations.d.ts +40 -6
  30. package/dist/operations.js +163 -736
  31. package/dist/{out-CsaJxg8m.js → out-fRNaVslw.js} +31 -1429
  32. package/dist/run-error-DBWqiJHH.js +110 -0
  33. package/dist/runtime/cloudflare-runner.d.ts +3 -5
  34. package/dist/runtime/cloudflare-runner.js +24 -42
  35. package/dist/runtime/cloudflare-shared.d.ts +2 -2
  36. package/dist/runtime/cloudflare-shared.js +1 -1
  37. package/dist/runtime/cloudflare-vite.d.ts +3 -2
  38. package/dist/runtime/cloudflare-vite.js +47 -1
  39. package/dist/runtime/dev-runs.d.ts +4 -0
  40. package/dist/runtime/dev-runs.js +73 -0
  41. package/dist/runtime/execute.d.ts +20 -4
  42. package/dist/runtime/execute.js +118 -12
  43. package/dist/runtime/openworkflow-worker.d.ts +29 -2
  44. package/dist/runtime/openworkflow-worker.js +156 -38
  45. package/dist/runtime/openworkflow.d.ts +2 -21
  46. package/dist/runtime/openworkflow.js +273 -36
  47. package/dist/runtime/state.d.ts +3 -1
  48. package/dist/runtime/state.js +11 -7
  49. package/dist/runtime/vercel-vite.d.ts +1 -1
  50. package/dist/runtime/vercel-vite.js +7 -4
  51. package/dist/types-CnKVDnEp.d.ts +241 -0
  52. package/dist/{vercel-D-ZNtB_u.js → vercel-BZU_O6ay.js} +51 -22
  53. package/dist/vite.d.ts +219 -27
  54. package/dist/vite.js +1787 -1183
  55. package/package.json +28 -50
  56. package/dist/client-DsGM3M4U.js +0 -389
  57. package/dist/cloudflare-shared-CaxrMD1A.d.ts +0 -1
  58. package/dist/cloudflare-vite-B3IabBsv.js +0 -47
  59. package/dist/error-diagnostics-A_8Kp-48.js +0 -116
  60. package/dist/error-diagnostics-pwNFvAHP.js +0 -67
  61. package/dist/operations-B_rYG71W.js +0 -230
  62. package/dist/provider-operation-CW2cYfVy.js +0 -65
  63. package/dist/runtime-type-DBCvIh5x.js +0 -7
  64. package/dist/types-D82WmfZa.d.ts +0 -180
@@ -1,48 +1,34 @@
1
- import { t as workflowErrorDiagnostics } from "../error-diagnostics-pwNFvAHP.js";
2
- import { n as isRuntimeRecord, t as hasRuntimeType } from "../runtime-type-DBCvIh5x.js";
3
- import { a as createWorkflowError, r as runWorkflowProviderOperation } from "../provider-operation-CW2cYfVy.js";
4
- import { getOpenWorkflowRuntime, registerOpenWorkflowDefinition } from "./openworkflow.js";
5
- import { getInlineWorkflowDefinitions, getWorkflowRuntimeConfig, getWorkflowRuntimeRegistry, setWorkflowRuntimeConfig, setWorkflowRuntimeRegistry, takeInlineWorkflowDefinitionForModule } from "./state.js";
6
- import "@vite-hub/runtime";
1
+ import { t as workflowErrorDiagnostics } from "../error-diagnostics-8YNJ37rP.js";
2
+ import { n as createWorkflowError } from "../errors-DCqRnZpN.js";
3
+ import { i as runWorkflowProviderOperation } from "../run-error-DBWqiJHH.js";
4
+ import { describeOpenWorkflowStorage, detachOpenWorkflowRuntimes, getOpenWorkflowRuntime, registerOpenWorkflowDefinition, setOpenWorkflowDatabaseUrl, setOpenWorkflowImporter } from "./openworkflow.js";
5
+ import { getWorkflowRuntimeConfig, getWorkflowRuntimeRegistry, loadWorkflowDefinition, setWorkflowRuntimeConfig, setWorkflowRuntimeRegistry } from "./state.js";
6
+ import { ViteHubError } from "@vite-hub/runtime";
7
+ import { onShutdown } from "@vite-hub/runtime/internal/shutdown";
7
8
  //#region src/runtime/openworkflow-worker.ts
8
9
  function getProcess() {
9
10
  return globalThis.process;
10
11
  }
11
- function isWorkflowDefinition(value) {
12
- return isRuntimeRecord(value) && Object.hasOwn(value, "handler") && hasRuntimeType(value.handler, "function");
13
- }
14
- async function loadRegistryDefinitions(registry) {
15
- const definitions = /* @__PURE__ */ new Map();
16
- for (const name of Object.keys(registry).sort()) {
17
- const loaded = await registry[name]?.();
18
- const definition = isRuntimeRecord(loaded) && "default" in loaded ? loaded.default : loaded;
19
- if (isWorkflowDefinition(definition)) {
20
- definitions.set(name, definition);
21
- continue;
22
- }
23
- const inlineDefinition = takeInlineWorkflowDefinitionForModule(name, loaded);
24
- if (inlineDefinition) definitions.set(name, inlineDefinition);
25
- }
26
- return definitions;
27
- }
28
- function mergeInlineDefinitions(definitions) {
29
- for (const [name, definition] of getInlineWorkflowDefinitions()) {
30
- const existing = definitions.get(name);
31
- if (existing && existing !== definition) throw workflowErrorDiagnostics.WORKFLOW_R0016({ message: `Duplicate workflow name "${name}" from inline and discovered definitions.` });
32
- definitions.set(name, definition);
33
- }
34
- }
35
- async function createOpenWorkflowWorker(options = {}) {
12
+ /** Registers every Workflow Definition of the registry on the OpenWorkflow client, before a worker copies them. */
13
+ async function prepareOpenWorkflowWorker(options) {
36
14
  const config = options.config ?? getWorkflowRuntimeConfig();
37
- if (!config || config.provider !== "openworkflow") throw workflowErrorDiagnostics.WORKFLOW_R0017({ message: "OpenWorkflow worker requires workflow.provider \"openworkflow\"." });
15
+ if (!config || config.driver !== "openworkflow") throw workflowErrorDiagnostics.WORKFLOW_R0017({ message: "OpenWorkflow worker requires workflow.driver \"openworkflow\"." });
38
16
  const registry = options.registry ?? getWorkflowRuntimeRegistry() ?? {};
39
17
  setWorkflowRuntimeConfig(config);
40
- setWorkflowRuntimeRegistry(registry);
18
+ if (registry !== getWorkflowRuntimeRegistry()) setWorkflowRuntimeRegistry(registry);
41
19
  const runtime = await getOpenWorkflowRuntime(config);
42
- const definitions = await loadRegistryDefinitions(registry);
43
- mergeInlineDefinitions(definitions);
44
- for (const [name, definition] of definitions) await registerOpenWorkflowDefinition(runtime, name, definition);
45
- return runtime.client.newWorker({ concurrency: options.concurrency ?? config.worker?.concurrency });
20
+ for (const name of Object.keys(registry).sort()) {
21
+ const definition = await loadWorkflowDefinition(name);
22
+ if (definition && Object.hasOwn(definition, "handler")) await registerOpenWorkflowDefinition(runtime, name, definition);
23
+ }
24
+ return {
25
+ concurrency: options.concurrency ?? (config.worker ? config.worker.concurrency : void 0) ?? 10,
26
+ runtime
27
+ };
28
+ }
29
+ async function createOpenWorkflowWorker(options = {}) {
30
+ const { concurrency, runtime } = await prepareOpenWorkflowWorker(options);
31
+ return runtime.client.newWorker({ concurrency });
46
32
  }
47
33
  async function startOpenWorkflowWorker(options = {}) {
48
34
  const worker = await createOpenWorkflowWorker(options);
@@ -145,5 +131,137 @@ async function startOpenWorkflowWorker(options = {}) {
145
131
  if (options.signal?.aborted) requestStop();
146
132
  return worker;
147
133
  }
134
+ const bundledOpenWorkflowModules = {
135
+ "openworkflow": () => import("openworkflow"),
136
+ "openworkflow/postgres": () => import("openworkflow/postgres"),
137
+ "openworkflow/sqlite": () => import("openworkflow/sqlite"),
138
+ "postgres": () => import("postgres")
139
+ };
140
+ const openWorkflowStartDelayMs = 500;
141
+ /**
142
+ * Errors that a new attempt cannot fix, because the configuration must change first. `WORKFLOW_OPENWORKFLOW_SETUP_CONNECTION_UNAVAILABLE` is not one: a
143
+ * pool that is full with other traffic when the server starts gives a second connection later.
144
+ */
145
+ const permanentSetupErrorCodes = /* @__PURE__ */ new Set(["WORKFLOW_OPENWORKFLOW_DATABASE_URL_MISSING", "WORKFLOW_OPENWORKFLOW_DATABASE_URL_IGNORED"]);
146
+ function hasPermanentSetupError(error) {
147
+ for (let current = error, depth = 0; current && typeof current === "object" && depth < 8; depth++) {
148
+ const code = Reflect.get(current, "code");
149
+ if (typeof code === "string" && permanentSetupErrorCodes.has(code)) return true;
150
+ current = Reflect.get(current, "cause");
151
+ }
152
+ return false;
153
+ }
154
+ const openWorkflowStartMaxDelayMs = 3e4;
155
+ const activeInstallKey = Symbol.for("vitehub.workflow.openworkflow.install");
156
+ function replaceActiveInstall(next) {
157
+ const scope = globalThis;
158
+ const previous = scope[activeInstallKey];
159
+ scope[activeInstallKey] = next;
160
+ return previous;
161
+ }
162
+ function useBundledOpenWorkflow() {
163
+ setOpenWorkflowImporter(async (specifier) => {
164
+ const load = bundledOpenWorkflowModules[specifier];
165
+ return await (load ? load() : import(
166
+ /* @vite-ignore */
167
+ specifier
168
+ ));
169
+ });
170
+ }
171
+ function delay(ms, signal) {
172
+ return new Promise((resolve) => {
173
+ const timer = setTimeout(resolve, ms);
174
+ timer.unref?.();
175
+ signal.addEventListener("abort", () => {
176
+ clearTimeout(timer);
177
+ resolve();
178
+ }, { once: true });
179
+ });
180
+ }
181
+ /**
182
+ * Installs OpenWorkflow in a long-lived Nitro server. The generated Workflow startup plugin calls it after it installs
183
+ * the runtime config and registry. It loads OpenWorkflow from the server bundle, then starts the worker unless
184
+ * `workflow.worker` is `false`. The worker stops when the server stops.
185
+ *
186
+ * The worker registers the discovered Workflow Definitions of the registry, which every server of the build has.
187
+ * When the storage is not ready, setup runs again until it works, with a delay that grows to 30 seconds. Each failure
188
+ * is reported. A failure that only a configuration change fixes, such as `WORKFLOW_OPENWORKFLOW_DATABASE_URL_MISSING`, stops the retries. The server keeps serving requests, and queued runs wait in storage until the worker starts.
189
+ * The returned promise resolves to `true` when the worker runs, and to `false` when it is off or the server closed
190
+ * first. When the plugin runs again in the same process, as `vite dev` does after a file changes, the previous worker
191
+ * stops taking runs, finishes the runs that it executes on its own backend, and the new one uses the changed definitions.
192
+ */
193
+ function installOpenWorkflow(app, options = {}) {
194
+ const config = getWorkflowRuntimeConfig();
195
+ if (!config || config.driver !== "openworkflow") return Promise.resolve(false);
196
+ useBundledOpenWorkflow();
197
+ setOpenWorkflowDatabaseUrl(options.databaseUrl);
198
+ const closing = new AbortController();
199
+ let worker;
200
+ let stopped = Promise.resolve();
201
+ const report = (error) => {
202
+ const reported = error instanceof ViteHubError ? error : createWorkflowError({
203
+ cause: error,
204
+ code: "OPENWORKFLOW_WORKER_FAILED",
205
+ details: { provider: "openworkflow" }
206
+ });
207
+ try {
208
+ console.error("[vitehub:workflow]", reported);
209
+ app.captureError?.(reported, { tags: ["vitehub-workflow"] });
210
+ } catch {}
211
+ };
212
+ let started = Promise.resolve(false);
213
+ const release = async () => {
214
+ closing.abort();
215
+ await started;
216
+ if (!worker) return;
217
+ const current = worker;
218
+ worker = void 0;
219
+ stopped = Promise.resolve().then(() => current.stop()).catch(report);
220
+ };
221
+ const finished = () => stopped;
222
+ const previous = replaceActiveInstall({
223
+ detachRuntimes: detachOpenWorkflowRuntimes,
224
+ finished,
225
+ release
226
+ });
227
+ started = (async () => {
228
+ if (previous) {
229
+ await previous.release();
230
+ const closeRuntimes = previous.detachRuntimes();
231
+ previous.finished().then(closeRuntimes).catch(report);
232
+ }
233
+ if (Object.keys(getWorkflowRuntimeRegistry() ?? {}).length === 0) return false;
234
+ try {
235
+ logDefaultStorage();
236
+ } catch (error) {
237
+ report(error);
238
+ }
239
+ if (closing.signal.aborted || config.worker === false) return false;
240
+ for (let attempt = 1; !closing.signal.aborted; attempt++) try {
241
+ const { concurrency, runtime } = await prepareOpenWorkflowWorker({ config });
242
+ if (closing.signal.aborted) return false;
243
+ const next = runtime.client.newWorker({ concurrency });
244
+ await next.start();
245
+ worker = next;
246
+ return true;
247
+ } catch (error) {
248
+ report(error);
249
+ if (hasPermanentSetupError(error)) return false;
250
+ const wait = Math.min(openWorkflowStartDelayMs * 2 ** (attempt - 1), openWorkflowStartMaxDelayMs);
251
+ console.warn(`[vitehub:workflow] The OpenWorkflow worker did not start (attempt ${attempt}). It tries again in ${wait} ms.`);
252
+ await delay(wait, closing.signal);
253
+ }
254
+ return false;
255
+ })();
256
+ function logDefaultStorage() {
257
+ if (!config || describeOpenWorkflowStorage(config).source !== "default") return;
258
+ console.warn("[vitehub:workflow] OpenWorkflow keeps runs in .vitehub/data/openworkflow.sqlite.db on this host. Other server instances do not see them. To share runs, add a Postgres Default Database, or set OPENWORKFLOW_POSTGRES_URL.");
259
+ }
260
+ onShutdown(app, "workflow.openworkflow-worker", async ({ signal }) => {
261
+ await release();
262
+ await Promise.race([finished(), new Promise((resolve) => signal.addEventListener("abort", () => resolve(), { once: true }))]);
263
+ });
264
+ return started;
265
+ }
148
266
  //#endregion
149
- export { createOpenWorkflowWorker, startOpenWorkflowWorker };
267
+ export { createOpenWorkflowWorker, installOpenWorkflow, startOpenWorkflowWorker };
@@ -1,21 +1,2 @@
1
- import { T as WorkflowRun, f as WorkflowDeferOptions, l as ResolvedWorkflowOptions, p as WorkflowDefinition } from "../types-D82WmfZa.js";
2
- //#region src/runtime/openworkflow.d.ts
3
- type OpenWorkflowModule = typeof import("openworkflow");
4
- type OpenWorkflowPostgresModule = typeof import("openworkflow/postgres");
5
- type OpenWorkflowSqliteModule = typeof import("openworkflow/sqlite");
6
- type OpenWorkflowClient = InstanceType<OpenWorkflowModule["OpenWorkflow"]>;
7
- type OpenWorkflowBackend = Awaited<ReturnType<OpenWorkflowPostgresModule["BackendPostgres"]["connect"]>> | ReturnType<OpenWorkflowSqliteModule["BackendSqlite"]["connect"]>;
8
- type OpenWorkflowRunnable = ReturnType<OpenWorkflowClient["defineWorkflow"]>;
9
- type OpenWorkflowImporter = <T>(specifier: string) => Promise<T>;
10
- interface OpenWorkflowRuntime {
11
- backend: OpenWorkflowBackend;
12
- client: OpenWorkflowClient;
13
- workflows: Map<string, OpenWorkflowRunnable>;
14
- }
15
- export declare function getOpenWorkflowRuntime(config: ResolvedWorkflowOptions): Promise<OpenWorkflowRuntime>;
16
- export declare function registerOpenWorkflowDefinition(runtime: OpenWorkflowRuntime, name: string, definition: WorkflowDefinition): Promise<OpenWorkflowRunnable>;
17
- export declare function runOpenWorkflow<TPayload = unknown, TResult = unknown>(config: ResolvedWorkflowOptions, name: string, payload: TPayload | undefined, definition: WorkflowDefinition<TPayload, TResult>, options: WorkflowDeferOptions, onDispatch?: () => void): Promise<WorkflowRun<TPayload, TResult>>;
18
- export declare function getOpenWorkflowRun<TPayload = unknown, TResult = unknown>(config: ResolvedWorkflowOptions, name: string, id: string): Promise<WorkflowRun<TPayload, TResult>>;
19
- export declare function resetOpenWorkflowRuntime(): Promise<void>;
20
- export declare function setOpenWorkflowImporter(importer: OpenWorkflowImporter): void;
21
- //#endregion
1
+ import { a as getOpenWorkflowRun, c as resetOpenWorkflowRuntime, d as setOpenWorkflowImporter, i as detachOpenWorkflowRuntimes, l as runOpenWorkflow, n as cancelOpenWorkflowRun, o as getOpenWorkflowRuntime, r as describeOpenWorkflowStorage, s as registerOpenWorkflowDefinition, t as OpenWorkflowStorageSource, u as setOpenWorkflowDatabaseUrl } from "../openworkflow-TEaNk0LV.js";
2
+ export { OpenWorkflowStorageSource, cancelOpenWorkflowRun, describeOpenWorkflowStorage, detachOpenWorkflowRuntimes, getOpenWorkflowRun, getOpenWorkflowRuntime, registerOpenWorkflowDefinition, resetOpenWorkflowRuntime, runOpenWorkflow, setOpenWorkflowDatabaseUrl, setOpenWorkflowImporter };
@@ -1,11 +1,16 @@
1
- import { t as workflowErrorDiagnostics } from "../error-diagnostics-pwNFvAHP.js";
2
- import { a as createWorkflowError, r as runWorkflowProviderOperation, t as getWorkflowProviderStatus } from "../provider-operation-CW2cYfVy.js";
3
- import { runSerializedWorkflowHandler } from "./execute.js";
1
+ import { t as workflowErrorDiagnostics } from "../error-diagnostics-8YNJ37rP.js";
2
+ import { t as resolveOpenWorkflowStorage } from "../openworkflow-storage-Dj9zUAsk.js";
3
+ import { n as createWorkflowError } from "../errors-DCqRnZpN.js";
4
+ import { readNonRetryableStepResult, runSerializedWorkflowHandler, toNonRetryableStepResult } 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";
4
7
  import { deserializeResponse, isSerializedResponse } from "@vite-hub/runtime";
5
8
  //#region src/runtime/openworkflow.ts
6
- const defaultImporter = new Function("specifier", "return import(specifier)");
9
+ const defaultImporter = (specifier) => import(
10
+ /* @vite-ignore */
11
+ specifier
12
+ );
7
13
  let openWorkflowImporter = defaultImporter;
8
- const defaultOpenWorkflowSqlitePath = ".vitehub/data/openworkflow.sqlite.db";
9
14
  let runtimes = /* @__PURE__ */ new Map();
10
15
  async function importOpenWorkflowModule(specifier, importer) {
11
16
  return await runWorkflowProviderOperation("openworkflow", "import", () => importer(specifier));
@@ -37,8 +42,23 @@ async function prepareSqlitePath(path, importer) {
37
42
  }
38
43
  return path;
39
44
  }
45
+ let databaseUrlResolver;
46
+ /**
47
+ * Makes OpenWorkflow use the Postgres Default Database of the app when no OpenWorkflow storage is configured. The
48
+ * generated startup plugin installs it when the build has a Postgres Default Database.
49
+ */
50
+ function setOpenWorkflowDatabaseUrl(resolve) {
51
+ databaseUrlResolver = resolve;
52
+ }
53
+ /** The Postgres URL of the Default Database, when the app has a Postgres Default Database. */
54
+ function readDatabasePostgresUrl() {
55
+ if (!databaseUrlResolver) return void 0;
56
+ const url = databaseUrlResolver()?.trim();
57
+ if (!url) throw workflowErrorDiagnostics.WORKFLOW_OPENWORKFLOW_DATABASE_URL_MISSING();
58
+ return url;
59
+ }
40
60
  function getOpenWorkflowConfig(config) {
41
- if (config.provider !== "openworkflow") throw workflowErrorDiagnostics.WORKFLOW_R0020({ message: `OpenWorkflow runtime requires workflow.provider "openworkflow", received "${config.provider}".` });
61
+ if (config.driver !== "openworkflow") throw workflowErrorDiagnostics.WORKFLOW_R0020({ message: `OpenWorkflow runtime requires workflow.driver "openworkflow", received "${config.driver}".` });
42
62
  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
63
  const sqlite = config.sqlite || {};
44
64
  const postgres = config.postgres || {};
@@ -47,28 +67,102 @@ function getOpenWorkflowConfig(config) {
47
67
  const explicitPostgresUrl = resolveRuntimeConfigValue(postgres.url)?.trim();
48
68
  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
69
  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 sqlitePath = explicitSqlitePath || (!explicitPostgresUrl ? readEnv("OPENWORKFLOW_SQLITE_PATH") : void 0);
51
- if (sqlitePath) return {
70
+ const storage = resolveOpenWorkflowStorage({
71
+ postgresUrl: explicitPostgresUrl,
72
+ sqlitePath: explicitSqlitePath
73
+ }, readEnv);
74
+ if (storage.backend === "sqlite" && storage.source !== "default") return {
52
75
  backend: "sqlite",
53
76
  namespaceId: sqlite.namespaceId || readEnv("OPENWORKFLOW_NAMESPACE_ID") || "production",
54
- path: normalizeSqlitePath(sqlitePath),
55
- runMigrations: sqlite.runMigrations
77
+ path: normalizeSqlitePath(storage.path),
78
+ runMigrations: sqlite.runMigrations,
79
+ source: "configured"
56
80
  };
57
- const url = explicitPostgresUrl || readEnv("OPENWORKFLOW_POSTGRES_URL") || readEnv("DATABASE_URL");
81
+ const configuredUrl = storage.backend === "postgres" ? storage.url : void 0;
82
+ const url = configuredUrl || readDatabasePostgresUrl();
58
83
  if (url) return {
59
84
  backend: "postgres",
60
85
  namespaceId: postgres.namespaceId || readEnv("OPENWORKFLOW_NAMESPACE_ID") || "production",
61
86
  runMigrations: postgres.runMigrations,
62
87
  schema: postgres.schema || readEnv("OPENWORKFLOW_SCHEMA") || "openworkflow",
88
+ source: configuredUrl ? "configured" : "database",
63
89
  url
64
90
  };
91
+ if (/^postgres(?:ql)?:\/\//i.test(readEnv("DATABASE_URL") || "")) throw workflowErrorDiagnostics.WORKFLOW_OPENWORKFLOW_DATABASE_URL_IGNORED();
65
92
  return {
66
93
  backend: "sqlite",
67
94
  namespaceId: sqlite.namespaceId || readEnv("OPENWORKFLOW_NAMESPACE_ID") || "production",
68
95
  path: defaultOpenWorkflowSqlitePath,
69
- runMigrations: sqlite.runMigrations
96
+ runMigrations: sqlite.runMigrations,
97
+ source: "default"
70
98
  };
71
99
  }
100
+ /** How long a server waits for the setup lock that another server holds, before the worker start tries again. */
101
+ const postgresSetupWaitMs = 12e4;
102
+ /** How long the server that holds the setup lock waits for the second connection that the OpenWorkflow migration needs. */
103
+ const postgresSecondConnectionTimeoutMs = 1e4;
104
+ function sleep(ms) {
105
+ return new Promise((resolve) => setTimeout(resolve, ms).unref?.());
106
+ }
107
+ /** Resolves `true` when `task` settles first, `false` when `ms` passes first. */
108
+ function settlesWithin(task, ms) {
109
+ let timer;
110
+ return Promise.race([task.then(() => true), new Promise((resolve) => {
111
+ timer = setTimeout(() => resolve(false), ms);
112
+ timer.unref?.();
113
+ })]).finally(() => clearTimeout(timer));
114
+ }
115
+ /**
116
+ * OpenWorkflow creates its Postgres schema without a lock. When servers start together, all but one fail with
117
+ * `duplicate key value violates unique constraint`, and OpenWorkflow leaves the failed migration connection open in an
118
+ * aborted transaction. So one server at a time sets up the schema, and the others then find it up to date.
119
+ *
120
+ * OpenWorkflow does not export its migrations, so they cannot run on the connection that holds the lock: they run on a
121
+ * connection that `BackendPostgres.connect()` opens.
122
+ * - A server tries the lock with `pg_try_advisory_xact_lock` in a short transaction. A server that does not get it
123
+ * commits at once and tries again later, so a waiting server holds no connection.
124
+ * - The server that gets it first checks that it can open a second connection. A pool of one connection, such as a
125
+ * pooler with one server connection, cannot run the migration while the lock holds that connection, so the server
126
+ * stops with `WORKFLOW_OPENWORKFLOW_SETUP_CONNECTION_UNAVAILABLE` before the setup starts.
127
+ * - Then it holds the lock until OpenWorkflow finished the setup.
128
+ * A transaction lock also works through a pooler in transaction mode, such as PgBouncer.
129
+ * OpenWorkflow 0.11.0 locks its setup with a session lock
130
+ * (https://github.com/openworkflowdev/openworkflow/commit/eb544db), which such a pooler does not keep, so this lock stays.
131
+ */
132
+ async function withPostgresSetupLock(postgres, url, schema, setup) {
133
+ const sql = postgres.default(url, {
134
+ idle_timeout: 1,
135
+ max: 1,
136
+ onnotice: () => {}
137
+ });
138
+ const key = `vitehub:openworkflow:${schema}`;
139
+ const deadline = Date.now() + postgresSetupWaitMs;
140
+ try {
141
+ for (let attempt = 1;; attempt++) {
142
+ let result;
143
+ await sql.begin(async (transaction) => {
144
+ const [lock] = await transaction`select pg_try_advisory_xact_lock(hashtextextended(${key}, 0)) as locked`;
145
+ if (!lock?.locked) return;
146
+ const probe = postgres.default(url, {
147
+ max: 1,
148
+ onnotice: () => {}
149
+ });
150
+ const answered = Promise.resolve(probe`select 1`).then(() => {}, () => {});
151
+ if (!await settlesWithin(answered, postgresSecondConnectionTimeoutMs)) {
152
+ answered.then(() => probe.end());
153
+ throw workflowErrorDiagnostics.WORKFLOW_OPENWORKFLOW_SETUP_CONNECTION_UNAVAILABLE();
154
+ }
155
+ await probe.end();
156
+ result = { value: await setup() };
157
+ });
158
+ if (result) return result.value;
159
+ if (Date.now() >= deadline) throw workflowErrorDiagnostics.WORKFLOW_OPENWORKFLOW_SETUP_LOCK_TIMEOUT({ seconds: postgresSetupWaitMs / 1e3 });
160
+ await sleep(Math.min(250 * attempt, 2e3));
161
+ }
162
+ } finally {
163
+ await sql.end({ timeout: 5 });
164
+ }
165
+ }
72
166
  async function createOpenWorkflowRuntime(options, importer) {
73
167
  const [{ OpenWorkflow }, backendModule] = await Promise.all([importOpenWorkflowModule("openworkflow", importer), options.backend === "sqlite" ? importOpenWorkflowModule("openworkflow/sqlite", importer) : importOpenWorkflowModule("openworkflow/postgres", importer)]);
74
168
  const { backend, client } = await runWorkflowProviderOperation("openworkflow", "connect", async () => {
@@ -77,11 +171,15 @@ async function createOpenWorkflowRuntime(options, importer) {
77
171
  namespaceId: options.namespaceId,
78
172
  ...typeof options.runMigrations === "boolean" ? { runMigrations: options.runMigrations } : {}
79
173
  });
80
- else backend = await backendModule.BackendPostgres.connect(options.url, {
81
- namespaceId: options.namespaceId,
82
- ...typeof options.runMigrations === "boolean" ? { runMigrations: options.runMigrations } : {},
83
- schema: options.schema
84
- });
174
+ else {
175
+ const { BackendPostgres } = backendModule;
176
+ const connect = () => BackendPostgres.connect(options.url, {
177
+ namespaceId: options.namespaceId,
178
+ ...typeof options.runMigrations === "boolean" ? { runMigrations: options.runMigrations } : {},
179
+ schema: options.schema
180
+ });
181
+ backend = options.runMigrations === false ? await connect() : await withPostgresSetupLock(await importOpenWorkflowModule("postgres", importer), options.url, options.schema, connect);
182
+ }
85
183
  return {
86
184
  backend,
87
185
  client: new OpenWorkflow({ backend })
@@ -90,9 +188,49 @@ async function createOpenWorkflowRuntime(options, importer) {
90
188
  return {
91
189
  backend,
92
190
  client,
191
+ findRunId: createRunIdLookup(backend, options),
93
192
  workflows: /* @__PURE__ */ new Map()
94
193
  };
95
194
  }
195
+ function isSqliteHandle(value) {
196
+ return typeof value === "object" && value !== null && typeof Reflect.get(value, "prepare") === "function";
197
+ }
198
+ function isPostgresHandle(value) {
199
+ return typeof value === "function";
200
+ }
201
+ function readRowId(row) {
202
+ if (typeof row !== "object" || row === null) return void 0;
203
+ const id = Reflect.get(row, "id");
204
+ return typeof id === "string" ? id : void 0;
205
+ }
206
+ /**
207
+ * ViteHub starts a run with the caller's id as the OpenWorkflow idempotency key, and OpenWorkflow gives the run its own
208
+ * UUID. The OpenWorkflow API reads runs by UUID only, so this lookup reads the key from the backend connection.
209
+ */
210
+ function createRunIdLookup(backend, options) {
211
+ const connection = Reflect.get(backend, options.backend === "sqlite" ? "db" : "pg");
212
+ return async (name, key) => {
213
+ 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));
214
+ if (options.backend === "postgres" && isPostgresHandle(connection)) {
215
+ 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`;
216
+ return readRowId(row);
217
+ }
218
+ throw invariantError(`OpenWorkflow 0.9 backends keep their connection in \`db\` (SQLite) or \`pg\` (Postgres), but the ${options.backend} backend has neither`);
219
+ };
220
+ }
221
+ /** The storage that OpenWorkflow uses for `config` now, without credentials. */
222
+ function describeOpenWorkflowStorage(config) {
223
+ const storage = getOpenWorkflowConfig(config);
224
+ return storage.backend === "sqlite" ? {
225
+ backend: "sqlite",
226
+ location: storage.path,
227
+ source: storage.source
228
+ } : {
229
+ backend: "postgres",
230
+ location: `schema ${storage.schema}`,
231
+ source: storage.source
232
+ };
233
+ }
96
234
  async function getOpenWorkflowRuntime(config) {
97
235
  const cache = runtimes;
98
236
  const options = getOpenWorkflowConfig(config);
@@ -124,12 +262,23 @@ function toOpenWorkflowRetryPolicy(options) {
124
262
  function createOpenWorkflowProviderStep(step) {
125
263
  return {
126
264
  async do(name, options, run) {
127
- return await step.run({
265
+ const output = await step.run({
128
266
  name,
129
267
  ...toOpenWorkflowRetryPolicy(options) ? { retryPolicy: toOpenWorkflowRetryPolicy(options) } : {}
130
- }, run);
268
+ }, async () => {
269
+ try {
270
+ return await run();
271
+ } catch (error) {
272
+ const result = toNonRetryableStepResult(error);
273
+ if (result) return result;
274
+ throw error;
275
+ }
276
+ });
277
+ const error = readNonRetryableStepResult(output);
278
+ if (error) throw error;
279
+ return output;
131
280
  },
132
- sleep: async (name, duration) => await step.sleep(name, duration)
281
+ sleep: async (name, milliseconds) => await step.sleep(name, `${milliseconds}ms`)
133
282
  };
134
283
  }
135
284
  async function registerOpenWorkflowDefinition(runtime, name, definition) {
@@ -137,8 +286,9 @@ async function registerOpenWorkflowDefinition(runtime, name, definition) {
137
286
  if (existing) return existing;
138
287
  const openWorkflowDefinition = definition;
139
288
  const workflow = runtime.client.defineWorkflow({ name }, async ({ input, run, step }) => {
289
+ const stored = await runtime.backend.getWorkflowRun({ workflowRunId: run.id });
140
290
  return await runSerializedWorkflowHandler({
141
- id: run.id,
291
+ id: stored?.idempotencyKey || run.id,
142
292
  name,
143
293
  payload: input,
144
294
  provider: "openworkflow",
@@ -167,57 +317,144 @@ function serializeOpenWorkflowRun(run, name) {
167
317
  status: "unknown"
168
318
  };
169
319
  const result = isSerializedResponse(run.output) ? deserializeResponse(run.output) : run.output;
320
+ const status = normalizeOpenWorkflowStatus(run.status);
170
321
  return {
171
- id: run.id,
172
- metadata: run.error || {
322
+ ...status === "failed" ? { error: toWorkflowRunError(run.error) } : {},
323
+ ...run.finishedAt ? { completedAt: run.finishedAt } : {},
324
+ createdAt: run.createdAt,
325
+ ...run.startedAt ? { startedAt: run.startedAt } : {},
326
+ id: run.idempotencyKey || run.id,
327
+ metadata: {
173
328
  namespaceId: run.namespaceId,
174
329
  version: run.version,
175
330
  workflowName: run.workflowName
176
331
  },
332
+ payload: run.input,
177
333
  provider: "openworkflow",
178
334
  result,
179
- status: normalizeOpenWorkflowStatus(run.status)
335
+ status
180
336
  };
181
337
  }
182
- async function runOpenWorkflow(config, name, payload, definition, options, onDispatch) {
183
- const workflow = await registerOpenWorkflowDefinition(await getOpenWorkflowRuntime(config), name, definition);
338
+ /** OpenWorkflow stores `name`, `message`, and `stack`. The stack has server paths, so the step keeps the message only. */
339
+ function toWorkflowRunStepError(error) {
340
+ const message = typeof error === "object" && error !== null ? Reflect.get(error, "message") : void 0;
341
+ return { message: typeof message === "string" && message ? message : "Workflow step failed." };
342
+ }
343
+ /** OpenWorkflow stores one row per step attempt. A run reports each step once, with its latest attempt. */
344
+ function toWorkflowRunSteps(attempts) {
345
+ const steps = /* @__PURE__ */ new Map();
346
+ for (const attempt of attempts) {
347
+ const nonRetryable = readNonRetryableStepResult(attempt.output);
348
+ steps.set(attempt.stepName, {
349
+ attempt: (steps.get(attempt.stepName)?.attempt ?? 0) + 1,
350
+ ...attempt.finishedAt ? { completedAt: attempt.finishedAt } : {},
351
+ ...attempt.status === "failed" || nonRetryable ? { error: toWorkflowRunStepError(nonRetryable ?? attempt.error) } : {},
352
+ id: attempt.id,
353
+ name: attempt.stepName,
354
+ ...attempt.context?.kind === "sleep" ? { sleepUntil: new Date(attempt.context.resumeAt) } : {},
355
+ ...attempt.startedAt ? { startedAt: attempt.startedAt } : {},
356
+ status: nonRetryable ? "failed" : normalizeOpenWorkflowStatus(attempt.status)
357
+ });
358
+ }
359
+ return [...steps.values()];
360
+ }
361
+ async function listOpenWorkflowStepAttempts(backend, workflowRunId) {
362
+ const attempts = [];
363
+ let after;
364
+ do {
365
+ const page = await backend.listStepAttempts({
366
+ workflowRunId,
367
+ limit: 100,
368
+ ...after ? { after } : {}
369
+ });
370
+ attempts.push(...page.data);
371
+ after = page.pagination.next ?? void 0;
372
+ } while (after);
373
+ return attempts;
374
+ }
375
+ async function runOpenWorkflow(config, name, payload, definition, options, onDispatch, startAt) {
376
+ const runtime = await getOpenWorkflowRuntime(config);
377
+ const workflow = await registerOpenWorkflowDefinition(runtime, name, definition);
184
378
  onDispatch?.();
185
379
  let firstAcknowledgementUnknown = false;
186
380
  const handle = await runWorkflowProviderOperation("openworkflow", "run", async () => {
187
- const start = () => workflow.run(payload, options.id ? { idempotencyKey: options.id } : void 0);
381
+ const existingId = options.id ? await runtime.findRunId(name, options.id) ?? options.id : void 0;
382
+ const existing = existingId ? await runtime.backend.getWorkflowRun({ workflowRunId: existingId }) : null;
383
+ if (existing?.workflowName === name) return { workflowRun: existing };
384
+ const runOptions = options.id || startAt !== void 0 ? {
385
+ ...options.id ? { idempotencyKey: options.id } : {},
386
+ ...startAt === void 0 ? {} : { availableAt: new Date(startAt) }
387
+ } : void 0;
388
+ const start = () => workflow.run(payload, runOptions);
188
389
  return await start().catch((error) => {
189
390
  if (!options.id) throw error;
190
391
  firstAcknowledgementUnknown = getWorkflowProviderStatus(error) === void 0;
191
392
  return start();
192
393
  });
193
- }, { acknowledgementUnknown: (_error, status) => firstAcknowledgementUnknown || status === void 0 });
394
+ }, { acknowledgement: (_error, status) => firstAcknowledgementUnknown || status === void 0 ? "unknown" : status < 500 ? "rejected" : void 0 });
194
395
  return await runWorkflowProviderOperation("openworkflow", "run", async () => {
195
- const serialized = serializeOpenWorkflowRun(handle.workflowRun, name);
196
396
  return {
197
- ...serialized,
198
- metadata: serialized.status === "failed" ? serialized.metadata : {
397
+ ...serializeOpenWorkflowRun(handle.workflowRun, name),
398
+ metadata: {
199
399
  ...options.id ? { idempotencyKey: options.id } : {},
200
400
  workflow: name
201
401
  },
202
- payload
402
+ payload: handle.workflowRun.input
203
403
  };
204
404
  });
205
405
  }
206
406
  async function getOpenWorkflowRun(config, name, id) {
207
407
  const runtime = await getOpenWorkflowRuntime(config);
208
408
  return await runWorkflowProviderOperation("openworkflow", "get", async () => {
209
- const serialized = serializeOpenWorkflowRun(await runtime.backend.getWorkflowRun({ workflowRunId: id }), name);
210
- return serialized.id ? serialized : {
409
+ const run = await runtime.backend.getWorkflowRun({ workflowRunId: await runtime.findRunId(name, id) ?? id });
410
+ if (!run || run.workflowName !== name) return {
211
411
  id,
212
412
  provider: "openworkflow",
213
413
  status: "unknown"
214
414
  };
415
+ return {
416
+ ...serializeOpenWorkflowRun(run, name),
417
+ steps: toWorkflowRunSteps(await listOpenWorkflowStepAttempts(runtime.backend, run.id))
418
+ };
215
419
  });
216
420
  }
421
+ const terminalOpenWorkflowStatuses = /* @__PURE__ */ new Set([
422
+ "cancelled",
423
+ "completed",
424
+ "failed"
425
+ ]);
426
+ /**
427
+ * Cancels a pending or running OpenWorkflow run of this Workflow and returns its state afterwards. A run of another
428
+ * Workflow, or an unknown run, reports `unknown` without being cancelled. A finished run keeps and reports its status.
429
+ */
430
+ async function cancelOpenWorkflowRun(config, name, id) {
431
+ const current = await getOpenWorkflowRun(config, name, id);
432
+ if (current.status === "unknown" || terminalOpenWorkflowStatuses.has(current.status)) return current;
433
+ const runtime = await getOpenWorkflowRuntime(config);
434
+ try {
435
+ await runWorkflowProviderOperation("openworkflow", "cancel", async () => await runtime.client.cancelWorkflowRun(await runtime.findRunId(name, id) ?? id));
436
+ } catch (error) {
437
+ const latest = await getOpenWorkflowRun(config, name, id).catch(() => void 0);
438
+ if (latest && terminalOpenWorkflowStatuses.has(latest.status)) return latest;
439
+ throw error;
440
+ }
441
+ return await getOpenWorkflowRun(config, name, id);
442
+ }
217
443
  async function resetOpenWorkflowRuntime() {
444
+ openWorkflowImporter = defaultImporter;
445
+ databaseUrlResolver = void 0;
446
+ await detachOpenWorkflowRuntimes()();
447
+ }
448
+ /**
449
+ * Starts a new runtime cache, so the next acquisition opens a fresh backend. Returns a function that closes the
450
+ * backends of the old cache. Call it after the work that still uses them, such as a stopping worker, finishes.
451
+ */
452
+ function detachOpenWorkflowRuntimes() {
218
453
  const closing = runtimes;
219
454
  runtimes = /* @__PURE__ */ new Map();
220
- openWorkflowImporter = defaultImporter;
455
+ return () => closeOpenWorkflowRuntimes(closing);
456
+ }
457
+ async function closeOpenWorkflowRuntimes(closing) {
221
458
  const fulfilled = (await Promise.allSettled(closing.values())).flatMap((entry) => entry.status === "fulfilled" ? [entry.value] : []);
222
459
  const failures = (await Promise.allSettled(fulfilled.map((runtime) => Promise.resolve().then(() => runtime.backend.stop())))).flatMap((entry) => entry.status === "rejected" ? [createWorkflowError({
223
460
  cause: entry.reason,
@@ -231,4 +468,4 @@ function setOpenWorkflowImporter(importer) {
231
468
  openWorkflowImporter = importer;
232
469
  }
233
470
  //#endregion
234
- export { getOpenWorkflowRun, getOpenWorkflowRuntime, registerOpenWorkflowDefinition, resetOpenWorkflowRuntime, runOpenWorkflow, setOpenWorkflowImporter };
471
+ export { cancelOpenWorkflowRun, describeOpenWorkflowStorage, detachOpenWorkflowRuntimes, getOpenWorkflowRun, getOpenWorkflowRuntime, registerOpenWorkflowDefinition, resetOpenWorkflowRuntime, runOpenWorkflow, setOpenWorkflowDatabaseUrl, setOpenWorkflowImporter };