@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
package/dist/runtime/execute.js
CHANGED
|
@@ -1,15 +1,107 @@
|
|
|
1
|
-
import { t as workflowErrorDiagnostics } from "../error-diagnostics-
|
|
2
|
-
import {
|
|
1
|
+
import { t as workflowErrorDiagnostics } from "../error-diagnostics-0V2T3JFw.js";
|
|
2
|
+
import { r as isNonRetryableError, t as NonRetryableError } from "../errors-DCqRnZpN.js";
|
|
3
|
+
import { t as getWorkflowDevRecorder } from "../dev-recorder-CTN5Fkao.js";
|
|
4
|
+
import { isResponse, serializeResponse, toResponse } from "@vite-hub/runtime";
|
|
3
5
|
//#region src/runtime/execute.ts
|
|
4
|
-
const
|
|
6
|
+
const defaultRetries = {
|
|
5
7
|
backoff: "exponential",
|
|
6
8
|
delay: "10 seconds",
|
|
7
9
|
limit: 3
|
|
8
|
-
}
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
10
|
+
};
|
|
11
|
+
const stepOptionKeys = /* @__PURE__ */ new Set(["retries", "timeout"]);
|
|
12
|
+
const retryOptionKeys = /* @__PURE__ */ new Set([
|
|
13
|
+
"backoff",
|
|
14
|
+
"delay",
|
|
15
|
+
"limit"
|
|
16
|
+
]);
|
|
17
|
+
function isPlainObject(value) {
|
|
18
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
12
19
|
}
|
|
20
|
+
/**
|
|
21
|
+
* Checks the options of a step and fills in the default retries. A step file, `context.step.do()`, and every provider
|
|
22
|
+
* read the options through this function, so an invalid value fails the same way everywhere.
|
|
23
|
+
*/
|
|
24
|
+
function resolveWorkflowStepOptions(step, options) {
|
|
25
|
+
const invalid = (option, value) => workflowErrorDiagnostics.WORKFLOW_STEP_OPTIONS_INVALID({
|
|
26
|
+
option,
|
|
27
|
+
step,
|
|
28
|
+
value: typeof value === "string" ? JSON.stringify(value) : String(value)
|
|
29
|
+
});
|
|
30
|
+
if (options === void 0) return { retries: { ...defaultRetries } };
|
|
31
|
+
if (!isPlainObject(options)) throw invalid("options", options);
|
|
32
|
+
for (const key of Object.keys(options)) if (!stepOptionKeys.has(key)) throw invalid(key, options[key]);
|
|
33
|
+
const retries = options.retries ?? {};
|
|
34
|
+
if (!isPlainObject(retries)) throw invalid("retries", retries);
|
|
35
|
+
for (const key of Object.keys(retries)) if (!retryOptionKeys.has(key)) throw invalid(`retries.${key}`, retries[key]);
|
|
36
|
+
const { backoff = defaultRetries.backoff, delay = defaultRetries.delay, limit = defaultRetries.limit } = retries;
|
|
37
|
+
if (typeof limit !== "number" || !Number.isInteger(limit) || limit < 0) throw invalid("retries.limit", limit);
|
|
38
|
+
if (toDurationMilliseconds(delay) === void 0) throw invalid("retries.delay", delay);
|
|
39
|
+
if (backoff !== "constant" && backoff !== "exponential") throw invalid("retries.backoff", backoff);
|
|
40
|
+
const timeout = options.timeout;
|
|
41
|
+
if (timeout !== void 0 && !toDurationMilliseconds(timeout)) throw invalid("timeout", timeout);
|
|
42
|
+
return {
|
|
43
|
+
retries: {
|
|
44
|
+
backoff,
|
|
45
|
+
delay,
|
|
46
|
+
limit
|
|
47
|
+
},
|
|
48
|
+
...timeout === void 0 ? {} : { timeout }
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
/** Calls `callback` after `milliseconds`, also when that is longer than one Node timer can wait. Returns a cancel function. */
|
|
52
|
+
function onTimeout(milliseconds, callback) {
|
|
53
|
+
const deadline = Date.now() + milliseconds;
|
|
54
|
+
let timer;
|
|
55
|
+
const arm = () => {
|
|
56
|
+
timer = setTimeout(() => Date.now() >= deadline ? callback() : arm(), Math.min(Math.max(deadline - Date.now(), 0), maxTimerDelay));
|
|
57
|
+
};
|
|
58
|
+
arm();
|
|
59
|
+
return () => clearTimeout(timer);
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Runs one attempt of a step. When `timeout` passes, the step's `signal` aborts and the attempt fails with
|
|
63
|
+
* `WORKFLOW_STEP_TIMEOUT`, so the provider retries it. A step that ignores the signal keeps running in the background:
|
|
64
|
+
* JavaScript cannot stop a promise.
|
|
65
|
+
*/
|
|
66
|
+
async function runWorkflowStepAttempt(step, timeout, run) {
|
|
67
|
+
const controller = new AbortController();
|
|
68
|
+
const milliseconds = timeout === void 0 ? void 0 : toDurationMilliseconds(timeout);
|
|
69
|
+
if (milliseconds === void 0) return await run({ signal: controller.signal });
|
|
70
|
+
const label = typeof timeout === "number" ? `${timeout} ms` : String(timeout);
|
|
71
|
+
let cancel = () => {};
|
|
72
|
+
const expired = new Promise((_resolve, reject) => {
|
|
73
|
+
cancel = onTimeout(milliseconds, () => {
|
|
74
|
+
const error = workflowErrorDiagnostics.WORKFLOW_STEP_TIMEOUT({
|
|
75
|
+
step,
|
|
76
|
+
timeout: label
|
|
77
|
+
});
|
|
78
|
+
controller.abort(error);
|
|
79
|
+
reject(error);
|
|
80
|
+
});
|
|
81
|
+
});
|
|
82
|
+
try {
|
|
83
|
+
return await Promise.race([Promise.resolve().then(() => run({ signal: controller.signal })), expired]);
|
|
84
|
+
} finally {
|
|
85
|
+
cancel();
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
const timedAttempts = /* @__PURE__ */ new WeakSet();
|
|
89
|
+
/** Adds a timeout once, including when a provider receives an already wrapped folder step. */
|
|
90
|
+
function withWorkflowStepTimeout(name, timeout, run) {
|
|
91
|
+
if (timeout === void 0 || timedAttempts.has(run)) return run;
|
|
92
|
+
const attempt = () => runWorkflowStepAttempt(name, timeout, run);
|
|
93
|
+
timedAttempts.add(attempt);
|
|
94
|
+
return attempt;
|
|
95
|
+
}
|
|
96
|
+
async function runProviderStep(step, name, run, options) {
|
|
97
|
+
const resolved = resolveWorkflowStepOptions(name, options);
|
|
98
|
+
const attempt = () => runWorkflowStepAttempt(name, resolved.timeout, run);
|
|
99
|
+
timedAttempts.add(attempt);
|
|
100
|
+
if (typeof step?.do === "function") return await step.do(name, resolved, attempt);
|
|
101
|
+
const recorder = getWorkflowDevRecorder();
|
|
102
|
+
return recorder ? await recorder.step(name, attempt) : await attempt();
|
|
103
|
+
}
|
|
104
|
+
/** `01.create-user.ts` becomes the `createUser` step. */
|
|
13
105
|
function toStepPropertyName(file) {
|
|
14
106
|
return file.split("/").pop().replace(/\.(?:c|m)?[jt]s$/i, "").replace(/^\d+[.-]?/, "").replace(/[-_.]+([a-z0-9])/gi, (_, char) => char.toUpperCase());
|
|
15
107
|
}
|
|
@@ -21,28 +113,135 @@ function createWorkflowSteps(context, stepModules) {
|
|
|
21
113
|
const previousName = names.get(propertyName);
|
|
22
114
|
if (previousName) throw workflowErrorDiagnostics.WORKFLOW_C0010({ message: `[vitehub] Workflow step files ${JSON.stringify(previousName)} and ${JSON.stringify(module.name)} both normalize to the \`${propertyName}\` step property. Rename one file so each step property is unique.` });
|
|
23
115
|
names.set(propertyName, module.name);
|
|
24
|
-
return [propertyName, async (input) => await runProviderStep(context.step, `${context.name}/${module.name}`, () => module.run(input))];
|
|
116
|
+
return [propertyName, async (input) => await runProviderStep(context.step, `${context.name}/${module.name}`, (stepContext) => module.run(input, stepContext), module.options)];
|
|
25
117
|
}));
|
|
26
118
|
}
|
|
119
|
+
/** The units of a sleep duration, in milliseconds. Cloudflare reads a month as 30 days and a year as 365.25 days. */
|
|
120
|
+
const durationUnits = {
|
|
121
|
+
second: 1e3,
|
|
122
|
+
minute: 6e4,
|
|
123
|
+
hour: 36e5,
|
|
124
|
+
day: 864e5,
|
|
125
|
+
week: 6048e5,
|
|
126
|
+
month: 2592e6,
|
|
127
|
+
year: 315576e5
|
|
128
|
+
};
|
|
129
|
+
const durationPattern = /^(\d+(?:\.\d+)?) (second|minute|hour|day|week|month|year)s?$/;
|
|
130
|
+
/** The milliseconds of a `WorkflowDuration`: a number of 0 or more, or a string such as `'30 seconds'`. */
|
|
131
|
+
function toDurationMilliseconds(value) {
|
|
132
|
+
if (typeof value === "number") return Number.isFinite(value) && value >= 0 ? value : void 0;
|
|
133
|
+
if (typeof value !== "string") return void 0;
|
|
134
|
+
const match = durationPattern.exec(value);
|
|
135
|
+
return match ? Number(match[1]) * durationUnits[match[2]] : void 0;
|
|
136
|
+
}
|
|
137
|
+
/** A sleep target: a number of milliseconds, or a date. */
|
|
138
|
+
function toSleepTarget(name, until) {
|
|
139
|
+
if (Object.prototype.toString.call(until) === "[object Date]") {
|
|
140
|
+
const date = new Date(until.getTime());
|
|
141
|
+
if (Number.isFinite(date.getTime())) return date;
|
|
142
|
+
} else {
|
|
143
|
+
const milliseconds = toDurationMilliseconds(until);
|
|
144
|
+
if (milliseconds !== void 0) return milliseconds;
|
|
145
|
+
}
|
|
146
|
+
const value = typeof until === "string" ? JSON.stringify(until) : String(until);
|
|
147
|
+
throw workflowErrorDiagnostics.WORKFLOW_SLEEP_DURATION_INVALID({
|
|
148
|
+
name,
|
|
149
|
+
value
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
/** Node fires a timer longer than this at once, so a longer wait uses more than one timer. */
|
|
153
|
+
const maxTimerDelay = 2147483647;
|
|
154
|
+
async function waitUntil(time) {
|
|
155
|
+
for (let left = time - Date.now(); left > 0; left = time - Date.now()) await new Promise((resolve) => setTimeout(resolve, Math.min(left, maxTimerDelay)));
|
|
156
|
+
}
|
|
27
157
|
/**
|
|
28
|
-
*
|
|
29
|
-
*
|
|
158
|
+
* `context.sleep()` of a folder Workflow. It names each sleep by call order (`sleep-1`, `sleep-2`), so the orchestrator
|
|
159
|
+
* must call it in the same order on each replay. Without a provider sleep, the run is inline and waits with a timer.
|
|
30
160
|
*/
|
|
31
|
-
function
|
|
161
|
+
function createSleep(context) {
|
|
162
|
+
let count = 0;
|
|
163
|
+
return async (until) => {
|
|
164
|
+
const target = toSleepTarget(context.name, until);
|
|
165
|
+
const name = `sleep-${++count}`;
|
|
166
|
+
const step = context.step;
|
|
167
|
+
if (step?.sleep) {
|
|
168
|
+
if (typeof target === "number") return await step.sleep(name, target);
|
|
169
|
+
if (step.sleepUntil) return await step.sleepUntil(name, target);
|
|
170
|
+
return await step.sleep(name, Math.max(0, target.getTime() - Date.now()));
|
|
171
|
+
}
|
|
172
|
+
const time = typeof target === "number" ? Date.now() + target : target.getTime();
|
|
173
|
+
await runProviderStep(void 0, name, async () => await waitUntil(time));
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
/**
|
|
177
|
+
* Gives every handler `context.sleep()` and a step runner. Generated folder Workflows replace this empty runner with
|
|
178
|
+
* their step files. The context keeps the provider step at runtime, so the generated step runner can use it.
|
|
179
|
+
*/
|
|
180
|
+
function toExecutionContext(context, sleep) {
|
|
32
181
|
return {
|
|
33
182
|
...context,
|
|
183
|
+
sleep,
|
|
34
184
|
steps: {}
|
|
35
185
|
};
|
|
36
186
|
}
|
|
187
|
+
/** The root step result that says the handler called `context.sleep()`. A replay reads it and fails the same way. */
|
|
188
|
+
const rootStepSleepResult = { "~vitehubRootStepSleep": true };
|
|
189
|
+
function toNonRetryableStepResult(error) {
|
|
190
|
+
if (!isNonRetryableError(error)) return void 0;
|
|
191
|
+
const code = Reflect.get(error, "code");
|
|
192
|
+
return { "~vitehubNonRetryableError": {
|
|
193
|
+
...typeof code === "string" ? { code } : {},
|
|
194
|
+
message: error.message,
|
|
195
|
+
name: error.name
|
|
196
|
+
} };
|
|
197
|
+
}
|
|
198
|
+
function readNonRetryableStepResult(value) {
|
|
199
|
+
if (typeof value !== "object" || value === null || !Object.hasOwn(value, "~vitehubNonRetryableError")) return void 0;
|
|
200
|
+
const { code, message, name } = value["~vitehubNonRetryableError"];
|
|
201
|
+
const error = new NonRetryableError(message);
|
|
202
|
+
error.name = name;
|
|
203
|
+
return code === void 0 ? error : Object.assign(error, { code });
|
|
204
|
+
}
|
|
205
|
+
/**
|
|
206
|
+
* Runs the handler in its root step, or alone for a folder Workflow (`rootStep: false`). A sleep inside the root step
|
|
207
|
+
* fails the run with `WORKFLOW_ROOT_STEP_SLEEP` on every provider. The root step returns a marker instead of throwing,
|
|
208
|
+
* so the provider does not retry it and run the code before the sleep again.
|
|
209
|
+
*/
|
|
210
|
+
async function runInRootStep(context, definition, encode) {
|
|
211
|
+
if (definition.rootStep === false) return await encode(await definition.handler(toExecutionContext(context, createSleep(context))));
|
|
212
|
+
let slept = false;
|
|
213
|
+
const sleepError = () => workflowErrorDiagnostics.WORKFLOW_ROOT_STEP_SLEEP({ name: context.name });
|
|
214
|
+
const sleep = async () => {
|
|
215
|
+
slept = true;
|
|
216
|
+
throw sleepError();
|
|
217
|
+
};
|
|
218
|
+
const output = await runProviderStep(context.step, context.name, async () => {
|
|
219
|
+
try {
|
|
220
|
+
const value = await encode(await definition.handler(toExecutionContext(context, sleep)));
|
|
221
|
+
return slept ? rootStepSleepResult : value;
|
|
222
|
+
} catch (error) {
|
|
223
|
+
if (slept) return rootStepSleepResult;
|
|
224
|
+
throw error;
|
|
225
|
+
}
|
|
226
|
+
});
|
|
227
|
+
if (typeof output === "object" && output !== null && "~vitehubRootStepSleep" in output) throw sleepError();
|
|
228
|
+
return output;
|
|
229
|
+
}
|
|
37
230
|
async function runWorkflowHandler(context, definition) {
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
231
|
+
return toResponse(await runInRootStep(context, definition, (value) => value));
|
|
232
|
+
}
|
|
233
|
+
/**
|
|
234
|
+
* The stored result of a run. A `Response` from the handler is stored as a serialized Response. Any other value is
|
|
235
|
+
* stored as JSON, so every provider returns the same plain value.
|
|
236
|
+
*/
|
|
237
|
+
async function toStoredWorkflowResult(value) {
|
|
238
|
+
if (isResponse(value)) return await serializeResponse(value);
|
|
239
|
+
const json = JSON.stringify(value);
|
|
240
|
+
return json === void 0 ? void 0 : JSON.parse(json);
|
|
41
241
|
}
|
|
42
242
|
/** Encode inside the root step so both checkpoints and final outputs survive replay. */
|
|
43
243
|
async function runSerializedWorkflowHandler(context, definition) {
|
|
44
|
-
|
|
45
|
-
return definition.options?.rootStep === false ? await run() : await runProviderStep(context.step, context.name, run);
|
|
244
|
+
return await runInRootStep(context, definition, toStoredWorkflowResult);
|
|
46
245
|
}
|
|
47
246
|
//#endregion
|
|
48
|
-
export { createWorkflowSteps, runProviderStep, runSerializedWorkflowHandler, runWorkflowHandler };
|
|
247
|
+
export { createWorkflowSteps, readNonRetryableStepResult, resolveWorkflowStepOptions, runProviderStep, runSerializedWorkflowHandler, runWorkflowHandler, runWorkflowStepAttempt, toDurationMilliseconds, toNonRetryableStepResult, toStepPropertyName, withWorkflowStepTimeout };
|
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { getOpenWorkflowRuntime } from "
|
|
1
|
+
import { l as ResolvedWorkflowOptions, m as WorkflowDefinitionRegistry } from "../types-Dsmwsdlv.js";
|
|
2
|
+
import { o as getOpenWorkflowRuntime } from "../openworkflow-BhzxV_Y3.js";
|
|
3
3
|
import { ViteHubError } from "@vite-hub/runtime";
|
|
4
|
+
import { ShutdownApp } from "@vite-hub/runtime/internal/shutdown";
|
|
4
5
|
//#region src/runtime/openworkflow-worker.d.ts
|
|
5
6
|
type OpenWorkflowWorker = ReturnType<Awaited<ReturnType<typeof getOpenWorkflowRuntime>>["client"]["newWorker"]>;
|
|
6
7
|
export interface CreateOpenWorkflowWorkerOptions {
|
|
@@ -15,4 +16,30 @@ export interface StartOpenWorkflowWorkerOptions extends CreateOpenWorkflowWorker
|
|
|
15
16
|
}
|
|
16
17
|
export declare function createOpenWorkflowWorker(options?: CreateOpenWorkflowWorkerOptions): Promise<OpenWorkflowWorker>;
|
|
17
18
|
export declare function startOpenWorkflowWorker(options?: StartOpenWorkflowWorkerOptions): Promise<OpenWorkflowWorker>;
|
|
19
|
+
/** The part of a Nitro app that `installOpenWorkflow()` uses. */
|
|
20
|
+
export interface OpenWorkflowWorkerApp extends ShutdownApp {
|
|
21
|
+
captureError?: (error: Error, context: {
|
|
22
|
+
tags: string[];
|
|
23
|
+
}) => void;
|
|
24
|
+
}
|
|
25
|
+
export interface InstallOpenWorkflowOptions {
|
|
26
|
+
/**
|
|
27
|
+
* Returns the connection URL of the Postgres Default Database. The generated plugin passes it when the build has
|
|
28
|
+
* one, and OpenWorkflow then keeps its runs there unless its own storage is configured.
|
|
29
|
+
*/
|
|
30
|
+
databaseUrl?: () => string | undefined;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Installs OpenWorkflow in a long-lived Nitro server. The generated Workflow startup plugin calls it after it installs
|
|
34
|
+
* the runtime config and registry. It loads OpenWorkflow from the server bundle, then starts the worker unless
|
|
35
|
+
* `workflow.worker` is `false`. The worker stops when the server stops.
|
|
36
|
+
*
|
|
37
|
+
* The worker registers the discovered Workflow Definitions of the registry, which every server of the build has.
|
|
38
|
+
* When the storage is not ready, setup runs again until it works, with a delay that grows to 30 seconds. Each failure
|
|
39
|
+
* 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.
|
|
40
|
+
* The returned promise resolves to `true` when the worker runs, and to `false` when it is off or the server closed
|
|
41
|
+
* first. When the plugin runs again in the same process, as `vite dev` does after a file changes, the previous worker
|
|
42
|
+
* stops taking runs, finishes the runs that it executes on its own backend, and the new one uses the changed definitions.
|
|
43
|
+
*/
|
|
44
|
+
export declare function installOpenWorkflow(app: OpenWorkflowWorkerApp, options?: InstallOpenWorkflowOptions): Promise<boolean>;
|
|
18
45
|
//#endregion
|
|
@@ -1,48 +1,34 @@
|
|
|
1
|
-
import { t as workflowErrorDiagnostics } from "../error-diagnostics-
|
|
2
|
-
import { n as
|
|
3
|
-
import {
|
|
4
|
-
import { getOpenWorkflowRuntime, registerOpenWorkflowDefinition } from "./openworkflow.js";
|
|
5
|
-
import {
|
|
6
|
-
import "@vite-hub/runtime";
|
|
1
|
+
import { t as workflowErrorDiagnostics } from "../error-diagnostics-0V2T3JFw.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
|
-
|
|
12
|
-
|
|
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.
|
|
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
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
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 {
|
|
2
|
-
|
|
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-BhzxV_Y3.js";
|
|
2
|
+
export { OpenWorkflowStorageSource, cancelOpenWorkflowRun, describeOpenWorkflowStorage, detachOpenWorkflowRuntimes, getOpenWorkflowRun, getOpenWorkflowRuntime, registerOpenWorkflowDefinition, resetOpenWorkflowRuntime, runOpenWorkflow, setOpenWorkflowDatabaseUrl, setOpenWorkflowImporter };
|