@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,210 @@
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 } from "drizzle-orm";
10
+ import { facilisJobs, runWithPolicyScope } from "@facilis.dev/db";
11
+ import { completionValues, toJobStatus, toStoredJob } from "./row-mapping.js";
12
+ /** Recovery marker; the memory store writes the same phrase so a fallback is indistinguishable. */
13
+ const INTERRUPTED_ERROR = "interrupted (recovered after restart)";
14
+ /**
15
+ * The queue permissions the framework engine uses for its own transactions (D-145). A request
16
+ * transaction carries the session's permissions instead: a route whose user lacks jobs:read/
17
+ * jobs:exec is denied by the RLS policies, not merely by its own wrapper check.
18
+ */
19
+ const FRAMEWORK_QUEUE_PERMISSIONS = ["jobs:read", "jobs:exec"];
20
+ /**
21
+ * The persistent JobStore over `facilis_jobs`.
22
+ *
23
+ * A missing table is not handled here: boot probes it with `isJobsTableAvailable` and picks
24
+ * the memory store instead, so these methods may throw when the project is not migrated.
25
+ * `tenantId` is the deployment tenant the queue belongs to (the single-tenant fallback
26
+ * unless configured).
27
+ */
28
+ export function createDbJobStore(options) {
29
+ const { db, tenantId, scope } = options;
30
+ /**
31
+ * One policy-scoped transaction per store operation; a row's tenant_id comes from the GUC.
32
+ *
33
+ * When a scope is bound (a handler's `ctx.jobs`), the operation joins that request
34
+ * transaction instead: PGlite is single-connection and a nested BEGIN would deadlock the
35
+ * request that is waiting for the queue call to return (D-107, docs/JOBS.md §8).
36
+ */
37
+ function run(fn) {
38
+ return scope === undefined
39
+ ? runWithPolicyScope(db, { tenantId, permissions: [...FRAMEWORK_QUEUE_PERMISSIONS] }, fn)
40
+ : fn(scope);
41
+ }
42
+ return {
43
+ async insert(job) {
44
+ await run((tx) => tx.insert(facilisJobs).values({
45
+ id: job.id,
46
+ name: job.name,
47
+ status: "queued",
48
+ input: job.input,
49
+ maxAttempts: job.maxAttempts,
50
+ timeoutMs: job.timeoutMs,
51
+ runAt: job.runAt,
52
+ createdAt: job.createdAt,
53
+ }));
54
+ },
55
+ async get(id) {
56
+ return run(async (tx) => {
57
+ const rows = await tx.select().from(facilisJobs).where(eq(facilisJobs.id, id)).limit(1);
58
+ const row = rows[0];
59
+ return row === undefined ? null : toStoredJob(row);
60
+ });
61
+ },
62
+ async list(filters) {
63
+ return run(async (tx) => {
64
+ const conditions = [];
65
+ if (filters.status !== undefined) {
66
+ conditions.push(typeof filters.status === "string"
67
+ ? eq(facilisJobs.status, filters.status)
68
+ : inArray(facilisJobs.status, [...filters.status]));
69
+ }
70
+ if (filters.name !== undefined)
71
+ conditions.push(eq(facilisJobs.name, filters.name));
72
+ const rows = await tx
73
+ .select()
74
+ .from(facilisJobs)
75
+ .where(and(...conditions))
76
+ .orderBy(desc(facilisJobs.createdAt))
77
+ .limit(filters.limit);
78
+ return rows.map(toStoredJob);
79
+ });
80
+ },
81
+ async queue(limit) {
82
+ return run(async (tx) => {
83
+ const query = tx
84
+ .select()
85
+ .from(facilisJobs)
86
+ .where(eq(facilisJobs.status, "queued"))
87
+ .orderBy(asc(facilisJobs.runAt), asc(facilisJobs.createdAt));
88
+ const rows = limit === undefined ? await query : await query.limit(limit);
89
+ return rows.map(toStoredJob);
90
+ });
91
+ },
92
+ async running() {
93
+ return run(async (tx) => {
94
+ const rows = await tx
95
+ .select()
96
+ .from(facilisJobs)
97
+ .where(eq(facilisJobs.status, "running"))
98
+ .orderBy(asc(facilisJobs.startedAt));
99
+ return rows.map(toStoredJob);
100
+ });
101
+ },
102
+ async claim(now, limit) {
103
+ // Select-then-update in ONE policy-scoped transaction. No SELECT ... SKIP LOCKED: the
104
+ // engine is the only claimer and the runtime assumes a single process per database
105
+ // (docs/JOBS.md §10), so the row cannot be claimed by anyone else between the two
106
+ // statements. The update repeats the queued predicate to stay correct anyway.
107
+ return run(async (tx) => {
108
+ const due = await tx
109
+ .select({ id: facilisJobs.id })
110
+ .from(facilisJobs)
111
+ .where(and(eq(facilisJobs.status, "queued"), lte(facilisJobs.runAt, now)))
112
+ .orderBy(asc(facilisJobs.runAt), asc(facilisJobs.createdAt))
113
+ .limit(limit);
114
+ if (due.length === 0)
115
+ return [];
116
+ const claimed = await tx
117
+ .update(facilisJobs)
118
+ .set({
119
+ status: "running",
120
+ attempts: sql `${facilisJobs.attempts} + 1`,
121
+ startedAt: now,
122
+ })
123
+ .where(and(inArray(facilisJobs.id, due.map((row) => row.id)), eq(facilisJobs.status, "queued")))
124
+ .returning();
125
+ return claimed.map(toStoredJob);
126
+ });
127
+ },
128
+ async complete(id, outcome) {
129
+ await run((tx) => tx.update(facilisJobs).set(completionValues(outcome)).where(eq(facilisJobs.id, id)));
130
+ },
131
+ async requeue(id, retry) {
132
+ await run((tx) => tx
133
+ .update(facilisJobs)
134
+ .set({
135
+ status: "queued",
136
+ runAt: retry.runAt,
137
+ error: retry.error,
138
+ startedAt: null,
139
+ finishedAt: null,
140
+ })
141
+ .where(eq(facilisJobs.id, id)));
142
+ },
143
+ async cancelQueued(id, finishedAt) {
144
+ return run(async (tx) => {
145
+ const rows = await tx
146
+ .update(facilisJobs)
147
+ .set({ status: "cancelled", finishedAt })
148
+ .where(and(eq(facilisJobs.id, id), eq(facilisJobs.status, "queued")))
149
+ .returning({ id: facilisJobs.id });
150
+ return rows.length > 0;
151
+ });
152
+ },
153
+ async recoverInterrupted(now) {
154
+ // Two updates in one scope: an exhausted row cannot be retried, a fresh one can. The
155
+ // attempt counter already covers the attempt that the crash interrupted.
156
+ return run(async (tx) => {
157
+ const failed = await tx
158
+ .update(facilisJobs)
159
+ .set({ status: "failed", error: INTERRUPTED_ERROR, finishedAt: now })
160
+ .where(and(eq(facilisJobs.status, "running"), gte(facilisJobs.attempts, facilisJobs.maxAttempts)))
161
+ .returning({ id: facilisJobs.id });
162
+ const requeued = await tx
163
+ .update(facilisJobs)
164
+ .set({
165
+ status: "queued",
166
+ error: INTERRUPTED_ERROR,
167
+ runAt: now,
168
+ startedAt: null,
169
+ })
170
+ .where(and(eq(facilisJobs.status, "running"), lt(facilisJobs.attempts, facilisJobs.maxAttempts)))
171
+ .returning({ id: facilisJobs.id });
172
+ return failed.length + requeued.length;
173
+ });
174
+ },
175
+ async counts() {
176
+ return run(async (tx) => {
177
+ const rows = await tx
178
+ .select({ status: facilisJobs.status, total: count() })
179
+ .from(facilisJobs)
180
+ .groupBy(facilisJobs.status);
181
+ const counts = {
182
+ queued: 0,
183
+ running: 0,
184
+ succeeded: 0,
185
+ failed: 0,
186
+ cancelled: 0,
187
+ };
188
+ for (const row of rows)
189
+ counts[toJobStatus(row.status)] = Number(row.total);
190
+ return counts;
191
+ });
192
+ },
193
+ close() {
194
+ // The Drizzle client belongs to the process, not to the store; boot owns its lifetime.
195
+ return Promise.resolve();
196
+ },
197
+ /** Joins queue operations to an existing request transaction (see `run` above). */
198
+ scoped(next) {
199
+ return createDbJobStore({ db, tenantId, scope: next });
200
+ },
201
+ };
202
+ }
203
+ /**
204
+ * Probe used by boot to pick persistence. `to_regclass` answers `null` for a missing table
205
+ * instead of raising, which is exactly the "project not migrated yet" case (JOBS.md §8).
206
+ */
207
+ export async function isJobsTableAvailable(db) {
208
+ const result = await db.db.execute(sql `select to_regclass('public.facilis_jobs') is not null as available`);
209
+ return result.rows[0]?.["available"] === true;
210
+ }
@@ -0,0 +1,14 @@
1
+ import { type JobDefinition, type ManifestWarning } from "@facilis.dev/core";
2
+ import type { JobModule } from "./contracts.js";
3
+ /** The project's job definitions plus the manifest warnings raised while indexing them. */
4
+ export interface JobRegistry {
5
+ readonly definitions: ReadonlyMap<string, JobDefinition<unknown, unknown>>;
6
+ readonly warnings: ManifestWarning[];
7
+ }
8
+ /**
9
+ * Indexes the modules behind `#facilis/jobs` (docs/JOBS.md §5).
10
+ *
11
+ * An invalid or duplicate definition must never break boot: it becomes a manifest warning
12
+ * and the module (or the later duplicate) is skipped.
13
+ */
14
+ export declare function buildJobRegistry(modules: readonly JobModule[]): JobRegistry;
@@ -0,0 +1,31 @@
1
+ import { isJobDefinition } from "@facilis.dev/core";
2
+ /**
3
+ * Indexes the modules behind `#facilis/jobs` (docs/JOBS.md §5).
4
+ *
5
+ * An invalid or duplicate definition must never break boot: it becomes a manifest warning
6
+ * and the module (or the later duplicate) is skipped.
7
+ */
8
+ export function buildJobRegistry(modules) {
9
+ const definitions = new Map();
10
+ const warnings = [];
11
+ for (const module of modules) {
12
+ if (!isJobDefinition(module.definition)) {
13
+ warnings.push({
14
+ code: "job_definition_invalid",
15
+ message: `${module.file} must default-export defineJob({...}); the module was skipped.`,
16
+ sourceFile: module.file,
17
+ });
18
+ continue;
19
+ }
20
+ if (definitions.has(module.definition.name)) {
21
+ warnings.push({
22
+ code: "job_definition_invalid",
23
+ message: `Duplicate job "${module.definition.name}" in ${module.file}; the first definition wins.`,
24
+ sourceFile: module.file,
25
+ });
26
+ continue;
27
+ }
28
+ definitions.set(module.definition.name, module.definition);
29
+ }
30
+ return { definitions, warnings };
31
+ }
@@ -0,0 +1,22 @@
1
+ import type { JobTimers } from "./contracts.js";
2
+ /**
3
+ * Small helpers shared by the scheduler and its view (D-107, docs/JOBS.md §7).
4
+ *
5
+ * Split out of engine.ts to keep the scheduler under the 300-line gate; none of this needs
6
+ * the engine's closure state.
7
+ */
8
+ /** Default process clock/timers; tests inject a deterministic implementation instead. */
9
+ export declare const SYSTEM_TIMERS: JobTimers;
10
+ export declare const DEFAULT_LIST_LIMIT = 50;
11
+ export declare const MAX_LIST_LIMIT = 200;
12
+ /** Stored errors are diagnostics, not a log: bound what a runaway failure can persist. */
13
+ export declare const MAX_STORED_ERROR = 2000;
14
+ export declare const INTERRUPTED_ERROR = "interrupted";
15
+ type ValidationIssues = readonly {
16
+ readonly path: readonly PropertyKey[];
17
+ readonly message: string;
18
+ }[];
19
+ export declare function formatIssues(issues: ValidationIssues): string;
20
+ export declare function errorMessage(error: unknown): string;
21
+ export declare function normalizeLimit(limit: number | undefined): number;
22
+ export {};
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Small helpers shared by the scheduler and its view (D-107, docs/JOBS.md §7).
3
+ *
4
+ * Split out of engine.ts to keep the scheduler under the 300-line gate; none of this needs
5
+ * the engine's closure state.
6
+ */
7
+ /** Default process clock/timers; tests inject a deterministic implementation instead. */
8
+ export const SYSTEM_TIMERS = {
9
+ now: () => Date.now(),
10
+ setTimeout: (fn, ms) => setTimeout(fn, ms),
11
+ clearTimeout: (handle) => clearTimeout(handle),
12
+ };
13
+ export const DEFAULT_LIST_LIMIT = 50;
14
+ export const MAX_LIST_LIMIT = 200;
15
+ /** Stored errors are diagnostics, not a log: bound what a runaway failure can persist. */
16
+ export const MAX_STORED_ERROR = 2000;
17
+ export const INTERRUPTED_ERROR = "interrupted";
18
+ export function formatIssues(issues) {
19
+ return issues
20
+ .map(({ path, message }) => path.length === 0 ? message : `${path.map(String).join(".")}: ${message}`)
21
+ .join("; ");
22
+ }
23
+ export function errorMessage(error) {
24
+ if (error instanceof Error && error.message.length > 0)
25
+ return error.message;
26
+ return typeof error === "string" && error.length > 0 ? error : "Job attempt failed.";
27
+ }
28
+ export function normalizeLimit(limit) {
29
+ if (limit === undefined || !Number.isFinite(limit))
30
+ return DEFAULT_LIST_LIMIT;
31
+ return Math.max(0, Math.min(MAX_LIST_LIMIT, Math.trunc(limit)));
32
+ }
@@ -0,0 +1,6 @@
1
+ import type { JobEngine, JobEngineOptions } from "./contracts.js";
2
+ /**
3
+ * The scheduler (docs/JOBS.md §7): claims due jobs, runs at most `maxConcurrent` attempts,
4
+ * applies retry/timeout/cancel and delegates all state to the injected `JobStore`.
5
+ */
6
+ export declare function createJobEngine(options: JobEngineOptions): JobEngine;
@@ -0,0 +1,261 @@
1
+ import { JobError, serializeJobData } from "@facilis.dev/core";
2
+ import { TableAccessError } from "@facilis.dev/db";
3
+ import { errorMessage, formatIssues, INTERRUPTED_ERROR, MAX_STORED_ERROR, normalizeLimit, SYSTEM_TIMERS, } from "./engine-support.js";
4
+ /**
5
+ * The scheduler (docs/JOBS.md §7): claims due jobs, runs at most `maxConcurrent` attempts,
6
+ * applies retry/timeout/cancel and delegates all state to the injected `JobStore`.
7
+ */
8
+ export function createJobEngine(options) {
9
+ const { definitions, store, config, executor } = options;
10
+ const timers = options.timers ?? SYSTEM_TIMERS;
11
+ const report = (error, context) => options.onError?.(error, context);
12
+ const running = new Map();
13
+ const attempts = new Set();
14
+ let started = false;
15
+ let stopping = false;
16
+ let stopped = false;
17
+ let tickRunning = false;
18
+ let wakeRequested = false;
19
+ let tickTimer = null;
20
+ let stopPromise = null;
21
+ const now = () => new Date(timers.now());
22
+ function scheduleTick(delayMs) {
23
+ if (!started || stopping)
24
+ return;
25
+ if (tickTimer !== null)
26
+ timers.clearTimeout(tickTimer);
27
+ tickTimer = timers.setTimeout(() => {
28
+ tickTimer = null;
29
+ void tick().catch(() => undefined);
30
+ }, delayMs);
31
+ }
32
+ /** Enqueue and attempt settlement ask for an immediate tick; a running tick defers to it. */
33
+ function requestTick(delayMs) {
34
+ if (!started || stopping)
35
+ return;
36
+ if (tickRunning) {
37
+ wakeRequested = true;
38
+ return;
39
+ }
40
+ scheduleTick(delayMs);
41
+ }
42
+ async function tick() {
43
+ if (!started || stopping || tickRunning)
44
+ return;
45
+ tickRunning = true;
46
+ try {
47
+ const free = config.maxConcurrent - running.size;
48
+ if (free <= 0)
49
+ return;
50
+ const claimed = await store.claim(now(), free);
51
+ // A stop() racing the claim must not start work the caller is shutting down.
52
+ if (stopping) {
53
+ await Promise.all(claimed.map((job) => interrupt(job)));
54
+ return;
55
+ }
56
+ for (const job of claimed)
57
+ launch(job);
58
+ }
59
+ catch (error) {
60
+ report(error, "engine.tick");
61
+ }
62
+ finally {
63
+ tickRunning = false;
64
+ if (started && !stopping) {
65
+ const immediate = wakeRequested;
66
+ wakeRequested = false;
67
+ scheduleTick(immediate ? 0 : config.pollIntervalMs);
68
+ }
69
+ }
70
+ }
71
+ async function interrupt(job) {
72
+ const finishedAt = now();
73
+ if (job.attempts >= job.maxAttempts) {
74
+ await store.complete(job.id, { status: "failed", error: INTERRUPTED_ERROR, finishedAt });
75
+ return;
76
+ }
77
+ await store.requeue(job.id, { runAt: finishedAt, error: INTERRUPTED_ERROR });
78
+ }
79
+ function launch(job) {
80
+ const attempt = { controller: new AbortController(), cancelRequested: false };
81
+ running.set(job.id, attempt);
82
+ const promise = runAttempt(job, attempt)
83
+ .catch((error) => report(error, `engine.attempt:${job.id}`))
84
+ .finally(() => {
85
+ running.delete(job.id);
86
+ requestTick(0);
87
+ });
88
+ attempts.add(promise);
89
+ void promise.finally(() => attempts.delete(promise)).catch(() => undefined);
90
+ }
91
+ async function runAttempt(job, attempt) {
92
+ const definition = definitions.get(job.name);
93
+ const outcome = definition === undefined
94
+ ? { ok: false, error: `Job "${job.name}" has no definition in this project.` }
95
+ : await executeAttempt(job, attempt, definition);
96
+ // Cancellation wins over a late result: once the caller asked the job to stop, its output
97
+ // is not trusted (docs/JOBS.md §6).
98
+ if (attempt.cancelRequested) {
99
+ await store.complete(job.id, { status: "cancelled", error: null, finishedAt: now() });
100
+ return;
101
+ }
102
+ if (outcome.ok) {
103
+ await store.complete(job.id, {
104
+ status: "succeeded",
105
+ output: outcome.output,
106
+ finishedAt: now(),
107
+ });
108
+ return;
109
+ }
110
+ if (outcome.terminal === true) {
111
+ // Retrying cannot fix a declaration the definition does not carry: store the stable
112
+ // code as the error and never the relation name the guard refused (D-157).
113
+ await store.complete(job.id, { status: "failed", error: outcome.error, finishedAt: now() });
114
+ return;
115
+ }
116
+ if (stopping)
117
+ return interrupt(job);
118
+ const error = outcome.error.length > MAX_STORED_ERROR
119
+ ? outcome.error.slice(0, MAX_STORED_ERROR)
120
+ : outcome.error;
121
+ if (job.attempts < job.maxAttempts) {
122
+ await store.requeue(job.id, { runAt: new Date(timers.now() + config.retryDelayMs), error });
123
+ return;
124
+ }
125
+ await store.complete(job.id, { status: "failed", error, finishedAt: now() });
126
+ }
127
+ async function executeAttempt(job, attempt, definition) {
128
+ const parsedInput = definition.input.safeParse(job.input);
129
+ if (!parsedInput.success)
130
+ return { ok: false, error: formatIssues(parsedInput.error.issues) };
131
+ const controller = attempt.controller;
132
+ let timedOut = false;
133
+ let timeoutHandle = null;
134
+ const abort = () => controller.abort();
135
+ const timeout = new Promise((_, reject) => {
136
+ timeoutHandle = timers.setTimeout(() => {
137
+ timedOut = true;
138
+ // The signal is the contract, not a kill: the engine moves on even if the job ignores it.
139
+ abort();
140
+ reject(new Error("timeout"));
141
+ }, job.timeoutMs);
142
+ });
143
+ const aborted = new Promise((_, reject) => {
144
+ controller.signal.addEventListener("abort", () => reject(new Error("aborted")), {
145
+ once: true,
146
+ });
147
+ });
148
+ try {
149
+ const raw = await Promise.race([
150
+ Promise.resolve(executor({ definition, data: parsedInput.data, job, signal: controller.signal })),
151
+ timeout,
152
+ aborted,
153
+ ]);
154
+ const parsedOutput = definition.output.safeParse(raw);
155
+ if (!parsedOutput.success)
156
+ return { ok: false, error: formatIssues(parsedOutput.error.issues) };
157
+ return { ok: true, output: serializeJobData(parsedOutput.data, "job_invalid_output") };
158
+ }
159
+ catch (error) {
160
+ if (timedOut)
161
+ return { ok: false, error: `timeout after ${job.timeoutMs}ms` };
162
+ if (error instanceof TableAccessError) {
163
+ return { ok: false, error: error.code, terminal: true };
164
+ }
165
+ return { ok: false, error: errorMessage(error) };
166
+ }
167
+ finally {
168
+ if (timeoutHandle !== null)
169
+ timers.clearTimeout(timeoutHandle);
170
+ }
171
+ }
172
+ async function enqueue(name, data, enqueueOptions, target) {
173
+ // stop() is terminal (the boot owns the lifecycle), so this is a caller bug, not a
174
+ // job-contract violation and therefore not a JobError code.
175
+ if (stopping || stopped)
176
+ throw new Error("The job engine is stopped.");
177
+ const definition = definitions.get(name);
178
+ if (definition === undefined) {
179
+ throw new JobError("job_unknown", `Job "${name}" is not defined by this project.`);
180
+ }
181
+ const parsed = definition.input.safeParse(data);
182
+ if (!parsed.success)
183
+ throw new JobError("job_invalid_input", formatIssues(parsed.error.issues));
184
+ const createdAt = now();
185
+ const id = crypto.randomUUID();
186
+ await target.insert({
187
+ id,
188
+ name,
189
+ input: serializeJobData(parsed.data, "job_invalid_input"),
190
+ maxAttempts: definition.maxAttempts ?? config.maxAttempts,
191
+ timeoutMs: definition.timeoutMs ?? config.timeoutMs,
192
+ runAt: enqueueOptions?.runAt ?? createdAt,
193
+ createdAt,
194
+ });
195
+ requestTick(0);
196
+ return { id };
197
+ }
198
+ async function cancel(id, target) {
199
+ const job = await target.get(id);
200
+ if (job === null)
201
+ return false;
202
+ if (job.status === "queued")
203
+ return target.cancelQueued(id, now());
204
+ if (job.status !== "running")
205
+ return false;
206
+ const attempt = running.get(id);
207
+ if (attempt === undefined)
208
+ return false;
209
+ attempt.cancelRequested = true;
210
+ attempt.controller.abort();
211
+ return true;
212
+ }
213
+ function start() {
214
+ if (started || stopped)
215
+ return Promise.resolve();
216
+ started = true;
217
+ return store
218
+ .recoverInterrupted(now())
219
+ .catch((error) => report(error, "engine.start"))
220
+ .then(() => {
221
+ scheduleTick(0);
222
+ });
223
+ }
224
+ function stop() {
225
+ stopPromise ??= (async () => {
226
+ if (!started)
227
+ return;
228
+ stopping = true;
229
+ started = false;
230
+ stopped = true;
231
+ if (tickTimer !== null) {
232
+ timers.clearTimeout(tickTimer);
233
+ tickTimer = null;
234
+ }
235
+ for (const attempt of running.values())
236
+ attempt.controller.abort();
237
+ await Promise.all(attempts);
238
+ wakeRequested = false;
239
+ })();
240
+ return stopPromise;
241
+ }
242
+ /** One engine surface over one store view; timer and in-flight state stay shared. */
243
+ function createView(target) {
244
+ return {
245
+ start,
246
+ stop,
247
+ enqueue: (name, data, enqueueOptions) => enqueue(name, data, enqueueOptions, target),
248
+ get: (id) => target.get(id),
249
+ list: (listOptions) => target.list({ ...listOptions, limit: normalizeLimit(listOptions?.limit) }),
250
+ queue: () => target.queue(),
251
+ running: () => target.running(),
252
+ cancel: (id) => cancel(id, target),
253
+ stats: async () => target.counts(),
254
+ };
255
+ }
256
+ const engine = createView(store);
257
+ // A handler's ctx.jobs is bound to the request transaction: queue operations must join it
258
+ // (PGlite single connection), while the scheduler keeps the base store for its own ticks.
259
+ engine.scoped = (scope) => createView(store.scoped?.(scope) ?? store);
260
+ return engine;
261
+ }
@@ -0,0 +1,11 @@
1
+ import type { FacilisDb } from "@facilis.dev/db";
2
+ import type { JobExecutor } from "./contracts.js";
3
+ /**
4
+ * Runs every job attempt in a system context (D-107, docs/JOBS.md §5/§7).
5
+ *
6
+ * The engine owns scheduling and input/output validation; this adapter owns the security
7
+ * boundary: each attempt is its own transaction as `facilis_system`, audited like a route's
8
+ * sudo and guarded by the job's `dbTables` declaration (D-157), so a job body never sees a
9
+ * policy-free client, the declaration is enforced and the trail names the job.
10
+ */
11
+ export declare function createSystemJobExecutor(db: FacilisDb): JobExecutor;
@@ -0,0 +1,27 @@
1
+ import { runAsSystem } from "@facilis.dev/db";
2
+ /**
3
+ * Runs every job attempt in a system context (D-107, docs/JOBS.md §5/§7).
4
+ *
5
+ * The engine owns scheduling and input/output validation; this adapter owns the security
6
+ * boundary: each attempt is its own transaction as `facilis_system`, audited like a route's
7
+ * sudo and guarded by the job's `dbTables` declaration (D-157), so a job body never sees a
8
+ * policy-free client, the declaration is enforced and the trail names the job.
9
+ */
10
+ export function createSystemJobExecutor(db) {
11
+ return async ({ definition, data, job, signal }) => runAsSystem(db, {
12
+ actor: `system:job:${definition.name}`,
13
+ operation: `jobs:${definition.name}`,
14
+ reason: `Background job "${definition.name}" (attempt ${job.attempts})`,
15
+ // The declaration is required (possibly empty) and enforced inside the elevation: an
16
+ // undeclared relation fails closed instead of being audited after the fact (D-157).
17
+ dbTables: definition.dbTables,
18
+ rawSql: definition.rawSql === true,
19
+ }, async (systemDb) => definition.run({
20
+ jobId: job.id,
21
+ name: definition.name,
22
+ attempt: job.attempts,
23
+ data,
24
+ signal,
25
+ db: systemDb,
26
+ }));
27
+ }
@@ -0,0 +1,7 @@
1
+ import type { JobStore } from "./contracts.js";
2
+ /**
3
+ * The in-memory queue: used when `jobs.persist` is false, or when the project has not
4
+ * migrated `facilis_jobs` yet. Work is lost across a reload, which is why persistence is
5
+ * the default (docs/JOBS.md §8).
6
+ */
7
+ export declare function createMemoryJobStore(): JobStore;