@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.
Files changed (267) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +18 -2
  3. package/dist/config.d.ts +30 -0
  4. package/dist/config.js +112 -0
  5. package/dist/constants.d.ts +24 -0
  6. package/dist/constants.js +24 -0
  7. package/dist/facade.d.ts +37 -0
  8. package/dist/facade.js +121 -0
  9. package/dist/index.d.ts +17 -0
  10. package/dist/index.js +14 -0
  11. package/dist/middleware/context.d.ts +5 -0
  12. package/dist/middleware/context.js +86 -0
  13. package/dist/middleware/cors.d.ts +10 -0
  14. package/dist/middleware/cors.js +34 -0
  15. package/dist/middleware/session.d.ts +9 -0
  16. package/dist/middleware/session.js +18 -0
  17. package/dist/module.d.ts +7 -0
  18. package/dist/module.js +234 -0
  19. package/dist/rolldown-parser.d.ts +3 -0
  20. package/dist/rolldown-parser.js +66 -0
  21. package/dist/route-metadata.d.ts +22 -0
  22. package/dist/route-metadata.js +161 -0
  23. package/dist/routes/dev-query.post.d.ts +10 -0
  24. package/dist/routes/dev-query.post.js +49 -0
  25. package/dist/routes/dev-schema.get.d.ts +9 -0
  26. package/dist/routes/dev-schema.get.js +34 -0
  27. package/dist/routes/dev-view.post.d.ts +11 -0
  28. package/dist/routes/dev-view.post.js +61 -0
  29. package/dist/routes/health.get.d.ts +8 -0
  30. package/dist/routes/health.get.js +18 -0
  31. package/dist/routes/manifest-revision.get.d.ts +8 -0
  32. package/dist/routes/manifest-revision.get.js +26 -0
  33. package/dist/routes/manifest.get.d.ts +8 -0
  34. package/dist/routes/manifest.get.js +68 -0
  35. package/dist/routes/openapi.get.d.ts +8 -0
  36. package/dist/routes/openapi.get.js +29 -0
  37. package/dist/routes/sso.d.ts +2 -0
  38. package/dist/routes/sso.js +216 -0
  39. package/dist/routes/token.post.d.ts +10 -0
  40. package/dist/routes/token.post.js +75 -0
  41. package/dist/runtime/boot-runtimes.d.ts +21 -0
  42. package/dist/runtime/boot-runtimes.js +38 -0
  43. package/dist/runtime/bootstrap.d.ts +47 -0
  44. package/dist/runtime/bootstrap.js +214 -0
  45. package/dist/runtime/config.d.ts +27 -0
  46. package/dist/runtime/config.js +44 -0
  47. package/dist/runtime/cors-policy.d.ts +16 -0
  48. package/dist/runtime/cors-policy.js +88 -0
  49. package/dist/runtime/db-bootstrap.d.ts +9 -0
  50. package/dist/runtime/db-bootstrap.js +87 -0
  51. package/dist/runtime/db-target.d.ts +21 -0
  52. package/dist/runtime/db-target.js +52 -0
  53. package/dist/runtime/dev-db-persistence.d.ts +39 -0
  54. package/dist/runtime/dev-db-persistence.js +124 -0
  55. package/dist/runtime/dev-query.d.ts +38 -0
  56. package/dist/runtime/dev-query.js +87 -0
  57. package/dist/runtime/env.d.ts +9 -0
  58. package/dist/runtime/env.js +14 -0
  59. package/dist/runtime/http-guard.d.ts +16 -0
  60. package/dist/runtime/http-guard.js +42 -0
  61. package/dist/runtime/http.d.ts +11 -0
  62. package/dist/runtime/http.js +18 -0
  63. package/dist/runtime/jobs/boot.d.ts +20 -0
  64. package/dist/runtime/jobs/boot.js +77 -0
  65. package/dist/runtime/jobs/contracts.d.ts +161 -0
  66. package/dist/runtime/jobs/contracts.js +1 -0
  67. package/dist/runtime/jobs/db-store.d.ts +21 -0
  68. package/dist/runtime/jobs/db-store.js +210 -0
  69. package/dist/runtime/jobs/definitions.d.ts +14 -0
  70. package/dist/runtime/jobs/definitions.js +31 -0
  71. package/dist/runtime/jobs/engine-support.d.ts +22 -0
  72. package/dist/runtime/jobs/engine-support.js +32 -0
  73. package/dist/runtime/jobs/engine.d.ts +6 -0
  74. package/dist/runtime/jobs/engine.js +261 -0
  75. package/dist/runtime/jobs/executor.d.ts +11 -0
  76. package/dist/runtime/jobs/executor.js +27 -0
  77. package/dist/runtime/jobs/memory-store.d.ts +7 -0
  78. package/dist/runtime/jobs/memory-store.js +183 -0
  79. package/dist/runtime/jobs/row-mapping.d.ts +28 -0
  80. package/dist/runtime/jobs/row-mapping.js +61 -0
  81. package/dist/runtime/jobs/runtime.d.ts +24 -0
  82. package/dist/runtime/jobs/runtime.js +86 -0
  83. package/dist/runtime/logging/audit-chain.d.ts +54 -0
  84. package/dist/runtime/logging/audit-chain.js +102 -0
  85. package/dist/runtime/logging/bootstrap-logging.d.ts +28 -0
  86. package/dist/runtime/logging/bootstrap-logging.js +26 -0
  87. package/dist/runtime/logging/entry.d.ts +14 -0
  88. package/dist/runtime/logging/entry.js +85 -0
  89. package/dist/runtime/logging/file-sink.d.ts +24 -0
  90. package/dist/runtime/logging/file-sink.js +128 -0
  91. package/dist/runtime/logging/log-settings.d.ts +52 -0
  92. package/dist/runtime/logging/log-settings.js +93 -0
  93. package/dist/runtime/logging/log-sink.d.ts +18 -0
  94. package/dist/runtime/logging/log-sink.js +22 -0
  95. package/dist/runtime/logging/redact.d.ts +31 -0
  96. package/dist/runtime/logging/redact.js +106 -0
  97. package/dist/runtime/logging/runtime.d.ts +25 -0
  98. package/dist/runtime/logging/runtime.js +114 -0
  99. package/dist/runtime/logging/sudo-bridge.d.ts +13 -0
  100. package/dist/runtime/logging/sudo-bridge.js +38 -0
  101. package/dist/runtime/manifest-data.d.ts +28 -0
  102. package/dist/runtime/manifest-data.js +70 -0
  103. package/dist/runtime/manifest-response.d.ts +45 -0
  104. package/dist/runtime/manifest-response.js +50 -0
  105. package/dist/runtime/manifest-sections.d.ts +20 -0
  106. package/dist/runtime/manifest-sections.js +59 -0
  107. package/dist/runtime/manifest-service.d.ts +16 -0
  108. package/dist/runtime/manifest-service.js +66 -0
  109. package/dist/runtime/project-config.d.ts +8 -0
  110. package/dist/runtime/project-config.js +22 -0
  111. package/dist/runtime/project-files.d.ts +12 -0
  112. package/dist/runtime/project-files.js +99 -0
  113. package/dist/runtime/rate-limit.d.ts +6 -0
  114. package/dist/runtime/rate-limit.js +6 -0
  115. package/dist/runtime/revision-service.d.ts +15 -0
  116. package/dist/runtime/revision-service.js +26 -0
  117. package/dist/runtime/sql.d.ts +8 -0
  118. package/dist/runtime/sql.js +23 -0
  119. package/dist/runtime/sso.d.ts +40 -0
  120. package/dist/runtime/sso.js +98 -0
  121. package/dist/runtime/state.d.ts +7 -0
  122. package/dist/runtime/state.js +7 -0
  123. package/dist/runtime/storage-keys.d.ts +9 -0
  124. package/dist/runtime/storage-keys.js +82 -0
  125. package/dist/runtime/storage-target.d.ts +25 -0
  126. package/dist/runtime/storage-target.js +155 -0
  127. package/dist/runtime/system-role.d.ts +9 -0
  128. package/dist/runtime/system-role.js +21 -0
  129. package/dist/runtime/tasks/boot.d.ts +20 -0
  130. package/dist/runtime/tasks/boot.js +32 -0
  131. package/dist/runtime/tasks/contracts.d.ts +70 -0
  132. package/dist/runtime/tasks/contracts.js +1 -0
  133. package/dist/runtime/tasks/db-store.d.ts +18 -0
  134. package/dist/runtime/tasks/db-store.js +139 -0
  135. package/dist/runtime/tasks/row-mapping.d.ts +11 -0
  136. package/dist/runtime/tasks/row-mapping.js +69 -0
  137. package/dist/runtime/tasks/runtime.d.ts +7 -0
  138. package/dist/runtime/tasks/runtime.js +162 -0
  139. package/dist/runtime/tasks/tasks-test-harness.d.ts +16 -0
  140. package/dist/runtime/tasks/tasks-test-harness.js +70 -0
  141. package/dist/runtime/tenant.d.ts +10 -0
  142. package/dist/runtime/tenant.js +13 -0
  143. package/dist/runtime/workflows/boot.d.ts +25 -0
  144. package/dist/runtime/workflows/boot.js +75 -0
  145. package/dist/runtime/workflows/contracts.d.ts +96 -0
  146. package/dist/runtime/workflows/contracts.js +1 -0
  147. package/dist/runtime/workflows/db-store.d.ts +18 -0
  148. package/dist/runtime/workflows/db-store.js +128 -0
  149. package/dist/runtime/workflows/definitions.d.ts +14 -0
  150. package/dist/runtime/workflows/definitions.js +50 -0
  151. package/dist/runtime/workflows/dispatch.d.ts +4 -0
  152. package/dist/runtime/workflows/dispatch.js +119 -0
  153. package/dist/runtime/workflows/row-mapping.d.ts +5 -0
  154. package/dist/runtime/workflows/row-mapping.js +38 -0
  155. package/dist/runtime/workflows/runner.d.ts +15 -0
  156. package/dist/runtime/workflows/runner.js +89 -0
  157. package/dist/runtime/workflows/runtime.d.ts +14 -0
  158. package/dist/runtime/workflows/runtime.js +129 -0
  159. package/dist/runtime/workflows/steps.d.ts +14 -0
  160. package/dist/runtime/workflows/steps.js +49 -0
  161. package/dist/runtime/workflows/support.d.ts +20 -0
  162. package/dist/runtime/workflows/support.js +36 -0
  163. package/dist/runtime/workflows/transitions.d.ts +8 -0
  164. package/dist/runtime/workflows/transitions.js +184 -0
  165. package/dist/runtime/workflows/workflows-test-harness.d.ts +62 -0
  166. package/dist/runtime/workflows/workflows-test-harness.js +178 -0
  167. package/dist/session-cookie.d.ts +13 -0
  168. package/dist/session-cookie.js +48 -0
  169. package/dist/storage.d.ts +50 -0
  170. package/dist/storage.js +118 -0
  171. package/dist/types.d.ts +44 -0
  172. package/dist/types.js +1 -0
  173. package/dist/virtual-ids.d.ts +17 -0
  174. package/dist/virtual-ids.js +17 -0
  175. package/dist/vite.d.ts +22 -0
  176. package/dist/vite.js +135 -0
  177. package/package.json +61 -4
  178. package/src/config.ts +120 -0
  179. package/src/constants.ts +24 -0
  180. package/src/facade.ts +153 -0
  181. package/src/index.ts +44 -0
  182. package/src/middleware/context.ts +106 -0
  183. package/src/middleware/cors.ts +42 -0
  184. package/src/middleware/session.ts +23 -0
  185. package/src/module.ts +278 -0
  186. package/src/rolldown-parser.ts +79 -0
  187. package/src/route-metadata-test-harness.ts +62 -0
  188. package/src/route-metadata.ts +194 -0
  189. package/src/routes/dev-query.post.ts +53 -0
  190. package/src/routes/dev-schema.get.ts +43 -0
  191. package/src/routes/dev-view.post.ts +66 -0
  192. package/src/routes/health.get.ts +26 -0
  193. package/src/routes/manifest-revision.get.ts +38 -0
  194. package/src/routes/manifest.get.ts +111 -0
  195. package/src/routes/openapi.get.ts +34 -0
  196. package/src/routes/sso.ts +247 -0
  197. package/src/routes/token.post.ts +89 -0
  198. package/src/runtime/boot-runtimes.ts +69 -0
  199. package/src/runtime/bootstrap.ts +300 -0
  200. package/src/runtime/config.ts +60 -0
  201. package/src/runtime/cors-policy.ts +107 -0
  202. package/src/runtime/db-bootstrap.ts +99 -0
  203. package/src/runtime/db-target.ts +87 -0
  204. package/src/runtime/dev-db-persistence.ts +146 -0
  205. package/src/runtime/dev-query.ts +124 -0
  206. package/src/runtime/env.ts +18 -0
  207. package/src/runtime/http-guard.ts +50 -0
  208. package/src/runtime/http.ts +30 -0
  209. package/src/runtime/jobs/boot.ts +97 -0
  210. package/src/runtime/jobs/contracts.ts +165 -0
  211. package/src/runtime/jobs/db-store-test-harness.ts +98 -0
  212. package/src/runtime/jobs/db-store.ts +273 -0
  213. package/src/runtime/jobs/definitions.ts +42 -0
  214. package/src/runtime/jobs/engine-support.ts +44 -0
  215. package/src/runtime/jobs/engine.ts +296 -0
  216. package/src/runtime/jobs/executor.ts +37 -0
  217. package/src/runtime/jobs/memory-store.ts +222 -0
  218. package/src/runtime/jobs/row-mapping.ts +67 -0
  219. package/src/runtime/jobs/runtime.ts +110 -0
  220. package/src/runtime/logging/audit-chain.ts +135 -0
  221. package/src/runtime/logging/bootstrap-logging.ts +62 -0
  222. package/src/runtime/logging/entry.ts +99 -0
  223. package/src/runtime/logging/file-sink.ts +157 -0
  224. package/src/runtime/logging/log-settings.ts +166 -0
  225. package/src/runtime/logging/log-sink.ts +31 -0
  226. package/src/runtime/logging/redact.ts +108 -0
  227. package/src/runtime/logging/runtime.ts +163 -0
  228. package/src/runtime/logging/sudo-bridge.ts +41 -0
  229. package/src/runtime/manifest-data.ts +103 -0
  230. package/src/runtime/manifest-response.ts +95 -0
  231. package/src/runtime/manifest-sections.ts +79 -0
  232. package/src/runtime/manifest-service.ts +83 -0
  233. package/src/runtime/project-config.ts +25 -0
  234. package/src/runtime/project-files.ts +103 -0
  235. package/src/runtime/rate-limit.ts +12 -0
  236. package/src/runtime/revision-service.ts +38 -0
  237. package/src/runtime/sql.ts +24 -0
  238. package/src/runtime/sso.ts +153 -0
  239. package/src/runtime/state.ts +7 -0
  240. package/src/runtime/storage-keys.ts +95 -0
  241. package/src/runtime/storage-target.ts +238 -0
  242. package/src/runtime/system-role.ts +26 -0
  243. package/src/runtime/tasks/boot.ts +49 -0
  244. package/src/runtime/tasks/contracts.ts +77 -0
  245. package/src/runtime/tasks/db-store.ts +191 -0
  246. package/src/runtime/tasks/row-mapping.ts +75 -0
  247. package/src/runtime/tasks/runtime.ts +192 -0
  248. package/src/runtime/tasks/tasks-test-harness.ts +92 -0
  249. package/src/runtime/tenant.ts +15 -0
  250. package/src/runtime/workflows/boot.ts +97 -0
  251. package/src/runtime/workflows/contracts.ts +114 -0
  252. package/src/runtime/workflows/db-store.ts +156 -0
  253. package/src/runtime/workflows/definitions.ts +75 -0
  254. package/src/runtime/workflows/dispatch.ts +148 -0
  255. package/src/runtime/workflows/row-mapping.ts +54 -0
  256. package/src/runtime/workflows/runner.ts +105 -0
  257. package/src/runtime/workflows/runtime.ts +161 -0
  258. package/src/runtime/workflows/steps.ts +74 -0
  259. package/src/runtime/workflows/support.ts +60 -0
  260. package/src/runtime/workflows/transitions.ts +259 -0
  261. package/src/runtime/workflows/workflows-test-harness.ts +238 -0
  262. package/src/session-cookie.ts +69 -0
  263. package/src/storage.ts +173 -0
  264. package/src/types.ts +51 -0
  265. package/src/virtual-ids.ts +18 -0
  266. package/src/virtual-modules.d.ts +53 -0
  267. package/src/vite.ts +175 -0
@@ -0,0 +1,165 @@
1
+ import type { JobDefinition, JobJson, JobListOptions, JobStatus } from "@facilis.dev/core";
2
+ import type { PolicyScopedDatabase } from "@facilis.dev/db";
3
+
4
+ /**
5
+ * Internal contracts of the job runtime (D-107, docs/JOBS.md §9).
6
+ *
7
+ * The engine and the stores both code against this file so the persistence layer can change
8
+ * (Drizzle table, in-memory fallback) without touching scheduling semantics. `StoredJob` uses
9
+ * Date objects; the public `JobRecord` converts them to ISO strings in runtime.ts.
10
+ */
11
+
12
+ /** One job row as the store knows it. */
13
+ export interface StoredJob {
14
+ readonly id: string;
15
+ readonly name: string;
16
+ readonly status: JobStatus;
17
+ readonly input: JobJson;
18
+ readonly output: JobJson | null;
19
+ readonly error: string | null;
20
+ readonly attempts: number;
21
+ readonly maxAttempts: number;
22
+ readonly timeoutMs: number;
23
+ readonly runAt: Date;
24
+ readonly createdAt: Date;
25
+ readonly startedAt: Date | null;
26
+ readonly finishedAt: Date | null;
27
+ }
28
+
29
+ /** What an enqueue writes; the store generates nothing but the id. */
30
+ export interface NewStoredJob {
31
+ readonly id: string;
32
+ readonly name: string;
33
+ readonly input: JobJson;
34
+ readonly maxAttempts: number;
35
+ readonly timeoutMs: number;
36
+ readonly runAt: Date;
37
+ readonly createdAt: Date;
38
+ }
39
+
40
+ /** Terminal outcome of one attempt (the engine retries by calling `requeue` instead). */
41
+ export type JobOutcome =
42
+ | { readonly status: "succeeded"; readonly output: JobJson; readonly finishedAt: Date }
43
+ | { readonly status: "failed"; readonly error: string; readonly finishedAt: Date }
44
+ | {
45
+ readonly status: "cancelled";
46
+ readonly error: string | null;
47
+ readonly finishedAt: Date;
48
+ };
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
+
59
+ /** Normalized `list` filter (the API applies defaults and the 200-row cap). */
60
+ export type StoredJobListOptions = Omit<JobListOptions, "limit"> & {
61
+ readonly limit: number;
62
+ };
63
+
64
+ /**
65
+ * Persistence seam between the engine and a store implementation.
66
+ *
67
+ * `claim` is the only state transition that must be atomic with respect to the queue: it
68
+ * marks due `queued` rows as `running`, increments `attempts` and sets `startedAt`.
69
+ */
70
+ export interface JobStore {
71
+ insert(job: NewStoredJob): Promise<void>;
72
+ get(id: string): Promise<StoredJob | null>;
73
+ list(options: StoredJobListOptions): Promise<StoredJob[]>;
74
+ /** Queued jobs ordered by runAt ascending (the "queue" view). */
75
+ queue(limit?: number): Promise<StoredJob[]>;
76
+ /** Jobs in status "running". */
77
+ running(): Promise<StoredJob[]>;
78
+ /** Atomically claim up to `limit` due jobs for execution. */
79
+ claim(now: Date, limit: number): Promise<StoredJob[]>;
80
+ complete(id: string, outcome: JobOutcome): Promise<void>;
81
+ /** Return a job to "queued" for a retry at `runAt`, retaining the last error. */
82
+ requeue(id: string, options: { readonly runAt: Date; readonly error: string }): Promise<void>;
83
+ /** queued -> cancelled; false when the job is no longer queued. */
84
+ cancelQueued(id: string, finishedAt: Date): Promise<boolean>;
85
+ /** Recover rows left "running" by a crashed process; returns how many were touched. */
86
+ recoverInterrupted(now: Date): Promise<number>;
87
+ counts(): Promise<JobCounts>;
88
+ close(): Promise<void>;
89
+ /**
90
+ * Optional view whose operations join `scope` (the request's policy transaction) instead
91
+ * of opening a new one. PGlite is single-connection: a nested BEGIN would deadlock, so a
92
+ * handler's `ctx.jobs` must reuse the transaction it already runs in (D-107, JOBS §8).
93
+ */
94
+ scoped?(scope: PolicyScopedDatabase): JobStore;
95
+ }
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
+
106
+ /** Clock and scheduling seam, injected so the engine tests are deterministic. */
107
+ export interface JobTimers {
108
+ now(): number;
109
+ setTimeout(fn: () => void, ms: number): unknown;
110
+ clearTimeout(handle: unknown): void;
111
+ }
112
+
113
+ /**
114
+ * Runs one attempt in a system context (wired to `runAsSystem` in executor.ts).
115
+ *
116
+ * The engine owns input/output validation and serialization; the executor owns the system
117
+ * role, the transaction and the audit entry around the definition's `run`.
118
+ */
119
+ export type JobExecutor = (input: {
120
+ readonly definition: JobDefinition<unknown, unknown>;
121
+ readonly data: unknown;
122
+ readonly job: StoredJob;
123
+ readonly signal: AbortSignal;
124
+ }) => Promise<unknown>;
125
+
126
+ export interface JobEngine {
127
+ /** Recovers interrupted rows, then starts ticking until `stop`. Idempotent. */
128
+ start(): Promise<void>;
129
+ /** Stops the ticker, aborts in-flight attempts and requeues them as interrupted. */
130
+ stop(): Promise<void>;
131
+ enqueue(name: string, data: unknown, options?: JobEnqueueOptions): Promise<{ id: string }>;
132
+ get(id: string): Promise<StoredJob | null>;
133
+ list(options?: JobListOptions): Promise<StoredJob[]>;
134
+ queue(): Promise<StoredJob[]>;
135
+ running(): Promise<StoredJob[]>;
136
+ cancel(id: string): Promise<boolean>;
137
+ stats(): Promise<JobCounts>;
138
+ /**
139
+ * Optional view whose queue operations use the store bound to `scope` while sharing this
140
+ * engine's timer and in-flight state. Used to bind `ctx.jobs` to a request transaction.
141
+ */
142
+ scoped?(scope: PolicyScopedDatabase): JobEngine;
143
+ }
144
+
145
+ /** Absolute/relative schedule resolved by the engine (validated by the API layer). */
146
+ export interface JobEnqueueOptions {
147
+ readonly runAt?: Date;
148
+ }
149
+
150
+ export interface JobEngineOptions {
151
+ readonly definitions: ReadonlyMap<string, JobDefinition<unknown, unknown>>;
152
+ readonly store: JobStore;
153
+ readonly config: JobEngineConfig;
154
+ readonly executor: JobExecutor;
155
+ /** Defaults to the process clock and timers. */
156
+ readonly timers?: JobTimers;
157
+ /** Receives unexpected engine-level failures (a store write failing in the tick). */
158
+ readonly onError?: (error: unknown, context: string) => void;
159
+ }
160
+
161
+ /** One scanned definition module: virtual module entry, useful for warning messages. */
162
+ export interface JobModule {
163
+ readonly file: string;
164
+ readonly definition: unknown;
165
+ }
@@ -0,0 +1,98 @@
1
+ // Shared PGlite fixture for the persistent job-store suites (db-store.test.ts and
2
+ // db-store-recovery.test.ts). The suites are split to stay under the 300-line limit; each
3
+ // gets its own in-memory cluster, created from the real drizzle table definition so the
4
+ // store is exercised through the real policies and tenant-column default.
5
+ import { randomUUID } from "node:crypto";
6
+
7
+ import { sql } from "drizzle-orm";
8
+ import { getTableConfig, PgDialect } from "drizzle-orm/pg-core";
9
+
10
+ import type { FacilisDb } from "@facilis.dev/db";
11
+ import {
12
+ createDb,
13
+ ensureAppRole,
14
+ facilisJobs,
15
+ policyCreateSql,
16
+ tenantDefaultSql,
17
+ } from "@facilis.dev/db";
18
+
19
+ import type { NewStoredJob, StoredJob } from "./contracts.ts";
20
+ import { createDbJobStore } from "./db-store.ts";
21
+
22
+ /** Deployment tenant; a second tenant proves the RLS boundary cannot be crossed. */
23
+ export const TENANT_ID = "cccccccc-cccc-cccc-cccc-cccccccccccc";
24
+ export const OTHER_TENANT = "dddddddd-dddd-dddd-dddd-dddddddddddd";
25
+ export const BASE = new Date("2026-11-07T12:00:00.000Z");
26
+ export const FINISHED = new Date("2026-11-07T12:30:00.000Z");
27
+
28
+ export type JobsTestStore = ReturnType<typeof createDbJobStore>;
29
+
30
+ export interface JobsTestContext {
31
+ readonly db: FacilisDb;
32
+ readonly store: JobsTestStore;
33
+ }
34
+
35
+ export async function createJobsTestContext(): Promise<JobsTestContext> {
36
+ const db = await createDb();
37
+ const tenantDefault = new PgDialect().sqlToQuery(tenantDefaultSql()).sql;
38
+ const statements = [
39
+ `CREATE TABLE facilis_jobs (
40
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
41
+ name text NOT NULL,
42
+ status text NOT NULL,
43
+ input jsonb NOT NULL,
44
+ output jsonb,
45
+ error text,
46
+ attempts integer NOT NULL DEFAULT 0,
47
+ max_attempts integer NOT NULL,
48
+ timeout_ms integer NOT NULL,
49
+ run_at timestamptz NOT NULL DEFAULT now(),
50
+ started_at timestamptz,
51
+ finished_at timestamptz,
52
+ created_at timestamptz NOT NULL DEFAULT now(),
53
+ tenant_id uuid NOT NULL DEFAULT ${tenantDefault}
54
+ )`,
55
+ "ALTER TABLE facilis_jobs ENABLE ROW LEVEL SECURITY",
56
+ ...getTableConfig(facilisJobs).policies.map((policy) =>
57
+ policyCreateSql("facilis_jobs", policy),
58
+ ),
59
+ ];
60
+ await db.db.transaction(async (tx) => {
61
+ // eslint-disable-next-line no-await-in-loop -- DDL must run in order on one connection.
62
+ for (const statement of statements) await tx.execute(sql.raw(statement));
63
+ });
64
+ await ensureAppRole(db);
65
+ return { db, store: createDbJobStore({ db, tenantId: TENANT_ID }) };
66
+ }
67
+
68
+ /** Empties the queue as the connecting superuser, so each test starts from a clean slate. */
69
+ export async function clearJobs(db: FacilisDb): Promise<void> {
70
+ await db.db.execute(sql.raw("delete from facilis_jobs"));
71
+ }
72
+
73
+ let sequence = 0;
74
+
75
+ export function newJob(overrides: Partial<NewStoredJob> = {}): NewStoredJob {
76
+ sequence += 1;
77
+ return {
78
+ id: randomUUID(),
79
+ name: "purge",
80
+ input: { olderThanDays: 7 },
81
+ maxAttempts: 3,
82
+ timeoutMs: 10_000,
83
+ runAt: BASE,
84
+ createdAt: new Date(BASE.getTime() + sequence),
85
+ ...overrides,
86
+ };
87
+ }
88
+
89
+ export async function insertAndClaim(
90
+ store: JobsTestStore,
91
+ job: NewStoredJob,
92
+ now = BASE,
93
+ ): Promise<StoredJob> {
94
+ await store.insert(job);
95
+ const [claimed] = await store.claim(now, 1);
96
+ if (claimed === undefined) throw new Error("the job was not claimable");
97
+ return claimed;
98
+ }
@@ -0,0 +1,273 @@
1
+ // The Drizzle-backed job store (D-107, docs/JOBS.md §8).
2
+ //
3
+ // Every operation runs through `runWithPolicyScope`, i.e. as facilis_app with
4
+ // `app.tenant_id` set: a new row's tenant_id comes from the tenantColumn default (the same
5
+ // GUC the restrictive policy reads), and a query cannot reach another tenant's queue. The
6
+ // engine adds the framework queue permissions to its scope (D-145); a request scope carries
7
+ // the user's permissions, which is what makes the RLS policies a second, DB-level gate. The
8
+ // only escalation is the job body itself, behind the executor.
9
+ import { and, asc, count, desc, eq, gte, inArray, lt, lte, sql, type SQL } from "drizzle-orm";
10
+
11
+ import { facilisJobs, runWithPolicyScope } from "@facilis.dev/db";
12
+ import type { FacilisDb, PolicyScopedDatabase } from "@facilis.dev/db";
13
+ import type { JobStatus } from "@facilis.dev/core";
14
+
15
+ import type {
16
+ JobCounts,
17
+ JobOutcome,
18
+ JobStore,
19
+ NewStoredJob,
20
+ StoredJob,
21
+ StoredJobListOptions,
22
+ } from "./contracts.ts";
23
+ import { completionValues, toJobStatus, toStoredJob } from "./row-mapping.ts";
24
+
25
+ /** Recovery marker; the memory store writes the same phrase so a fallback is indistinguishable. */
26
+ const INTERRUPTED_ERROR = "interrupted (recovered after restart)";
27
+
28
+ /**
29
+ * The queue permissions the framework engine uses for its own transactions (D-145). A request
30
+ * transaction carries the session's permissions instead: a route whose user lacks jobs:read/
31
+ * jobs:exec is denied by the RLS policies, not merely by its own wrapper check.
32
+ */
33
+ const FRAMEWORK_QUEUE_PERMISSIONS = ["jobs:read", "jobs:exec"] as const;
34
+
35
+ /**
36
+ * The persistent JobStore over `facilis_jobs`.
37
+ *
38
+ * A missing table is not handled here: boot probes it with `isJobsTableAvailable` and picks
39
+ * the memory store instead, so these methods may throw when the project is not migrated.
40
+ * `tenantId` is the deployment tenant the queue belongs to (the single-tenant fallback
41
+ * unless configured).
42
+ */
43
+ export function createDbJobStore(options: {
44
+ readonly db: FacilisDb;
45
+ readonly tenantId: string;
46
+ /** Request transaction to join (from `JobStore.scoped`); absent for engine-owned work. */
47
+ readonly scope?: PolicyScopedDatabase;
48
+ }): JobStore {
49
+ const { db, tenantId, scope } = options;
50
+
51
+ /**
52
+ * One policy-scoped transaction per store operation; a row's tenant_id comes from the GUC.
53
+ *
54
+ * When a scope is bound (a handler's `ctx.jobs`), the operation joins that request
55
+ * transaction instead: PGlite is single-connection and a nested BEGIN would deadlock the
56
+ * request that is waiting for the queue call to return (D-107, docs/JOBS.md §8).
57
+ */
58
+ function run<T>(fn: (tx: PolicyScopedDatabase) => Promise<T>): Promise<T> {
59
+ return scope === undefined
60
+ ? runWithPolicyScope(db, { tenantId, permissions: [...FRAMEWORK_QUEUE_PERMISSIONS] }, fn)
61
+ : fn(scope);
62
+ }
63
+
64
+ return {
65
+ async insert(job: NewStoredJob): Promise<void> {
66
+ await run((tx) =>
67
+ tx.insert(facilisJobs).values({
68
+ id: job.id,
69
+ name: job.name,
70
+ status: "queued",
71
+ input: job.input,
72
+ maxAttempts: job.maxAttempts,
73
+ timeoutMs: job.timeoutMs,
74
+ runAt: job.runAt,
75
+ createdAt: job.createdAt,
76
+ }),
77
+ );
78
+ },
79
+
80
+ async get(id: string): Promise<StoredJob | null> {
81
+ return run(async (tx) => {
82
+ const rows = await tx.select().from(facilisJobs).where(eq(facilisJobs.id, id)).limit(1);
83
+ const row = rows[0];
84
+ return row === undefined ? null : toStoredJob(row);
85
+ });
86
+ },
87
+
88
+ async list(filters: StoredJobListOptions): Promise<StoredJob[]> {
89
+ return run(async (tx) => {
90
+ const conditions: SQL[] = [];
91
+ if (filters.status !== undefined) {
92
+ conditions.push(
93
+ typeof filters.status === "string"
94
+ ? eq(facilisJobs.status, filters.status)
95
+ : inArray(facilisJobs.status, [...filters.status]),
96
+ );
97
+ }
98
+ if (filters.name !== undefined) conditions.push(eq(facilisJobs.name, filters.name));
99
+ const rows = await tx
100
+ .select()
101
+ .from(facilisJobs)
102
+ .where(and(...conditions))
103
+ .orderBy(desc(facilisJobs.createdAt))
104
+ .limit(filters.limit);
105
+ return rows.map(toStoredJob);
106
+ });
107
+ },
108
+
109
+ async queue(limit?: number): Promise<StoredJob[]> {
110
+ return run(async (tx) => {
111
+ const query = tx
112
+ .select()
113
+ .from(facilisJobs)
114
+ .where(eq(facilisJobs.status, "queued"))
115
+ .orderBy(asc(facilisJobs.runAt), asc(facilisJobs.createdAt));
116
+ const rows = limit === undefined ? await query : await query.limit(limit);
117
+ return rows.map(toStoredJob);
118
+ });
119
+ },
120
+
121
+ async running(): Promise<StoredJob[]> {
122
+ return run(async (tx) => {
123
+ const rows = await tx
124
+ .select()
125
+ .from(facilisJobs)
126
+ .where(eq(facilisJobs.status, "running"))
127
+ .orderBy(asc(facilisJobs.startedAt));
128
+ return rows.map(toStoredJob);
129
+ });
130
+ },
131
+
132
+ async claim(now: Date, limit: number): Promise<StoredJob[]> {
133
+ // Select-then-update in ONE policy-scoped transaction. No SELECT ... SKIP LOCKED: the
134
+ // engine is the only claimer and the runtime assumes a single process per database
135
+ // (docs/JOBS.md §10), so the row cannot be claimed by anyone else between the two
136
+ // statements. The update repeats the queued predicate to stay correct anyway.
137
+ return run(async (tx) => {
138
+ const due = await tx
139
+ .select({ id: facilisJobs.id })
140
+ .from(facilisJobs)
141
+ .where(and(eq(facilisJobs.status, "queued"), lte(facilisJobs.runAt, now)))
142
+ .orderBy(asc(facilisJobs.runAt), asc(facilisJobs.createdAt))
143
+ .limit(limit);
144
+ if (due.length === 0) return [];
145
+ const claimed = await tx
146
+ .update(facilisJobs)
147
+ .set({
148
+ status: "running",
149
+ attempts: sql`${facilisJobs.attempts} + 1`,
150
+ startedAt: now,
151
+ })
152
+ .where(
153
+ and(
154
+ inArray(
155
+ facilisJobs.id,
156
+ due.map((row) => row.id),
157
+ ),
158
+ eq(facilisJobs.status, "queued"),
159
+ ),
160
+ )
161
+ .returning();
162
+ return claimed.map(toStoredJob);
163
+ });
164
+ },
165
+
166
+ async complete(id: string, outcome: JobOutcome): Promise<void> {
167
+ await run((tx) =>
168
+ tx.update(facilisJobs).set(completionValues(outcome)).where(eq(facilisJobs.id, id)),
169
+ );
170
+ },
171
+
172
+ async requeue(
173
+ id: string,
174
+ retry: { readonly runAt: Date; readonly error: string },
175
+ ): Promise<void> {
176
+ await run((tx) =>
177
+ tx
178
+ .update(facilisJobs)
179
+ .set({
180
+ status: "queued",
181
+ runAt: retry.runAt,
182
+ error: retry.error,
183
+ startedAt: null,
184
+ finishedAt: null,
185
+ })
186
+ .where(eq(facilisJobs.id, id)),
187
+ );
188
+ },
189
+
190
+ async cancelQueued(id: string, finishedAt: Date): Promise<boolean> {
191
+ return run(async (tx) => {
192
+ const rows = await tx
193
+ .update(facilisJobs)
194
+ .set({ status: "cancelled", finishedAt })
195
+ .where(and(eq(facilisJobs.id, id), eq(facilisJobs.status, "queued")))
196
+ .returning({ id: facilisJobs.id });
197
+ return rows.length > 0;
198
+ });
199
+ },
200
+
201
+ async recoverInterrupted(now: Date): Promise<number> {
202
+ // Two updates in one scope: an exhausted row cannot be retried, a fresh one can. The
203
+ // attempt counter already covers the attempt that the crash interrupted.
204
+ return run(async (tx) => {
205
+ const failed = await tx
206
+ .update(facilisJobs)
207
+ .set({ status: "failed", error: INTERRUPTED_ERROR, finishedAt: now })
208
+ .where(
209
+ and(
210
+ eq(facilisJobs.status, "running"),
211
+ gte(facilisJobs.attempts, facilisJobs.maxAttempts),
212
+ ),
213
+ )
214
+ .returning({ id: facilisJobs.id });
215
+ const requeued = await tx
216
+ .update(facilisJobs)
217
+ .set({
218
+ status: "queued",
219
+ error: INTERRUPTED_ERROR,
220
+ runAt: now,
221
+ startedAt: null,
222
+ })
223
+ .where(
224
+ and(
225
+ eq(facilisJobs.status, "running"),
226
+ lt(facilisJobs.attempts, facilisJobs.maxAttempts),
227
+ ),
228
+ )
229
+ .returning({ id: facilisJobs.id });
230
+ return failed.length + requeued.length;
231
+ });
232
+ },
233
+
234
+ async counts(): Promise<JobCounts> {
235
+ return run(async (tx) => {
236
+ const rows = await tx
237
+ .select({ status: facilisJobs.status, total: count() })
238
+ .from(facilisJobs)
239
+ .groupBy(facilisJobs.status);
240
+ const counts: Record<JobStatus, number> = {
241
+ queued: 0,
242
+ running: 0,
243
+ succeeded: 0,
244
+ failed: 0,
245
+ cancelled: 0,
246
+ };
247
+ for (const row of rows) counts[toJobStatus(row.status)] = Number(row.total);
248
+ return counts;
249
+ });
250
+ },
251
+
252
+ close(): Promise<void> {
253
+ // The Drizzle client belongs to the process, not to the store; boot owns its lifetime.
254
+ return Promise.resolve();
255
+ },
256
+
257
+ /** Joins queue operations to an existing request transaction (see `run` above). */
258
+ scoped(next: PolicyScopedDatabase): JobStore {
259
+ return createDbJobStore({ db, tenantId, scope: next });
260
+ },
261
+ };
262
+ }
263
+
264
+ /**
265
+ * Probe used by boot to pick persistence. `to_regclass` answers `null` for a missing table
266
+ * instead of raising, which is exactly the "project not migrated yet" case (JOBS.md §8).
267
+ */
268
+ export async function isJobsTableAvailable(db: FacilisDb): Promise<boolean> {
269
+ const result = await db.db.execute(
270
+ sql`select to_regclass('public.facilis_jobs') is not null as available`,
271
+ );
272
+ return result.rows[0]?.["available"] === true;
273
+ }
@@ -0,0 +1,42 @@
1
+ import { isJobDefinition, type JobDefinition, type ManifestWarning } from "@facilis.dev/core";
2
+
3
+ import type { JobModule } from "./contracts.ts";
4
+
5
+ /** The project's job definitions plus the manifest warnings raised while indexing them. */
6
+ export interface JobRegistry {
7
+ readonly definitions: ReadonlyMap<string, JobDefinition<unknown, unknown>>;
8
+ readonly warnings: ManifestWarning[];
9
+ }
10
+
11
+ /**
12
+ * Indexes the modules behind `#facilis/jobs` (docs/JOBS.md §5).
13
+ *
14
+ * An invalid or duplicate definition must never break boot: it becomes a manifest warning
15
+ * and the module (or the later duplicate) is skipped.
16
+ */
17
+ export function buildJobRegistry(modules: readonly JobModule[]): JobRegistry {
18
+ const definitions = new Map<string, JobDefinition<unknown, unknown>>();
19
+ const warnings: ManifestWarning[] = [];
20
+
21
+ for (const module of modules) {
22
+ if (!isJobDefinition(module.definition)) {
23
+ warnings.push({
24
+ code: "job_definition_invalid",
25
+ message: `${module.file} must default-export defineJob({...}); the module was skipped.`,
26
+ sourceFile: module.file,
27
+ });
28
+ continue;
29
+ }
30
+ if (definitions.has(module.definition.name)) {
31
+ warnings.push({
32
+ code: "job_definition_invalid",
33
+ message: `Duplicate job "${module.definition.name}" in ${module.file}; the first definition wins.`,
34
+ sourceFile: module.file,
35
+ });
36
+ continue;
37
+ }
38
+ definitions.set(module.definition.name, module.definition);
39
+ }
40
+
41
+ return { definitions, warnings };
42
+ }
@@ -0,0 +1,44 @@
1
+ import type { JobTimers } from "./contracts.ts";
2
+
3
+ /**
4
+ * Small helpers shared by the scheduler and its view (D-107, docs/JOBS.md §7).
5
+ *
6
+ * Split out of engine.ts to keep the scheduler under the 300-line gate; none of this needs
7
+ * the engine's closure state.
8
+ */
9
+
10
+ /** Default process clock/timers; tests inject a deterministic implementation instead. */
11
+ export const SYSTEM_TIMERS: JobTimers = {
12
+ now: () => Date.now(),
13
+ setTimeout: (fn, ms) => setTimeout(fn, ms),
14
+ clearTimeout: (handle) => clearTimeout(handle as ReturnType<typeof setTimeout>),
15
+ };
16
+
17
+ export const DEFAULT_LIST_LIMIT = 50;
18
+ export const MAX_LIST_LIMIT = 200;
19
+ /** Stored errors are diagnostics, not a log: bound what a runaway failure can persist. */
20
+ export const MAX_STORED_ERROR = 2000;
21
+ export const INTERRUPTED_ERROR = "interrupted";
22
+
23
+ type ValidationIssues = readonly {
24
+ readonly path: readonly PropertyKey[];
25
+ readonly message: string;
26
+ }[];
27
+
28
+ export function formatIssues(issues: ValidationIssues): string {
29
+ return issues
30
+ .map(({ path, message }) =>
31
+ path.length === 0 ? message : `${path.map(String).join(".")}: ${message}`,
32
+ )
33
+ .join("; ");
34
+ }
35
+
36
+ export function errorMessage(error: unknown): string {
37
+ if (error instanceof Error && error.message.length > 0) return error.message;
38
+ return typeof error === "string" && error.length > 0 ? error : "Job attempt failed.";
39
+ }
40
+
41
+ export function normalizeLimit(limit: number | undefined): number {
42
+ if (limit === undefined || !Number.isFinite(limit)) return DEFAULT_LIST_LIMIT;
43
+ return Math.max(0, Math.min(MAX_LIST_LIMIT, Math.trunc(limit)));
44
+ }