@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,124 @@
|
|
|
1
|
+
// Dev database persistence (D-052).
|
|
2
|
+
//
|
|
3
|
+
// PGlite runs in memory for speed, but a memory-only dev database is wiped every time
|
|
4
|
+
// the Nitro worker restarts — which happens on every edit to a server route. That made
|
|
5
|
+
// "register a user, change a handler, log in again" the normal loop. This module keeps a
|
|
6
|
+
// single snapshot archive in the project's `.facilis/db` directory:
|
|
7
|
+
//
|
|
8
|
+
// boot: read `.facilis/db/snapshot.tar.gz` -> `createDb({ loadSnapshot })`
|
|
9
|
+
// run: every tick, if the cluster changed, `dumpDataDir('gzip')` -> write atomically
|
|
10
|
+
// stop: flush()
|
|
11
|
+
//
|
|
12
|
+
// One file, ~5 MB for a small app, so it crosses the VFS/OPFS mirror cheaply and the
|
|
13
|
+
// project's scoped restore (D-036) replays exactly one path. The directory is per-project
|
|
14
|
+
// state, never source: `.facilis/.gitignore` ignores the whole tree for git, and the IDE
|
|
15
|
+
// hides it from the Explorer/index/export.
|
|
16
|
+
import { access, mkdir, readFile, rename, writeFile } from "node:fs/promises";
|
|
17
|
+
import { dirname, join } from "node:path";
|
|
18
|
+
/** Per-project, non-source state directory (dev database, binary blobs). */
|
|
19
|
+
export const FACILIS_STATE_DIR = ".facilis";
|
|
20
|
+
/** The dev database snapshot, relative to the project root. */
|
|
21
|
+
export const DEV_DB_SNAPSHOT_FILE = join(FACILIS_STATE_DIR, "db", "snapshot.tar.gz");
|
|
22
|
+
const SNAPSHOT_INTERVAL_MS = 1_000;
|
|
23
|
+
export function devDbSnapshotPath(projectRoot) {
|
|
24
|
+
return join(projectRoot, DEV_DB_SNAPSHOT_FILE);
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Create `.facilis` and its self-ignoring `.gitignore`.
|
|
28
|
+
*
|
|
29
|
+
* The folder must persist in the VFS (that is how it survives a reload), but it is not
|
|
30
|
+
* source: a `.gitignore` containing `*` ignores the whole tree even when the project's
|
|
31
|
+
* own .gitignore was written before this directory existed. Written idempotently, and
|
|
32
|
+
* never overwriting a file the user may have edited.
|
|
33
|
+
*/
|
|
34
|
+
export async function ensureFacilisStateDir(projectRoot) {
|
|
35
|
+
const dir = join(projectRoot, FACILIS_STATE_DIR);
|
|
36
|
+
await mkdir(dir, { recursive: true });
|
|
37
|
+
const ignore = join(dir, ".gitignore");
|
|
38
|
+
try {
|
|
39
|
+
await access(ignore);
|
|
40
|
+
}
|
|
41
|
+
catch {
|
|
42
|
+
await writeFile(ignore, "*\n");
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
/** Read the dev snapshot; null when the project has none yet. */
|
|
46
|
+
export async function readDevDbSnapshot(path) {
|
|
47
|
+
try {
|
|
48
|
+
return new Uint8Array(await readFile(path));
|
|
49
|
+
}
|
|
50
|
+
catch (error) {
|
|
51
|
+
if (error?.code === "ENOENT")
|
|
52
|
+
return null;
|
|
53
|
+
throw error;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Start snapshotting a dev database. Only a changed cluster is dumped (`activity()`),
|
|
58
|
+
* so an idle project never pays for a dump, and a failed write keeps the last good file.
|
|
59
|
+
*/
|
|
60
|
+
export function installDevDbSnapshotter(options) {
|
|
61
|
+
const { db, projectRoot } = options;
|
|
62
|
+
const snapshotPath = options.snapshotPath ?? devDbSnapshotPath(projectRoot);
|
|
63
|
+
const intervalMs = options.intervalMs ?? SNAPSHOT_INTERVAL_MS;
|
|
64
|
+
// Nothing has been dumped yet: the first tick persists the boot state (migrations,
|
|
65
|
+
// seeds), not just the first request-driven write after it.
|
|
66
|
+
let seen = 0;
|
|
67
|
+
let saving = false;
|
|
68
|
+
let dirty = false;
|
|
69
|
+
let stopped = false;
|
|
70
|
+
let lastSnapshotAt = null;
|
|
71
|
+
const save = async () => {
|
|
72
|
+
if (saving) {
|
|
73
|
+
dirty = true;
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
saving = true;
|
|
77
|
+
const activityAtStart = db.activity();
|
|
78
|
+
try {
|
|
79
|
+
const bytes = await db.snapshot();
|
|
80
|
+
await ensureFacilisStateDir(projectRoot);
|
|
81
|
+
await writeAtomic(snapshotPath, bytes);
|
|
82
|
+
seen = activityAtStart;
|
|
83
|
+
lastSnapshotAt = Date.now();
|
|
84
|
+
}
|
|
85
|
+
catch (error) {
|
|
86
|
+
options.onError?.(error);
|
|
87
|
+
}
|
|
88
|
+
finally {
|
|
89
|
+
saving = false;
|
|
90
|
+
if (dirty && !stopped) {
|
|
91
|
+
dirty = false;
|
|
92
|
+
void save();
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
};
|
|
96
|
+
const tick = () => {
|
|
97
|
+
if (stopped || saving)
|
|
98
|
+
return;
|
|
99
|
+
if (db.activity() === seen)
|
|
100
|
+
return;
|
|
101
|
+
void save();
|
|
102
|
+
};
|
|
103
|
+
const timer = setInterval(tick, intervalMs);
|
|
104
|
+
// Never keep the process (or a test run) alive for the snapshot ticker alone.
|
|
105
|
+
timer.unref?.();
|
|
106
|
+
return {
|
|
107
|
+
async flush() {
|
|
108
|
+
if (db.activity() !== seen)
|
|
109
|
+
await save();
|
|
110
|
+
},
|
|
111
|
+
stop() {
|
|
112
|
+
stopped = true;
|
|
113
|
+
clearInterval(timer);
|
|
114
|
+
},
|
|
115
|
+
lastSnapshotAt: () => lastSnapshotAt,
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
/** Write via a sibling temp file + rename, so a killed process never truncates the snapshot. */
|
|
119
|
+
async function writeAtomic(path, bytes) {
|
|
120
|
+
await mkdir(dirname(path), { recursive: true });
|
|
121
|
+
const temp = path + ".tmp";
|
|
122
|
+
await writeFile(temp, bytes);
|
|
123
|
+
await rename(temp, path);
|
|
124
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { type FacilisDb, type QueryExecution } from "@facilis.dev/db";
|
|
2
|
+
export declare const DEFAULT_QUERY_LIMIT = 100;
|
|
3
|
+
export declare const MAX_QUERY_LIMIT = 500;
|
|
4
|
+
export type DevQueryErrorCode = "invalid_body" | "invalid_name" | "invalid_sql" | "invalid_permission" | "query_failed" | "create_failed";
|
|
5
|
+
/** A request the console can render; the code is the body's `code` field. */
|
|
6
|
+
export declare class DevQueryError extends Error {
|
|
7
|
+
readonly code: DevQueryErrorCode;
|
|
8
|
+
constructor(code: DevQueryErrorCode, message: string);
|
|
9
|
+
}
|
|
10
|
+
export interface QueryRequest {
|
|
11
|
+
readonly sql: string;
|
|
12
|
+
readonly limit: number;
|
|
13
|
+
}
|
|
14
|
+
export interface ViewRequest {
|
|
15
|
+
readonly name: string;
|
|
16
|
+
readonly sql: string;
|
|
17
|
+
/** The view's own permission (D-098); null keeps the invoker form. */
|
|
18
|
+
readonly permission: string | null;
|
|
19
|
+
}
|
|
20
|
+
/** Narrow the console body, or a typed error whose code the route returns as-is. */
|
|
21
|
+
export declare function parseQueryBody(body: unknown): {
|
|
22
|
+
ok: true;
|
|
23
|
+
request: QueryRequest;
|
|
24
|
+
} | {
|
|
25
|
+
ok: false;
|
|
26
|
+
error: DevQueryError;
|
|
27
|
+
};
|
|
28
|
+
export declare function parseViewBody(body: unknown): {
|
|
29
|
+
ok: true;
|
|
30
|
+
request: ViewRequest;
|
|
31
|
+
} | {
|
|
32
|
+
ok: false;
|
|
33
|
+
error: DevQueryError;
|
|
34
|
+
};
|
|
35
|
+
/** Execute a parsed query, mapping the database's codes onto the route's codes. */
|
|
36
|
+
export declare function runQuery(db: FacilisDb, request: QueryRequest): Promise<QueryExecution>;
|
|
37
|
+
/** Create a live view from a parsed request, mapping declaration/database failures. */
|
|
38
|
+
export declare function createView(db: FacilisDb, request: ViewRequest): Promise<void>;
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
// Dev-only SQL console + live view creation: transport parsing for the two dev routes
|
|
2
|
+
// (SPEC §11.2, D-097). The SQL itself lives in @facilis.dev/db (security rule 5); this module
|
|
3
|
+
// narrows the request bodies and maps database failures to the route's 400 codes.
|
|
4
|
+
import { createLiveView, QueryExecutionError, runReadOnlyQuery, } from "@facilis.dev/db";
|
|
5
|
+
export const DEFAULT_QUERY_LIMIT = 100;
|
|
6
|
+
export const MAX_QUERY_LIMIT = 500;
|
|
7
|
+
/** A request the console can render; the code is the body's `code` field. */
|
|
8
|
+
export class DevQueryError extends Error {
|
|
9
|
+
code;
|
|
10
|
+
constructor(code, message) {
|
|
11
|
+
super(message);
|
|
12
|
+
this.name = "DevQueryError";
|
|
13
|
+
this.code = code;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
function isRecord(value) {
|
|
17
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
18
|
+
}
|
|
19
|
+
function readLimit(value) {
|
|
20
|
+
if (value === undefined)
|
|
21
|
+
return DEFAULT_QUERY_LIMIT;
|
|
22
|
+
if (typeof value !== "number" || !Number.isInteger(value) || value < 1)
|
|
23
|
+
return null;
|
|
24
|
+
return Math.min(value, MAX_QUERY_LIMIT);
|
|
25
|
+
}
|
|
26
|
+
/** Narrow the console body, or a typed error whose code the route returns as-is. */
|
|
27
|
+
export function parseQueryBody(body) {
|
|
28
|
+
if (!isRecord(body))
|
|
29
|
+
return { ok: false, error: invalidBody("Expected a JSON object body.") };
|
|
30
|
+
const sqlText = body["sql"];
|
|
31
|
+
if (typeof sqlText !== "string" || sqlText.trim().length === 0) {
|
|
32
|
+
return { ok: false, error: invalidBody('"sql" must be a non-empty string.') };
|
|
33
|
+
}
|
|
34
|
+
const limit = readLimit(body["limit"]);
|
|
35
|
+
if (limit === null) {
|
|
36
|
+
return { ok: false, error: invalidBody('"limit" must be a positive integer.') };
|
|
37
|
+
}
|
|
38
|
+
return { ok: true, request: { sql: sqlText, limit } };
|
|
39
|
+
}
|
|
40
|
+
export function parseViewBody(body) {
|
|
41
|
+
if (!isRecord(body))
|
|
42
|
+
return { ok: false, error: invalidBody("Expected a JSON object body.") };
|
|
43
|
+
const name = body["name"];
|
|
44
|
+
const sqlText = body["sql"];
|
|
45
|
+
if (typeof name !== "string" || name.length === 0) {
|
|
46
|
+
return { ok: false, error: invalidBody('"name" must be a non-empty string.') };
|
|
47
|
+
}
|
|
48
|
+
if (typeof sqlText !== "string" || sqlText.trim().length === 0) {
|
|
49
|
+
return { ok: false, error: invalidBody('"sql" must be a non-empty string.') };
|
|
50
|
+
}
|
|
51
|
+
const permission = body["permission"];
|
|
52
|
+
if (permission !== undefined &&
|
|
53
|
+
permission !== null &&
|
|
54
|
+
(typeof permission !== "string" || permission.length === 0)) {
|
|
55
|
+
return { ok: false, error: invalidBody('"permission" must be a non-empty string.') };
|
|
56
|
+
}
|
|
57
|
+
return {
|
|
58
|
+
ok: true,
|
|
59
|
+
request: { name, sql: sqlText, permission: typeof permission === "string" ? permission : null },
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
/** Execute a parsed query, mapping the database's codes onto the route's codes. */
|
|
63
|
+
export async function runQuery(db, request) {
|
|
64
|
+
try {
|
|
65
|
+
return await runReadOnlyQuery(db, request.sql, request.limit);
|
|
66
|
+
}
|
|
67
|
+
catch (error) {
|
|
68
|
+
throw toDevError(error);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
/** Create a live view from a parsed request, mapping declaration/database failures. */
|
|
72
|
+
export async function createView(db, request) {
|
|
73
|
+
try {
|
|
74
|
+
await createLiveView(db, request.name, request.sql, request.permission ?? undefined);
|
|
75
|
+
}
|
|
76
|
+
catch (error) {
|
|
77
|
+
throw toDevError(error);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
function toDevError(error) {
|
|
81
|
+
if (error instanceof QueryExecutionError)
|
|
82
|
+
return new DevQueryError(error.code, error.message);
|
|
83
|
+
return error;
|
|
84
|
+
}
|
|
85
|
+
function invalidBody(message) {
|
|
86
|
+
return new DevQueryError("invalid_body", message);
|
|
87
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Environment access is centralised so the dev-only guards have one definition.
|
|
3
|
+
*
|
|
4
|
+
* The default is **fail-closed** (D-146): only an explicit `development` or `test` counts as
|
|
5
|
+
* non-production, so a deploy that forgets NODE_ENV still gets the production guards (404 dev
|
|
6
|
+
* endpoints, Secure cookies, no in-memory PGlite) instead of exposing them.
|
|
7
|
+
*/
|
|
8
|
+
export declare function isProductionEnvironment(environment?: NodeJS.ProcessEnv): boolean;
|
|
9
|
+
export declare function readEnvironment(name: string, environment?: NodeJS.ProcessEnv): string | undefined;
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Environment access is centralised so the dev-only guards have one definition.
|
|
3
|
+
*
|
|
4
|
+
* The default is **fail-closed** (D-146): only an explicit `development` or `test` counts as
|
|
5
|
+
* non-production, so a deploy that forgets NODE_ENV still gets the production guards (404 dev
|
|
6
|
+
* endpoints, Secure cookies, no in-memory PGlite) instead of exposing them.
|
|
7
|
+
*/
|
|
8
|
+
export function isProductionEnvironment(environment = process.env) {
|
|
9
|
+
const nodeEnv = environment["NODE_ENV"];
|
|
10
|
+
return nodeEnv !== "development" && nodeEnv !== "test";
|
|
11
|
+
}
|
|
12
|
+
export function readEnvironment(name, environment = process.env) {
|
|
13
|
+
return environment[name];
|
|
14
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { type HttpResult } from "./http.js";
|
|
2
|
+
/** Structural header reader: H3Event.req.headers and Headers both satisfy it. */
|
|
3
|
+
export interface HeaderReader {
|
|
4
|
+
get(name: string): string | null;
|
|
5
|
+
}
|
|
6
|
+
/**
|
|
7
|
+
* SPEC §6.8/§8.5 origin allowlist: the request must come from the page the dev
|
|
8
|
+
* server serves. Browsers omit Origin on same-origin GETs, so a missing Origin is
|
|
9
|
+
* allowed; anything present must be loopback or the request host itself.
|
|
10
|
+
*/
|
|
11
|
+
export declare function isOriginAllowed(headers: HeaderReader): boolean;
|
|
12
|
+
/**
|
|
13
|
+
* Guard a dev-only endpoint. Returns the error response to short-circuit with, or
|
|
14
|
+
* null when the request may proceed (404 in production, 403 on origin mismatch).
|
|
15
|
+
*/
|
|
16
|
+
export declare function guardDevRequest(headers: HeaderReader, environment?: NodeJS.ProcessEnv): HttpResult | null;
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { isProductionEnvironment } from "./env.js";
|
|
2
|
+
import { jsonResult } from "./http.js";
|
|
3
|
+
const LOOPBACK_HOSTNAMES = new Set(["localhost", "127.0.0.1", "::1", "[::1]"]);
|
|
4
|
+
const DEV_HEADERS = { "cache-control": "no-cache" };
|
|
5
|
+
/**
|
|
6
|
+
* SPEC §6.8/§8.5 origin allowlist: the request must come from the page the dev
|
|
7
|
+
* server serves. Browsers omit Origin on same-origin GETs, so a missing Origin is
|
|
8
|
+
* allowed; anything present must be loopback or the request host itself.
|
|
9
|
+
*/
|
|
10
|
+
export function isOriginAllowed(headers) {
|
|
11
|
+
const origin = headers.get("origin");
|
|
12
|
+
if (origin === null || origin === "")
|
|
13
|
+
return true;
|
|
14
|
+
if (origin === "null")
|
|
15
|
+
return false;
|
|
16
|
+
let originUrl;
|
|
17
|
+
try {
|
|
18
|
+
originUrl = new URL(origin);
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
return false;
|
|
22
|
+
}
|
|
23
|
+
if (originUrl.protocol !== "http:" && originUrl.protocol !== "https:")
|
|
24
|
+
return false;
|
|
25
|
+
if (LOOPBACK_HOSTNAMES.has(originUrl.hostname))
|
|
26
|
+
return true;
|
|
27
|
+
const host = headers.get("host");
|
|
28
|
+
return host !== null && host !== "" && originUrl.host === host;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Guard a dev-only endpoint. Returns the error response to short-circuit with, or
|
|
32
|
+
* null when the request may proceed (404 in production, 403 on origin mismatch).
|
|
33
|
+
*/
|
|
34
|
+
export function guardDevRequest(headers, environment = process.env) {
|
|
35
|
+
if (isProductionEnvironment(environment)) {
|
|
36
|
+
return jsonResult(404, { code: "not_found" }, { ...DEV_HEADERS });
|
|
37
|
+
}
|
|
38
|
+
if (!isOriginAllowed(headers)) {
|
|
39
|
+
return jsonResult(403, { code: "forbidden" }, { ...DEV_HEADERS });
|
|
40
|
+
}
|
|
41
|
+
return null;
|
|
42
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/** Environment-independent response envelope used by pure builders and route adapters. */
|
|
2
|
+
export interface HttpResult {
|
|
3
|
+
status: number;
|
|
4
|
+
headers: Record<string, string>;
|
|
5
|
+
body?: unknown;
|
|
6
|
+
}
|
|
7
|
+
export declare function jsonResult(status: number, body: unknown, headers?: Record<string, string>): HttpResult;
|
|
8
|
+
/** Adapter from the pure builders to a web Response (Nitro v3/h3 v2 accept it). */
|
|
9
|
+
export declare function toResponse(result: HttpResult): Response;
|
|
10
|
+
/** Request URLs are origin-relative in Nitro; a dummy base only lets URL parse them. */
|
|
11
|
+
export declare function parseRequestUrl(rawUrl: string): URL;
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
export function jsonResult(status, body, headers = {}) {
|
|
2
|
+
return {
|
|
3
|
+
status,
|
|
4
|
+
headers: { "content-type": "application/json; charset=utf-8", ...headers },
|
|
5
|
+
body,
|
|
6
|
+
};
|
|
7
|
+
}
|
|
8
|
+
/** Adapter from the pure builders to a web Response (Nitro v3/h3 v2 accept it). */
|
|
9
|
+
export function toResponse(result) {
|
|
10
|
+
const headers = new Headers(result.headers);
|
|
11
|
+
if (result.body === undefined)
|
|
12
|
+
return new Response(null, { status: result.status, headers });
|
|
13
|
+
return new Response(JSON.stringify(result.body), { status: result.status, headers });
|
|
14
|
+
}
|
|
15
|
+
/** Request URLs are origin-relative in Nitro; a dummy base only lets URL parse them. */
|
|
16
|
+
export function parseRequestUrl(rawUrl) {
|
|
17
|
+
return new URL(rawUrl, "http://localhost");
|
|
18
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { FacilisJobsConfig, ManifestWarning } from "@facilis.dev/core";
|
|
2
|
+
import type { FacilisDb } from "@facilis.dev/db";
|
|
3
|
+
import type { JobModule } from "./contracts.js";
|
|
4
|
+
import { type JobsRuntime } from "./runtime.js";
|
|
5
|
+
export interface BootJobsOptions {
|
|
6
|
+
readonly db: FacilisDb;
|
|
7
|
+
readonly jobsConfig: FacilisJobsConfig;
|
|
8
|
+
readonly modules: readonly JobModule[];
|
|
9
|
+
readonly tenantId: string;
|
|
10
|
+
/** Session-wide manifest warnings; boot pushes into it instead of throwing. */
|
|
11
|
+
readonly warnings: ManifestWarning[];
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Boots the background-job runtime (D-107, docs/JOBS.md §8).
|
|
15
|
+
*
|
|
16
|
+
* Never throws: a broken queue degrades to "no jobs" with a manifest warning, because the
|
|
17
|
+
* dev server must still serve the project (contracts §8). The returned runtime is carried by
|
|
18
|
+
* `BootstrapState` and exposed as `ctx.jobs`.
|
|
19
|
+
*/
|
|
20
|
+
export declare function bootJobs(options: BootJobsOptions): Promise<JobsRuntime | null>;
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { createDbJobStore, isJobsTableAvailable } from "./db-store.js";
|
|
2
|
+
import { buildJobRegistry } from "./definitions.js";
|
|
3
|
+
import { createJobEngine } from "./engine.js";
|
|
4
|
+
import { createSystemJobExecutor } from "./executor.js";
|
|
5
|
+
import { createMemoryJobStore } from "./memory-store.js";
|
|
6
|
+
import { createJobsApi } from "./runtime.js";
|
|
7
|
+
/**
|
|
8
|
+
* Boots the background-job runtime (D-107, docs/JOBS.md §8).
|
|
9
|
+
*
|
|
10
|
+
* Never throws: a broken queue degrades to "no jobs" with a manifest warning, because the
|
|
11
|
+
* dev server must still serve the project (contracts §8). The returned runtime is carried by
|
|
12
|
+
* `BootstrapState` and exposed as `ctx.jobs`.
|
|
13
|
+
*/
|
|
14
|
+
export async function bootJobs(options) {
|
|
15
|
+
const { db, jobsConfig, modules, tenantId, warnings } = options;
|
|
16
|
+
try {
|
|
17
|
+
const registry = buildJobRegistry(modules);
|
|
18
|
+
warnings.push(...registry.warnings);
|
|
19
|
+
const store = await selectStore(db, jobsConfig, tenantId, warnings);
|
|
20
|
+
// One warning per failing context is enough: a broken store would otherwise flood the
|
|
21
|
+
// manifest on every tick.
|
|
22
|
+
const reportedErrors = new Set();
|
|
23
|
+
const engine = createJobEngine({
|
|
24
|
+
definitions: registry.definitions,
|
|
25
|
+
store,
|
|
26
|
+
config: {
|
|
27
|
+
maxConcurrent: jobsConfig.maxConcurrent,
|
|
28
|
+
maxAttempts: jobsConfig.maxAttempts,
|
|
29
|
+
retryDelayMs: jobsConfig.retryDelayMs,
|
|
30
|
+
timeoutMs: jobsConfig.timeoutMs,
|
|
31
|
+
pollIntervalMs: jobsConfig.pollIntervalMs,
|
|
32
|
+
},
|
|
33
|
+
executor: createSystemJobExecutor(db),
|
|
34
|
+
onError: (error, context) => {
|
|
35
|
+
if (reportedErrors.has(context))
|
|
36
|
+
return;
|
|
37
|
+
reportedErrors.add(context);
|
|
38
|
+
warnings.push({
|
|
39
|
+
code: "jobs_runtime_error",
|
|
40
|
+
message: `Background-job scheduler error (${context}): ${describe(error)}`,
|
|
41
|
+
});
|
|
42
|
+
},
|
|
43
|
+
});
|
|
44
|
+
const runtime = {
|
|
45
|
+
api: createJobsApi(engine, jobsConfig.maxConcurrent),
|
|
46
|
+
engine,
|
|
47
|
+
definitions: registry.definitions,
|
|
48
|
+
start: () => engine.start(),
|
|
49
|
+
stop: () => engine.stop(),
|
|
50
|
+
};
|
|
51
|
+
await runtime.start();
|
|
52
|
+
return runtime;
|
|
53
|
+
}
|
|
54
|
+
catch (error) {
|
|
55
|
+
warnings.push({
|
|
56
|
+
code: "jobs_boot_failed",
|
|
57
|
+
message: `Background jobs are disabled: ${describe(error)}`,
|
|
58
|
+
});
|
|
59
|
+
return null;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
async function selectStore(db, jobsConfig, tenantId, warnings) {
|
|
63
|
+
if (!jobsConfig.persist)
|
|
64
|
+
return createMemoryJobStore();
|
|
65
|
+
if (await isJobsTableAvailable(db))
|
|
66
|
+
return createDbJobStore({ db, tenantId });
|
|
67
|
+
// The project has not applied the framework migration yet: jobs still work, but queued
|
|
68
|
+
// work is lost on the next reload (docs/JOBS.md §8).
|
|
69
|
+
warnings.push({
|
|
70
|
+
code: "jobs_table_missing",
|
|
71
|
+
message: "facilis_jobs is missing; background jobs fall back to the in-memory queue. Re-export the table from db/schema.ts and apply the framework migration to persist them.",
|
|
72
|
+
});
|
|
73
|
+
return createMemoryJobStore();
|
|
74
|
+
}
|
|
75
|
+
function describe(error) {
|
|
76
|
+
return error instanceof Error ? error.message : String(error);
|
|
77
|
+
}
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import type { JobDefinition, JobJson, JobListOptions, JobStatus } from "@facilis.dev/core";
|
|
2
|
+
import type { PolicyScopedDatabase } from "@facilis.dev/db";
|
|
3
|
+
/**
|
|
4
|
+
* Internal contracts of the job runtime (D-107, docs/JOBS.md §9).
|
|
5
|
+
*
|
|
6
|
+
* The engine and the stores both code against this file so the persistence layer can change
|
|
7
|
+
* (Drizzle table, in-memory fallback) without touching scheduling semantics. `StoredJob` uses
|
|
8
|
+
* Date objects; the public `JobRecord` converts them to ISO strings in runtime.ts.
|
|
9
|
+
*/
|
|
10
|
+
/** One job row as the store knows it. */
|
|
11
|
+
export interface StoredJob {
|
|
12
|
+
readonly id: string;
|
|
13
|
+
readonly name: string;
|
|
14
|
+
readonly status: JobStatus;
|
|
15
|
+
readonly input: JobJson;
|
|
16
|
+
readonly output: JobJson | null;
|
|
17
|
+
readonly error: string | null;
|
|
18
|
+
readonly attempts: number;
|
|
19
|
+
readonly maxAttempts: number;
|
|
20
|
+
readonly timeoutMs: number;
|
|
21
|
+
readonly runAt: Date;
|
|
22
|
+
readonly createdAt: Date;
|
|
23
|
+
readonly startedAt: Date | null;
|
|
24
|
+
readonly finishedAt: Date | null;
|
|
25
|
+
}
|
|
26
|
+
/** What an enqueue writes; the store generates nothing but the id. */
|
|
27
|
+
export interface NewStoredJob {
|
|
28
|
+
readonly id: string;
|
|
29
|
+
readonly name: string;
|
|
30
|
+
readonly input: JobJson;
|
|
31
|
+
readonly maxAttempts: number;
|
|
32
|
+
readonly timeoutMs: number;
|
|
33
|
+
readonly runAt: Date;
|
|
34
|
+
readonly createdAt: Date;
|
|
35
|
+
}
|
|
36
|
+
/** Terminal outcome of one attempt (the engine retries by calling `requeue` instead). */
|
|
37
|
+
export type JobOutcome = {
|
|
38
|
+
readonly status: "succeeded";
|
|
39
|
+
readonly output: JobJson;
|
|
40
|
+
readonly finishedAt: Date;
|
|
41
|
+
} | {
|
|
42
|
+
readonly status: "failed";
|
|
43
|
+
readonly error: string;
|
|
44
|
+
readonly finishedAt: Date;
|
|
45
|
+
} | {
|
|
46
|
+
readonly status: "cancelled";
|
|
47
|
+
readonly error: string | null;
|
|
48
|
+
readonly finishedAt: Date;
|
|
49
|
+
};
|
|
50
|
+
/** Per-status counters for `ctx.jobs.stats`. */
|
|
51
|
+
export interface JobCounts {
|
|
52
|
+
readonly queued: number;
|
|
53
|
+
readonly running: number;
|
|
54
|
+
readonly succeeded: number;
|
|
55
|
+
readonly failed: number;
|
|
56
|
+
readonly cancelled: number;
|
|
57
|
+
}
|
|
58
|
+
/** Normalized `list` filter (the API applies defaults and the 200-row cap). */
|
|
59
|
+
export type StoredJobListOptions = Omit<JobListOptions, "limit"> & {
|
|
60
|
+
readonly limit: number;
|
|
61
|
+
};
|
|
62
|
+
/**
|
|
63
|
+
* Persistence seam between the engine and a store implementation.
|
|
64
|
+
*
|
|
65
|
+
* `claim` is the only state transition that must be atomic with respect to the queue: it
|
|
66
|
+
* marks due `queued` rows as `running`, increments `attempts` and sets `startedAt`.
|
|
67
|
+
*/
|
|
68
|
+
export interface JobStore {
|
|
69
|
+
insert(job: NewStoredJob): Promise<void>;
|
|
70
|
+
get(id: string): Promise<StoredJob | null>;
|
|
71
|
+
list(options: StoredJobListOptions): Promise<StoredJob[]>;
|
|
72
|
+
/** Queued jobs ordered by runAt ascending (the "queue" view). */
|
|
73
|
+
queue(limit?: number): Promise<StoredJob[]>;
|
|
74
|
+
/** Jobs in status "running". */
|
|
75
|
+
running(): Promise<StoredJob[]>;
|
|
76
|
+
/** Atomically claim up to `limit` due jobs for execution. */
|
|
77
|
+
claim(now: Date, limit: number): Promise<StoredJob[]>;
|
|
78
|
+
complete(id: string, outcome: JobOutcome): Promise<void>;
|
|
79
|
+
/** Return a job to "queued" for a retry at `runAt`, retaining the last error. */
|
|
80
|
+
requeue(id: string, options: {
|
|
81
|
+
readonly runAt: Date;
|
|
82
|
+
readonly error: string;
|
|
83
|
+
}): Promise<void>;
|
|
84
|
+
/** queued -> cancelled; false when the job is no longer queued. */
|
|
85
|
+
cancelQueued(id: string, finishedAt: Date): Promise<boolean>;
|
|
86
|
+
/** Recover rows left "running" by a crashed process; returns how many were touched. */
|
|
87
|
+
recoverInterrupted(now: Date): Promise<number>;
|
|
88
|
+
counts(): Promise<JobCounts>;
|
|
89
|
+
close(): Promise<void>;
|
|
90
|
+
/**
|
|
91
|
+
* Optional view whose operations join `scope` (the request's policy transaction) instead
|
|
92
|
+
* of opening a new one. PGlite is single-connection: a nested BEGIN would deadlock, so a
|
|
93
|
+
* handler's `ctx.jobs` must reuse the transaction it already runs in (D-107, JOBS §8).
|
|
94
|
+
*/
|
|
95
|
+
scoped?(scope: PolicyScopedDatabase): JobStore;
|
|
96
|
+
}
|
|
97
|
+
/** The engine's slice of `FacilisJobsConfig` (persistence and API caps stay outside). */
|
|
98
|
+
export interface JobEngineConfig {
|
|
99
|
+
readonly maxConcurrent: number;
|
|
100
|
+
readonly maxAttempts: number;
|
|
101
|
+
readonly retryDelayMs: number;
|
|
102
|
+
readonly timeoutMs: number;
|
|
103
|
+
readonly pollIntervalMs: number;
|
|
104
|
+
}
|
|
105
|
+
/** Clock and scheduling seam, injected so the engine tests are deterministic. */
|
|
106
|
+
export interface JobTimers {
|
|
107
|
+
now(): number;
|
|
108
|
+
setTimeout(fn: () => void, ms: number): unknown;
|
|
109
|
+
clearTimeout(handle: unknown): void;
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Runs one attempt in a system context (wired to `runAsSystem` in executor.ts).
|
|
113
|
+
*
|
|
114
|
+
* The engine owns input/output validation and serialization; the executor owns the system
|
|
115
|
+
* role, the transaction and the audit entry around the definition's `run`.
|
|
116
|
+
*/
|
|
117
|
+
export type JobExecutor = (input: {
|
|
118
|
+
readonly definition: JobDefinition<unknown, unknown>;
|
|
119
|
+
readonly data: unknown;
|
|
120
|
+
readonly job: StoredJob;
|
|
121
|
+
readonly signal: AbortSignal;
|
|
122
|
+
}) => Promise<unknown>;
|
|
123
|
+
export interface JobEngine {
|
|
124
|
+
/** Recovers interrupted rows, then starts ticking until `stop`. Idempotent. */
|
|
125
|
+
start(): Promise<void>;
|
|
126
|
+
/** Stops the ticker, aborts in-flight attempts and requeues them as interrupted. */
|
|
127
|
+
stop(): Promise<void>;
|
|
128
|
+
enqueue(name: string, data: unknown, options?: JobEnqueueOptions): Promise<{
|
|
129
|
+
id: string;
|
|
130
|
+
}>;
|
|
131
|
+
get(id: string): Promise<StoredJob | null>;
|
|
132
|
+
list(options?: JobListOptions): Promise<StoredJob[]>;
|
|
133
|
+
queue(): Promise<StoredJob[]>;
|
|
134
|
+
running(): Promise<StoredJob[]>;
|
|
135
|
+
cancel(id: string): Promise<boolean>;
|
|
136
|
+
stats(): Promise<JobCounts>;
|
|
137
|
+
/**
|
|
138
|
+
* Optional view whose queue operations use the store bound to `scope` while sharing this
|
|
139
|
+
* engine's timer and in-flight state. Used to bind `ctx.jobs` to a request transaction.
|
|
140
|
+
*/
|
|
141
|
+
scoped?(scope: PolicyScopedDatabase): JobEngine;
|
|
142
|
+
}
|
|
143
|
+
/** Absolute/relative schedule resolved by the engine (validated by the API layer). */
|
|
144
|
+
export interface JobEnqueueOptions {
|
|
145
|
+
readonly runAt?: Date;
|
|
146
|
+
}
|
|
147
|
+
export interface JobEngineOptions {
|
|
148
|
+
readonly definitions: ReadonlyMap<string, JobDefinition<unknown, unknown>>;
|
|
149
|
+
readonly store: JobStore;
|
|
150
|
+
readonly config: JobEngineConfig;
|
|
151
|
+
readonly executor: JobExecutor;
|
|
152
|
+
/** Defaults to the process clock and timers. */
|
|
153
|
+
readonly timers?: JobTimers;
|
|
154
|
+
/** Receives unexpected engine-level failures (a store write failing in the tick). */
|
|
155
|
+
readonly onError?: (error: unknown, context: string) => void;
|
|
156
|
+
}
|
|
157
|
+
/** One scanned definition module: virtual module entry, useful for warning messages. */
|
|
158
|
+
export interface JobModule {
|
|
159
|
+
readonly file: string;
|
|
160
|
+
readonly definition: unknown;
|
|
161
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { FacilisDb, PolicyScopedDatabase } from "@facilis.dev/db";
|
|
2
|
+
import type { JobStore } from "./contracts.js";
|
|
3
|
+
/**
|
|
4
|
+
* The persistent JobStore over `facilis_jobs`.
|
|
5
|
+
*
|
|
6
|
+
* A missing table is not handled here: boot probes it with `isJobsTableAvailable` and picks
|
|
7
|
+
* the memory store instead, so these methods may throw when the project is not migrated.
|
|
8
|
+
* `tenantId` is the deployment tenant the queue belongs to (the single-tenant fallback
|
|
9
|
+
* unless configured).
|
|
10
|
+
*/
|
|
11
|
+
export declare function createDbJobStore(options: {
|
|
12
|
+
readonly db: FacilisDb;
|
|
13
|
+
readonly tenantId: string;
|
|
14
|
+
/** Request transaction to join (from `JobStore.scoped`); absent for engine-owned work. */
|
|
15
|
+
readonly scope?: PolicyScopedDatabase;
|
|
16
|
+
}): JobStore;
|
|
17
|
+
/**
|
|
18
|
+
* Probe used by boot to pick persistence. `to_regclass` answers `null` for a missing table
|
|
19
|
+
* instead of raising, which is exactly the "project not migrated yet" case (JOBS.md §8).
|
|
20
|
+
*/
|
|
21
|
+
export declare function isJobsTableAvailable(db: FacilisDb): Promise<boolean>;
|