@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,75 @@
|
|
|
1
|
+
import { createDbTaskStore, isTasksTableAvailable } from "../tasks/db-store.js";
|
|
2
|
+
import { createDbWorkflowStore, isWorkflowsTableAvailable } from "./db-store.js";
|
|
3
|
+
import { buildWorkflowRegistry } from "./definitions.js";
|
|
4
|
+
import { createWorkflowRunner } from "./runner.js";
|
|
5
|
+
/**
|
|
6
|
+
* Boots the workflow runtime (D-135, docs/WORKFLOWS.md §8).
|
|
7
|
+
*
|
|
8
|
+
* Never throws: without both tables (or without the job queue) the API is unavailable with a
|
|
9
|
+
* manifest warning, because a suspended chain needs durable rows and jobs (there is
|
|
10
|
+
* deliberately no in-memory mode). The returned runtime is carried by BootstrapState and
|
|
11
|
+
* exposed as ctx.workflows.
|
|
12
|
+
*/
|
|
13
|
+
export async function bootWorkflows(options) {
|
|
14
|
+
const { db, tenantId, modules, jobs, jobsConfig, workflowsConfig, warnings } = options;
|
|
15
|
+
if (!workflowsConfig.persist) {
|
|
16
|
+
warnings.push({
|
|
17
|
+
code: "workflows_disabled",
|
|
18
|
+
message: "workflows.persist is false; workflows are disabled (rows are the contract).",
|
|
19
|
+
});
|
|
20
|
+
return null;
|
|
21
|
+
}
|
|
22
|
+
if (jobs === null) {
|
|
23
|
+
warnings.push({
|
|
24
|
+
code: "workflows_disabled",
|
|
25
|
+
message: "Background jobs are unavailable; workflows are disabled.",
|
|
26
|
+
});
|
|
27
|
+
return null;
|
|
28
|
+
}
|
|
29
|
+
try {
|
|
30
|
+
if (!(await isWorkflowsTableAvailable(db)) || !(await isTasksTableAvailable(db))) {
|
|
31
|
+
warnings.push({
|
|
32
|
+
code: "workflows_table_missing",
|
|
33
|
+
message: "facilis_workflows or facilis_tasks is missing; workflows are disabled. Re-export the tables from db/schema.ts and apply the framework migration.",
|
|
34
|
+
});
|
|
35
|
+
return null;
|
|
36
|
+
}
|
|
37
|
+
const registry = buildWorkflowRegistry(modules, jobs.definitions);
|
|
38
|
+
warnings.push(...registry.warnings);
|
|
39
|
+
// One warning per failing context is enough: a broken store would otherwise flood the
|
|
40
|
+
// manifest on every tick.
|
|
41
|
+
const reportedErrors = new Set();
|
|
42
|
+
const taskStore = createDbTaskStore({ db, tenantId });
|
|
43
|
+
const runner = createWorkflowRunner({
|
|
44
|
+
db,
|
|
45
|
+
tenantId,
|
|
46
|
+
definitions: registry.definitions,
|
|
47
|
+
store: createDbWorkflowStore({ db, tenantId }),
|
|
48
|
+
tasks: taskStore,
|
|
49
|
+
jobs: jobs.engine,
|
|
50
|
+
config: workflowsConfig,
|
|
51
|
+
maxStepAttempts: jobsConfig.maxAttempts,
|
|
52
|
+
onError: (error, context) => {
|
|
53
|
+
if (reportedErrors.has(context))
|
|
54
|
+
return;
|
|
55
|
+
reportedErrors.add(context);
|
|
56
|
+
warnings.push({
|
|
57
|
+
code: "workflow_runtime_error",
|
|
58
|
+
message: "Workflow runner error (" + context + "): " + describe(error),
|
|
59
|
+
});
|
|
60
|
+
},
|
|
61
|
+
});
|
|
62
|
+
await runner.start();
|
|
63
|
+
return runner;
|
|
64
|
+
}
|
|
65
|
+
catch (error) {
|
|
66
|
+
warnings.push({
|
|
67
|
+
code: "workflows_boot_failed",
|
|
68
|
+
message: "Workflows are disabled: " + describe(error),
|
|
69
|
+
});
|
|
70
|
+
return null;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
function describe(error) {
|
|
74
|
+
return error instanceof Error ? error.message : String(error);
|
|
75
|
+
}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import type { FacilisDb, PolicyScopedDatabase } from "@facilis.dev/db";
|
|
2
|
+
import type { FacilisWorkflowsConfig, JobJson, WorkflowDefinition, WorkflowProgressEntry, WorkflowStatus, WorkflowStepIdentity } from "@facilis.dev/core";
|
|
3
|
+
import type { JobEngine, JobTimers } from "../jobs/contracts.js";
|
|
4
|
+
import type { TaskStore } from "../tasks/contracts.js";
|
|
5
|
+
/** One workflow row as the store knows it: JSON data plus real Dates (the API ISO-izes them). */
|
|
6
|
+
export interface StoredWorkflow {
|
|
7
|
+
readonly id: string;
|
|
8
|
+
readonly name: string;
|
|
9
|
+
readonly status: WorkflowStatus;
|
|
10
|
+
readonly input: JobJson;
|
|
11
|
+
readonly progress: readonly WorkflowProgressEntry[];
|
|
12
|
+
readonly plan: readonly WorkflowStepIdentity[];
|
|
13
|
+
readonly currentStep: number;
|
|
14
|
+
readonly currentJobId: string | null;
|
|
15
|
+
readonly waitingTaskId: string | null;
|
|
16
|
+
readonly attempts: number;
|
|
17
|
+
readonly output: JobJson | null;
|
|
18
|
+
readonly error: string | null;
|
|
19
|
+
readonly startedAt: Date;
|
|
20
|
+
readonly finishedAt: Date | null;
|
|
21
|
+
readonly createdAt: Date;
|
|
22
|
+
}
|
|
23
|
+
/** What `start` writes; status/attempts belong to the runtime, not the caller. */
|
|
24
|
+
export interface NewStoredWorkflow {
|
|
25
|
+
readonly id: string;
|
|
26
|
+
readonly name: string;
|
|
27
|
+
readonly input: JobJson;
|
|
28
|
+
readonly plan: readonly WorkflowStepIdentity[];
|
|
29
|
+
readonly startedAt: Date;
|
|
30
|
+
readonly createdAt: Date;
|
|
31
|
+
}
|
|
32
|
+
export interface WorkflowListFilters {
|
|
33
|
+
readonly status?: WorkflowStatus | readonly WorkflowStatus[];
|
|
34
|
+
readonly name?: string;
|
|
35
|
+
/** Already normalised by the API (default 50, max 200). */
|
|
36
|
+
readonly limit: number;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Expected current values for one compare-and-set write. Every present field is an AND
|
|
40
|
+
* condition on the UPDATE, so a transition that lost a race changes nothing.
|
|
41
|
+
*/
|
|
42
|
+
export interface WorkflowGuard {
|
|
43
|
+
readonly status: WorkflowStatus;
|
|
44
|
+
readonly currentStep?: number;
|
|
45
|
+
readonly currentJobId?: string | null;
|
|
46
|
+
readonly waitingTaskId?: string | null;
|
|
47
|
+
}
|
|
48
|
+
/** The fields a transition may change; absent fields keep their row value. */
|
|
49
|
+
export interface WorkflowPatch {
|
|
50
|
+
readonly status?: WorkflowStatus;
|
|
51
|
+
readonly progress?: readonly WorkflowProgressEntry[];
|
|
52
|
+
readonly currentStep?: number;
|
|
53
|
+
readonly currentJobId?: string | null;
|
|
54
|
+
readonly waitingTaskId?: string | null;
|
|
55
|
+
readonly attempts?: number;
|
|
56
|
+
readonly output?: JobJson | null;
|
|
57
|
+
readonly error?: string | null;
|
|
58
|
+
readonly finishedAt?: Date | null;
|
|
59
|
+
}
|
|
60
|
+
export interface WorkflowStore {
|
|
61
|
+
insert(workflow: NewStoredWorkflow): Promise<void>;
|
|
62
|
+
get(id: string): Promise<StoredWorkflow | null>;
|
|
63
|
+
list(filters: WorkflowListFilters): Promise<StoredWorkflow[]>;
|
|
64
|
+
/** CAS update; null when the current row no longer matches the guard. */
|
|
65
|
+
update(id: string, guard: WorkflowGuard, patch: WorkflowPatch): Promise<StoredWorkflow | null>;
|
|
66
|
+
/**
|
|
67
|
+
* Optional view whose operations join the request's policy transaction instead of opening
|
|
68
|
+
* a new one: PGlite is single-connection, so a nested BEGIN would deadlock (JOBS §8).
|
|
69
|
+
*/
|
|
70
|
+
scoped?(scope: PolicyScopedDatabase): WorkflowStore;
|
|
71
|
+
}
|
|
72
|
+
/** One scanned definition module: virtual module entry, useful for warning messages. */
|
|
73
|
+
export interface WorkflowModule {
|
|
74
|
+
readonly file: string;
|
|
75
|
+
readonly definition: unknown;
|
|
76
|
+
}
|
|
77
|
+
/** Everything the API and the runner share; the runner is the only writer of transitions. */
|
|
78
|
+
export interface WorkflowRuntimeDeps {
|
|
79
|
+
readonly db: FacilisDb;
|
|
80
|
+
readonly tenantId: string;
|
|
81
|
+
readonly definitions: ReadonlyMap<string, WorkflowDefinition<unknown, unknown>>;
|
|
82
|
+
/** Base store; a bound API view swaps in `store.scoped(scope)`. */
|
|
83
|
+
readonly store: WorkflowStore;
|
|
84
|
+
readonly tasks: TaskStore;
|
|
85
|
+
/** The job engine: step dispatch enqueues through it, possibly inside the runner's transaction. */
|
|
86
|
+
readonly jobs: JobEngine;
|
|
87
|
+
readonly config: FacilisWorkflowsConfig;
|
|
88
|
+
/** Step dispatches of one step allowed before the chain fails (`jobs.maxAttempts`). */
|
|
89
|
+
readonly maxStepAttempts: number;
|
|
90
|
+
/** Defaults to the process clock. */
|
|
91
|
+
readonly now?: () => Date;
|
|
92
|
+
/** Defaults to the process timers; tests inject a deterministic ticker. */
|
|
93
|
+
readonly timers?: JobTimers;
|
|
94
|
+
/** Receives unexpected runner failures (a store write failing in the tick). */
|
|
95
|
+
readonly onError?: (error: unknown, context: string) => void;
|
|
96
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { FacilisDb, PolicyScopedDatabase } from "@facilis.dev/db";
|
|
2
|
+
import type { WorkflowStore } from "./contracts.js";
|
|
3
|
+
/**
|
|
4
|
+
* The persistent WorkflowStore over facilis_workflows. A missing table is not handled here:
|
|
5
|
+
* boot probes it with isWorkflowsTableAvailable and disables the API instead (D-135: no
|
|
6
|
+
* in-memory mode), so these methods may throw when the project is not migrated.
|
|
7
|
+
*/
|
|
8
|
+
export declare function createDbWorkflowStore(options: {
|
|
9
|
+
readonly db: FacilisDb;
|
|
10
|
+
readonly tenantId: string;
|
|
11
|
+
/** Request transaction to join (from WorkflowStore.scoped); absent for runner-owned work. */
|
|
12
|
+
readonly scope?: PolicyScopedDatabase;
|
|
13
|
+
}): WorkflowStore;
|
|
14
|
+
/**
|
|
15
|
+
* Probe used by boot: to_regclass answers null for a missing table instead of raising, which
|
|
16
|
+
* is exactly the "project not migrated yet" case (D-135).
|
|
17
|
+
*/
|
|
18
|
+
export declare function isWorkflowsTableAvailable(db: FacilisDb): Promise<boolean>;
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
// The Drizzle-backed workflow store (D-135, docs/WORKFLOWS.md §5-§8).
|
|
2
|
+
//
|
|
3
|
+
// Every operation runs through runWithPolicyScope, i.e. as facilis_app with app.tenant_id set:
|
|
4
|
+
// a new row's tenant_id comes from the tenantColumn default (the same GUC the restrictive
|
|
5
|
+
// policy reads), and a query cannot reach another tenant's chains. The runner's transitions
|
|
6
|
+
// are compare-and-set UPDATEs, so a transition that lost a race changes nothing.
|
|
7
|
+
import { and, asc, eq, inArray, isNull, sql } from "drizzle-orm";
|
|
8
|
+
import { facilisWorkflows, runWithPolicyScope } from "@facilis.dev/db";
|
|
9
|
+
import { toStoredWorkflow } from "./row-mapping.js";
|
|
10
|
+
/**
|
|
11
|
+
* The persistent WorkflowStore over facilis_workflows. A missing table is not handled here:
|
|
12
|
+
* boot probes it with isWorkflowsTableAvailable and disables the API instead (D-135: no
|
|
13
|
+
* in-memory mode), so these methods may throw when the project is not migrated.
|
|
14
|
+
*/
|
|
15
|
+
export function createDbWorkflowStore(options) {
|
|
16
|
+
const { db, tenantId, scope } = options;
|
|
17
|
+
function run(fn) {
|
|
18
|
+
return scope === undefined ? runWithPolicyScope(db, { tenantId }, fn) : fn(scope);
|
|
19
|
+
}
|
|
20
|
+
return {
|
|
21
|
+
async insert(workflow) {
|
|
22
|
+
await run((tx) => tx.insert(facilisWorkflows).values({
|
|
23
|
+
id: workflow.id,
|
|
24
|
+
name: workflow.name,
|
|
25
|
+
status: "running",
|
|
26
|
+
input: workflow.input,
|
|
27
|
+
progress: [],
|
|
28
|
+
plan: workflow.plan,
|
|
29
|
+
currentStep: 0,
|
|
30
|
+
attempts: 0,
|
|
31
|
+
startedAt: workflow.startedAt,
|
|
32
|
+
createdAt: workflow.createdAt,
|
|
33
|
+
}));
|
|
34
|
+
},
|
|
35
|
+
async get(id) {
|
|
36
|
+
return run(async (tx) => {
|
|
37
|
+
const rows = await tx
|
|
38
|
+
.select()
|
|
39
|
+
.from(facilisWorkflows)
|
|
40
|
+
.where(eq(facilisWorkflows.id, id))
|
|
41
|
+
.limit(1);
|
|
42
|
+
const row = rows[0];
|
|
43
|
+
return row === undefined ? null : toStoredWorkflow(row);
|
|
44
|
+
});
|
|
45
|
+
},
|
|
46
|
+
async list(filters) {
|
|
47
|
+
return run(async (tx) => {
|
|
48
|
+
const conditions = [];
|
|
49
|
+
if (filters.status !== undefined) {
|
|
50
|
+
conditions.push(typeof filters.status === "string"
|
|
51
|
+
? eq(facilisWorkflows.status, filters.status)
|
|
52
|
+
: inArray(facilisWorkflows.status, [...filters.status]));
|
|
53
|
+
}
|
|
54
|
+
if (filters.name !== undefined)
|
|
55
|
+
conditions.push(eq(facilisWorkflows.name, filters.name));
|
|
56
|
+
const rows = await tx
|
|
57
|
+
.select()
|
|
58
|
+
.from(facilisWorkflows)
|
|
59
|
+
.where(conditions.length === 0 ? undefined : and(...conditions))
|
|
60
|
+
// Chain order: the tick advances the oldest active run first.
|
|
61
|
+
.orderBy(asc(facilisWorkflows.createdAt))
|
|
62
|
+
.limit(filters.limit);
|
|
63
|
+
return rows.map(toStoredWorkflow);
|
|
64
|
+
});
|
|
65
|
+
},
|
|
66
|
+
async update(id, guard, patch) {
|
|
67
|
+
const values = {};
|
|
68
|
+
if (patch.status !== undefined)
|
|
69
|
+
values.status = patch.status;
|
|
70
|
+
if (patch.progress !== undefined)
|
|
71
|
+
values.progress = [...patch.progress];
|
|
72
|
+
if (patch.currentStep !== undefined)
|
|
73
|
+
values.currentStep = patch.currentStep;
|
|
74
|
+
if (patch.currentJobId !== undefined)
|
|
75
|
+
values.currentJobId = patch.currentJobId;
|
|
76
|
+
if (patch.waitingTaskId !== undefined)
|
|
77
|
+
values.waitingTaskId = patch.waitingTaskId;
|
|
78
|
+
if (patch.attempts !== undefined)
|
|
79
|
+
values.attempts = patch.attempts;
|
|
80
|
+
if (patch.output !== undefined)
|
|
81
|
+
values.output = patch.output;
|
|
82
|
+
if (patch.error !== undefined)
|
|
83
|
+
values.error = patch.error;
|
|
84
|
+
if (patch.finishedAt !== undefined)
|
|
85
|
+
values.finishedAt = patch.finishedAt;
|
|
86
|
+
if (Object.keys(values).length === 0)
|
|
87
|
+
throw new Error("workflow update has no fields");
|
|
88
|
+
return run(async (tx) => {
|
|
89
|
+
const conditions = [
|
|
90
|
+
eq(facilisWorkflows.id, id),
|
|
91
|
+
eq(facilisWorkflows.status, guard.status),
|
|
92
|
+
];
|
|
93
|
+
if (guard.currentStep !== undefined) {
|
|
94
|
+
conditions.push(eq(facilisWorkflows.currentStep, guard.currentStep));
|
|
95
|
+
}
|
|
96
|
+
if (guard.currentJobId !== undefined) {
|
|
97
|
+
conditions.push(guard.currentJobId === null
|
|
98
|
+
? isNull(facilisWorkflows.currentJobId)
|
|
99
|
+
: eq(facilisWorkflows.currentJobId, guard.currentJobId));
|
|
100
|
+
}
|
|
101
|
+
if (guard.waitingTaskId !== undefined) {
|
|
102
|
+
conditions.push(guard.waitingTaskId === null
|
|
103
|
+
? isNull(facilisWorkflows.waitingTaskId)
|
|
104
|
+
: eq(facilisWorkflows.waitingTaskId, guard.waitingTaskId));
|
|
105
|
+
}
|
|
106
|
+
const rows = await tx
|
|
107
|
+
.update(facilisWorkflows)
|
|
108
|
+
.set(values)
|
|
109
|
+
.where(and(...conditions))
|
|
110
|
+
.returning();
|
|
111
|
+
const row = rows[0];
|
|
112
|
+
return row === undefined ? null : toStoredWorkflow(row);
|
|
113
|
+
});
|
|
114
|
+
},
|
|
115
|
+
/** Joins workflow operations to an existing transaction (see run above). */
|
|
116
|
+
scoped(next) {
|
|
117
|
+
return createDbWorkflowStore({ db, tenantId, scope: next });
|
|
118
|
+
},
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* Probe used by boot: to_regclass answers null for a missing table instead of raising, which
|
|
123
|
+
* is exactly the "project not migrated yet" case (D-135).
|
|
124
|
+
*/
|
|
125
|
+
export async function isWorkflowsTableAvailable(db) {
|
|
126
|
+
const result = await db.db.execute(sql `select to_regclass('public.facilis_workflows') is not null as available`);
|
|
127
|
+
return result.rows[0]?.["available"] === true;
|
|
128
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { type JobDefinition, type ManifestWarning, type WorkflowDefinition } from "@facilis.dev/core";
|
|
2
|
+
import type { WorkflowModule } from "./contracts.js";
|
|
3
|
+
/** The project's workflow definitions plus the manifest warnings raised while indexing them. */
|
|
4
|
+
export interface WorkflowRegistry {
|
|
5
|
+
readonly definitions: ReadonlyMap<string, WorkflowDefinition<unknown, unknown>>;
|
|
6
|
+
readonly warnings: ManifestWarning[];
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Indexes the modules behind `#facilis/workflows` (docs/WORKFLOWS.md §6).
|
|
10
|
+
*
|
|
11
|
+
* An invalid, duplicate or dangling definition must never break boot: it becomes a manifest
|
|
12
|
+
* warning and the module is skipped (jobs behaviour, docs/JOBS.md §5).
|
|
13
|
+
*/
|
|
14
|
+
export declare function buildWorkflowRegistry(modules: readonly WorkflowModule[], jobs: ReadonlyMap<string, JobDefinition<unknown, unknown>>): WorkflowRegistry;
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { isWorkflowDefinition, } from "@facilis.dev/core";
|
|
2
|
+
/**
|
|
3
|
+
* Indexes the modules behind `#facilis/workflows` (docs/WORKFLOWS.md §6).
|
|
4
|
+
*
|
|
5
|
+
* An invalid, duplicate or dangling definition must never break boot: it becomes a manifest
|
|
6
|
+
* warning and the module is skipped (jobs behaviour, docs/JOBS.md §5).
|
|
7
|
+
*/
|
|
8
|
+
export function buildWorkflowRegistry(modules, jobs) {
|
|
9
|
+
const definitions = new Map();
|
|
10
|
+
const warnings = [];
|
|
11
|
+
for (const module of modules) {
|
|
12
|
+
if (!isWorkflowDefinition(module.definition)) {
|
|
13
|
+
warnings.push({
|
|
14
|
+
code: "workflow_definition_invalid",
|
|
15
|
+
message: `${module.file} must default-export defineWorkflow({...}); the module was skipped.`,
|
|
16
|
+
sourceFile: module.file,
|
|
17
|
+
});
|
|
18
|
+
continue;
|
|
19
|
+
}
|
|
20
|
+
if (definitions.has(module.definition.name)) {
|
|
21
|
+
warnings.push({
|
|
22
|
+
code: "workflow_definition_invalid",
|
|
23
|
+
message: `Duplicate workflow "${module.definition.name}" in ${module.file}; the first definition wins.`,
|
|
24
|
+
sourceFile: module.file,
|
|
25
|
+
});
|
|
26
|
+
continue;
|
|
27
|
+
}
|
|
28
|
+
const dangling = danglingJob(module.definition, jobs);
|
|
29
|
+
if (dangling !== null) {
|
|
30
|
+
warnings.push({
|
|
31
|
+
code: "workflow_definition_invalid",
|
|
32
|
+
message: `${module.file}: step references unknown job "${dangling}"; the workflow was skipped.`,
|
|
33
|
+
sourceFile: module.file,
|
|
34
|
+
});
|
|
35
|
+
continue;
|
|
36
|
+
}
|
|
37
|
+
// The registry is deliberately input-erased (a project mixes definitions with different
|
|
38
|
+
// inputs); the resolver context is reconstructed from the row at dispatch time (§6).
|
|
39
|
+
definitions.set(module.definition.name, module.definition);
|
|
40
|
+
}
|
|
41
|
+
return { definitions, warnings };
|
|
42
|
+
}
|
|
43
|
+
/** First job step whose name is not in the job registry; null when every step resolves. */
|
|
44
|
+
function danglingJob(definition, jobs) {
|
|
45
|
+
for (const step of definition.steps) {
|
|
46
|
+
if ("job" in step && !jobs.has(step.job))
|
|
47
|
+
return step.job;
|
|
48
|
+
}
|
|
49
|
+
return null;
|
|
50
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { StoredWorkflow, WorkflowRuntimeDeps } from "./contracts.js";
|
|
2
|
+
import { type Now } from "./support.js";
|
|
3
|
+
/** Dispatches the current step: enqueue its job or request its approval (§8.4). */
|
|
4
|
+
export declare function dispatch(deps: WorkflowRuntimeDeps, now: Now, workflow: StoredWorkflow, attempts: number): Promise<void>;
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
// Step dispatch: the two side effects a chain can hand off (D-135, WORKFLOWS.md §8.4).
|
|
2
|
+
//
|
|
3
|
+
// A job step enqueues its job in the same transaction as the workflow update, and an approval
|
|
4
|
+
// step inserts its task in the same transaction as the waiting transition: either both sides
|
|
5
|
+
// of the hand-off exist or neither does.
|
|
6
|
+
import { randomUUID } from "node:crypto";
|
|
7
|
+
import { runWithPolicyScope } from "@facilis.dev/db";
|
|
8
|
+
import { normalizeTitleParams, planMatches, resolveContext } from "./steps.js";
|
|
9
|
+
import { CasLost, describe, fail, guard, lastOutput } from "./support.js";
|
|
10
|
+
/** Dispatches the current step: enqueue its job or request its approval (§8.4). */
|
|
11
|
+
export async function dispatch(deps, now, workflow, attempts) {
|
|
12
|
+
const definition = deps.definitions.get(workflow.name);
|
|
13
|
+
if (definition === undefined) {
|
|
14
|
+
return fail(deps, now, workflow, "workflow_definition_changed", 'Workflow "' + workflow.name + '" is no longer defined.');
|
|
15
|
+
}
|
|
16
|
+
const index = workflow.currentStep;
|
|
17
|
+
if (index >= definition.steps.length) {
|
|
18
|
+
await deps.store.update(workflow.id, guard(workflow), {
|
|
19
|
+
status: "succeeded",
|
|
20
|
+
currentStep: index,
|
|
21
|
+
currentJobId: null,
|
|
22
|
+
attempts: 0,
|
|
23
|
+
output: lastOutput(workflow.progress, index - 1),
|
|
24
|
+
error: null,
|
|
25
|
+
finishedAt: now(),
|
|
26
|
+
});
|
|
27
|
+
return;
|
|
28
|
+
}
|
|
29
|
+
if (!planMatches(workflow.plan, definition, index)) {
|
|
30
|
+
return fail(deps, now, workflow, "workflow_definition_changed", "Step " + index + " changed since the run started.");
|
|
31
|
+
}
|
|
32
|
+
const step = definition.steps[index];
|
|
33
|
+
if (step === undefined)
|
|
34
|
+
return;
|
|
35
|
+
const context = resolveContext(workflow.input, workflow.progress, index);
|
|
36
|
+
if ("job" in step) {
|
|
37
|
+
return dispatchJob(deps, now, workflow, step, context, attempts);
|
|
38
|
+
}
|
|
39
|
+
return dispatchApproval(deps, now, workflow, step, index, context);
|
|
40
|
+
}
|
|
41
|
+
/** Resolves, enqueues and records one job step inside a single transaction. */
|
|
42
|
+
async function dispatchJob(deps, now, workflow, step, context, attempts) {
|
|
43
|
+
let data;
|
|
44
|
+
try {
|
|
45
|
+
// No resolver means "the chain input is this job's input": the common first-step case.
|
|
46
|
+
data = step.input === undefined ? workflow.input : step.input(context);
|
|
47
|
+
}
|
|
48
|
+
catch (error) {
|
|
49
|
+
await fail(deps, now, workflow, "workflow_step_failed", describe(error));
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
try {
|
|
53
|
+
await runWithPolicyScope(deps.db, { tenantId: deps.tenantId }, async (tx) => {
|
|
54
|
+
const store = deps.store.scoped?.(tx) ?? deps.store;
|
|
55
|
+
const jobs = deps.jobs.scoped?.(tx) ?? deps.jobs;
|
|
56
|
+
const { id: jobId } = await jobs.enqueue(step.job, data);
|
|
57
|
+
const updated = await store.update(workflow.id, guard(workflow), {
|
|
58
|
+
status: "running",
|
|
59
|
+
currentJobId: jobId,
|
|
60
|
+
attempts,
|
|
61
|
+
});
|
|
62
|
+
if (updated === null)
|
|
63
|
+
throw new CasLost();
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
catch (error) {
|
|
67
|
+
if (error instanceof CasLost)
|
|
68
|
+
return;
|
|
69
|
+
await fail(deps, now, workflow, "workflow_step_failed", describe(error));
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
/** Inserts the approval task and suspends the chain on it inside a single transaction. */
|
|
73
|
+
async function dispatchApproval(deps, now, workflow, step, index, context) {
|
|
74
|
+
const approval = step.approval;
|
|
75
|
+
let params;
|
|
76
|
+
try {
|
|
77
|
+
params = normalizeTitleParams(approval.params === undefined ? {} : approval.params(context));
|
|
78
|
+
}
|
|
79
|
+
catch (error) {
|
|
80
|
+
await fail(deps, now, workflow, "workflow_step_failed", describe(error));
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
const ttl = approval.ttlMs ?? deps.config.defaultTaskTtlMs;
|
|
84
|
+
const taskId = randomUUID();
|
|
85
|
+
const createdAt = now();
|
|
86
|
+
const expiresAt = ttl === null ? null : new Date(createdAt.getTime() + ttl);
|
|
87
|
+
try {
|
|
88
|
+
await runWithPolicyScope(deps.db, { tenantId: deps.tenantId }, async (tx) => {
|
|
89
|
+
const store = deps.store.scoped?.(tx) ?? deps.store;
|
|
90
|
+
const tasks = deps.tasks.scoped?.(tx) ?? deps.tasks;
|
|
91
|
+
await tasks.insert({
|
|
92
|
+
id: taskId,
|
|
93
|
+
workflowId: workflow.id,
|
|
94
|
+
stepIndex: index,
|
|
95
|
+
kind: "approval",
|
|
96
|
+
titleKey: approval.titleKey,
|
|
97
|
+
titleParams: params,
|
|
98
|
+
// The decider sees the chain input; the params are only the rendered title.
|
|
99
|
+
payload: workflow.input,
|
|
100
|
+
requestedBy: "system:workflow:" + workflow.name,
|
|
101
|
+
assignedPermission: approval.permission ?? null,
|
|
102
|
+
expiresAt,
|
|
103
|
+
createdAt,
|
|
104
|
+
});
|
|
105
|
+
const updated = await store.update(workflow.id, guard(workflow), {
|
|
106
|
+
status: "waiting",
|
|
107
|
+
waitingTaskId: taskId,
|
|
108
|
+
attempts: 0,
|
|
109
|
+
});
|
|
110
|
+
if (updated === null)
|
|
111
|
+
throw new CasLost();
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
catch (error) {
|
|
115
|
+
if (error instanceof CasLost)
|
|
116
|
+
return;
|
|
117
|
+
await fail(deps, now, workflow, "workflow_step_failed", describe(error));
|
|
118
|
+
}
|
|
119
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { WorkflowRecord } from "@facilis.dev/core";
|
|
2
|
+
import type { FacilisWorkflowRow } from "@facilis.dev/db";
|
|
3
|
+
import type { StoredWorkflow } from "./contracts.js";
|
|
4
|
+
export declare function toStoredWorkflow(row: FacilisWorkflowRow): StoredWorkflow;
|
|
5
|
+
export declare function toWorkflowRecord(workflow: StoredWorkflow): WorkflowRecord;
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
export function toStoredWorkflow(row) {
|
|
2
|
+
return {
|
|
3
|
+
id: row.id,
|
|
4
|
+
name: row.name,
|
|
5
|
+
status: row.status,
|
|
6
|
+
input: row.input,
|
|
7
|
+
// JSONB comes back as parsed JSON; the plan/progress contracts are enforced on write.
|
|
8
|
+
progress: Array.isArray(row.progress) ? row.progress : [],
|
|
9
|
+
plan: Array.isArray(row.plan) ? row.plan : [],
|
|
10
|
+
currentStep: row.currentStep,
|
|
11
|
+
currentJobId: row.currentJobId,
|
|
12
|
+
waitingTaskId: row.waitingTaskId,
|
|
13
|
+
attempts: row.attempts,
|
|
14
|
+
output: row.output ?? null,
|
|
15
|
+
error: row.error,
|
|
16
|
+
startedAt: row.startedAt,
|
|
17
|
+
finishedAt: row.finishedAt,
|
|
18
|
+
createdAt: row.createdAt,
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
export function toWorkflowRecord(workflow) {
|
|
22
|
+
return {
|
|
23
|
+
id: workflow.id,
|
|
24
|
+
name: workflow.name,
|
|
25
|
+
status: workflow.status,
|
|
26
|
+
input: workflow.input,
|
|
27
|
+
progress: workflow.progress,
|
|
28
|
+
currentStep: workflow.currentStep,
|
|
29
|
+
currentJobId: workflow.currentJobId,
|
|
30
|
+
waitingTaskId: workflow.waitingTaskId,
|
|
31
|
+
attempts: workflow.attempts,
|
|
32
|
+
output: workflow.output,
|
|
33
|
+
error: workflow.error,
|
|
34
|
+
startedAt: workflow.startedAt.toISOString(),
|
|
35
|
+
finishedAt: workflow.finishedAt === null ? null : workflow.finishedAt.toISOString(),
|
|
36
|
+
createdAt: workflow.createdAt.toISOString(),
|
|
37
|
+
};
|
|
38
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { WorkflowsApi } from "@facilis.dev/core";
|
|
2
|
+
import type { WorkflowRuntimeDeps } from "./contracts.js";
|
|
3
|
+
/** The booted workflow runtime carried by BootstrapState (D-135). */
|
|
4
|
+
export interface WorkflowsRuntime {
|
|
5
|
+
readonly api: WorkflowsApi;
|
|
6
|
+
start(): Promise<void>;
|
|
7
|
+
stop(): Promise<void>;
|
|
8
|
+
/** One tick; exposed for boot recovery and deterministic tests. */
|
|
9
|
+
tick(): Promise<void>;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Builds the runner around the shared deps: the API reads/writes rows, the tick advances
|
|
13
|
+
* chains, and the job engine is only used for step dispatch, status and cancellation.
|
|
14
|
+
*/
|
|
15
|
+
export declare function createWorkflowRunner(deps: WorkflowRuntimeDeps): WorkflowsRuntime;
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { SYSTEM_TIMERS } from "../jobs/engine-support.js";
|
|
2
|
+
import { createWorkflowsApi } from "./runtime.js";
|
|
3
|
+
import { expireDueTasks, stepWorkflow, TICK_BATCH } from "./transitions.js";
|
|
4
|
+
/**
|
|
5
|
+
* Builds the runner around the shared deps: the API reads/writes rows, the tick advances
|
|
6
|
+
* chains, and the job engine is only used for step dispatch, status and cancellation.
|
|
7
|
+
*/
|
|
8
|
+
export function createWorkflowRunner(deps) {
|
|
9
|
+
const timers = deps.timers ?? SYSTEM_TIMERS;
|
|
10
|
+
const now = () => new Date(timers.now());
|
|
11
|
+
const report = (error, context) => deps.onError?.(error, context);
|
|
12
|
+
let started = false;
|
|
13
|
+
let stopping = false;
|
|
14
|
+
let tickRunning = false;
|
|
15
|
+
let wakeRequested = false;
|
|
16
|
+
let timer = null;
|
|
17
|
+
function scheduleTick(delayMs) {
|
|
18
|
+
if (!started || stopping)
|
|
19
|
+
return;
|
|
20
|
+
if (timer !== null)
|
|
21
|
+
timers.clearTimeout(timer);
|
|
22
|
+
timer = timers.setTimeout(() => {
|
|
23
|
+
timer = null;
|
|
24
|
+
void tick().catch(() => undefined);
|
|
25
|
+
}, delayMs);
|
|
26
|
+
}
|
|
27
|
+
/** A start/decision asks for an immediate tick; a running tick defers to it. */
|
|
28
|
+
function requestTick() {
|
|
29
|
+
if (!started || stopping)
|
|
30
|
+
return;
|
|
31
|
+
if (tickRunning) {
|
|
32
|
+
wakeRequested = true;
|
|
33
|
+
return;
|
|
34
|
+
}
|
|
35
|
+
scheduleTick(0);
|
|
36
|
+
}
|
|
37
|
+
async function tick() {
|
|
38
|
+
if (stopping || tickRunning)
|
|
39
|
+
return;
|
|
40
|
+
tickRunning = true;
|
|
41
|
+
try {
|
|
42
|
+
await expireDueTasks(deps, now);
|
|
43
|
+
const active = await deps.store.list({ status: ["running", "waiting"], limit: TICK_BATCH });
|
|
44
|
+
for (const workflow of active) {
|
|
45
|
+
try {
|
|
46
|
+
await stepWorkflow(deps, now, workflow);
|
|
47
|
+
}
|
|
48
|
+
catch (error) {
|
|
49
|
+
// One broken row must not stall the others; the next tick retries it.
|
|
50
|
+
report(error, "runner:" + workflow.id);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
catch (error) {
|
|
55
|
+
report(error, "runner.tick");
|
|
56
|
+
}
|
|
57
|
+
finally {
|
|
58
|
+
tickRunning = false;
|
|
59
|
+
if (started && !stopping) {
|
|
60
|
+
const immediate = wakeRequested;
|
|
61
|
+
wakeRequested = false;
|
|
62
|
+
scheduleTick(immediate ? 0 : deps.config.tickIntervalMs);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
const api = createWorkflowsApi(deps, requestTick);
|
|
67
|
+
return {
|
|
68
|
+
api,
|
|
69
|
+
async start() {
|
|
70
|
+
if (started || stopping)
|
|
71
|
+
return;
|
|
72
|
+
started = true;
|
|
73
|
+
// The first tick is the boot recovery: it reconciles rows a reload left behind.
|
|
74
|
+
scheduleTick(0);
|
|
75
|
+
},
|
|
76
|
+
async stop() {
|
|
77
|
+
if (!started && timer === null)
|
|
78
|
+
return;
|
|
79
|
+
stopping = true;
|
|
80
|
+
started = false;
|
|
81
|
+
if (timer !== null) {
|
|
82
|
+
timers.clearTimeout(timer);
|
|
83
|
+
timer = null;
|
|
84
|
+
}
|
|
85
|
+
wakeRequested = false;
|
|
86
|
+
},
|
|
87
|
+
tick,
|
|
88
|
+
};
|
|
89
|
+
}
|