@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,95 @@
|
|
|
1
|
+
import { isValidEncryptionKeyId, type StorageEncryptionKeys } from "@facilis.dev/storage";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Resolve the optional at-rest encryption keys from the environment (D-117).
|
|
5
|
+
*
|
|
6
|
+
* The active key encrypts new blobs; retired keys only decrypt blobs whose header names
|
|
7
|
+
* them, which is what makes rotation possible without rewriting content-addressed bodies.
|
|
8
|
+
* Values are base64 (recommended) or 64-character hex, and must decode to 32 bytes.
|
|
9
|
+
*/
|
|
10
|
+
const KEY_ENV = "FACILIS_STORAGE_ENCRYPTION_KEY";
|
|
11
|
+
const KEY_ID_ENV = "FACILIS_STORAGE_ENCRYPTION_KEY_ID";
|
|
12
|
+
const RETIRED_KEYS_ENV = "FACILIS_STORAGE_ENCRYPTION_RETIRED_KEYS";
|
|
13
|
+
const DEFAULT_KEY_ID = "primary";
|
|
14
|
+
const KEY_BYTES = 32;
|
|
15
|
+
|
|
16
|
+
export type EncryptionKeyResolution =
|
|
17
|
+
| { readonly keys: StorageEncryptionKeys }
|
|
18
|
+
| { readonly keys: null; readonly problem: "missing" | "invalid"; readonly message: string };
|
|
19
|
+
|
|
20
|
+
export function resolveEncryptionKeys(env: NodeJS.ProcessEnv): EncryptionKeyResolution {
|
|
21
|
+
const rawKey = readEnv(env, KEY_ENV);
|
|
22
|
+
if (rawKey === undefined) {
|
|
23
|
+
return {
|
|
24
|
+
keys: null,
|
|
25
|
+
problem: "missing",
|
|
26
|
+
message:
|
|
27
|
+
"Set FACILIS_STORAGE_ENCRYPTION_KEY (base64 or hex, 32 bytes) because storage.encryption.enabled is true.",
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
const keyId = readEnv(env, KEY_ID_ENV) ?? DEFAULT_KEY_ID;
|
|
31
|
+
if (!isValidEncryptionKeyId(keyId)) {
|
|
32
|
+
return invalid("FACILIS_STORAGE_ENCRYPTION_KEY_ID must match [A-Za-z0-9._-]{1,64}.");
|
|
33
|
+
}
|
|
34
|
+
const activeKey = decodeKey(rawKey);
|
|
35
|
+
if (activeKey === null) {
|
|
36
|
+
return invalid("FACILIS_STORAGE_ENCRYPTION_KEY must be a base64 or hex 32-byte key.");
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// Null-prototype record: key ids are validated, but __proto__ must still never become an
|
|
40
|
+
// inherited value instead of an own key.
|
|
41
|
+
const keys: Record<string, Uint8Array> = Object.create(null) as Record<string, Uint8Array>;
|
|
42
|
+
keys[keyId] = activeKey;
|
|
43
|
+
const retiredRaw = readEnv(env, RETIRED_KEYS_ENV);
|
|
44
|
+
if (retiredRaw !== undefined) {
|
|
45
|
+
let parsed: unknown;
|
|
46
|
+
try {
|
|
47
|
+
parsed = JSON.parse(retiredRaw);
|
|
48
|
+
} catch {
|
|
49
|
+
return invalid(
|
|
50
|
+
"FACILIS_STORAGE_ENCRYPTION_RETIRED_KEYS must be a JSON object of key id to key.",
|
|
51
|
+
);
|
|
52
|
+
}
|
|
53
|
+
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
54
|
+
return invalid(
|
|
55
|
+
"FACILIS_STORAGE_ENCRYPTION_RETIRED_KEYS must be a JSON object of key id to key.",
|
|
56
|
+
);
|
|
57
|
+
}
|
|
58
|
+
for (const [retiredId, value] of Object.entries(parsed)) {
|
|
59
|
+
if (!isValidEncryptionKeyId(retiredId)) {
|
|
60
|
+
return invalid('Retired encryption key id "' + retiredId + '" is not a valid key id.');
|
|
61
|
+
}
|
|
62
|
+
if (Object.hasOwn(keys, retiredId)) {
|
|
63
|
+
return invalid('Encryption key id "' + retiredId + '" is both active and retired.');
|
|
64
|
+
}
|
|
65
|
+
if (typeof value !== "string") {
|
|
66
|
+
return invalid('Retired encryption key "' + retiredId + '" must be a string.');
|
|
67
|
+
}
|
|
68
|
+
const decoded = decodeKey(value);
|
|
69
|
+
if (decoded === null) {
|
|
70
|
+
return invalid('Retired encryption key "' + retiredId + '" must be 32 bytes.');
|
|
71
|
+
}
|
|
72
|
+
keys[retiredId] = decoded;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
return { keys: { activeKeyId: keyId, keys } };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function decodeKey(value: string): Uint8Array | null {
|
|
79
|
+
const trimmed = value.trim();
|
|
80
|
+
if (/^[0-9a-fA-F]{64}$/.test(trimmed)) {
|
|
81
|
+
return new Uint8Array(Buffer.from(trimmed, "hex"));
|
|
82
|
+
}
|
|
83
|
+
if (!/^[A-Za-z0-9+/]+={0,2}$/.test(trimmed)) return null;
|
|
84
|
+
const decoded = Buffer.from(trimmed, "base64");
|
|
85
|
+
return decoded.length === KEY_BYTES ? new Uint8Array(decoded) : null;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function readEnv(env: NodeJS.ProcessEnv, name: string): string | undefined {
|
|
89
|
+
const value = env[name]?.trim();
|
|
90
|
+
return value === undefined || value.length === 0 ? undefined : value;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function invalid(message: string): EncryptionKeyResolution {
|
|
94
|
+
return { keys: null, problem: "invalid", message };
|
|
95
|
+
}
|
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
import { randomBytes } from "node:crypto";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
|
|
4
|
+
import {
|
|
5
|
+
DEFAULT_STORAGE_CONFIG,
|
|
6
|
+
type FacilisConfig,
|
|
7
|
+
type ManifestWarning,
|
|
8
|
+
type StorageApi,
|
|
9
|
+
} from "@facilis.dev/core";
|
|
10
|
+
import {
|
|
11
|
+
buildSignedDownloadUrl,
|
|
12
|
+
createEncryptedStorage,
|
|
13
|
+
createLocalStorage,
|
|
14
|
+
createS3Storage,
|
|
15
|
+
verifyDownloadToken,
|
|
16
|
+
type SigningStorageDriver,
|
|
17
|
+
type StorageDriver,
|
|
18
|
+
type StorageEncryptionKeys,
|
|
19
|
+
} from "@facilis.dev/storage";
|
|
20
|
+
|
|
21
|
+
import { isProductionEnvironment } from "./env.ts";
|
|
22
|
+
import { resolveEncryptionKeys } from "./storage-keys.ts";
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Resolve the binary-storage runtime from the project config + environment (D-053).
|
|
26
|
+
*
|
|
27
|
+
* The environment, not the config, holds credentials and the token secret, so the
|
|
28
|
+
* committed facilis.config.ts never carries a secret. Every refusal is a manifest warning
|
|
29
|
+
* and yields a null storage: the app keeps booting and only the file routes answer
|
|
30
|
+
* `storage_unavailable`, exactly like the database target (D-068).
|
|
31
|
+
*/
|
|
32
|
+
export interface ResolvedStorage {
|
|
33
|
+
readonly storage: StorageApi | null;
|
|
34
|
+
readonly warnings: readonly ManifestWarning[];
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export interface ResolveStorageDeps {
|
|
38
|
+
/** Test seam: build the low-level driver without touching the filesystem or the network. */
|
|
39
|
+
readonly createDriver?: (config: FacilisConfig["storage"], rootDir: string) => StorageDriver;
|
|
40
|
+
/** Test seam: the HMAC secret (defaults to FACILIS_STORAGE_SECRET / a per-boot random). */
|
|
41
|
+
readonly secret?: string;
|
|
42
|
+
/** Test seam: the dev fallback secret. */
|
|
43
|
+
readonly randomSecret?: () => string;
|
|
44
|
+
/** Test seam: skip the environment and use this key ring (D-117). */
|
|
45
|
+
readonly encryptionKeys?: StorageEncryptionKeys;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const SECRET_ENV = "FACILIS_STORAGE_SECRET";
|
|
49
|
+
const S3_KEY_ENV = "FACILIS_S3_ACCESS_KEY_ID";
|
|
50
|
+
const S3_SECRET_ENV = "FACILIS_S3_SECRET_ACCESS_KEY";
|
|
51
|
+
const S3_SESSION_ENV = "FACILIS_S3_SESSION_TOKEN";
|
|
52
|
+
const LOCAL_ROOT = join(".facilis", "binary");
|
|
53
|
+
|
|
54
|
+
export function resolveStorage(
|
|
55
|
+
config: FacilisConfig | null,
|
|
56
|
+
env: NodeJS.ProcessEnv,
|
|
57
|
+
projectRoot: string,
|
|
58
|
+
deps: ResolveStorageDeps = {},
|
|
59
|
+
): ResolvedStorage {
|
|
60
|
+
const storageConfig = config?.storage ?? DEFAULT_STORAGE_CONFIG;
|
|
61
|
+
const production = isProductionEnvironment(env);
|
|
62
|
+
const warnings: ManifestWarning[] = [];
|
|
63
|
+
|
|
64
|
+
if (storageConfig.driver === "local" && production) {
|
|
65
|
+
return {
|
|
66
|
+
storage: null,
|
|
67
|
+
warnings: [
|
|
68
|
+
warning(
|
|
69
|
+
"storage_local_in_production",
|
|
70
|
+
'Production refuses the local file driver: set storage.driver to "s3" and an S3-compatible bucket.',
|
|
71
|
+
),
|
|
72
|
+
],
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
if (
|
|
77
|
+
storageConfig.driver === "s3" &&
|
|
78
|
+
(readEnv(env, S3_KEY_ENV) === undefined || readEnv(env, S3_SECRET_ENV) === undefined)
|
|
79
|
+
) {
|
|
80
|
+
return {
|
|
81
|
+
storage: null,
|
|
82
|
+
warnings: [
|
|
83
|
+
warning(
|
|
84
|
+
"storage_s3_credentials_missing",
|
|
85
|
+
"S3 storage needs FACILIS_S3_ACCESS_KEY_ID and FACILIS_S3_SECRET_ACCESS_KEY.",
|
|
86
|
+
),
|
|
87
|
+
],
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const secret = readSecret(env, deps);
|
|
92
|
+
if (secret === null) {
|
|
93
|
+
return {
|
|
94
|
+
storage: null,
|
|
95
|
+
warnings: [
|
|
96
|
+
warning(
|
|
97
|
+
"storage_secret_missing",
|
|
98
|
+
"Set FACILIS_STORAGE_SECRET in production: signed download tokens need a stable secret across restarts and instances.",
|
|
99
|
+
),
|
|
100
|
+
],
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
let encryptionKeys: StorageEncryptionKeys | null = null;
|
|
105
|
+
if (storageConfig.encryption.enabled) {
|
|
106
|
+
if (deps.encryptionKeys !== undefined) {
|
|
107
|
+
encryptionKeys = deps.encryptionKeys;
|
|
108
|
+
} else {
|
|
109
|
+
const resolved = resolveEncryptionKeys(env);
|
|
110
|
+
if (resolved.keys === null) {
|
|
111
|
+
return {
|
|
112
|
+
storage: null,
|
|
113
|
+
warnings: [
|
|
114
|
+
warning(
|
|
115
|
+
resolved.problem === "missing"
|
|
116
|
+
? "storage_encryption_key_missing"
|
|
117
|
+
: "storage_encryption_key_invalid",
|
|
118
|
+
resolved.message,
|
|
119
|
+
),
|
|
120
|
+
],
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
encryptionKeys = resolved.keys;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
try {
|
|
128
|
+
const baseDriver =
|
|
129
|
+
deps.createDriver?.(storageConfig, projectRoot) ??
|
|
130
|
+
createDriver(storageConfig, env, projectRoot);
|
|
131
|
+
const driver =
|
|
132
|
+
encryptionKeys === null
|
|
133
|
+
? baseDriver
|
|
134
|
+
: createEncryptedStorage({ driver: baseDriver, keys: encryptionKeys });
|
|
135
|
+
return { storage: createStorageApi(driver, secret, storageConfig), warnings };
|
|
136
|
+
} catch (error) {
|
|
137
|
+
return {
|
|
138
|
+
storage: null,
|
|
139
|
+
warnings: [
|
|
140
|
+
warning("storage_boot_failed", `Binary storage could not start: ${describe(error)}`),
|
|
141
|
+
],
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function createDriver(
|
|
147
|
+
config: FacilisConfig["storage"],
|
|
148
|
+
env: NodeJS.ProcessEnv,
|
|
149
|
+
projectRoot: string,
|
|
150
|
+
): StorageDriver {
|
|
151
|
+
if (config.driver === "local") {
|
|
152
|
+
return createLocalStorage({ rootDir: join(projectRoot, LOCAL_ROOT) });
|
|
153
|
+
}
|
|
154
|
+
const accessKeyId = readEnv(env, S3_KEY_ENV);
|
|
155
|
+
const secretAccessKey = readEnv(env, S3_SECRET_ENV);
|
|
156
|
+
// Config validation already requires bucket/region; the guard keeps a hand-edited or
|
|
157
|
+
// older virtual config from reaching the driver with nulls.
|
|
158
|
+
if (
|
|
159
|
+
config.bucket === null ||
|
|
160
|
+
config.region === null ||
|
|
161
|
+
accessKeyId === undefined ||
|
|
162
|
+
secretAccessKey === undefined
|
|
163
|
+
) {
|
|
164
|
+
throw new Error(
|
|
165
|
+
"S3 storage requires storage.bucket, storage.region, FACILIS_S3_ACCESS_KEY_ID and FACILIS_S3_SECRET_ACCESS_KEY",
|
|
166
|
+
);
|
|
167
|
+
}
|
|
168
|
+
const sessionToken = readEnv(env, S3_SESSION_ENV);
|
|
169
|
+
return createS3Storage({
|
|
170
|
+
bucket: config.bucket,
|
|
171
|
+
region: config.region,
|
|
172
|
+
accessKeyId,
|
|
173
|
+
secretAccessKey,
|
|
174
|
+
...(sessionToken === undefined ? {} : { sessionToken }),
|
|
175
|
+
...(config.endpoint === null ? {} : { endpoint: config.endpoint }),
|
|
176
|
+
...(config.forcePathStyle === null ? {} : { forcePathStyle: config.forcePathStyle }),
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function createStorageApi(
|
|
181
|
+
driver: StorageDriver,
|
|
182
|
+
secret: string,
|
|
183
|
+
config: FacilisConfig["storage"],
|
|
184
|
+
): StorageApi {
|
|
185
|
+
const signing = isSigningDriver(driver) ? driver : null;
|
|
186
|
+
const api: StorageApi = {
|
|
187
|
+
kind: driver.driver,
|
|
188
|
+
available: true,
|
|
189
|
+
maxUploadBytes: config.maxUploadBytes,
|
|
190
|
+
put: (bytes) => driver.put(bytes),
|
|
191
|
+
get: (hash) => driver.get(hash),
|
|
192
|
+
exists: (hash) => driver.exists(hash),
|
|
193
|
+
delete: (hash) => driver.delete(hash),
|
|
194
|
+
buildDownloadUrl: (fileId, options) =>
|
|
195
|
+
buildSignedDownloadUrl({
|
|
196
|
+
fileId,
|
|
197
|
+
secret,
|
|
198
|
+
expiresInSeconds: options?.expiresInSeconds ?? config.tokenTtlSeconds,
|
|
199
|
+
...(options?.tenantId === undefined ? {} : { tenantId: options.tenantId }),
|
|
200
|
+
...(options?.subject === undefined ? {} : { subject: options.subject }),
|
|
201
|
+
}),
|
|
202
|
+
verifyDownloadToken: (token, fileId) => {
|
|
203
|
+
const payload = verifyDownloadToken(token, secret);
|
|
204
|
+
return payload === null || payload.fileId !== fileId ? null : payload;
|
|
205
|
+
},
|
|
206
|
+
};
|
|
207
|
+
if (signing !== null) {
|
|
208
|
+
api.presignedGetUrl = (hash, options) => signing.signedGetUrl(hash, options);
|
|
209
|
+
}
|
|
210
|
+
return api;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
function isSigningDriver(driver: StorageDriver): driver is SigningStorageDriver {
|
|
214
|
+
return typeof (driver as Partial<SigningStorageDriver>).signedGetUrl === "function";
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
function readSecret(env: NodeJS.ProcessEnv, deps: ResolveStorageDeps): string | null {
|
|
218
|
+
if (deps.secret !== undefined) return deps.secret.length === 0 ? null : deps.secret;
|
|
219
|
+
const fromEnv = readEnv(env, SECRET_ENV);
|
|
220
|
+
if (fromEnv !== undefined) return fromEnv;
|
|
221
|
+
if (isProductionEnvironment(env)) return null;
|
|
222
|
+
// Dev tokens only need to live for the boot (five-minute TTL); a per-boot secret keeps
|
|
223
|
+
// the zero-config dev path working without writing a secret to the project.
|
|
224
|
+
return (deps.randomSecret ?? (() => randomBytes(32).toString("hex")))();
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
function readEnv(env: NodeJS.ProcessEnv, name: string): string | undefined {
|
|
228
|
+
const value = env[name]?.trim();
|
|
229
|
+
return value === undefined || value.length === 0 ? undefined : value;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
function warning(code: string, message: string): ManifestWarning {
|
|
233
|
+
return { code, message };
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
function describe(error: unknown): string {
|
|
237
|
+
return error instanceof Error ? error.message : String(error);
|
|
238
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { ensureSystemRole, type FacilisDb } from "@facilis.dev/db";
|
|
2
|
+
import type { ManifestWarning } from "@facilis.dev/core";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Boot step: provision `facilis_system` after the app role (D-099).
|
|
6
|
+
*
|
|
7
|
+
* A failure is a manifest warning, never a failed boot: without the role every sudo call
|
|
8
|
+
* fails closed at SET ROLE, so the app degrades to "no escalation" instead of crashing.
|
|
9
|
+
*/
|
|
10
|
+
export async function provisionSystemRole(
|
|
11
|
+
db: FacilisDb,
|
|
12
|
+
warnings: ManifestWarning[],
|
|
13
|
+
): Promise<void> {
|
|
14
|
+
try {
|
|
15
|
+
await ensureSystemRole(db);
|
|
16
|
+
} catch (error) {
|
|
17
|
+
warnings.push({
|
|
18
|
+
code: "system_role_failed",
|
|
19
|
+
message: `Could not provision the system role: ${describe(error)}`,
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function describe(error: unknown): string {
|
|
25
|
+
return error instanceof Error ? error.message : String(error);
|
|
26
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import type { ManifestWarning, TasksApi } from "@facilis.dev/core";
|
|
2
|
+
import type { FacilisDb } from "@facilis.dev/db";
|
|
3
|
+
|
|
4
|
+
import { createDbTaskStore, isTasksTableAvailable } from "./db-store.ts";
|
|
5
|
+
import { createTasksApi } from "./runtime.ts";
|
|
6
|
+
|
|
7
|
+
/** The booted task runtime carried by BootstrapState (D-135). */
|
|
8
|
+
export interface TasksRuntime {
|
|
9
|
+
readonly api: TasksApi;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface BootTasksOptions {
|
|
13
|
+
readonly db: FacilisDb;
|
|
14
|
+
readonly tenantId: string;
|
|
15
|
+
/** Session-wide manifest warnings; boot pushes into it instead of throwing. */
|
|
16
|
+
readonly warnings: ManifestWarning[];
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Boots the manual-task runtime (D-135, docs/WORKFLOWS.md §7).
|
|
21
|
+
*
|
|
22
|
+
* Never throws: without the table the API is unavailable with a manifest warning, because a
|
|
23
|
+
* reload-durable task needs rows (there is deliberately no in-memory mode). The returned
|
|
24
|
+
* runtime is carried by BootstrapState and exposed as ctx.tasks.
|
|
25
|
+
*/
|
|
26
|
+
export async function bootTasks(options: BootTasksOptions): Promise<TasksRuntime | null> {
|
|
27
|
+
const { db, tenantId, warnings } = options;
|
|
28
|
+
try {
|
|
29
|
+
if (!(await isTasksTableAvailable(db))) {
|
|
30
|
+
warnings.push({
|
|
31
|
+
code: "tasks_table_missing",
|
|
32
|
+
message:
|
|
33
|
+
"facilis_tasks is missing; manual tasks are disabled. Re-export the table from db/schema.ts and apply the framework migration.",
|
|
34
|
+
});
|
|
35
|
+
return null;
|
|
36
|
+
}
|
|
37
|
+
return { api: createTasksApi(createDbTaskStore({ db, tenantId })) };
|
|
38
|
+
} catch (error) {
|
|
39
|
+
warnings.push({
|
|
40
|
+
code: "tasks_boot_failed",
|
|
41
|
+
message: "Manual tasks are disabled: " + describe(error),
|
|
42
|
+
});
|
|
43
|
+
return null;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function describe(error: unknown): string {
|
|
48
|
+
return error instanceof Error ? error.message : String(error);
|
|
49
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
// Internal task-runtime contract (D-135, docs/WORKFLOWS.md §7-8). The public API lives in
|
|
2
|
+
// @facilis.dev/core; this module only knows rows, statuses and the store seams.
|
|
3
|
+
import type { PolicyScopedDatabase } from "@facilis.dev/db";
|
|
4
|
+
import type { JobJson, TaskDecision, TaskKind, TaskStatus } from "@facilis.dev/core";
|
|
5
|
+
|
|
6
|
+
/** One task as the store sees it: JSON data plus real Dates (the API ISO-izes them). */
|
|
7
|
+
export interface StoredTask {
|
|
8
|
+
readonly id: string;
|
|
9
|
+
readonly workflowId: string | null;
|
|
10
|
+
readonly stepIndex: number | null;
|
|
11
|
+
readonly kind: TaskKind;
|
|
12
|
+
readonly status: TaskStatus;
|
|
13
|
+
readonly decision: TaskDecision | null;
|
|
14
|
+
readonly titleKey: string;
|
|
15
|
+
readonly titleParams: JobJson;
|
|
16
|
+
readonly payload: JobJson | null;
|
|
17
|
+
readonly requestedBy: string | null;
|
|
18
|
+
readonly assignedPermission: string | null;
|
|
19
|
+
readonly expiresAt: Date | null;
|
|
20
|
+
readonly decidedBy: string | null;
|
|
21
|
+
readonly decidedAt: Date | null;
|
|
22
|
+
readonly comment: string | null;
|
|
23
|
+
readonly createdAt: Date;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** What the API writes for a new task; status/decision belong to the store. */
|
|
27
|
+
export interface NewStoredTask {
|
|
28
|
+
readonly id: string;
|
|
29
|
+
readonly workflowId: string | null;
|
|
30
|
+
readonly stepIndex: number | null;
|
|
31
|
+
readonly kind: TaskKind;
|
|
32
|
+
readonly titleKey: string;
|
|
33
|
+
readonly titleParams: JobJson;
|
|
34
|
+
readonly payload: JobJson | null;
|
|
35
|
+
readonly requestedBy: string | null;
|
|
36
|
+
readonly assignedPermission: string | null;
|
|
37
|
+
readonly expiresAt: Date | null;
|
|
38
|
+
readonly createdAt: Date;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export interface TaskListFilters {
|
|
42
|
+
readonly status?: TaskStatus | readonly TaskStatus[];
|
|
43
|
+
readonly workflowId?: string;
|
|
44
|
+
readonly assignedPermission?: string;
|
|
45
|
+
/** Already normalised by the API (default 50, max 200). */
|
|
46
|
+
readonly limit: number;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** A decision write: decider, instant and comment land atomically with the status change. */
|
|
50
|
+
export interface TaskDecisionWrite {
|
|
51
|
+
readonly decision: TaskDecision;
|
|
52
|
+
readonly decidedBy: string | null;
|
|
53
|
+
readonly comment: string | null;
|
|
54
|
+
readonly now: Date;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export interface TaskStore {
|
|
58
|
+
insert(task: NewStoredTask): Promise<void>;
|
|
59
|
+
get(id: string): Promise<StoredTask | null>;
|
|
60
|
+
list(filters: TaskListFilters): Promise<StoredTask[]>;
|
|
61
|
+
/**
|
|
62
|
+
* Marks up to `limit` due pending tasks expired and returns them: the workflow runner
|
|
63
|
+
* fails the chains waiting on them (docs/WORKFLOWS.md §8.1).
|
|
64
|
+
*/
|
|
65
|
+
expireDue(now: Date, limit: number): Promise<StoredTask[]>;
|
|
66
|
+
/** pending -> decided when the row is still pending and not expired; null otherwise. */
|
|
67
|
+
decide(id: string, write: TaskDecisionWrite): Promise<StoredTask | null>;
|
|
68
|
+
/** pending -> expired (lazy expiry, called by decide); false when the row is not pending. */
|
|
69
|
+
expire(id: string, now: Date): Promise<boolean>;
|
|
70
|
+
/** pending -> cancelled; false when the row is no longer pending. */
|
|
71
|
+
cancel(id: string, now: Date): Promise<boolean>;
|
|
72
|
+
/**
|
|
73
|
+
* Optional view whose operations join the request's policy transaction instead of opening
|
|
74
|
+
* a new one: PGlite is single-connection, so a nested BEGIN would deadlock (D-107, JOBS §8).
|
|
75
|
+
*/
|
|
76
|
+
scoped?(scope: PolicyScopedDatabase): TaskStore;
|
|
77
|
+
}
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
// The Drizzle-backed task store (D-135, docs/WORKFLOWS.md §7).
|
|
2
|
+
//
|
|
3
|
+
// Every operation runs through runWithPolicyScope, i.e. as facilis_app with app.tenant_id
|
|
4
|
+
// set: a new row's tenant_id comes from the tenantColumn default (the same GUC the
|
|
5
|
+
// restrictive policy reads), and a query cannot reach another tenant's tasks. The workflow
|
|
6
|
+
// runner (W2) reuses this store; only the actor differs.
|
|
7
|
+
import { and, asc, eq, gt, inArray, isNull, lte, or, sql, type SQL } from "drizzle-orm";
|
|
8
|
+
|
|
9
|
+
import { facilisTasks, runWithPolicyScope } from "@facilis.dev/db";
|
|
10
|
+
import type { FacilisDb, PolicyScopedDatabase } from "@facilis.dev/db";
|
|
11
|
+
|
|
12
|
+
import type {
|
|
13
|
+
NewStoredTask,
|
|
14
|
+
StoredTask,
|
|
15
|
+
TaskDecisionWrite,
|
|
16
|
+
TaskListFilters,
|
|
17
|
+
TaskStore,
|
|
18
|
+
} from "./contracts.ts";
|
|
19
|
+
import { toStoredTask } from "./row-mapping.ts";
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* The persistent TaskStore over facilis_tasks. A missing table is not handled here: boot
|
|
23
|
+
* probes it with isTasksTableAvailable and disables the API instead (D-135: no memory mode),
|
|
24
|
+
* so these methods may throw when the project is not migrated.
|
|
25
|
+
*/
|
|
26
|
+
export function createDbTaskStore(options: {
|
|
27
|
+
readonly db: FacilisDb;
|
|
28
|
+
readonly tenantId: string;
|
|
29
|
+
/** Request transaction to join (from TaskStore.scoped); absent for runtime-owned work. */
|
|
30
|
+
readonly scope?: PolicyScopedDatabase;
|
|
31
|
+
}): TaskStore {
|
|
32
|
+
const { db, tenantId, scope } = options;
|
|
33
|
+
|
|
34
|
+
// One policy-scoped transaction per operation; when a scope is bound (a handler's
|
|
35
|
+
// ctx.tasks), the operation joins that request transaction instead (D-135, JOBS §8).
|
|
36
|
+
function run<T>(fn: (tx: PolicyScopedDatabase) => Promise<T>): Promise<T> {
|
|
37
|
+
return scope === undefined ? runWithPolicyScope(db, { tenantId }, fn) : fn(scope);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
return {
|
|
41
|
+
async insert(task: NewStoredTask): Promise<void> {
|
|
42
|
+
await run((tx) =>
|
|
43
|
+
tx.insert(facilisTasks).values({
|
|
44
|
+
id: task.id,
|
|
45
|
+
workflowId: task.workflowId,
|
|
46
|
+
stepIndex: task.stepIndex,
|
|
47
|
+
kind: task.kind,
|
|
48
|
+
status: "pending",
|
|
49
|
+
titleKey: task.titleKey,
|
|
50
|
+
titleParams: task.titleParams,
|
|
51
|
+
payload: task.payload,
|
|
52
|
+
requestedBy: task.requestedBy,
|
|
53
|
+
assignedPermission: task.assignedPermission,
|
|
54
|
+
expiresAt: task.expiresAt,
|
|
55
|
+
createdAt: task.createdAt,
|
|
56
|
+
}),
|
|
57
|
+
);
|
|
58
|
+
},
|
|
59
|
+
|
|
60
|
+
async get(id: string): Promise<StoredTask | null> {
|
|
61
|
+
return run(async (tx) => {
|
|
62
|
+
const rows = await tx.select().from(facilisTasks).where(eq(facilisTasks.id, id)).limit(1);
|
|
63
|
+
const row = rows[0];
|
|
64
|
+
return row === undefined ? null : toStoredTask(row);
|
|
65
|
+
});
|
|
66
|
+
},
|
|
67
|
+
|
|
68
|
+
async list(filters: TaskListFilters): Promise<StoredTask[]> {
|
|
69
|
+
return run(async (tx) => {
|
|
70
|
+
const conditions: SQL[] = [];
|
|
71
|
+
if (filters.status !== undefined) {
|
|
72
|
+
conditions.push(
|
|
73
|
+
typeof filters.status === "string"
|
|
74
|
+
? eq(facilisTasks.status, filters.status)
|
|
75
|
+
: inArray(facilisTasks.status, [...filters.status]),
|
|
76
|
+
);
|
|
77
|
+
}
|
|
78
|
+
if (filters.workflowId !== undefined) {
|
|
79
|
+
conditions.push(eq(facilisTasks.workflowId, filters.workflowId));
|
|
80
|
+
}
|
|
81
|
+
if (filters.assignedPermission !== undefined) {
|
|
82
|
+
conditions.push(eq(facilisTasks.assignedPermission, filters.assignedPermission));
|
|
83
|
+
}
|
|
84
|
+
const rows = await tx
|
|
85
|
+
.select()
|
|
86
|
+
.from(facilisTasks)
|
|
87
|
+
.where(conditions.length === 0 ? undefined : and(...conditions))
|
|
88
|
+
// FIFO: the inbox shows the oldest pending request first.
|
|
89
|
+
.orderBy(asc(facilisTasks.createdAt))
|
|
90
|
+
.limit(filters.limit);
|
|
91
|
+
return rows.map(toStoredTask);
|
|
92
|
+
});
|
|
93
|
+
},
|
|
94
|
+
|
|
95
|
+
async decide(id: string, write: TaskDecisionWrite): Promise<StoredTask | null> {
|
|
96
|
+
return run(async (tx) => {
|
|
97
|
+
const rows = await tx
|
|
98
|
+
.update(facilisTasks)
|
|
99
|
+
.set({
|
|
100
|
+
status: "decided",
|
|
101
|
+
decision: write.decision,
|
|
102
|
+
decidedBy: write.decidedBy,
|
|
103
|
+
decidedAt: write.now,
|
|
104
|
+
comment: write.comment,
|
|
105
|
+
})
|
|
106
|
+
// Compare-and-set: only the first decider wins, and an expired row cannot be decided.
|
|
107
|
+
.where(
|
|
108
|
+
and(
|
|
109
|
+
eq(facilisTasks.id, id),
|
|
110
|
+
eq(facilisTasks.status, "pending"),
|
|
111
|
+
or(isNull(facilisTasks.expiresAt), gt(facilisTasks.expiresAt, write.now)),
|
|
112
|
+
),
|
|
113
|
+
)
|
|
114
|
+
.returning();
|
|
115
|
+
const row = rows[0];
|
|
116
|
+
return row === undefined ? null : toStoredTask(row);
|
|
117
|
+
});
|
|
118
|
+
},
|
|
119
|
+
|
|
120
|
+
async expireDue(now: Date, limit: number): Promise<StoredTask[]> {
|
|
121
|
+
return run(async (tx) => {
|
|
122
|
+
const due = await tx
|
|
123
|
+
.select({ id: facilisTasks.id })
|
|
124
|
+
.from(facilisTasks)
|
|
125
|
+
.where(and(eq(facilisTasks.status, "pending"), lte(facilisTasks.expiresAt, now)))
|
|
126
|
+
.orderBy(asc(facilisTasks.createdAt))
|
|
127
|
+
.limit(limit);
|
|
128
|
+
if (due.length === 0) return [];
|
|
129
|
+
const rows = await tx
|
|
130
|
+
.update(facilisTasks)
|
|
131
|
+
.set({ status: "expired" })
|
|
132
|
+
.where(
|
|
133
|
+
and(
|
|
134
|
+
eq(facilisTasks.status, "pending"),
|
|
135
|
+
lte(facilisTasks.expiresAt, now),
|
|
136
|
+
inArray(
|
|
137
|
+
facilisTasks.id,
|
|
138
|
+
due.map((row) => row.id),
|
|
139
|
+
),
|
|
140
|
+
),
|
|
141
|
+
)
|
|
142
|
+
.returning();
|
|
143
|
+
return rows.map(toStoredTask);
|
|
144
|
+
});
|
|
145
|
+
},
|
|
146
|
+
|
|
147
|
+
async expire(id: string, now: Date): Promise<boolean> {
|
|
148
|
+
return run(async (tx) => {
|
|
149
|
+
const rows = await tx
|
|
150
|
+
.update(facilisTasks)
|
|
151
|
+
.set({ status: "expired" })
|
|
152
|
+
.where(
|
|
153
|
+
and(
|
|
154
|
+
eq(facilisTasks.id, id),
|
|
155
|
+
eq(facilisTasks.status, "pending"),
|
|
156
|
+
lte(facilisTasks.expiresAt, now),
|
|
157
|
+
),
|
|
158
|
+
)
|
|
159
|
+
.returning({ id: facilisTasks.id });
|
|
160
|
+
return rows.length > 0;
|
|
161
|
+
});
|
|
162
|
+
},
|
|
163
|
+
|
|
164
|
+
async cancel(id: string, _now: Date): Promise<boolean> {
|
|
165
|
+
return run(async (tx) => {
|
|
166
|
+
const rows = await tx
|
|
167
|
+
.update(facilisTasks)
|
|
168
|
+
.set({ status: "cancelled" })
|
|
169
|
+
.where(and(eq(facilisTasks.id, id), eq(facilisTasks.status, "pending")))
|
|
170
|
+
.returning({ id: facilisTasks.id });
|
|
171
|
+
return rows.length > 0;
|
|
172
|
+
});
|
|
173
|
+
},
|
|
174
|
+
|
|
175
|
+
/** Joins task operations to an existing request transaction (see run above). */
|
|
176
|
+
scoped(next: PolicyScopedDatabase): TaskStore {
|
|
177
|
+
return createDbTaskStore({ db, tenantId, scope: next });
|
|
178
|
+
},
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* Probe used by boot: to_regclass answers null for a missing table instead of raising, which
|
|
184
|
+
* is exactly the "project not migrated yet" case (D-135).
|
|
185
|
+
*/
|
|
186
|
+
export async function isTasksTableAvailable(db: FacilisDb): Promise<boolean> {
|
|
187
|
+
const result = await db.db.execute(
|
|
188
|
+
sql`select to_regclass('public.facilis_tasks') is not null as available`,
|
|
189
|
+
);
|
|
190
|
+
return result.rows[0]?.["available"] === true;
|
|
191
|
+
}
|