@pattern-stack/codegen 0.15.0 → 0.15.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.
Files changed (562) hide show
  1. package/CHANGELOG.md +111 -0
  2. package/dist/chunk-24CWKBK5.js +94 -0
  3. package/dist/chunk-24CWKBK5.js.map +1 -0
  4. package/dist/chunk-2E224ZSN.js +20 -0
  5. package/dist/chunk-2E224ZSN.js.map +1 -0
  6. package/dist/chunk-2FTZLDBP.js +179 -0
  7. package/dist/chunk-2FTZLDBP.js.map +1 -0
  8. package/dist/chunk-2N4UG4VD.js +20 -0
  9. package/dist/chunk-2N4UG4VD.js.map +1 -0
  10. package/dist/chunk-2TVVBC53.js +92 -0
  11. package/dist/chunk-2TVVBC53.js.map +1 -0
  12. package/dist/chunk-2VHZ7EKC.js +37 -0
  13. package/dist/chunk-2VHZ7EKC.js.map +1 -0
  14. package/dist/chunk-32BMMV4H.js +109 -0
  15. package/dist/chunk-32BMMV4H.js.map +1 -0
  16. package/dist/chunk-32DOFN3T.js +4042 -0
  17. package/dist/chunk-32DOFN3T.js.map +1 -0
  18. package/dist/chunk-36U5UGIO.js +107 -0
  19. package/dist/chunk-36U5UGIO.js.map +1 -0
  20. package/dist/chunk-3CJFPU6Q.js +14 -0
  21. package/dist/chunk-3CJFPU6Q.js.map +1 -0
  22. package/dist/chunk-3NMCDN7L.js +90 -0
  23. package/dist/chunk-3NMCDN7L.js.map +1 -0
  24. package/dist/chunk-3SZFUTXE.js +62 -0
  25. package/dist/chunk-3SZFUTXE.js.map +1 -0
  26. package/dist/chunk-4DOJBQTP.js +117 -0
  27. package/dist/chunk-4DOJBQTP.js.map +1 -0
  28. package/dist/chunk-4JLJYWJC.js +308 -0
  29. package/dist/chunk-4JLJYWJC.js.map +1 -0
  30. package/dist/chunk-4KNXX6TI.js +29 -0
  31. package/dist/chunk-4KNXX6TI.js.map +1 -0
  32. package/dist/chunk-4LH67P4U.js +17 -0
  33. package/dist/chunk-4LH67P4U.js.map +1 -0
  34. package/dist/chunk-4MVGAMUA.js +40 -0
  35. package/dist/chunk-4MVGAMUA.js.map +1 -0
  36. package/dist/chunk-4OMHBMZJ.js +75 -0
  37. package/dist/chunk-4OMHBMZJ.js.map +1 -0
  38. package/dist/chunk-4RFHUZXU.js +635 -0
  39. package/dist/chunk-4RFHUZXU.js.map +1 -0
  40. package/dist/chunk-5A432NZJ.js +7 -0
  41. package/dist/chunk-5A432NZJ.js.map +1 -0
  42. package/dist/chunk-5Y7W3XR6.js +356 -0
  43. package/dist/chunk-5Y7W3XR6.js.map +1 -0
  44. package/dist/chunk-6DWFJNIK.js +15 -0
  45. package/dist/chunk-6DWFJNIK.js.map +1 -0
  46. package/dist/chunk-6I7ULIN6.js +15 -0
  47. package/dist/chunk-6I7ULIN6.js.map +1 -0
  48. package/dist/chunk-6XY6ZMMD.js +25 -0
  49. package/dist/chunk-6XY6ZMMD.js.map +1 -0
  50. package/dist/chunk-7B3RYX45.js +63 -0
  51. package/dist/chunk-7B3RYX45.js.map +1 -0
  52. package/dist/chunk-7C3FOSDI.js +1 -0
  53. package/dist/chunk-7C3FOSDI.js.map +1 -0
  54. package/dist/chunk-7KOW6PU6.js +59 -0
  55. package/dist/chunk-7KOW6PU6.js.map +1 -0
  56. package/dist/chunk-7LKAMLV4.js +92 -0
  57. package/dist/chunk-7LKAMLV4.js.map +1 -0
  58. package/dist/chunk-7RELQJIN.js +22 -0
  59. package/dist/chunk-7RELQJIN.js.map +1 -0
  60. package/dist/chunk-AHV4GDYM.js +63 -0
  61. package/dist/chunk-AHV4GDYM.js.map +1 -0
  62. package/dist/chunk-AQFQ4BYM.js +81 -0
  63. package/dist/chunk-AQFQ4BYM.js.map +1 -0
  64. package/dist/chunk-AS3NAZB6.js +14 -0
  65. package/dist/chunk-AS3NAZB6.js.map +1 -0
  66. package/dist/chunk-BGULBWKJ.js +88 -0
  67. package/dist/chunk-BGULBWKJ.js.map +1 -0
  68. package/dist/chunk-BIO6F7YI.js +17 -0
  69. package/dist/chunk-BIO6F7YI.js.map +1 -0
  70. package/dist/chunk-BOPZWRJK.js +36 -0
  71. package/dist/chunk-BOPZWRJK.js.map +1 -0
  72. package/dist/chunk-BPARRK6F.js +14 -0
  73. package/dist/chunk-BPARRK6F.js.map +1 -0
  74. package/dist/chunk-CO6LUM72.js +59 -0
  75. package/dist/chunk-CO6LUM72.js.map +1 -0
  76. package/dist/chunk-COGHTKXY.js +84 -0
  77. package/dist/chunk-COGHTKXY.js.map +1 -0
  78. package/dist/chunk-DCCZB4UC.js +100 -0
  79. package/dist/chunk-DCCZB4UC.js.map +1 -0
  80. package/dist/chunk-DKKFTHHI.js +53 -0
  81. package/dist/chunk-DKKFTHHI.js.map +1 -0
  82. package/dist/chunk-DV4RV2DC.js +59 -0
  83. package/dist/chunk-DV4RV2DC.js.map +1 -0
  84. package/dist/chunk-EDKJU5BO.js +11 -0
  85. package/dist/chunk-EDKJU5BO.js.map +1 -0
  86. package/dist/chunk-EO2QPOKH.js +116 -0
  87. package/dist/chunk-EO2QPOKH.js.map +1 -0
  88. package/dist/chunk-EOLLMEAH.js +155 -0
  89. package/dist/chunk-EOLLMEAH.js.map +1 -0
  90. package/dist/chunk-EWYCWP4H.js +14 -0
  91. package/dist/chunk-EWYCWP4H.js.map +1 -0
  92. package/dist/chunk-EXVDJMIY.js +33 -0
  93. package/dist/chunk-EXVDJMIY.js.map +1 -0
  94. package/dist/chunk-FASRXRX5.js +19 -0
  95. package/dist/chunk-FASRXRX5.js.map +1 -0
  96. package/dist/chunk-FI34KYZ5.js +1 -0
  97. package/dist/chunk-FI34KYZ5.js.map +1 -0
  98. package/dist/chunk-FN2PYDPP.js +1 -0
  99. package/dist/chunk-FN2PYDPP.js.map +1 -0
  100. package/dist/chunk-GM3RMJIJ.js +92 -0
  101. package/dist/chunk-GM3RMJIJ.js.map +1 -0
  102. package/dist/chunk-GYGNEQSC.js +9 -0
  103. package/dist/chunk-GYGNEQSC.js.map +1 -0
  104. package/dist/chunk-H5NH7KPE.js +21 -0
  105. package/dist/chunk-H5NH7KPE.js.map +1 -0
  106. package/dist/chunk-HNWZFNKP.js +168 -0
  107. package/dist/chunk-HNWZFNKP.js.map +1 -0
  108. package/dist/chunk-HUH73XGI.js +1 -0
  109. package/dist/chunk-HUH73XGI.js.map +1 -0
  110. package/dist/chunk-I6MG4M3F.js +201 -0
  111. package/dist/chunk-I6MG4M3F.js.map +1 -0
  112. package/dist/chunk-I6MVCB5A.js +39 -0
  113. package/dist/chunk-I6MVCB5A.js.map +1 -0
  114. package/dist/chunk-IBGER4YK.js +12 -0
  115. package/dist/chunk-IBGER4YK.js.map +1 -0
  116. package/dist/chunk-IF5I3DAA.js +92 -0
  117. package/dist/chunk-IF5I3DAA.js.map +1 -0
  118. package/dist/chunk-IP4OO26U.js +54 -0
  119. package/dist/chunk-IP4OO26U.js.map +1 -0
  120. package/dist/chunk-IWAOY6KC.js +1 -0
  121. package/dist/chunk-IWAOY6KC.js.map +1 -0
  122. package/dist/chunk-J37YWU7Y.js +19 -0
  123. package/dist/chunk-J37YWU7Y.js.map +1 -0
  124. package/dist/chunk-J6KZS54B.js +269 -0
  125. package/dist/chunk-J6KZS54B.js.map +1 -0
  126. package/dist/chunk-J6MN42LG.js +19 -0
  127. package/dist/chunk-J6MN42LG.js.map +1 -0
  128. package/dist/chunk-JRQO2IOF.js +65 -0
  129. package/dist/chunk-JRQO2IOF.js.map +1 -0
  130. package/dist/chunk-JRVNVKN6.js +212 -0
  131. package/dist/chunk-JRVNVKN6.js.map +1 -0
  132. package/dist/chunk-JWNHNUYL.js +96 -0
  133. package/dist/chunk-JWNHNUYL.js.map +1 -0
  134. package/dist/chunk-K2I6XIK5.js +122 -0
  135. package/dist/chunk-K2I6XIK5.js.map +1 -0
  136. package/dist/chunk-KMZCQASO.js +111 -0
  137. package/dist/chunk-KMZCQASO.js.map +1 -0
  138. package/dist/chunk-KVOWSC5S.js +1 -0
  139. package/dist/chunk-KVOWSC5S.js.map +1 -0
  140. package/dist/chunk-KYR3B3OW.js +79 -0
  141. package/dist/chunk-KYR3B3OW.js.map +1 -0
  142. package/dist/chunk-L3LZWWSX.js +61 -0
  143. package/dist/chunk-L3LZWWSX.js.map +1 -0
  144. package/dist/chunk-L4SDDEEU.js +1 -0
  145. package/dist/chunk-L4SDDEEU.js.map +1 -0
  146. package/dist/chunk-L6FTY45T.js +13 -0
  147. package/dist/chunk-L6FTY45T.js.map +1 -0
  148. package/dist/chunk-L7BNNRGI.js +134 -0
  149. package/dist/chunk-L7BNNRGI.js.map +1 -0
  150. package/dist/chunk-LG57S2SC.js +150 -0
  151. package/dist/chunk-LG57S2SC.js.map +1 -0
  152. package/dist/chunk-M6QLSLPO.js +97 -0
  153. package/dist/chunk-M6QLSLPO.js.map +1 -0
  154. package/dist/chunk-MZ6GV4YF.js +21 -0
  155. package/dist/chunk-MZ6GV4YF.js.map +1 -0
  156. package/dist/chunk-N5OTOWTP.js +55 -0
  157. package/dist/chunk-N5OTOWTP.js.map +1 -0
  158. package/dist/chunk-NN7XZEGF.js +14 -0
  159. package/dist/chunk-NN7XZEGF.js.map +1 -0
  160. package/dist/chunk-NPFPZ2HO.js +13 -0
  161. package/dist/chunk-NPFPZ2HO.js.map +1 -0
  162. package/dist/chunk-NXXDZ6ZF.js +42 -0
  163. package/dist/chunk-NXXDZ6ZF.js.map +1 -0
  164. package/dist/chunk-NYBCQZC7.js +11 -0
  165. package/dist/chunk-NYBCQZC7.js.map +1 -0
  166. package/dist/chunk-OFRRBC7M.js +78 -0
  167. package/dist/chunk-OFRRBC7M.js.map +1 -0
  168. package/dist/chunk-OGIZXGPY.js +222 -0
  169. package/dist/chunk-OGIZXGPY.js.map +1 -0
  170. package/dist/chunk-OKXZ63IA.js +168 -0
  171. package/dist/chunk-OKXZ63IA.js.map +1 -0
  172. package/dist/chunk-OSQRXVG2.js +58 -0
  173. package/dist/chunk-OSQRXVG2.js.map +1 -0
  174. package/dist/chunk-OTDN3OUQ.js +215 -0
  175. package/dist/chunk-OTDN3OUQ.js.map +1 -0
  176. package/dist/chunk-OZZJDRGW.js +122 -0
  177. package/dist/chunk-OZZJDRGW.js.map +1 -0
  178. package/dist/chunk-PNZSGAB2.js +114 -0
  179. package/dist/chunk-PNZSGAB2.js.map +1 -0
  180. package/dist/chunk-PRWIX6UW.js +21 -0
  181. package/dist/chunk-PRWIX6UW.js.map +1 -0
  182. package/dist/chunk-PSXUNOVU.js +7 -0
  183. package/dist/chunk-PSXUNOVU.js.map +1 -0
  184. package/dist/chunk-QLTJSCE6.js +44 -0
  185. package/dist/chunk-QLTJSCE6.js.map +1 -0
  186. package/dist/chunk-RC23QROE.js +447 -0
  187. package/dist/chunk-RC23QROE.js.map +1 -0
  188. package/dist/chunk-RFH7N6EP.js +36 -0
  189. package/dist/chunk-RFH7N6EP.js.map +1 -0
  190. package/dist/chunk-RHVN6NA7.js +134 -0
  191. package/dist/chunk-RHVN6NA7.js.map +1 -0
  192. package/dist/chunk-S7C6TIIF.js +21 -0
  193. package/dist/chunk-S7C6TIIF.js.map +1 -0
  194. package/dist/chunk-SNQ3TOWP.js +20 -0
  195. package/dist/chunk-SNQ3TOWP.js.map +1 -0
  196. package/dist/chunk-SOVM2VEK.js +14 -0
  197. package/dist/chunk-SOVM2VEK.js.map +1 -0
  198. package/dist/chunk-SQDOBLBP.js +13 -0
  199. package/dist/chunk-SQDOBLBP.js.map +1 -0
  200. package/dist/chunk-SR7F3TJY.js +130 -0
  201. package/dist/chunk-SR7F3TJY.js.map +1 -0
  202. package/dist/chunk-SZVPIHWE.js +129 -0
  203. package/dist/chunk-SZVPIHWE.js.map +1 -0
  204. package/dist/chunk-T4BIIU5E.js +89 -0
  205. package/dist/chunk-T4BIIU5E.js.map +1 -0
  206. package/dist/chunk-T6C4LFLC.js +112 -0
  207. package/dist/chunk-T6C4LFLC.js.map +1 -0
  208. package/dist/chunk-TNXH7BJS.js +48 -0
  209. package/dist/chunk-TNXH7BJS.js.map +1 -0
  210. package/dist/chunk-U64T4YZE.js +9 -0
  211. package/dist/chunk-U64T4YZE.js.map +1 -0
  212. package/dist/chunk-UQ5EHOH2.js +39 -0
  213. package/dist/chunk-UQ5EHOH2.js.map +1 -0
  214. package/dist/chunk-UTN4GBPQ.js +1 -0
  215. package/dist/chunk-UTN4GBPQ.js.map +1 -0
  216. package/dist/chunk-V4AF6DI4.js +16 -0
  217. package/dist/chunk-V4AF6DI4.js.map +1 -0
  218. package/dist/chunk-W72PRNJY.js +126 -0
  219. package/dist/chunk-W72PRNJY.js.map +1 -0
  220. package/dist/chunk-WEVWJKOW.js +81 -0
  221. package/dist/chunk-WEVWJKOW.js.map +1 -0
  222. package/dist/chunk-WL67FZGF.js +21 -0
  223. package/dist/chunk-WL67FZGF.js.map +1 -0
  224. package/dist/chunk-WPXNN6QS.js +290 -0
  225. package/dist/chunk-WPXNN6QS.js.map +1 -0
  226. package/dist/chunk-WRUUSZDJ.js +29 -0
  227. package/dist/chunk-WRUUSZDJ.js.map +1 -0
  228. package/dist/chunk-X2GMTYPA.js +50 -0
  229. package/dist/chunk-X2GMTYPA.js.map +1 -0
  230. package/dist/chunk-XCEI7NUH.js +41 -0
  231. package/dist/chunk-XCEI7NUH.js.map +1 -0
  232. package/dist/chunk-Y7GDG744.js +88 -0
  233. package/dist/chunk-Y7GDG744.js.map +1 -0
  234. package/dist/chunk-Y7RRSEOC.js +9 -0
  235. package/dist/chunk-Y7RRSEOC.js.map +1 -0
  236. package/dist/chunk-YPWODKD5.js +184 -0
  237. package/dist/chunk-YPWODKD5.js.map +1 -0
  238. package/dist/chunk-YSLTTQLC.js +25 -0
  239. package/dist/chunk-YSLTTQLC.js.map +1 -0
  240. package/dist/chunk-YTN6BKWA.js +121 -0
  241. package/dist/chunk-YTN6BKWA.js.map +1 -0
  242. package/dist/chunk-Z7PQCAVK.js +200 -0
  243. package/dist/chunk-Z7PQCAVK.js.map +1 -0
  244. package/dist/chunk-ZUKFQL6E.js +47 -0
  245. package/dist/chunk-ZUKFQL6E.js.map +1 -0
  246. package/dist/chunk-ZUMULSEQ.js +1 -0
  247. package/dist/chunk-ZUMULSEQ.js.map +1 -0
  248. package/dist/{job-orchestrator.protocol-CARhMLCO.d.ts → job-orchestrator.protocol-DubMVbm9.d.ts} +1 -1
  249. package/dist/runtime/analytics/index.js +8 -41
  250. package/dist/runtime/analytics/index.js.map +1 -1
  251. package/dist/runtime/analytics/types.js +8 -41
  252. package/dist/runtime/analytics/types.js.map +1 -1
  253. package/dist/runtime/base-classes/activity-entity-repository.js +6 -312
  254. package/dist/runtime/base-classes/activity-entity-repository.js.map +1 -1
  255. package/dist/runtime/base-classes/activity-entity-service.js +6 -212
  256. package/dist/runtime/base-classes/activity-entity-service.js.map +1 -1
  257. package/dist/runtime/base-classes/base-read-use-cases.js +5 -27
  258. package/dist/runtime/base-classes/base-read-use-cases.js.map +1 -1
  259. package/dist/runtime/base-classes/base-repository.js +5 -277
  260. package/dist/runtime/base-classes/base-repository.js.map +1 -1
  261. package/dist/runtime/base-classes/base-service.js +5 -184
  262. package/dist/runtime/base-classes/base-service.js.map +1 -1
  263. package/dist/runtime/base-classes/index.js +59 -1076
  264. package/dist/runtime/base-classes/index.js.map +1 -1
  265. package/dist/runtime/base-classes/integrated-entity-repository.js +6 -486
  266. package/dist/runtime/base-classes/integrated-entity-repository.js.map +1 -1
  267. package/dist/runtime/base-classes/integrated-entity-service.js +6 -213
  268. package/dist/runtime/base-classes/integrated-entity-service.js.map +1 -1
  269. package/dist/runtime/base-classes/junction-integration-repository.js +8 -448
  270. package/dist/runtime/base-classes/junction-integration-repository.js.map +1 -1
  271. package/dist/runtime/base-classes/knowledge-entity-repository.js +6 -283
  272. package/dist/runtime/base-classes/knowledge-entity-repository.js.map +1 -1
  273. package/dist/runtime/base-classes/knowledge-entity-service.js +6 -190
  274. package/dist/runtime/base-classes/knowledge-entity-service.js.map +1 -1
  275. package/dist/runtime/base-classes/lifecycle-events.js +8 -70
  276. package/dist/runtime/base-classes/lifecycle-events.js.map +1 -1
  277. package/dist/runtime/base-classes/metadata-entity-repository.js +6 -330
  278. package/dist/runtime/base-classes/metadata-entity-repository.js.map +1 -1
  279. package/dist/runtime/base-classes/metadata-entity-service.js +6 -212
  280. package/dist/runtime/base-classes/metadata-entity-service.js.map +1 -1
  281. package/dist/runtime/base-classes/tenant-context.js +10 -36
  282. package/dist/runtime/base-classes/tenant-context.js.map +1 -1
  283. package/dist/runtime/base-classes/with-analytics.js +4 -7
  284. package/dist/runtime/base-classes/with-analytics.js.map +1 -1
  285. package/dist/runtime/constants/tokens.js +5 -3
  286. package/dist/runtime/constants/tokens.js.map +1 -1
  287. package/dist/runtime/eav-helpers.js +2 -0
  288. package/dist/runtime/eav-helpers.js.map +1 -1
  289. package/dist/runtime/pipes/zod-validation.pipe.js +3 -10
  290. package/dist/runtime/pipes/zod-validation.pipe.js.map +1 -1
  291. package/dist/runtime/shared/openapi/error-response.dto.js +5 -8
  292. package/dist/runtime/shared/openapi/error-response.dto.js.map +1 -1
  293. package/dist/runtime/shared/openapi/errors.js +5 -19
  294. package/dist/runtime/shared/openapi/errors.js.map +1 -1
  295. package/dist/runtime/shared/openapi/index.js +15 -106
  296. package/dist/runtime/shared/openapi/index.js.map +1 -1
  297. package/dist/runtime/shared/openapi/registry.js +6 -103
  298. package/dist/runtime/shared/openapi/registry.js.map +1 -1
  299. package/dist/runtime/shared/openapi/registry.tokens.js +4 -2
  300. package/dist/runtime/shared/openapi/registry.tokens.js.map +1 -1
  301. package/dist/runtime/subsystems/analytics/analytics.module.js +8 -117
  302. package/dist/runtime/subsystems/analytics/analytics.module.js.map +1 -1
  303. package/dist/runtime/subsystems/analytics/analytics.tokens.js +7 -8
  304. package/dist/runtime/subsystems/analytics/analytics.tokens.js.map +1 -1
  305. package/dist/runtime/subsystems/analytics/cube-backend.js +6 -71
  306. package/dist/runtime/subsystems/analytics/cube-backend.js.map +1 -1
  307. package/dist/runtime/subsystems/analytics/index.js +16 -117
  308. package/dist/runtime/subsystems/analytics/index.js.map +1 -1
  309. package/dist/runtime/subsystems/analytics/noop-backend.js +4 -21
  310. package/dist/runtime/subsystems/analytics/noop-backend.js.map +1 -1
  311. package/dist/runtime/subsystems/auth/auth-oauth-state.schema.js +4 -8
  312. package/dist/runtime/subsystems/auth/auth-oauth-state.schema.js.map +1 -1
  313. package/dist/runtime/subsystems/auth/auth.module.js +12 -359
  314. package/dist/runtime/subsystems/auth/auth.module.js.map +1 -1
  315. package/dist/runtime/subsystems/auth/auth.tokens.js +12 -13
  316. package/dist/runtime/subsystems/auth/auth.tokens.js.map +1 -1
  317. package/dist/runtime/subsystems/auth/backends/encryption-key/env.js +4 -49
  318. package/dist/runtime/subsystems/auth/backends/encryption-key/env.js.map +1 -1
  319. package/dist/runtime/subsystems/auth/backends/state-store.drizzle-backend.js +6 -64
  320. package/dist/runtime/subsystems/auth/backends/state-store.drizzle-backend.js.map +1 -1
  321. package/dist/runtime/subsystems/auth/backends/state-store.memory-backend.js +5 -47
  322. package/dist/runtime/subsystems/auth/backends/state-store.memory-backend.js.map +1 -1
  323. package/dist/runtime/subsystems/auth/controllers/auth.controller.js +5 -139
  324. package/dist/runtime/subsystems/auth/controllers/auth.controller.js.map +1 -1
  325. package/dist/runtime/subsystems/auth/index.js +53 -542
  326. package/dist/runtime/subsystems/auth/index.js.map +1 -1
  327. package/dist/runtime/subsystems/auth/middleware/requester-context.js +9 -65
  328. package/dist/runtime/subsystems/auth/middleware/requester-context.js.map +1 -1
  329. package/dist/runtime/subsystems/auth/protocols/oauth-state-store.js +4 -9
  330. package/dist/runtime/subsystems/auth/protocols/oauth-state-store.js.map +1 -1
  331. package/dist/runtime/subsystems/auth/runtime/connection-broken.error.js +4 -15
  332. package/dist/runtime/subsystems/auth/runtime/connection-broken.error.js.map +1 -1
  333. package/dist/runtime/subsystems/auth/runtime/oauth2-refresh.strategy.js +5 -104
  334. package/dist/runtime/subsystems/auth/runtime/oauth2-refresh.strategy.js.map +1 -1
  335. package/dist/runtime/subsystems/auth/runtime/session-expired.error.js +5 -16
  336. package/dist/runtime/subsystems/auth/runtime/session-expired.error.js.map +1 -1
  337. package/dist/runtime/subsystems/auth/runtime/with-auth-retry.js +5 -29
  338. package/dist/runtime/subsystems/auth/runtime/with-auth-retry.js.map +1 -1
  339. package/dist/runtime/subsystems/bridge/assert-tenant-id.js +5 -18
  340. package/dist/runtime/subsystems/bridge/assert-tenant-id.js.map +1 -1
  341. package/dist/runtime/subsystems/bridge/bridge-delivery-handler.d.ts +2 -2
  342. package/dist/runtime/subsystems/bridge/bridge-delivery-handler.js +12 -184
  343. package/dist/runtime/subsystems/bridge/bridge-delivery-handler.js.map +1 -1
  344. package/dist/runtime/subsystems/bridge/bridge-delivery.drizzle-backend.d.ts +1 -1
  345. package/dist/runtime/subsystems/bridge/bridge-delivery.drizzle-backend.js +10 -448
  346. package/dist/runtime/subsystems/bridge/bridge-delivery.drizzle-backend.js.map +1 -1
  347. package/dist/runtime/subsystems/bridge/bridge-delivery.memory-backend.d.ts +1 -1
  348. package/dist/runtime/subsystems/bridge/bridge-delivery.memory-backend.js +5 -126
  349. package/dist/runtime/subsystems/bridge/bridge-delivery.memory-backend.js.map +1 -1
  350. package/dist/runtime/subsystems/bridge/bridge-delivery.schema.js +6 -308
  351. package/dist/runtime/subsystems/bridge/bridge-delivery.schema.js.map +1 -1
  352. package/dist/runtime/subsystems/bridge/bridge-errors.js +6 -35
  353. package/dist/runtime/subsystems/bridge/bridge-errors.js.map +1 -1
  354. package/dist/runtime/subsystems/bridge/bridge-outbox-drain-hook.d.ts +1 -1
  355. package/dist/runtime/subsystems/bridge/bridge-outbox-drain-hook.js +14 -606
  356. package/dist/runtime/subsystems/bridge/bridge-outbox-drain-hook.js.map +1 -1
  357. package/dist/runtime/subsystems/bridge/bridge.module.d.ts +2 -2
  358. package/dist/runtime/subsystems/bridge/bridge.module.js +35 -3476
  359. package/dist/runtime/subsystems/bridge/bridge.module.js.map +1 -1
  360. package/dist/runtime/subsystems/bridge/bridge.protocol.d.ts +1 -1
  361. package/dist/runtime/subsystems/bridge/bridge.tokens.js +9 -7
  362. package/dist/runtime/subsystems/bridge/bridge.tokens.js.map +1 -1
  363. package/dist/runtime/subsystems/bridge/event-flow.service.d.ts +2 -2
  364. package/dist/runtime/subsystems/bridge/event-flow.service.js +11 -137
  365. package/dist/runtime/subsystems/bridge/event-flow.service.js.map +1 -1
  366. package/dist/runtime/subsystems/bridge/generated/registry.d.ts +1 -1
  367. package/dist/runtime/subsystems/bridge/generated/registry.js +4 -2
  368. package/dist/runtime/subsystems/bridge/generated/registry.js.map +1 -1
  369. package/dist/runtime/subsystems/bridge/index.d.ts +2 -2
  370. package/dist/runtime/subsystems/bridge/index.js +60 -3470
  371. package/dist/runtime/subsystems/bridge/index.js.map +1 -1
  372. package/dist/runtime/subsystems/bridge/reserved-pools.js +4 -6
  373. package/dist/runtime/subsystems/bridge/reserved-pools.js.map +1 -1
  374. package/dist/runtime/subsystems/cache/cache.drizzle-backend.js +10 -133
  375. package/dist/runtime/subsystems/cache/cache.drizzle-backend.js.map +1 -1
  376. package/dist/runtime/subsystems/cache/cache.memory-backend.js +6 -101
  377. package/dist/runtime/subsystems/cache/cache.memory-backend.js.map +1 -1
  378. package/dist/runtime/subsystems/cache/cache.module.js +10 -278
  379. package/dist/runtime/subsystems/cache/cache.module.js.map +1 -1
  380. package/dist/runtime/subsystems/cache/cache.schema.js +4 -14
  381. package/dist/runtime/subsystems/cache/cache.schema.js.map +1 -1
  382. package/dist/runtime/subsystems/cache/cache.tokens.js +6 -7
  383. package/dist/runtime/subsystems/cache/cache.tokens.js.map +1 -1
  384. package/dist/runtime/subsystems/cache/index.js +20 -278
  385. package/dist/runtime/subsystems/cache/index.js.map +1 -1
  386. package/dist/runtime/subsystems/events/domain-events.schema.js +3 -72
  387. package/dist/runtime/subsystems/events/domain-events.schema.js.map +1 -1
  388. package/dist/runtime/subsystems/events/event-bus.drizzle-backend.d.ts +1 -1
  389. package/dist/runtime/subsystems/events/event-bus.drizzle-backend.js +9 -413
  390. package/dist/runtime/subsystems/events/event-bus.drizzle-backend.js.map +1 -1
  391. package/dist/runtime/subsystems/events/event-bus.memory-backend.js +7 -235
  392. package/dist/runtime/subsystems/events/event-bus.memory-backend.js.map +1 -1
  393. package/dist/runtime/subsystems/events/event-bus.redis-backend.js +8 -20
  394. package/dist/runtime/subsystems/events/event-bus.redis-backend.js.map +1 -1
  395. package/dist/runtime/subsystems/events/event-keyset-cursor.js +8 -30
  396. package/dist/runtime/subsystems/events/event-keyset-cursor.js.map +1 -1
  397. package/dist/runtime/subsystems/events/event-read.protocol.js +2 -0
  398. package/dist/runtime/subsystems/events/event-read.protocol.js.map +1 -1
  399. package/dist/runtime/subsystems/events/event-registry.d.ts +77 -0
  400. package/dist/runtime/subsystems/events/event-registry.js +1 -0
  401. package/dist/runtime/subsystems/events/event-registry.js.map +1 -0
  402. package/dist/runtime/subsystems/events/events-errors.js +4 -11
  403. package/dist/runtime/subsystems/events/events-errors.js.map +1 -1
  404. package/dist/runtime/subsystems/events/events.module.js +15 -949
  405. package/dist/runtime/subsystems/events/events.module.js.map +1 -1
  406. package/dist/runtime/subsystems/events/events.tokens.js +10 -11
  407. package/dist/runtime/subsystems/events/events.tokens.js.map +1 -1
  408. package/dist/runtime/subsystems/events/generated/bus.js +9 -240
  409. package/dist/runtime/subsystems/events/generated/bus.js.map +1 -1
  410. package/dist/runtime/subsystems/events/generated/index.js +23 -240
  411. package/dist/runtime/subsystems/events/generated/index.js.map +1 -1
  412. package/dist/runtime/subsystems/events/generated/registry.js +5 -82
  413. package/dist/runtime/subsystems/events/generated/registry.js.map +1 -1
  414. package/dist/runtime/subsystems/events/generated/schemas.js +12 -52
  415. package/dist/runtime/subsystems/events/generated/schemas.js.map +1 -1
  416. package/dist/runtime/subsystems/events/generated/types.js +1 -0
  417. package/dist/runtime/subsystems/events/index.d.ts +1 -0
  418. package/dist/runtime/subsystems/events/index.js +32 -949
  419. package/dist/runtime/subsystems/events/index.js.map +1 -1
  420. package/dist/runtime/subsystems/index.d.ts +2 -2
  421. package/dist/runtime/subsystems/index.js +171 -5912
  422. package/dist/runtime/subsystems/index.js.map +1 -1
  423. package/dist/runtime/subsystems/integration/build-change-source.js +6 -178
  424. package/dist/runtime/subsystems/integration/build-change-source.js.map +1 -1
  425. package/dist/runtime/subsystems/integration/deep-equal.differ.js +4 -109
  426. package/dist/runtime/subsystems/integration/deep-equal.differ.js.map +1 -1
  427. package/dist/runtime/subsystems/integration/detection-config.schema.js +11 -78
  428. package/dist/runtime/subsystems/integration/detection-config.schema.js.map +1 -1
  429. package/dist/runtime/subsystems/integration/entity-change-source-registry.memory.js +5 -30
  430. package/dist/runtime/subsystems/integration/entity-change-source-registry.memory.js.map +1 -1
  431. package/dist/runtime/subsystems/integration/entity-change-source-registry.protocol.js +4 -9
  432. package/dist/runtime/subsystems/integration/entity-change-source-registry.protocol.js.map +1 -1
  433. package/dist/runtime/subsystems/integration/execute-integration.use-case.js +6 -239
  434. package/dist/runtime/subsystems/integration/execute-integration.use-case.js.map +1 -1
  435. package/dist/runtime/subsystems/integration/incremental-read.js +5 -144
  436. package/dist/runtime/subsystems/integration/incremental-read.js.map +1 -1
  437. package/dist/runtime/subsystems/integration/index.js +83 -1352
  438. package/dist/runtime/subsystems/integration/index.js.map +1 -1
  439. package/dist/runtime/subsystems/integration/integration-audit.schema.js +10 -155
  440. package/dist/runtime/subsystems/integration/integration-audit.schema.js.map +1 -1
  441. package/dist/runtime/subsystems/integration/integration-cursor-store.drizzle-backend.js +7 -270
  442. package/dist/runtime/subsystems/integration/integration-cursor-store.drizzle-backend.js.map +1 -1
  443. package/dist/runtime/subsystems/integration/integration-cursor-store.memory-backend.js +4 -65
  444. package/dist/runtime/subsystems/integration/integration-cursor-store.memory-backend.js.map +1 -1
  445. package/dist/runtime/subsystems/integration/integration-errors.js +5 -15
  446. package/dist/runtime/subsystems/integration/integration-errors.js.map +1 -1
  447. package/dist/runtime/subsystems/integration/integration-field-diff.protocol.js +5 -7
  448. package/dist/runtime/subsystems/integration/integration-field-diff.protocol.js.map +1 -1
  449. package/dist/runtime/subsystems/integration/integration-run-recorder.drizzle-backend.js +8 -303
  450. package/dist/runtime/subsystems/integration/integration-run-recorder.drizzle-backend.js.map +1 -1
  451. package/dist/runtime/subsystems/integration/integration-run-recorder.memory-backend.js +5 -125
  452. package/dist/runtime/subsystems/integration/integration-run-recorder.memory-backend.js.map +1 -1
  453. package/dist/runtime/subsystems/integration/integration.module.js +13 -700
  454. package/dist/runtime/subsystems/integration/integration.module.js.map +1 -1
  455. package/dist/runtime/subsystems/integration/integration.tokens.js +11 -9
  456. package/dist/runtime/subsystems/integration/integration.tokens.js.map +1 -1
  457. package/dist/runtime/subsystems/integration/loopback.middleware.js +4 -16
  458. package/dist/runtime/subsystems/integration/loopback.middleware.js.map +1 -1
  459. package/dist/runtime/subsystems/integration/poll-change-source.js +4 -89
  460. package/dist/runtime/subsystems/integration/poll-change-source.js.map +1 -1
  461. package/dist/runtime/subsystems/integration/webhook-change-source.js +4 -70
  462. package/dist/runtime/subsystems/integration/webhook-change-source.js.map +1 -1
  463. package/dist/runtime/subsystems/jobs/bullmq.config.js +9 -140
  464. package/dist/runtime/subsystems/jobs/bullmq.config.js.map +1 -1
  465. package/dist/runtime/subsystems/jobs/index.d.ts +2 -2
  466. package/dist/runtime/subsystems/jobs/index.js +88 -2691
  467. package/dist/runtime/subsystems/jobs/index.js.map +1 -1
  468. package/dist/runtime/subsystems/jobs/job-handler.base.d.ts +2 -2
  469. package/dist/runtime/subsystems/jobs/job-handler.base.js +10 -49
  470. package/dist/runtime/subsystems/jobs/job-handler.base.js.map +1 -1
  471. package/dist/runtime/subsystems/jobs/job-orchestration.schema.js +13 -152
  472. package/dist/runtime/subsystems/jobs/job-orchestration.schema.js.map +1 -1
  473. package/dist/runtime/subsystems/jobs/job-orchestrator.bullmq-backend.d.ts +2 -2
  474. package/dist/runtime/subsystems/jobs/job-orchestrator.bullmq-backend.js +36 -699
  475. package/dist/runtime/subsystems/jobs/job-orchestrator.bullmq-backend.js.map +1 -1
  476. package/dist/runtime/subsystems/jobs/job-orchestrator.drizzle-backend.d.ts +2 -2
  477. package/dist/runtime/subsystems/jobs/job-orchestrator.drizzle-backend.js +10 -564
  478. package/dist/runtime/subsystems/jobs/job-orchestrator.drizzle-backend.js.map +1 -1
  479. package/dist/runtime/subsystems/jobs/job-orchestrator.memory-backend.d.ts +2 -2
  480. package/dist/runtime/subsystems/jobs/job-orchestrator.memory-backend.js +10 -824
  481. package/dist/runtime/subsystems/jobs/job-orchestrator.memory-backend.js.map +1 -1
  482. package/dist/runtime/subsystems/jobs/job-orchestrator.protocol.d.ts +2 -2
  483. package/dist/runtime/subsystems/jobs/job-run-keyset-cursor.d.ts +2 -2
  484. package/dist/runtime/subsystems/jobs/job-run-keyset-cursor.js +9 -51
  485. package/dist/runtime/subsystems/jobs/job-run-keyset-cursor.js.map +1 -1
  486. package/dist/runtime/subsystems/jobs/job-run-service.drizzle-backend.d.ts +2 -2
  487. package/dist/runtime/subsystems/jobs/job-run-service.drizzle-backend.js +9 -416
  488. package/dist/runtime/subsystems/jobs/job-run-service.drizzle-backend.js.map +1 -1
  489. package/dist/runtime/subsystems/jobs/job-run-service.memory-backend.d.ts +2 -2
  490. package/dist/runtime/subsystems/jobs/job-run-service.memory-backend.js +9 -290
  491. package/dist/runtime/subsystems/jobs/job-run-service.memory-backend.js.map +1 -1
  492. package/dist/runtime/subsystems/jobs/job-run-service.protocol.d.ts +2 -2
  493. package/dist/runtime/subsystems/jobs/job-step-service.drizzle-backend.js +5 -213
  494. package/dist/runtime/subsystems/jobs/job-step-service.drizzle-backend.js.map +1 -1
  495. package/dist/runtime/subsystems/jobs/job-step-service.memory-backend.js +5 -131
  496. package/dist/runtime/subsystems/jobs/job-step-service.memory-backend.js.map +1 -1
  497. package/dist/runtime/subsystems/jobs/job-worker.bullmq-backend.d.ts +2 -2
  498. package/dist/runtime/subsystems/jobs/job-worker.bullmq-backend.js +9 -175
  499. package/dist/runtime/subsystems/jobs/job-worker.bullmq-backend.js.map +1 -1
  500. package/dist/runtime/subsystems/jobs/job-worker.d.ts +2 -2
  501. package/dist/runtime/subsystems/jobs/job-worker.js +14 -613
  502. package/dist/runtime/subsystems/jobs/job-worker.js.map +1 -1
  503. package/dist/runtime/subsystems/jobs/job-worker.module.d.ts +2 -2
  504. package/dist/runtime/subsystems/jobs/job-worker.module.js +23 -2647
  505. package/dist/runtime/subsystems/jobs/job-worker.module.js.map +1 -1
  506. package/dist/runtime/subsystems/jobs/jobs-domain.module.js +19 -1897
  507. package/dist/runtime/subsystems/jobs/jobs-domain.module.js.map +1 -1
  508. package/dist/runtime/subsystems/jobs/jobs-domain.tokens.js +8 -9
  509. package/dist/runtime/subsystems/jobs/jobs-domain.tokens.js.map +1 -1
  510. package/dist/runtime/subsystems/jobs/jobs-errors.d.ts +2 -2
  511. package/dist/runtime/subsystems/jobs/jobs-errors.js +10 -78
  512. package/dist/runtime/subsystems/jobs/jobs-errors.js.map +1 -1
  513. package/dist/runtime/subsystems/jobs/memory-job-store.js +4 -15
  514. package/dist/runtime/subsystems/jobs/memory-job-store.js.map +1 -1
  515. package/dist/runtime/subsystems/jobs/pool-config.loader.js +9 -124
  516. package/dist/runtime/subsystems/jobs/pool-config.loader.js.map +1 -1
  517. package/dist/runtime/subsystems/observability/index.d.ts +2 -2
  518. package/dist/runtime/subsystems/observability/index.js +21 -310
  519. package/dist/runtime/subsystems/observability/index.js.map +1 -1
  520. package/dist/runtime/subsystems/observability/observability-errors.js +4 -9
  521. package/dist/runtime/subsystems/observability/observability-errors.js.map +1 -1
  522. package/dist/runtime/subsystems/observability/observability.module.js +11 -300
  523. package/dist/runtime/subsystems/observability/observability.module.js.map +1 -1
  524. package/dist/runtime/subsystems/observability/observability.protocol.d.ts +2 -2
  525. package/dist/runtime/subsystems/observability/observability.service.d.ts +2 -2
  526. package/dist/runtime/subsystems/observability/observability.service.js +9 -197
  527. package/dist/runtime/subsystems/observability/observability.service.js.map +1 -1
  528. package/dist/runtime/subsystems/observability/observability.tokens.js +5 -3
  529. package/dist/runtime/subsystems/observability/observability.tokens.js.map +1 -1
  530. package/dist/runtime/subsystems/observability/reporters/bridge-metrics.reporter.d.ts +2 -2
  531. package/dist/runtime/subsystems/observability/reporters/bridge-metrics.reporter.js +4 -84
  532. package/dist/runtime/subsystems/observability/reporters/bridge-metrics.reporter.js.map +1 -1
  533. package/dist/runtime/subsystems/observability/reporters/index.d.ts +2 -2
  534. package/dist/runtime/subsystems/observability/reporters/index.js +5 -84
  535. package/dist/runtime/subsystems/observability/reporters/index.js.map +1 -1
  536. package/dist/runtime/subsystems/storage/index.js +15 -200
  537. package/dist/runtime/subsystems/storage/index.js.map +1 -1
  538. package/dist/runtime/subsystems/storage/storage.local-backend.js +4 -103
  539. package/dist/runtime/subsystems/storage/storage.local-backend.js.map +1 -1
  540. package/dist/runtime/subsystems/storage/storage.memory-backend.js +5 -68
  541. package/dist/runtime/subsystems/storage/storage.memory-backend.js.map +1 -1
  542. package/dist/runtime/subsystems/storage/storage.module.js +8 -200
  543. package/dist/runtime/subsystems/storage/storage.module.js.map +1 -1
  544. package/dist/runtime/subsystems/storage/storage.tokens.js +5 -6
  545. package/dist/runtime/subsystems/storage/storage.tokens.js.map +1 -1
  546. package/dist/runtime/subsystems/storage/storage.utils.js +4 -14
  547. package/dist/runtime/subsystems/storage/storage.utils.js.map +1 -1
  548. package/dist/runtime/subsystems/token-key.js +5 -3
  549. package/dist/runtime/subsystems/token-key.js.map +1 -1
  550. package/dist/src/cli/index.js +653 -5444
  551. package/dist/src/cli/index.js.map +1 -1
  552. package/dist/src/index.js +68 -4170
  553. package/dist/src/index.js.map +1 -1
  554. package/package.json +1 -1
  555. package/runtime/subsystems/bridge/bridge-delivery-handler.ts +1 -1
  556. package/runtime/subsystems/bridge/bridge-outbox-drain-hook.ts +45 -22
  557. package/runtime/subsystems/bridge/bridge.protocol.ts +1 -1
  558. package/runtime/subsystems/bridge/event-flow.service.ts +1 -1
  559. package/runtime/subsystems/events/event-registry.ts +77 -0
  560. package/runtime/subsystems/events/index.ts +12 -0
  561. package/runtime/subsystems/jobs/job-handler.base.ts +1 -1
  562. package/runtime/subsystems/jobs/job-worker.ts +17 -11
@@ -1,2651 +1,27 @@
1
- var __defProp = Object.defineProperty;
2
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
- var __decorateClass = (decorators, target, key, kind) => {
4
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
5
- for (var i = decorators.length - 1, decorator; i >= 0; i--)
6
- if (decorator = decorators[i])
7
- result = (kind ? decorator(target, key, result) : decorator(result)) || result;
8
- if (kind && result) __defProp(target, key, result);
9
- return result;
10
- };
11
- var __decorateParam = (index2, decorator) => (target, key) => decorator(target, key, index2);
12
-
13
- // runtime/subsystems/jobs/job-worker.module.ts
14
- import {
15
- Inject as Inject8,
16
- Injectable as Injectable8,
17
- Logger as Logger4,
18
- Module as Module2,
19
- Optional as Optional2
20
- } from "@nestjs/common";
21
- import { ModuleRef as ModuleRef2 } from "@nestjs/core";
22
-
23
- // runtime/subsystems/token-key.ts
24
- var PKG = "@pattern-stack/codegen";
25
- var tokenKey = (area, name) => `${PKG}.${area}.${name}`;
26
-
27
- // runtime/constants/tokens.ts
28
- var DRIZZLE = "DRIZZLE";
29
-
30
- // runtime/subsystems/jobs/job-handler.base.ts
31
- var JOB_HANDLER_REGISTRY = /* @__PURE__ */ new Map();
32
- var JOB_HANDLER_METADATA_KEY = Symbol.for(tokenKey("jobs", "handler-metadata"));
33
- var HandlerRegistry;
34
- ((HandlerRegistry2) => {
35
- function getAll() {
36
- return Array.from(JOB_HANDLER_REGISTRY.values());
37
- }
38
- HandlerRegistry2.getAll = getAll;
39
- function get(type) {
40
- return JOB_HANDLER_REGISTRY.get(type);
41
- }
42
- HandlerRegistry2.get = get;
43
- })(HandlerRegistry || (HandlerRegistry = {}));
44
-
45
- // runtime/subsystems/jobs/jobs-domain.module.ts
46
- import { Module } from "@nestjs/common";
47
-
48
- // runtime/subsystems/jobs/jobs-domain.tokens.ts
49
- var JOB_ORCHESTRATOR = Symbol.for(tokenKey("jobs", "orchestrator"));
50
- var JOB_RUN_SERVICE = Symbol.for(tokenKey("jobs", "run-service"));
51
- var JOB_STEP_SERVICE = Symbol.for(tokenKey("jobs", "step-service"));
52
- var JOBS_MULTI_TENANT = Symbol.for(tokenKey("jobs", "multi-tenant"));
53
-
54
- // runtime/subsystems/jobs/job-orchestrator.drizzle-backend.ts
55
- import { randomUUID } from "crypto";
56
- import { Inject, Injectable, Logger } from "@nestjs/common";
57
- import { and, desc, eq, gt, inArray, isNotNull, ne, notInArray, sql as sql2 } from "drizzle-orm";
58
-
59
- // runtime/subsystems/jobs/job-orchestration.schema.ts
60
1
  import {
61
- pgEnum,
62
- pgTable,
63
- uuid,
64
- text,
65
- jsonb,
66
- integer,
67
- timestamp,
68
- index,
69
- uniqueIndex
70
- } from "drizzle-orm/pg-core";
71
- import { sql } from "drizzle-orm";
72
- var jobRunStatusEnum = pgEnum("job_run_status", [
73
- "pending",
74
- "running",
75
- "waiting",
76
- "completed",
77
- "failed",
78
- "timed_out",
79
- "canceled"
80
- ]);
81
- var jobStepKindEnum = pgEnum("job_step_kind", ["task"]);
82
- var jobStepStatusEnum = pgEnum("job_step_status", [
83
- "pending",
84
- "running",
85
- "completed",
86
- "failed",
87
- "skipped"
88
- ]);
89
- var collisionModeEnum = pgEnum("job_collision_mode", [
90
- "queue",
91
- "reject",
92
- "replace"
93
- ]);
94
- var replayFromEnum = pgEnum("job_replay_from", [
95
- "scratch",
96
- "last_step",
97
- "last_checkpoint"
98
- ]);
99
- var parentClosePolicyEnum = pgEnum("job_parent_close_policy", [
100
- "terminate",
101
- "cancel",
102
- "abandon"
103
- ]);
104
- var waitKindEnum = pgEnum("job_wait_kind", ["signal"]);
105
- var triggerSourceEnum = pgEnum("job_trigger_source", [
106
- "manual",
107
- "schedule",
108
- "event",
109
- "parent"
110
- ]);
111
- var jobs = pgTable("job", {
112
- type: text("type").primaryKey(),
113
- version: integer("version").notNull().default(1),
114
- pool: text("pool").notNull(),
115
- scopeEntityType: text("scope_entity_type"),
116
- retryPolicy: jsonb("retry_policy").notNull().$type(),
117
- timeoutMs: integer("timeout_ms"),
118
- concurrencyKeyTemplate: text("concurrency_key_template"),
119
- collisionMode: collisionModeEnum("collision_mode").notNull().default("queue"),
120
- dedupeKeyTemplate: text("dedupe_key_template"),
121
- dedupeWindowMs: integer("dedupe_window_ms"),
122
- priorityDefault: integer("priority_default").notNull().default(0),
123
- replayFrom: replayFromEnum("replay_from").notNull().default("last_checkpoint"),
124
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
125
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
126
- });
127
- var jobRuns = pgTable(
128
- "job_run",
129
- {
130
- id: uuid("id").primaryKey().defaultRandom(),
131
- jobType: text("job_type").notNull().references(() => jobs.type),
132
- jobVersion: integer("job_version").notNull(),
133
- parentRunId: uuid("parent_run_id").references(() => jobRuns.id),
134
- /**
135
- * Service generates `id` client-side via randomUUID() and sets
136
- * root_run_id = id for root runs (single INSERT, no self-FK race).
137
- */
138
- rootRunId: uuid("root_run_id").notNull(),
139
- parentClosePolicy: parentClosePolicyEnum("parent_close_policy").notNull().default("terminate"),
140
- scopeEntityType: text("scope_entity_type"),
141
- scopeEntityId: text("scope_entity_id"),
142
- tenantId: text("tenant_id"),
143
- tags: jsonb("tags").notNull().default({}).$type(),
144
- pool: text("pool").notNull(),
145
- priority: integer("priority").notNull().default(0),
146
- concurrencyKey: text("concurrency_key"),
147
- dedupeKey: text("dedupe_key"),
148
- status: jobRunStatusEnum("status").notNull().default("pending"),
149
- input: jsonb("input").notNull().$type(),
150
- output: jsonb("output").$type(),
151
- error: jsonb("error").$type(),
152
- triggerSource: triggerSourceEnum("trigger_source").notNull(),
153
- triggerRef: text("trigger_ref"),
154
- runAt: timestamp("run_at", { withTimezone: true }).notNull().defaultNow(),
155
- startedAt: timestamp("started_at", { withTimezone: true }),
156
- finishedAt: timestamp("finished_at", { withTimezone: true }),
157
- claimedAt: timestamp("claimed_at", { withTimezone: true }),
158
- attempts: integer("attempts").notNull().default(0),
159
- // Phase 3 placeholder — see ADR-025
160
- waitKind: waitKindEnum("wait_kind"),
161
- // Phase 3 placeholder — see ADR-025
162
- resumeToken: text("resume_token"),
163
- // Phase 3 placeholder — see ADR-025
164
- waitDeadline: timestamp("wait_deadline", { withTimezone: true }),
165
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
166
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
167
- },
168
- (t) => ({
169
- /** Claim query: ORDER BY priority DESC, run_at ASC. */
170
- idxJobRunClaim: index("idx_job_run_claim").on(t.status, t.pool, t.runAt),
171
- /** Tree traversal / cascade cancel. */
172
- idxJobRunRoot: index("idx_job_run_root").on(t.rootRunId),
173
- /** listForScope query. */
174
- idxJobRunScope: index("idx_job_run_scope").on(t.scopeEntityType, t.scopeEntityId),
175
- /** Idempotency collapse — partial index. */
176
- idxJobRunDedupe: index("idx_job_run_dedupe").on(t.jobType, t.dedupeKey).where(sql`${t.dedupeKey} IS NOT NULL`),
177
- /** Collision check — partial index. */
178
- idxJobRunConcurrency: index("idx_job_run_concurrency").on(t.concurrencyKey).where(
179
- sql`${t.concurrencyKey} IS NOT NULL AND ${t.status} IN ('pending','running')`
180
- )
181
- })
182
- );
183
- var jobSteps = pgTable(
184
- "job_step",
185
- {
186
- id: uuid("id").primaryKey().defaultRandom(),
187
- jobRunId: uuid("job_run_id").notNull().references(() => jobRuns.id),
188
- stepId: text("step_id").notNull(),
189
- kind: jobStepKindEnum("kind").notNull().default("task"),
190
- /**
191
- * Monotonic within run. integer (max ~2B per run) is sufficient —
192
- * downgraded from ADR-022's bigint; revisit only if a single run
193
- * ever exceeds 2 billion steps.
194
- */
195
- seq: integer("seq").notNull(),
196
- status: jobStepStatusEnum("status").notNull().default("pending"),
197
- input: jsonb("input").$type(),
198
- /** Memoised on success for replay. */
199
- output: jsonb("output").$type(),
200
- error: jsonb("error").$type(),
201
- attempts: integer("attempts").notNull().default(0),
202
- startedAt: timestamp("started_at", { withTimezone: true }),
203
- finishedAt: timestamp("finished_at", { withTimezone: true })
204
- },
205
- (t) => ({
206
- /** No duplicate step IDs per run. */
207
- idxJobStepRunStep: uniqueIndex("idx_job_step_run_step").on(t.jobRunId, t.stepId),
208
- /** Ordered timeline reads. */
209
- idxJobStepTimeline: index("idx_job_step_timeline").on(t.jobRunId, t.seq)
210
- })
211
- );
212
-
213
- // runtime/subsystems/jobs/jobs-errors.ts
214
- var JobTypeNotFoundError = class extends Error {
215
- constructor(jobType) {
216
- super(`No job definition registered for type '${jobType}'.`);
217
- this.jobType = jobType;
218
- }
219
- jobType;
220
- name = "JobTypeNotFoundError";
221
- };
222
- var JobCollisionError = class extends Error {
223
- constructor(jobType, concurrencyKey, incumbent) {
224
- super(
225
- `Job type '${jobType}' has an in-flight run with concurrency_key '${concurrencyKey}' (incumbent ${incumbent.id}); collision_mode=reject.`
226
- );
227
- this.jobType = jobType;
228
- this.concurrencyKey = concurrencyKey;
229
- this.incumbent = incumbent;
230
- }
231
- jobType;
232
- concurrencyKey;
233
- incumbent;
234
- name = "JobCollisionError";
235
- };
236
- var JobNotReplayableError = class extends Error {
237
- constructor(runId, currentStatus) {
238
- super(
239
- `Run ${runId} is not replayable from status '${currentStatus}'. Only 'completed', 'failed', 'timed_out', and 'canceled' are eligible.`
240
- );
241
- this.runId = runId;
242
- this.currentStatus = currentStatus;
243
- }
244
- runId;
245
- currentStatus;
246
- name = "JobNotReplayableError";
247
- };
248
- var JobTemplateFieldMissingError = class extends Error {
249
- constructor(template, field) {
250
- super(
251
- `Template '${template}' references input field '${field}' which is missing or undefined on the payload.`
252
- );
253
- this.template = template;
254
- this.field = field;
255
- }
256
- template;
257
- field;
258
- name = "JobTemplateFieldMissingError";
259
- };
260
- var MissingTenantIdError = class extends Error {
261
- constructor(method) {
262
- super(
263
- `MissingTenantIdError: JobsDomainModule was configured with multiTenant=true but ${method} was called without tenantId (undefined). Pass an explicit tenantId, or pass null for cross-tenant work.`
264
- );
265
- this.method = method;
266
- }
267
- method;
268
- name = "MissingTenantIdError";
269
- };
270
- var BootValidationError = class extends Error {
271
- constructor(missingHandlers) {
272
- super(
273
- `BootValidationError: ${missingHandlers.length} orphaned job type(s) in 'job' table with no matching @JobHandler in the running process: [${missingHandlers.join(", ")}]. Either register the handler(s) or remove the rows.`
274
- );
275
- this.missingHandlers = missingHandlers;
276
- }
277
- missingHandlers;
278
- name = "BootValidationError";
279
- };
280
- var ReservedPoolViolationError = class extends Error {
281
- constructor(offenders) {
282
- super(
283
- `ReservedPoolViolationError: ${offenders.length} @JobHandler(s) target reserved pools \u2014 reserved pools are framework-only:
284
- ` + offenders.map((o) => ` - ${o.handlerClass} \u2192 pool='${o.pool}'`).join("\n")
285
- );
286
- this.offenders = offenders;
287
- }
288
- offenders;
289
- name = "ReservedPoolViolationError";
290
- };
291
-
292
- // runtime/subsystems/jobs/job-orchestrator.drizzle-backend.ts
293
- var TERMINAL_STATUSES = [
294
- "completed",
295
- "failed",
296
- "timed_out",
297
- "canceled"
298
- ];
299
- var DEDUPE_EXCLUDED_STATUSES = ["canceled", "failed"];
300
- var IN_FLIGHT_STATUSES = ["pending", "running"];
301
- function evaluateKeyTemplate(template, input) {
302
- return template.replace(/\{\{\s*([a-zA-Z0-9_]+)\s*\}\}/g, (_match, field) => {
303
- const value = input[field];
304
- if (value === void 0 || value === null) {
305
- throw new JobTemplateFieldMissingError(template, field);
306
- }
307
- return String(value);
308
- });
309
- }
310
- var DrizzleJobOrchestrator = class {
311
- constructor(db, multiTenant) {
312
- this.db = db;
313
- this.multiTenant = multiTenant;
314
- }
315
- db;
316
- multiTenant;
317
- // TODO(logging-subsystem): swap to ILogger once ADR-028 lands
318
- logger = new Logger(DrizzleJobOrchestrator.name);
319
- /**
320
- * JOB-8 — resolve `tenantId` for a mutating / targeted-read call.
321
- * Returns the tenant value that should be written to the row (or compared
322
- * against in a WHERE clause). When `multiTenant` is off, the column is
323
- * forced to `null` regardless of what callers pass. When on, `undefined`
324
- * throws; `null` and strings pass through untouched.
325
- */
326
- resolveTenantId(method, tenantId) {
327
- if (!this.multiTenant) return null;
328
- if (tenantId === void 0) throw new MissingTenantIdError(method);
329
- return tenantId;
330
- }
331
- // ==========================================================================
332
- // start
333
- // ==========================================================================
334
- async start(type, input, opts = {}, tx) {
335
- const payload = input ?? {};
336
- const tenantId = this.resolveTenantId("start", opts.tenantId);
337
- const client = tx ?? this.db;
338
- const [def] = await client.select().from(jobs).where(eq(jobs.type, type)).limit(1);
339
- if (!def) throw new JobTypeNotFoundError(type);
340
- const definition = def;
341
- if (definition.dedupeKeyTemplate && definition.dedupeWindowMs) {
342
- const dedupeKey2 = evaluateKeyTemplate(definition.dedupeKeyTemplate, payload);
343
- const windowStart = new Date(Date.now() - definition.dedupeWindowMs);
344
- const existing = await client.select().from(jobRuns).where(
345
- and(
346
- eq(jobRuns.jobType, type),
347
- eq(jobRuns.dedupeKey, dedupeKey2),
348
- gt(jobRuns.createdAt, windowStart),
349
- // status NOT IN ('canceled', 'failed')
350
- notInStatus(DEDUPE_EXCLUDED_STATUSES)
351
- )
352
- ).orderBy(desc(jobRuns.createdAt)).limit(1);
353
- if (existing.length > 0) {
354
- return existing[0];
355
- }
356
- }
357
- let concurrencyKey = null;
358
- if (definition.concurrencyKeyTemplate) {
359
- concurrencyKey = evaluateKeyTemplate(
360
- definition.concurrencyKeyTemplate,
361
- payload
362
- );
363
- const inFlight = await client.select().from(jobRuns).where(
364
- and(
365
- eq(jobRuns.concurrencyKey, concurrencyKey),
366
- inArray(jobRuns.status, IN_FLIGHT_STATUSES)
367
- )
368
- ).limit(1);
369
- if (inFlight.length > 0) {
370
- const incumbent = inFlight[0];
371
- switch (definition.collisionMode) {
372
- case "reject":
373
- throw new JobCollisionError(type, concurrencyKey, incumbent);
374
- case "replace":
375
- await this.cancel(incumbent.id, {
376
- cascade: true,
377
- reason: "replaced",
378
- tenantId: incumbent.tenantId
379
- });
380
- break;
381
- case "queue":
382
- break;
383
- }
384
- }
385
- }
386
- const newId = randomUUID();
387
- let rootRunId = newId;
388
- if (opts.parentRunId) {
389
- const [parent] = await client.select({ rootRunId: jobRuns.rootRunId }).from(jobRuns).where(eq(jobRuns.id, opts.parentRunId)).limit(1);
390
- if (!parent) {
391
- throw new Error(
392
- `parentRunId ${opts.parentRunId} does not reference an existing job_run`
393
- );
394
- }
395
- rootRunId = parent.rootRunId;
396
- }
397
- const dedupeKey = definition.dedupeKeyTemplate ? evaluateKeyTemplate(definition.dedupeKeyTemplate, payload) : null;
398
- const [inserted] = await client.insert(jobRuns).values({
399
- id: newId,
400
- jobType: type,
401
- jobVersion: definition.version,
402
- parentRunId: opts.parentRunId ?? null,
403
- rootRunId,
404
- parentClosePolicy: opts.parentClosePolicy ?? "terminate",
405
- scopeEntityType: opts.scope?.entityType ?? null,
406
- scopeEntityId: opts.scope?.entityId ?? null,
407
- tenantId,
408
- tags: opts.tags ?? {},
409
- pool: opts.pool ?? definition.pool,
410
- priority: opts.priority ?? definition.priorityDefault,
411
- concurrencyKey,
412
- dedupeKey,
413
- status: "pending",
414
- input: payload,
415
- output: null,
416
- error: null,
417
- triggerSource: opts.triggerSource ?? "manual",
418
- triggerRef: opts.triggerRef ?? null,
419
- runAt: opts.runAt ?? /* @__PURE__ */ new Date(),
420
- startedAt: null,
421
- finishedAt: null,
422
- claimedAt: null,
423
- attempts: 0
424
- }).returning();
425
- return inserted;
426
- }
427
- // ==========================================================================
428
- // cancel
429
- // ==========================================================================
430
- async cancel(runId, opts = {}) {
431
- const tenantId = this.resolveTenantId("cancel", opts.tenantId);
432
- const [target] = await this.db.select().from(jobRuns).where(eq(jobRuns.id, runId)).limit(1);
433
- if (!target) return;
434
- if (this.multiTenant && target.tenantId !== tenantId) return;
435
- if (TERMINAL_STATUSES.includes(target.status)) {
436
- return;
437
- }
438
- const [cancelled] = await this.db.update(jobRuns).set({
439
- status: "canceled",
440
- finishedAt: /* @__PURE__ */ new Date(),
441
- updatedAt: /* @__PURE__ */ new Date()
442
- }).where(
443
- and(eq(jobRuns.id, runId), notInStatus([...TERMINAL_STATUSES]))
444
- ).returning();
445
- if (!cancelled) return;
446
- if (opts.cascade === false) return;
447
- const descendants = await this.db.select().from(jobRuns).where(
448
- and(
449
- eq(jobRuns.rootRunId, target.rootRunId),
450
- ne(jobRuns.id, runId),
451
- notInStatus([...TERMINAL_STATUSES])
452
- )
453
- );
454
- for (const child of descendants) {
455
- const policy = child.parentClosePolicy;
456
- if (policy === "abandon") continue;
457
- await this.db.update(jobRuns).set({
458
- status: "canceled",
459
- finishedAt: /* @__PURE__ */ new Date(),
460
- updatedAt: /* @__PURE__ */ new Date()
461
- }).where(
462
- and(
463
- eq(jobRuns.id, child.id),
464
- notInStatus([...TERMINAL_STATUSES])
465
- )
466
- );
467
- }
468
- void opts.reason;
469
- }
470
- // ==========================================================================
471
- // replay
472
- // ==========================================================================
473
- async replay(runId) {
474
- const [target] = await this.db.select().from(jobRuns).where(eq(jobRuns.id, runId)).limit(1);
475
- if (!target) {
476
- throw new Error(`replay: run ${runId} not found`);
477
- }
478
- const run = target;
479
- if (!TERMINAL_STATUSES.includes(run.status)) {
480
- throw new JobNotReplayableError(runId, run.status);
481
- }
482
- const [def] = await this.db.select().from(jobs).where(eq(jobs.type, run.jobType)).limit(1);
483
- if (!def) throw new JobTypeNotFoundError(run.jobType);
484
- const mode = def.replayFrom;
485
- const result = await this.db.transaction(async (tx) => {
486
- if (mode === "scratch") {
487
- await tx.delete(jobSteps).where(eq(jobSteps.jobRunId, runId));
488
- } else if (mode === "last_step") {
489
- await tx.delete(jobSteps).where(
490
- and(eq(jobSteps.jobRunId, runId), ne(jobSteps.status, "completed"))
491
- );
492
- } else {
493
- await tx.delete(jobSteps).where(
494
- and(eq(jobSteps.jobRunId, runId), ne(jobSteps.status, "completed"))
495
- );
496
- }
497
- const [updated] = await tx.update(jobRuns).set({
498
- status: "pending",
499
- attempts: 0,
500
- runAt: /* @__PURE__ */ new Date(),
501
- startedAt: null,
502
- finishedAt: null,
503
- claimedAt: null,
504
- error: null,
505
- output: null,
506
- updatedAt: /* @__PURE__ */ new Date()
507
- }).where(eq(jobRuns.id, runId)).returning();
508
- return updated;
509
- });
510
- return result;
511
- }
512
- // ==========================================================================
513
- // upsertJobRows — boot-time materialisation of `job` definitions
514
- // ==========================================================================
515
- /**
516
- * Hash-gated `INSERT … ON CONFLICT (type) DO UPDATE … WHERE` per Q3
517
- * resolution (2026-04-19): the `UPDATE` branch executes only when one
518
- * of the persisted metadata fields differs from the incoming payload;
519
- * `version` bumps only on real change; concurrent boots with identical
520
- * content are idempotent no-ops.
521
- *
522
- * Why this shape (not `DO NOTHING`, not advisory locks):
523
- * - `DO NOTHING` would let an old-version instance leave a stale row
524
- * that a new-version instance can't overwrite during a rolling deploy.
525
- * - Advisory locks add latency and leak risk under crashes.
526
- * - The `WHERE … IS DISTINCT FROM …` clause makes the conditional
527
- * atomic — no read-modify-write race on `version` between concurrent
528
- * boots.
529
- *
530
- * Orphan detection: a single `SELECT type FROM job WHERE type NOT IN (...)`
531
- * returns the types present in DB but absent from `entries`. Caller (boot
532
- * validator) decides whether to throw `BootValidationError`.
533
- */
534
- async upsertJobRows(entries, poolConfig) {
535
- void poolConfig;
536
- for (const entry of entries) {
537
- const meta = entry.meta;
538
- const pool = meta.pool ?? "batch";
539
- const retryPolicy = meta.retry ?? {
540
- attempts: 1,
541
- backoff: "fixed",
542
- baseMs: 0
543
- };
544
- const concurrencyKeyTemplate = meta.concurrency?.key;
545
- const concurrencyKeyTemplateStr = typeof concurrencyKeyTemplate === "string" ? concurrencyKeyTemplate : null;
546
- const collisionMode = meta.concurrency?.collisionMode ?? "queue";
547
- const dedupeKeyTemplate = meta.dedupe?.key;
548
- const dedupeKeyTemplateStr = typeof dedupeKeyTemplate === "string" ? dedupeKeyTemplate : null;
549
- const dedupeWindowMs = meta.dedupe?.windowMs ?? null;
550
- const timeoutMs = meta.timeoutMs ?? null;
551
- const replayFrom = meta.replayFrom ?? "last_checkpoint";
552
- const scopeEntityType = meta.scope?.entity ?? null;
553
- const priorityDefault = 0;
554
- await this.db.insert(jobs).values({
555
- type: entry.type,
556
- version: 1,
557
- pool,
558
- scopeEntityType,
559
- retryPolicy,
560
- timeoutMs,
561
- concurrencyKeyTemplate: concurrencyKeyTemplateStr,
562
- collisionMode,
563
- dedupeKeyTemplate: dedupeKeyTemplateStr,
564
- dedupeWindowMs,
565
- priorityDefault,
566
- replayFrom
567
- }).onConflictDoUpdate({
568
- target: jobs.type,
569
- set: {
570
- pool: sql2`EXCLUDED.pool`,
571
- scopeEntityType: sql2`EXCLUDED.scope_entity_type`,
572
- retryPolicy: sql2`EXCLUDED.retry_policy`,
573
- timeoutMs: sql2`EXCLUDED.timeout_ms`,
574
- concurrencyKeyTemplate: sql2`EXCLUDED.concurrency_key_template`,
575
- collisionMode: sql2`EXCLUDED.collision_mode`,
576
- dedupeKeyTemplate: sql2`EXCLUDED.dedupe_key_template`,
577
- dedupeWindowMs: sql2`EXCLUDED.dedupe_window_ms`,
578
- priorityDefault: sql2`EXCLUDED.priority_default`,
579
- replayFrom: sql2`EXCLUDED.replay_from`,
580
- version: sql2`${jobs.version} + 1`,
581
- updatedAt: sql2`now()`
582
- },
583
- // The hash gate: every field listed in the Q3 resolution appears
584
- // here. `IS DISTINCT FROM` is the null-safe inequality operator;
585
- // jsonb cast to text gives stable comparison without invoking a
586
- // dedicated hash column (avoids a JOB-1 schema migration).
587
- setWhere: sql2`
588
- ${jobs.pool} IS DISTINCT FROM EXCLUDED.pool OR
589
- ${jobs.retryPolicy}::text IS DISTINCT FROM EXCLUDED.retry_policy::text OR
590
- ${jobs.timeoutMs} IS DISTINCT FROM EXCLUDED.timeout_ms OR
591
- ${jobs.concurrencyKeyTemplate} IS DISTINCT FROM EXCLUDED.concurrency_key_template OR
592
- ${jobs.collisionMode} IS DISTINCT FROM EXCLUDED.collision_mode OR
593
- ${jobs.dedupeKeyTemplate} IS DISTINCT FROM EXCLUDED.dedupe_key_template OR
594
- ${jobs.dedupeWindowMs} IS DISTINCT FROM EXCLUDED.dedupe_window_ms OR
595
- ${jobs.priorityDefault} IS DISTINCT FROM EXCLUDED.priority_default OR
596
- ${jobs.replayFrom} IS DISTINCT FROM EXCLUDED.replay_from OR
597
- ${jobs.scopeEntityType} IS DISTINCT FROM EXCLUDED.scope_entity_type
598
- `
599
- });
600
- }
601
- const types = entries.map((e) => e.type);
602
- const orphans = types.length === 0 ? await this.db.select({ type: jobs.type }).from(jobs) : await this.db.select({ type: jobs.type }).from(jobs).where(notInArray(jobs.type, types));
603
- return { orphaned: orphans.map((o) => o.type) };
604
- }
605
- };
606
- DrizzleJobOrchestrator = __decorateClass([
607
- Injectable(),
608
- __decorateParam(0, Inject(DRIZZLE)),
609
- __decorateParam(1, Inject(JOBS_MULTI_TENANT))
610
- ], DrizzleJobOrchestrator);
611
- function notInStatus(statuses) {
612
- const negated = statuses.map((s) => ne(jobRuns.status, s));
613
- return and(...negated);
614
- }
615
-
616
- // runtime/subsystems/jobs/job-run-service.drizzle-backend.ts
617
- import { Inject as Inject2, Injectable as Injectable2 } from "@nestjs/common";
618
- import { and as and2, asc, desc as desc2, eq as eq2, gte, inArray as inArray2, isNull, lt, or, sql as sql3 } from "drizzle-orm";
619
-
620
- // runtime/subsystems/jobs/job-run-keyset-cursor.ts
621
- var DEFAULT_LIST_LIMIT = 50;
622
- var MAX_LIST_LIMIT = 200;
623
- function clampLimit(limit) {
624
- if (typeof limit !== "number" || !Number.isFinite(limit)) {
625
- return DEFAULT_LIST_LIMIT;
626
- }
627
- const floored = Math.floor(limit);
628
- if (floored < 1) return 1;
629
- if (floored > MAX_LIST_LIMIT) return MAX_LIST_LIMIT;
630
- return floored;
631
- }
632
- function encodeKeysetCursor(keyset) {
633
- const tuple = [keyset.createdAt.toISOString(), keyset.id];
634
- return Buffer.from(JSON.stringify(tuple), "utf8").toString("base64url");
635
- }
636
- function decodeKeysetCursor(cursor) {
637
- try {
638
- const json = Buffer.from(cursor, "base64url").toString("utf8");
639
- const parsed = JSON.parse(json);
640
- if (!Array.isArray(parsed) || parsed.length !== 2) return null;
641
- const [iso, id] = parsed;
642
- if (typeof iso !== "string" || typeof id !== "string") return null;
643
- const createdAt = new Date(iso);
644
- if (Number.isNaN(createdAt.getTime())) return null;
645
- return { createdAt, id };
646
- } catch {
647
- return null;
648
- }
649
- }
650
- function toJobRunSummary(r) {
651
- return {
652
- runId: r.id,
653
- rootRunId: r.rootRunId,
654
- parentRunId: r.parentRunId,
655
- triggerSource: r.triggerSource,
656
- triggerRef: r.triggerRef,
657
- jobType: r.jobType,
658
- pool: r.pool,
659
- status: r.status,
660
- scopeEntityType: r.scopeEntityType,
661
- scopeEntityId: r.scopeEntityId,
662
- tenantId: r.tenantId,
663
- attempts: r.attempts,
664
- errorMessage: r.error?.message ?? null,
665
- runAt: r.runAt,
666
- startedAt: r.startedAt,
667
- finishedAt: r.finishedAt,
668
- createdAt: r.createdAt
669
- };
670
- }
671
-
672
- // runtime/subsystems/jobs/job-run-service.drizzle-backend.ts
673
- var NON_TERMINAL_STATUSES = [
674
- "pending",
675
- "running",
676
- "waiting"
677
- ];
678
- var DrizzleJobRunService = class {
679
- constructor(db, orchestrator, multiTenant) {
680
- this.db = db;
681
- this.orchestrator = orchestrator;
682
- this.multiTenant = multiTenant;
683
- }
684
- db;
685
- orchestrator;
686
- multiTenant;
687
- /**
688
- * JOB-8 — produce the tenant WHERE fragment (or `null` to opt out).
689
- * Returns `null` when multi-tenancy is off (caller skips the predicate).
690
- * Throws `MissingTenantIdError` when on + `undefined`.
691
- * When on + explicit `null`, filters `tenant_id IS NULL`.
692
- */
693
- tenantCondition(method, tenantId) {
694
- if (!this.multiTenant) return null;
695
- if (tenantId === void 0) throw new MissingTenantIdError(method);
696
- return tenantId === null ? isNull(jobRuns.tenantId) : eq2(jobRuns.tenantId, tenantId);
697
- }
698
- async listForScope(entityType, entityId, opts = {}) {
699
- const conditions = [
700
- eq2(jobRuns.scopeEntityType, entityType),
701
- eq2(jobRuns.scopeEntityId, entityId)
702
- ];
703
- const tenantCond = this.tenantCondition("listForScope", opts.tenantId);
704
- if (tenantCond) conditions.push(tenantCond);
705
- if (opts.status) {
706
- if (Array.isArray(opts.status)) {
707
- conditions.push(inArray2(jobRuns.status, opts.status));
708
- } else {
709
- conditions.push(eq2(jobRuns.status, opts.status));
710
- }
711
- }
712
- if (opts.jobType) {
713
- conditions.push(eq2(jobRuns.jobType, opts.jobType));
714
- }
715
- const orderCol = (() => {
716
- switch (opts.orderBy) {
717
- case "created_at asc":
718
- return asc(jobRuns.createdAt);
719
- case "run_at desc":
720
- return desc2(jobRuns.runAt);
721
- case "run_at asc":
722
- return asc(jobRuns.runAt);
723
- case "created_at desc":
724
- default:
725
- return desc2(jobRuns.createdAt);
726
- }
727
- })();
728
- let q = this.db.select().from(jobRuns).where(and2(...conditions)).orderBy(orderCol).$dynamic();
729
- if (typeof opts.limit === "number") {
730
- q = q.limit(opts.limit);
731
- }
732
- if (typeof opts.offset === "number") {
733
- q = q.offset(opts.offset);
734
- }
735
- const rows = await q;
736
- return rows;
737
- }
738
- async cancelForScope(entityType, entityId, opts = {}) {
739
- const tenantCond = this.tenantCondition("cancelForScope", opts.tenantId);
740
- const conditions = [
741
- eq2(jobRuns.scopeEntityType, entityType),
742
- eq2(jobRuns.scopeEntityId, entityId),
743
- inArray2(jobRuns.status, NON_TERMINAL_STATUSES)
744
- ];
745
- if (tenantCond) conditions.push(tenantCond);
746
- const rows = await this.db.select({ id: jobRuns.id }).from(jobRuns).where(and2(...conditions));
747
- for (const { id } of rows) {
748
- await this.orchestrator.cancel(id, {
749
- cascade: true,
750
- tenantId: opts.tenantId
751
- });
752
- }
753
- }
754
- async rescheduleForScope(entityType, entityId, newRunAt, opts = {}) {
755
- const tenantCond = this.tenantCondition("rescheduleForScope", opts.tenantId);
756
- const conditions = [
757
- eq2(jobRuns.scopeEntityType, entityType),
758
- eq2(jobRuns.scopeEntityId, entityId),
759
- eq2(jobRuns.status, "pending")
760
- ];
761
- if (tenantCond) conditions.push(tenantCond);
762
- await this.db.update(jobRuns).set({ runAt: newRunAt, updatedAt: /* @__PURE__ */ new Date() }).where(and2(...conditions));
763
- }
764
- async countByPoolAndStatus(tenantId) {
765
- const tenantCond = this.tenantCondition("countByPoolAndStatus", tenantId);
766
- const rows = await this.db.select({
767
- pool: jobRuns.pool,
768
- status: jobRuns.status,
769
- count: sql3`count(*)::int`.as("count")
770
- }).from(jobRuns).where(tenantCond ?? void 0).groupBy(jobRuns.pool, jobRuns.status);
771
- return rows.map((r) => ({
772
- pool: r.pool,
773
- status: r.status,
774
- count: Number(r.count)
775
- }));
776
- }
777
- async listRecentFailed(limit, tenantId) {
778
- const conditions = [eq2(jobRuns.status, "failed")];
779
- const tenantCond = this.tenantCondition("listRecentFailed", tenantId);
780
- if (tenantCond) conditions.push(tenantCond);
781
- const rows = await this.db.select().from(jobRuns).where(and2(...conditions)).orderBy(desc2(jobRuns.finishedAt), desc2(jobRuns.updatedAt)).limit(limit);
782
- return rows.map((r) => ({
783
- runId: r.id,
784
- jobType: r.jobType,
785
- pool: r.pool,
786
- scopeEntityType: r.scopeEntityType,
787
- scopeEntityId: r.scopeEntityId,
788
- tenantId: r.tenantId,
789
- attempts: r.attempts,
790
- errorMessage: r.error?.message ?? null,
791
- failedAt: r.finishedAt ?? r.updatedAt,
792
- createdAt: r.createdAt
793
- }));
794
- }
795
- async listJobRuns(query = {}) {
796
- const limit = clampLimit(query.limit);
797
- const conditions = [];
798
- const tenantCond = this.tenantCondition("listJobRuns", query.tenantId);
799
- if (tenantCond) conditions.push(tenantCond);
800
- if (query.poolId) conditions.push(eq2(jobRuns.pool, query.poolId));
801
- if (query.rootRunId) conditions.push(eq2(jobRuns.rootRunId, query.rootRunId));
802
- if (query.status) conditions.push(eq2(jobRuns.status, query.status));
803
- if (query.since) conditions.push(gte(jobRuns.createdAt, query.since));
804
- if (query.cursor) {
805
- const keyset = decodeKeysetCursor(query.cursor);
806
- if (keyset) {
807
- conditions.push(
808
- or(
809
- lt(jobRuns.createdAt, keyset.createdAt),
810
- and2(
811
- eq2(jobRuns.createdAt, keyset.createdAt),
812
- lt(jobRuns.id, keyset.id)
813
- )
814
- )
815
- );
816
- }
817
- }
818
- const rows = await this.db.select().from(jobRuns).where(conditions.length > 0 ? and2(...conditions) : void 0).orderBy(desc2(jobRuns.createdAt), desc2(jobRuns.id)).limit(limit + 1);
819
- const hasMore = rows.length > limit;
820
- const page = hasMore ? rows.slice(0, limit) : rows;
821
- const items = page.map(toJobRunSummary);
822
- const last = page[page.length - 1];
823
- const nextCursor = hasMore && last ? encodeKeysetCursor({ createdAt: last.createdAt, id: last.id }) : null;
824
- return { items, nextCursor };
825
- }
826
- /**
827
- * Internal helper used by cascade paths (not on the public protocol).
828
- * Exposed as a public method on the concrete class so infrastructure
829
- * code (cascade tests, debug tools) can call it without a cast.
830
- */
831
- async findByRootRunId(rootRunId) {
832
- const rows = await this.db.select().from(jobRuns).where(eq2(jobRuns.rootRunId, rootRunId));
833
- return rows;
834
- }
835
- };
836
- DrizzleJobRunService = __decorateClass([
837
- Injectable2(),
838
- __decorateParam(0, Inject2(DRIZZLE)),
839
- __decorateParam(1, Inject2(JOB_ORCHESTRATOR)),
840
- __decorateParam(2, Inject2(JOBS_MULTI_TENANT))
841
- ], DrizzleJobRunService);
842
-
843
- // runtime/subsystems/jobs/job-step-service.drizzle-backend.ts
844
- import { Inject as Inject3, Injectable as Injectable3 } from "@nestjs/common";
845
- import { and as and3, eq as eq3 } from "drizzle-orm";
846
- var DrizzleJobStepService = class {
847
- constructor(db) {
848
- this.db = db;
849
- }
850
- db;
851
- async recordStep(input) {
852
- const values = {
853
- jobRunId: input.jobRunId,
854
- stepId: input.stepId,
855
- kind: input.kind,
856
- seq: input.seq,
857
- status: input.status,
858
- input: input.input ?? null,
859
- output: input.output ?? null,
860
- error: input.error ?? null,
861
- attempts: input.attempts ?? 0,
862
- startedAt: input.startedAt ?? null,
863
- finishedAt: input.finishedAt ?? null
864
- };
865
- const [row] = await this.db.insert(jobSteps).values(values).onConflictDoUpdate({
866
- target: [jobSteps.jobRunId, jobSteps.stepId],
867
- set: {
868
- status: values.status,
869
- output: values.output,
870
- error: values.error,
871
- finishedAt: values.finishedAt,
872
- attempts: values.attempts
873
- }
874
- }).returning();
875
- return row;
876
- }
877
- async findStep(runId, stepId) {
878
- const [row] = await this.db.select().from(jobSteps).where(and3(eq3(jobSteps.jobRunId, runId), eq3(jobSteps.stepId, stepId))).limit(1);
879
- return row ?? null;
880
- }
881
- };
882
- DrizzleJobStepService = __decorateClass([
883
- Injectable3(),
884
- __decorateParam(0, Inject3(DRIZZLE))
885
- ], DrizzleJobStepService);
886
-
887
- // runtime/subsystems/jobs/job-orchestrator.memory-backend.ts
888
- import { randomUUID as randomUUID3 } from "crypto";
889
- import { Inject as Inject5, Injectable as Injectable5, Logger as Logger2, Optional } from "@nestjs/common";
890
- import { ModuleRef } from "@nestjs/core";
891
-
892
- // runtime/subsystems/jobs/memory-job-store.ts
893
- var MemoryJobStore = class {
894
- /** Runs keyed by `id` (single source of truth for status/scope/lineage). */
895
- runs = /* @__PURE__ */ new Map();
896
- /** Steps keyed by `job_run_id`; array order matches insertion order. */
897
- steps = /* @__PURE__ */ new Map();
898
- /** Job definitions keyed by `type` — memory mirror of the `job` table. */
899
- jobs = /* @__PURE__ */ new Map();
900
- /** Reset everything. Tests call this in `beforeEach`. */
901
- clear() {
902
- this.runs.clear();
903
- this.steps.clear();
904
- this.jobs.clear();
905
- }
906
- };
907
-
908
- // runtime/subsystems/jobs/job-step-service.memory-backend.ts
909
- import { randomUUID as randomUUID2 } from "crypto";
910
- import { Inject as Inject4, Injectable as Injectable4 } from "@nestjs/common";
911
- var MemoryJobStepService = class {
912
- // ADR-037 (package-mode DI): explicit `@Inject(MemoryJobStore)` — the
913
- // published bundle carries no `design:paramtypes`, so a by-type inject
914
- // would resolve to `undefined` in package mode.
915
- constructor(store) {
916
- this.store = store;
917
- }
918
- store;
919
- async findStep(runId, stepId) {
920
- const rows = this.store.steps.get(runId);
921
- if (!rows) return null;
922
- const match = rows.find(
923
- (r) => r.stepId === stepId && r.status === "completed"
924
- );
925
- return match ?? null;
926
- }
927
- async recordStep(input) {
928
- const rows = this.getOrCreateRows(input.jobRunId);
929
- const existingIdx = rows.findIndex((r) => r.stepId === input.stepId);
930
- const normalisedInput = input.input ?? null;
931
- const normalisedOutput = input.output ?? null;
932
- if (existingIdx >= 0) {
933
- const prev = rows[existingIdx];
934
- const next = {
935
- ...prev,
936
- status: input.status,
937
- input: normalisedInput ?? prev.input,
938
- output: normalisedOutput ?? prev.output,
939
- error: input.error ?? prev.error,
940
- attempts: input.attempts ?? prev.attempts,
941
- startedAt: input.startedAt ?? prev.startedAt,
942
- finishedAt: input.finishedAt ?? prev.finishedAt
943
- };
944
- rows[existingIdx] = next;
945
- return next;
946
- }
947
- const seq = input.seq ?? this.nextSeq(rows);
948
- const row = {
949
- id: randomUUID2(),
950
- jobRunId: input.jobRunId,
951
- stepId: input.stepId,
952
- kind: input.kind,
953
- seq,
954
- status: input.status,
955
- input: normalisedInput,
956
- output: normalisedOutput,
957
- error: input.error ?? null,
958
- attempts: input.attempts ?? 0,
959
- startedAt: input.startedAt ?? null,
960
- finishedAt: input.finishedAt ?? null
961
- };
962
- rows.push(row);
963
- return row;
964
- }
965
- /**
966
- * Replay helper — wipe every step row for a run. Mirrors the `scratch`
967
- * replay mode of the Drizzle backend (`DELETE FROM job_step WHERE job_run_id = …`).
968
- */
969
- clearStepsForRun(runId) {
970
- this.store.steps.delete(runId);
971
- }
972
- /**
973
- * Remove every non-`completed` row for the run. Memoized (`completed`)
974
- * rows are preserved — this is the `last_checkpoint` / `last_step`
975
- * semantics the Drizzle backend implements via
976
- * `DELETE … WHERE status != 'completed'`. Both replay modes route here
977
- * (Phase 1 collapses `last_step` onto this behaviour; see JOB-3 notes).
978
- */
979
- clearIncompleteSteps(runId) {
980
- const rows = this.store.steps.get(runId);
981
- if (!rows) return;
982
- const kept = rows.filter((r) => r.status === "completed");
983
- if (kept.length === 0) {
984
- this.store.steps.delete(runId);
985
- } else {
986
- this.store.steps.set(runId, kept);
987
- }
988
- }
989
- getOrCreateRows(runId) {
990
- let rows = this.store.steps.get(runId);
991
- if (!rows) {
992
- rows = [];
993
- this.store.steps.set(runId, rows);
994
- }
995
- return rows;
996
- }
997
- nextSeq(rows) {
998
- let max = 0;
999
- for (const r of rows) {
1000
- if (r.seq > max) max = r.seq;
1001
- }
1002
- return max + 1;
1003
- }
1004
- };
1005
- MemoryJobStepService = __decorateClass([
1006
- Injectable4(),
1007
- __decorateParam(0, Inject4(MemoryJobStore))
1008
- ], MemoryJobStepService);
1009
-
1010
- // runtime/subsystems/jobs/job-orchestrator.memory-backend.ts
1011
- var QUEUED_RUN_AT = /* @__PURE__ */ new Date(864e13);
1012
- var TERMINAL_STATUSES2 = [
1013
- "completed",
1014
- "failed",
1015
- "timed_out",
1016
- "canceled"
1017
- ];
1018
- var DEDUPE_EXCLUDED_STATUSES2 = ["canceled", "failed"];
1019
- var IN_FLIGHT_STATUSES2 = ["pending", "running"];
1020
- function isTerminal(status) {
1021
- return TERMINAL_STATUSES2.includes(status);
1022
- }
1023
- function evaluateKeyTemplate2(template, input) {
1024
- return template.replace(
1025
- /\{\{\s*([a-zA-Z0-9_]+)\s*\}\}/g,
1026
- (_m, field) => {
1027
- const value = input[field];
1028
- if (value === void 0 || value === null) {
1029
- throw new JobTemplateFieldMissingError(template, field);
1030
- }
1031
- return String(value);
1032
- }
1033
- );
1034
- }
1035
- var PromiseMutex = class {
1036
- queue = Promise.resolve();
1037
- async run(fn) {
1038
- const next = this.queue.then(() => fn());
1039
- this.queue = next.then(
1040
- () => void 0,
1041
- () => void 0
1042
- );
1043
- return next;
1044
- }
1045
- };
1046
- var MemoryJobOrchestrator = class {
1047
- constructor(store, stepService, multiTenant, moduleRef) {
1048
- this.store = store;
1049
- this.stepService = stepService;
1050
- this.multiTenant = multiTenant;
1051
- this.moduleRef = moduleRef;
1052
- }
1053
- store;
1054
- stepService;
1055
- multiTenant;
1056
- moduleRef;
1057
- logger = new Logger2(MemoryJobOrchestrator.name);
1058
- mutex = new PromiseMutex();
1059
- handlerRegistry = /* @__PURE__ */ new Map();
1060
- /**
1061
- * `runId → dependent runId[]` — when a run with `concurrencyKey = K`
1062
- * blocks on an incumbent, its id is added here under the incumbent's id.
1063
- * On incumbent terminal transition we advance every dependent's `runAt`
1064
- * back to `now()` so it becomes claimable.
1065
- */
1066
- queueBlockers = /* @__PURE__ */ new Map();
1067
- /**
1068
- * JOB-8 — mirror of the Drizzle backend's `resolveTenantId`. Returns the
1069
- * value to stamp on `tenant_id` / compare against in memory predicates.
1070
- * Off → always `null`. On + `undefined` → throw. On + `null`/string → pass.
1071
- */
1072
- resolveTenantId(method, tenantId) {
1073
- if (!this.multiTenant) return null;
1074
- if (tenantId === void 0) throw new MissingTenantIdError(method);
1075
- return tenantId;
1076
- }
1077
- // ==========================================================================
1078
- // registerHandler — replaces Drizzle's `job` table upsert
1079
- // ==========================================================================
1080
- /**
1081
- * Populate the in-memory job definition row plus handler class lookup.
1082
- * Called by `JobWorkerModule.onModuleInit` in memory mode, or directly by
1083
- * unit tests that want to seed the registry without NestJS.
1084
- */
1085
- registerHandler(type, meta, handlerClass) {
1086
- const concurrencyKeyTemplate = meta.concurrency?.key ?? null;
1087
- const dedupeKeyTemplate = meta.dedupe?.key ?? null;
1088
- const dedupeWindowMs = meta.dedupe?.windowMs ?? null;
1089
- const now = /* @__PURE__ */ new Date();
1090
- const def = {
1091
- type,
1092
- version: 1,
1093
- pool: meta.pool ?? "batch",
1094
- scopeEntityType: meta.scope?.entity ?? null,
1095
- retryPolicy: meta.retry ?? {
1096
- attempts: 1,
1097
- backoff: "fixed",
1098
- baseMs: 0
1099
- },
1100
- timeoutMs: meta.timeoutMs ?? null,
1101
- concurrencyKeyTemplate: typeof concurrencyKeyTemplate === "string" ? concurrencyKeyTemplate : null,
1102
- collisionMode: meta.concurrency?.collisionMode ?? "queue",
1103
- dedupeKeyTemplate: typeof dedupeKeyTemplate === "string" ? dedupeKeyTemplate : null,
1104
- dedupeWindowMs,
1105
- priorityDefault: 0,
1106
- replayFrom: meta.replayFrom ?? "last_checkpoint",
1107
- createdAt: now,
1108
- updatedAt: now
1109
- };
1110
- this.store.jobs.set(type, def);
1111
- this.handlerRegistry.set(type, {
1112
- type,
1113
- meta,
1114
- handlerClass
1115
- });
1116
- }
1117
- /** Test helper — look up a registered handler without exposing the map. */
1118
- getHandlerRegistration(type) {
1119
- return this.handlerRegistry.get(type);
1120
- }
1121
- /**
1122
- * Boot-time upsert per `IJobOrchestrator.upsertJobRows`. Memory backend
1123
- * just funnels each entry through `registerHandler`. The validator is
1124
- * skipped entirely in memory mode (Q4 resolution 2026-04-19), so the
1125
- * orphaned list is always empty — there are no DB rows to compare against.
1126
- */
1127
- async upsertJobRows(entries, poolConfig) {
1128
- void poolConfig;
1129
- for (const entry of entries) {
1130
- this.registerHandler(
1131
- entry.type,
1132
- entry.meta,
1133
- entry.handlerClass
1134
- );
1135
- }
1136
- return { orphaned: [] };
1137
- }
1138
- // ==========================================================================
1139
- // start
1140
- // ==========================================================================
1141
- async start(type, input, opts = {}, _tx) {
1142
- const tenantId = this.resolveTenantId("start", opts.tenantId);
1143
- return this.mutex.run(async () => {
1144
- const payload = input ?? {};
1145
- const definition = this.store.jobs.get(type);
1146
- if (!definition) throw new JobTypeNotFoundError(type);
1147
- if (definition.dedupeKeyTemplate && definition.dedupeWindowMs) {
1148
- const dedupeKey2 = evaluateKeyTemplate2(
1149
- definition.dedupeKeyTemplate,
1150
- payload
1151
- );
1152
- const windowStart = Date.now() - definition.dedupeWindowMs;
1153
- const existing = this.findDedupeCandidate(type, dedupeKey2, windowStart);
1154
- if (existing) return existing;
1155
- }
1156
- let concurrencyKey = null;
1157
- let queueBlockedBy = null;
1158
- if (definition.concurrencyKeyTemplate) {
1159
- concurrencyKey = evaluateKeyTemplate2(
1160
- definition.concurrencyKeyTemplate,
1161
- payload
1162
- );
1163
- const incumbent = this.findInFlightByConcurrencyKey(concurrencyKey);
1164
- if (incumbent) {
1165
- switch (definition.collisionMode) {
1166
- case "reject":
1167
- throw new JobCollisionError(type, concurrencyKey, incumbent);
1168
- case "replace":
1169
- this.cancelLocked(
1170
- incumbent.id,
1171
- { cascade: true, reason: "replaced" },
1172
- incumbent.tenantId
1173
- );
1174
- break;
1175
- case "queue":
1176
- queueBlockedBy = incumbent.id;
1177
- break;
1178
- }
1179
- }
1180
- }
1181
- const newId = randomUUID3();
1182
- let rootRunId = newId;
1183
- if (opts.parentRunId) {
1184
- const parent = this.store.runs.get(opts.parentRunId);
1185
- if (!parent) {
1186
- throw new Error(
1187
- `parentRunId ${opts.parentRunId} does not reference an existing job_run`
1188
- );
1189
- }
1190
- rootRunId = parent.rootRunId;
1191
- }
1192
- const dedupeKey = definition.dedupeKeyTemplate ? evaluateKeyTemplate2(definition.dedupeKeyTemplate, payload) : null;
1193
- const now = /* @__PURE__ */ new Date();
1194
- const runAt = queueBlockedBy ? QUEUED_RUN_AT : opts.runAt ?? now;
1195
- const row = {
1196
- id: newId,
1197
- jobType: type,
1198
- jobVersion: definition.version,
1199
- parentRunId: opts.parentRunId ?? null,
1200
- rootRunId,
1201
- parentClosePolicy: opts.parentClosePolicy ?? "terminate",
1202
- scopeEntityType: opts.scope?.entityType ?? null,
1203
- scopeEntityId: opts.scope?.entityId ?? null,
1204
- tenantId,
1205
- tags: opts.tags ?? {},
1206
- pool: opts.pool ?? definition.pool,
1207
- priority: opts.priority ?? definition.priorityDefault,
1208
- concurrencyKey,
1209
- dedupeKey,
1210
- status: "pending",
1211
- input: payload,
1212
- output: null,
1213
- error: null,
1214
- triggerSource: opts.triggerSource ?? "manual",
1215
- triggerRef: opts.triggerRef ?? null,
1216
- runAt,
1217
- startedAt: null,
1218
- finishedAt: null,
1219
- claimedAt: null,
1220
- attempts: 0,
1221
- waitKind: null,
1222
- resumeToken: null,
1223
- waitDeadline: null,
1224
- createdAt: now,
1225
- updatedAt: now
1226
- };
1227
- this.store.runs.set(newId, row);
1228
- if (queueBlockedBy) {
1229
- const list = this.queueBlockers.get(queueBlockedBy) ?? [];
1230
- list.push(newId);
1231
- this.queueBlockers.set(queueBlockedBy, list);
1232
- }
1233
- return row;
1234
- });
1235
- }
1236
- // ==========================================================================
1237
- // cancel
1238
- // ==========================================================================
1239
- async cancel(runId, opts = {}) {
1240
- const tenantId = this.resolveTenantId("cancel", opts.tenantId);
1241
- await this.mutex.run(async () => {
1242
- this.cancelLocked(runId, opts, tenantId);
1243
- });
1244
- }
1245
- /**
1246
- * Internal cancel that assumes the caller already holds the mutex.
1247
- * Synchronous because all store ops are in-memory. Idempotent.
1248
- *
1249
- * `tenantForGate` is the already-validated tenant id (or `null`). When
1250
- * non-null it gates the initial cancellation to that tenant's run; the
1251
- * cascade step then sweeps descendants on the same `rootRunId` without
1252
- * re-checking — children of a tenant-gated parent always share the
1253
- * tenant (enforced at `start` time).
1254
- */
1255
- cancelLocked(runId, opts, tenantForGate) {
1256
- const run = this.store.runs.get(runId);
1257
- if (!run) return;
1258
- if (this.multiTenant && run.tenantId !== tenantForGate) return;
1259
- if (isTerminal(run.status)) return;
1260
- const now = /* @__PURE__ */ new Date();
1261
- const descendants = opts.cascade === false ? [] : Array.from(this.store.runs.values()).filter(
1262
- (r) => r.rootRunId === run.rootRunId && r.id !== runId && !isTerminal(r.status)
1263
- );
1264
- const terminateChildren = descendants.filter(
1265
- (d) => d.parentClosePolicy === "terminate" /* Terminate */
1266
- );
1267
- const cancelChildren = descendants.filter(
1268
- (d) => d.parentClosePolicy === "cancel" /* Cancel */
1269
- );
1270
- for (const child of terminateChildren) {
1271
- this.transitionToCanceled(child.id, now);
1272
- }
1273
- for (const child of cancelChildren) {
1274
- this.transitionToCanceled(child.id, now);
1275
- }
1276
- this.transitionToCanceled(runId, now);
1277
- void opts.reason;
1278
- }
1279
- transitionToCanceled(runId, at) {
1280
- const run = this.store.runs.get(runId);
1281
- if (!run) return;
1282
- if (isTerminal(run.status)) return;
1283
- const next = {
1284
- ...run,
1285
- status: "canceled",
1286
- finishedAt: at,
1287
- updatedAt: at
1288
- };
1289
- this.store.runs.set(runId, next);
1290
- this.unblockQueuedDependents(runId);
1291
- }
1292
- /**
1293
- * When `runId` transitions to a terminal state, advance every dependent
1294
- * `queue`-blocked run's `run_at` back to `now()` so `claimNext` picks
1295
- * them up.
1296
- */
1297
- unblockQueuedDependents(runId) {
1298
- const dependents = this.queueBlockers.get(runId);
1299
- if (!dependents || dependents.length === 0) return;
1300
- const now = /* @__PURE__ */ new Date();
1301
- for (const dep of dependents) {
1302
- const depRun = this.store.runs.get(dep);
1303
- if (!depRun) continue;
1304
- if (depRun.status !== "pending") continue;
1305
- this.store.runs.set(dep, { ...depRun, runAt: now, updatedAt: now });
1306
- }
1307
- this.queueBlockers.delete(runId);
1308
- }
1309
- // ==========================================================================
1310
- // claimNext — consumed by JobWorker in memory mode (tests exercise directly)
1311
- // ==========================================================================
1312
- async claimNext(pool) {
1313
- return this.mutex.run(async () => {
1314
- const now = Date.now();
1315
- const candidates = Array.from(this.store.runs.values()).filter(
1316
- (r) => r.status === "pending" && r.pool === pool && r.runAt.getTime() <= now
1317
- );
1318
- if (candidates.length === 0) return null;
1319
- candidates.sort((a, b) => {
1320
- if (a.priority !== b.priority) return b.priority - a.priority;
1321
- return a.runAt.getTime() - b.runAt.getTime();
1322
- });
1323
- const winner = candidates[0];
1324
- const claimedAt = /* @__PURE__ */ new Date();
1325
- const next = {
1326
- ...winner,
1327
- status: "running",
1328
- claimedAt,
1329
- startedAt: claimedAt,
1330
- updatedAt: claimedAt
1331
- };
1332
- this.store.runs.set(winner.id, next);
1333
- return next;
1334
- });
1335
- }
1336
- // ==========================================================================
1337
- // replay
1338
- // ==========================================================================
1339
- async replay(runId) {
1340
- return this.mutex.run(async () => {
1341
- const run = this.store.runs.get(runId);
1342
- if (!run) throw new Error(`replay: run ${runId} not found`);
1343
- if (!isTerminal(run.status)) {
1344
- throw new JobNotReplayableError(runId, run.status);
1345
- }
1346
- const def = this.store.jobs.get(run.jobType);
1347
- if (!def) throw new JobTypeNotFoundError(run.jobType);
1348
- const mode = def.replayFrom;
1349
- if (mode === "scratch") {
1350
- this.stepService.clearStepsForRun(runId);
1351
- } else {
1352
- this.stepService.clearIncompleteSteps(runId);
1353
- }
1354
- const now = /* @__PURE__ */ new Date();
1355
- const next = {
1356
- ...run,
1357
- status: "pending",
1358
- attempts: 0,
1359
- runAt: now,
1360
- startedAt: null,
1361
- finishedAt: null,
1362
- claimedAt: null,
1363
- error: null,
1364
- output: null,
1365
- updatedAt: now
1366
- };
1367
- this.store.runs.set(runId, next);
1368
- return next;
1369
- });
1370
- }
1371
- // ==========================================================================
1372
- // tick — used by unit tests + memory-mode JobWorker
1373
- // ==========================================================================
1374
- /**
1375
- * Execute a single claimed run to completion, retry, or failure. Not on
1376
- * `IJobOrchestrator` — it's the memory equivalent of the Drizzle
1377
- * `JobWorker.processRun` code path. The unit tests drive it directly so
1378
- * they can assert memoization across ticks without spinning up a worker.
1379
- */
1380
- async tick(runId) {
1381
- const run = this.store.runs.get(runId);
1382
- if (!run) throw new Error(`tick: run ${runId} not found`);
1383
- if (run.status !== "running") {
1384
- throw new Error(
1385
- `tick: run ${runId} must be 'running' (got '${run.status}')`
1386
- );
1387
- }
1388
- const registration = this.handlerRegistry.get(run.jobType);
1389
- if (!registration) {
1390
- await this.markFailed(run, new Error(
1391
- `No handler registered for jobType='${run.jobType}'`
1392
- ), (run.attempts ?? 0) + 1);
1393
- return;
1394
- }
1395
- const meta = registration.meta;
1396
- const HandlerClass = registration.handlerClass;
1397
- const handler = this.moduleRef ? this.moduleRef.get(
1398
- HandlerClass,
1399
- { strict: false }
1400
- ) : new HandlerClass();
1401
- const ctx = {
1402
- input: run.input,
1403
- run,
1404
- step: this.makeStepFn(run),
1405
- spawnChild: this.makeSpawnFn(run),
1406
- logger: new Logger2(`JobRun:${run.id}`)
1407
- };
1408
- const attemptsBefore = run.attempts ?? 0;
1409
- try {
1410
- const output = await handler.run(ctx);
1411
- await this.markCompleted(run, output ?? {}, attemptsBefore + 1);
1412
- } catch (err) {
1413
- const policy = meta.retry;
1414
- const decision = classifyError(err, policy, attemptsBefore);
1415
- const nextAttempts = attemptsBefore + 1;
1416
- if (decision === "retry" && policy) {
1417
- const delay = computeBackoff(policy, nextAttempts);
1418
- await this.rescheduleForRetry(run, err, nextAttempts, delay);
1419
- } else {
1420
- await this.markFailed(run, err, nextAttempts);
1421
- }
1422
- }
1423
- }
1424
- makeStepFn(run) {
1425
- return async (stepId, fn, _opts) => {
1426
- void _opts;
1427
- const existing = await this.stepService.findStep(run.id, stepId);
1428
- if (existing?.status === "completed") {
1429
- return existing.output;
1430
- }
1431
- const seq = this.nextStepSeq(run.id);
1432
- const startedAt = /* @__PURE__ */ new Date();
1433
- const nextAttempts = (existing?.attempts ?? 0) + 1;
1434
- await this.stepService.recordStep({
1435
- jobRunId: run.id,
1436
- stepId,
1437
- kind: "task",
1438
- seq,
1439
- status: "running",
1440
- startedAt,
1441
- attempts: nextAttempts
1442
- });
1443
- try {
1444
- const output = await fn();
1445
- await this.stepService.recordStep({
1446
- jobRunId: run.id,
1447
- stepId,
1448
- kind: "task",
1449
- seq,
1450
- status: "completed",
1451
- output,
1452
- finishedAt: /* @__PURE__ */ new Date(),
1453
- attempts: nextAttempts
1454
- });
1455
- return output;
1456
- } catch (err) {
1457
- await this.stepService.recordStep({
1458
- jobRunId: run.id,
1459
- stepId,
1460
- kind: "task",
1461
- seq,
1462
- status: "failed",
1463
- error: serialiseError(err, nextAttempts, false),
1464
- finishedAt: /* @__PURE__ */ new Date(),
1465
- attempts: nextAttempts
1466
- });
1467
- throw err;
1468
- }
1469
- };
1470
- }
1471
- makeSpawnFn(run) {
1472
- return async (type, input, opts) => {
1473
- return this.start(type, input, {
1474
- parentRunId: run.id,
1475
- parentClosePolicy: opts?.closePolicy,
1476
- runAt: opts?.runAt,
1477
- priority: opts?.priority,
1478
- tags: opts?.tags,
1479
- triggerSource: "parent",
1480
- triggerRef: run.id
1481
- });
1482
- };
1483
- }
1484
- nextStepSeq(runId) {
1485
- const rows = this.store.steps.get(runId);
1486
- if (!rows || rows.length === 0) return 1;
1487
- let max = 0;
1488
- for (const r of rows) if (r.seq > max) max = r.seq;
1489
- return max + 1;
1490
- }
1491
- async markCompleted(run, output, attempts) {
1492
- await this.mutex.run(async () => {
1493
- const current = this.store.runs.get(run.id);
1494
- if (!current || isTerminal(current.status)) return;
1495
- const now = /* @__PURE__ */ new Date();
1496
- this.store.runs.set(run.id, {
1497
- ...current,
1498
- status: "completed",
1499
- output,
1500
- finishedAt: now,
1501
- updatedAt: now,
1502
- attempts
1503
- });
1504
- this.unblockQueuedDependents(run.id);
1505
- });
1506
- }
1507
- async markFailed(run, err, attempts) {
1508
- await this.mutex.run(async () => {
1509
- const current = this.store.runs.get(run.id);
1510
- if (!current || isTerminal(current.status)) return;
1511
- const now = /* @__PURE__ */ new Date();
1512
- this.store.runs.set(run.id, {
1513
- ...current,
1514
- status: "failed",
1515
- finishedAt: now,
1516
- updatedAt: now,
1517
- attempts,
1518
- error: serialiseError(err, attempts, false)
1519
- });
1520
- this.unblockQueuedDependents(run.id);
1521
- });
1522
- if (run.parentClosePolicy === "terminate") {
1523
- try {
1524
- await this.cancel(run.id, {
1525
- cascade: true,
1526
- reason: "parent-failed",
1527
- tenantId: run.tenantId
1528
- });
1529
- } catch (cascadeErr) {
1530
- this.logger.warn(
1531
- `cascade on failed run ${run.id}: ${cascadeErr.message}`
1532
- );
1533
- }
1534
- }
1535
- }
1536
- async rescheduleForRetry(run, err, attempts, delayMs) {
1537
- await this.mutex.run(async () => {
1538
- const current = this.store.runs.get(run.id);
1539
- if (!current || isTerminal(current.status)) return;
1540
- const now = /* @__PURE__ */ new Date();
1541
- this.store.runs.set(run.id, {
1542
- ...current,
1543
- status: "pending",
1544
- attempts,
1545
- runAt: new Date(Date.now() + delayMs),
1546
- startedAt: null,
1547
- claimedAt: null,
1548
- updatedAt: now,
1549
- error: serialiseError(err, attempts, true)
1550
- });
1551
- });
1552
- }
1553
- // ==========================================================================
1554
- // Internal queries — used by start / cancel
1555
- // ==========================================================================
1556
- findDedupeCandidate(jobType, dedupeKey, windowStartMs) {
1557
- let best = null;
1558
- for (const r of this.store.runs.values()) {
1559
- if (r.jobType !== jobType) continue;
1560
- if (r.dedupeKey !== dedupeKey) continue;
1561
- if (DEDUPE_EXCLUDED_STATUSES2.includes(r.status)) continue;
1562
- if (r.createdAt.getTime() <= windowStartMs) continue;
1563
- if (!best || r.createdAt.getTime() > best.createdAt.getTime()) {
1564
- best = r;
1565
- }
1566
- }
1567
- return best;
1568
- }
1569
- findInFlightByConcurrencyKey(key) {
1570
- for (const r of this.store.runs.values()) {
1571
- if (r.concurrencyKey !== key) continue;
1572
- if (!IN_FLIGHT_STATUSES2.includes(r.status)) continue;
1573
- return r;
1574
- }
1575
- return null;
1576
- }
1577
- };
1578
- MemoryJobOrchestrator = __decorateClass([
1579
- Injectable5(),
1580
- __decorateParam(0, Inject5(MemoryJobStore)),
1581
- __decorateParam(1, Inject5(MemoryJobStepService)),
1582
- __decorateParam(2, Inject5(JOBS_MULTI_TENANT)),
1583
- __decorateParam(3, Optional()),
1584
- __decorateParam(3, Inject5(ModuleRef))
1585
- ], MemoryJobOrchestrator);
1586
- function classifyError(err, policy, currentAttempts) {
1587
- if (!policy) return "fail";
1588
- const errObj = err;
1589
- const name = errObj?.name;
1590
- const code = errObj?.code;
1591
- const nonRetryable = policy.nonRetryableErrors ?? [];
1592
- if (nonRetryable.some((n) => n === name || n === code)) return "fail";
1593
- if (currentAttempts + 1 >= policy.attempts) return "fail";
1594
- return "retry";
1595
- }
1596
- function computeBackoff(policy, attempts) {
1597
- const base = Math.max(policy.baseMs, 0);
1598
- if (policy.backoff === "fixed") return base;
1599
- const exponent = Math.max(attempts - 1, 0);
1600
- if (exponent >= 53) return Number.MAX_SAFE_INTEGER;
1601
- const raw = base * Math.pow(2, exponent);
1602
- if (!Number.isFinite(raw) || raw >= Number.MAX_SAFE_INTEGER) {
1603
- return Number.MAX_SAFE_INTEGER;
1604
- }
1605
- return raw;
1606
- }
1607
- function serialiseError(err, attempt, retryable) {
1608
- const e = err;
1609
- return {
1610
- message: e?.message ?? String(err),
1611
- stack: e?.stack,
1612
- retryable,
1613
- attempt
1614
- };
1615
- }
1616
-
1617
- // runtime/subsystems/jobs/job-run-service.memory-backend.ts
1618
- import { Inject as Inject6, Injectable as Injectable6 } from "@nestjs/common";
1619
- var NON_TERMINAL_STATUSES2 = [
1620
- "pending",
1621
- "running",
1622
- "waiting"
1623
- ];
1624
- var MemoryJobRunService = class {
1625
- constructor(store, orchestrator, multiTenant) {
1626
- this.store = store;
1627
- this.orchestrator = orchestrator;
1628
- this.multiTenant = multiTenant;
1629
- }
1630
- store;
1631
- orchestrator;
1632
- multiTenant;
1633
- /**
1634
- * JOB-8 — produce a per-row predicate for the tenant gate.
1635
- * Returns `null` when multi-tenancy is off (caller doesn't check).
1636
- * Throws when on + `undefined`; matches `tenant_id IS NULL` on explicit
1637
- * `null` to support cross-tenant background work.
1638
- */
1639
- tenantPredicate(method, tenantId) {
1640
- if (!this.multiTenant) return null;
1641
- if (tenantId === void 0) throw new MissingTenantIdError(method);
1642
- return (r) => r.tenantId === tenantId;
1643
- }
1644
- async listForScope(entityType, entityId, opts = {}) {
1645
- const statusFilter = opts.status ? Array.isArray(opts.status) ? new Set(opts.status) : /* @__PURE__ */ new Set([opts.status]) : null;
1646
- const tenantCheck = this.tenantPredicate("listForScope", opts.tenantId);
1647
- const rows = [];
1648
- for (const r of this.store.runs.values()) {
1649
- if (r.scopeEntityType !== entityType) continue;
1650
- if (r.scopeEntityId !== entityId) continue;
1651
- if (statusFilter && !statusFilter.has(r.status)) continue;
1652
- if (opts.jobType && r.jobType !== opts.jobType) continue;
1653
- if (tenantCheck && !tenantCheck(r)) continue;
1654
- rows.push(r);
1655
- }
1656
- const orderBy = opts.orderBy ?? "created_at desc";
1657
- rows.sort((a, b) => compareBy(a, b, orderBy));
1658
- const offset = opts.offset ?? 0;
1659
- const limit = opts.limit;
1660
- const sliced = typeof limit === "number" ? rows.slice(offset, offset + limit) : rows.slice(offset);
1661
- return sliced;
1662
- }
1663
- async cancelForScope(entityType, entityId, opts = {}) {
1664
- const tenantCheck = this.tenantPredicate("cancelForScope", opts.tenantId);
1665
- const ids = [];
1666
- for (const r of this.store.runs.values()) {
1667
- if (r.scopeEntityType !== entityType) continue;
1668
- if (r.scopeEntityId !== entityId) continue;
1669
- if (!NON_TERMINAL_STATUSES2.includes(r.status)) continue;
1670
- if (tenantCheck && !tenantCheck(r)) continue;
1671
- ids.push(r.id);
1672
- }
1673
- for (const id of ids) {
1674
- await this.orchestrator.cancel(id, {
1675
- cascade: true,
1676
- tenantId: opts.tenantId
1677
- });
1678
- }
1679
- }
1680
- async rescheduleForScope(entityType, entityId, newRunAt, opts = {}) {
1681
- const tenantCheck = this.tenantPredicate("rescheduleForScope", opts.tenantId);
1682
- for (const r of this.store.runs.values()) {
1683
- if (r.scopeEntityType !== entityType) continue;
1684
- if (r.scopeEntityId !== entityId) continue;
1685
- if (r.status !== "pending") continue;
1686
- if (tenantCheck && !tenantCheck(r)) continue;
1687
- this.store.runs.set(r.id, {
1688
- ...r,
1689
- runAt: newRunAt,
1690
- updatedAt: /* @__PURE__ */ new Date()
1691
- });
1692
- }
1693
- }
1694
- async countByPoolAndStatus(tenantId) {
1695
- const tenantCheck = this.tenantPredicate("countByPoolAndStatus", tenantId);
1696
- const map = /* @__PURE__ */ new Map();
1697
- for (const r of this.store.runs.values()) {
1698
- if (tenantCheck && !tenantCheck(r)) continue;
1699
- const key = `${r.pool}\0${r.status}`;
1700
- const cur = map.get(key);
1701
- if (cur) {
1702
- cur.count += 1;
1703
- } else {
1704
- map.set(key, { pool: r.pool, status: r.status, count: 1 });
1705
- }
1706
- }
1707
- return Array.from(map.values());
1708
- }
1709
- async listRecentFailed(limit, tenantId) {
1710
- const tenantCheck = this.tenantPredicate("listRecentFailed", tenantId);
1711
- const failed = [];
1712
- for (const r of this.store.runs.values()) {
1713
- if (r.status !== "failed") continue;
1714
- if (tenantCheck && !tenantCheck(r)) continue;
1715
- failed.push(r);
1716
- }
1717
- failed.sort((a, b) => {
1718
- const at = (a.finishedAt ?? a.updatedAt).getTime();
1719
- const bt = (b.finishedAt ?? b.updatedAt).getTime();
1720
- return bt - at;
1721
- });
1722
- return failed.slice(0, limit).map((r) => ({
1723
- runId: r.id,
1724
- jobType: r.jobType,
1725
- pool: r.pool,
1726
- scopeEntityType: r.scopeEntityType,
1727
- scopeEntityId: r.scopeEntityId,
1728
- tenantId: r.tenantId,
1729
- attempts: r.attempts,
1730
- errorMessage: r.error?.message ?? null,
1731
- failedAt: r.finishedAt ?? r.updatedAt,
1732
- createdAt: r.createdAt
1733
- }));
1734
- }
1735
- async listJobRuns(query = {}) {
1736
- const limit = clampLimit(query.limit);
1737
- const tenantCheck = this.tenantPredicate("listJobRuns", query.tenantId);
1738
- const keyset = query.cursor ? decodeKeysetCursor(query.cursor) : null;
1739
- const matched = [];
1740
- for (const r of this.store.runs.values()) {
1741
- if (tenantCheck && !tenantCheck(r)) continue;
1742
- if (query.poolId && r.pool !== query.poolId) continue;
1743
- if (query.rootRunId && r.rootRunId !== query.rootRunId) continue;
1744
- if (query.status && r.status !== query.status) continue;
1745
- if (query.since && r.createdAt.getTime() < query.since.getTime()) continue;
1746
- matched.push(r);
1747
- }
1748
- matched.sort((a, b) => {
1749
- const dt = b.createdAt.getTime() - a.createdAt.getTime();
1750
- if (dt !== 0) return dt;
1751
- return a.id < b.id ? 1 : a.id > b.id ? -1 : 0;
1752
- });
1753
- const seeked = keyset ? matched.filter((r) => {
1754
- const ct = r.createdAt.getTime();
1755
- const kt = keyset.createdAt.getTime();
1756
- if (ct < kt) return true;
1757
- if (ct > kt) return false;
1758
- return r.id < keyset.id;
1759
- }) : matched;
1760
- const hasMore = seeked.length > limit;
1761
- const page = hasMore ? seeked.slice(0, limit) : seeked;
1762
- const items = page.map(toJobRunSummary);
1763
- const last = page[page.length - 1];
1764
- const nextCursor = hasMore && last ? encodeKeysetCursor({ createdAt: last.createdAt, id: last.id }) : null;
1765
- return { items, nextCursor };
1766
- }
1767
- /**
1768
- * Direct lookup. Not on the protocol — concrete-class convenience for
1769
- * tests. Matches `DrizzleJobRunService.findByRootRunId` in spirit; both
1770
- * are debug / test helpers that sidestep the orchestrator.
1771
- */
1772
- findById(runId) {
1773
- return this.store.runs.get(runId) ?? null;
1774
- }
1775
- /** Public counterpart to the Drizzle backend's `findByRootRunId` helper. */
1776
- findByRootRunId(rootRunId) {
1777
- const out = [];
1778
- for (const r of this.store.runs.values()) {
1779
- if (r.rootRunId === rootRunId) out.push(r);
1780
- }
1781
- return out;
1782
- }
1783
- };
1784
- MemoryJobRunService = __decorateClass([
1785
- Injectable6(),
1786
- __decorateParam(0, Inject6(MemoryJobStore)),
1787
- __decorateParam(1, Inject6(JOB_ORCHESTRATOR)),
1788
- __decorateParam(2, Inject6(JOBS_MULTI_TENANT))
1789
- ], MemoryJobRunService);
1790
- function compareBy(a, b, order) {
1791
- switch (order) {
1792
- case "created_at asc":
1793
- return a.createdAt.getTime() - b.createdAt.getTime();
1794
- case "run_at desc":
1795
- return b.runAt.getTime() - a.runAt.getTime();
1796
- case "run_at asc":
1797
- return a.runAt.getTime() - b.runAt.getTime();
1798
- case "created_at desc":
1799
- default:
1800
- return b.createdAt.getTime() - a.createdAt.getTime();
1801
- }
1802
- }
1803
-
1804
- // runtime/subsystems/jobs/pool-config.loader.ts
1805
- import { existsSync, readFileSync } from "fs";
1806
- import { resolve } from "path";
1807
- import { parse as parseYaml } from "yaml";
1808
- var FRAMEWORK_POOLS = Object.freeze({
1809
- events_inbound: Object.freeze({
1810
- queue: "jobs-events-inbound",
1811
- concurrency: 20,
1812
- reserved: true,
1813
- description: "Inbound events drain (events subsystem outbox)."
1814
- }),
1815
- events_change: Object.freeze({
1816
- queue: "jobs-events-change",
1817
- concurrency: 30,
1818
- reserved: true,
1819
- description: "Change events drain (events subsystem outbox)."
1820
- }),
1821
- events_outbound: Object.freeze({
1822
- queue: "jobs-events-outbound",
1823
- concurrency: 10,
1824
- reserved: true,
1825
- description: "Outbound events drain (events subsystem outbox)."
1826
- }),
1827
- interactive: Object.freeze({
1828
- queue: "jobs-interactive",
1829
- concurrency: 20,
1830
- reserved: false,
1831
- description: "User-facing latency-sensitive jobs."
1832
- }),
1833
- batch: Object.freeze({
1834
- queue: "jobs-batch",
1835
- concurrency: 5,
1836
- reserved: false,
1837
- description: "Default pool for background jobs."
1838
- })
1839
- });
1840
- var RESERVED_POOL_NAMES = new Set(
1841
- Object.entries(FRAMEWORK_POOLS).filter(([, def]) => def.reserved).map(([name]) => name)
1842
- );
1843
- var cache = /* @__PURE__ */ new Map();
1844
- function loadPoolConfig(configPath) {
1845
- const resolved = resolve(configPath ?? `${process.cwd()}/codegen.config.yaml`);
1846
- const cached = cache.get(resolved);
1847
- if (cached) return cached;
1848
- const merged = /* @__PURE__ */ new Map();
1849
- for (const [name, def] of Object.entries(FRAMEWORK_POOLS)) {
1850
- merged.set(name, { ...def });
1851
- }
1852
- if (!existsSync(resolved)) {
1853
- cache.set(resolved, merged);
1854
- return merged;
1855
- }
1856
- let raw;
1857
- try {
1858
- raw = parseYaml(readFileSync(resolved, "utf8"));
1859
- } catch (err) {
1860
- throw new Error(
1861
- `pool-config.loader: failed to parse YAML at ${resolved}: ${err.message}`
1862
- );
1863
- }
1864
- const userPools = extractUserPools(raw);
1865
- for (const [name, userDef] of Object.entries(userPools)) {
1866
- const existing = merged.get(name);
1867
- if (existing) {
1868
- const next = {
1869
- queue: existing.queue,
1870
- concurrency: typeof userDef.concurrency === "number" ? userDef.concurrency : existing.concurrency,
1871
- reserved: existing.reserved,
1872
- description: userDef.description ?? existing.description
1873
- };
1874
- merged.set(name, next);
1875
- continue;
1876
- }
1877
- if (typeof userDef.queue !== "string" || userDef.queue.length === 0) {
1878
- throw new Error(
1879
- `pool-config.loader: pool '${name}' must declare a non-empty 'queue'.`
1880
- );
1881
- }
1882
- if (typeof userDef.concurrency !== "number" || userDef.concurrency <= 0) {
1883
- throw new Error(
1884
- `pool-config.loader: pool '${name}' must declare a positive 'concurrency'.`
1885
- );
1886
- }
1887
- if (userDef.reserved === true) {
1888
- throw new Error(
1889
- `pool-config.loader: user-defined pool '${name}' cannot set 'reserved: true' \u2014 reserved is framework-only.`
1890
- );
1891
- }
1892
- merged.set(name, {
1893
- queue: userDef.queue,
1894
- concurrency: userDef.concurrency,
1895
- reserved: false,
1896
- description: userDef.description
1897
- });
1898
- }
1899
- cache.set(resolved, merged);
1900
- return merged;
1901
- }
1902
- function allNonReservedPoolNames(config) {
1903
- const out = [];
1904
- for (const [name, def] of config) {
1905
- if (!def.reserved) out.push(name);
1906
- }
1907
- return out;
1908
- }
1909
- function allPoolNames(config) {
1910
- return [...config.keys()];
1911
- }
1912
- function extractUserPools(raw) {
1913
- if (!raw || typeof raw !== "object") return {};
1914
- const jobs2 = raw.jobs;
1915
- if (!jobs2 || typeof jobs2 !== "object") return {};
1916
- const pools = jobs2.pools;
1917
- if (!pools || typeof pools !== "object") return {};
1918
- const out = {};
1919
- for (const [name, def] of Object.entries(pools)) {
1920
- if (!def || typeof def !== "object") continue;
1921
- out[name] = def;
1922
- }
1923
- return out;
1924
- }
1925
-
1926
- // runtime/subsystems/jobs/bullmq.config.ts
1927
- var BULLMQ_CONNECTION = Symbol.for(tokenKey("jobs", "bullmq-connection"));
1928
- var BULLMQ_RESOLVED_CONFIG = Symbol.for(tokenKey("jobs", "bullmq-resolved-config"));
1929
- var DEFAULT_REDIS_URL = "redis://localhost:6379";
1930
- var DEFAULT_BULL_BOARD_MOUNT = "/admin/queues";
1931
- function resolveBullMqConfig(ext) {
1932
- const url = ext?.redis_url ?? process.env.REDIS_URL ?? DEFAULT_REDIS_URL;
1933
- const resolved = {
1934
- connection: { url },
1935
- queuePrefix: ext?.queue_prefix
1936
- };
1937
- if (ext?.bull_board?.enabled) {
1938
- resolved.bullBoard = {
1939
- enabled: true,
1940
- mountPath: ext.bull_board.mount_path ?? DEFAULT_BULL_BOARD_MOUNT
1941
- };
1942
- }
1943
- return resolved;
1944
- }
1945
- function resolvePoolQueueName(pool, config, poolConfig = loadPoolConfig()) {
1946
- const alias = poolConfig.get(pool)?.queue ?? pool;
1947
- const prefix = config?.queuePrefix;
1948
- return prefix ? `${prefix}:${alias}` : alias;
1949
- }
1950
-
1951
- // runtime/subsystems/jobs/jobs-domain.module.ts
1952
- var JobsDomainModule = class {
1953
- static forRoot(opts) {
1954
- const multiTenant = opts.multiTenant ?? false;
1955
- const providers = [
1956
- // JOB-8 — boolean provider consumed by the four service-layer backends.
1957
- // Always provided (even when `multiTenant === false`) so `@Inject`
1958
- // always resolves; backends short-circuit the enforcement path when
1959
- // the value is `false`. See `jobs-domain.tokens.ts` for the claim-loop
1960
- // cross-tenant-by-design decision.
1961
- { provide: JOBS_MULTI_TENANT, useValue: multiTenant }
1962
- ];
1963
- if (opts.backend === "memory") {
1964
- const store = new MemoryJobStore();
1965
- providers.push({ provide: MemoryJobStore, useValue: store });
1966
- providers.push(MemoryJobStepService);
1967
- providers.push({ provide: JOB_STEP_SERVICE, useExisting: MemoryJobStepService });
1968
- providers.push(MemoryJobOrchestrator);
1969
- providers.push({ provide: JOB_ORCHESTRATOR, useExisting: MemoryJobOrchestrator });
1970
- providers.push(MemoryJobRunService);
1971
- providers.push({ provide: JOB_RUN_SERVICE, useExisting: MemoryJobRunService });
1972
- } else if (opts.backend === "bullmq") {
1973
- const resolved = resolveBullMqConfig(opts.extensions?.bullmq);
1974
- providers.push({ provide: BULLMQ_CONNECTION, useValue: resolved.connection });
1975
- providers.push({ provide: BULLMQ_RESOLVED_CONFIG, useValue: resolved });
1976
- providers.push({
1977
- provide: JOB_ORCHESTRATOR,
1978
- useFactory: async (...args) => {
1979
- const specifier = "./job-orchestrator.bullmq-backend";
1980
- const mod = await import(specifier);
1981
- return new mod.BullMQJobOrchestrator(...args);
1982
- },
1983
- // The bullmq orchestrator constructor mirrors DrizzleJobOrchestrator's
1984
- // injection list: DRIZZLE + JOBS_MULTI_TENANT + the resolved BullMQ
1985
- // tokens. Importing token references would force a static dep on the
1986
- // tokens file in this module's import graph; using the existing
1987
- // symbols already in scope is sufficient.
1988
- inject: [DRIZZLE, JOBS_MULTI_TENANT, BULLMQ_CONNECTION, BULLMQ_RESOLVED_CONFIG]
1989
- });
1990
- providers.push({ provide: JOB_RUN_SERVICE, useClass: DrizzleJobRunService });
1991
- providers.push({ provide: JOB_STEP_SERVICE, useClass: DrizzleJobStepService });
1992
- } else {
1993
- providers.push({ provide: JOB_ORCHESTRATOR, useClass: DrizzleJobOrchestrator });
1994
- providers.push({ provide: JOB_RUN_SERVICE, useClass: DrizzleJobRunService });
1995
- providers.push({ provide: JOB_STEP_SERVICE, useClass: DrizzleJobStepService });
1996
- }
1997
- const exports = [
1998
- JOB_ORCHESTRATOR,
1999
- JOB_RUN_SERVICE,
2000
- JOB_STEP_SERVICE,
2001
- JOBS_MULTI_TENANT
2002
- ];
2003
- if (opts.backend === "bullmq") {
2004
- exports.push(BULLMQ_CONNECTION, BULLMQ_RESOLVED_CONFIG);
2005
- }
2006
- return {
2007
- module: JobsDomainModule,
2008
- global: true,
2009
- providers,
2010
- exports
2011
- };
2012
- }
2013
- };
2014
- JobsDomainModule = __decorateClass([
2015
- Module({})
2016
- ], JobsDomainModule);
2017
-
2018
- // runtime/subsystems/jobs/job-worker.ts
2019
- import { Inject as Inject7, Injectable as Injectable7, Logger as Logger3 } from "@nestjs/common";
2020
- import { and as and4, asc as asc2, desc as desc3, eq as eq4, inArray as inArray3, lt as lt2, lte, sql as sql4 } from "drizzle-orm";
2021
- var JOB_WORKER_OPTIONS = Symbol.for(tokenKey("jobs", "worker-options"));
2022
- var DEFAULT_POLL_INTERVAL_MS = 1e3;
2023
- var DEFAULT_STALE_SWEEPER_INTERVAL_MS = 6e4;
2024
- var DEFAULT_STALE_THRESHOLD_MS = 5 * 6e4;
2025
- var DEFAULT_SHUTDOWN_TIMEOUT_MS = 3e4;
2026
- function computeBackoff2(policy, attempts) {
2027
- const base = Math.max(policy.baseMs, 0);
2028
- if (policy.backoff === "fixed") {
2029
- return base;
2030
- }
2031
- const exponent = Math.max(attempts - 1, 0);
2032
- if (exponent >= 53) return Number.MAX_SAFE_INTEGER;
2033
- const raw = base * Math.pow(2, exponent);
2034
- if (!Number.isFinite(raw) || raw >= Number.MAX_SAFE_INTEGER) {
2035
- return Number.MAX_SAFE_INTEGER;
2036
- }
2037
- return raw;
2038
- }
2039
- function classifyError2(err, policy, currentAttempts) {
2040
- if (!policy) return "fail";
2041
- const errObj = err;
2042
- const name = errObj?.name;
2043
- const code = errObj?.code;
2044
- const nonRetryable = policy.nonRetryableErrors ?? [];
2045
- if (nonRetryable.some((n) => n === name || n === code)) return "fail";
2046
- if (currentAttempts + 1 >= policy.attempts) return "fail";
2047
- return "retry";
2048
- }
2049
- function serialiseError2(err, attempt, retryable) {
2050
- const e = err;
2051
- return {
2052
- message: e?.message ?? String(err),
2053
- stack: e?.stack,
2054
- retryable,
2055
- attempt
2056
- };
2057
- }
2058
- var JobWorker = class {
2059
- constructor(db, orchestrator, runService, stepService, options, moduleRef) {
2060
- this.db = db;
2061
- this.orchestrator = orchestrator;
2062
- this.runService = runService;
2063
- this.stepService = stepService;
2064
- this.options = options;
2065
- this.moduleRef = moduleRef;
2066
- this.pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
2067
- this.staleSweeperIntervalMs = options.staleSweeperIntervalMs ?? DEFAULT_STALE_SWEEPER_INTERVAL_MS;
2068
- this.staleThresholdMs = options.staleThresholdMs ?? DEFAULT_STALE_THRESHOLD_MS;
2069
- this.shutdownTimeoutMs = options.shutdownTimeoutMs ?? DEFAULT_SHUTDOWN_TIMEOUT_MS;
2070
- this.sigtermHandler = () => {
2071
- if (this.sigtermHandled) return;
2072
- this.sigtermHandled = true;
2073
- void this.onModuleDestroy();
2074
- };
2075
- void this.runService;
2076
- }
2077
- db;
2078
- orchestrator;
2079
- runService;
2080
- stepService;
2081
- options;
2082
- moduleRef;
2083
- logger = new Logger3(JobWorker.name);
2084
- shuttingDown = false;
2085
- inFlight = /* @__PURE__ */ new Set();
2086
- pollTimer = null;
2087
- sweeperTimer = null;
2088
- sigtermHandled = false;
2089
- sigtermHandler;
2090
- pollIntervalMs;
2091
- staleSweeperIntervalMs;
2092
- staleThresholdMs;
2093
- shutdownTimeoutMs;
2094
- // ============================================================================
2095
- // Lifecycle
2096
- // ============================================================================
2097
- onModuleInit() {
2098
- this.pollTimer = setInterval(() => {
2099
- void this.pollAndProcess();
2100
- }, this.pollIntervalMs);
2101
- this.sweeperTimer = setInterval(() => {
2102
- void this.sweepStaleClaims();
2103
- }, this.staleSweeperIntervalMs);
2104
- process.on("SIGTERM", this.sigtermHandler);
2105
- }
2106
- async onModuleDestroy() {
2107
- if (this.shuttingDown) {
2108
- await this.drainInFlight();
2109
- return;
2110
- }
2111
- this.shuttingDown = true;
2112
- if (this.pollTimer) {
2113
- clearInterval(this.pollTimer);
2114
- this.pollTimer = null;
2115
- }
2116
- if (this.sweeperTimer) {
2117
- clearInterval(this.sweeperTimer);
2118
- this.sweeperTimer = null;
2119
- }
2120
- process.removeListener("SIGTERM", this.sigtermHandler);
2121
- await this.drainInFlight();
2122
- try {
2123
- await this.db.update(jobRuns).set({ status: "pending", claimedAt: null, startedAt: null }).where(
2124
- and4(eq4(jobRuns.status, "running"), eq4(jobRuns.pool, this.options.pool))
2125
- );
2126
- } catch (err) {
2127
- this.logger.error(`shutdown reset failed: ${err.message}`);
2128
- }
2129
- }
2130
- async drainInFlight() {
2131
- if (this.inFlight.size === 0) return;
2132
- const timeout = new Promise(
2133
- (resolve2) => setTimeout(resolve2, this.shutdownTimeoutMs)
2134
- );
2135
- await Promise.race([
2136
- Promise.allSettled([...this.inFlight]).then(() => void 0),
2137
- timeout
2138
- ]);
2139
- }
2140
- // ============================================================================
2141
- // Poll loop
2142
- // ============================================================================
2143
- async pollAndProcess() {
2144
- if (this.shuttingDown) return;
2145
- if (this.inFlight.size >= this.options.concurrency) return;
2146
- let claimed;
2147
- try {
2148
- claimed = await this.claimNext(this.options.pool);
2149
- } catch (err) {
2150
- this.logger.error(`claimNext failed: ${err.message}`);
2151
- return;
2152
- }
2153
- if (!claimed) return;
2154
- const run = claimed;
2155
- const promise = this.processRun(run).catch((err) => {
2156
- this.logger.error(
2157
- `processRun(${run.id}) unhandled: ${err.message}`
2158
- );
2159
- });
2160
- this.inFlight.add(promise);
2161
- promise.finally(() => {
2162
- this.inFlight.delete(promise);
2163
- });
2164
- }
2165
- /**
2166
- * Claim the next runnable row from the pool. Transaction ensures the
2167
- * select-candidate + update-to-running pair is atomic; FOR UPDATE SKIP
2168
- * LOCKED lets multiple workers share the table without serialising.
2169
- */
2170
- async claimNext(pool) {
2171
- return this.db.transaction(async (tx) => {
2172
- const candidates = await tx.select({ id: jobRuns.id }).from(jobRuns).where(
2173
- and4(
2174
- eq4(jobRuns.status, "pending"),
2175
- eq4(jobRuns.pool, pool),
2176
- lte(jobRuns.runAt, /* @__PURE__ */ new Date())
2177
- )
2178
- ).orderBy(desc3(jobRuns.priority), asc2(jobRuns.runAt)).limit(1).for("update", { skipLocked: true });
2179
- const candidate = candidates[0];
2180
- if (!candidate) return null;
2181
- const [claimed] = await tx.update(jobRuns).set({
2182
- status: "running",
2183
- claimedAt: /* @__PURE__ */ new Date(),
2184
- startedAt: /* @__PURE__ */ new Date(),
2185
- updatedAt: /* @__PURE__ */ new Date()
2186
- }).where(eq4(jobRuns.id, candidate.id)).returning();
2187
- return claimed ?? null;
2188
- });
2189
- }
2190
- // ============================================================================
2191
- // Stale claim sweeper
2192
- // ============================================================================
2193
- /**
2194
- * Release rows whose `claimed_at` is older than the threshold. Safe to
2195
- * run concurrently across workers — the two-phase tx (select-for-update
2196
- * then update) guarantees each stranded row is only reset once.
2197
- */
2198
- async sweepStaleClaims() {
2199
- if (this.shuttingDown) return;
2200
- try {
2201
- await this.db.transaction(async (tx) => {
2202
- const threshold = new Date(Date.now() - this.staleThresholdMs);
2203
- const stale = await tx.select({ id: jobRuns.id }).from(jobRuns).where(
2204
- and4(eq4(jobRuns.status, "running"), lt2(jobRuns.claimedAt, threshold))
2205
- ).for("update", { skipLocked: true });
2206
- if (stale.length === 0) return;
2207
- const ids = stale.map((r) => r.id);
2208
- await tx.update(jobRuns).set({ status: "pending", claimedAt: null, startedAt: null }).where(inArray3(jobRuns.id, ids));
2209
- for (const id of ids) {
2210
- this.logger.warn(`Recovered stale claim on run ${id}`);
2211
- }
2212
- });
2213
- } catch (err) {
2214
- this.logger.error(`sweepStaleClaims failed: ${err.message}`);
2215
- }
2216
- }
2217
- // ============================================================================
2218
- // processRun
2219
- // ============================================================================
2220
- async processRun(claimed) {
2221
- const registryEntry = JOB_HANDLER_REGISTRY.get(claimed.jobType);
2222
- if (!registryEntry) {
2223
- this.logger.error(
2224
- `No handler registered for jobType='${claimed.jobType}' (run ${claimed.id})`
2225
- );
2226
- await this.markFailed(
2227
- claimed,
2228
- new Error(`No handler registered for jobType='${claimed.jobType}'`),
2229
- /*finalAttempts*/
2230
- (claimed.attempts ?? 0) + 1
2231
- );
2232
- return;
2233
- }
2234
- if (claimed.concurrencyKey) {
2235
- const inflight = await this.db.select({ id: jobRuns.id }).from(jobRuns).where(
2236
- and4(
2237
- eq4(jobRuns.concurrencyKey, claimed.concurrencyKey),
2238
- eq4(jobRuns.status, "running")
2239
- )
2240
- );
2241
- const other = inflight.find((r) => r.id !== claimed.id);
2242
- if (other) {
2243
- await this.db.update(jobRuns).set({
2244
- status: "pending",
2245
- claimedAt: null,
2246
- startedAt: null,
2247
- updatedAt: /* @__PURE__ */ new Date()
2248
- }).where(eq4(jobRuns.id, claimed.id));
2249
- return;
2250
- }
2251
- }
2252
- const meta = registryEntry.meta;
2253
- const HandlerClass = registryEntry.handlerClass;
2254
- const handler = this.moduleRef.get(
2255
- HandlerClass,
2256
- { strict: false }
2257
- );
2258
- const ctx = {
2259
- input: claimed.input,
2260
- run: claimed,
2261
- step: this.makeStepFn(claimed),
2262
- spawnChild: this.makeSpawnFn(claimed),
2263
- logger: new Logger3(`JobRun:${claimed.id}`)
2264
- };
2265
- const attemptsBefore = claimed.attempts ?? 0;
2266
- try {
2267
- const output = await handler.run(ctx);
2268
- await this.db.update(jobRuns).set({
2269
- status: "completed",
2270
- output: output ?? {},
2271
- finishedAt: /* @__PURE__ */ new Date(),
2272
- updatedAt: /* @__PURE__ */ new Date(),
2273
- attempts: attemptsBefore + 1
2274
- }).where(eq4(jobRuns.id, claimed.id));
2275
- } catch (err) {
2276
- const policy = meta.retry;
2277
- const decision = classifyError2(err, policy, attemptsBefore);
2278
- const nextAttempts = attemptsBefore + 1;
2279
- if (decision === "retry" && policy) {
2280
- const delay = computeBackoff2(policy, nextAttempts);
2281
- await this.db.update(jobRuns).set({
2282
- status: "pending",
2283
- attempts: nextAttempts,
2284
- runAt: new Date(Date.now() + delay),
2285
- startedAt: null,
2286
- claimedAt: null,
2287
- error: serialiseError2(err, nextAttempts, true),
2288
- updatedAt: /* @__PURE__ */ new Date()
2289
- }).where(eq4(jobRuns.id, claimed.id));
2290
- } else {
2291
- await this.markFailed(claimed, err, nextAttempts);
2292
- }
2293
- }
2294
- }
2295
- async markFailed(claimed, err, finalAttempts) {
2296
- await this.db.update(jobRuns).set({
2297
- status: "failed",
2298
- attempts: finalAttempts,
2299
- finishedAt: /* @__PURE__ */ new Date(),
2300
- error: serialiseError2(err, finalAttempts, false),
2301
- updatedAt: /* @__PURE__ */ new Date()
2302
- }).where(eq4(jobRuns.id, claimed.id));
2303
- if (claimed.parentClosePolicy === "terminate") {
2304
- try {
2305
- await this.orchestrator.cancel(claimed.id, {
2306
- cascade: true,
2307
- reason: "parent-failed",
2308
- tenantId: claimed.tenantId
2309
- });
2310
- } catch (cascadeErr) {
2311
- this.logger.warn(
2312
- `cascade on failed run ${claimed.id}: ${cascadeErr.message}`
2313
- );
2314
- }
2315
- }
2316
- }
2317
- // ============================================================================
2318
- // ctx.step / ctx.spawnChild builders
2319
- // ============================================================================
2320
- makeStepFn(run) {
2321
- return async (stepId, fn, _opts) => {
2322
- void _opts;
2323
- const existing = await this.stepService.findStep(run.id, stepId);
2324
- if (existing?.status === "completed") {
2325
- return existing.output;
2326
- }
2327
- const seq = await this.nextStepSeq(run.id);
2328
- const startedAt = /* @__PURE__ */ new Date();
2329
- const nextAttempts = (existing?.attempts ?? 0) + 1;
2330
- await this.stepService.recordStep({
2331
- jobRunId: run.id,
2332
- stepId,
2333
- kind: "task",
2334
- seq,
2335
- status: "running",
2336
- startedAt,
2337
- attempts: nextAttempts
2338
- });
2339
- try {
2340
- const output = await fn();
2341
- await this.stepService.recordStep({
2342
- jobRunId: run.id,
2343
- stepId,
2344
- kind: "task",
2345
- seq,
2346
- status: "completed",
2347
- output,
2348
- finishedAt: /* @__PURE__ */ new Date(),
2349
- attempts: nextAttempts
2350
- });
2351
- return output;
2352
- } catch (err) {
2353
- await this.stepService.recordStep({
2354
- jobRunId: run.id,
2355
- stepId,
2356
- kind: "task",
2357
- seq,
2358
- status: "failed",
2359
- error: serialiseError2(err, nextAttempts, false),
2360
- finishedAt: /* @__PURE__ */ new Date(),
2361
- attempts: nextAttempts
2362
- });
2363
- throw err;
2364
- }
2365
- };
2366
- }
2367
- makeSpawnFn(run) {
2368
- return async (type, input, opts) => {
2369
- return this.orchestrator.start(type, input, {
2370
- parentRunId: run.id,
2371
- parentClosePolicy: opts?.closePolicy,
2372
- runAt: opts?.runAt,
2373
- priority: opts?.priority,
2374
- tags: opts?.tags,
2375
- triggerSource: "parent",
2376
- triggerRef: run.id
2377
- });
2378
- };
2379
- }
2380
- /**
2381
- * Allocate the next `seq` for a given run. SELECT-max approach — runs
2382
- * typically have <100 steps so the scan is cheap, and correctness across
2383
- * retries is more important than the microseconds saved by an in-memory
2384
- * counter (which would drift if the worker crashes mid-run and another
2385
- * worker resumes via stale-claim sweep).
2386
- */
2387
- async nextStepSeq(runId) {
2388
- const [row] = await this.db.execute(
2389
- sql4`SELECT COALESCE(MAX(seq), 0) + 1 AS next FROM job_step WHERE job_run_id = ${runId}`
2390
- );
2391
- const maybeRows = row?.rows;
2392
- if (Array.isArray(maybeRows) && maybeRows.length > 0) {
2393
- return Number(maybeRows[0].next ?? 1);
2394
- }
2395
- if (row && typeof row.next !== "undefined") {
2396
- return Number(row.next);
2397
- }
2398
- return 1;
2399
- }
2400
- // ============================================================================
2401
- // (suppress unused-import noise)
2402
- // ============================================================================
2403
- };
2404
- JobWorker = __decorateClass([
2405
- Injectable7(),
2406
- __decorateParam(0, Inject7(DRIZZLE)),
2407
- __decorateParam(1, Inject7(JOB_ORCHESTRATOR)),
2408
- __decorateParam(2, Inject7(JOB_RUN_SERVICE)),
2409
- __decorateParam(3, Inject7(JOB_STEP_SERVICE)),
2410
- __decorateParam(4, Inject7(JOB_WORKER_OPTIONS))
2411
- ], JobWorker);
2412
-
2413
- // runtime/subsystems/jobs/job-worker.module.ts
2414
- var DEFAULT_SHUTDOWN_TIMEOUT_MS2 = 3e4;
2415
- var JOB_WORKER_MODULE_OPTIONS = Symbol.for(tokenKey("jobs", "worker-module-options"));
2416
- var JobWorkerOrchestrator = class {
2417
- constructor(orchestrator, runService, stepService, options, db = null, moduleRef, bullConnection = null, bullConfig = null) {
2418
- this.orchestrator = orchestrator;
2419
- this.runService = runService;
2420
- this.stepService = stepService;
2421
- this.options = options;
2422
- this.db = db;
2423
- this.moduleRef = moduleRef;
2424
- this.bullConnection = bullConnection;
2425
- this.bullConfig = bullConfig;
2426
- }
2427
- orchestrator;
2428
- runService;
2429
- stepService;
2430
- options;
2431
- db;
2432
- moduleRef;
2433
- bullConnection;
2434
- bullConfig;
2435
- logger = new Logger4(JobWorkerOrchestrator.name);
2436
- workers = [];
2437
- // ============================================================================
2438
- // Lifecycle
2439
- // ============================================================================
2440
- async onModuleInit() {
2441
- const backend = this.options.backend ?? "drizzle";
2442
- const poolConfig = loadPoolConfig(this.options.configPath);
2443
- const entries = HandlerRegistry.getAll();
2444
- this.assertNoReservedPoolHandlers(entries, poolConfig);
2445
- const { orphaned } = await this.orchestrator.upsertJobRows(
2446
- entries,
2447
- poolConfig
2448
- );
2449
- if (backend !== "memory" && orphaned.length > 0) {
2450
- throw new BootValidationError(orphaned);
2451
- }
2452
- const activePools = this.options.pools ? this.options.pools : this.options.allPools ? allPoolNames(poolConfig) : allNonReservedPoolNames(poolConfig);
2453
- for (const poolName of activePools) {
2454
- const def = poolConfig.get(poolName);
2455
- if (!def) {
2456
- throw new Error(
2457
- `JobWorkerModule: active pool '${poolName}' is not defined in the resolved pool config. Configured pools: [${[...poolConfig.keys()].join(", ")}].`
2458
- );
2459
- }
2460
- const workerOptions = {
2461
- pool: poolName,
2462
- concurrency: def.concurrency,
2463
- shutdownTimeoutMs: this.options.shutdownTimeoutMs ?? DEFAULT_SHUTDOWN_TIMEOUT_MS2
2464
- };
2465
- const worker = this.options.workerFactory ? this.options.workerFactory(workerOptions) : backend === "bullmq" ? await this.spawnBullMQWorker(poolName, def.queue, def.concurrency, poolConfig) : this.spawnWorker(workerOptions);
2466
- await worker.onModuleInit();
2467
- this.workers.push(worker);
2468
- this.logger.log(
2469
- `JobWorker started: pool='${poolName}' (queue='${def.queue}') concurrency=${def.concurrency} backend='${backend}'`
2470
- );
2471
- }
2472
- }
2473
- async onModuleDestroy() {
2474
- for (let i = this.workers.length - 1; i >= 0; i--) {
2475
- const worker = this.workers[i];
2476
- if (!worker) continue;
2477
- try {
2478
- await worker.onModuleDestroy();
2479
- } catch (err) {
2480
- this.logger.error(
2481
- `JobWorker shutdown failed: ${err.message}`
2482
- );
2483
- }
2484
- }
2485
- this.workers.length = 0;
2486
- const orch = this.orchestrator;
2487
- if (typeof orch.closeConnections === "function") {
2488
- try {
2489
- await orch.closeConnections();
2490
- } catch (err) {
2491
- this.logger.error(
2492
- `BullMQ orchestrator connection close failed: ${err.message}`
2493
- );
2494
- }
2495
- }
2496
- }
2497
- // ============================================================================
2498
- // Internals
2499
- // ============================================================================
2500
- /**
2501
- * Walk every registered handler; collect any whose declared `pool`
2502
- * targets a reserved pool from the resolved config. If non-empty,
2503
- * throw `ReservedPoolViolationError` with the offender list so the
2504
- * operator sees every violating class on a single boot.
2505
- */
2506
- assertNoReservedPoolHandlers(entries, poolConfig) {
2507
- const offenders = [];
2508
- for (const entry of entries) {
2509
- if (entry.type.startsWith("@framework/")) continue;
2510
- const declaredPool = entry.meta.pool ?? "batch";
2511
- const def = poolConfig.get(declaredPool);
2512
- if (def?.reserved) {
2513
- offenders.push({
2514
- handlerClass: entry.handlerClass.name,
2515
- pool: declaredPool
2516
- });
2517
- }
2518
- }
2519
- if (offenders.length > 0) {
2520
- throw new ReservedPoolViolationError(offenders);
2521
- }
2522
- }
2523
- /**
2524
- * Production worker spawn. `JobWorker` requires `DRIZZLE` so this only
2525
- * succeeds when the module was booted with `backend: 'drizzle'`. Memory
2526
- * mode tests must supply `workerFactory` — the memory backend has no
2527
- * polling loop equivalent (`MemoryJobOrchestrator` is direct-invocation
2528
- * only).
2529
- *
2530
- * We instantiate outside the Nest container because the module spawns
2531
- * N workers from a single options shape, which doesn't fit Nest's
2532
- * "one provider per token" model. The dependencies are passed
2533
- * positionally; the constructor's `@Inject` decorators are unused on
2534
- * this path (Nest still uses them when `JobWorker` is a provider — e.g.
2535
- * in JOB-6's standalone `worker.ts` entrypoint).
2536
- */
2537
- spawnWorker(workerOptions) {
2538
- if (!this.db) {
2539
- throw new Error(
2540
- `JobWorkerModule: in-process worker spawning requires the Drizzle backend (no DRIZZLE provider available). Memory-mode tests must pass 'workerFactory' to inject a stub.`
2541
- );
2542
- }
2543
- if (!this.moduleRef) {
2544
- throw new Error(
2545
- `JobWorkerModule: ModuleRef not available \u2014 cannot construct JobWorker with handler DI support. Ensure the orchestrator is resolved through the Nest container (not instantiated manually in tests).`
2546
- );
2547
- }
2548
- return new JobWorker(
2549
- this.db,
2550
- this.orchestrator,
2551
- this.runService,
2552
- this.stepService,
2553
- workerOptions,
2554
- this.moduleRef
2555
- );
2556
- }
2557
- /**
2558
- * BULLMQ-1 — spawn a per-pool `BullMQJobWorker`. Requires the Drizzle
2559
- * client (the worker drives `job_run` as the source of truth) AND the
2560
- * resolved BullMQ connection (bound by `JobsDomainModule` when
2561
- * `backend: 'bullmq'`). The queue name is derived identically to the
2562
- * orchestrator's `dispatch` via `resolvePoolQueueName(pool, …)` so producer
2563
- * and consumer agree.
2564
- */
2565
- /**
2566
- * #6 — async + dynamic-import. The `job-worker.bullmq-backend.ts` file is
2567
- * filtered out of the vendor set for drizzle/memory installs (no `bullmq`
2568
- * peer dep needed). The non-literal import specifier makes TS treat the
2569
- * module as `any` so the consumer's tsc never tries to resolve an absent
2570
- * file. This method is only entered when `backend === 'bullmq'` — at which
2571
- * point the file IS vendored.
2572
- */
2573
- async spawnBullMQWorker(pool, _queueAlias, concurrency, poolConfig) {
2574
- if (!this.db) {
2575
- throw new Error(
2576
- `JobWorkerModule: BullMQ worker spawning requires the Drizzle client (no DRIZZLE provider available) \u2014 job_run remains the source of truth.`
2577
- );
2578
- }
2579
- if (!this.bullConnection) {
2580
- throw new Error(
2581
- `JobWorkerModule: BullMQ worker spawning requires a resolved BULLMQ_CONNECTION. Ensure JobsDomainModule was booted with backend: 'bullmq'.`
2582
- );
2583
- }
2584
- if (!this.moduleRef) {
2585
- throw new Error(
2586
- `JobWorkerModule: ModuleRef not available \u2014 cannot construct BullMQJobWorker with handler DI support.`
2587
- );
2588
- }
2589
- const queueName = resolvePoolQueueName(pool, this.bullConfig, poolConfig);
2590
- const specifier = "./job-worker.bullmq-backend";
2591
- const mod = await import(specifier);
2592
- return new mod.BullMQJobWorker(
2593
- this.db,
2594
- this.orchestrator,
2595
- this.stepService,
2596
- {
2597
- pool,
2598
- queueName,
2599
- concurrency,
2600
- connection: this.bullConnection
2601
- },
2602
- this.moduleRef
2603
- );
2604
- }
2605
- };
2606
- JobWorkerOrchestrator = __decorateClass([
2607
- Injectable8(),
2608
- __decorateParam(0, Inject8(JOB_ORCHESTRATOR)),
2609
- __decorateParam(1, Inject8(JOB_RUN_SERVICE)),
2610
- __decorateParam(2, Inject8(JOB_STEP_SERVICE)),
2611
- __decorateParam(3, Inject8(JOB_WORKER_MODULE_OPTIONS)),
2612
- __decorateParam(4, Optional2()),
2613
- __decorateParam(4, Inject8(DRIZZLE)),
2614
- __decorateParam(5, Inject8(ModuleRef2)),
2615
- __decorateParam(6, Optional2()),
2616
- __decorateParam(6, Inject8(BULLMQ_CONNECTION)),
2617
- __decorateParam(7, Optional2()),
2618
- __decorateParam(7, Inject8(BULLMQ_RESOLVED_CONFIG))
2619
- ], JobWorkerOrchestrator);
2620
- var JobWorkerModule = class {
2621
- static forRoot(opts) {
2622
- return {
2623
- module: JobWorkerModule,
2624
- imports: [
2625
- JobsDomainModule.forRoot({
2626
- backend: opts.backend ?? "drizzle",
2627
- extensions: opts.domainModuleExtensions,
2628
- multiTenant: opts.multiTenant
2629
- })
2630
- ],
2631
- providers: [
2632
- { provide: JOB_WORKER_MODULE_OPTIONS, useValue: opts },
2633
- JobWorkerOrchestrator
2634
- ],
2635
- // BULLMQ-1 Phase 1 — export the options token so `BridgeModule`'s
2636
- // reserved-pool guard (`onModuleInit`) can actually inject it.
2637
- // Previously `exports: []` left the `@Optional()` inject resolving to
2638
- // `undefined` and the guard silently no-opped (a dead check). With the
2639
- // token exported the guard fires for real; consumers that omit the
2640
- // reserved pools (and don't set `allPools`) now fail fast with
2641
- // `BridgeReservedPoolsNotPolledError` — which is correct.
2642
- exports: [JOB_WORKER_MODULE_OPTIONS]
2643
- };
2644
- }
2645
- };
2646
- JobWorkerModule = __decorateClass([
2647
- Module2({})
2648
- ], JobWorkerModule);
2
+ JOB_WORKER_MODULE_OPTIONS,
3
+ JobWorkerModule,
4
+ JobWorkerOrchestrator
5
+ } from "../../../chunk-WPXNN6QS.js";
6
+ import "../../../chunk-RC23QROE.js";
7
+ import "../../../chunk-KMZCQASO.js";
8
+ import "../../../chunk-I6MG4M3F.js";
9
+ import "../../../chunk-JRVNVKN6.js";
10
+ import "../../../chunk-DV4RV2DC.js";
11
+ import "../../../chunk-5Y7W3XR6.js";
12
+ import "../../../chunk-4RFHUZXU.js";
13
+ import "../../../chunk-PNZSGAB2.js";
14
+ import "../../../chunk-SNQ3TOWP.js";
15
+ import "../../../chunk-T4BIIU5E.js";
16
+ import "../../../chunk-L3LZWWSX.js";
17
+ import "../../../chunk-I6MVCB5A.js";
18
+ import "../../../chunk-RHVN6NA7.js";
19
+ import "../../../chunk-CO6LUM72.js";
20
+ import "../../../chunk-BIO6F7YI.js";
21
+ import "../../../chunk-OKXZ63IA.js";
22
+ import "../../../chunk-GYGNEQSC.js";
23
+ import "../../../chunk-U64T4YZE.js";
24
+ import "../../../chunk-2E224ZSN.js";
2649
25
  export {
2650
26
  JOB_WORKER_MODULE_OPTIONS,
2651
27
  JobWorkerModule,