@facilis.dev/nitro 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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,74 @@
|
|
|
1
|
+
// Step helpers shared by the API and the runner (D-135, docs/WORKFLOWS.md §6-§8).
|
|
2
|
+
import type {
|
|
3
|
+
JobJson,
|
|
4
|
+
WorkflowDefinition,
|
|
5
|
+
WorkflowProgressEntry,
|
|
6
|
+
WorkflowResolveContext,
|
|
7
|
+
WorkflowStep,
|
|
8
|
+
WorkflowStepIdentity,
|
|
9
|
+
} from "@facilis.dev/core";
|
|
10
|
+
import { WorkflowError } from "@facilis.dev/core";
|
|
11
|
+
|
|
12
|
+
/** The plan-snapshot identity of a step: kind plus the name a resume compares against. */
|
|
13
|
+
export function stepIdentity(step: WorkflowStep, index: number): WorkflowStepIdentity {
|
|
14
|
+
return "job" in step
|
|
15
|
+
? { index, kind: "job", name: step.job }
|
|
16
|
+
: { index, kind: "approval", name: step.approval.titleKey };
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** True when the stored plan still describes the definition's step at `index`. */
|
|
20
|
+
export function planMatches(
|
|
21
|
+
plan: readonly WorkflowStepIdentity[],
|
|
22
|
+
definition: WorkflowDefinition,
|
|
23
|
+
index: number,
|
|
24
|
+
): boolean {
|
|
25
|
+
const step = definition.steps[index];
|
|
26
|
+
if (step === undefined) return false;
|
|
27
|
+
const expected = stepIdentity(step, index);
|
|
28
|
+
const stored = plan[index];
|
|
29
|
+
return stored !== undefined && stored.kind === expected.kind && stored.name === expected.name;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Outputs of the completed steps in order; an approval step contributes null. */
|
|
33
|
+
export function stepOutputs(
|
|
34
|
+
progress: readonly WorkflowProgressEntry[],
|
|
35
|
+
count: number,
|
|
36
|
+
): (JobJson | null)[] {
|
|
37
|
+
const outputs: (JobJson | null)[] = [];
|
|
38
|
+
for (let index = 0; index < count; index += 1) {
|
|
39
|
+
const entry = progress.find((candidate) => candidate.index === index);
|
|
40
|
+
outputs.push(entry?.output ?? null);
|
|
41
|
+
}
|
|
42
|
+
return outputs;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** The resolver context for the step at `index`: chain input plus completed outputs. */
|
|
46
|
+
export function resolveContext(
|
|
47
|
+
input: JobJson,
|
|
48
|
+
progress: readonly WorkflowProgressEntry[],
|
|
49
|
+
index: number,
|
|
50
|
+
): WorkflowResolveContext {
|
|
51
|
+
return { input, steps: stepOutputs(progress, index) };
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Validates a resolved approval `params` value: a flat JSON object of string/number
|
|
56
|
+
* values, exactly what `t(titleKey, params)` can interpolate.
|
|
57
|
+
*/
|
|
58
|
+
export function normalizeTitleParams(value: unknown): Record<string, string | number> {
|
|
59
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
60
|
+
throw new WorkflowError("workflow_step_failed", "Approval params must resolve to an object.");
|
|
61
|
+
}
|
|
62
|
+
const params: Record<string, string | number> = {};
|
|
63
|
+
for (const [key, entry] of Object.entries(value)) {
|
|
64
|
+
if (typeof entry === "string") params[key] = entry;
|
|
65
|
+
else if (typeof entry === "number" && Number.isFinite(entry)) params[key] = entry;
|
|
66
|
+
else {
|
|
67
|
+
throw new WorkflowError(
|
|
68
|
+
"workflow_step_failed",
|
|
69
|
+
`Approval param "${key}" must be a string or a finite number.`,
|
|
70
|
+
);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
return params;
|
|
74
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
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
|
+
import type { JobJson, WorkflowProgressEntry } from "@facilis.dev/core";
|
|
7
|
+
|
|
8
|
+
import type { StoredWorkflow, WorkflowRuntimeDeps } from "./contracts.ts";
|
|
9
|
+
|
|
10
|
+
/** Stored failures are diagnostics, not a log (same bound as a job's error). */
|
|
11
|
+
export const MAX_STORED_ERROR = 2000;
|
|
12
|
+
|
|
13
|
+
export type Now = () => Date;
|
|
14
|
+
|
|
15
|
+
/** Thrown inside a transaction when the CAS guard no longer matches, to roll the write back. */
|
|
16
|
+
export class CasLost extends Error {}
|
|
17
|
+
|
|
18
|
+
/** Settles a chain as failed, keeping the coded reason in `error`. */
|
|
19
|
+
export async function fail(
|
|
20
|
+
deps: WorkflowRuntimeDeps,
|
|
21
|
+
now: Now,
|
|
22
|
+
workflow: StoredWorkflow,
|
|
23
|
+
code: string,
|
|
24
|
+
message: string,
|
|
25
|
+
): Promise<void> {
|
|
26
|
+
await deps.store.update(workflow.id, guard(workflow), {
|
|
27
|
+
status: "failed",
|
|
28
|
+
currentJobId: null,
|
|
29
|
+
waitingTaskId: null,
|
|
30
|
+
error: (code + ": " + message).slice(0, MAX_STORED_ERROR),
|
|
31
|
+
finishedAt: now(),
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Every present field is an AND condition: the transition only applies to what it read. */
|
|
36
|
+
export function guard(workflow: StoredWorkflow): {
|
|
37
|
+
status: StoredWorkflow["status"];
|
|
38
|
+
currentStep: number;
|
|
39
|
+
currentJobId: string | null;
|
|
40
|
+
waitingTaskId: string | null;
|
|
41
|
+
} {
|
|
42
|
+
return {
|
|
43
|
+
status: workflow.status,
|
|
44
|
+
currentStep: workflow.currentStep,
|
|
45
|
+
currentJobId: workflow.currentJobId,
|
|
46
|
+
waitingTaskId: workflow.waitingTaskId,
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** The serialized output of the step at `index`, or null when it has none. */
|
|
51
|
+
export function lastOutput(
|
|
52
|
+
progress: readonly WorkflowProgressEntry[],
|
|
53
|
+
index: number,
|
|
54
|
+
): JobJson | null {
|
|
55
|
+
return progress.find((entry) => entry.index === index)?.output ?? null;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function describe(error: unknown): string {
|
|
59
|
+
return error instanceof WorkflowError || error instanceof Error ? error.message : String(error);
|
|
60
|
+
}
|
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
// The workflow state machine (D-135, docs/WORKFLOWS.md §8).
|
|
2
|
+
//
|
|
3
|
+
// Every transition is a short transaction with a compare-and-set guard on the row it read;
|
|
4
|
+
// the side-effecting half of a transition (job enqueue, task insert) lives in dispatch.ts.
|
|
5
|
+
import type { JobJson, WorkflowDefinition, WorkflowProgressEntry } from "@facilis.dev/core";
|
|
6
|
+
|
|
7
|
+
import { formatIssues } from "../jobs/engine-support.ts";
|
|
8
|
+
import type { StoredTask } from "../tasks/contracts.ts";
|
|
9
|
+
import type { StoredWorkflow, WorkflowRuntimeDeps } from "./contracts.ts";
|
|
10
|
+
import { dispatch } from "./dispatch.ts";
|
|
11
|
+
import { planMatches } from "./steps.ts";
|
|
12
|
+
import { fail, guard, type Now } from "./support.ts";
|
|
13
|
+
|
|
14
|
+
/** Active rows one tick advances; the tick re-arms itself, so this is a fairness bound. */
|
|
15
|
+
export const TICK_BATCH = 25;
|
|
16
|
+
|
|
17
|
+
/** Expires due tasks, then fails the workflows waiting on them (docs/WORKFLOWS.md §8.1). */
|
|
18
|
+
export async function expireDueTasks(deps: WorkflowRuntimeDeps, now: Now): Promise<void> {
|
|
19
|
+
const expired = await deps.tasks.expireDue(now(), TICK_BATCH);
|
|
20
|
+
if (expired.length === 0) return;
|
|
21
|
+
for (const task of expired) {
|
|
22
|
+
if (task.workflowId === null) continue;
|
|
23
|
+
const workflow = await deps.store.get(task.workflowId);
|
|
24
|
+
if (workflow === null || workflow.status !== "waiting") continue;
|
|
25
|
+
if (workflow.waitingTaskId !== task.id) continue;
|
|
26
|
+
await fail(deps, now, workflow, "workflow_task_expired", "Task " + task.id + " expired.");
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** One transition of one active workflow. */
|
|
31
|
+
export async function stepWorkflow(
|
|
32
|
+
deps: WorkflowRuntimeDeps,
|
|
33
|
+
now: Now,
|
|
34
|
+
workflow: StoredWorkflow,
|
|
35
|
+
): Promise<void> {
|
|
36
|
+
if (workflow.status === "waiting") return resume(deps, now, workflow);
|
|
37
|
+
if (workflow.currentJobId !== null) return advance(deps, now, workflow);
|
|
38
|
+
return dispatch(deps, now, workflow, 1);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** A decided/expired/cancelled waiting task resumes or fails the chain (§8.2). */
|
|
42
|
+
async function resume(
|
|
43
|
+
deps: WorkflowRuntimeDeps,
|
|
44
|
+
now: Now,
|
|
45
|
+
workflow: StoredWorkflow,
|
|
46
|
+
): Promise<void> {
|
|
47
|
+
if (workflow.waitingTaskId === null) {
|
|
48
|
+
return fail(deps, now, workflow, "workflow_interrupted", "Waiting workflow has no task.");
|
|
49
|
+
}
|
|
50
|
+
const task = await deps.tasks.get(workflow.waitingTaskId);
|
|
51
|
+
if (task === null) {
|
|
52
|
+
return fail(
|
|
53
|
+
deps,
|
|
54
|
+
now,
|
|
55
|
+
workflow,
|
|
56
|
+
"workflow_interrupted",
|
|
57
|
+
"Task " + workflow.waitingTaskId + " is missing.",
|
|
58
|
+
);
|
|
59
|
+
}
|
|
60
|
+
if (task.status === "pending") {
|
|
61
|
+
if (task.expiresAt !== null && task.expiresAt.getTime() <= now().getTime()) {
|
|
62
|
+
// A decision may have won the race between the read and the expiry: then wait for the
|
|
63
|
+
// next tick, which sees the decided row (the CAS keeps exactly one winner, D-135).
|
|
64
|
+
const expired = await deps.tasks.expire(task.id, now());
|
|
65
|
+
if (expired) {
|
|
66
|
+
return fail(deps, now, workflow, "workflow_task_expired", "Task " + task.id + " expired.");
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
if (task.status === "expired") {
|
|
72
|
+
return fail(deps, now, workflow, "workflow_task_expired", "Task " + task.id + " expired.");
|
|
73
|
+
}
|
|
74
|
+
if (task.status === "cancelled") {
|
|
75
|
+
return fail(
|
|
76
|
+
deps,
|
|
77
|
+
now,
|
|
78
|
+
workflow,
|
|
79
|
+
"workflow_task_cancelled",
|
|
80
|
+
"Task " + task.id + " was cancelled.",
|
|
81
|
+
);
|
|
82
|
+
}
|
|
83
|
+
if (task.decision === "reject") {
|
|
84
|
+
return rejectTask(deps, now, workflow, task);
|
|
85
|
+
}
|
|
86
|
+
const entry: WorkflowProgressEntry = {
|
|
87
|
+
index: task.stepIndex ?? workflow.currentStep,
|
|
88
|
+
kind: "approval",
|
|
89
|
+
taskId: task.id,
|
|
90
|
+
decision: "approve",
|
|
91
|
+
};
|
|
92
|
+
const updated = await deps.store.update(workflow.id, guard(workflow), {
|
|
93
|
+
status: "running",
|
|
94
|
+
waitingTaskId: null,
|
|
95
|
+
progress: [...workflow.progress, entry],
|
|
96
|
+
currentStep: workflow.currentStep + 1,
|
|
97
|
+
attempts: 0,
|
|
98
|
+
});
|
|
99
|
+
if (updated === null) return;
|
|
100
|
+
await dispatch(deps, now, updated, 1);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** A rejected approval continues at its declared step, or fails the run (§8.2). */
|
|
104
|
+
async function rejectTask(
|
|
105
|
+
deps: WorkflowRuntimeDeps,
|
|
106
|
+
now: Now,
|
|
107
|
+
workflow: StoredWorkflow,
|
|
108
|
+
task: StoredTask,
|
|
109
|
+
): Promise<void> {
|
|
110
|
+
const definition = deps.definitions.get(workflow.name);
|
|
111
|
+
if (definition === undefined) {
|
|
112
|
+
return fail(
|
|
113
|
+
deps,
|
|
114
|
+
now,
|
|
115
|
+
workflow,
|
|
116
|
+
"workflow_definition_changed",
|
|
117
|
+
'Workflow "' + workflow.name + '" is no longer defined.',
|
|
118
|
+
);
|
|
119
|
+
}
|
|
120
|
+
const index = task.stepIndex ?? workflow.currentStep;
|
|
121
|
+
const step = definition.steps[index];
|
|
122
|
+
const target = step !== undefined && "approval" in step ? step.approval.onReject : undefined;
|
|
123
|
+
if (target === undefined) {
|
|
124
|
+
return fail(
|
|
125
|
+
deps,
|
|
126
|
+
now,
|
|
127
|
+
workflow,
|
|
128
|
+
"workflow_task_rejected",
|
|
129
|
+
"Task " + task.id + " was rejected.",
|
|
130
|
+
);
|
|
131
|
+
}
|
|
132
|
+
// A definition edited mid-run must not redirect the branch: the plan snapshot has to still
|
|
133
|
+
// describe the target step (the same rule dispatch applies to the current step).
|
|
134
|
+
if (
|
|
135
|
+
target.step <= index ||
|
|
136
|
+
target.step >= definition.steps.length ||
|
|
137
|
+
!planMatches(workflow.plan, definition, target.step)
|
|
138
|
+
) {
|
|
139
|
+
return fail(
|
|
140
|
+
deps,
|
|
141
|
+
now,
|
|
142
|
+
workflow,
|
|
143
|
+
"workflow_definition_changed",
|
|
144
|
+
"Step " + target.step + " is not the planned reject target.",
|
|
145
|
+
);
|
|
146
|
+
}
|
|
147
|
+
const entry: WorkflowProgressEntry = {
|
|
148
|
+
index,
|
|
149
|
+
kind: "approval",
|
|
150
|
+
taskId: task.id,
|
|
151
|
+
decision: "reject",
|
|
152
|
+
};
|
|
153
|
+
const updated = await deps.store.update(workflow.id, guard(workflow), {
|
|
154
|
+
status: "running",
|
|
155
|
+
waitingTaskId: null,
|
|
156
|
+
progress: [...workflow.progress, entry],
|
|
157
|
+
currentStep: target.step,
|
|
158
|
+
attempts: 0,
|
|
159
|
+
});
|
|
160
|
+
if (updated !== null) await dispatch(deps, now, updated, 1);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** Settles the in-flight job step: advance, fail, cancelled, or recover a missing job (§8.3). */
|
|
164
|
+
async function advance(
|
|
165
|
+
deps: WorkflowRuntimeDeps,
|
|
166
|
+
now: Now,
|
|
167
|
+
workflow: StoredWorkflow,
|
|
168
|
+
): Promise<void> {
|
|
169
|
+
const jobId = workflow.currentJobId;
|
|
170
|
+
if (jobId === null) return;
|
|
171
|
+
const job = await deps.jobs.get(jobId);
|
|
172
|
+
if (job === null) {
|
|
173
|
+
// Boot recovery: the queue lost the row (memory fallback or an interrupted process).
|
|
174
|
+
if (workflow.attempts >= deps.maxStepAttempts) {
|
|
175
|
+
return fail(
|
|
176
|
+
deps,
|
|
177
|
+
now,
|
|
178
|
+
workflow,
|
|
179
|
+
"workflow_interrupted",
|
|
180
|
+
"Step job " + jobId + " disappeared after " + workflow.attempts + " dispatch(es).",
|
|
181
|
+
);
|
|
182
|
+
}
|
|
183
|
+
return dispatch(deps, now, workflow, workflow.attempts + 1);
|
|
184
|
+
}
|
|
185
|
+
if (job.status === "queued" || job.status === "running") return;
|
|
186
|
+
if (job.status === "failed") {
|
|
187
|
+
return fail(
|
|
188
|
+
deps,
|
|
189
|
+
now,
|
|
190
|
+
workflow,
|
|
191
|
+
"workflow_step_failed",
|
|
192
|
+
job.error ?? "Job " + jobId + " failed.",
|
|
193
|
+
);
|
|
194
|
+
}
|
|
195
|
+
if (job.status === "cancelled") {
|
|
196
|
+
await deps.store.update(workflow.id, guard(workflow), {
|
|
197
|
+
status: "cancelled",
|
|
198
|
+
currentJobId: null,
|
|
199
|
+
error: null,
|
|
200
|
+
finishedAt: now(),
|
|
201
|
+
});
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
const definition = deps.definitions.get(workflow.name);
|
|
206
|
+
if (definition === undefined) {
|
|
207
|
+
return fail(
|
|
208
|
+
deps,
|
|
209
|
+
now,
|
|
210
|
+
workflow,
|
|
211
|
+
"workflow_definition_changed",
|
|
212
|
+
'Workflow "' + workflow.name + '" is no longer defined.',
|
|
213
|
+
);
|
|
214
|
+
}
|
|
215
|
+
const output = job.output ?? null;
|
|
216
|
+
const entry: WorkflowProgressEntry = {
|
|
217
|
+
index: workflow.currentStep,
|
|
218
|
+
kind: "job",
|
|
219
|
+
jobId,
|
|
220
|
+
...(output === null ? {} : { output }),
|
|
221
|
+
};
|
|
222
|
+
const progress = [...workflow.progress, entry];
|
|
223
|
+
const nextStep = workflow.currentStep + 1;
|
|
224
|
+
|
|
225
|
+
if (nextStep >= definition.steps.length) {
|
|
226
|
+
const invalid = validateOutput(definition, output);
|
|
227
|
+
if (invalid !== null) {
|
|
228
|
+
return fail(deps, now, workflow, "workflow_invalid_output", invalid);
|
|
229
|
+
}
|
|
230
|
+
await deps.store.update(workflow.id, guard(workflow), {
|
|
231
|
+
status: "succeeded",
|
|
232
|
+
progress,
|
|
233
|
+
currentStep: nextStep,
|
|
234
|
+
currentJobId: null,
|
|
235
|
+
attempts: 0,
|
|
236
|
+
output,
|
|
237
|
+
error: null,
|
|
238
|
+
finishedAt: now(),
|
|
239
|
+
});
|
|
240
|
+
return;
|
|
241
|
+
}
|
|
242
|
+
const updated = await deps.store.update(workflow.id, guard(workflow), {
|
|
243
|
+
status: "running",
|
|
244
|
+
progress,
|
|
245
|
+
currentStep: nextStep,
|
|
246
|
+
currentJobId: null,
|
|
247
|
+
attempts: 0,
|
|
248
|
+
});
|
|
249
|
+
if (updated !== null) await dispatch(deps, now, updated, 1);
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
function validateOutput(
|
|
253
|
+
definition: WorkflowDefinition<unknown, unknown>,
|
|
254
|
+
output: JobJson | null,
|
|
255
|
+
): string | null {
|
|
256
|
+
if (definition.output === undefined) return null;
|
|
257
|
+
const parsed = definition.output.safeParse(output);
|
|
258
|
+
return parsed.success ? null : formatIssues(parsed.error.issues);
|
|
259
|
+
}
|
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
// Shared PGlite fixture for the workflow suite (D-135). It creates both real table
|
|
2
|
+
// definitions, their policies and the tenant defaults, so the store and runner are exercised
|
|
3
|
+
// through the same RLS boundary the runtime uses in dev.
|
|
4
|
+
import { randomUUID } from "node:crypto";
|
|
5
|
+
|
|
6
|
+
import { sql } from "drizzle-orm";
|
|
7
|
+
import { getTableConfig, PgDialect } from "drizzle-orm/pg-core";
|
|
8
|
+
|
|
9
|
+
import type { JobDefinition, JobJson, JobStatus } from "@facilis.dev/core";
|
|
10
|
+
import type { FacilisDb } from "@facilis.dev/db";
|
|
11
|
+
import {
|
|
12
|
+
createDb,
|
|
13
|
+
ensureAppRole,
|
|
14
|
+
facilisTasks,
|
|
15
|
+
facilisWorkflows,
|
|
16
|
+
policyCreateSql,
|
|
17
|
+
tenantDefaultSql,
|
|
18
|
+
} from "@facilis.dev/db";
|
|
19
|
+
|
|
20
|
+
import type { JobCounts, JobEngine } from "../jobs/contracts.ts";
|
|
21
|
+
import { createDbTaskStore } from "../tasks/db-store.ts";
|
|
22
|
+
import { createDbWorkflowStore } from "./db-store.ts";
|
|
23
|
+
|
|
24
|
+
/** Deployment tenant; a second tenant proves the RLS boundary cannot be crossed. */
|
|
25
|
+
export const TENANT_ID = "eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee";
|
|
26
|
+
export const OTHER_TENANT = "ffffffff-ffff-ffff-ffff-ffffffffffff";
|
|
27
|
+
export const BASE = new Date("2026-11-10T12:00:00.000Z");
|
|
28
|
+
|
|
29
|
+
export interface FakeJob {
|
|
30
|
+
id: string;
|
|
31
|
+
name: string;
|
|
32
|
+
status: JobStatus;
|
|
33
|
+
input: JobJson;
|
|
34
|
+
output: JobJson | null;
|
|
35
|
+
error: string | null;
|
|
36
|
+
attempts: number;
|
|
37
|
+
maxAttempts: number;
|
|
38
|
+
timeoutMs: number;
|
|
39
|
+
runAt: Date;
|
|
40
|
+
createdAt: Date;
|
|
41
|
+
startedAt: Date | null;
|
|
42
|
+
finishedAt: Date | null;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* The runner only needs enqueue/get/cancel from the queue; this fake lets a test decide when
|
|
47
|
+
* a step job succeeds, fails or disappears (boot recovery) without a real scheduler.
|
|
48
|
+
*/
|
|
49
|
+
export class FakeJobs implements JobEngine {
|
|
50
|
+
readonly jobs = new Map<string, FakeJob>();
|
|
51
|
+
private sequence = 0;
|
|
52
|
+
|
|
53
|
+
async start(): Promise<void> {}
|
|
54
|
+
async stop(): Promise<void> {}
|
|
55
|
+
|
|
56
|
+
async enqueue(name: string, data: unknown): Promise<{ id: string }> {
|
|
57
|
+
this.sequence += 1;
|
|
58
|
+
const id = randomUUID();
|
|
59
|
+
const at = new Date(BASE.getTime() + this.sequence * 1000);
|
|
60
|
+
this.jobs.set(id, {
|
|
61
|
+
id,
|
|
62
|
+
name,
|
|
63
|
+
status: "queued",
|
|
64
|
+
input: data as JobJson,
|
|
65
|
+
output: null,
|
|
66
|
+
error: null,
|
|
67
|
+
attempts: 0,
|
|
68
|
+
maxAttempts: 2,
|
|
69
|
+
timeoutMs: 30_000,
|
|
70
|
+
runAt: at,
|
|
71
|
+
createdAt: at,
|
|
72
|
+
startedAt: null,
|
|
73
|
+
finishedAt: null,
|
|
74
|
+
});
|
|
75
|
+
return { id };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
async get(id: string): Promise<FakeJob | null> {
|
|
79
|
+
return this.jobs.get(id) ?? null;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
async list(): Promise<FakeJob[]> {
|
|
83
|
+
return [...this.jobs.values()];
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
async queue(): Promise<FakeJob[]> {
|
|
87
|
+
return this.list();
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
async running(): Promise<FakeJob[]> {
|
|
91
|
+
return this.list();
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
async cancel(id: string): Promise<boolean> {
|
|
95
|
+
const job = this.jobs.get(id);
|
|
96
|
+
if (job === undefined || isTerminal(job.status)) return false;
|
|
97
|
+
job.status = "cancelled";
|
|
98
|
+
job.finishedAt = new Date(BASE.getTime() + this.sequence * 1000);
|
|
99
|
+
return true;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
async stats(): Promise<JobCounts> {
|
|
103
|
+
return { queued: 0, running: 0, succeeded: 0, failed: 0, cancelled: 0 };
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
scoped(): JobEngine {
|
|
107
|
+
return this;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** The job row remains but settles as succeeded (what advance() reads on the next tick). */
|
|
111
|
+
succeed(id: string, output: JobJson = null): void {
|
|
112
|
+
const job = this.required(id);
|
|
113
|
+
job.status = "succeeded";
|
|
114
|
+
job.output = output;
|
|
115
|
+
job.finishedAt = new Date();
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
fail(id: string, error: string): void {
|
|
119
|
+
const job = this.required(id);
|
|
120
|
+
job.status = "failed";
|
|
121
|
+
job.error = error;
|
|
122
|
+
job.finishedAt = new Date();
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** Boot recovery case: the queue lost the row entirely. */
|
|
126
|
+
forget(id: string): void {
|
|
127
|
+
this.jobs.delete(id);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** A definition the runner validates a dangling step against. */
|
|
131
|
+
static definitions(...names: string[]): ReadonlyMap<string, JobDefinition<unknown, unknown>> {
|
|
132
|
+
return new Map(
|
|
133
|
+
names.map((name) => [
|
|
134
|
+
name,
|
|
135
|
+
{
|
|
136
|
+
name,
|
|
137
|
+
input: { safeParse: (value: unknown) => ({ success: true, data: value }) },
|
|
138
|
+
output: { safeParse: (value: unknown) => ({ success: true, data: value }) },
|
|
139
|
+
run: () => undefined,
|
|
140
|
+
} as unknown as JobDefinition<unknown, unknown>,
|
|
141
|
+
]),
|
|
142
|
+
);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
lastEnqueuedName(): string | null {
|
|
146
|
+
const jobs = [...this.jobs.values()];
|
|
147
|
+
return jobs.length === 0 ? null : (jobs[jobs.length - 1]?.name ?? null);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
get latest(): FakeJob | undefined {
|
|
151
|
+
const jobs = [...this.jobs.values()];
|
|
152
|
+
return jobs[jobs.length - 1];
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
private required(id: string): FakeJob {
|
|
156
|
+
const job = this.jobs.get(id);
|
|
157
|
+
if (job === undefined) throw new Error("unknown fake job " + id);
|
|
158
|
+
return job;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function isTerminal(status: JobStatus): boolean {
|
|
163
|
+
return status === "succeeded" || status === "failed" || status === "cancelled";
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
export interface WorkflowsTestContext {
|
|
167
|
+
readonly db: FacilisDb;
|
|
168
|
+
readonly workflows: ReturnType<typeof createDbWorkflowStore>;
|
|
169
|
+
readonly tasks: ReturnType<typeof createDbTaskStore>;
|
|
170
|
+
readonly jobs: FakeJobs;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
export async function createWorkflowsTestContext(): Promise<WorkflowsTestContext> {
|
|
174
|
+
const db = await createDb();
|
|
175
|
+
const tenantDefault = new PgDialect().sqlToQuery(tenantDefaultSql()).sql;
|
|
176
|
+
const statements = [
|
|
177
|
+
`CREATE TABLE facilis_tasks (
|
|
178
|
+
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
179
|
+
workflow_id uuid,
|
|
180
|
+
step_index integer,
|
|
181
|
+
kind text NOT NULL,
|
|
182
|
+
status text NOT NULL,
|
|
183
|
+
decision text,
|
|
184
|
+
title_key text NOT NULL,
|
|
185
|
+
title_params jsonb NOT NULL DEFAULT '{}'::jsonb,
|
|
186
|
+
payload jsonb,
|
|
187
|
+
requested_by text,
|
|
188
|
+
assigned_permission text,
|
|
189
|
+
expires_at timestamptz,
|
|
190
|
+
decided_by text,
|
|
191
|
+
decided_at timestamptz,
|
|
192
|
+
comment text,
|
|
193
|
+
created_at timestamptz NOT NULL DEFAULT now(),
|
|
194
|
+
tenant_id uuid NOT NULL DEFAULT ${tenantDefault}
|
|
195
|
+
)`,
|
|
196
|
+
"ALTER TABLE facilis_tasks ENABLE ROW LEVEL SECURITY",
|
|
197
|
+
`CREATE TABLE facilis_workflows (
|
|
198
|
+
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
199
|
+
name text NOT NULL,
|
|
200
|
+
status text NOT NULL,
|
|
201
|
+
input jsonb NOT NULL,
|
|
202
|
+
progress jsonb NOT NULL DEFAULT '[]'::jsonb,
|
|
203
|
+
plan jsonb NOT NULL DEFAULT '[]'::jsonb,
|
|
204
|
+
current_step integer NOT NULL DEFAULT 0,
|
|
205
|
+
current_job_id uuid,
|
|
206
|
+
waiting_task_id uuid,
|
|
207
|
+
attempts integer NOT NULL DEFAULT 0,
|
|
208
|
+
output jsonb,
|
|
209
|
+
error text,
|
|
210
|
+
started_at timestamptz NOT NULL DEFAULT now(),
|
|
211
|
+
finished_at timestamptz,
|
|
212
|
+
created_at timestamptz NOT NULL DEFAULT now(),
|
|
213
|
+
tenant_id uuid NOT NULL DEFAULT ${tenantDefault}
|
|
214
|
+
)`,
|
|
215
|
+
"ALTER TABLE facilis_workflows ENABLE ROW LEVEL SECURITY",
|
|
216
|
+
...getTableConfig(facilisTasks).policies.map((policy) =>
|
|
217
|
+
policyCreateSql("facilis_tasks", policy),
|
|
218
|
+
),
|
|
219
|
+
...getTableConfig(facilisWorkflows).policies.map((policy) =>
|
|
220
|
+
policyCreateSql("facilis_workflows", policy),
|
|
221
|
+
),
|
|
222
|
+
];
|
|
223
|
+
await db.db.transaction(async (tx) => {
|
|
224
|
+
for (const statement of statements) await tx.execute(sql.raw(statement));
|
|
225
|
+
});
|
|
226
|
+
await ensureAppRole(db);
|
|
227
|
+
return {
|
|
228
|
+
db,
|
|
229
|
+
workflows: createDbWorkflowStore({ db, tenantId: TENANT_ID }),
|
|
230
|
+
tasks: createDbTaskStore({ db, tenantId: TENANT_ID }),
|
|
231
|
+
jobs: new FakeJobs(),
|
|
232
|
+
};
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
export async function clearWorkflows(db: FacilisDb): Promise<void> {
|
|
236
|
+
await db.db.execute(sql.raw("delete from facilis_workflows"));
|
|
237
|
+
await db.db.execute(sql.raw("delete from facilis_tasks"));
|
|
238
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { SESSION_COOKIE_NAME } from "@facilis.dev/auth";
|
|
2
|
+
import type { FacilisHandlerEvent } from "@facilis.dev/core";
|
|
3
|
+
import { deleteCookie, getCookie, setCookie, type H3Event } from "nitro/h3";
|
|
4
|
+
|
|
5
|
+
import { isProductionEnvironment } from "./runtime/env.ts";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Session-cookie helpers for route handlers (contracts §4.4, D-038).
|
|
9
|
+
*
|
|
10
|
+
* h3 owns the cookie surface: `setCookie`/`deleteCookie` serialise the attributes and
|
|
11
|
+
* write them to the EVENT's response headers, which is the only place a cookie is merged
|
|
12
|
+
* into the response by this server (a `Set-Cookie` on a returned `Response` is dropped
|
|
13
|
+
* in the in-VM Nitro dev path — D-038). They also APPEND rather than replace, so a cookie
|
|
14
|
+
* another handler staged on the same response is not clobbered.
|
|
15
|
+
*
|
|
16
|
+
* The attribute set is the framework's, not the app's: every Facilis app that logs a user
|
|
17
|
+
* in must emit the same `facilis_session` cookie (HttpOnly, Path=/, SameSite=Lax, Secure
|
|
18
|
+
* in production), so apps call these helpers instead of h3's setters directly.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
const COOKIE_PATH = "/";
|
|
22
|
+
const MS_PER_SECOND = 1000;
|
|
23
|
+
|
|
24
|
+
export interface SessionCookieOptions {
|
|
25
|
+
/** Session lifetime: the cookie must expire with the `sessions` row (config.auth.sessionDurationMs). */
|
|
26
|
+
readonly ttlMs: number;
|
|
27
|
+
/** `Secure` attribute; defaults to the fail-closed production check (D-146). */
|
|
28
|
+
readonly secure?: boolean;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Nitro hands handlers a real `H3Event`, but the route contract is core's structural
|
|
33
|
+
* event: core, auth and db never import h3, so a handler can be reused by any Fetch
|
|
34
|
+
* runtime (contracts §4.1). The cast is the one place that narrows back to the runtime.
|
|
35
|
+
*/
|
|
36
|
+
function h3Event(event: FacilisHandlerEvent): H3Event {
|
|
37
|
+
if (event.res === undefined) {
|
|
38
|
+
throw new Error(
|
|
39
|
+
"facilis: the server event has no response headers to stage the session cookie on",
|
|
40
|
+
);
|
|
41
|
+
}
|
|
42
|
+
return event as unknown as H3Event;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Sets `facilis_session` on the response of the current request. */
|
|
46
|
+
export function setSessionCookie(
|
|
47
|
+
event: FacilisHandlerEvent,
|
|
48
|
+
sessionId: string,
|
|
49
|
+
options: SessionCookieOptions,
|
|
50
|
+
): void {
|
|
51
|
+
setCookie(h3Event(event), SESSION_COOKIE_NAME, sessionId, {
|
|
52
|
+
httpOnly: true,
|
|
53
|
+
path: COOKIE_PATH,
|
|
54
|
+
sameSite: "lax",
|
|
55
|
+
secure: options.secure ?? isProductionEnvironment(),
|
|
56
|
+
maxAge: Math.max(0, Math.floor(options.ttlMs / MS_PER_SECOND)),
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Expires `facilis_session` on the response of the current request (logout). */
|
|
61
|
+
export function clearSessionCookie(event: FacilisHandlerEvent): void {
|
|
62
|
+
deleteCookie(h3Event(event), SESSION_COOKIE_NAME, { path: COOKIE_PATH });
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Reads the session id from the request; `null` when the request carries no session. */
|
|
66
|
+
export function sessionIdFromRequest(event: FacilisHandlerEvent): string | null {
|
|
67
|
+
const value = getCookie(event as unknown as H3Event, SESSION_COOKIE_NAME);
|
|
68
|
+
return value === undefined || value.length === 0 ? null : value;
|
|
69
|
+
}
|