@pattern-stack/codegen 0.15.1 → 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 (521) hide show
  1. package/CHANGELOG.md +53 -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/runtime/analytics/index.js +8 -41
  249. package/dist/runtime/analytics/index.js.map +1 -1
  250. package/dist/runtime/analytics/types.js +8 -41
  251. package/dist/runtime/analytics/types.js.map +1 -1
  252. package/dist/runtime/base-classes/activity-entity-repository.js +6 -312
  253. package/dist/runtime/base-classes/activity-entity-repository.js.map +1 -1
  254. package/dist/runtime/base-classes/activity-entity-service.js +6 -212
  255. package/dist/runtime/base-classes/activity-entity-service.js.map +1 -1
  256. package/dist/runtime/base-classes/base-read-use-cases.js +5 -27
  257. package/dist/runtime/base-classes/base-read-use-cases.js.map +1 -1
  258. package/dist/runtime/base-classes/base-repository.js +5 -277
  259. package/dist/runtime/base-classes/base-repository.js.map +1 -1
  260. package/dist/runtime/base-classes/base-service.js +5 -184
  261. package/dist/runtime/base-classes/base-service.js.map +1 -1
  262. package/dist/runtime/base-classes/index.js +59 -1076
  263. package/dist/runtime/base-classes/index.js.map +1 -1
  264. package/dist/runtime/base-classes/integrated-entity-repository.js +6 -486
  265. package/dist/runtime/base-classes/integrated-entity-repository.js.map +1 -1
  266. package/dist/runtime/base-classes/integrated-entity-service.js +6 -213
  267. package/dist/runtime/base-classes/integrated-entity-service.js.map +1 -1
  268. package/dist/runtime/base-classes/junction-integration-repository.js +8 -448
  269. package/dist/runtime/base-classes/junction-integration-repository.js.map +1 -1
  270. package/dist/runtime/base-classes/knowledge-entity-repository.js +6 -283
  271. package/dist/runtime/base-classes/knowledge-entity-repository.js.map +1 -1
  272. package/dist/runtime/base-classes/knowledge-entity-service.js +6 -190
  273. package/dist/runtime/base-classes/knowledge-entity-service.js.map +1 -1
  274. package/dist/runtime/base-classes/lifecycle-events.js +8 -70
  275. package/dist/runtime/base-classes/lifecycle-events.js.map +1 -1
  276. package/dist/runtime/base-classes/metadata-entity-repository.js +6 -330
  277. package/dist/runtime/base-classes/metadata-entity-repository.js.map +1 -1
  278. package/dist/runtime/base-classes/metadata-entity-service.js +6 -212
  279. package/dist/runtime/base-classes/metadata-entity-service.js.map +1 -1
  280. package/dist/runtime/base-classes/tenant-context.js +10 -36
  281. package/dist/runtime/base-classes/tenant-context.js.map +1 -1
  282. package/dist/runtime/base-classes/with-analytics.js +4 -7
  283. package/dist/runtime/base-classes/with-analytics.js.map +1 -1
  284. package/dist/runtime/constants/tokens.js +5 -3
  285. package/dist/runtime/constants/tokens.js.map +1 -1
  286. package/dist/runtime/eav-helpers.js +2 -0
  287. package/dist/runtime/eav-helpers.js.map +1 -1
  288. package/dist/runtime/pipes/zod-validation.pipe.js +3 -10
  289. package/dist/runtime/pipes/zod-validation.pipe.js.map +1 -1
  290. package/dist/runtime/shared/openapi/error-response.dto.js +5 -8
  291. package/dist/runtime/shared/openapi/error-response.dto.js.map +1 -1
  292. package/dist/runtime/shared/openapi/errors.js +5 -19
  293. package/dist/runtime/shared/openapi/errors.js.map +1 -1
  294. package/dist/runtime/shared/openapi/index.js +15 -106
  295. package/dist/runtime/shared/openapi/index.js.map +1 -1
  296. package/dist/runtime/shared/openapi/registry.js +6 -103
  297. package/dist/runtime/shared/openapi/registry.js.map +1 -1
  298. package/dist/runtime/shared/openapi/registry.tokens.js +4 -2
  299. package/dist/runtime/shared/openapi/registry.tokens.js.map +1 -1
  300. package/dist/runtime/subsystems/analytics/analytics.module.js +8 -117
  301. package/dist/runtime/subsystems/analytics/analytics.module.js.map +1 -1
  302. package/dist/runtime/subsystems/analytics/analytics.tokens.js +7 -8
  303. package/dist/runtime/subsystems/analytics/analytics.tokens.js.map +1 -1
  304. package/dist/runtime/subsystems/analytics/cube-backend.js +6 -71
  305. package/dist/runtime/subsystems/analytics/cube-backend.js.map +1 -1
  306. package/dist/runtime/subsystems/analytics/index.js +16 -117
  307. package/dist/runtime/subsystems/analytics/index.js.map +1 -1
  308. package/dist/runtime/subsystems/analytics/noop-backend.js +4 -21
  309. package/dist/runtime/subsystems/analytics/noop-backend.js.map +1 -1
  310. package/dist/runtime/subsystems/auth/auth-oauth-state.schema.js +4 -8
  311. package/dist/runtime/subsystems/auth/auth-oauth-state.schema.js.map +1 -1
  312. package/dist/runtime/subsystems/auth/auth.module.js +12 -359
  313. package/dist/runtime/subsystems/auth/auth.module.js.map +1 -1
  314. package/dist/runtime/subsystems/auth/auth.tokens.js +12 -13
  315. package/dist/runtime/subsystems/auth/auth.tokens.js.map +1 -1
  316. package/dist/runtime/subsystems/auth/backends/encryption-key/env.js +4 -49
  317. package/dist/runtime/subsystems/auth/backends/encryption-key/env.js.map +1 -1
  318. package/dist/runtime/subsystems/auth/backends/state-store.drizzle-backend.js +6 -64
  319. package/dist/runtime/subsystems/auth/backends/state-store.drizzle-backend.js.map +1 -1
  320. package/dist/runtime/subsystems/auth/backends/state-store.memory-backend.js +5 -47
  321. package/dist/runtime/subsystems/auth/backends/state-store.memory-backend.js.map +1 -1
  322. package/dist/runtime/subsystems/auth/controllers/auth.controller.js +5 -139
  323. package/dist/runtime/subsystems/auth/controllers/auth.controller.js.map +1 -1
  324. package/dist/runtime/subsystems/auth/index.js +53 -542
  325. package/dist/runtime/subsystems/auth/index.js.map +1 -1
  326. package/dist/runtime/subsystems/auth/middleware/requester-context.js +9 -65
  327. package/dist/runtime/subsystems/auth/middleware/requester-context.js.map +1 -1
  328. package/dist/runtime/subsystems/auth/protocols/oauth-state-store.js +4 -9
  329. package/dist/runtime/subsystems/auth/protocols/oauth-state-store.js.map +1 -1
  330. package/dist/runtime/subsystems/auth/runtime/connection-broken.error.js +4 -15
  331. package/dist/runtime/subsystems/auth/runtime/connection-broken.error.js.map +1 -1
  332. package/dist/runtime/subsystems/auth/runtime/oauth2-refresh.strategy.js +5 -104
  333. package/dist/runtime/subsystems/auth/runtime/oauth2-refresh.strategy.js.map +1 -1
  334. package/dist/runtime/subsystems/auth/runtime/session-expired.error.js +5 -16
  335. package/dist/runtime/subsystems/auth/runtime/session-expired.error.js.map +1 -1
  336. package/dist/runtime/subsystems/auth/runtime/with-auth-retry.js +5 -29
  337. package/dist/runtime/subsystems/auth/runtime/with-auth-retry.js.map +1 -1
  338. package/dist/runtime/subsystems/bridge/assert-tenant-id.js +5 -18
  339. package/dist/runtime/subsystems/bridge/assert-tenant-id.js.map +1 -1
  340. package/dist/runtime/subsystems/bridge/bridge-delivery-handler.js +12 -184
  341. package/dist/runtime/subsystems/bridge/bridge-delivery-handler.js.map +1 -1
  342. package/dist/runtime/subsystems/bridge/bridge-delivery.drizzle-backend.js +10 -448
  343. package/dist/runtime/subsystems/bridge/bridge-delivery.drizzle-backend.js.map +1 -1
  344. package/dist/runtime/subsystems/bridge/bridge-delivery.memory-backend.js +5 -126
  345. package/dist/runtime/subsystems/bridge/bridge-delivery.memory-backend.js.map +1 -1
  346. package/dist/runtime/subsystems/bridge/bridge-delivery.schema.js +6 -308
  347. package/dist/runtime/subsystems/bridge/bridge-delivery.schema.js.map +1 -1
  348. package/dist/runtime/subsystems/bridge/bridge-errors.js +6 -35
  349. package/dist/runtime/subsystems/bridge/bridge-errors.js.map +1 -1
  350. package/dist/runtime/subsystems/bridge/bridge-outbox-drain-hook.js +14 -606
  351. package/dist/runtime/subsystems/bridge/bridge-outbox-drain-hook.js.map +1 -1
  352. package/dist/runtime/subsystems/bridge/bridge.module.js +35 -3476
  353. package/dist/runtime/subsystems/bridge/bridge.module.js.map +1 -1
  354. package/dist/runtime/subsystems/bridge/bridge.tokens.js +9 -7
  355. package/dist/runtime/subsystems/bridge/bridge.tokens.js.map +1 -1
  356. package/dist/runtime/subsystems/bridge/event-flow.service.js +11 -137
  357. package/dist/runtime/subsystems/bridge/event-flow.service.js.map +1 -1
  358. package/dist/runtime/subsystems/bridge/generated/registry.js +4 -2
  359. package/dist/runtime/subsystems/bridge/generated/registry.js.map +1 -1
  360. package/dist/runtime/subsystems/bridge/index.js +60 -3470
  361. package/dist/runtime/subsystems/bridge/index.js.map +1 -1
  362. package/dist/runtime/subsystems/bridge/reserved-pools.js +4 -6
  363. package/dist/runtime/subsystems/bridge/reserved-pools.js.map +1 -1
  364. package/dist/runtime/subsystems/cache/cache.drizzle-backend.js +10 -133
  365. package/dist/runtime/subsystems/cache/cache.drizzle-backend.js.map +1 -1
  366. package/dist/runtime/subsystems/cache/cache.memory-backend.js +6 -101
  367. package/dist/runtime/subsystems/cache/cache.memory-backend.js.map +1 -1
  368. package/dist/runtime/subsystems/cache/cache.module.js +10 -278
  369. package/dist/runtime/subsystems/cache/cache.module.js.map +1 -1
  370. package/dist/runtime/subsystems/cache/cache.schema.js +4 -14
  371. package/dist/runtime/subsystems/cache/cache.schema.js.map +1 -1
  372. package/dist/runtime/subsystems/cache/cache.tokens.js +6 -7
  373. package/dist/runtime/subsystems/cache/cache.tokens.js.map +1 -1
  374. package/dist/runtime/subsystems/cache/index.js +20 -278
  375. package/dist/runtime/subsystems/cache/index.js.map +1 -1
  376. package/dist/runtime/subsystems/events/domain-events.schema.js +3 -72
  377. package/dist/runtime/subsystems/events/domain-events.schema.js.map +1 -1
  378. package/dist/runtime/subsystems/events/event-bus.drizzle-backend.js +9 -413
  379. package/dist/runtime/subsystems/events/event-bus.drizzle-backend.js.map +1 -1
  380. package/dist/runtime/subsystems/events/event-bus.memory-backend.js +7 -235
  381. package/dist/runtime/subsystems/events/event-bus.memory-backend.js.map +1 -1
  382. package/dist/runtime/subsystems/events/event-bus.redis-backend.js +8 -20
  383. package/dist/runtime/subsystems/events/event-bus.redis-backend.js.map +1 -1
  384. package/dist/runtime/subsystems/events/event-keyset-cursor.js +8 -30
  385. package/dist/runtime/subsystems/events/event-keyset-cursor.js.map +1 -1
  386. package/dist/runtime/subsystems/events/event-read.protocol.js +2 -0
  387. package/dist/runtime/subsystems/events/event-read.protocol.js.map +1 -1
  388. package/dist/runtime/subsystems/events/events-errors.js +4 -11
  389. package/dist/runtime/subsystems/events/events-errors.js.map +1 -1
  390. package/dist/runtime/subsystems/events/events.module.js +15 -949
  391. package/dist/runtime/subsystems/events/events.module.js.map +1 -1
  392. package/dist/runtime/subsystems/events/events.tokens.js +10 -11
  393. package/dist/runtime/subsystems/events/events.tokens.js.map +1 -1
  394. package/dist/runtime/subsystems/events/generated/bus.js +9 -240
  395. package/dist/runtime/subsystems/events/generated/bus.js.map +1 -1
  396. package/dist/runtime/subsystems/events/generated/index.js +23 -240
  397. package/dist/runtime/subsystems/events/generated/index.js.map +1 -1
  398. package/dist/runtime/subsystems/events/generated/registry.js +5 -82
  399. package/dist/runtime/subsystems/events/generated/registry.js.map +1 -1
  400. package/dist/runtime/subsystems/events/generated/schemas.js +12 -52
  401. package/dist/runtime/subsystems/events/generated/schemas.js.map +1 -1
  402. package/dist/runtime/subsystems/events/generated/types.js +1 -0
  403. package/dist/runtime/subsystems/events/index.js +32 -949
  404. package/dist/runtime/subsystems/events/index.js.map +1 -1
  405. package/dist/runtime/subsystems/index.js +171 -5912
  406. package/dist/runtime/subsystems/index.js.map +1 -1
  407. package/dist/runtime/subsystems/integration/build-change-source.js +6 -178
  408. package/dist/runtime/subsystems/integration/build-change-source.js.map +1 -1
  409. package/dist/runtime/subsystems/integration/deep-equal.differ.js +4 -109
  410. package/dist/runtime/subsystems/integration/deep-equal.differ.js.map +1 -1
  411. package/dist/runtime/subsystems/integration/detection-config.schema.js +11 -78
  412. package/dist/runtime/subsystems/integration/detection-config.schema.js.map +1 -1
  413. package/dist/runtime/subsystems/integration/entity-change-source-registry.memory.js +5 -30
  414. package/dist/runtime/subsystems/integration/entity-change-source-registry.memory.js.map +1 -1
  415. package/dist/runtime/subsystems/integration/entity-change-source-registry.protocol.js +4 -9
  416. package/dist/runtime/subsystems/integration/entity-change-source-registry.protocol.js.map +1 -1
  417. package/dist/runtime/subsystems/integration/execute-integration.use-case.js +6 -239
  418. package/dist/runtime/subsystems/integration/execute-integration.use-case.js.map +1 -1
  419. package/dist/runtime/subsystems/integration/incremental-read.js +5 -144
  420. package/dist/runtime/subsystems/integration/incremental-read.js.map +1 -1
  421. package/dist/runtime/subsystems/integration/index.js +83 -1352
  422. package/dist/runtime/subsystems/integration/index.js.map +1 -1
  423. package/dist/runtime/subsystems/integration/integration-audit.schema.js +10 -155
  424. package/dist/runtime/subsystems/integration/integration-audit.schema.js.map +1 -1
  425. package/dist/runtime/subsystems/integration/integration-cursor-store.drizzle-backend.js +7 -270
  426. package/dist/runtime/subsystems/integration/integration-cursor-store.drizzle-backend.js.map +1 -1
  427. package/dist/runtime/subsystems/integration/integration-cursor-store.memory-backend.js +4 -65
  428. package/dist/runtime/subsystems/integration/integration-cursor-store.memory-backend.js.map +1 -1
  429. package/dist/runtime/subsystems/integration/integration-errors.js +5 -15
  430. package/dist/runtime/subsystems/integration/integration-errors.js.map +1 -1
  431. package/dist/runtime/subsystems/integration/integration-field-diff.protocol.js +5 -7
  432. package/dist/runtime/subsystems/integration/integration-field-diff.protocol.js.map +1 -1
  433. package/dist/runtime/subsystems/integration/integration-run-recorder.drizzle-backend.js +8 -303
  434. package/dist/runtime/subsystems/integration/integration-run-recorder.drizzle-backend.js.map +1 -1
  435. package/dist/runtime/subsystems/integration/integration-run-recorder.memory-backend.js +5 -125
  436. package/dist/runtime/subsystems/integration/integration-run-recorder.memory-backend.js.map +1 -1
  437. package/dist/runtime/subsystems/integration/integration.module.js +13 -700
  438. package/dist/runtime/subsystems/integration/integration.module.js.map +1 -1
  439. package/dist/runtime/subsystems/integration/integration.tokens.js +11 -9
  440. package/dist/runtime/subsystems/integration/integration.tokens.js.map +1 -1
  441. package/dist/runtime/subsystems/integration/loopback.middleware.js +4 -16
  442. package/dist/runtime/subsystems/integration/loopback.middleware.js.map +1 -1
  443. package/dist/runtime/subsystems/integration/poll-change-source.js +4 -89
  444. package/dist/runtime/subsystems/integration/poll-change-source.js.map +1 -1
  445. package/dist/runtime/subsystems/integration/webhook-change-source.js +4 -70
  446. package/dist/runtime/subsystems/integration/webhook-change-source.js.map +1 -1
  447. package/dist/runtime/subsystems/jobs/bullmq.config.js +9 -140
  448. package/dist/runtime/subsystems/jobs/bullmq.config.js.map +1 -1
  449. package/dist/runtime/subsystems/jobs/index.js +88 -2691
  450. package/dist/runtime/subsystems/jobs/index.js.map +1 -1
  451. package/dist/runtime/subsystems/jobs/job-handler.base.js +10 -49
  452. package/dist/runtime/subsystems/jobs/job-handler.base.js.map +1 -1
  453. package/dist/runtime/subsystems/jobs/job-orchestration.schema.js +13 -152
  454. package/dist/runtime/subsystems/jobs/job-orchestration.schema.js.map +1 -1
  455. package/dist/runtime/subsystems/jobs/job-orchestrator.bullmq-backend.js +36 -699
  456. package/dist/runtime/subsystems/jobs/job-orchestrator.bullmq-backend.js.map +1 -1
  457. package/dist/runtime/subsystems/jobs/job-orchestrator.drizzle-backend.js +10 -564
  458. package/dist/runtime/subsystems/jobs/job-orchestrator.drizzle-backend.js.map +1 -1
  459. package/dist/runtime/subsystems/jobs/job-orchestrator.memory-backend.js +10 -824
  460. package/dist/runtime/subsystems/jobs/job-orchestrator.memory-backend.js.map +1 -1
  461. package/dist/runtime/subsystems/jobs/job-run-keyset-cursor.js +9 -51
  462. package/dist/runtime/subsystems/jobs/job-run-keyset-cursor.js.map +1 -1
  463. package/dist/runtime/subsystems/jobs/job-run-service.drizzle-backend.js +9 -416
  464. package/dist/runtime/subsystems/jobs/job-run-service.drizzle-backend.js.map +1 -1
  465. package/dist/runtime/subsystems/jobs/job-run-service.memory-backend.js +9 -290
  466. package/dist/runtime/subsystems/jobs/job-run-service.memory-backend.js.map +1 -1
  467. package/dist/runtime/subsystems/jobs/job-step-service.drizzle-backend.js +5 -213
  468. package/dist/runtime/subsystems/jobs/job-step-service.drizzle-backend.js.map +1 -1
  469. package/dist/runtime/subsystems/jobs/job-step-service.memory-backend.js +5 -131
  470. package/dist/runtime/subsystems/jobs/job-step-service.memory-backend.js.map +1 -1
  471. package/dist/runtime/subsystems/jobs/job-worker.bullmq-backend.js +9 -175
  472. package/dist/runtime/subsystems/jobs/job-worker.bullmq-backend.js.map +1 -1
  473. package/dist/runtime/subsystems/jobs/job-worker.js +14 -613
  474. package/dist/runtime/subsystems/jobs/job-worker.js.map +1 -1
  475. package/dist/runtime/subsystems/jobs/job-worker.module.js +23 -2647
  476. package/dist/runtime/subsystems/jobs/job-worker.module.js.map +1 -1
  477. package/dist/runtime/subsystems/jobs/jobs-domain.module.js +19 -1897
  478. package/dist/runtime/subsystems/jobs/jobs-domain.module.js.map +1 -1
  479. package/dist/runtime/subsystems/jobs/jobs-domain.tokens.js +8 -9
  480. package/dist/runtime/subsystems/jobs/jobs-domain.tokens.js.map +1 -1
  481. package/dist/runtime/subsystems/jobs/jobs-errors.js +10 -78
  482. package/dist/runtime/subsystems/jobs/jobs-errors.js.map +1 -1
  483. package/dist/runtime/subsystems/jobs/memory-job-store.js +4 -15
  484. package/dist/runtime/subsystems/jobs/memory-job-store.js.map +1 -1
  485. package/dist/runtime/subsystems/jobs/pool-config.loader.js +9 -124
  486. package/dist/runtime/subsystems/jobs/pool-config.loader.js.map +1 -1
  487. package/dist/runtime/subsystems/observability/index.js +21 -310
  488. package/dist/runtime/subsystems/observability/index.js.map +1 -1
  489. package/dist/runtime/subsystems/observability/observability-errors.js +4 -9
  490. package/dist/runtime/subsystems/observability/observability-errors.js.map +1 -1
  491. package/dist/runtime/subsystems/observability/observability.module.js +11 -300
  492. package/dist/runtime/subsystems/observability/observability.module.js.map +1 -1
  493. package/dist/runtime/subsystems/observability/observability.service.js +9 -197
  494. package/dist/runtime/subsystems/observability/observability.service.js.map +1 -1
  495. package/dist/runtime/subsystems/observability/observability.tokens.js +5 -3
  496. package/dist/runtime/subsystems/observability/observability.tokens.js.map +1 -1
  497. package/dist/runtime/subsystems/observability/reporters/bridge-metrics.reporter.js +4 -84
  498. package/dist/runtime/subsystems/observability/reporters/bridge-metrics.reporter.js.map +1 -1
  499. package/dist/runtime/subsystems/observability/reporters/index.js +5 -84
  500. package/dist/runtime/subsystems/observability/reporters/index.js.map +1 -1
  501. package/dist/runtime/subsystems/storage/index.js +15 -200
  502. package/dist/runtime/subsystems/storage/index.js.map +1 -1
  503. package/dist/runtime/subsystems/storage/storage.local-backend.js +4 -103
  504. package/dist/runtime/subsystems/storage/storage.local-backend.js.map +1 -1
  505. package/dist/runtime/subsystems/storage/storage.memory-backend.js +5 -68
  506. package/dist/runtime/subsystems/storage/storage.memory-backend.js.map +1 -1
  507. package/dist/runtime/subsystems/storage/storage.module.js +8 -200
  508. package/dist/runtime/subsystems/storage/storage.module.js.map +1 -1
  509. package/dist/runtime/subsystems/storage/storage.tokens.js +5 -6
  510. package/dist/runtime/subsystems/storage/storage.tokens.js.map +1 -1
  511. package/dist/runtime/subsystems/storage/storage.utils.js +4 -14
  512. package/dist/runtime/subsystems/storage/storage.utils.js.map +1 -1
  513. package/dist/runtime/subsystems/token-key.js +5 -3
  514. package/dist/runtime/subsystems/token-key.js.map +1 -1
  515. package/dist/src/cli/index.js +637 -5454
  516. package/dist/src/cli/index.js.map +1 -1
  517. package/dist/src/index.js +68 -4170
  518. package/dist/src/index.js.map +1 -1
  519. package/package.json +1 -1
  520. package/runtime/subsystems/bridge/bridge-outbox-drain-hook.ts +44 -21
  521. package/runtime/subsystems/jobs/job-worker.ts +17 -11
@@ -1,3480 +1,39 @@
1
- var __defProp = Object.defineProperty;
2
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
- var __decorateClass = (decorators, target, key2, kind) => {
4
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key2) : target;
5
- for (var i = decorators.length - 1, decorator; i >= 0; i--)
6
- if (decorator = decorators[i])
7
- result = (kind ? decorator(target, key2, result) : decorator(result)) || result;
8
- if (kind && result) __defProp(target, key2, result);
9
- return result;
10
- };
11
- var __decorateParam = (index4, decorator) => (target, key2) => decorator(target, key2, index4);
12
-
13
- // runtime/subsystems/bridge/bridge.module.ts
14
- import {
15
- Inject as Inject13,
16
- Module as Module3,
17
- Optional as Optional7
18
- } from "@nestjs/common";
19
-
20
- // runtime/subsystems/jobs/job-worker.module.ts
21
- import {
22
- Inject as Inject8,
23
- Injectable as Injectable8,
24
- Logger as Logger4,
25
- Module as Module2,
26
- Optional as Optional2
27
- } from "@nestjs/common";
28
- import { ModuleRef as ModuleRef2 } from "@nestjs/core";
29
-
30
- // runtime/subsystems/token-key.ts
31
- var PKG = "@pattern-stack/codegen";
32
- var tokenKey = (area, name) => `${PKG}.${area}.${name}`;
33
-
34
- // runtime/constants/tokens.ts
35
- var DRIZZLE = "DRIZZLE";
36
-
37
- // runtime/subsystems/jobs/job-handler.base.ts
38
- var JobHandlerBase = class {
39
- };
40
- var JOB_HANDLER_REGISTRY = /* @__PURE__ */ new Map();
41
- var JOB_HANDLER_METADATA_KEY = Symbol.for(tokenKey("jobs", "handler-metadata"));
42
- function JobHandler(type, meta) {
43
- return (target) => {
44
- if (JOB_HANDLER_REGISTRY.has(type)) {
45
- const env = process.env.NODE_ENV;
46
- if (env === "production") {
47
- throw new Error(
48
- `[JobHandler] Duplicate registration for job type '${type}'. Each @JobHandler must declare a unique type.`
49
- );
50
- }
51
- if (env !== "test") {
52
- console.warn(
53
- `[JobHandler] Duplicate registration for job type '${type}'. Overwriting previous handler \u2014 this is almost certainly a bug.`
54
- );
55
- }
56
- }
57
- Reflect.defineMetadata(JOB_HANDLER_METADATA_KEY, { type, meta }, target);
58
- JOB_HANDLER_REGISTRY.set(type, {
59
- type,
60
- meta,
61
- handlerClass: target
62
- });
63
- };
64
- }
65
- var HandlerRegistry;
66
- ((HandlerRegistry2) => {
67
- function getAll() {
68
- return Array.from(JOB_HANDLER_REGISTRY.values());
69
- }
70
- HandlerRegistry2.getAll = getAll;
71
- function get(type) {
72
- return JOB_HANDLER_REGISTRY.get(type);
73
- }
74
- HandlerRegistry2.get = get;
75
- })(HandlerRegistry || (HandlerRegistry = {}));
76
-
77
- // runtime/subsystems/jobs/jobs-domain.module.ts
78
- import { Module } from "@nestjs/common";
79
-
80
- // runtime/subsystems/jobs/jobs-domain.tokens.ts
81
- var JOB_ORCHESTRATOR = Symbol.for(tokenKey("jobs", "orchestrator"));
82
- var JOB_RUN_SERVICE = Symbol.for(tokenKey("jobs", "run-service"));
83
- var JOB_STEP_SERVICE = Symbol.for(tokenKey("jobs", "step-service"));
84
- var JOBS_MULTI_TENANT = Symbol.for(tokenKey("jobs", "multi-tenant"));
85
-
86
- // runtime/subsystems/jobs/job-orchestrator.drizzle-backend.ts
87
- import { randomUUID } from "crypto";
88
- import { Inject, Injectable, Logger } from "@nestjs/common";
89
- import { and, desc, eq, gt, inArray, isNotNull, ne, notInArray, sql as sql2 } from "drizzle-orm";
90
-
91
- // runtime/subsystems/jobs/job-orchestration.schema.ts
92
- import {
93
- pgEnum,
94
- pgTable,
95
- uuid,
96
- text,
97
- jsonb,
98
- integer,
99
- timestamp,
100
- index,
101
- uniqueIndex
102
- } from "drizzle-orm/pg-core";
103
- import { sql } from "drizzle-orm";
104
- var jobRunStatusEnum = pgEnum("job_run_status", [
105
- "pending",
106
- "running",
107
- "waiting",
108
- "completed",
109
- "failed",
110
- "timed_out",
111
- "canceled"
112
- ]);
113
- var jobStepKindEnum = pgEnum("job_step_kind", ["task"]);
114
- var jobStepStatusEnum = pgEnum("job_step_status", [
115
- "pending",
116
- "running",
117
- "completed",
118
- "failed",
119
- "skipped"
120
- ]);
121
- var collisionModeEnum = pgEnum("job_collision_mode", [
122
- "queue",
123
- "reject",
124
- "replace"
125
- ]);
126
- var replayFromEnum = pgEnum("job_replay_from", [
127
- "scratch",
128
- "last_step",
129
- "last_checkpoint"
130
- ]);
131
- var parentClosePolicyEnum = pgEnum("job_parent_close_policy", [
132
- "terminate",
133
- "cancel",
134
- "abandon"
135
- ]);
136
- var waitKindEnum = pgEnum("job_wait_kind", ["signal"]);
137
- var triggerSourceEnum = pgEnum("job_trigger_source", [
138
- "manual",
139
- "schedule",
140
- "event",
141
- "parent"
142
- ]);
143
- var jobs = pgTable("job", {
144
- type: text("type").primaryKey(),
145
- version: integer("version").notNull().default(1),
146
- pool: text("pool").notNull(),
147
- scopeEntityType: text("scope_entity_type"),
148
- retryPolicy: jsonb("retry_policy").notNull().$type(),
149
- timeoutMs: integer("timeout_ms"),
150
- concurrencyKeyTemplate: text("concurrency_key_template"),
151
- collisionMode: collisionModeEnum("collision_mode").notNull().default("queue"),
152
- dedupeKeyTemplate: text("dedupe_key_template"),
153
- dedupeWindowMs: integer("dedupe_window_ms"),
154
- priorityDefault: integer("priority_default").notNull().default(0),
155
- replayFrom: replayFromEnum("replay_from").notNull().default("last_checkpoint"),
156
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
157
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
158
- });
159
- var jobRuns = pgTable(
160
- "job_run",
161
- {
162
- id: uuid("id").primaryKey().defaultRandom(),
163
- jobType: text("job_type").notNull().references(() => jobs.type),
164
- jobVersion: integer("job_version").notNull(),
165
- parentRunId: uuid("parent_run_id").references(() => jobRuns.id),
166
- /**
167
- * Service generates `id` client-side via randomUUID() and sets
168
- * root_run_id = id for root runs (single INSERT, no self-FK race).
169
- */
170
- rootRunId: uuid("root_run_id").notNull(),
171
- parentClosePolicy: parentClosePolicyEnum("parent_close_policy").notNull().default("terminate"),
172
- scopeEntityType: text("scope_entity_type"),
173
- scopeEntityId: text("scope_entity_id"),
174
- tenantId: text("tenant_id"),
175
- tags: jsonb("tags").notNull().default({}).$type(),
176
- pool: text("pool").notNull(),
177
- priority: integer("priority").notNull().default(0),
178
- concurrencyKey: text("concurrency_key"),
179
- dedupeKey: text("dedupe_key"),
180
- status: jobRunStatusEnum("status").notNull().default("pending"),
181
- input: jsonb("input").notNull().$type(),
182
- output: jsonb("output").$type(),
183
- error: jsonb("error").$type(),
184
- triggerSource: triggerSourceEnum("trigger_source").notNull(),
185
- triggerRef: text("trigger_ref"),
186
- runAt: timestamp("run_at", { withTimezone: true }).notNull().defaultNow(),
187
- startedAt: timestamp("started_at", { withTimezone: true }),
188
- finishedAt: timestamp("finished_at", { withTimezone: true }),
189
- claimedAt: timestamp("claimed_at", { withTimezone: true }),
190
- attempts: integer("attempts").notNull().default(0),
191
- // Phase 3 placeholder — see ADR-025
192
- waitKind: waitKindEnum("wait_kind"),
193
- // Phase 3 placeholder — see ADR-025
194
- resumeToken: text("resume_token"),
195
- // Phase 3 placeholder — see ADR-025
196
- waitDeadline: timestamp("wait_deadline", { withTimezone: true }),
197
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
198
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
199
- },
200
- (t) => ({
201
- /** Claim query: ORDER BY priority DESC, run_at ASC. */
202
- idxJobRunClaim: index("idx_job_run_claim").on(t.status, t.pool, t.runAt),
203
- /** Tree traversal / cascade cancel. */
204
- idxJobRunRoot: index("idx_job_run_root").on(t.rootRunId),
205
- /** listForScope query. */
206
- idxJobRunScope: index("idx_job_run_scope").on(t.scopeEntityType, t.scopeEntityId),
207
- /** Idempotency collapse — partial index. */
208
- idxJobRunDedupe: index("idx_job_run_dedupe").on(t.jobType, t.dedupeKey).where(sql`${t.dedupeKey} IS NOT NULL`),
209
- /** Collision check — partial index. */
210
- idxJobRunConcurrency: index("idx_job_run_concurrency").on(t.concurrencyKey).where(
211
- sql`${t.concurrencyKey} IS NOT NULL AND ${t.status} IN ('pending','running')`
212
- )
213
- })
214
- );
215
- var jobSteps = pgTable(
216
- "job_step",
217
- {
218
- id: uuid("id").primaryKey().defaultRandom(),
219
- jobRunId: uuid("job_run_id").notNull().references(() => jobRuns.id),
220
- stepId: text("step_id").notNull(),
221
- kind: jobStepKindEnum("kind").notNull().default("task"),
222
- /**
223
- * Monotonic within run. integer (max ~2B per run) is sufficient —
224
- * downgraded from ADR-022's bigint; revisit only if a single run
225
- * ever exceeds 2 billion steps.
226
- */
227
- seq: integer("seq").notNull(),
228
- status: jobStepStatusEnum("status").notNull().default("pending"),
229
- input: jsonb("input").$type(),
230
- /** Memoised on success for replay. */
231
- output: jsonb("output").$type(),
232
- error: jsonb("error").$type(),
233
- attempts: integer("attempts").notNull().default(0),
234
- startedAt: timestamp("started_at", { withTimezone: true }),
235
- finishedAt: timestamp("finished_at", { withTimezone: true })
236
- },
237
- (t) => ({
238
- /** No duplicate step IDs per run. */
239
- idxJobStepRunStep: uniqueIndex("idx_job_step_run_step").on(t.jobRunId, t.stepId),
240
- /** Ordered timeline reads. */
241
- idxJobStepTimeline: index("idx_job_step_timeline").on(t.jobRunId, t.seq)
242
- })
243
- );
244
-
245
- // runtime/subsystems/jobs/jobs-errors.ts
246
- var JobTypeNotFoundError = class extends Error {
247
- constructor(jobType) {
248
- super(`No job definition registered for type '${jobType}'.`);
249
- this.jobType = jobType;
250
- }
251
- jobType;
252
- name = "JobTypeNotFoundError";
253
- };
254
- var JobCollisionError = class extends Error {
255
- constructor(jobType, concurrencyKey, incumbent) {
256
- super(
257
- `Job type '${jobType}' has an in-flight run with concurrency_key '${concurrencyKey}' (incumbent ${incumbent.id}); collision_mode=reject.`
258
- );
259
- this.jobType = jobType;
260
- this.concurrencyKey = concurrencyKey;
261
- this.incumbent = incumbent;
262
- }
263
- jobType;
264
- concurrencyKey;
265
- incumbent;
266
- name = "JobCollisionError";
267
- };
268
- var JobNotReplayableError = class extends Error {
269
- constructor(runId, currentStatus) {
270
- super(
271
- `Run ${runId} is not replayable from status '${currentStatus}'. Only 'completed', 'failed', 'timed_out', and 'canceled' are eligible.`
272
- );
273
- this.runId = runId;
274
- this.currentStatus = currentStatus;
275
- }
276
- runId;
277
- currentStatus;
278
- name = "JobNotReplayableError";
279
- };
280
- var JobTemplateFieldMissingError = class extends Error {
281
- constructor(template, field) {
282
- super(
283
- `Template '${template}' references input field '${field}' which is missing or undefined on the payload.`
284
- );
285
- this.template = template;
286
- this.field = field;
287
- }
288
- template;
289
- field;
290
- name = "JobTemplateFieldMissingError";
291
- };
292
- var MissingTenantIdError = class extends Error {
293
- constructor(method) {
294
- super(
295
- `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.`
296
- );
297
- this.method = method;
298
- }
299
- method;
300
- name = "MissingTenantIdError";
301
- };
302
- var BootValidationError = class extends Error {
303
- constructor(missingHandlers) {
304
- super(
305
- `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.`
306
- );
307
- this.missingHandlers = missingHandlers;
308
- }
309
- missingHandlers;
310
- name = "BootValidationError";
311
- };
312
- var ReservedPoolViolationError = class extends Error {
313
- constructor(offenders) {
314
- super(
315
- `ReservedPoolViolationError: ${offenders.length} @JobHandler(s) target reserved pools \u2014 reserved pools are framework-only:
316
- ` + offenders.map((o) => ` - ${o.handlerClass} \u2192 pool='${o.pool}'`).join("\n")
317
- );
318
- this.offenders = offenders;
319
- }
320
- offenders;
321
- name = "ReservedPoolViolationError";
322
- };
323
-
324
- // runtime/subsystems/jobs/job-orchestrator.drizzle-backend.ts
325
- var TERMINAL_STATUSES = [
326
- "completed",
327
- "failed",
328
- "timed_out",
329
- "canceled"
330
- ];
331
- var DEDUPE_EXCLUDED_STATUSES = ["canceled", "failed"];
332
- var IN_FLIGHT_STATUSES = ["pending", "running"];
333
- function evaluateKeyTemplate(template, input) {
334
- return template.replace(/\{\{\s*([a-zA-Z0-9_]+)\s*\}\}/g, (_match, field) => {
335
- const value = input[field];
336
- if (value === void 0 || value === null) {
337
- throw new JobTemplateFieldMissingError(template, field);
338
- }
339
- return String(value);
340
- });
341
- }
342
- var DrizzleJobOrchestrator = class {
343
- constructor(db, multiTenant) {
344
- this.db = db;
345
- this.multiTenant = multiTenant;
346
- }
347
- db;
348
- multiTenant;
349
- // TODO(logging-subsystem): swap to ILogger once ADR-028 lands
350
- logger = new Logger(DrizzleJobOrchestrator.name);
351
- /**
352
- * JOB-8 — resolve `tenantId` for a mutating / targeted-read call.
353
- * Returns the tenant value that should be written to the row (or compared
354
- * against in a WHERE clause). When `multiTenant` is off, the column is
355
- * forced to `null` regardless of what callers pass. When on, `undefined`
356
- * throws; `null` and strings pass through untouched.
357
- */
358
- resolveTenantId(method, tenantId) {
359
- if (!this.multiTenant) return null;
360
- if (tenantId === void 0) throw new MissingTenantIdError(method);
361
- return tenantId;
362
- }
363
- // ==========================================================================
364
- // start
365
- // ==========================================================================
366
- async start(type, input, opts = {}, tx) {
367
- const payload = input ?? {};
368
- const tenantId = this.resolveTenantId("start", opts.tenantId);
369
- const client = tx ?? this.db;
370
- const [def] = await client.select().from(jobs).where(eq(jobs.type, type)).limit(1);
371
- if (!def) throw new JobTypeNotFoundError(type);
372
- const definition = def;
373
- if (definition.dedupeKeyTemplate && definition.dedupeWindowMs) {
374
- const dedupeKey2 = evaluateKeyTemplate(definition.dedupeKeyTemplate, payload);
375
- const windowStart = new Date(Date.now() - definition.dedupeWindowMs);
376
- const existing = await client.select().from(jobRuns).where(
377
- and(
378
- eq(jobRuns.jobType, type),
379
- eq(jobRuns.dedupeKey, dedupeKey2),
380
- gt(jobRuns.createdAt, windowStart),
381
- // status NOT IN ('canceled', 'failed')
382
- notInStatus(DEDUPE_EXCLUDED_STATUSES)
383
- )
384
- ).orderBy(desc(jobRuns.createdAt)).limit(1);
385
- if (existing.length > 0) {
386
- return existing[0];
387
- }
388
- }
389
- let concurrencyKey = null;
390
- if (definition.concurrencyKeyTemplate) {
391
- concurrencyKey = evaluateKeyTemplate(
392
- definition.concurrencyKeyTemplate,
393
- payload
394
- );
395
- const inFlight = await client.select().from(jobRuns).where(
396
- and(
397
- eq(jobRuns.concurrencyKey, concurrencyKey),
398
- inArray(jobRuns.status, IN_FLIGHT_STATUSES)
399
- )
400
- ).limit(1);
401
- if (inFlight.length > 0) {
402
- const incumbent = inFlight[0];
403
- switch (definition.collisionMode) {
404
- case "reject":
405
- throw new JobCollisionError(type, concurrencyKey, incumbent);
406
- case "replace":
407
- await this.cancel(incumbent.id, {
408
- cascade: true,
409
- reason: "replaced",
410
- tenantId: incumbent.tenantId
411
- });
412
- break;
413
- case "queue":
414
- break;
415
- }
416
- }
417
- }
418
- const newId = randomUUID();
419
- let rootRunId = newId;
420
- if (opts.parentRunId) {
421
- const [parent] = await client.select({ rootRunId: jobRuns.rootRunId }).from(jobRuns).where(eq(jobRuns.id, opts.parentRunId)).limit(1);
422
- if (!parent) {
423
- throw new Error(
424
- `parentRunId ${opts.parentRunId} does not reference an existing job_run`
425
- );
426
- }
427
- rootRunId = parent.rootRunId;
428
- }
429
- const dedupeKey = definition.dedupeKeyTemplate ? evaluateKeyTemplate(definition.dedupeKeyTemplate, payload) : null;
430
- const [inserted] = await client.insert(jobRuns).values({
431
- id: newId,
432
- jobType: type,
433
- jobVersion: definition.version,
434
- parentRunId: opts.parentRunId ?? null,
435
- rootRunId,
436
- parentClosePolicy: opts.parentClosePolicy ?? "terminate",
437
- scopeEntityType: opts.scope?.entityType ?? null,
438
- scopeEntityId: opts.scope?.entityId ?? null,
439
- tenantId,
440
- tags: opts.tags ?? {},
441
- pool: opts.pool ?? definition.pool,
442
- priority: opts.priority ?? definition.priorityDefault,
443
- concurrencyKey,
444
- dedupeKey,
445
- status: "pending",
446
- input: payload,
447
- output: null,
448
- error: null,
449
- triggerSource: opts.triggerSource ?? "manual",
450
- triggerRef: opts.triggerRef ?? null,
451
- runAt: opts.runAt ?? /* @__PURE__ */ new Date(),
452
- startedAt: null,
453
- finishedAt: null,
454
- claimedAt: null,
455
- attempts: 0
456
- }).returning();
457
- return inserted;
458
- }
459
- // ==========================================================================
460
- // cancel
461
- // ==========================================================================
462
- async cancel(runId, opts = {}) {
463
- const tenantId = this.resolveTenantId("cancel", opts.tenantId);
464
- const [target] = await this.db.select().from(jobRuns).where(eq(jobRuns.id, runId)).limit(1);
465
- if (!target) return;
466
- if (this.multiTenant && target.tenantId !== tenantId) return;
467
- if (TERMINAL_STATUSES.includes(target.status)) {
468
- return;
469
- }
470
- const [cancelled] = await this.db.update(jobRuns).set({
471
- status: "canceled",
472
- finishedAt: /* @__PURE__ */ new Date(),
473
- updatedAt: /* @__PURE__ */ new Date()
474
- }).where(
475
- and(eq(jobRuns.id, runId), notInStatus([...TERMINAL_STATUSES]))
476
- ).returning();
477
- if (!cancelled) return;
478
- if (opts.cascade === false) return;
479
- const descendants = await this.db.select().from(jobRuns).where(
480
- and(
481
- eq(jobRuns.rootRunId, target.rootRunId),
482
- ne(jobRuns.id, runId),
483
- notInStatus([...TERMINAL_STATUSES])
484
- )
485
- );
486
- for (const child of descendants) {
487
- const policy = child.parentClosePolicy;
488
- if (policy === "abandon") continue;
489
- await this.db.update(jobRuns).set({
490
- status: "canceled",
491
- finishedAt: /* @__PURE__ */ new Date(),
492
- updatedAt: /* @__PURE__ */ new Date()
493
- }).where(
494
- and(
495
- eq(jobRuns.id, child.id),
496
- notInStatus([...TERMINAL_STATUSES])
497
- )
498
- );
499
- }
500
- void opts.reason;
501
- }
502
- // ==========================================================================
503
- // replay
504
- // ==========================================================================
505
- async replay(runId) {
506
- const [target] = await this.db.select().from(jobRuns).where(eq(jobRuns.id, runId)).limit(1);
507
- if (!target) {
508
- throw new Error(`replay: run ${runId} not found`);
509
- }
510
- const run = target;
511
- if (!TERMINAL_STATUSES.includes(run.status)) {
512
- throw new JobNotReplayableError(runId, run.status);
513
- }
514
- const [def] = await this.db.select().from(jobs).where(eq(jobs.type, run.jobType)).limit(1);
515
- if (!def) throw new JobTypeNotFoundError(run.jobType);
516
- const mode = def.replayFrom;
517
- const result = await this.db.transaction(async (tx) => {
518
- if (mode === "scratch") {
519
- await tx.delete(jobSteps).where(eq(jobSteps.jobRunId, runId));
520
- } else if (mode === "last_step") {
521
- await tx.delete(jobSteps).where(
522
- and(eq(jobSteps.jobRunId, runId), ne(jobSteps.status, "completed"))
523
- );
524
- } else {
525
- await tx.delete(jobSteps).where(
526
- and(eq(jobSteps.jobRunId, runId), ne(jobSteps.status, "completed"))
527
- );
528
- }
529
- const [updated] = await tx.update(jobRuns).set({
530
- status: "pending",
531
- attempts: 0,
532
- runAt: /* @__PURE__ */ new Date(),
533
- startedAt: null,
534
- finishedAt: null,
535
- claimedAt: null,
536
- error: null,
537
- output: null,
538
- updatedAt: /* @__PURE__ */ new Date()
539
- }).where(eq(jobRuns.id, runId)).returning();
540
- return updated;
541
- });
542
- return result;
543
- }
544
- // ==========================================================================
545
- // upsertJobRows — boot-time materialisation of `job` definitions
546
- // ==========================================================================
547
- /**
548
- * Hash-gated `INSERT … ON CONFLICT (type) DO UPDATE … WHERE` per Q3
549
- * resolution (2026-04-19): the `UPDATE` branch executes only when one
550
- * of the persisted metadata fields differs from the incoming payload;
551
- * `version` bumps only on real change; concurrent boots with identical
552
- * content are idempotent no-ops.
553
- *
554
- * Why this shape (not `DO NOTHING`, not advisory locks):
555
- * - `DO NOTHING` would let an old-version instance leave a stale row
556
- * that a new-version instance can't overwrite during a rolling deploy.
557
- * - Advisory locks add latency and leak risk under crashes.
558
- * - The `WHERE … IS DISTINCT FROM …` clause makes the conditional
559
- * atomic — no read-modify-write race on `version` between concurrent
560
- * boots.
561
- *
562
- * Orphan detection: a single `SELECT type FROM job WHERE type NOT IN (...)`
563
- * returns the types present in DB but absent from `entries`. Caller (boot
564
- * validator) decides whether to throw `BootValidationError`.
565
- */
566
- async upsertJobRows(entries, poolConfig) {
567
- void poolConfig;
568
- for (const entry of entries) {
569
- const meta = entry.meta;
570
- const pool = meta.pool ?? "batch";
571
- const retryPolicy = meta.retry ?? {
572
- attempts: 1,
573
- backoff: "fixed",
574
- baseMs: 0
575
- };
576
- const concurrencyKeyTemplate = meta.concurrency?.key;
577
- const concurrencyKeyTemplateStr = typeof concurrencyKeyTemplate === "string" ? concurrencyKeyTemplate : null;
578
- const collisionMode = meta.concurrency?.collisionMode ?? "queue";
579
- const dedupeKeyTemplate = meta.dedupe?.key;
580
- const dedupeKeyTemplateStr = typeof dedupeKeyTemplate === "string" ? dedupeKeyTemplate : null;
581
- const dedupeWindowMs = meta.dedupe?.windowMs ?? null;
582
- const timeoutMs = meta.timeoutMs ?? null;
583
- const replayFrom = meta.replayFrom ?? "last_checkpoint";
584
- const scopeEntityType = meta.scope?.entity ?? null;
585
- const priorityDefault = 0;
586
- await this.db.insert(jobs).values({
587
- type: entry.type,
588
- version: 1,
589
- pool,
590
- scopeEntityType,
591
- retryPolicy,
592
- timeoutMs,
593
- concurrencyKeyTemplate: concurrencyKeyTemplateStr,
594
- collisionMode,
595
- dedupeKeyTemplate: dedupeKeyTemplateStr,
596
- dedupeWindowMs,
597
- priorityDefault,
598
- replayFrom
599
- }).onConflictDoUpdate({
600
- target: jobs.type,
601
- set: {
602
- pool: sql2`EXCLUDED.pool`,
603
- scopeEntityType: sql2`EXCLUDED.scope_entity_type`,
604
- retryPolicy: sql2`EXCLUDED.retry_policy`,
605
- timeoutMs: sql2`EXCLUDED.timeout_ms`,
606
- concurrencyKeyTemplate: sql2`EXCLUDED.concurrency_key_template`,
607
- collisionMode: sql2`EXCLUDED.collision_mode`,
608
- dedupeKeyTemplate: sql2`EXCLUDED.dedupe_key_template`,
609
- dedupeWindowMs: sql2`EXCLUDED.dedupe_window_ms`,
610
- priorityDefault: sql2`EXCLUDED.priority_default`,
611
- replayFrom: sql2`EXCLUDED.replay_from`,
612
- version: sql2`${jobs.version} + 1`,
613
- updatedAt: sql2`now()`
614
- },
615
- // The hash gate: every field listed in the Q3 resolution appears
616
- // here. `IS DISTINCT FROM` is the null-safe inequality operator;
617
- // jsonb cast to text gives stable comparison without invoking a
618
- // dedicated hash column (avoids a JOB-1 schema migration).
619
- setWhere: sql2`
620
- ${jobs.pool} IS DISTINCT FROM EXCLUDED.pool OR
621
- ${jobs.retryPolicy}::text IS DISTINCT FROM EXCLUDED.retry_policy::text OR
622
- ${jobs.timeoutMs} IS DISTINCT FROM EXCLUDED.timeout_ms OR
623
- ${jobs.concurrencyKeyTemplate} IS DISTINCT FROM EXCLUDED.concurrency_key_template OR
624
- ${jobs.collisionMode} IS DISTINCT FROM EXCLUDED.collision_mode OR
625
- ${jobs.dedupeKeyTemplate} IS DISTINCT FROM EXCLUDED.dedupe_key_template OR
626
- ${jobs.dedupeWindowMs} IS DISTINCT FROM EXCLUDED.dedupe_window_ms OR
627
- ${jobs.priorityDefault} IS DISTINCT FROM EXCLUDED.priority_default OR
628
- ${jobs.replayFrom} IS DISTINCT FROM EXCLUDED.replay_from OR
629
- ${jobs.scopeEntityType} IS DISTINCT FROM EXCLUDED.scope_entity_type
630
- `
631
- });
632
- }
633
- const types = entries.map((e) => e.type);
634
- 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));
635
- return { orphaned: orphans.map((o) => o.type) };
636
- }
637
- };
638
- DrizzleJobOrchestrator = __decorateClass([
639
- Injectable(),
640
- __decorateParam(0, Inject(DRIZZLE)),
641
- __decorateParam(1, Inject(JOBS_MULTI_TENANT))
642
- ], DrizzleJobOrchestrator);
643
- function notInStatus(statuses) {
644
- const negated = statuses.map((s) => ne(jobRuns.status, s));
645
- return and(...negated);
646
- }
647
-
648
- // runtime/subsystems/jobs/job-run-service.drizzle-backend.ts
649
- import { Inject as Inject2, Injectable as Injectable2 } from "@nestjs/common";
650
- import { and as and2, asc, desc as desc2, eq as eq2, gte, inArray as inArray2, isNull, lt, or, sql as sql3 } from "drizzle-orm";
651
-
652
- // runtime/subsystems/jobs/job-run-keyset-cursor.ts
653
- var DEFAULT_LIST_LIMIT = 50;
654
- var MAX_LIST_LIMIT = 200;
655
- function clampLimit(limit) {
656
- if (typeof limit !== "number" || !Number.isFinite(limit)) {
657
- return DEFAULT_LIST_LIMIT;
658
- }
659
- const floored = Math.floor(limit);
660
- if (floored < 1) return 1;
661
- if (floored > MAX_LIST_LIMIT) return MAX_LIST_LIMIT;
662
- return floored;
663
- }
664
- function encodeKeysetCursor(keyset) {
665
- const tuple = [keyset.createdAt.toISOString(), keyset.id];
666
- return Buffer.from(JSON.stringify(tuple), "utf8").toString("base64url");
667
- }
668
- function decodeKeysetCursor(cursor) {
669
- try {
670
- const json = Buffer.from(cursor, "base64url").toString("utf8");
671
- const parsed = JSON.parse(json);
672
- if (!Array.isArray(parsed) || parsed.length !== 2) return null;
673
- const [iso, id] = parsed;
674
- if (typeof iso !== "string" || typeof id !== "string") return null;
675
- const createdAt = new Date(iso);
676
- if (Number.isNaN(createdAt.getTime())) return null;
677
- return { createdAt, id };
678
- } catch {
679
- return null;
680
- }
681
- }
682
- function toJobRunSummary(r) {
683
- return {
684
- runId: r.id,
685
- rootRunId: r.rootRunId,
686
- parentRunId: r.parentRunId,
687
- triggerSource: r.triggerSource,
688
- triggerRef: r.triggerRef,
689
- jobType: r.jobType,
690
- pool: r.pool,
691
- status: r.status,
692
- scopeEntityType: r.scopeEntityType,
693
- scopeEntityId: r.scopeEntityId,
694
- tenantId: r.tenantId,
695
- attempts: r.attempts,
696
- errorMessage: r.error?.message ?? null,
697
- runAt: r.runAt,
698
- startedAt: r.startedAt,
699
- finishedAt: r.finishedAt,
700
- createdAt: r.createdAt
701
- };
702
- }
703
-
704
- // runtime/subsystems/jobs/job-run-service.drizzle-backend.ts
705
- var NON_TERMINAL_STATUSES = [
706
- "pending",
707
- "running",
708
- "waiting"
709
- ];
710
- var DrizzleJobRunService = class {
711
- constructor(db, orchestrator, multiTenant) {
712
- this.db = db;
713
- this.orchestrator = orchestrator;
714
- this.multiTenant = multiTenant;
715
- }
716
- db;
717
- orchestrator;
718
- multiTenant;
719
- /**
720
- * JOB-8 — produce the tenant WHERE fragment (or `null` to opt out).
721
- * Returns `null` when multi-tenancy is off (caller skips the predicate).
722
- * Throws `MissingTenantIdError` when on + `undefined`.
723
- * When on + explicit `null`, filters `tenant_id IS NULL`.
724
- */
725
- tenantCondition(method, tenantId) {
726
- if (!this.multiTenant) return null;
727
- if (tenantId === void 0) throw new MissingTenantIdError(method);
728
- return tenantId === null ? isNull(jobRuns.tenantId) : eq2(jobRuns.tenantId, tenantId);
729
- }
730
- async listForScope(entityType, entityId, opts = {}) {
731
- const conditions = [
732
- eq2(jobRuns.scopeEntityType, entityType),
733
- eq2(jobRuns.scopeEntityId, entityId)
734
- ];
735
- const tenantCond = this.tenantCondition("listForScope", opts.tenantId);
736
- if (tenantCond) conditions.push(tenantCond);
737
- if (opts.status) {
738
- if (Array.isArray(opts.status)) {
739
- conditions.push(inArray2(jobRuns.status, opts.status));
740
- } else {
741
- conditions.push(eq2(jobRuns.status, opts.status));
742
- }
743
- }
744
- if (opts.jobType) {
745
- conditions.push(eq2(jobRuns.jobType, opts.jobType));
746
- }
747
- const orderCol = (() => {
748
- switch (opts.orderBy) {
749
- case "created_at asc":
750
- return asc(jobRuns.createdAt);
751
- case "run_at desc":
752
- return desc2(jobRuns.runAt);
753
- case "run_at asc":
754
- return asc(jobRuns.runAt);
755
- case "created_at desc":
756
- default:
757
- return desc2(jobRuns.createdAt);
758
- }
759
- })();
760
- let q = this.db.select().from(jobRuns).where(and2(...conditions)).orderBy(orderCol).$dynamic();
761
- if (typeof opts.limit === "number") {
762
- q = q.limit(opts.limit);
763
- }
764
- if (typeof opts.offset === "number") {
765
- q = q.offset(opts.offset);
766
- }
767
- const rows = await q;
768
- return rows;
769
- }
770
- async cancelForScope(entityType, entityId, opts = {}) {
771
- const tenantCond = this.tenantCondition("cancelForScope", opts.tenantId);
772
- const conditions = [
773
- eq2(jobRuns.scopeEntityType, entityType),
774
- eq2(jobRuns.scopeEntityId, entityId),
775
- inArray2(jobRuns.status, NON_TERMINAL_STATUSES)
776
- ];
777
- if (tenantCond) conditions.push(tenantCond);
778
- const rows = await this.db.select({ id: jobRuns.id }).from(jobRuns).where(and2(...conditions));
779
- for (const { id } of rows) {
780
- await this.orchestrator.cancel(id, {
781
- cascade: true,
782
- tenantId: opts.tenantId
783
- });
784
- }
785
- }
786
- async rescheduleForScope(entityType, entityId, newRunAt, opts = {}) {
787
- const tenantCond = this.tenantCondition("rescheduleForScope", opts.tenantId);
788
- const conditions = [
789
- eq2(jobRuns.scopeEntityType, entityType),
790
- eq2(jobRuns.scopeEntityId, entityId),
791
- eq2(jobRuns.status, "pending")
792
- ];
793
- if (tenantCond) conditions.push(tenantCond);
794
- await this.db.update(jobRuns).set({ runAt: newRunAt, updatedAt: /* @__PURE__ */ new Date() }).where(and2(...conditions));
795
- }
796
- async countByPoolAndStatus(tenantId) {
797
- const tenantCond = this.tenantCondition("countByPoolAndStatus", tenantId);
798
- const rows = await this.db.select({
799
- pool: jobRuns.pool,
800
- status: jobRuns.status,
801
- count: sql3`count(*)::int`.as("count")
802
- }).from(jobRuns).where(tenantCond ?? void 0).groupBy(jobRuns.pool, jobRuns.status);
803
- return rows.map((r) => ({
804
- pool: r.pool,
805
- status: r.status,
806
- count: Number(r.count)
807
- }));
808
- }
809
- async listRecentFailed(limit, tenantId) {
810
- const conditions = [eq2(jobRuns.status, "failed")];
811
- const tenantCond = this.tenantCondition("listRecentFailed", tenantId);
812
- if (tenantCond) conditions.push(tenantCond);
813
- const rows = await this.db.select().from(jobRuns).where(and2(...conditions)).orderBy(desc2(jobRuns.finishedAt), desc2(jobRuns.updatedAt)).limit(limit);
814
- return rows.map((r) => ({
815
- runId: r.id,
816
- jobType: r.jobType,
817
- pool: r.pool,
818
- scopeEntityType: r.scopeEntityType,
819
- scopeEntityId: r.scopeEntityId,
820
- tenantId: r.tenantId,
821
- attempts: r.attempts,
822
- errorMessage: r.error?.message ?? null,
823
- failedAt: r.finishedAt ?? r.updatedAt,
824
- createdAt: r.createdAt
825
- }));
826
- }
827
- async listJobRuns(query = {}) {
828
- const limit = clampLimit(query.limit);
829
- const conditions = [];
830
- const tenantCond = this.tenantCondition("listJobRuns", query.tenantId);
831
- if (tenantCond) conditions.push(tenantCond);
832
- if (query.poolId) conditions.push(eq2(jobRuns.pool, query.poolId));
833
- if (query.rootRunId) conditions.push(eq2(jobRuns.rootRunId, query.rootRunId));
834
- if (query.status) conditions.push(eq2(jobRuns.status, query.status));
835
- if (query.since) conditions.push(gte(jobRuns.createdAt, query.since));
836
- if (query.cursor) {
837
- const keyset = decodeKeysetCursor(query.cursor);
838
- if (keyset) {
839
- conditions.push(
840
- or(
841
- lt(jobRuns.createdAt, keyset.createdAt),
842
- and2(
843
- eq2(jobRuns.createdAt, keyset.createdAt),
844
- lt(jobRuns.id, keyset.id)
845
- )
846
- )
847
- );
848
- }
849
- }
850
- 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);
851
- const hasMore = rows.length > limit;
852
- const page = hasMore ? rows.slice(0, limit) : rows;
853
- const items = page.map(toJobRunSummary);
854
- const last = page[page.length - 1];
855
- const nextCursor = hasMore && last ? encodeKeysetCursor({ createdAt: last.createdAt, id: last.id }) : null;
856
- return { items, nextCursor };
857
- }
858
- /**
859
- * Internal helper used by cascade paths (not on the public protocol).
860
- * Exposed as a public method on the concrete class so infrastructure
861
- * code (cascade tests, debug tools) can call it without a cast.
862
- */
863
- async findByRootRunId(rootRunId) {
864
- const rows = await this.db.select().from(jobRuns).where(eq2(jobRuns.rootRunId, rootRunId));
865
- return rows;
866
- }
867
- };
868
- DrizzleJobRunService = __decorateClass([
869
- Injectable2(),
870
- __decorateParam(0, Inject2(DRIZZLE)),
871
- __decorateParam(1, Inject2(JOB_ORCHESTRATOR)),
872
- __decorateParam(2, Inject2(JOBS_MULTI_TENANT))
873
- ], DrizzleJobRunService);
874
-
875
- // runtime/subsystems/jobs/job-step-service.drizzle-backend.ts
876
- import { Inject as Inject3, Injectable as Injectable3 } from "@nestjs/common";
877
- import { and as and3, eq as eq3 } from "drizzle-orm";
878
- var DrizzleJobStepService = class {
879
- constructor(db) {
880
- this.db = db;
881
- }
882
- db;
883
- async recordStep(input) {
884
- const values = {
885
- jobRunId: input.jobRunId,
886
- stepId: input.stepId,
887
- kind: input.kind,
888
- seq: input.seq,
889
- status: input.status,
890
- input: input.input ?? null,
891
- output: input.output ?? null,
892
- error: input.error ?? null,
893
- attempts: input.attempts ?? 0,
894
- startedAt: input.startedAt ?? null,
895
- finishedAt: input.finishedAt ?? null
896
- };
897
- const [row] = await this.db.insert(jobSteps).values(values).onConflictDoUpdate({
898
- target: [jobSteps.jobRunId, jobSteps.stepId],
899
- set: {
900
- status: values.status,
901
- output: values.output,
902
- error: values.error,
903
- finishedAt: values.finishedAt,
904
- attempts: values.attempts
905
- }
906
- }).returning();
907
- return row;
908
- }
909
- async findStep(runId, stepId) {
910
- const [row] = await this.db.select().from(jobSteps).where(and3(eq3(jobSteps.jobRunId, runId), eq3(jobSteps.stepId, stepId))).limit(1);
911
- return row ?? null;
912
- }
913
- };
914
- DrizzleJobStepService = __decorateClass([
915
- Injectable3(),
916
- __decorateParam(0, Inject3(DRIZZLE))
917
- ], DrizzleJobStepService);
918
-
919
- // runtime/subsystems/jobs/job-orchestrator.memory-backend.ts
920
- import { randomUUID as randomUUID3 } from "crypto";
921
- import { Inject as Inject5, Injectable as Injectable5, Logger as Logger2, Optional } from "@nestjs/common";
922
- import { ModuleRef } from "@nestjs/core";
923
-
924
- // runtime/subsystems/jobs/memory-job-store.ts
925
- var MemoryJobStore = class {
926
- /** Runs keyed by `id` (single source of truth for status/scope/lineage). */
927
- runs = /* @__PURE__ */ new Map();
928
- /** Steps keyed by `job_run_id`; array order matches insertion order. */
929
- steps = /* @__PURE__ */ new Map();
930
- /** Job definitions keyed by `type` — memory mirror of the `job` table. */
931
- jobs = /* @__PURE__ */ new Map();
932
- /** Reset everything. Tests call this in `beforeEach`. */
933
- clear() {
934
- this.runs.clear();
935
- this.steps.clear();
936
- this.jobs.clear();
937
- }
938
- };
939
-
940
- // runtime/subsystems/jobs/job-step-service.memory-backend.ts
941
- import { randomUUID as randomUUID2 } from "crypto";
942
- import { Inject as Inject4, Injectable as Injectable4 } from "@nestjs/common";
943
- var MemoryJobStepService = class {
944
- // ADR-037 (package-mode DI): explicit `@Inject(MemoryJobStore)` — the
945
- // published bundle carries no `design:paramtypes`, so a by-type inject
946
- // would resolve to `undefined` in package mode.
947
- constructor(store) {
948
- this.store = store;
949
- }
950
- store;
951
- async findStep(runId, stepId) {
952
- const rows = this.store.steps.get(runId);
953
- if (!rows) return null;
954
- const match = rows.find(
955
- (r) => r.stepId === stepId && r.status === "completed"
956
- );
957
- return match ?? null;
958
- }
959
- async recordStep(input) {
960
- const rows = this.getOrCreateRows(input.jobRunId);
961
- const existingIdx = rows.findIndex((r) => r.stepId === input.stepId);
962
- const normalisedInput = input.input ?? null;
963
- const normalisedOutput = input.output ?? null;
964
- if (existingIdx >= 0) {
965
- const prev = rows[existingIdx];
966
- const next = {
967
- ...prev,
968
- status: input.status,
969
- input: normalisedInput ?? prev.input,
970
- output: normalisedOutput ?? prev.output,
971
- error: input.error ?? prev.error,
972
- attempts: input.attempts ?? prev.attempts,
973
- startedAt: input.startedAt ?? prev.startedAt,
974
- finishedAt: input.finishedAt ?? prev.finishedAt
975
- };
976
- rows[existingIdx] = next;
977
- return next;
978
- }
979
- const seq = input.seq ?? this.nextSeq(rows);
980
- const row = {
981
- id: randomUUID2(),
982
- jobRunId: input.jobRunId,
983
- stepId: input.stepId,
984
- kind: input.kind,
985
- seq,
986
- status: input.status,
987
- input: normalisedInput,
988
- output: normalisedOutput,
989
- error: input.error ?? null,
990
- attempts: input.attempts ?? 0,
991
- startedAt: input.startedAt ?? null,
992
- finishedAt: input.finishedAt ?? null
993
- };
994
- rows.push(row);
995
- return row;
996
- }
997
- /**
998
- * Replay helper — wipe every step row for a run. Mirrors the `scratch`
999
- * replay mode of the Drizzle backend (`DELETE FROM job_step WHERE job_run_id = …`).
1000
- */
1001
- clearStepsForRun(runId) {
1002
- this.store.steps.delete(runId);
1003
- }
1004
- /**
1005
- * Remove every non-`completed` row for the run. Memoized (`completed`)
1006
- * rows are preserved — this is the `last_checkpoint` / `last_step`
1007
- * semantics the Drizzle backend implements via
1008
- * `DELETE … WHERE status != 'completed'`. Both replay modes route here
1009
- * (Phase 1 collapses `last_step` onto this behaviour; see JOB-3 notes).
1010
- */
1011
- clearIncompleteSteps(runId) {
1012
- const rows = this.store.steps.get(runId);
1013
- if (!rows) return;
1014
- const kept = rows.filter((r) => r.status === "completed");
1015
- if (kept.length === 0) {
1016
- this.store.steps.delete(runId);
1017
- } else {
1018
- this.store.steps.set(runId, kept);
1019
- }
1020
- }
1021
- getOrCreateRows(runId) {
1022
- let rows = this.store.steps.get(runId);
1023
- if (!rows) {
1024
- rows = [];
1025
- this.store.steps.set(runId, rows);
1026
- }
1027
- return rows;
1028
- }
1029
- nextSeq(rows) {
1030
- let max = 0;
1031
- for (const r of rows) {
1032
- if (r.seq > max) max = r.seq;
1033
- }
1034
- return max + 1;
1035
- }
1036
- };
1037
- MemoryJobStepService = __decorateClass([
1038
- Injectable4(),
1039
- __decorateParam(0, Inject4(MemoryJobStore))
1040
- ], MemoryJobStepService);
1041
-
1042
- // runtime/subsystems/jobs/job-orchestrator.memory-backend.ts
1043
- var QUEUED_RUN_AT = /* @__PURE__ */ new Date(864e13);
1044
- var TERMINAL_STATUSES2 = [
1045
- "completed",
1046
- "failed",
1047
- "timed_out",
1048
- "canceled"
1049
- ];
1050
- var DEDUPE_EXCLUDED_STATUSES2 = ["canceled", "failed"];
1051
- var IN_FLIGHT_STATUSES2 = ["pending", "running"];
1052
- function isTerminal(status) {
1053
- return TERMINAL_STATUSES2.includes(status);
1054
- }
1055
- function evaluateKeyTemplate2(template, input) {
1056
- return template.replace(
1057
- /\{\{\s*([a-zA-Z0-9_]+)\s*\}\}/g,
1058
- (_m, field) => {
1059
- const value = input[field];
1060
- if (value === void 0 || value === null) {
1061
- throw new JobTemplateFieldMissingError(template, field);
1062
- }
1063
- return String(value);
1064
- }
1065
- );
1066
- }
1067
- var PromiseMutex = class {
1068
- queue = Promise.resolve();
1069
- async run(fn) {
1070
- const next = this.queue.then(() => fn());
1071
- this.queue = next.then(
1072
- () => void 0,
1073
- () => void 0
1074
- );
1075
- return next;
1076
- }
1077
- };
1078
- var MemoryJobOrchestrator = class {
1079
- constructor(store, stepService, multiTenant, moduleRef) {
1080
- this.store = store;
1081
- this.stepService = stepService;
1082
- this.multiTenant = multiTenant;
1083
- this.moduleRef = moduleRef;
1084
- }
1085
- store;
1086
- stepService;
1087
- multiTenant;
1088
- moduleRef;
1089
- logger = new Logger2(MemoryJobOrchestrator.name);
1090
- mutex = new PromiseMutex();
1091
- handlerRegistry = /* @__PURE__ */ new Map();
1092
- /**
1093
- * `runId → dependent runId[]` — when a run with `concurrencyKey = K`
1094
- * blocks on an incumbent, its id is added here under the incumbent's id.
1095
- * On incumbent terminal transition we advance every dependent's `runAt`
1096
- * back to `now()` so it becomes claimable.
1097
- */
1098
- queueBlockers = /* @__PURE__ */ new Map();
1099
- /**
1100
- * JOB-8 — mirror of the Drizzle backend's `resolveTenantId`. Returns the
1101
- * value to stamp on `tenant_id` / compare against in memory predicates.
1102
- * Off → always `null`. On + `undefined` → throw. On + `null`/string → pass.
1103
- */
1104
- resolveTenantId(method, tenantId) {
1105
- if (!this.multiTenant) return null;
1106
- if (tenantId === void 0) throw new MissingTenantIdError(method);
1107
- return tenantId;
1108
- }
1109
- // ==========================================================================
1110
- // registerHandler — replaces Drizzle's `job` table upsert
1111
- // ==========================================================================
1112
- /**
1113
- * Populate the in-memory job definition row plus handler class lookup.
1114
- * Called by `JobWorkerModule.onModuleInit` in memory mode, or directly by
1115
- * unit tests that want to seed the registry without NestJS.
1116
- */
1117
- registerHandler(type, meta, handlerClass) {
1118
- const concurrencyKeyTemplate = meta.concurrency?.key ?? null;
1119
- const dedupeKeyTemplate = meta.dedupe?.key ?? null;
1120
- const dedupeWindowMs = meta.dedupe?.windowMs ?? null;
1121
- const now = /* @__PURE__ */ new Date();
1122
- const def = {
1123
- type,
1124
- version: 1,
1125
- pool: meta.pool ?? "batch",
1126
- scopeEntityType: meta.scope?.entity ?? null,
1127
- retryPolicy: meta.retry ?? {
1128
- attempts: 1,
1129
- backoff: "fixed",
1130
- baseMs: 0
1131
- },
1132
- timeoutMs: meta.timeoutMs ?? null,
1133
- concurrencyKeyTemplate: typeof concurrencyKeyTemplate === "string" ? concurrencyKeyTemplate : null,
1134
- collisionMode: meta.concurrency?.collisionMode ?? "queue",
1135
- dedupeKeyTemplate: typeof dedupeKeyTemplate === "string" ? dedupeKeyTemplate : null,
1136
- dedupeWindowMs,
1137
- priorityDefault: 0,
1138
- replayFrom: meta.replayFrom ?? "last_checkpoint",
1139
- createdAt: now,
1140
- updatedAt: now
1141
- };
1142
- this.store.jobs.set(type, def);
1143
- this.handlerRegistry.set(type, {
1144
- type,
1145
- meta,
1146
- handlerClass
1147
- });
1148
- }
1149
- /** Test helper — look up a registered handler without exposing the map. */
1150
- getHandlerRegistration(type) {
1151
- return this.handlerRegistry.get(type);
1152
- }
1153
- /**
1154
- * Boot-time upsert per `IJobOrchestrator.upsertJobRows`. Memory backend
1155
- * just funnels each entry through `registerHandler`. The validator is
1156
- * skipped entirely in memory mode (Q4 resolution 2026-04-19), so the
1157
- * orphaned list is always empty — there are no DB rows to compare against.
1158
- */
1159
- async upsertJobRows(entries, poolConfig) {
1160
- void poolConfig;
1161
- for (const entry of entries) {
1162
- this.registerHandler(
1163
- entry.type,
1164
- entry.meta,
1165
- entry.handlerClass
1166
- );
1167
- }
1168
- return { orphaned: [] };
1169
- }
1170
- // ==========================================================================
1171
- // start
1172
- // ==========================================================================
1173
- async start(type, input, opts = {}, _tx) {
1174
- const tenantId = this.resolveTenantId("start", opts.tenantId);
1175
- return this.mutex.run(async () => {
1176
- const payload = input ?? {};
1177
- const definition = this.store.jobs.get(type);
1178
- if (!definition) throw new JobTypeNotFoundError(type);
1179
- if (definition.dedupeKeyTemplate && definition.dedupeWindowMs) {
1180
- const dedupeKey2 = evaluateKeyTemplate2(
1181
- definition.dedupeKeyTemplate,
1182
- payload
1183
- );
1184
- const windowStart = Date.now() - definition.dedupeWindowMs;
1185
- const existing = this.findDedupeCandidate(type, dedupeKey2, windowStart);
1186
- if (existing) return existing;
1187
- }
1188
- let concurrencyKey = null;
1189
- let queueBlockedBy = null;
1190
- if (definition.concurrencyKeyTemplate) {
1191
- concurrencyKey = evaluateKeyTemplate2(
1192
- definition.concurrencyKeyTemplate,
1193
- payload
1194
- );
1195
- const incumbent = this.findInFlightByConcurrencyKey(concurrencyKey);
1196
- if (incumbent) {
1197
- switch (definition.collisionMode) {
1198
- case "reject":
1199
- throw new JobCollisionError(type, concurrencyKey, incumbent);
1200
- case "replace":
1201
- this.cancelLocked(
1202
- incumbent.id,
1203
- { cascade: true, reason: "replaced" },
1204
- incumbent.tenantId
1205
- );
1206
- break;
1207
- case "queue":
1208
- queueBlockedBy = incumbent.id;
1209
- break;
1210
- }
1211
- }
1212
- }
1213
- const newId = randomUUID3();
1214
- let rootRunId = newId;
1215
- if (opts.parentRunId) {
1216
- const parent = this.store.runs.get(opts.parentRunId);
1217
- if (!parent) {
1218
- throw new Error(
1219
- `parentRunId ${opts.parentRunId} does not reference an existing job_run`
1220
- );
1221
- }
1222
- rootRunId = parent.rootRunId;
1223
- }
1224
- const dedupeKey = definition.dedupeKeyTemplate ? evaluateKeyTemplate2(definition.dedupeKeyTemplate, payload) : null;
1225
- const now = /* @__PURE__ */ new Date();
1226
- const runAt = queueBlockedBy ? QUEUED_RUN_AT : opts.runAt ?? now;
1227
- const row = {
1228
- id: newId,
1229
- jobType: type,
1230
- jobVersion: definition.version,
1231
- parentRunId: opts.parentRunId ?? null,
1232
- rootRunId,
1233
- parentClosePolicy: opts.parentClosePolicy ?? "terminate",
1234
- scopeEntityType: opts.scope?.entityType ?? null,
1235
- scopeEntityId: opts.scope?.entityId ?? null,
1236
- tenantId,
1237
- tags: opts.tags ?? {},
1238
- pool: opts.pool ?? definition.pool,
1239
- priority: opts.priority ?? definition.priorityDefault,
1240
- concurrencyKey,
1241
- dedupeKey,
1242
- status: "pending",
1243
- input: payload,
1244
- output: null,
1245
- error: null,
1246
- triggerSource: opts.triggerSource ?? "manual",
1247
- triggerRef: opts.triggerRef ?? null,
1248
- runAt,
1249
- startedAt: null,
1250
- finishedAt: null,
1251
- claimedAt: null,
1252
- attempts: 0,
1253
- waitKind: null,
1254
- resumeToken: null,
1255
- waitDeadline: null,
1256
- createdAt: now,
1257
- updatedAt: now
1258
- };
1259
- this.store.runs.set(newId, row);
1260
- if (queueBlockedBy) {
1261
- const list = this.queueBlockers.get(queueBlockedBy) ?? [];
1262
- list.push(newId);
1263
- this.queueBlockers.set(queueBlockedBy, list);
1264
- }
1265
- return row;
1266
- });
1267
- }
1268
- // ==========================================================================
1269
- // cancel
1270
- // ==========================================================================
1271
- async cancel(runId, opts = {}) {
1272
- const tenantId = this.resolveTenantId("cancel", opts.tenantId);
1273
- await this.mutex.run(async () => {
1274
- this.cancelLocked(runId, opts, tenantId);
1275
- });
1276
- }
1277
- /**
1278
- * Internal cancel that assumes the caller already holds the mutex.
1279
- * Synchronous because all store ops are in-memory. Idempotent.
1280
- *
1281
- * `tenantForGate` is the already-validated tenant id (or `null`). When
1282
- * non-null it gates the initial cancellation to that tenant's run; the
1283
- * cascade step then sweeps descendants on the same `rootRunId` without
1284
- * re-checking — children of a tenant-gated parent always share the
1285
- * tenant (enforced at `start` time).
1286
- */
1287
- cancelLocked(runId, opts, tenantForGate) {
1288
- const run = this.store.runs.get(runId);
1289
- if (!run) return;
1290
- if (this.multiTenant && run.tenantId !== tenantForGate) return;
1291
- if (isTerminal(run.status)) return;
1292
- const now = /* @__PURE__ */ new Date();
1293
- const descendants = opts.cascade === false ? [] : Array.from(this.store.runs.values()).filter(
1294
- (r) => r.rootRunId === run.rootRunId && r.id !== runId && !isTerminal(r.status)
1295
- );
1296
- const terminateChildren = descendants.filter(
1297
- (d) => d.parentClosePolicy === "terminate" /* Terminate */
1298
- );
1299
- const cancelChildren = descendants.filter(
1300
- (d) => d.parentClosePolicy === "cancel" /* Cancel */
1301
- );
1302
- for (const child of terminateChildren) {
1303
- this.transitionToCanceled(child.id, now);
1304
- }
1305
- for (const child of cancelChildren) {
1306
- this.transitionToCanceled(child.id, now);
1307
- }
1308
- this.transitionToCanceled(runId, now);
1309
- void opts.reason;
1310
- }
1311
- transitionToCanceled(runId, at) {
1312
- const run = this.store.runs.get(runId);
1313
- if (!run) return;
1314
- if (isTerminal(run.status)) return;
1315
- const next = {
1316
- ...run,
1317
- status: "canceled",
1318
- finishedAt: at,
1319
- updatedAt: at
1320
- };
1321
- this.store.runs.set(runId, next);
1322
- this.unblockQueuedDependents(runId);
1323
- }
1324
- /**
1325
- * When `runId` transitions to a terminal state, advance every dependent
1326
- * `queue`-blocked run's `run_at` back to `now()` so `claimNext` picks
1327
- * them up.
1328
- */
1329
- unblockQueuedDependents(runId) {
1330
- const dependents = this.queueBlockers.get(runId);
1331
- if (!dependents || dependents.length === 0) return;
1332
- const now = /* @__PURE__ */ new Date();
1333
- for (const dep of dependents) {
1334
- const depRun = this.store.runs.get(dep);
1335
- if (!depRun) continue;
1336
- if (depRun.status !== "pending") continue;
1337
- this.store.runs.set(dep, { ...depRun, runAt: now, updatedAt: now });
1338
- }
1339
- this.queueBlockers.delete(runId);
1340
- }
1341
- // ==========================================================================
1342
- // claimNext — consumed by JobWorker in memory mode (tests exercise directly)
1343
- // ==========================================================================
1344
- async claimNext(pool) {
1345
- return this.mutex.run(async () => {
1346
- const now = Date.now();
1347
- const candidates = Array.from(this.store.runs.values()).filter(
1348
- (r) => r.status === "pending" && r.pool === pool && r.runAt.getTime() <= now
1349
- );
1350
- if (candidates.length === 0) return null;
1351
- candidates.sort((a, b) => {
1352
- if (a.priority !== b.priority) return b.priority - a.priority;
1353
- return a.runAt.getTime() - b.runAt.getTime();
1354
- });
1355
- const winner = candidates[0];
1356
- const claimedAt = /* @__PURE__ */ new Date();
1357
- const next = {
1358
- ...winner,
1359
- status: "running",
1360
- claimedAt,
1361
- startedAt: claimedAt,
1362
- updatedAt: claimedAt
1363
- };
1364
- this.store.runs.set(winner.id, next);
1365
- return next;
1366
- });
1367
- }
1368
- // ==========================================================================
1369
- // replay
1370
- // ==========================================================================
1371
- async replay(runId) {
1372
- return this.mutex.run(async () => {
1373
- const run = this.store.runs.get(runId);
1374
- if (!run) throw new Error(`replay: run ${runId} not found`);
1375
- if (!isTerminal(run.status)) {
1376
- throw new JobNotReplayableError(runId, run.status);
1377
- }
1378
- const def = this.store.jobs.get(run.jobType);
1379
- if (!def) throw new JobTypeNotFoundError(run.jobType);
1380
- const mode = def.replayFrom;
1381
- if (mode === "scratch") {
1382
- this.stepService.clearStepsForRun(runId);
1383
- } else {
1384
- this.stepService.clearIncompleteSteps(runId);
1385
- }
1386
- const now = /* @__PURE__ */ new Date();
1387
- const next = {
1388
- ...run,
1389
- status: "pending",
1390
- attempts: 0,
1391
- runAt: now,
1392
- startedAt: null,
1393
- finishedAt: null,
1394
- claimedAt: null,
1395
- error: null,
1396
- output: null,
1397
- updatedAt: now
1398
- };
1399
- this.store.runs.set(runId, next);
1400
- return next;
1401
- });
1402
- }
1403
- // ==========================================================================
1404
- // tick — used by unit tests + memory-mode JobWorker
1405
- // ==========================================================================
1406
- /**
1407
- * Execute a single claimed run to completion, retry, or failure. Not on
1408
- * `IJobOrchestrator` — it's the memory equivalent of the Drizzle
1409
- * `JobWorker.processRun` code path. The unit tests drive it directly so
1410
- * they can assert memoization across ticks without spinning up a worker.
1411
- */
1412
- async tick(runId) {
1413
- const run = this.store.runs.get(runId);
1414
- if (!run) throw new Error(`tick: run ${runId} not found`);
1415
- if (run.status !== "running") {
1416
- throw new Error(
1417
- `tick: run ${runId} must be 'running' (got '${run.status}')`
1418
- );
1419
- }
1420
- const registration = this.handlerRegistry.get(run.jobType);
1421
- if (!registration) {
1422
- await this.markFailed(run, new Error(
1423
- `No handler registered for jobType='${run.jobType}'`
1424
- ), (run.attempts ?? 0) + 1);
1425
- return;
1426
- }
1427
- const meta = registration.meta;
1428
- const HandlerClass = registration.handlerClass;
1429
- const handler = this.moduleRef ? this.moduleRef.get(
1430
- HandlerClass,
1431
- { strict: false }
1432
- ) : new HandlerClass();
1433
- const ctx = {
1434
- input: run.input,
1435
- run,
1436
- step: this.makeStepFn(run),
1437
- spawnChild: this.makeSpawnFn(run),
1438
- logger: new Logger2(`JobRun:${run.id}`)
1439
- };
1440
- const attemptsBefore = run.attempts ?? 0;
1441
- try {
1442
- const output = await handler.run(ctx);
1443
- await this.markCompleted(run, output ?? {}, attemptsBefore + 1);
1444
- } catch (err) {
1445
- const policy = meta.retry;
1446
- const decision = classifyError(err, policy, attemptsBefore);
1447
- const nextAttempts = attemptsBefore + 1;
1448
- if (decision === "retry" && policy) {
1449
- const delay = computeBackoff(policy, nextAttempts);
1450
- await this.rescheduleForRetry(run, err, nextAttempts, delay);
1451
- } else {
1452
- await this.markFailed(run, err, nextAttempts);
1453
- }
1454
- }
1455
- }
1456
- makeStepFn(run) {
1457
- return async (stepId, fn, _opts) => {
1458
- void _opts;
1459
- const existing = await this.stepService.findStep(run.id, stepId);
1460
- if (existing?.status === "completed") {
1461
- return existing.output;
1462
- }
1463
- const seq = this.nextStepSeq(run.id);
1464
- const startedAt = /* @__PURE__ */ new Date();
1465
- const nextAttempts = (existing?.attempts ?? 0) + 1;
1466
- await this.stepService.recordStep({
1467
- jobRunId: run.id,
1468
- stepId,
1469
- kind: "task",
1470
- seq,
1471
- status: "running",
1472
- startedAt,
1473
- attempts: nextAttempts
1474
- });
1475
- try {
1476
- const output = await fn();
1477
- await this.stepService.recordStep({
1478
- jobRunId: run.id,
1479
- stepId,
1480
- kind: "task",
1481
- seq,
1482
- status: "completed",
1483
- output,
1484
- finishedAt: /* @__PURE__ */ new Date(),
1485
- attempts: nextAttempts
1486
- });
1487
- return output;
1488
- } catch (err) {
1489
- await this.stepService.recordStep({
1490
- jobRunId: run.id,
1491
- stepId,
1492
- kind: "task",
1493
- seq,
1494
- status: "failed",
1495
- error: serialiseError(err, nextAttempts, false),
1496
- finishedAt: /* @__PURE__ */ new Date(),
1497
- attempts: nextAttempts
1498
- });
1499
- throw err;
1500
- }
1501
- };
1502
- }
1503
- makeSpawnFn(run) {
1504
- return async (type, input, opts) => {
1505
- return this.start(type, input, {
1506
- parentRunId: run.id,
1507
- parentClosePolicy: opts?.closePolicy,
1508
- runAt: opts?.runAt,
1509
- priority: opts?.priority,
1510
- tags: opts?.tags,
1511
- triggerSource: "parent",
1512
- triggerRef: run.id
1513
- });
1514
- };
1515
- }
1516
- nextStepSeq(runId) {
1517
- const rows = this.store.steps.get(runId);
1518
- if (!rows || rows.length === 0) return 1;
1519
- let max = 0;
1520
- for (const r of rows) if (r.seq > max) max = r.seq;
1521
- return max + 1;
1522
- }
1523
- async markCompleted(run, output, attempts) {
1524
- await this.mutex.run(async () => {
1525
- const current = this.store.runs.get(run.id);
1526
- if (!current || isTerminal(current.status)) return;
1527
- const now = /* @__PURE__ */ new Date();
1528
- this.store.runs.set(run.id, {
1529
- ...current,
1530
- status: "completed",
1531
- output,
1532
- finishedAt: now,
1533
- updatedAt: now,
1534
- attempts
1535
- });
1536
- this.unblockQueuedDependents(run.id);
1537
- });
1538
- }
1539
- async markFailed(run, err, attempts) {
1540
- await this.mutex.run(async () => {
1541
- const current = this.store.runs.get(run.id);
1542
- if (!current || isTerminal(current.status)) return;
1543
- const now = /* @__PURE__ */ new Date();
1544
- this.store.runs.set(run.id, {
1545
- ...current,
1546
- status: "failed",
1547
- finishedAt: now,
1548
- updatedAt: now,
1549
- attempts,
1550
- error: serialiseError(err, attempts, false)
1551
- });
1552
- this.unblockQueuedDependents(run.id);
1553
- });
1554
- if (run.parentClosePolicy === "terminate") {
1555
- try {
1556
- await this.cancel(run.id, {
1557
- cascade: true,
1558
- reason: "parent-failed",
1559
- tenantId: run.tenantId
1560
- });
1561
- } catch (cascadeErr) {
1562
- this.logger.warn(
1563
- `cascade on failed run ${run.id}: ${cascadeErr.message}`
1564
- );
1565
- }
1566
- }
1567
- }
1568
- async rescheduleForRetry(run, err, attempts, delayMs) {
1569
- await this.mutex.run(async () => {
1570
- const current = this.store.runs.get(run.id);
1571
- if (!current || isTerminal(current.status)) return;
1572
- const now = /* @__PURE__ */ new Date();
1573
- this.store.runs.set(run.id, {
1574
- ...current,
1575
- status: "pending",
1576
- attempts,
1577
- runAt: new Date(Date.now() + delayMs),
1578
- startedAt: null,
1579
- claimedAt: null,
1580
- updatedAt: now,
1581
- error: serialiseError(err, attempts, true)
1582
- });
1583
- });
1584
- }
1585
- // ==========================================================================
1586
- // Internal queries — used by start / cancel
1587
- // ==========================================================================
1588
- findDedupeCandidate(jobType, dedupeKey, windowStartMs) {
1589
- let best = null;
1590
- for (const r of this.store.runs.values()) {
1591
- if (r.jobType !== jobType) continue;
1592
- if (r.dedupeKey !== dedupeKey) continue;
1593
- if (DEDUPE_EXCLUDED_STATUSES2.includes(r.status)) continue;
1594
- if (r.createdAt.getTime() <= windowStartMs) continue;
1595
- if (!best || r.createdAt.getTime() > best.createdAt.getTime()) {
1596
- best = r;
1597
- }
1598
- }
1599
- return best;
1600
- }
1601
- findInFlightByConcurrencyKey(key2) {
1602
- for (const r of this.store.runs.values()) {
1603
- if (r.concurrencyKey !== key2) continue;
1604
- if (!IN_FLIGHT_STATUSES2.includes(r.status)) continue;
1605
- return r;
1606
- }
1607
- return null;
1608
- }
1609
- };
1610
- MemoryJobOrchestrator = __decorateClass([
1611
- Injectable5(),
1612
- __decorateParam(0, Inject5(MemoryJobStore)),
1613
- __decorateParam(1, Inject5(MemoryJobStepService)),
1614
- __decorateParam(2, Inject5(JOBS_MULTI_TENANT)),
1615
- __decorateParam(3, Optional()),
1616
- __decorateParam(3, Inject5(ModuleRef))
1617
- ], MemoryJobOrchestrator);
1618
- function classifyError(err, policy, currentAttempts) {
1619
- if (!policy) return "fail";
1620
- const errObj = err;
1621
- const name = errObj?.name;
1622
- const code = errObj?.code;
1623
- const nonRetryable = policy.nonRetryableErrors ?? [];
1624
- if (nonRetryable.some((n) => n === name || n === code)) return "fail";
1625
- if (currentAttempts + 1 >= policy.attempts) return "fail";
1626
- return "retry";
1627
- }
1628
- function computeBackoff(policy, attempts) {
1629
- const base = Math.max(policy.baseMs, 0);
1630
- if (policy.backoff === "fixed") return base;
1631
- const exponent = Math.max(attempts - 1, 0);
1632
- if (exponent >= 53) return Number.MAX_SAFE_INTEGER;
1633
- const raw = base * Math.pow(2, exponent);
1634
- if (!Number.isFinite(raw) || raw >= Number.MAX_SAFE_INTEGER) {
1635
- return Number.MAX_SAFE_INTEGER;
1636
- }
1637
- return raw;
1638
- }
1639
- function serialiseError(err, attempt, retryable) {
1640
- const e = err;
1641
- return {
1642
- message: e?.message ?? String(err),
1643
- stack: e?.stack,
1644
- retryable,
1645
- attempt
1646
- };
1647
- }
1648
-
1649
- // runtime/subsystems/jobs/job-run-service.memory-backend.ts
1650
- import { Inject as Inject6, Injectable as Injectable6 } from "@nestjs/common";
1651
- var NON_TERMINAL_STATUSES2 = [
1652
- "pending",
1653
- "running",
1654
- "waiting"
1655
- ];
1656
- var MemoryJobRunService = class {
1657
- constructor(store, orchestrator, multiTenant) {
1658
- this.store = store;
1659
- this.orchestrator = orchestrator;
1660
- this.multiTenant = multiTenant;
1661
- }
1662
- store;
1663
- orchestrator;
1664
- multiTenant;
1665
- /**
1666
- * JOB-8 — produce a per-row predicate for the tenant gate.
1667
- * Returns `null` when multi-tenancy is off (caller doesn't check).
1668
- * Throws when on + `undefined`; matches `tenant_id IS NULL` on explicit
1669
- * `null` to support cross-tenant background work.
1670
- */
1671
- tenantPredicate(method, tenantId) {
1672
- if (!this.multiTenant) return null;
1673
- if (tenantId === void 0) throw new MissingTenantIdError(method);
1674
- return (r) => r.tenantId === tenantId;
1675
- }
1676
- async listForScope(entityType, entityId, opts = {}) {
1677
- const statusFilter = opts.status ? Array.isArray(opts.status) ? new Set(opts.status) : /* @__PURE__ */ new Set([opts.status]) : null;
1678
- const tenantCheck = this.tenantPredicate("listForScope", opts.tenantId);
1679
- const rows = [];
1680
- for (const r of this.store.runs.values()) {
1681
- if (r.scopeEntityType !== entityType) continue;
1682
- if (r.scopeEntityId !== entityId) continue;
1683
- if (statusFilter && !statusFilter.has(r.status)) continue;
1684
- if (opts.jobType && r.jobType !== opts.jobType) continue;
1685
- if (tenantCheck && !tenantCheck(r)) continue;
1686
- rows.push(r);
1687
- }
1688
- const orderBy = opts.orderBy ?? "created_at desc";
1689
- rows.sort((a, b) => compareBy(a, b, orderBy));
1690
- const offset = opts.offset ?? 0;
1691
- const limit = opts.limit;
1692
- const sliced = typeof limit === "number" ? rows.slice(offset, offset + limit) : rows.slice(offset);
1693
- return sliced;
1694
- }
1695
- async cancelForScope(entityType, entityId, opts = {}) {
1696
- const tenantCheck = this.tenantPredicate("cancelForScope", opts.tenantId);
1697
- const ids = [];
1698
- for (const r of this.store.runs.values()) {
1699
- if (r.scopeEntityType !== entityType) continue;
1700
- if (r.scopeEntityId !== entityId) continue;
1701
- if (!NON_TERMINAL_STATUSES2.includes(r.status)) continue;
1702
- if (tenantCheck && !tenantCheck(r)) continue;
1703
- ids.push(r.id);
1704
- }
1705
- for (const id of ids) {
1706
- await this.orchestrator.cancel(id, {
1707
- cascade: true,
1708
- tenantId: opts.tenantId
1709
- });
1710
- }
1711
- }
1712
- async rescheduleForScope(entityType, entityId, newRunAt, opts = {}) {
1713
- const tenantCheck = this.tenantPredicate("rescheduleForScope", opts.tenantId);
1714
- for (const r of this.store.runs.values()) {
1715
- if (r.scopeEntityType !== entityType) continue;
1716
- if (r.scopeEntityId !== entityId) continue;
1717
- if (r.status !== "pending") continue;
1718
- if (tenantCheck && !tenantCheck(r)) continue;
1719
- this.store.runs.set(r.id, {
1720
- ...r,
1721
- runAt: newRunAt,
1722
- updatedAt: /* @__PURE__ */ new Date()
1723
- });
1724
- }
1725
- }
1726
- async countByPoolAndStatus(tenantId) {
1727
- const tenantCheck = this.tenantPredicate("countByPoolAndStatus", tenantId);
1728
- const map = /* @__PURE__ */ new Map();
1729
- for (const r of this.store.runs.values()) {
1730
- if (tenantCheck && !tenantCheck(r)) continue;
1731
- const key2 = `${r.pool}\0${r.status}`;
1732
- const cur = map.get(key2);
1733
- if (cur) {
1734
- cur.count += 1;
1735
- } else {
1736
- map.set(key2, { pool: r.pool, status: r.status, count: 1 });
1737
- }
1738
- }
1739
- return Array.from(map.values());
1740
- }
1741
- async listRecentFailed(limit, tenantId) {
1742
- const tenantCheck = this.tenantPredicate("listRecentFailed", tenantId);
1743
- const failed = [];
1744
- for (const r of this.store.runs.values()) {
1745
- if (r.status !== "failed") continue;
1746
- if (tenantCheck && !tenantCheck(r)) continue;
1747
- failed.push(r);
1748
- }
1749
- failed.sort((a, b) => {
1750
- const at = (a.finishedAt ?? a.updatedAt).getTime();
1751
- const bt = (b.finishedAt ?? b.updatedAt).getTime();
1752
- return bt - at;
1753
- });
1754
- return failed.slice(0, limit).map((r) => ({
1755
- runId: r.id,
1756
- jobType: r.jobType,
1757
- pool: r.pool,
1758
- scopeEntityType: r.scopeEntityType,
1759
- scopeEntityId: r.scopeEntityId,
1760
- tenantId: r.tenantId,
1761
- attempts: r.attempts,
1762
- errorMessage: r.error?.message ?? null,
1763
- failedAt: r.finishedAt ?? r.updatedAt,
1764
- createdAt: r.createdAt
1765
- }));
1766
- }
1767
- async listJobRuns(query = {}) {
1768
- const limit = clampLimit(query.limit);
1769
- const tenantCheck = this.tenantPredicate("listJobRuns", query.tenantId);
1770
- const keyset = query.cursor ? decodeKeysetCursor(query.cursor) : null;
1771
- const matched = [];
1772
- for (const r of this.store.runs.values()) {
1773
- if (tenantCheck && !tenantCheck(r)) continue;
1774
- if (query.poolId && r.pool !== query.poolId) continue;
1775
- if (query.rootRunId && r.rootRunId !== query.rootRunId) continue;
1776
- if (query.status && r.status !== query.status) continue;
1777
- if (query.since && r.createdAt.getTime() < query.since.getTime()) continue;
1778
- matched.push(r);
1779
- }
1780
- matched.sort((a, b) => {
1781
- const dt = b.createdAt.getTime() - a.createdAt.getTime();
1782
- if (dt !== 0) return dt;
1783
- return a.id < b.id ? 1 : a.id > b.id ? -1 : 0;
1784
- });
1785
- const seeked = keyset ? matched.filter((r) => {
1786
- const ct = r.createdAt.getTime();
1787
- const kt = keyset.createdAt.getTime();
1788
- if (ct < kt) return true;
1789
- if (ct > kt) return false;
1790
- return r.id < keyset.id;
1791
- }) : matched;
1792
- const hasMore = seeked.length > limit;
1793
- const page = hasMore ? seeked.slice(0, limit) : seeked;
1794
- const items = page.map(toJobRunSummary);
1795
- const last = page[page.length - 1];
1796
- const nextCursor = hasMore && last ? encodeKeysetCursor({ createdAt: last.createdAt, id: last.id }) : null;
1797
- return { items, nextCursor };
1798
- }
1799
- /**
1800
- * Direct lookup. Not on the protocol — concrete-class convenience for
1801
- * tests. Matches `DrizzleJobRunService.findByRootRunId` in spirit; both
1802
- * are debug / test helpers that sidestep the orchestrator.
1803
- */
1804
- findById(runId) {
1805
- return this.store.runs.get(runId) ?? null;
1806
- }
1807
- /** Public counterpart to the Drizzle backend's `findByRootRunId` helper. */
1808
- findByRootRunId(rootRunId) {
1809
- const out = [];
1810
- for (const r of this.store.runs.values()) {
1811
- if (r.rootRunId === rootRunId) out.push(r);
1812
- }
1813
- return out;
1814
- }
1815
- };
1816
- MemoryJobRunService = __decorateClass([
1817
- Injectable6(),
1818
- __decorateParam(0, Inject6(MemoryJobStore)),
1819
- __decorateParam(1, Inject6(JOB_ORCHESTRATOR)),
1820
- __decorateParam(2, Inject6(JOBS_MULTI_TENANT))
1821
- ], MemoryJobRunService);
1822
- function compareBy(a, b, order) {
1823
- switch (order) {
1824
- case "created_at asc":
1825
- return a.createdAt.getTime() - b.createdAt.getTime();
1826
- case "run_at desc":
1827
- return b.runAt.getTime() - a.runAt.getTime();
1828
- case "run_at asc":
1829
- return a.runAt.getTime() - b.runAt.getTime();
1830
- case "created_at desc":
1831
- default:
1832
- return b.createdAt.getTime() - a.createdAt.getTime();
1833
- }
1834
- }
1835
-
1836
- // runtime/subsystems/jobs/pool-config.loader.ts
1837
- import { existsSync, readFileSync } from "fs";
1838
- import { resolve } from "path";
1839
- import { parse as parseYaml } from "yaml";
1840
- var FRAMEWORK_POOLS = Object.freeze({
1841
- events_inbound: Object.freeze({
1842
- queue: "jobs-events-inbound",
1843
- concurrency: 20,
1844
- reserved: true,
1845
- description: "Inbound events drain (events subsystem outbox)."
1846
- }),
1847
- events_change: Object.freeze({
1848
- queue: "jobs-events-change",
1849
- concurrency: 30,
1850
- reserved: true,
1851
- description: "Change events drain (events subsystem outbox)."
1852
- }),
1853
- events_outbound: Object.freeze({
1854
- queue: "jobs-events-outbound",
1855
- concurrency: 10,
1856
- reserved: true,
1857
- description: "Outbound events drain (events subsystem outbox)."
1858
- }),
1859
- interactive: Object.freeze({
1860
- queue: "jobs-interactive",
1861
- concurrency: 20,
1862
- reserved: false,
1863
- description: "User-facing latency-sensitive jobs."
1864
- }),
1865
- batch: Object.freeze({
1866
- queue: "jobs-batch",
1867
- concurrency: 5,
1868
- reserved: false,
1869
- description: "Default pool for background jobs."
1870
- })
1871
- });
1872
- var RESERVED_POOL_NAMES = new Set(
1873
- Object.entries(FRAMEWORK_POOLS).filter(([, def]) => def.reserved).map(([name]) => name)
1874
- );
1875
- var cache = /* @__PURE__ */ new Map();
1876
- function loadPoolConfig(configPath) {
1877
- const resolved = resolve(configPath ?? `${process.cwd()}/codegen.config.yaml`);
1878
- const cached = cache.get(resolved);
1879
- if (cached) return cached;
1880
- const merged = /* @__PURE__ */ new Map();
1881
- for (const [name, def] of Object.entries(FRAMEWORK_POOLS)) {
1882
- merged.set(name, { ...def });
1883
- }
1884
- if (!existsSync(resolved)) {
1885
- cache.set(resolved, merged);
1886
- return merged;
1887
- }
1888
- let raw;
1889
- try {
1890
- raw = parseYaml(readFileSync(resolved, "utf8"));
1891
- } catch (err) {
1892
- throw new Error(
1893
- `pool-config.loader: failed to parse YAML at ${resolved}: ${err.message}`
1894
- );
1895
- }
1896
- const userPools = extractUserPools(raw);
1897
- for (const [name, userDef] of Object.entries(userPools)) {
1898
- const existing = merged.get(name);
1899
- if (existing) {
1900
- const next = {
1901
- queue: existing.queue,
1902
- concurrency: typeof userDef.concurrency === "number" ? userDef.concurrency : existing.concurrency,
1903
- reserved: existing.reserved,
1904
- description: userDef.description ?? existing.description
1905
- };
1906
- merged.set(name, next);
1907
- continue;
1908
- }
1909
- if (typeof userDef.queue !== "string" || userDef.queue.length === 0) {
1910
- throw new Error(
1911
- `pool-config.loader: pool '${name}' must declare a non-empty 'queue'.`
1912
- );
1913
- }
1914
- if (typeof userDef.concurrency !== "number" || userDef.concurrency <= 0) {
1915
- throw new Error(
1916
- `pool-config.loader: pool '${name}' must declare a positive 'concurrency'.`
1917
- );
1918
- }
1919
- if (userDef.reserved === true) {
1920
- throw new Error(
1921
- `pool-config.loader: user-defined pool '${name}' cannot set 'reserved: true' \u2014 reserved is framework-only.`
1922
- );
1923
- }
1924
- merged.set(name, {
1925
- queue: userDef.queue,
1926
- concurrency: userDef.concurrency,
1927
- reserved: false,
1928
- description: userDef.description
1929
- });
1930
- }
1931
- cache.set(resolved, merged);
1932
- return merged;
1933
- }
1934
- function allNonReservedPoolNames(config) {
1935
- const out = [];
1936
- for (const [name, def] of config) {
1937
- if (!def.reserved) out.push(name);
1938
- }
1939
- return out;
1940
- }
1941
- function allPoolNames(config) {
1942
- return [...config.keys()];
1943
- }
1944
- function extractUserPools(raw) {
1945
- if (!raw || typeof raw !== "object") return {};
1946
- const jobs2 = raw.jobs;
1947
- if (!jobs2 || typeof jobs2 !== "object") return {};
1948
- const pools = jobs2.pools;
1949
- if (!pools || typeof pools !== "object") return {};
1950
- const out = {};
1951
- for (const [name, def] of Object.entries(pools)) {
1952
- if (!def || typeof def !== "object") continue;
1953
- out[name] = def;
1954
- }
1955
- return out;
1956
- }
1957
-
1958
- // runtime/subsystems/jobs/bullmq.config.ts
1959
- var BULLMQ_CONNECTION = Symbol.for(tokenKey("jobs", "bullmq-connection"));
1960
- var BULLMQ_RESOLVED_CONFIG = Symbol.for(tokenKey("jobs", "bullmq-resolved-config"));
1961
- var DEFAULT_REDIS_URL = "redis://localhost:6379";
1962
- var DEFAULT_BULL_BOARD_MOUNT = "/admin/queues";
1963
- function resolveBullMqConfig(ext) {
1964
- const url = ext?.redis_url ?? process.env.REDIS_URL ?? DEFAULT_REDIS_URL;
1965
- const resolved = {
1966
- connection: { url },
1967
- queuePrefix: ext?.queue_prefix
1968
- };
1969
- if (ext?.bull_board?.enabled) {
1970
- resolved.bullBoard = {
1971
- enabled: true,
1972
- mountPath: ext.bull_board.mount_path ?? DEFAULT_BULL_BOARD_MOUNT
1973
- };
1974
- }
1975
- return resolved;
1976
- }
1977
- function resolvePoolQueueName(pool, config, poolConfig = loadPoolConfig()) {
1978
- const alias = poolConfig.get(pool)?.queue ?? pool;
1979
- const prefix = config?.queuePrefix;
1980
- return prefix ? `${prefix}:${alias}` : alias;
1981
- }
1982
-
1983
- // runtime/subsystems/jobs/jobs-domain.module.ts
1984
- var JobsDomainModule = class {
1985
- static forRoot(opts) {
1986
- const multiTenant = opts.multiTenant ?? false;
1987
- const providers = [
1988
- // JOB-8 — boolean provider consumed by the four service-layer backends.
1989
- // Always provided (even when `multiTenant === false`) so `@Inject`
1990
- // always resolves; backends short-circuit the enforcement path when
1991
- // the value is `false`. See `jobs-domain.tokens.ts` for the claim-loop
1992
- // cross-tenant-by-design decision.
1993
- { provide: JOBS_MULTI_TENANT, useValue: multiTenant }
1994
- ];
1995
- if (opts.backend === "memory") {
1996
- const store = new MemoryJobStore();
1997
- providers.push({ provide: MemoryJobStore, useValue: store });
1998
- providers.push(MemoryJobStepService);
1999
- providers.push({ provide: JOB_STEP_SERVICE, useExisting: MemoryJobStepService });
2000
- providers.push(MemoryJobOrchestrator);
2001
- providers.push({ provide: JOB_ORCHESTRATOR, useExisting: MemoryJobOrchestrator });
2002
- providers.push(MemoryJobRunService);
2003
- providers.push({ provide: JOB_RUN_SERVICE, useExisting: MemoryJobRunService });
2004
- } else if (opts.backend === "bullmq") {
2005
- const resolved = resolveBullMqConfig(opts.extensions?.bullmq);
2006
- providers.push({ provide: BULLMQ_CONNECTION, useValue: resolved.connection });
2007
- providers.push({ provide: BULLMQ_RESOLVED_CONFIG, useValue: resolved });
2008
- providers.push({
2009
- provide: JOB_ORCHESTRATOR,
2010
- useFactory: async (...args) => {
2011
- const specifier = "./job-orchestrator.bullmq-backend";
2012
- const mod = await import(specifier);
2013
- return new mod.BullMQJobOrchestrator(...args);
2014
- },
2015
- // The bullmq orchestrator constructor mirrors DrizzleJobOrchestrator's
2016
- // injection list: DRIZZLE + JOBS_MULTI_TENANT + the resolved BullMQ
2017
- // tokens. Importing token references would force a static dep on the
2018
- // tokens file in this module's import graph; using the existing
2019
- // symbols already in scope is sufficient.
2020
- inject: [DRIZZLE, JOBS_MULTI_TENANT, BULLMQ_CONNECTION, BULLMQ_RESOLVED_CONFIG]
2021
- });
2022
- providers.push({ provide: JOB_RUN_SERVICE, useClass: DrizzleJobRunService });
2023
- providers.push({ provide: JOB_STEP_SERVICE, useClass: DrizzleJobStepService });
2024
- } else {
2025
- providers.push({ provide: JOB_ORCHESTRATOR, useClass: DrizzleJobOrchestrator });
2026
- providers.push({ provide: JOB_RUN_SERVICE, useClass: DrizzleJobRunService });
2027
- providers.push({ provide: JOB_STEP_SERVICE, useClass: DrizzleJobStepService });
2028
- }
2029
- const exports = [
2030
- JOB_ORCHESTRATOR,
2031
- JOB_RUN_SERVICE,
2032
- JOB_STEP_SERVICE,
2033
- JOBS_MULTI_TENANT
2034
- ];
2035
- if (opts.backend === "bullmq") {
2036
- exports.push(BULLMQ_CONNECTION, BULLMQ_RESOLVED_CONFIG);
2037
- }
2038
- return {
2039
- module: JobsDomainModule,
2040
- global: true,
2041
- providers,
2042
- exports
2043
- };
2044
- }
2045
- };
2046
- JobsDomainModule = __decorateClass([
2047
- Module({})
2048
- ], JobsDomainModule);
2049
-
2050
- // runtime/subsystems/jobs/job-worker.ts
2051
- import { Inject as Inject7, Injectable as Injectable7, Logger as Logger3 } from "@nestjs/common";
2052
- 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";
2053
- var JOB_WORKER_OPTIONS = Symbol.for(tokenKey("jobs", "worker-options"));
2054
- var DEFAULT_POLL_INTERVAL_MS = 1e3;
2055
- var DEFAULT_STALE_SWEEPER_INTERVAL_MS = 6e4;
2056
- var DEFAULT_STALE_THRESHOLD_MS = 5 * 6e4;
2057
- var DEFAULT_SHUTDOWN_TIMEOUT_MS = 3e4;
2058
- function computeBackoff2(policy, attempts) {
2059
- const base = Math.max(policy.baseMs, 0);
2060
- if (policy.backoff === "fixed") {
2061
- return base;
2062
- }
2063
- const exponent = Math.max(attempts - 1, 0);
2064
- if (exponent >= 53) return Number.MAX_SAFE_INTEGER;
2065
- const raw = base * Math.pow(2, exponent);
2066
- if (!Number.isFinite(raw) || raw >= Number.MAX_SAFE_INTEGER) {
2067
- return Number.MAX_SAFE_INTEGER;
2068
- }
2069
- return raw;
2070
- }
2071
- function classifyError2(err, policy, currentAttempts) {
2072
- if (!policy) return "fail";
2073
- const errObj = err;
2074
- const name = errObj?.name;
2075
- const code = errObj?.code;
2076
- const nonRetryable = policy.nonRetryableErrors ?? [];
2077
- if (nonRetryable.some((n) => n === name || n === code)) return "fail";
2078
- if (currentAttempts + 1 >= policy.attempts) return "fail";
2079
- return "retry";
2080
- }
2081
- function serialiseError2(err, attempt, retryable) {
2082
- const e = err;
2083
- return {
2084
- message: e?.message ?? String(err),
2085
- stack: e?.stack,
2086
- retryable,
2087
- attempt
2088
- };
2089
- }
2090
- var JobWorker = class {
2091
- constructor(db, orchestrator, runService, stepService, options, moduleRef) {
2092
- this.db = db;
2093
- this.orchestrator = orchestrator;
2094
- this.runService = runService;
2095
- this.stepService = stepService;
2096
- this.options = options;
2097
- this.moduleRef = moduleRef;
2098
- this.pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
2099
- this.staleSweeperIntervalMs = options.staleSweeperIntervalMs ?? DEFAULT_STALE_SWEEPER_INTERVAL_MS;
2100
- this.staleThresholdMs = options.staleThresholdMs ?? DEFAULT_STALE_THRESHOLD_MS;
2101
- this.shutdownTimeoutMs = options.shutdownTimeoutMs ?? DEFAULT_SHUTDOWN_TIMEOUT_MS;
2102
- this.sigtermHandler = () => {
2103
- if (this.sigtermHandled) return;
2104
- this.sigtermHandled = true;
2105
- void this.onModuleDestroy();
2106
- };
2107
- void this.runService;
2108
- }
2109
- db;
2110
- orchestrator;
2111
- runService;
2112
- stepService;
2113
- options;
2114
- moduleRef;
2115
- logger = new Logger3(JobWorker.name);
2116
- shuttingDown = false;
2117
- inFlight = /* @__PURE__ */ new Set();
2118
- pollTimer = null;
2119
- sweeperTimer = null;
2120
- sigtermHandled = false;
2121
- sigtermHandler;
2122
- pollIntervalMs;
2123
- staleSweeperIntervalMs;
2124
- staleThresholdMs;
2125
- shutdownTimeoutMs;
2126
- // ============================================================================
2127
- // Lifecycle
2128
- // ============================================================================
2129
- onModuleInit() {
2130
- this.pollTimer = setInterval(() => {
2131
- void this.pollAndProcess();
2132
- }, this.pollIntervalMs);
2133
- this.sweeperTimer = setInterval(() => {
2134
- void this.sweepStaleClaims();
2135
- }, this.staleSweeperIntervalMs);
2136
- process.on("SIGTERM", this.sigtermHandler);
2137
- }
2138
- async onModuleDestroy() {
2139
- if (this.shuttingDown) {
2140
- await this.drainInFlight();
2141
- return;
2142
- }
2143
- this.shuttingDown = true;
2144
- if (this.pollTimer) {
2145
- clearInterval(this.pollTimer);
2146
- this.pollTimer = null;
2147
- }
2148
- if (this.sweeperTimer) {
2149
- clearInterval(this.sweeperTimer);
2150
- this.sweeperTimer = null;
2151
- }
2152
- process.removeListener("SIGTERM", this.sigtermHandler);
2153
- await this.drainInFlight();
2154
- try {
2155
- await this.db.update(jobRuns).set({ status: "pending", claimedAt: null, startedAt: null }).where(
2156
- and4(eq4(jobRuns.status, "running"), eq4(jobRuns.pool, this.options.pool))
2157
- );
2158
- } catch (err) {
2159
- this.logger.error(`shutdown reset failed: ${err.message}`);
2160
- }
2161
- }
2162
- async drainInFlight() {
2163
- if (this.inFlight.size === 0) return;
2164
- const timeout = new Promise(
2165
- (resolve2) => setTimeout(resolve2, this.shutdownTimeoutMs)
2166
- );
2167
- await Promise.race([
2168
- Promise.allSettled([...this.inFlight]).then(() => void 0),
2169
- timeout
2170
- ]);
2171
- }
2172
- // ============================================================================
2173
- // Poll loop
2174
- // ============================================================================
2175
- async pollAndProcess() {
2176
- if (this.shuttingDown) return;
2177
- if (this.inFlight.size >= this.options.concurrency) return;
2178
- let claimed;
2179
- try {
2180
- claimed = await this.claimNext(this.options.pool);
2181
- } catch (err) {
2182
- this.logger.error(`claimNext failed: ${err.message}`);
2183
- return;
2184
- }
2185
- if (!claimed) return;
2186
- const run = claimed;
2187
- const promise = this.processRun(run).catch((err) => {
2188
- this.logger.error(
2189
- `processRun(${run.id}) unhandled: ${err.message}`
2190
- );
2191
- });
2192
- this.inFlight.add(promise);
2193
- promise.finally(() => {
2194
- this.inFlight.delete(promise);
2195
- });
2196
- }
2197
- /**
2198
- * Claim the next runnable row from the pool. Transaction ensures the
2199
- * select-candidate + update-to-running pair is atomic; FOR UPDATE SKIP
2200
- * LOCKED lets multiple workers share the table without serialising.
2201
- */
2202
- async claimNext(pool) {
2203
- return this.db.transaction(async (tx) => {
2204
- const candidates = await tx.select({ id: jobRuns.id }).from(jobRuns).where(
2205
- and4(
2206
- eq4(jobRuns.status, "pending"),
2207
- eq4(jobRuns.pool, pool),
2208
- lte(jobRuns.runAt, /* @__PURE__ */ new Date())
2209
- )
2210
- ).orderBy(desc3(jobRuns.priority), asc2(jobRuns.runAt)).limit(1).for("update", { skipLocked: true });
2211
- const candidate = candidates[0];
2212
- if (!candidate) return null;
2213
- const [claimed] = await tx.update(jobRuns).set({
2214
- status: "running",
2215
- claimedAt: /* @__PURE__ */ new Date(),
2216
- startedAt: /* @__PURE__ */ new Date(),
2217
- updatedAt: /* @__PURE__ */ new Date()
2218
- }).where(eq4(jobRuns.id, candidate.id)).returning();
2219
- return claimed ?? null;
2220
- });
2221
- }
2222
- // ============================================================================
2223
- // Stale claim sweeper
2224
- // ============================================================================
2225
- /**
2226
- * Release rows whose `claimed_at` is older than the threshold. Safe to
2227
- * run concurrently across workers — the two-phase tx (select-for-update
2228
- * then update) guarantees each stranded row is only reset once.
2229
- */
2230
- async sweepStaleClaims() {
2231
- if (this.shuttingDown) return;
2232
- try {
2233
- await this.db.transaction(async (tx) => {
2234
- const threshold = new Date(Date.now() - this.staleThresholdMs);
2235
- const stale = await tx.select({ id: jobRuns.id }).from(jobRuns).where(
2236
- and4(eq4(jobRuns.status, "running"), lt2(jobRuns.claimedAt, threshold))
2237
- ).for("update", { skipLocked: true });
2238
- if (stale.length === 0) return;
2239
- const ids = stale.map((r) => r.id);
2240
- await tx.update(jobRuns).set({ status: "pending", claimedAt: null, startedAt: null }).where(inArray3(jobRuns.id, ids));
2241
- for (const id of ids) {
2242
- this.logger.warn(`Recovered stale claim on run ${id}`);
2243
- }
2244
- });
2245
- } catch (err) {
2246
- this.logger.error(`sweepStaleClaims failed: ${err.message}`);
2247
- }
2248
- }
2249
- // ============================================================================
2250
- // processRun
2251
- // ============================================================================
2252
- async processRun(claimed) {
2253
- const registryEntry = JOB_HANDLER_REGISTRY.get(claimed.jobType);
2254
- if (!registryEntry) {
2255
- this.logger.error(
2256
- `No handler registered for jobType='${claimed.jobType}' (run ${claimed.id})`
2257
- );
2258
- await this.markFailed(
2259
- claimed,
2260
- new Error(`No handler registered for jobType='${claimed.jobType}'`),
2261
- /*finalAttempts*/
2262
- (claimed.attempts ?? 0) + 1
2263
- );
2264
- return;
2265
- }
2266
- if (claimed.concurrencyKey) {
2267
- const inflight = await this.db.select({ id: jobRuns.id }).from(jobRuns).where(
2268
- and4(
2269
- eq4(jobRuns.concurrencyKey, claimed.concurrencyKey),
2270
- eq4(jobRuns.status, "running")
2271
- )
2272
- );
2273
- const other = inflight.find((r) => r.id !== claimed.id);
2274
- if (other) {
2275
- await this.db.update(jobRuns).set({
2276
- status: "pending",
2277
- claimedAt: null,
2278
- startedAt: null,
2279
- updatedAt: /* @__PURE__ */ new Date()
2280
- }).where(eq4(jobRuns.id, claimed.id));
2281
- return;
2282
- }
2283
- }
2284
- const meta = registryEntry.meta;
2285
- const HandlerClass = registryEntry.handlerClass;
2286
- const handler = this.moduleRef.get(
2287
- HandlerClass,
2288
- { strict: false }
2289
- );
2290
- const ctx = {
2291
- input: claimed.input,
2292
- run: claimed,
2293
- step: this.makeStepFn(claimed),
2294
- spawnChild: this.makeSpawnFn(claimed),
2295
- logger: new Logger3(`JobRun:${claimed.id}`)
2296
- };
2297
- const attemptsBefore = claimed.attempts ?? 0;
2298
- try {
2299
- const output = await handler.run(ctx);
2300
- await this.db.update(jobRuns).set({
2301
- status: "completed",
2302
- output: output ?? {},
2303
- finishedAt: /* @__PURE__ */ new Date(),
2304
- updatedAt: /* @__PURE__ */ new Date(),
2305
- attempts: attemptsBefore + 1
2306
- }).where(eq4(jobRuns.id, claimed.id));
2307
- } catch (err) {
2308
- const policy = meta.retry;
2309
- const decision = classifyError2(err, policy, attemptsBefore);
2310
- const nextAttempts = attemptsBefore + 1;
2311
- if (decision === "retry" && policy) {
2312
- const delay = computeBackoff2(policy, nextAttempts);
2313
- await this.db.update(jobRuns).set({
2314
- status: "pending",
2315
- attempts: nextAttempts,
2316
- runAt: new Date(Date.now() + delay),
2317
- startedAt: null,
2318
- claimedAt: null,
2319
- error: serialiseError2(err, nextAttempts, true),
2320
- updatedAt: /* @__PURE__ */ new Date()
2321
- }).where(eq4(jobRuns.id, claimed.id));
2322
- } else {
2323
- await this.markFailed(claimed, err, nextAttempts);
2324
- }
2325
- }
2326
- }
2327
- async markFailed(claimed, err, finalAttempts) {
2328
- await this.db.update(jobRuns).set({
2329
- status: "failed",
2330
- attempts: finalAttempts,
2331
- finishedAt: /* @__PURE__ */ new Date(),
2332
- error: serialiseError2(err, finalAttempts, false),
2333
- updatedAt: /* @__PURE__ */ new Date()
2334
- }).where(eq4(jobRuns.id, claimed.id));
2335
- if (claimed.parentClosePolicy === "terminate") {
2336
- try {
2337
- await this.orchestrator.cancel(claimed.id, {
2338
- cascade: true,
2339
- reason: "parent-failed",
2340
- tenantId: claimed.tenantId
2341
- });
2342
- } catch (cascadeErr) {
2343
- this.logger.warn(
2344
- `cascade on failed run ${claimed.id}: ${cascadeErr.message}`
2345
- );
2346
- }
2347
- }
2348
- }
2349
- // ============================================================================
2350
- // ctx.step / ctx.spawnChild builders
2351
- // ============================================================================
2352
- makeStepFn(run) {
2353
- return async (stepId, fn, _opts) => {
2354
- void _opts;
2355
- const existing = await this.stepService.findStep(run.id, stepId);
2356
- if (existing?.status === "completed") {
2357
- return existing.output;
2358
- }
2359
- const seq = await this.nextStepSeq(run.id);
2360
- const startedAt = /* @__PURE__ */ new Date();
2361
- const nextAttempts = (existing?.attempts ?? 0) + 1;
2362
- await this.stepService.recordStep({
2363
- jobRunId: run.id,
2364
- stepId,
2365
- kind: "task",
2366
- seq,
2367
- status: "running",
2368
- startedAt,
2369
- attempts: nextAttempts
2370
- });
2371
- try {
2372
- const output = await fn();
2373
- await this.stepService.recordStep({
2374
- jobRunId: run.id,
2375
- stepId,
2376
- kind: "task",
2377
- seq,
2378
- status: "completed",
2379
- output,
2380
- finishedAt: /* @__PURE__ */ new Date(),
2381
- attempts: nextAttempts
2382
- });
2383
- return output;
2384
- } catch (err) {
2385
- await this.stepService.recordStep({
2386
- jobRunId: run.id,
2387
- stepId,
2388
- kind: "task",
2389
- seq,
2390
- status: "failed",
2391
- error: serialiseError2(err, nextAttempts, false),
2392
- finishedAt: /* @__PURE__ */ new Date(),
2393
- attempts: nextAttempts
2394
- });
2395
- throw err;
2396
- }
2397
- };
2398
- }
2399
- makeSpawnFn(run) {
2400
- return async (type, input, opts) => {
2401
- return this.orchestrator.start(type, input, {
2402
- parentRunId: run.id,
2403
- parentClosePolicy: opts?.closePolicy,
2404
- runAt: opts?.runAt,
2405
- priority: opts?.priority,
2406
- tags: opts?.tags,
2407
- triggerSource: "parent",
2408
- triggerRef: run.id
2409
- });
2410
- };
2411
- }
2412
- /**
2413
- * Allocate the next `seq` for a given run. SELECT-max approach — runs
2414
- * typically have <100 steps so the scan is cheap, and correctness across
2415
- * retries is more important than the microseconds saved by an in-memory
2416
- * counter (which would drift if the worker crashes mid-run and another
2417
- * worker resumes via stale-claim sweep).
2418
- */
2419
- async nextStepSeq(runId) {
2420
- const [row] = await this.db.execute(
2421
- sql4`SELECT COALESCE(MAX(seq), 0) + 1 AS next FROM job_step WHERE job_run_id = ${runId}`
2422
- );
2423
- const maybeRows = row?.rows;
2424
- if (Array.isArray(maybeRows) && maybeRows.length > 0) {
2425
- return Number(maybeRows[0].next ?? 1);
2426
- }
2427
- if (row && typeof row.next !== "undefined") {
2428
- return Number(row.next);
2429
- }
2430
- return 1;
2431
- }
2432
- // ============================================================================
2433
- // (suppress unused-import noise)
2434
- // ============================================================================
2435
- };
2436
- JobWorker = __decorateClass([
2437
- Injectable7(),
2438
- __decorateParam(0, Inject7(DRIZZLE)),
2439
- __decorateParam(1, Inject7(JOB_ORCHESTRATOR)),
2440
- __decorateParam(2, Inject7(JOB_RUN_SERVICE)),
2441
- __decorateParam(3, Inject7(JOB_STEP_SERVICE)),
2442
- __decorateParam(4, Inject7(JOB_WORKER_OPTIONS))
2443
- ], JobWorker);
2444
-
2445
- // runtime/subsystems/jobs/job-worker.module.ts
2446
- var DEFAULT_SHUTDOWN_TIMEOUT_MS2 = 3e4;
2447
- var JOB_WORKER_MODULE_OPTIONS = Symbol.for(tokenKey("jobs", "worker-module-options"));
2448
- var JobWorkerOrchestrator = class {
2449
- constructor(orchestrator, runService, stepService, options, db = null, moduleRef, bullConnection = null, bullConfig = null) {
2450
- this.orchestrator = orchestrator;
2451
- this.runService = runService;
2452
- this.stepService = stepService;
2453
- this.options = options;
2454
- this.db = db;
2455
- this.moduleRef = moduleRef;
2456
- this.bullConnection = bullConnection;
2457
- this.bullConfig = bullConfig;
2458
- }
2459
- orchestrator;
2460
- runService;
2461
- stepService;
2462
- options;
2463
- db;
2464
- moduleRef;
2465
- bullConnection;
2466
- bullConfig;
2467
- logger = new Logger4(JobWorkerOrchestrator.name);
2468
- workers = [];
2469
- // ============================================================================
2470
- // Lifecycle
2471
- // ============================================================================
2472
- async onModuleInit() {
2473
- const backend = this.options.backend ?? "drizzle";
2474
- const poolConfig = loadPoolConfig(this.options.configPath);
2475
- const entries = HandlerRegistry.getAll();
2476
- this.assertNoReservedPoolHandlers(entries, poolConfig);
2477
- const { orphaned } = await this.orchestrator.upsertJobRows(
2478
- entries,
2479
- poolConfig
2480
- );
2481
- if (backend !== "memory" && orphaned.length > 0) {
2482
- throw new BootValidationError(orphaned);
2483
- }
2484
- const activePools = this.options.pools ? this.options.pools : this.options.allPools ? allPoolNames(poolConfig) : allNonReservedPoolNames(poolConfig);
2485
- for (const poolName of activePools) {
2486
- const def = poolConfig.get(poolName);
2487
- if (!def) {
2488
- throw new Error(
2489
- `JobWorkerModule: active pool '${poolName}' is not defined in the resolved pool config. Configured pools: [${[...poolConfig.keys()].join(", ")}].`
2490
- );
2491
- }
2492
- const workerOptions = {
2493
- pool: poolName,
2494
- concurrency: def.concurrency,
2495
- shutdownTimeoutMs: this.options.shutdownTimeoutMs ?? DEFAULT_SHUTDOWN_TIMEOUT_MS2
2496
- };
2497
- const worker = this.options.workerFactory ? this.options.workerFactory(workerOptions) : backend === "bullmq" ? await this.spawnBullMQWorker(poolName, def.queue, def.concurrency, poolConfig) : this.spawnWorker(workerOptions);
2498
- await worker.onModuleInit();
2499
- this.workers.push(worker);
2500
- this.logger.log(
2501
- `JobWorker started: pool='${poolName}' (queue='${def.queue}') concurrency=${def.concurrency} backend='${backend}'`
2502
- );
2503
- }
2504
- }
2505
- async onModuleDestroy() {
2506
- for (let i = this.workers.length - 1; i >= 0; i--) {
2507
- const worker = this.workers[i];
2508
- if (!worker) continue;
2509
- try {
2510
- await worker.onModuleDestroy();
2511
- } catch (err) {
2512
- this.logger.error(
2513
- `JobWorker shutdown failed: ${err.message}`
2514
- );
2515
- }
2516
- }
2517
- this.workers.length = 0;
2518
- const orch = this.orchestrator;
2519
- if (typeof orch.closeConnections === "function") {
2520
- try {
2521
- await orch.closeConnections();
2522
- } catch (err) {
2523
- this.logger.error(
2524
- `BullMQ orchestrator connection close failed: ${err.message}`
2525
- );
2526
- }
2527
- }
2528
- }
2529
- // ============================================================================
2530
- // Internals
2531
- // ============================================================================
2532
- /**
2533
- * Walk every registered handler; collect any whose declared `pool`
2534
- * targets a reserved pool from the resolved config. If non-empty,
2535
- * throw `ReservedPoolViolationError` with the offender list so the
2536
- * operator sees every violating class on a single boot.
2537
- */
2538
- assertNoReservedPoolHandlers(entries, poolConfig) {
2539
- const offenders = [];
2540
- for (const entry of entries) {
2541
- if (entry.type.startsWith("@framework/")) continue;
2542
- const declaredPool = entry.meta.pool ?? "batch";
2543
- const def = poolConfig.get(declaredPool);
2544
- if (def?.reserved) {
2545
- offenders.push({
2546
- handlerClass: entry.handlerClass.name,
2547
- pool: declaredPool
2548
- });
2549
- }
2550
- }
2551
- if (offenders.length > 0) {
2552
- throw new ReservedPoolViolationError(offenders);
2553
- }
2554
- }
2555
- /**
2556
- * Production worker spawn. `JobWorker` requires `DRIZZLE` so this only
2557
- * succeeds when the module was booted with `backend: 'drizzle'`. Memory
2558
- * mode tests must supply `workerFactory` — the memory backend has no
2559
- * polling loop equivalent (`MemoryJobOrchestrator` is direct-invocation
2560
- * only).
2561
- *
2562
- * We instantiate outside the Nest container because the module spawns
2563
- * N workers from a single options shape, which doesn't fit Nest's
2564
- * "one provider per token" model. The dependencies are passed
2565
- * positionally; the constructor's `@Inject` decorators are unused on
2566
- * this path (Nest still uses them when `JobWorker` is a provider — e.g.
2567
- * in JOB-6's standalone `worker.ts` entrypoint).
2568
- */
2569
- spawnWorker(workerOptions) {
2570
- if (!this.db) {
2571
- throw new Error(
2572
- `JobWorkerModule: in-process worker spawning requires the Drizzle backend (no DRIZZLE provider available). Memory-mode tests must pass 'workerFactory' to inject a stub.`
2573
- );
2574
- }
2575
- if (!this.moduleRef) {
2576
- throw new Error(
2577
- `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).`
2578
- );
2579
- }
2580
- return new JobWorker(
2581
- this.db,
2582
- this.orchestrator,
2583
- this.runService,
2584
- this.stepService,
2585
- workerOptions,
2586
- this.moduleRef
2587
- );
2588
- }
2589
- /**
2590
- * BULLMQ-1 — spawn a per-pool `BullMQJobWorker`. Requires the Drizzle
2591
- * client (the worker drives `job_run` as the source of truth) AND the
2592
- * resolved BullMQ connection (bound by `JobsDomainModule` when
2593
- * `backend: 'bullmq'`). The queue name is derived identically to the
2594
- * orchestrator's `dispatch` via `resolvePoolQueueName(pool, …)` so producer
2595
- * and consumer agree.
2596
- */
2597
- /**
2598
- * #6 — async + dynamic-import. The `job-worker.bullmq-backend.ts` file is
2599
- * filtered out of the vendor set for drizzle/memory installs (no `bullmq`
2600
- * peer dep needed). The non-literal import specifier makes TS treat the
2601
- * module as `any` so the consumer's tsc never tries to resolve an absent
2602
- * file. This method is only entered when `backend === 'bullmq'` — at which
2603
- * point the file IS vendored.
2604
- */
2605
- async spawnBullMQWorker(pool, _queueAlias, concurrency, poolConfig) {
2606
- if (!this.db) {
2607
- throw new Error(
2608
- `JobWorkerModule: BullMQ worker spawning requires the Drizzle client (no DRIZZLE provider available) \u2014 job_run remains the source of truth.`
2609
- );
2610
- }
2611
- if (!this.bullConnection) {
2612
- throw new Error(
2613
- `JobWorkerModule: BullMQ worker spawning requires a resolved BULLMQ_CONNECTION. Ensure JobsDomainModule was booted with backend: 'bullmq'.`
2614
- );
2615
- }
2616
- if (!this.moduleRef) {
2617
- throw new Error(
2618
- `JobWorkerModule: ModuleRef not available \u2014 cannot construct BullMQJobWorker with handler DI support.`
2619
- );
2620
- }
2621
- const queueName = resolvePoolQueueName(pool, this.bullConfig, poolConfig);
2622
- const specifier = "./job-worker.bullmq-backend";
2623
- const mod = await import(specifier);
2624
- return new mod.BullMQJobWorker(
2625
- this.db,
2626
- this.orchestrator,
2627
- this.stepService,
2628
- {
2629
- pool,
2630
- queueName,
2631
- concurrency,
2632
- connection: this.bullConnection
2633
- },
2634
- this.moduleRef
2635
- );
2636
- }
2637
- };
2638
- JobWorkerOrchestrator = __decorateClass([
2639
- Injectable8(),
2640
- __decorateParam(0, Inject8(JOB_ORCHESTRATOR)),
2641
- __decorateParam(1, Inject8(JOB_RUN_SERVICE)),
2642
- __decorateParam(2, Inject8(JOB_STEP_SERVICE)),
2643
- __decorateParam(3, Inject8(JOB_WORKER_MODULE_OPTIONS)),
2644
- __decorateParam(4, Optional2()),
2645
- __decorateParam(4, Inject8(DRIZZLE)),
2646
- __decorateParam(5, Inject8(ModuleRef2)),
2647
- __decorateParam(6, Optional2()),
2648
- __decorateParam(6, Inject8(BULLMQ_CONNECTION)),
2649
- __decorateParam(7, Optional2()),
2650
- __decorateParam(7, Inject8(BULLMQ_RESOLVED_CONFIG))
2651
- ], JobWorkerOrchestrator);
2652
- var JobWorkerModule = class {
2653
- static forRoot(opts) {
2654
- return {
2655
- module: JobWorkerModule,
2656
- imports: [
2657
- JobsDomainModule.forRoot({
2658
- backend: opts.backend ?? "drizzle",
2659
- extensions: opts.domainModuleExtensions,
2660
- multiTenant: opts.multiTenant
2661
- })
2662
- ],
2663
- providers: [
2664
- { provide: JOB_WORKER_MODULE_OPTIONS, useValue: opts },
2665
- JobWorkerOrchestrator
2666
- ],
2667
- // BULLMQ-1 Phase 1 — export the options token so `BridgeModule`'s
2668
- // reserved-pool guard (`onModuleInit`) can actually inject it.
2669
- // Previously `exports: []` left the `@Optional()` inject resolving to
2670
- // `undefined` and the guard silently no-opped (a dead check). With the
2671
- // token exported the guard fires for real; consumers that omit the
2672
- // reserved pools (and don't set `allPools`) now fail fast with
2673
- // `BridgeReservedPoolsNotPolledError` — which is correct.
2674
- exports: [JOB_WORKER_MODULE_OPTIONS]
2675
- };
2676
- }
2677
- };
2678
- JobWorkerModule = __decorateClass([
2679
- Module2({})
2680
- ], JobWorkerModule);
2681
-
2682
- // runtime/subsystems/bridge/bridge.tokens.ts
2683
- var BRIDGE_DELIVERY_REPO = "BRIDGE_DELIVERY_REPO";
2684
- var EVENT_FLOW = "EVENT_FLOW";
2685
- var BRIDGE_MULTI_TENANT = "BRIDGE_MULTI_TENANT";
2686
- var BRIDGE_MODULE_OPTIONS = "BRIDGE_MODULE_OPTIONS";
2687
- var BRIDGE_REGISTRY = "BRIDGE_REGISTRY";
2688
- var BRIDGE_OUTBOX_DRAIN_HOOK = "BRIDGE_OUTBOX_DRAIN_HOOK";
2689
-
2690
- // runtime/subsystems/bridge/bridge-errors.ts
2691
- var MissingTenantIdError2 = class extends Error {
2692
- constructor(callSite) {
2693
- super(
2694
- `MissingTenantIdError: BridgeModule was configured with multiTenant=true but ${callSite} was called without tenantId (undefined). Pass an explicit tenantId, or pass null for cross-tenant work.`
2695
- );
2696
- this.callSite = callSite;
2697
- }
2698
- callSite;
2699
- name = "MissingTenantIdError";
2700
- };
2701
- var BridgeReservedPoolsNotPolledError = class extends Error {
2702
- constructor(missingPools) {
2703
- super(
2704
- `BridgeModule loaded but JobWorkerModule is not polling reserved pool '${missingPools[0]}'. Add ...BRIDGE_RESERVED_POOLS to your JobWorkerModule.forRoot({ pools }) configuration. Missing pools: ${missingPools.join(", ")}. (Bridge-fanout wrappers will sit pending forever without these pollers.)`
2705
- );
2706
- this.missingPools = missingPools;
2707
- }
2708
- missingPools;
2709
- name = "BridgeReservedPoolsNotPolledError";
2710
- };
2711
- var UniqueConstraintError = class extends Error {
2712
- constructor(constraint, eventId, triggerId) {
2713
- super(
2714
- `UniqueConstraintError: duplicate insert into bridge_delivery for (event_id='${eventId}', trigger_id='${triggerId}') \u2014 violates constraint '${constraint}'.`
2715
- );
2716
- this.constraint = constraint;
2717
- this.eventId = eventId;
2718
- this.triggerId = triggerId;
2719
- }
2720
- constraint;
2721
- eventId;
2722
- triggerId;
2723
- name = "UniqueConstraintError";
2724
- };
2725
-
2726
- // runtime/subsystems/bridge/bridge-delivery.memory-backend.ts
2727
- import { randomUUID as randomUUID4 } from "crypto";
2728
- var BRIDGE_DELIVERY_UNIQUE_CONSTRAINT = "uq_bridge_delivery_event_trigger";
2729
- function key(eventId, triggerId) {
2730
- return `${eventId}::${triggerId}`;
2731
- }
2732
- var MemoryBridgeDeliveryRepo = class {
2733
- deliveries = /* @__PURE__ */ new Map();
2734
- async insertDelivery(row) {
2735
- const k = key(row.eventId, row.triggerId);
2736
- if (this.deliveries.has(k)) {
2737
- throw new UniqueConstraintError(
2738
- BRIDGE_DELIVERY_UNIQUE_CONSTRAINT,
2739
- row.eventId,
2740
- row.triggerId
2741
- );
2742
- }
2743
- const record = {
2744
- id: row.id ?? randomUUID4(),
2745
- eventId: row.eventId,
2746
- triggerId: row.triggerId,
2747
- wrapperRunId: row.wrapperRunId ?? null,
2748
- userRunId: row.userRunId ?? null,
2749
- status: row.status ?? "pending",
2750
- skipReason: row.skipReason ?? null,
2751
- error: row.error ?? null,
2752
- tenantId: row.tenantId ?? null,
2753
- attemptedAt: row.attemptedAt instanceof Date ? row.attemptedAt : /* @__PURE__ */ new Date(),
2754
- deliveredAt: row.deliveredAt instanceof Date ? row.deliveredAt : null
2755
- };
2756
- this.deliveries.set(k, record);
2757
- }
2758
- async findDelivery(eventId, triggerId) {
2759
- return this.deliveries.get(key(eventId, triggerId)) ?? null;
2760
- }
2761
- async findDeliveryById(id) {
2762
- for (const record of this.deliveries.values()) {
2763
- if (record.id === id) return record;
2764
- }
2765
- return null;
2766
- }
2767
- async markDelivered(id, userRunId) {
2768
- const record = this.findById(id);
2769
- record.status = "delivered";
2770
- record.userRunId = userRunId;
2771
- record.deliveredAt = /* @__PURE__ */ new Date();
2772
- }
2773
- async markSkipped(id, reason) {
2774
- const record = this.findById(id);
2775
- record.status = "skipped";
2776
- record.skipReason = reason;
2777
- }
2778
- async markFailed(id, error) {
2779
- const record = this.findById(id);
2780
- record.status = "failed";
2781
- record.error = error;
2782
- }
2783
- /**
2784
- * Observability read — see `IJobBridge.getStatusHistogram` JSDoc for the
2785
- * tenant-filter and windowHours contract.
2786
- *
2787
- * Unlike `insertDelivery`, this read does NOT call `assertTenantId`:
2788
- * `tenantId === undefined` is the supported cross-tenant admin view.
2789
- */
2790
- async getStatusHistogram(windowHours, tenantId, nowMs = Date.now()) {
2791
- if (!Number.isFinite(windowHours) || windowHours <= 0) {
2792
- throw new RangeError("windowHours must be positive");
2793
- }
2794
- const cutoffMs = nowMs - windowHours * 36e5;
2795
- const histogram = {
2796
- pending: 0,
2797
- delivered: 0,
2798
- skipped: 0,
2799
- failed: 0
2800
- };
2801
- for (const record of this.deliveries.values()) {
2802
- if (record.attemptedAt.getTime() < cutoffMs) continue;
2803
- if (tenantId === null && record.tenantId !== null) continue;
2804
- if (typeof tenantId === "string" && record.tenantId !== tenantId) {
2805
- continue;
2806
- }
2807
- histogram[record.status] += 1;
2808
- }
2809
- return histogram;
2810
- }
2811
- // ─── Test helpers ────────────────────────────────────────────────────────
2812
- /** All deliveries for a given event (any status, declaration order). */
2813
- getDeliveriesForEvent(eventId) {
2814
- return [...this.deliveries.values()].filter((r) => r.eventId === eventId);
2815
- }
2816
- /** All deliveries currently in the given status. */
2817
- getByStatus(status) {
2818
- return [...this.deliveries.values()].filter((r) => r.status === status);
2819
- }
2820
- /** Reset the store. Tests use this in `beforeEach`. */
2821
- clear() {
2822
- this.deliveries.clear();
2823
- }
2824
- // ─── Internals ───────────────────────────────────────────────────────────
2825
- findById(id) {
2826
- for (const record of this.deliveries.values()) {
2827
- if (record.id === id) return record;
2828
- }
2829
- throw new Error(
2830
- `MemoryBridgeDeliveryRepo: no delivery with id '${id}' (transition methods may not be called for unknown rows; the framework handler should always findDelivery first or operate on a row it just inserted).`
2831
- );
2832
- }
2833
- };
2834
-
2835
- // runtime/subsystems/bridge/bridge-delivery.drizzle-backend.ts
2836
- import { Inject as Inject9, Injectable as Injectable9, Optional as Optional3 } from "@nestjs/common";
2837
- import { eq as eq5, and as and5, gte as gte2, isNull as isNull2, sql as sql7 } from "drizzle-orm";
2838
-
2839
- // runtime/subsystems/bridge/bridge-delivery.schema.ts
2840
- import {
2841
- index as index3,
2842
- jsonb as jsonb3,
2843
- pgEnum as pgEnum2,
2844
- pgTable as pgTable3,
2845
- text as text3,
2846
- timestamp as timestamp3,
2847
- unique,
2848
- uuid as uuid3
2849
- } from "drizzle-orm/pg-core";
2850
- import { sql as sql6 } from "drizzle-orm";
2851
-
2852
- // runtime/subsystems/events/domain-events.schema.ts
2853
1
  import {
2854
- check,
2855
- index as index2,
2856
- jsonb as jsonb2,
2857
- pgTable as pgTable2,
2858
- text as text2,
2859
- timestamp as timestamp2,
2860
- uuid as uuid2
2861
- } from "drizzle-orm/pg-core";
2862
- import { sql as sql5 } from "drizzle-orm";
2863
- var domainEvents = pgTable2(
2864
- "domain_events",
2865
- {
2866
- id: uuid2("id").primaryKey(),
2867
- type: text2("type").notNull(),
2868
- aggregateId: text2("aggregate_id").notNull(),
2869
- aggregateType: text2("aggregate_type").notNull(),
2870
- payload: jsonb2("payload").notNull().$type(),
2871
- occurredAt: timestamp2("occurred_at", { withTimezone: true }).notNull(),
2872
- processedAt: timestamp2("processed_at", { withTimezone: true }),
2873
- /** Lifecycle status: pending | processed | failed */
2874
- status: text2("status").notNull().default("pending"),
2875
- /** Error message from the last failed dispatch attempt. */
2876
- error: text2("error"),
2877
- metadata: jsonb2("metadata").$type(),
2878
- /** Routing pool (e.g. `events_inbound`, `events_change`, `events_outbound`). Populated by DrizzleEventBus.publish() in EVT-4. NULL when `tier='audit'`. */
2879
- pool: text2("pool"),
2880
- /** Routing direction: `inbound` | `change` | `outbound`. Populated by DrizzleEventBus.publish() in EVT-4. NULL when `tier='audit'`. */
2881
- direction: text2("direction"),
2882
- /**
2883
- * Event tier: `'domain'` (default) or `'audit'`. Audit-tier rows are
2884
- * observability-only and have null `pool`/`direction` by construction —
2885
- * enforced by the `domain_events_tier_routing_check` CHECK constraint
2886
- * declared below. (AUDIT-1)
2887
- */
2888
- tier: text2("tier").notNull().default("domain"),
2889
- // conditional: emitted only when events.multi_tenant: true
2890
- tenantId: text2("tenant_id")
2891
- },
2892
- (t) => ({
2893
- /** Polling drain filter (existing — promoted from comment to declaration in EVT-1). */
2894
- idxDomainEventsStatusOccurredAt: index2("idx_domain_events_status_occurred_at").on(
2895
- t.status,
2896
- t.occurredAt
2897
- ),
2898
- /** Event replay per aggregate (existing — promoted from comment to declaration in EVT-1). */
2899
- idxDomainEventsAggregate: index2("idx_domain_events_aggregate").on(
2900
- t.aggregateId,
2901
- t.aggregateType
2902
- ),
2903
- /** Per-pool drain filter (EVT-1). Enables DrizzleEventBus to drain a single pool without scanning all events. */
2904
- idxDomainEventsPoolStatusOccurredAt: index2(
2905
- "idx_domain_events_pool_status_occurred_at"
2906
- ).on(t.pool, t.status, t.occurredAt),
2907
- /** Per-tier filter (AUDIT-1). Backs the observability viewer's tier toggle. */
2908
- idxDomainEventsTierStatusOccurredAt: index2(
2909
- "idx_domain_events_tier_status_occurred_at"
2910
- ).on(t.tier, t.status, t.occurredAt),
2911
- /**
2912
- * Tier ↔ routing-fields invariant (AUDIT-1):
2913
- * - `tier` is one of `'domain' | 'audit'`.
2914
- * - `tier='audit'` ⇔ `pool IS NULL AND direction IS NULL`.
2915
- * - `tier='domain'` ⇒ `pool` and `direction` are populated (the
2916
- * DrizzleEventBus inserts always supply them; the bus stamps them
2917
- * in AUDIT-3).
2918
- */
2919
- tierRoutingCheck: check(
2920
- "domain_events_tier_routing_check",
2921
- sql5`${t.tier} in ('domain','audit') AND ((${t.tier} = 'audit') = (${t.pool} is null and ${t.direction} is null))`
2922
- )
2923
- })
2924
- );
2925
-
2926
- // runtime/subsystems/bridge/bridge-delivery.schema.ts
2927
- var bridgeDeliveryStatusEnum = pgEnum2("bridge_delivery_status", [
2928
- "pending",
2929
- "delivered",
2930
- "skipped",
2931
- "failed"
2932
- ]);
2933
- var bridgeDelivery = pgTable3(
2934
- "bridge_delivery",
2935
- {
2936
- id: uuid3("id").primaryKey().defaultRandom(),
2937
- /** FK to the source event in the outbox. */
2938
- eventId: uuid3("event_id").notNull().references(() => domainEvents.id),
2939
- /**
2940
- * Stable codegen-emitted identifier for the (job, trigger) pair, of the
2941
- * form `<job_type>#<triggerIndex>` (BRIDGE-6). Forms the second half of
2942
- * the UNIQUE idempotency key.
2943
- */
2944
- triggerId: text3("trigger_id").notNull(),
2945
- /**
2946
- * Wrapper `job_run.id` (the framework `@framework/bridge_delivery` run
2947
- * that drove this delivery). Nullable: the facade-eager path
2948
- * (`publishAndStart` Case B) pre-writes a delivered row with no wrapper.
2949
- */
2950
- wrapperRunId: uuid3("wrapper_run_id").references(() => jobRuns.id),
2951
- /**
2952
- * Spawned user `job_run.id`. Null until status is `delivered`; remains
2953
- * null for `skipped` and `failed` deliveries.
2954
- */
2955
- userRunId: uuid3("user_run_id").references(() => jobRuns.id),
2956
- status: bridgeDeliveryStatusEnum("status").notNull().default("pending"),
2957
- /** Populated when status=`skipped` (e.g. `'when_returned_false'`, `'trigger_unregistered'`). */
2958
- skipReason: text3("skip_reason"),
2959
- /** Populated when status=`failed`. Mirrors `job_run.error` shape. */
2960
- error: jsonb3("error").$type(),
2961
- /**
2962
- * Emitted unconditionally and nullable (JOB-8 / SYNC-6 precedent).
2963
- * Enforcement gated on `BRIDGE_MULTI_TENANT` at the service layer
2964
- * (BRIDGE-8); no DB constraint.
2965
- */
2966
- tenantId: text3("tenant_id"),
2967
- attemptedAt: timestamp3("attempted_at", { withTimezone: true }).notNull().defaultNow(),
2968
- deliveredAt: timestamp3("delivered_at", { withTimezone: true })
2969
- },
2970
- (t) => ({
2971
- /**
2972
- * Idempotency ledger. Outbox replays and facade-vs-drain collisions both
2973
- * dedup through this constraint.
2974
- */
2975
- uqBridgeDeliveryEventTrigger: unique("uq_bridge_delivery_event_trigger").on(
2976
- t.eventId,
2977
- t.triggerId
2978
- ),
2979
- /** Lookup all deliveries for an event (fanout report, debugging). */
2980
- idxBridgeDeliveryEvent: index3("idx_bridge_delivery_event").on(t.eventId),
2981
- /**
2982
- * Ops dashboard filter — only the actionable states. Partial index keeps
2983
- * it small at scale (the bulk of rows will be `delivered`).
2984
- */
2985
- idxBridgeDeliveryStatus: index3("idx_bridge_delivery_status").on(t.status).where(sql6`${t.status} IN ('pending','failed')`),
2986
- /**
2987
- * Reverse lookup from a spawned user run back to its delivery row.
2988
- * Partial — most rows in the bridge ledger but only successful
2989
- * deliveries have a `user_run_id`.
2990
- */
2991
- idxBridgeDeliveryUserRun: index3("idx_bridge_delivery_user_run").on(t.userRunId).where(sql6`${t.userRunId} IS NOT NULL`)
2992
- })
2993
- );
2994
-
2995
- // runtime/subsystems/bridge/assert-tenant-id.ts
2996
- function assertTenantId(site, multiTenant, tenantId) {
2997
- if (multiTenant && tenantId === void 0) {
2998
- throw new MissingTenantIdError2(site);
2999
- }
3000
- }
3001
-
3002
- // runtime/subsystems/bridge/bridge-delivery.drizzle-backend.ts
3003
- var DrizzleBridgeDeliveryRepo = class {
3004
- constructor(db, multiTenant = false) {
3005
- this.db = db;
3006
- this.multiTenant = multiTenant;
3007
- }
3008
- db;
3009
- multiTenant;
3010
- async insertDelivery(row, tx) {
3011
- assertTenantId(
3012
- "DrizzleBridgeDeliveryRepo.insertDelivery",
3013
- this.multiTenant,
3014
- row.tenantId
3015
- );
3016
- const client = tx ?? this.db;
3017
- await client.insert(bridgeDelivery).values(row).onConflictDoNothing({
3018
- target: [bridgeDelivery.eventId, bridgeDelivery.triggerId]
3019
- });
3020
- }
3021
- async findDelivery(eventId, triggerId) {
3022
- const rows = await this.db.select().from(bridgeDelivery).where(
3023
- and5(
3024
- eq5(bridgeDelivery.eventId, eventId),
3025
- eq5(bridgeDelivery.triggerId, triggerId)
3026
- )
3027
- ).limit(1);
3028
- return rows[0] ?? null;
3029
- }
3030
- async findDeliveryById(id) {
3031
- const rows = await this.db.select().from(bridgeDelivery).where(eq5(bridgeDelivery.id, id)).limit(1);
3032
- return rows[0] ?? null;
3033
- }
3034
- async markDelivered(id, userRunId, tx) {
3035
- const client = tx ?? this.db;
3036
- await client.update(bridgeDelivery).set({
3037
- status: "delivered",
3038
- userRunId,
3039
- deliveredAt: /* @__PURE__ */ new Date()
3040
- }).where(eq5(bridgeDelivery.id, id));
3041
- }
3042
- async markSkipped(id, reason, tx) {
3043
- const client = tx ?? this.db;
3044
- await client.update(bridgeDelivery).set({ status: "skipped", skipReason: reason }).where(eq5(bridgeDelivery.id, id));
3045
- }
3046
- async markFailed(id, error, tx) {
3047
- const client = tx ?? this.db;
3048
- await client.update(bridgeDelivery).set({ status: "failed", error }).where(eq5(bridgeDelivery.id, id));
3049
- }
3050
- /**
3051
- * Observability read — see `IJobBridge.getStatusHistogram` JSDoc for the
3052
- * tenant-filter and windowHours contract.
3053
- *
3054
- * Tenant-filter note: this method intentionally does NOT call
3055
- * `assertTenantId`. The write methods on this repo (`insertDelivery`)
3056
- * treat `tenantId === undefined` as a misconfiguration and fail fast.
3057
- * Reads are different — `undefined` is the supported "cross-tenant
3058
- * admin view" mode that OBS-5 uses to render a framework-wide health
3059
- * panel. Callers that need strict tenant scoping pass an explicit
3060
- * string or `null`.
3061
- *
3062
- * Cast note: `count(*)::int` is applied in SQL so the node-pg driver
3063
- * returns a `number` instead of the default `bigint → string` for
3064
- * `count(*)`. Don't relax this cast — consumers (and the protocol)
3065
- * type the result as `number`.
3066
- */
3067
- async getStatusHistogram(windowHours, tenantId) {
3068
- if (!Number.isFinite(windowHours) || windowHours <= 0) {
3069
- throw new RangeError("windowHours must be positive");
3070
- }
3071
- const cutoff = sql7`now() - make_interval(hours => ${windowHours})`;
3072
- const conditions = [gte2(bridgeDelivery.attemptedAt, cutoff)];
3073
- if (tenantId === null) {
3074
- conditions.push(isNull2(bridgeDelivery.tenantId));
3075
- } else if (typeof tenantId === "string") {
3076
- conditions.push(eq5(bridgeDelivery.tenantId, tenantId));
3077
- }
3078
- const rows = await this.db.select({
3079
- status: bridgeDelivery.status,
3080
- count: sql7`count(*)::int`
3081
- }).from(bridgeDelivery).where(and5(...conditions)).groupBy(bridgeDelivery.status);
3082
- const histogram = {
3083
- pending: 0,
3084
- delivered: 0,
3085
- skipped: 0,
3086
- failed: 0
3087
- };
3088
- for (const row of rows) {
3089
- histogram[row.status] = Number(row.count);
3090
- }
3091
- return histogram;
3092
- }
3093
- };
3094
- DrizzleBridgeDeliveryRepo = __decorateClass([
3095
- Injectable9(),
3096
- __decorateParam(0, Inject9(DRIZZLE)),
3097
- __decorateParam(1, Optional3()),
3098
- __decorateParam(1, Inject9(BRIDGE_MULTI_TENANT))
3099
- ], DrizzleBridgeDeliveryRepo);
3100
-
3101
- // runtime/subsystems/bridge/bridge-outbox-drain-hook.ts
3102
- import { Inject as Inject11, Injectable as Injectable11, Logger as Logger6, Optional as Optional5 } from "@nestjs/common";
3103
- import { randomUUID as randomUUID5 } from "crypto";
3104
-
3105
- // runtime/subsystems/bridge/bridge-delivery-handler.ts
3106
- import { Inject as Inject10, Injectable as Injectable10, Logger as Logger5, Optional as Optional4 } from "@nestjs/common";
3107
-
3108
- // runtime/subsystems/events/events.tokens.ts
3109
- var EVENT_BUS = "EVENT_BUS";
3110
- var REDIS_URL = Symbol.for(tokenKey("events", "redis-url"));
3111
-
3112
- // runtime/subsystems/bridge/bridge-delivery-handler.ts
3113
- var BRIDGE_DELIVERY_JOB_TYPE = "@framework/bridge_delivery";
3114
- var SPAWN_USER_RUN_STEP = "spawn_user_run";
3115
- var BridgeDeliveryHandler = class extends JobHandlerBase {
3116
- constructor(repo, orchestrator, events, registry, multiTenant = false) {
3117
- super();
3118
- this.repo = repo;
3119
- this.orchestrator = orchestrator;
3120
- this.events = events;
3121
- this.registry = registry;
3122
- this.multiTenant = multiTenant;
3123
- }
3124
- repo;
3125
- orchestrator;
3126
- events;
3127
- registry;
3128
- multiTenant;
3129
- classLogger = new Logger5(BridgeDeliveryHandler.name);
3130
- async run(ctx) {
3131
- const { deliveryId } = ctx.input;
3132
- const delivery = await this.repo.findDeliveryById(deliveryId);
3133
- if (!delivery) {
3134
- this.classLogger.warn(
3135
- `bridge_delivery row '${deliveryId}' not found; wrapper completes without spawning a user job.`
3136
- );
3137
- return { skipped: true, reason: "delivery_row_missing" };
3138
- }
3139
- assertTenantId(
3140
- "BridgeDeliveryHandler.run",
3141
- this.multiTenant,
3142
- delivery.tenantId
3143
- );
3144
- const event = await this.events.findById(delivery.eventId);
3145
- if (!event) {
3146
- this.classLogger.warn(
3147
- `domain_events row '${delivery.eventId}' missing for delivery '${deliveryId}'; marking skipped.`
3148
- );
3149
- await this.repo.markSkipped(delivery.id, "event_row_missing");
3150
- return { skipped: true, reason: "event_row_missing" };
3151
- }
3152
- const entry = this.findRegistryEntry(event.type, delivery.triggerId);
3153
- if (!entry) {
3154
- await this.repo.markSkipped(delivery.id, "trigger_unregistered");
3155
- return { skipped: true, reason: "trigger_unregistered" };
3156
- }
3157
- if (entry.when && !entry.when(event)) {
3158
- await this.repo.markSkipped(delivery.id, "predicate_false");
3159
- return { skipped: true, reason: "predicate_false" };
3160
- }
3161
- const input = entry.map(event);
3162
- const { runId } = await ctx.step(
3163
- SPAWN_USER_RUN_STEP,
3164
- async () => {
3165
- const run = await this.orchestrator.start(entry.jobType, input, {
3166
- parentRunId: ctx.run.id,
3167
- triggerSource: "event",
3168
- triggerRef: delivery.eventId,
3169
- tenantId: delivery.tenantId
3170
- });
3171
- return { runId: run.id };
3172
- }
3173
- );
3174
- await this.repo.markDelivered(delivery.id, runId);
3175
- return { runId };
3176
- }
3177
- /**
3178
- * Locate the registry entry for `(eventType, triggerId)`. Linear scan
3179
- * over the per-event-type array — N is the number of triggers declared
3180
- * for one event, typically 1–5; the table is not big enough to warrant
3181
- * a secondary index.
3182
- */
3183
- findRegistryEntry(eventType, triggerId) {
3184
- const candidates = this.registry[eventType] ?? void 0;
3185
- if (!candidates) return void 0;
3186
- return candidates.find((c) => c.triggerId === triggerId);
3187
- }
3188
- };
3189
- BridgeDeliveryHandler = __decorateClass([
3190
- Injectable10(),
3191
- JobHandler(BRIDGE_DELIVERY_JOB_TYPE, {
3192
- pool: "events_change",
3193
- retry: { attempts: 3, backoff: "exponential", baseMs: 250 },
3194
- replayFrom: "last_step"
3195
- }),
3196
- __decorateParam(0, Inject10(BRIDGE_DELIVERY_REPO)),
3197
- __decorateParam(1, Inject10(JOB_ORCHESTRATOR)),
3198
- __decorateParam(2, Inject10(EVENT_BUS)),
3199
- __decorateParam(3, Inject10(BRIDGE_REGISTRY)),
3200
- __decorateParam(4, Optional4()),
3201
- __decorateParam(4, Inject10(BRIDGE_MULTI_TENANT))
3202
- ], BridgeDeliveryHandler);
3203
-
3204
- // runtime/subsystems/bridge/bridge-outbox-drain-hook.ts
3205
- var POOL_BY_DIRECTION = {
3206
- inbound: "events_inbound",
3207
- change: "events_change",
3208
- outbound: "events_outbound"
3209
- };
3210
- var BridgeOutboxDrainHook = class {
3211
- constructor(registry = {}) {
3212
- this.registry = registry;
3213
- }
3214
- registry;
3215
- logger = new Logger6(BridgeOutboxDrainHook.name);
3216
- warnedNullDirection = false;
3217
- warnedAuditTypes = /* @__PURE__ */ new Set();
3218
- async processEvent(event, tx) {
3219
- if (event.metadata?.["tier"] === "audit") {
3220
- this.warnAuditBlockedOnce(event);
3221
- return {
3222
- delivered: 0,
3223
- dedupSkips: 0,
3224
- triggerCount: 0,
3225
- auditBlocked: 1
3226
- };
3227
- }
3228
- const triggers = this.lookupTriggers(event.type);
3229
- if (triggers.length === 0) {
3230
- return {
3231
- delivered: 0,
3232
- dedupSkips: 0,
3233
- triggerCount: 0,
3234
- auditBlocked: 0
3235
- };
3236
- }
3237
- const direction = event.metadata?.["direction"] ?? null;
3238
- const tenantId = event.metadata?.["tenantId"] ?? null;
3239
- const wrapperPool = direction ? POOL_BY_DIRECTION[direction] : void 0;
3240
- if (!wrapperPool) {
3241
- if (!this.warnedNullDirection) {
3242
- this.warnedNullDirection = true;
3243
- this.logger.warn(
3244
- `Skipping bridge fanout for events with null/unknown direction. event.id=${event.id} event.type=${event.type} direction=${String(direction)}. The wrapper pool is derived from direction (events_<direction>); publishers must use TypedEventBus.publish() so direction is stamped on the outbox row.`
3245
- );
3246
- }
3247
- return {
3248
- delivered: 0,
3249
- dedupSkips: 0,
3250
- triggerCount: triggers.length,
3251
- auditBlocked: 0
3252
- };
3253
- }
3254
- let delivered = 0;
3255
- let dedupSkips = 0;
3256
- const client = tx;
3257
- for (const trigger of triggers) {
3258
- const deliveryId = randomUUID5();
3259
- const wrapperRunId = randomUUID5();
3260
- const inserted = await tx.insert(bridgeDelivery).values({
3261
- id: deliveryId,
3262
- eventId: event.id,
3263
- triggerId: trigger.triggerId,
3264
- wrapperRunId,
3265
- status: "pending",
3266
- tenantId
3267
- }).onConflictDoNothing({
3268
- target: [bridgeDelivery.eventId, bridgeDelivery.triggerId]
3269
- }).returning({ id: bridgeDelivery.id });
3270
- if (inserted.length === 0) {
3271
- dedupSkips++;
3272
- continue;
3273
- }
3274
- await tx.insert(jobRuns).values({
3275
- id: wrapperRunId,
3276
- jobType: BRIDGE_DELIVERY_JOB_TYPE,
3277
- jobVersion: 1,
3278
- rootRunId: wrapperRunId,
3279
- pool: wrapperPool,
3280
- status: "pending",
3281
- input: { deliveryId },
3282
- triggerSource: "event",
3283
- triggerRef: event.id,
3284
- tenantId
3285
- });
3286
- delivered++;
3287
- }
3288
- return {
3289
- delivered,
3290
- dedupSkips,
3291
- triggerCount: triggers.length,
3292
- auditBlocked: 0
3293
- };
3294
- }
3295
- warnAuditBlockedOnce(event) {
3296
- if (this.warnedAuditTypes.has(event.type)) return;
3297
- this.warnedAuditTypes.add(event.type);
3298
- this.logger.warn(
3299
- `Bridge guard blocked audit-tier event '${event.type}' (event.id=${event.id}). Registry says this event is not bridge-eligible; a bridge_trigger row exists out-of-band. Investigate registry/runtime drift.`
3300
- );
3301
- }
3302
- lookupTriggers(eventType) {
3303
- const candidates = this.registry[eventType];
3304
- return candidates ?? [];
3305
- }
3306
- };
3307
- BridgeOutboxDrainHook = __decorateClass([
3308
- Injectable11(),
3309
- __decorateParam(0, Optional5()),
3310
- __decorateParam(0, Inject11(BRIDGE_REGISTRY))
3311
- ], BridgeOutboxDrainHook);
3312
-
3313
- // runtime/subsystems/bridge/event-flow.service.ts
3314
- import { Inject as Inject12, Injectable as Injectable12, Optional as Optional6 } from "@nestjs/common";
3315
- var EventFlowService = class {
3316
- constructor(db, eventBus, orchestrator, bridgeRepo, registry = {}, multiTenant = false) {
3317
- this.db = db;
3318
- this.eventBus = eventBus;
3319
- this.orchestrator = orchestrator;
3320
- this.bridgeRepo = bridgeRepo;
3321
- this.registry = registry;
3322
- this.multiTenant = multiTenant;
3323
- }
3324
- db;
3325
- eventBus;
3326
- orchestrator;
3327
- bridgeRepo;
3328
- registry;
3329
- multiTenant;
3330
- async publish(event, tx) {
3331
- await this.eventBus.publish(event, tx);
3332
- }
3333
- async publishAndStart(event, jobType, input, opts = {}) {
3334
- assertTenantId(
3335
- "EventFlowService.publishAndStart",
3336
- this.multiTenant,
3337
- opts.tenantId
3338
- );
3339
- const tenantId = opts.tenantId ?? null;
3340
- const matchingTriggers = this.matchingTriggers(event.type, jobType);
3341
- return this.db.transaction(async (tx) => {
3342
- await this.eventBus.publish(event, tx);
3343
- const run = await this.orchestrator.start(
3344
- jobType,
3345
- input,
3346
- {
3347
- parentRunId: opts.parentRunId,
3348
- tenantId,
3349
- triggerSource: "event",
3350
- triggerRef: event.id
3351
- },
3352
- tx
3353
- );
3354
- const now = /* @__PURE__ */ new Date();
3355
- for (const trigger of matchingTriggers) {
3356
- await this.bridgeRepo.insertDelivery(
3357
- {
3358
- eventId: event.id,
3359
- triggerId: trigger.triggerId,
3360
- wrapperRunId: null,
3361
- // facade never writes a wrapper
3362
- userRunId: run.id,
3363
- status: "delivered",
3364
- tenantId,
3365
- attemptedAt: now,
3366
- deliveredAt: now
3367
- },
3368
- tx
3369
- );
3370
- }
3371
- return { runId: run.id };
3372
- });
3373
- }
3374
- /**
3375
- * Linear scan of the per-event-type trigger list for entries whose
3376
- * `jobType` matches. Typical N is 1–5; the table is not big enough to
3377
- * warrant a secondary index. Returns an empty array for Case A.
3378
- */
3379
- matchingTriggers(eventType, jobType) {
3380
- const triggers = this.registry[eventType] ?? [];
3381
- return triggers.filter((t) => t.jobType === jobType);
3382
- }
3383
- };
3384
- EventFlowService = __decorateClass([
3385
- Injectable12(),
3386
- __decorateParam(0, Inject12(DRIZZLE)),
3387
- __decorateParam(1, Inject12(EVENT_BUS)),
3388
- __decorateParam(2, Inject12(JOB_ORCHESTRATOR)),
3389
- __decorateParam(3, Inject12(BRIDGE_DELIVERY_REPO)),
3390
- __decorateParam(4, Optional6()),
3391
- __decorateParam(4, Inject12(BRIDGE_REGISTRY)),
3392
- __decorateParam(5, Optional6()),
3393
- __decorateParam(5, Inject12(BRIDGE_MULTI_TENANT))
3394
- ], EventFlowService);
3395
-
3396
- // runtime/subsystems/bridge/generated/registry.ts
3397
- var bridgeRegistry = {};
3398
-
3399
- // runtime/subsystems/bridge/reserved-pools.ts
3400
- var BRIDGE_RESERVED_POOLS = [
3401
- "events_inbound",
3402
- "events_change",
3403
- "events_outbound"
3404
- ];
3405
-
3406
- // runtime/subsystems/bridge/bridge.module.ts
3407
- var BridgeModule = class {
3408
- /**
3409
- * `JOB_WORKER_MODULE_OPTIONS` is declared `@Optional()` so unit tests
3410
- * that mount `BridgeModule` alone (no `JobWorkerModule`) boot
3411
- * cleanly — the boot-time check skips when the token is undefined.
3412
- */
3413
- constructor(workerOpts) {
3414
- this.workerOpts = workerOpts;
3415
- }
3416
- workerOpts;
3417
- static forRoot(opts) {
3418
- const repoProvider = opts.backend === "memory" ? { provide: BRIDGE_DELIVERY_REPO, useClass: MemoryBridgeDeliveryRepo } : { provide: BRIDGE_DELIVERY_REPO, useClass: DrizzleBridgeDeliveryRepo };
3419
- return {
3420
- module: BridgeModule,
3421
- global: true,
3422
- // BridgeModule consumes EVENT_BUS / JOB_ORCHESTRATOR / DRIZZLE
3423
- // from sibling subsystems via DI; no `imports` needed here. The
3424
- // consumer is responsible for wiring EventsModule + JobsDomainModule
3425
- // (or JobWorkerModule, which transitively imports the latter)
3426
- // BEFORE BridgeModule.
3427
- providers: [
3428
- { provide: BRIDGE_MODULE_OPTIONS, useValue: opts },
3429
- { provide: BRIDGE_MULTI_TENANT, useValue: opts.multiTenant ?? false },
3430
- // Package mode threads the consumer's generated registry through
3431
- // `opts.registry`; vendored mode omits it and we fall back to the
3432
- // bundled `./generated/registry` (which IS the consumer's generated
3433
- // file in a vendored tree). See `BridgeModuleOptions.registry`.
3434
- { provide: BRIDGE_REGISTRY, useValue: opts.registry ?? bridgeRegistry },
3435
- repoProvider,
3436
- // Drain hook — always wired; `DrizzleEventBus` consumes it via
3437
- // `@Optional()`, so non-bridge mounts simply see `undefined`.
3438
- { provide: BRIDGE_OUTBOX_DRAIN_HOOK, useClass: BridgeOutboxDrainHook },
3439
- // Facade — class provider + token alias.
3440
- EventFlowService,
3441
- { provide: EVENT_FLOW, useExisting: EventFlowService },
3442
- // Framework handler — provider so DI can construct it. The
3443
- // `@JobHandler` decorator already auto-registers it in
3444
- // `JOB_HANDLER_REGISTRY` at module-load time, and its `jobs`
3445
- // row is upserted at `JobWorkerModule.onModuleInit`. We just
3446
- // need the class instantiated as a Nest provider so its DI
3447
- // deps (BRIDGE_DELIVERY_REPO, JOB_ORCHESTRATOR, EVENT_BUS,
3448
- // BRIDGE_REGISTRY, BRIDGE_MULTI_TENANT) resolve.
3449
- BridgeDeliveryHandler
3450
- ],
3451
- exports: [
3452
- EVENT_FLOW,
3453
- BRIDGE_DELIVERY_REPO,
3454
- BRIDGE_REGISTRY,
3455
- BRIDGE_MULTI_TENANT,
3456
- BRIDGE_MODULE_OPTIONS,
3457
- BRIDGE_OUTBOX_DRAIN_HOOK
3458
- ]
3459
- };
3460
- }
3461
- async onModuleInit() {
3462
- if (!this.workerOpts) return;
3463
- if (this.workerOpts.allPools) return;
3464
- const activePools = this.workerOpts.pools ?? [];
3465
- const missing = BRIDGE_RESERVED_POOLS.filter(
3466
- (p) => !activePools.includes(p)
3467
- );
3468
- if (missing.length > 0) {
3469
- throw new BridgeReservedPoolsNotPolledError(missing);
3470
- }
3471
- }
3472
- };
3473
- BridgeModule = __decorateClass([
3474
- Module3({}),
3475
- __decorateParam(0, Optional7()),
3476
- __decorateParam(0, Inject13(JOB_WORKER_MODULE_OPTIONS))
3477
- ], BridgeModule);
2
+ BridgeModule
3
+ } from "../../../chunk-OZZJDRGW.js";
4
+ import "../../../chunk-5A432NZJ.js";
5
+ import "../../../chunk-L7BNNRGI.js";
6
+ import "../../../chunk-32BMMV4H.js";
7
+ import "../../../chunk-EDKJU5BO.js";
8
+ import "../../../chunk-YTN6BKWA.js";
9
+ import "../../../chunk-K2I6XIK5.js";
10
+ import "../../../chunk-6DWFJNIK.js";
11
+ import "../../../chunk-4DOJBQTP.js";
12
+ import "../../../chunk-2TVVBC53.js";
13
+ import "../../../chunk-NXXDZ6ZF.js";
14
+ import "../../../chunk-WPXNN6QS.js";
15
+ import "../../../chunk-RC23QROE.js";
16
+ import "../../../chunk-KMZCQASO.js";
17
+ import "../../../chunk-I6MG4M3F.js";
18
+ import "../../../chunk-JRVNVKN6.js";
19
+ import "../../../chunk-DV4RV2DC.js";
20
+ import "../../../chunk-5Y7W3XR6.js";
21
+ import "../../../chunk-4RFHUZXU.js";
22
+ import "../../../chunk-PNZSGAB2.js";
23
+ import "../../../chunk-SNQ3TOWP.js";
24
+ import "../../../chunk-T4BIIU5E.js";
25
+ import "../../../chunk-L3LZWWSX.js";
26
+ import "../../../chunk-I6MVCB5A.js";
27
+ import "../../../chunk-RHVN6NA7.js";
28
+ import "../../../chunk-CO6LUM72.js";
29
+ import "../../../chunk-BIO6F7YI.js";
30
+ import "../../../chunk-H5NH7KPE.js";
31
+ import "../../../chunk-4LH67P4U.js";
32
+ import "../../../chunk-OKXZ63IA.js";
33
+ import "../../../chunk-OFRRBC7M.js";
34
+ import "../../../chunk-GYGNEQSC.js";
35
+ import "../../../chunk-U64T4YZE.js";
36
+ import "../../../chunk-2E224ZSN.js";
3478
37
  export {
3479
38
  BridgeModule
3480
39
  };