@facilis.dev/nitro 0.0.0-stage → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +18 -2
- package/dist/config.d.ts +30 -0
- package/dist/config.js +112 -0
- package/dist/constants.d.ts +24 -0
- package/dist/constants.js +24 -0
- package/dist/facade.d.ts +37 -0
- package/dist/facade.js +121 -0
- package/dist/index.d.ts +17 -0
- package/dist/index.js +14 -0
- package/dist/middleware/context.d.ts +5 -0
- package/dist/middleware/context.js +86 -0
- package/dist/middleware/cors.d.ts +10 -0
- package/dist/middleware/cors.js +34 -0
- package/dist/middleware/session.d.ts +9 -0
- package/dist/middleware/session.js +18 -0
- package/dist/module.d.ts +7 -0
- package/dist/module.js +234 -0
- package/dist/rolldown-parser.d.ts +3 -0
- package/dist/rolldown-parser.js +66 -0
- package/dist/route-metadata.d.ts +22 -0
- package/dist/route-metadata.js +161 -0
- package/dist/routes/dev-query.post.d.ts +10 -0
- package/dist/routes/dev-query.post.js +49 -0
- package/dist/routes/dev-schema.get.d.ts +9 -0
- package/dist/routes/dev-schema.get.js +34 -0
- package/dist/routes/dev-view.post.d.ts +11 -0
- package/dist/routes/dev-view.post.js +61 -0
- package/dist/routes/health.get.d.ts +8 -0
- package/dist/routes/health.get.js +18 -0
- package/dist/routes/manifest-revision.get.d.ts +8 -0
- package/dist/routes/manifest-revision.get.js +26 -0
- package/dist/routes/manifest.get.d.ts +8 -0
- package/dist/routes/manifest.get.js +68 -0
- package/dist/routes/openapi.get.d.ts +8 -0
- package/dist/routes/openapi.get.js +29 -0
- package/dist/routes/sso.d.ts +2 -0
- package/dist/routes/sso.js +216 -0
- package/dist/routes/token.post.d.ts +10 -0
- package/dist/routes/token.post.js +75 -0
- package/dist/runtime/boot-runtimes.d.ts +21 -0
- package/dist/runtime/boot-runtimes.js +38 -0
- package/dist/runtime/bootstrap.d.ts +47 -0
- package/dist/runtime/bootstrap.js +214 -0
- package/dist/runtime/config.d.ts +27 -0
- package/dist/runtime/config.js +44 -0
- package/dist/runtime/cors-policy.d.ts +16 -0
- package/dist/runtime/cors-policy.js +88 -0
- package/dist/runtime/db-bootstrap.d.ts +9 -0
- package/dist/runtime/db-bootstrap.js +87 -0
- package/dist/runtime/db-target.d.ts +21 -0
- package/dist/runtime/db-target.js +52 -0
- package/dist/runtime/dev-db-persistence.d.ts +39 -0
- package/dist/runtime/dev-db-persistence.js +124 -0
- package/dist/runtime/dev-query.d.ts +38 -0
- package/dist/runtime/dev-query.js +87 -0
- package/dist/runtime/env.d.ts +9 -0
- package/dist/runtime/env.js +14 -0
- package/dist/runtime/http-guard.d.ts +16 -0
- package/dist/runtime/http-guard.js +42 -0
- package/dist/runtime/http.d.ts +11 -0
- package/dist/runtime/http.js +18 -0
- package/dist/runtime/jobs/boot.d.ts +20 -0
- package/dist/runtime/jobs/boot.js +77 -0
- package/dist/runtime/jobs/contracts.d.ts +161 -0
- package/dist/runtime/jobs/contracts.js +1 -0
- package/dist/runtime/jobs/db-store.d.ts +21 -0
- package/dist/runtime/jobs/db-store.js +210 -0
- package/dist/runtime/jobs/definitions.d.ts +14 -0
- package/dist/runtime/jobs/definitions.js +31 -0
- package/dist/runtime/jobs/engine-support.d.ts +22 -0
- package/dist/runtime/jobs/engine-support.js +32 -0
- package/dist/runtime/jobs/engine.d.ts +6 -0
- package/dist/runtime/jobs/engine.js +261 -0
- package/dist/runtime/jobs/executor.d.ts +11 -0
- package/dist/runtime/jobs/executor.js +27 -0
- package/dist/runtime/jobs/memory-store.d.ts +7 -0
- package/dist/runtime/jobs/memory-store.js +183 -0
- package/dist/runtime/jobs/row-mapping.d.ts +28 -0
- package/dist/runtime/jobs/row-mapping.js +61 -0
- package/dist/runtime/jobs/runtime.d.ts +24 -0
- package/dist/runtime/jobs/runtime.js +86 -0
- package/dist/runtime/logging/audit-chain.d.ts +54 -0
- package/dist/runtime/logging/audit-chain.js +102 -0
- package/dist/runtime/logging/bootstrap-logging.d.ts +28 -0
- package/dist/runtime/logging/bootstrap-logging.js +26 -0
- package/dist/runtime/logging/entry.d.ts +14 -0
- package/dist/runtime/logging/entry.js +85 -0
- package/dist/runtime/logging/file-sink.d.ts +24 -0
- package/dist/runtime/logging/file-sink.js +128 -0
- package/dist/runtime/logging/log-settings.d.ts +52 -0
- package/dist/runtime/logging/log-settings.js +93 -0
- package/dist/runtime/logging/log-sink.d.ts +18 -0
- package/dist/runtime/logging/log-sink.js +22 -0
- package/dist/runtime/logging/redact.d.ts +31 -0
- package/dist/runtime/logging/redact.js +106 -0
- package/dist/runtime/logging/runtime.d.ts +25 -0
- package/dist/runtime/logging/runtime.js +114 -0
- package/dist/runtime/logging/sudo-bridge.d.ts +13 -0
- package/dist/runtime/logging/sudo-bridge.js +38 -0
- package/dist/runtime/manifest-data.d.ts +28 -0
- package/dist/runtime/manifest-data.js +70 -0
- package/dist/runtime/manifest-response.d.ts +45 -0
- package/dist/runtime/manifest-response.js +50 -0
- package/dist/runtime/manifest-sections.d.ts +20 -0
- package/dist/runtime/manifest-sections.js +59 -0
- package/dist/runtime/manifest-service.d.ts +16 -0
- package/dist/runtime/manifest-service.js +66 -0
- package/dist/runtime/project-config.d.ts +8 -0
- package/dist/runtime/project-config.js +22 -0
- package/dist/runtime/project-files.d.ts +12 -0
- package/dist/runtime/project-files.js +99 -0
- package/dist/runtime/rate-limit.d.ts +6 -0
- package/dist/runtime/rate-limit.js +6 -0
- package/dist/runtime/revision-service.d.ts +15 -0
- package/dist/runtime/revision-service.js +26 -0
- package/dist/runtime/sql.d.ts +8 -0
- package/dist/runtime/sql.js +23 -0
- package/dist/runtime/sso.d.ts +40 -0
- package/dist/runtime/sso.js +98 -0
- package/dist/runtime/state.d.ts +7 -0
- package/dist/runtime/state.js +7 -0
- package/dist/runtime/storage-keys.d.ts +9 -0
- package/dist/runtime/storage-keys.js +82 -0
- package/dist/runtime/storage-target.d.ts +25 -0
- package/dist/runtime/storage-target.js +155 -0
- package/dist/runtime/system-role.d.ts +9 -0
- package/dist/runtime/system-role.js +21 -0
- package/dist/runtime/tasks/boot.d.ts +20 -0
- package/dist/runtime/tasks/boot.js +32 -0
- package/dist/runtime/tasks/contracts.d.ts +70 -0
- package/dist/runtime/tasks/contracts.js +1 -0
- package/dist/runtime/tasks/db-store.d.ts +18 -0
- package/dist/runtime/tasks/db-store.js +139 -0
- package/dist/runtime/tasks/row-mapping.d.ts +11 -0
- package/dist/runtime/tasks/row-mapping.js +69 -0
- package/dist/runtime/tasks/runtime.d.ts +7 -0
- package/dist/runtime/tasks/runtime.js +162 -0
- package/dist/runtime/tasks/tasks-test-harness.d.ts +16 -0
- package/dist/runtime/tasks/tasks-test-harness.js +70 -0
- package/dist/runtime/tenant.d.ts +10 -0
- package/dist/runtime/tenant.js +13 -0
- package/dist/runtime/workflows/boot.d.ts +25 -0
- package/dist/runtime/workflows/boot.js +75 -0
- package/dist/runtime/workflows/contracts.d.ts +96 -0
- package/dist/runtime/workflows/contracts.js +1 -0
- package/dist/runtime/workflows/db-store.d.ts +18 -0
- package/dist/runtime/workflows/db-store.js +128 -0
- package/dist/runtime/workflows/definitions.d.ts +14 -0
- package/dist/runtime/workflows/definitions.js +50 -0
- package/dist/runtime/workflows/dispatch.d.ts +4 -0
- package/dist/runtime/workflows/dispatch.js +119 -0
- package/dist/runtime/workflows/row-mapping.d.ts +5 -0
- package/dist/runtime/workflows/row-mapping.js +38 -0
- package/dist/runtime/workflows/runner.d.ts +15 -0
- package/dist/runtime/workflows/runner.js +89 -0
- package/dist/runtime/workflows/runtime.d.ts +14 -0
- package/dist/runtime/workflows/runtime.js +129 -0
- package/dist/runtime/workflows/steps.d.ts +14 -0
- package/dist/runtime/workflows/steps.js +49 -0
- package/dist/runtime/workflows/support.d.ts +20 -0
- package/dist/runtime/workflows/support.js +36 -0
- package/dist/runtime/workflows/transitions.d.ts +8 -0
- package/dist/runtime/workflows/transitions.js +184 -0
- package/dist/runtime/workflows/workflows-test-harness.d.ts +62 -0
- package/dist/runtime/workflows/workflows-test-harness.js +178 -0
- package/dist/session-cookie.d.ts +13 -0
- package/dist/session-cookie.js +48 -0
- package/dist/storage.d.ts +50 -0
- package/dist/storage.js +118 -0
- package/dist/types.d.ts +44 -0
- package/dist/types.js +1 -0
- package/dist/virtual-ids.d.ts +17 -0
- package/dist/virtual-ids.js +17 -0
- package/dist/vite.d.ts +22 -0
- package/dist/vite.js +135 -0
- package/package.json +61 -4
- package/src/config.ts +120 -0
- package/src/constants.ts +24 -0
- package/src/facade.ts +153 -0
- package/src/index.ts +44 -0
- package/src/middleware/context.ts +106 -0
- package/src/middleware/cors.ts +42 -0
- package/src/middleware/session.ts +23 -0
- package/src/module.ts +278 -0
- package/src/rolldown-parser.ts +79 -0
- package/src/route-metadata-test-harness.ts +62 -0
- package/src/route-metadata.ts +194 -0
- package/src/routes/dev-query.post.ts +53 -0
- package/src/routes/dev-schema.get.ts +43 -0
- package/src/routes/dev-view.post.ts +66 -0
- package/src/routes/health.get.ts +26 -0
- package/src/routes/manifest-revision.get.ts +38 -0
- package/src/routes/manifest.get.ts +111 -0
- package/src/routes/openapi.get.ts +34 -0
- package/src/routes/sso.ts +247 -0
- package/src/routes/token.post.ts +89 -0
- package/src/runtime/boot-runtimes.ts +69 -0
- package/src/runtime/bootstrap.ts +300 -0
- package/src/runtime/config.ts +60 -0
- package/src/runtime/cors-policy.ts +107 -0
- package/src/runtime/db-bootstrap.ts +99 -0
- package/src/runtime/db-target.ts +87 -0
- package/src/runtime/dev-db-persistence.ts +146 -0
- package/src/runtime/dev-query.ts +124 -0
- package/src/runtime/env.ts +18 -0
- package/src/runtime/http-guard.ts +50 -0
- package/src/runtime/http.ts +30 -0
- package/src/runtime/jobs/boot.ts +97 -0
- package/src/runtime/jobs/contracts.ts +165 -0
- package/src/runtime/jobs/db-store-test-harness.ts +98 -0
- package/src/runtime/jobs/db-store.ts +273 -0
- package/src/runtime/jobs/definitions.ts +42 -0
- package/src/runtime/jobs/engine-support.ts +44 -0
- package/src/runtime/jobs/engine.ts +296 -0
- package/src/runtime/jobs/executor.ts +37 -0
- package/src/runtime/jobs/memory-store.ts +222 -0
- package/src/runtime/jobs/row-mapping.ts +67 -0
- package/src/runtime/jobs/runtime.ts +110 -0
- package/src/runtime/logging/audit-chain.ts +135 -0
- package/src/runtime/logging/bootstrap-logging.ts +62 -0
- package/src/runtime/logging/entry.ts +99 -0
- package/src/runtime/logging/file-sink.ts +157 -0
- package/src/runtime/logging/log-settings.ts +166 -0
- package/src/runtime/logging/log-sink.ts +31 -0
- package/src/runtime/logging/redact.ts +108 -0
- package/src/runtime/logging/runtime.ts +163 -0
- package/src/runtime/logging/sudo-bridge.ts +41 -0
- package/src/runtime/manifest-data.ts +103 -0
- package/src/runtime/manifest-response.ts +95 -0
- package/src/runtime/manifest-sections.ts +79 -0
- package/src/runtime/manifest-service.ts +83 -0
- package/src/runtime/project-config.ts +25 -0
- package/src/runtime/project-files.ts +103 -0
- package/src/runtime/rate-limit.ts +12 -0
- package/src/runtime/revision-service.ts +38 -0
- package/src/runtime/sql.ts +24 -0
- package/src/runtime/sso.ts +153 -0
- package/src/runtime/state.ts +7 -0
- package/src/runtime/storage-keys.ts +95 -0
- package/src/runtime/storage-target.ts +238 -0
- package/src/runtime/system-role.ts +26 -0
- package/src/runtime/tasks/boot.ts +49 -0
- package/src/runtime/tasks/contracts.ts +77 -0
- package/src/runtime/tasks/db-store.ts +191 -0
- package/src/runtime/tasks/row-mapping.ts +75 -0
- package/src/runtime/tasks/runtime.ts +192 -0
- package/src/runtime/tasks/tasks-test-harness.ts +92 -0
- package/src/runtime/tenant.ts +15 -0
- package/src/runtime/workflows/boot.ts +97 -0
- package/src/runtime/workflows/contracts.ts +114 -0
- package/src/runtime/workflows/db-store.ts +156 -0
- package/src/runtime/workflows/definitions.ts +75 -0
- package/src/runtime/workflows/dispatch.ts +148 -0
- package/src/runtime/workflows/row-mapping.ts +54 -0
- package/src/runtime/workflows/runner.ts +105 -0
- package/src/runtime/workflows/runtime.ts +161 -0
- package/src/runtime/workflows/steps.ts +74 -0
- package/src/runtime/workflows/support.ts +60 -0
- package/src/runtime/workflows/transitions.ts +259 -0
- package/src/runtime/workflows/workflows-test-harness.ts +238 -0
- package/src/session-cookie.ts +69 -0
- package/src/storage.ts +173 -0
- package/src/types.ts +51 -0
- package/src/virtual-ids.ts +18 -0
- package/src/virtual-modules.d.ts +53 -0
- package/src/vite.ts +175 -0
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { serializeWorkflowData } from "@facilis.dev/core";
|
|
2
|
+
import type { WorkflowDefinition, WorkflowsApi, WorkflowStatus } from "@facilis.dev/core";
|
|
3
|
+
import type { WorkflowRuntimeDeps } from "./contracts.js";
|
|
4
|
+
/** Terminal statuses: cancel is a no-op and the tick never reads them. */
|
|
5
|
+
export declare const TERMINAL_WORKFLOW_STATUSES: ReadonlySet<WorkflowStatus>;
|
|
6
|
+
/**
|
|
7
|
+
* Adapts the workflow store and the job engine to the handler-facing API.
|
|
8
|
+
*
|
|
9
|
+
* `wake` asks the runner for an immediate tick; a bound view (`bindScope`) joins the
|
|
10
|
+
* request transaction for every read/write it performs.
|
|
11
|
+
*/
|
|
12
|
+
export declare function createWorkflowsApi(deps: WorkflowRuntimeDeps, wake: () => void): WorkflowsApi;
|
|
13
|
+
/** Zod-validates the start input and serializes it for the row (what the runner reads). */
|
|
14
|
+
export declare function parseStartInput(definition: WorkflowDefinition<unknown, unknown>, input: unknown): ReturnType<typeof serializeWorkflowData>;
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
// The server-only workflow API (D-135, docs/WORKFLOWS.md §7).
|
|
2
|
+
//
|
|
3
|
+
// Validation and JSON serialization live here; the store only knows rows and the runner owns
|
|
4
|
+
// every state transition. `start` writes the row and wakes the tick - it never executes a
|
|
5
|
+
// step inline, so a route's latency is independent of the chain (WORKFLOWS.md §4).
|
|
6
|
+
import { randomUUID } from "node:crypto";
|
|
7
|
+
import { serializeWorkflowData, WORKFLOW_STATUSES, WorkflowError } from "@facilis.dev/core";
|
|
8
|
+
import { formatIssues } from "../jobs/engine-support.js";
|
|
9
|
+
import { toWorkflowRecord } from "./row-mapping.js";
|
|
10
|
+
import { stepIdentity } from "./steps.js";
|
|
11
|
+
const DEFAULT_LIMIT = 50;
|
|
12
|
+
const MAX_LIMIT = 200;
|
|
13
|
+
/** Terminal statuses: cancel is a no-op and the tick never reads them. */
|
|
14
|
+
export const TERMINAL_WORKFLOW_STATUSES = new Set([
|
|
15
|
+
"succeeded",
|
|
16
|
+
"failed",
|
|
17
|
+
"cancelled",
|
|
18
|
+
]);
|
|
19
|
+
/**
|
|
20
|
+
* Adapts the workflow store and the job engine to the handler-facing API.
|
|
21
|
+
*
|
|
22
|
+
* `wake` asks the runner for an immediate tick; a bound view (`bindScope`) joins the
|
|
23
|
+
* request transaction for every read/write it performs.
|
|
24
|
+
*/
|
|
25
|
+
export function createWorkflowsApi(deps, wake) {
|
|
26
|
+
const now = () => (deps.now ?? (() => new Date()))();
|
|
27
|
+
const api = {
|
|
28
|
+
async start(name, input) {
|
|
29
|
+
const definition = deps.definitions.get(name);
|
|
30
|
+
if (definition === undefined) {
|
|
31
|
+
throw new WorkflowError("workflow_unknown", `Workflow "${name}" is not defined by this project.`);
|
|
32
|
+
}
|
|
33
|
+
const data = parseStartInput(definition, input);
|
|
34
|
+
const id = randomUUID();
|
|
35
|
+
const createdAt = now();
|
|
36
|
+
await deps.store.insert({
|
|
37
|
+
id,
|
|
38
|
+
name,
|
|
39
|
+
input: data,
|
|
40
|
+
plan: definition.steps.map(stepIdentity),
|
|
41
|
+
startedAt: createdAt,
|
|
42
|
+
createdAt,
|
|
43
|
+
});
|
|
44
|
+
wake();
|
|
45
|
+
return { id };
|
|
46
|
+
},
|
|
47
|
+
async get(id) {
|
|
48
|
+
const workflow = await deps.store.get(id);
|
|
49
|
+
return workflow === null ? null : toWorkflowRecord(workflow);
|
|
50
|
+
},
|
|
51
|
+
async list(options = {}) {
|
|
52
|
+
return (await deps.store.list(normalizeFilters(options))).map(toWorkflowRecord);
|
|
53
|
+
},
|
|
54
|
+
async cancel(id) {
|
|
55
|
+
const workflow = await deps.store.get(id);
|
|
56
|
+
if (workflow === null || TERMINAL_WORKFLOW_STATUSES.has(workflow.status))
|
|
57
|
+
return false;
|
|
58
|
+
const finishedAt = now();
|
|
59
|
+
// Stop the side effect first, then settle the row: a crash in between leaves the job/
|
|
60
|
+
// task terminal, so the next tick observes cancellation instead of stalling (JOBS §8).
|
|
61
|
+
if (workflow.currentJobId !== null)
|
|
62
|
+
await deps.jobs.cancel(workflow.currentJobId);
|
|
63
|
+
if (workflow.waitingTaskId !== null) {
|
|
64
|
+
await deps.tasks.cancel(workflow.waitingTaskId, finishedAt);
|
|
65
|
+
}
|
|
66
|
+
const updated = await deps.store.update(id, {
|
|
67
|
+
status: workflow.status,
|
|
68
|
+
currentStep: workflow.currentStep,
|
|
69
|
+
currentJobId: workflow.currentJobId,
|
|
70
|
+
waitingTaskId: workflow.waitingTaskId,
|
|
71
|
+
}, {
|
|
72
|
+
status: "cancelled",
|
|
73
|
+
currentJobId: null,
|
|
74
|
+
waitingTaskId: null,
|
|
75
|
+
error: null,
|
|
76
|
+
finishedAt,
|
|
77
|
+
});
|
|
78
|
+
return updated !== null;
|
|
79
|
+
},
|
|
80
|
+
/**
|
|
81
|
+
* A handler's ctx.workflows joins the request's policy transaction, so starting or
|
|
82
|
+
* cancelling inside a route does not open a second transaction on the one connection
|
|
83
|
+
* (D-107, docs/JOBS.md §8).
|
|
84
|
+
*/
|
|
85
|
+
bindScope(scope) {
|
|
86
|
+
return createWorkflowsApi({
|
|
87
|
+
...deps,
|
|
88
|
+
store: deps.store.scoped?.(scope) ?? deps.store,
|
|
89
|
+
tasks: deps.tasks.scoped?.(scope) ?? deps.tasks,
|
|
90
|
+
jobs: deps.jobs.scoped?.(scope) ?? deps.jobs,
|
|
91
|
+
}, wake);
|
|
92
|
+
},
|
|
93
|
+
};
|
|
94
|
+
return api;
|
|
95
|
+
}
|
|
96
|
+
/** Zod-validates the start input and serializes it for the row (what the runner reads). */
|
|
97
|
+
export function parseStartInput(definition, input) {
|
|
98
|
+
const parsed = definition.input.safeParse(input);
|
|
99
|
+
if (!parsed.success) {
|
|
100
|
+
throw new WorkflowError("workflow_invalid_input", formatIssues(parsed.error.issues));
|
|
101
|
+
}
|
|
102
|
+
return serializeWorkflowData(parsed.data);
|
|
103
|
+
}
|
|
104
|
+
function normalizeFilters(options) {
|
|
105
|
+
const status = options.status;
|
|
106
|
+
if (status !== undefined) {
|
|
107
|
+
const values = typeof status === "string" ? [status] : [...status];
|
|
108
|
+
for (const value of values) {
|
|
109
|
+
if (!WORKFLOW_STATUSES.includes(value)) {
|
|
110
|
+
throw invalid(`Unknown workflow status "${String(value)}".`);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
return {
|
|
115
|
+
...(status === undefined ? {} : { status }),
|
|
116
|
+
...(options.name === undefined ? {} : { name: options.name }),
|
|
117
|
+
limit: normalizeLimit(options.limit),
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
function normalizeLimit(value) {
|
|
121
|
+
if (value === undefined)
|
|
122
|
+
return DEFAULT_LIMIT;
|
|
123
|
+
if (!Number.isInteger(value) || value < 1)
|
|
124
|
+
throw invalid("limit must be a positive integer.");
|
|
125
|
+
return Math.min(value, MAX_LIMIT);
|
|
126
|
+
}
|
|
127
|
+
function invalid(message) {
|
|
128
|
+
return new WorkflowError("workflow_invalid_input", message);
|
|
129
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { JobJson, WorkflowDefinition, WorkflowProgressEntry, WorkflowResolveContext, WorkflowStep, WorkflowStepIdentity } from "@facilis.dev/core";
|
|
2
|
+
/** The plan-snapshot identity of a step: kind plus the name a resume compares against. */
|
|
3
|
+
export declare function stepIdentity(step: WorkflowStep, index: number): WorkflowStepIdentity;
|
|
4
|
+
/** True when the stored plan still describes the definition's step at `index`. */
|
|
5
|
+
export declare function planMatches(plan: readonly WorkflowStepIdentity[], definition: WorkflowDefinition, index: number): boolean;
|
|
6
|
+
/** Outputs of the completed steps in order; an approval step contributes null. */
|
|
7
|
+
export declare function stepOutputs(progress: readonly WorkflowProgressEntry[], count: number): (JobJson | null)[];
|
|
8
|
+
/** The resolver context for the step at `index`: chain input plus completed outputs. */
|
|
9
|
+
export declare function resolveContext(input: JobJson, progress: readonly WorkflowProgressEntry[], index: number): WorkflowResolveContext;
|
|
10
|
+
/**
|
|
11
|
+
* Validates a resolved approval `params` value: a flat JSON object of string/number
|
|
12
|
+
* values, exactly what `t(titleKey, params)` can interpolate.
|
|
13
|
+
*/
|
|
14
|
+
export declare function normalizeTitleParams(value: unknown): Record<string, string | number>;
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { WorkflowError } from "@facilis.dev/core";
|
|
2
|
+
/** The plan-snapshot identity of a step: kind plus the name a resume compares against. */
|
|
3
|
+
export function stepIdentity(step, index) {
|
|
4
|
+
return "job" in step
|
|
5
|
+
? { index, kind: "job", name: step.job }
|
|
6
|
+
: { index, kind: "approval", name: step.approval.titleKey };
|
|
7
|
+
}
|
|
8
|
+
/** True when the stored plan still describes the definition's step at `index`. */
|
|
9
|
+
export function planMatches(plan, definition, index) {
|
|
10
|
+
const step = definition.steps[index];
|
|
11
|
+
if (step === undefined)
|
|
12
|
+
return false;
|
|
13
|
+
const expected = stepIdentity(step, index);
|
|
14
|
+
const stored = plan[index];
|
|
15
|
+
return stored !== undefined && stored.kind === expected.kind && stored.name === expected.name;
|
|
16
|
+
}
|
|
17
|
+
/** Outputs of the completed steps in order; an approval step contributes null. */
|
|
18
|
+
export function stepOutputs(progress, count) {
|
|
19
|
+
const outputs = [];
|
|
20
|
+
for (let index = 0; index < count; index += 1) {
|
|
21
|
+
const entry = progress.find((candidate) => candidate.index === index);
|
|
22
|
+
outputs.push(entry?.output ?? null);
|
|
23
|
+
}
|
|
24
|
+
return outputs;
|
|
25
|
+
}
|
|
26
|
+
/** The resolver context for the step at `index`: chain input plus completed outputs. */
|
|
27
|
+
export function resolveContext(input, progress, index) {
|
|
28
|
+
return { input, steps: stepOutputs(progress, index) };
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Validates a resolved approval `params` value: a flat JSON object of string/number
|
|
32
|
+
* values, exactly what `t(titleKey, params)` can interpolate.
|
|
33
|
+
*/
|
|
34
|
+
export function normalizeTitleParams(value) {
|
|
35
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
36
|
+
throw new WorkflowError("workflow_step_failed", "Approval params must resolve to an object.");
|
|
37
|
+
}
|
|
38
|
+
const params = {};
|
|
39
|
+
for (const [key, entry] of Object.entries(value)) {
|
|
40
|
+
if (typeof entry === "string")
|
|
41
|
+
params[key] = entry;
|
|
42
|
+
else if (typeof entry === "number" && Number.isFinite(entry))
|
|
43
|
+
params[key] = entry;
|
|
44
|
+
else {
|
|
45
|
+
throw new WorkflowError("workflow_step_failed", `Approval param "${key}" must be a string or a finite number.`);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
return params;
|
|
49
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { JobJson, WorkflowProgressEntry } from "@facilis.dev/core";
|
|
2
|
+
import type { StoredWorkflow, WorkflowRuntimeDeps } from "./contracts.js";
|
|
3
|
+
/** Stored failures are diagnostics, not a log (same bound as a job's error). */
|
|
4
|
+
export declare const MAX_STORED_ERROR = 2000;
|
|
5
|
+
export type Now = () => Date;
|
|
6
|
+
/** Thrown inside a transaction when the CAS guard no longer matches, to roll the write back. */
|
|
7
|
+
export declare class CasLost extends Error {
|
|
8
|
+
}
|
|
9
|
+
/** Settles a chain as failed, keeping the coded reason in `error`. */
|
|
10
|
+
export declare function fail(deps: WorkflowRuntimeDeps, now: Now, workflow: StoredWorkflow, code: string, message: string): Promise<void>;
|
|
11
|
+
/** Every present field is an AND condition: the transition only applies to what it read. */
|
|
12
|
+
export declare function guard(workflow: StoredWorkflow): {
|
|
13
|
+
status: StoredWorkflow["status"];
|
|
14
|
+
currentStep: number;
|
|
15
|
+
currentJobId: string | null;
|
|
16
|
+
waitingTaskId: string | null;
|
|
17
|
+
};
|
|
18
|
+
/** The serialized output of the step at `index`, or null when it has none. */
|
|
19
|
+
export declare function lastOutput(progress: readonly WorkflowProgressEntry[], index: number): JobJson | null;
|
|
20
|
+
export declare function describe(error: unknown): string;
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
// Shared helpers of the workflow state machine (D-135, docs/WORKFLOWS.md §8).
|
|
2
|
+
//
|
|
3
|
+
// Kept out of transitions.ts/dispatch.ts so both files stay under the 300-line gate and the
|
|
4
|
+
// compare-and-set policy lives in one place: a transition only applies to the row it read.
|
|
5
|
+
import { WorkflowError } from "@facilis.dev/core";
|
|
6
|
+
/** Stored failures are diagnostics, not a log (same bound as a job's error). */
|
|
7
|
+
export const MAX_STORED_ERROR = 2000;
|
|
8
|
+
/** Thrown inside a transaction when the CAS guard no longer matches, to roll the write back. */
|
|
9
|
+
export class CasLost extends Error {
|
|
10
|
+
}
|
|
11
|
+
/** Settles a chain as failed, keeping the coded reason in `error`. */
|
|
12
|
+
export async function fail(deps, now, workflow, code, message) {
|
|
13
|
+
await deps.store.update(workflow.id, guard(workflow), {
|
|
14
|
+
status: "failed",
|
|
15
|
+
currentJobId: null,
|
|
16
|
+
waitingTaskId: null,
|
|
17
|
+
error: (code + ": " + message).slice(0, MAX_STORED_ERROR),
|
|
18
|
+
finishedAt: now(),
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
/** Every present field is an AND condition: the transition only applies to what it read. */
|
|
22
|
+
export function guard(workflow) {
|
|
23
|
+
return {
|
|
24
|
+
status: workflow.status,
|
|
25
|
+
currentStep: workflow.currentStep,
|
|
26
|
+
currentJobId: workflow.currentJobId,
|
|
27
|
+
waitingTaskId: workflow.waitingTaskId,
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
/** The serialized output of the step at `index`, or null when it has none. */
|
|
31
|
+
export function lastOutput(progress, index) {
|
|
32
|
+
return progress.find((entry) => entry.index === index)?.output ?? null;
|
|
33
|
+
}
|
|
34
|
+
export function describe(error) {
|
|
35
|
+
return error instanceof WorkflowError || error instanceof Error ? error.message : String(error);
|
|
36
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { StoredWorkflow, WorkflowRuntimeDeps } from "./contracts.js";
|
|
2
|
+
import { type Now } from "./support.js";
|
|
3
|
+
/** Active rows one tick advances; the tick re-arms itself, so this is a fairness bound. */
|
|
4
|
+
export declare const TICK_BATCH = 25;
|
|
5
|
+
/** Expires due tasks, then fails the workflows waiting on them (docs/WORKFLOWS.md §8.1). */
|
|
6
|
+
export declare function expireDueTasks(deps: WorkflowRuntimeDeps, now: Now): Promise<void>;
|
|
7
|
+
/** One transition of one active workflow. */
|
|
8
|
+
export declare function stepWorkflow(deps: WorkflowRuntimeDeps, now: Now, workflow: StoredWorkflow): Promise<void>;
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
import { formatIssues } from "../jobs/engine-support.js";
|
|
2
|
+
import { dispatch } from "./dispatch.js";
|
|
3
|
+
import { planMatches } from "./steps.js";
|
|
4
|
+
import { fail, guard } from "./support.js";
|
|
5
|
+
/** Active rows one tick advances; the tick re-arms itself, so this is a fairness bound. */
|
|
6
|
+
export const TICK_BATCH = 25;
|
|
7
|
+
/** Expires due tasks, then fails the workflows waiting on them (docs/WORKFLOWS.md §8.1). */
|
|
8
|
+
export async function expireDueTasks(deps, now) {
|
|
9
|
+
const expired = await deps.tasks.expireDue(now(), TICK_BATCH);
|
|
10
|
+
if (expired.length === 0)
|
|
11
|
+
return;
|
|
12
|
+
for (const task of expired) {
|
|
13
|
+
if (task.workflowId === null)
|
|
14
|
+
continue;
|
|
15
|
+
const workflow = await deps.store.get(task.workflowId);
|
|
16
|
+
if (workflow === null || workflow.status !== "waiting")
|
|
17
|
+
continue;
|
|
18
|
+
if (workflow.waitingTaskId !== task.id)
|
|
19
|
+
continue;
|
|
20
|
+
await fail(deps, now, workflow, "workflow_task_expired", "Task " + task.id + " expired.");
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
/** One transition of one active workflow. */
|
|
24
|
+
export async function stepWorkflow(deps, now, workflow) {
|
|
25
|
+
if (workflow.status === "waiting")
|
|
26
|
+
return resume(deps, now, workflow);
|
|
27
|
+
if (workflow.currentJobId !== null)
|
|
28
|
+
return advance(deps, now, workflow);
|
|
29
|
+
return dispatch(deps, now, workflow, 1);
|
|
30
|
+
}
|
|
31
|
+
/** A decided/expired/cancelled waiting task resumes or fails the chain (§8.2). */
|
|
32
|
+
async function resume(deps, now, workflow) {
|
|
33
|
+
if (workflow.waitingTaskId === null) {
|
|
34
|
+
return fail(deps, now, workflow, "workflow_interrupted", "Waiting workflow has no task.");
|
|
35
|
+
}
|
|
36
|
+
const task = await deps.tasks.get(workflow.waitingTaskId);
|
|
37
|
+
if (task === null) {
|
|
38
|
+
return fail(deps, now, workflow, "workflow_interrupted", "Task " + workflow.waitingTaskId + " is missing.");
|
|
39
|
+
}
|
|
40
|
+
if (task.status === "pending") {
|
|
41
|
+
if (task.expiresAt !== null && task.expiresAt.getTime() <= now().getTime()) {
|
|
42
|
+
// A decision may have won the race between the read and the expiry: then wait for the
|
|
43
|
+
// next tick, which sees the decided row (the CAS keeps exactly one winner, D-135).
|
|
44
|
+
const expired = await deps.tasks.expire(task.id, now());
|
|
45
|
+
if (expired) {
|
|
46
|
+
return fail(deps, now, workflow, "workflow_task_expired", "Task " + task.id + " expired.");
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
if (task.status === "expired") {
|
|
52
|
+
return fail(deps, now, workflow, "workflow_task_expired", "Task " + task.id + " expired.");
|
|
53
|
+
}
|
|
54
|
+
if (task.status === "cancelled") {
|
|
55
|
+
return fail(deps, now, workflow, "workflow_task_cancelled", "Task " + task.id + " was cancelled.");
|
|
56
|
+
}
|
|
57
|
+
if (task.decision === "reject") {
|
|
58
|
+
return rejectTask(deps, now, workflow, task);
|
|
59
|
+
}
|
|
60
|
+
const entry = {
|
|
61
|
+
index: task.stepIndex ?? workflow.currentStep,
|
|
62
|
+
kind: "approval",
|
|
63
|
+
taskId: task.id,
|
|
64
|
+
decision: "approve",
|
|
65
|
+
};
|
|
66
|
+
const updated = await deps.store.update(workflow.id, guard(workflow), {
|
|
67
|
+
status: "running",
|
|
68
|
+
waitingTaskId: null,
|
|
69
|
+
progress: [...workflow.progress, entry],
|
|
70
|
+
currentStep: workflow.currentStep + 1,
|
|
71
|
+
attempts: 0,
|
|
72
|
+
});
|
|
73
|
+
if (updated === null)
|
|
74
|
+
return;
|
|
75
|
+
await dispatch(deps, now, updated, 1);
|
|
76
|
+
}
|
|
77
|
+
/** A rejected approval continues at its declared step, or fails the run (§8.2). */
|
|
78
|
+
async function rejectTask(deps, now, workflow, task) {
|
|
79
|
+
const definition = deps.definitions.get(workflow.name);
|
|
80
|
+
if (definition === undefined) {
|
|
81
|
+
return fail(deps, now, workflow, "workflow_definition_changed", 'Workflow "' + workflow.name + '" is no longer defined.');
|
|
82
|
+
}
|
|
83
|
+
const index = task.stepIndex ?? workflow.currentStep;
|
|
84
|
+
const step = definition.steps[index];
|
|
85
|
+
const target = step !== undefined && "approval" in step ? step.approval.onReject : undefined;
|
|
86
|
+
if (target === undefined) {
|
|
87
|
+
return fail(deps, now, workflow, "workflow_task_rejected", "Task " + task.id + " was rejected.");
|
|
88
|
+
}
|
|
89
|
+
// A definition edited mid-run must not redirect the branch: the plan snapshot has to still
|
|
90
|
+
// describe the target step (the same rule dispatch applies to the current step).
|
|
91
|
+
if (target.step <= index ||
|
|
92
|
+
target.step >= definition.steps.length ||
|
|
93
|
+
!planMatches(workflow.plan, definition, target.step)) {
|
|
94
|
+
return fail(deps, now, workflow, "workflow_definition_changed", "Step " + target.step + " is not the planned reject target.");
|
|
95
|
+
}
|
|
96
|
+
const entry = {
|
|
97
|
+
index,
|
|
98
|
+
kind: "approval",
|
|
99
|
+
taskId: task.id,
|
|
100
|
+
decision: "reject",
|
|
101
|
+
};
|
|
102
|
+
const updated = await deps.store.update(workflow.id, guard(workflow), {
|
|
103
|
+
status: "running",
|
|
104
|
+
waitingTaskId: null,
|
|
105
|
+
progress: [...workflow.progress, entry],
|
|
106
|
+
currentStep: target.step,
|
|
107
|
+
attempts: 0,
|
|
108
|
+
});
|
|
109
|
+
if (updated !== null)
|
|
110
|
+
await dispatch(deps, now, updated, 1);
|
|
111
|
+
}
|
|
112
|
+
/** Settles the in-flight job step: advance, fail, cancelled, or recover a missing job (§8.3). */
|
|
113
|
+
async function advance(deps, now, workflow) {
|
|
114
|
+
const jobId = workflow.currentJobId;
|
|
115
|
+
if (jobId === null)
|
|
116
|
+
return;
|
|
117
|
+
const job = await deps.jobs.get(jobId);
|
|
118
|
+
if (job === null) {
|
|
119
|
+
// Boot recovery: the queue lost the row (memory fallback or an interrupted process).
|
|
120
|
+
if (workflow.attempts >= deps.maxStepAttempts) {
|
|
121
|
+
return fail(deps, now, workflow, "workflow_interrupted", "Step job " + jobId + " disappeared after " + workflow.attempts + " dispatch(es).");
|
|
122
|
+
}
|
|
123
|
+
return dispatch(deps, now, workflow, workflow.attempts + 1);
|
|
124
|
+
}
|
|
125
|
+
if (job.status === "queued" || job.status === "running")
|
|
126
|
+
return;
|
|
127
|
+
if (job.status === "failed") {
|
|
128
|
+
return fail(deps, now, workflow, "workflow_step_failed", job.error ?? "Job " + jobId + " failed.");
|
|
129
|
+
}
|
|
130
|
+
if (job.status === "cancelled") {
|
|
131
|
+
await deps.store.update(workflow.id, guard(workflow), {
|
|
132
|
+
status: "cancelled",
|
|
133
|
+
currentJobId: null,
|
|
134
|
+
error: null,
|
|
135
|
+
finishedAt: now(),
|
|
136
|
+
});
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
const definition = deps.definitions.get(workflow.name);
|
|
140
|
+
if (definition === undefined) {
|
|
141
|
+
return fail(deps, now, workflow, "workflow_definition_changed", 'Workflow "' + workflow.name + '" is no longer defined.');
|
|
142
|
+
}
|
|
143
|
+
const output = job.output ?? null;
|
|
144
|
+
const entry = {
|
|
145
|
+
index: workflow.currentStep,
|
|
146
|
+
kind: "job",
|
|
147
|
+
jobId,
|
|
148
|
+
...(output === null ? {} : { output }),
|
|
149
|
+
};
|
|
150
|
+
const progress = [...workflow.progress, entry];
|
|
151
|
+
const nextStep = workflow.currentStep + 1;
|
|
152
|
+
if (nextStep >= definition.steps.length) {
|
|
153
|
+
const invalid = validateOutput(definition, output);
|
|
154
|
+
if (invalid !== null) {
|
|
155
|
+
return fail(deps, now, workflow, "workflow_invalid_output", invalid);
|
|
156
|
+
}
|
|
157
|
+
await deps.store.update(workflow.id, guard(workflow), {
|
|
158
|
+
status: "succeeded",
|
|
159
|
+
progress,
|
|
160
|
+
currentStep: nextStep,
|
|
161
|
+
currentJobId: null,
|
|
162
|
+
attempts: 0,
|
|
163
|
+
output,
|
|
164
|
+
error: null,
|
|
165
|
+
finishedAt: now(),
|
|
166
|
+
});
|
|
167
|
+
return;
|
|
168
|
+
}
|
|
169
|
+
const updated = await deps.store.update(workflow.id, guard(workflow), {
|
|
170
|
+
status: "running",
|
|
171
|
+
progress,
|
|
172
|
+
currentStep: nextStep,
|
|
173
|
+
currentJobId: null,
|
|
174
|
+
attempts: 0,
|
|
175
|
+
});
|
|
176
|
+
if (updated !== null)
|
|
177
|
+
await dispatch(deps, now, updated, 1);
|
|
178
|
+
}
|
|
179
|
+
function validateOutput(definition, output) {
|
|
180
|
+
if (definition.output === undefined)
|
|
181
|
+
return null;
|
|
182
|
+
const parsed = definition.output.safeParse(output);
|
|
183
|
+
return parsed.success ? null : formatIssues(parsed.error.issues);
|
|
184
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import type { JobDefinition, JobJson, JobStatus } from "@facilis.dev/core";
|
|
2
|
+
import type { FacilisDb } from "@facilis.dev/db";
|
|
3
|
+
import type { JobCounts, JobEngine } from "../jobs/contracts.js";
|
|
4
|
+
import { createDbTaskStore } from "../tasks/db-store.js";
|
|
5
|
+
import { createDbWorkflowStore } from "./db-store.js";
|
|
6
|
+
/** Deployment tenant; a second tenant proves the RLS boundary cannot be crossed. */
|
|
7
|
+
export declare const TENANT_ID = "eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee";
|
|
8
|
+
export declare const OTHER_TENANT = "ffffffff-ffff-ffff-ffff-ffffffffffff";
|
|
9
|
+
export declare const BASE: Date;
|
|
10
|
+
export interface FakeJob {
|
|
11
|
+
id: string;
|
|
12
|
+
name: string;
|
|
13
|
+
status: JobStatus;
|
|
14
|
+
input: JobJson;
|
|
15
|
+
output: JobJson | null;
|
|
16
|
+
error: string | null;
|
|
17
|
+
attempts: number;
|
|
18
|
+
maxAttempts: number;
|
|
19
|
+
timeoutMs: number;
|
|
20
|
+
runAt: Date;
|
|
21
|
+
createdAt: Date;
|
|
22
|
+
startedAt: Date | null;
|
|
23
|
+
finishedAt: Date | null;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* The runner only needs enqueue/get/cancel from the queue; this fake lets a test decide when
|
|
27
|
+
* a step job succeeds, fails or disappears (boot recovery) without a real scheduler.
|
|
28
|
+
*/
|
|
29
|
+
export declare class FakeJobs implements JobEngine {
|
|
30
|
+
readonly jobs: Map<string, FakeJob>;
|
|
31
|
+
private sequence;
|
|
32
|
+
start(): Promise<void>;
|
|
33
|
+
stop(): Promise<void>;
|
|
34
|
+
enqueue(name: string, data: unknown): Promise<{
|
|
35
|
+
id: string;
|
|
36
|
+
}>;
|
|
37
|
+
get(id: string): Promise<FakeJob | null>;
|
|
38
|
+
list(): Promise<FakeJob[]>;
|
|
39
|
+
queue(): Promise<FakeJob[]>;
|
|
40
|
+
running(): Promise<FakeJob[]>;
|
|
41
|
+
cancel(id: string): Promise<boolean>;
|
|
42
|
+
stats(): Promise<JobCounts>;
|
|
43
|
+
scoped(): JobEngine;
|
|
44
|
+
/** The job row remains but settles as succeeded (what advance() reads on the next tick). */
|
|
45
|
+
succeed(id: string, output?: JobJson): void;
|
|
46
|
+
fail(id: string, error: string): void;
|
|
47
|
+
/** Boot recovery case: the queue lost the row entirely. */
|
|
48
|
+
forget(id: string): void;
|
|
49
|
+
/** A definition the runner validates a dangling step against. */
|
|
50
|
+
static definitions(...names: string[]): ReadonlyMap<string, JobDefinition<unknown, unknown>>;
|
|
51
|
+
lastEnqueuedName(): string | null;
|
|
52
|
+
get latest(): FakeJob | undefined;
|
|
53
|
+
private required;
|
|
54
|
+
}
|
|
55
|
+
export interface WorkflowsTestContext {
|
|
56
|
+
readonly db: FacilisDb;
|
|
57
|
+
readonly workflows: ReturnType<typeof createDbWorkflowStore>;
|
|
58
|
+
readonly tasks: ReturnType<typeof createDbTaskStore>;
|
|
59
|
+
readonly jobs: FakeJobs;
|
|
60
|
+
}
|
|
61
|
+
export declare function createWorkflowsTestContext(): Promise<WorkflowsTestContext>;
|
|
62
|
+
export declare function clearWorkflows(db: FacilisDb): Promise<void>;
|