gemi 0.219.0 → 0.220.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (220) hide show
  1. package/dist/ai/index.js +2 -2
  2. package/dist/ai/index.js.map +1 -1
  3. package/dist/ai/testing/index.js +2 -2
  4. package/dist/ai/testing/index.js.map +1 -1
  5. package/dist/app/index.js +1 -1
  6. package/dist/bun/plugin.js +1 -1
  7. package/dist/bun/preload.js +1 -1
  8. package/dist/{chunk-xyv3y476.js → chunk-0av1gyns.js} +3 -3
  9. package/dist/{chunk-xyv3y476.js.map → chunk-0av1gyns.js.map} +1 -1
  10. package/dist/{chunk-yxtfg4wy.js → chunk-0k2r6bep.js} +2 -2
  11. package/dist/{chunk-yxtfg4wy.js.map → chunk-0k2r6bep.js.map} +1 -1
  12. package/dist/chunk-169e9dg7.js +517 -0
  13. package/dist/chunk-169e9dg7.js.map +25 -0
  14. package/dist/{chunk-xp5mmgfp.js → chunk-2vv04thj.js} +2 -2
  15. package/dist/{chunk-xp5mmgfp.js.map → chunk-2vv04thj.js.map} +1 -1
  16. package/dist/{chunk-kt174y9e.js → chunk-2y0nr525.js} +3 -3
  17. package/dist/{chunk-kt174y9e.js.map → chunk-2y0nr525.js.map} +1 -1
  18. package/dist/{chunk-aes0ecnp.js → chunk-37209psn.js} +3 -3
  19. package/dist/{chunk-aes0ecnp.js.map → chunk-37209psn.js.map} +1 -1
  20. package/dist/{chunk-yedb5vvg.js → chunk-3dkv4989.js} +2 -2
  21. package/dist/{chunk-5gp49wph.js.map → chunk-3dkv4989.js.map} +1 -1
  22. package/dist/{chunk-5wh3cw2x.js → chunk-3y91vexx.js} +3 -3
  23. package/dist/{chunk-5wh3cw2x.js.map → chunk-3y91vexx.js.map} +1 -1
  24. package/dist/{chunk-cmyt2txd.js → chunk-4v5nwqw6.js} +3 -3
  25. package/dist/{chunk-cmyt2txd.js.map → chunk-4v5nwqw6.js.map} +1 -1
  26. package/dist/{chunk-v0sgcy87.js → chunk-4wh4dfgf.js} +1 -1
  27. package/dist/{chunk-1nw9jhpt.js → chunk-50791bmz.js} +2 -2
  28. package/dist/{chunk-1nw9jhpt.js.map → chunk-50791bmz.js.map} +1 -1
  29. package/dist/{chunk-rp2f9mq1.js → chunk-55btq9c7.js} +2 -2
  30. package/dist/{chunk-rp2f9mq1.js.map → chunk-55btq9c7.js.map} +1 -1
  31. package/dist/{chunk-w3ks9nz7.js → chunk-5h2xj3cx.js} +2 -2
  32. package/dist/{chunk-w3ks9nz7.js.map → chunk-5h2xj3cx.js.map} +1 -1
  33. package/dist/{chunk-at6zjajz.js → chunk-5jvbr0e5.js} +2 -2
  34. package/dist/{chunk-at6zjajz.js.map → chunk-5jvbr0e5.js.map} +1 -1
  35. package/dist/{chunk-hmtn7996.js → chunk-5mrtgr7q.js} +2 -2
  36. package/dist/{chunk-hmtn7996.js.map → chunk-5mrtgr7q.js.map} +1 -1
  37. package/dist/{chunk-2vktfp1f.js → chunk-6d67a1d4.js} +2 -2
  38. package/dist/{chunk-2vktfp1f.js.map → chunk-6d67a1d4.js.map} +1 -1
  39. package/dist/{chunk-q0d45r2j.js → chunk-6r7956dh.js} +2 -2
  40. package/dist/{chunk-q0d45r2j.js.map → chunk-6r7956dh.js.map} +1 -1
  41. package/dist/{chunk-ee7xb9qr.js → chunk-6ttbhhnn.js} +1 -1
  42. package/dist/{chunk-w85wrer7.js → chunk-726gd69z.js} +2 -2
  43. package/dist/{chunk-w85wrer7.js.map → chunk-726gd69z.js.map} +1 -1
  44. package/dist/{chunk-dgna0e7g.js → chunk-79wjkaa4.js} +2 -2
  45. package/dist/{chunk-dgna0e7g.js.map → chunk-79wjkaa4.js.map} +1 -1
  46. package/dist/{chunk-c250kpcm.js → chunk-7etvj6w2.js} +2 -2
  47. package/dist/{chunk-c250kpcm.js.map → chunk-7etvj6w2.js.map} +1 -1
  48. package/dist/{chunk-yv3y3r9q.js → chunk-7sjzgme6.js} +4 -4
  49. package/dist/{chunk-yv3y3r9q.js.map → chunk-7sjzgme6.js.map} +1 -1
  50. package/dist/chunk-89egc0h3.js +5 -0
  51. package/dist/{chunk-4g24ffv8.js.map → chunk-89egc0h3.js.map} +1 -1
  52. package/dist/{chunk-4k3r37be.js → chunk-8a3fqcf0.js} +2 -2
  53. package/dist/{chunk-4k3r37be.js.map → chunk-8a3fqcf0.js.map} +1 -1
  54. package/dist/{chunk-3r7z4kc0.js → chunk-8ddt5fa2.js} +2 -2
  55. package/dist/{chunk-3r7z4kc0.js.map → chunk-8ddt5fa2.js.map} +1 -1
  56. package/dist/{chunk-4kkb85z8.js → chunk-8gnbc9dg.js} +3 -3
  57. package/dist/{chunk-4kkb85z8.js.map → chunk-8gnbc9dg.js.map} +1 -1
  58. package/dist/{chunk-66re5qsr.js → chunk-8nctfg18.js} +2 -2
  59. package/dist/{chunk-66re5qsr.js.map → chunk-8nctfg18.js.map} +1 -1
  60. package/dist/{chunk-17agj0r3.js → chunk-8vpe54ek.js} +2 -2
  61. package/dist/{chunk-17agj0r3.js.map → chunk-8vpe54ek.js.map} +1 -1
  62. package/dist/{chunk-9c8e4nkz.js → chunk-97tj0d7v.js} +2 -2
  63. package/dist/{chunk-9c8e4nkz.js.map → chunk-97tj0d7v.js.map} +1 -1
  64. package/dist/{chunk-w9a3b4vs.js → chunk-9yascc81.js} +2 -2
  65. package/dist/{chunk-w9a3b4vs.js.map → chunk-9yascc81.js.map} +1 -1
  66. package/dist/{chunk-9pvxexh1.js → chunk-adw279ge.js} +2 -2
  67. package/dist/{chunk-9pvxexh1.js.map → chunk-adw279ge.js.map} +1 -1
  68. package/dist/{chunk-w4aw44zg.js → chunk-anc5v266.js} +2 -2
  69. package/dist/{chunk-w4aw44zg.js.map → chunk-anc5v266.js.map} +1 -1
  70. package/dist/{chunk-6b7z5h54.js → chunk-ax042w6k.js} +2 -2
  71. package/dist/{chunk-6b7z5h54.js.map → chunk-ax042w6k.js.map} +1 -1
  72. package/dist/{chunk-59p034g3.js → chunk-b87wvmsz.js} +2 -2
  73. package/dist/{chunk-59p034g3.js.map → chunk-b87wvmsz.js.map} +1 -1
  74. package/dist/{chunk-xn7azkgd.js → chunk-bqm79ar0.js} +3 -3
  75. package/dist/{chunk-xn7azkgd.js.map → chunk-bqm79ar0.js.map} +1 -1
  76. package/dist/{chunk-5gp49wph.js → chunk-cf8bztwq.js} +2 -2
  77. package/dist/{chunk-yedb5vvg.js.map → chunk-cf8bztwq.js.map} +1 -1
  78. package/dist/{chunk-kggwk7hz.js → chunk-dj0nvj66.js} +1 -1
  79. package/dist/{chunk-xf3wke41.js → chunk-e4zxacxd.js} +2 -2
  80. package/dist/{chunk-xf3wke41.js.map → chunk-e4zxacxd.js.map} +1 -1
  81. package/dist/{chunk-b8tmmpcf.js → chunk-fp9yn4k8.js} +2 -2
  82. package/dist/{chunk-b8tmmpcf.js.map → chunk-fp9yn4k8.js.map} +1 -1
  83. package/dist/{chunk-sba3s380.js → chunk-fqhkkpq3.js} +2 -2
  84. package/dist/{chunk-sba3s380.js.map → chunk-fqhkkpq3.js.map} +1 -1
  85. package/dist/{chunk-nhebjh6n.js → chunk-fxa72ppw.js} +1 -1
  86. package/dist/{chunk-w9sw2kn7.js → chunk-gyszenps.js} +3 -3
  87. package/dist/{chunk-w9sw2kn7.js.map → chunk-gyszenps.js.map} +1 -1
  88. package/dist/{chunk-y12m6w7b.js → chunk-h1wmpa03.js} +2 -2
  89. package/dist/{chunk-y12m6w7b.js.map → chunk-h1wmpa03.js.map} +1 -1
  90. package/dist/{chunk-5vdkqv17.js → chunk-h9nt7hm6.js} +2 -2
  91. package/dist/{chunk-5vdkqv17.js.map → chunk-h9nt7hm6.js.map} +1 -1
  92. package/dist/{chunk-nrv7hdeh.js → chunk-j9abwrkv.js} +3 -3
  93. package/dist/{chunk-nrv7hdeh.js.map → chunk-j9abwrkv.js.map} +1 -1
  94. package/dist/{chunk-m68cxnbv.js → chunk-jf2dr481.js} +2 -2
  95. package/dist/{chunk-m68cxnbv.js.map → chunk-jf2dr481.js.map} +1 -1
  96. package/dist/{chunk-h6knw9f0.js → chunk-k16phdjv.js} +1 -1
  97. package/dist/{chunk-vewxnk3g.js → chunk-k6af7qek.js} +2 -2
  98. package/dist/{chunk-vewxnk3g.js.map → chunk-k6af7qek.js.map} +1 -1
  99. package/dist/{chunk-xm6hfksv.js → chunk-kp7wcpx7.js} +2 -2
  100. package/dist/{chunk-xm6hfksv.js.map → chunk-kp7wcpx7.js.map} +1 -1
  101. package/dist/{chunk-d6056zme.js → chunk-mt82209n.js} +2 -2
  102. package/dist/{chunk-d6056zme.js.map → chunk-mt82209n.js.map} +1 -1
  103. package/dist/{chunk-vawqmdh4.js → chunk-ncnygh0s.js} +2 -2
  104. package/dist/{chunk-vawqmdh4.js.map → chunk-ncnygh0s.js.map} +1 -1
  105. package/dist/{chunk-g178aect.js → chunk-nqgeny8m.js} +4 -4
  106. package/dist/{chunk-g178aect.js.map → chunk-nqgeny8m.js.map} +1 -1
  107. package/dist/{chunk-zy6hj5cc.js → chunk-nqqyn3cx.js} +2 -2
  108. package/dist/{chunk-zy6hj5cc.js.map → chunk-nqqyn3cx.js.map} +1 -1
  109. package/dist/{chunk-ppdfwnqw.js → chunk-nzd7z4s6.js} +1 -1
  110. package/dist/{chunk-s4sx97fn.js → chunk-p4v71qfx.js} +3 -3
  111. package/dist/{chunk-s4sx97fn.js.map → chunk-p4v71qfx.js.map} +1 -1
  112. package/dist/{chunk-vck02shp.js → chunk-ps5rpy9n.js} +2 -2
  113. package/dist/{chunk-vck02shp.js.map → chunk-ps5rpy9n.js.map} +1 -1
  114. package/dist/{chunk-gt6eq1p2.js → chunk-pxjkxhf9.js} +3 -3
  115. package/dist/{chunk-gt6eq1p2.js.map → chunk-pxjkxhf9.js.map} +1 -1
  116. package/dist/{chunk-r90djdx6.js → chunk-pxjptskr.js} +2 -2
  117. package/dist/{chunk-r90djdx6.js.map → chunk-pxjptskr.js.map} +1 -1
  118. package/dist/{chunk-6ncn8rdn.js → chunk-q5xcjm5z.js} +2 -2
  119. package/dist/{chunk-6ncn8rdn.js.map → chunk-q5xcjm5z.js.map} +1 -1
  120. package/dist/{chunk-0egjv6cj.js → chunk-qs2xvc8g.js} +2 -2
  121. package/dist/{chunk-0egjv6cj.js.map → chunk-qs2xvc8g.js.map} +1 -1
  122. package/dist/{chunk-6my6c6b1.js → chunk-qy0k2s5f.js} +2 -2
  123. package/dist/{chunk-6my6c6b1.js.map → chunk-qy0k2s5f.js.map} +1 -1
  124. package/dist/{chunk-jzqywxpj.js → chunk-rat2827k.js} +2 -2
  125. package/dist/{chunk-jzqywxpj.js.map → chunk-rat2827k.js.map} +1 -1
  126. package/dist/{chunk-ykshxc5k.js → chunk-s3gn68dy.js} +2 -2
  127. package/dist/{chunk-ykshxc5k.js.map → chunk-s3gn68dy.js.map} +1 -1
  128. package/dist/{chunk-8524ejgk.js → chunk-sfrjkysf.js} +2 -2
  129. package/dist/{chunk-8524ejgk.js.map → chunk-sfrjkysf.js.map} +1 -1
  130. package/dist/{chunk-cw50n89n.js → chunk-snmyjq03.js} +2 -2
  131. package/dist/{chunk-cw50n89n.js.map → chunk-snmyjq03.js.map} +1 -1
  132. package/dist/{chunk-cwm5x7rf.js → chunk-swmf6w3z.js} +2 -2
  133. package/dist/{chunk-cwm5x7rf.js.map → chunk-swmf6w3z.js.map} +1 -1
  134. package/dist/{chunk-xvf1hcxg.js → chunk-t0ke72e9.js} +2 -2
  135. package/dist/{chunk-xvf1hcxg.js.map → chunk-t0ke72e9.js.map} +1 -1
  136. package/dist/{chunk-gf3m0866.js → chunk-t586p2g2.js} +2 -2
  137. package/dist/{chunk-gf3m0866.js.map → chunk-t586p2g2.js.map} +1 -1
  138. package/dist/{chunk-zyvmbqcx.js → chunk-t8ygf6zj.js} +3 -3
  139. package/dist/{chunk-zyvmbqcx.js.map → chunk-t8ygf6zj.js.map} +1 -1
  140. package/dist/{chunk-ak85ee4e.js → chunk-tac25cnj.js} +3 -3
  141. package/dist/{chunk-ak85ee4e.js.map → chunk-tac25cnj.js.map} +1 -1
  142. package/dist/{chunk-p4b5hmr8.js → chunk-vcw98sp6.js} +3 -3
  143. package/dist/{chunk-p4b5hmr8.js.map → chunk-vcw98sp6.js.map} +1 -1
  144. package/dist/{chunk-jfpwjqvq.js → chunk-vcy1y0ta.js} +2 -2
  145. package/dist/{chunk-jfpwjqvq.js.map → chunk-vcy1y0ta.js.map} +1 -1
  146. package/dist/{chunk-fhb00fjx.js → chunk-vmmjq9fn.js} +2 -2
  147. package/dist/{chunk-fhb00fjx.js.map → chunk-vmmjq9fn.js.map} +1 -1
  148. package/dist/{chunk-prc4bcgp.js → chunk-wt4ekzp9.js} +2 -2
  149. package/dist/{chunk-prc4bcgp.js.map → chunk-wt4ekzp9.js.map} +1 -1
  150. package/dist/{chunk-xrkr2yzz.js → chunk-wy82t7mz.js} +2 -2
  151. package/dist/{chunk-xrkr2yzz.js.map → chunk-wy82t7mz.js.map} +1 -1
  152. package/dist/{chunk-g5drp5xx.js → chunk-x3pbssy4.js} +2 -2
  153. package/dist/{chunk-g5drp5xx.js.map → chunk-x3pbssy4.js.map} +1 -1
  154. package/dist/{chunk-71r1x773.js → chunk-xjgfmefy.js} +2 -2
  155. package/dist/{chunk-71r1x773.js.map → chunk-xjgfmefy.js.map} +1 -1
  156. package/dist/{chunk-qstjm3cb.js → chunk-yj7pbbnm.js} +2 -2
  157. package/dist/{chunk-qstjm3cb.js.map → chunk-yj7pbbnm.js.map} +1 -1
  158. package/dist/{chunk-qa528feb.js → chunk-zmt5kdpb.js} +2 -2
  159. package/dist/{chunk-qa528feb.js.map → chunk-zmt5kdpb.js.map} +1 -1
  160. package/dist/config/index.js +1 -1
  161. package/dist/console/run.js +2 -2
  162. package/dist/console/run.js.map +1 -1
  163. package/dist/container/index.js +2 -2
  164. package/dist/container/index.js.map +1 -1
  165. package/dist/database/index.js +2 -2
  166. package/dist/database/index.js.map +1 -1
  167. package/dist/email/index.js +2 -2
  168. package/dist/email/index.js.map +1 -1
  169. package/dist/facades/index.js +2 -2
  170. package/dist/facades/index.js.map +1 -1
  171. package/dist/foundation/index.js +2 -2
  172. package/dist/foundation/index.js.map +1 -1
  173. package/dist/http/index.js +2 -2
  174. package/dist/http/index.js.map +1 -1
  175. package/dist/i18n/dictionaryRuntime.js +2 -2
  176. package/dist/i18n/dictionaryRuntime.js.map +1 -1
  177. package/dist/i18n/index.js +2 -2
  178. package/dist/i18n/index.js.map +1 -1
  179. package/dist/kernel/index.js +2 -2
  180. package/dist/kernel/index.js.map +1 -1
  181. package/dist/orm/index.js +2 -2
  182. package/dist/orm/index.js.map +1 -1
  183. package/dist/probe/index.js +2 -2
  184. package/dist/probe/index.js.map +1 -1
  185. package/dist/server/index.js +2 -2
  186. package/dist/server/index.js.map +1 -1
  187. package/dist/services/index.d.ts +2 -1
  188. package/dist/services/index.d.ts.map +1 -1
  189. package/dist/services/index.js +3 -3
  190. package/dist/services/index.js.map +2 -2
  191. package/dist/services/queue/DatabaseQueueDriver.d.ts +8 -1
  192. package/dist/services/queue/DatabaseQueueDriver.d.ts.map +1 -1
  193. package/dist/services/queue/work.js +2 -2
  194. package/dist/services/queue/work.js.map +1 -1
  195. package/dist/services/queue/workflow/DatabaseWorkflowStore.d.ts +21 -0
  196. package/dist/services/queue/workflow/DatabaseWorkflowStore.d.ts.map +1 -1
  197. package/dist/services/queue/workflow/ItemSource.d.ts +68 -0
  198. package/dist/services/queue/workflow/ItemSource.d.ts.map +1 -0
  199. package/dist/services/queue/workflow/MemoryWorkflowStore.d.ts +12 -0
  200. package/dist/services/queue/workflow/MemoryWorkflowStore.d.ts.map +1 -1
  201. package/dist/services/queue/workflow/Step.d.ts +28 -1
  202. package/dist/services/queue/workflow/Step.d.ts.map +1 -1
  203. package/dist/services/queue/workflow/WorkflowRuntime.d.ts.map +1 -1
  204. package/dist/services/queue/workflow/WorkflowStore.d.ts +23 -1
  205. package/dist/services/queue/workflow/WorkflowStore.d.ts.map +1 -1
  206. package/dist/services/queue/workflow/workflowContract.d.ts.map +1 -1
  207. package/dist/stats/route-table.js +1 -1
  208. package/dist/support/index.js +2 -2
  209. package/dist/support/index.js.map +1 -1
  210. package/dist/vitest/index.js +1 -1
  211. package/package.json +1 -1
  212. package/dist/chunk-4g24ffv8.js +0 -5
  213. package/dist/chunk-pnt0c59g.js +0 -484
  214. package/dist/chunk-pnt0c59g.js.map +0 -24
  215. /package/dist/{chunk-v0sgcy87.js.map → chunk-4wh4dfgf.js.map} +0 -0
  216. /package/dist/{chunk-ee7xb9qr.js.map → chunk-6ttbhhnn.js.map} +0 -0
  217. /package/dist/{chunk-kggwk7hz.js.map → chunk-dj0nvj66.js.map} +0 -0
  218. /package/dist/{chunk-nhebjh6n.js.map → chunk-fxa72ppw.js.map} +0 -0
  219. /package/dist/{chunk-h6knw9f0.js.map → chunk-k16phdjv.js.map} +0 -0
  220. /package/dist/{chunk-ppdfwnqw.js.map → chunk-nzd7z4s6.js.map} +0 -0
@@ -1,484 +0,0 @@
1
- // @bun
2
- import{Lk as n,Mk as Q0,Ok as Kz,_k as D0}from"./chunk-ak85ee4e.js";import{al as Uz}from"./chunk-yxtfg4wy.js";import{cl as r0,dl as t0,el as p0,gl as y,hl as Nz,jl as $0,sl as w0}from"./chunk-xyv3y476.js";import{Ll as q0}from"./chunk-qa528feb.js";import{gm as Pz,jm as G0}from"./chunk-aes0ecnp.js";import{sm as N0}from"./chunk-q0d45r2j.js";class Z0{table;sql;dialect;connection;busyTimeout;configured;constructor(z,Z={}){let $=Z.table??"gemi_locks";if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test($))throw Error(`The lock table name "${$}" is not a plain identifier. Use letters, digits and underscores.`);this.table=$,this.sql=z.sql,this.dialect=z.dialect,this.connection=z.name,this.busyTimeout=Z.busyTimeout??1000}async createTable(){await this.configure();for(let z of _z(this.dialect,this.table))await this.sql.unsafe(z)}async acquire(z,Z,$){await this.configure();let V=this.sql,X=this.now(V);if(await this.seed(V,z),this.mysql){let G=await V`
3
- UPDATE ${this.name(V)}
4
- SET owner = ${Z}, token = token + 1, expires_at = ${X} + ${this.ms(V,$)},
5
- updated_at = ${X}
6
- WHERE name = ${z} AND expires_at <= ${X}
7
- `;if(p(G)===0)return null;let[Q]=await V`
8
- SELECT token FROM ${this.name(V)} WHERE name = ${z} AND owner = ${Z}
9
- `;return Q?Number(Q.token):null}let Y=await V`
10
- UPDATE ${this.name(V)}
11
- SET owner = ${Z}, token = token + 1, expires_at = ${X} + ${this.ms(V,$)},
12
- updated_at = ${X}
13
- WHERE name = ${z} AND expires_at <= ${X}
14
- RETURNING token
15
- `;return Y[0]?Number(Y[0].token):null}async extend(z,Z,$,V){await this.configure();let X=this.sql,Y=this.now(X),G=await X`
16
- UPDATE ${this.name(X)}
17
- SET expires_at = ${Y} + ${this.ms(X,V)}, updated_at = ${Y}
18
- WHERE name = ${z} AND owner = ${Z} AND token = ${$} AND expires_at > ${Y}
19
- `;if(p(G)>0)return!0;return this.mysql?this.held(z,Z,$):!1}async release(z,Z,$){await this.configure();let V=this.sql,X=this.now(V),Y=$===void 0?V`1 = 1`:V`token = ${$}`,G=await V`
20
- UPDATE ${this.name(V)}
21
- SET owner = '', expires_at = 0, updated_at = ${X}
22
- WHERE name = ${z} AND owner = ${Z} AND ${Y} AND expires_at > ${X}
23
- `;return p(G)>0}async holder(z){await this.configure();let Z=this.sql,[$]=await Z`
24
- SELECT owner, token FROM ${this.name(Z)}
25
- WHERE name = ${z} AND expires_at > ${this.now(Z)}
26
- `;return $?{owner:String($.owner),token:Number($.token)}:null}async held(z,Z,$){await this.configure();let V=this.sql;return(await V`
27
- SELECT 1 AS held FROM ${this.name(V)}
28
- WHERE name = ${z} AND owner = ${Z} AND token = ${$} AND expires_at > ${this.now(V)}
29
- `).length>0}async advance(z,Z){await this.configure();let $=this.sql;await this.seed($,z);let V=await $`
30
- UPDATE ${this.name($)}
31
- SET token = ${this.int($,Z)}, updated_at = ${this.now($)}
32
- WHERE name = ${z} AND token < ${this.int($,Z)}
33
- `;return p(V)>0}async fence(z,Z,$,V){await this.configure();let X=async(G)=>{let Q=this.now(G),J;if(this.dialect==="sqlite"){let B=await G`
34
- UPDATE ${this.name(G)} SET updated_at = ${Q}
35
- WHERE name = ${z} AND owner = ${Z} AND token = ${$} AND expires_at > ${Q}
36
- `;J=p(B)>0}else J=(await G`
37
- SELECT 1 AS held FROM ${this.name(G)}
38
- WHERE name = ${z} AND owner = ${Z} AND token = ${$} AND expires_at > ${Q}
39
- FOR UPDATE
40
- `).length>0;if(!J)throw new Q0(z,$);return V()},Y=this.connection;if(Y===void 0)return await this.sql.begin((G)=>X(G));return w0(this.sql,(G)=>p0(Y,()=>X(G)),{connection:Y})}async hit(z,Z,$){await this.configure();let V=this.sql,X=this.now(V);await this.seed(V,z);let Y=this.ms(V,Math.max(1,$)),G=await V`
41
- UPDATE ${this.name(V)}
42
- SET token = CASE WHEN expires_at <= ${X} THEN 1 ELSE token + 1 END,
43
- expires_at = CASE WHEN expires_at <= ${X} THEN ${X} + ${Y} ELSE expires_at END,
44
- updated_at = ${X}
45
- WHERE name = ${z} AND (expires_at <= ${X} OR token < ${this.int(V,Z)})
46
- `,Q=p(G)>0,[J]=await V`
47
- SELECT expires_at - ${X} AS reset FROM ${this.name(V)} WHERE name = ${z}
48
- `;return{allowed:Q,resetInMs:Math.max(0,Number(J?.reset??0))}}async refund(z){await this.configure();let Z=this.sql,$=this.now(Z);await Z`
49
- UPDATE ${this.name(Z)} SET token = token - 1, updated_at = ${$}
50
- WHERE name = ${z} AND token > 0 AND expires_at > ${$}
51
- `}async prune(z){await this.configure();let Z=this.sql,$=this.now(Z),V=await Z`
52
- DELETE FROM ${this.name(Z)}
53
- WHERE expires_at <= ${$} AND updated_at <= ${$} - ${this.ms(Z,z)}
54
- `;return p(V)}async seed(z,Z){let $=this.now(z);if(this.mysql){await z`
55
- INSERT IGNORE INTO ${this.name(z)} (name, owner, token, expires_at, updated_at)
56
- VALUES (${Z}, '', 0, 0, ${$})
57
- `;return}await z`
58
- INSERT INTO ${this.name(z)} (name, owner, token, expires_at, updated_at)
59
- VALUES (${Z}, '', 0, 0, ${$})
60
- ON CONFLICT (name) DO NOTHING
61
- `}get mysql(){return this.dialect==="mysql"||this.dialect==="mariadb"}configure(){if(this.dialect!=="sqlite"||this.busyTimeout===0)return Promise.resolve();return this.configured??=(async()=>{let[z]=await this.sql.unsafe("PRAGMA busy_timeout");if(Number(z?.timeout??0)!==0)return;await this.sql.unsafe(`PRAGMA busy_timeout = ${this.busyTimeout}`)})().catch((z)=>{throw this.configured=void 0,z}),this.configured}name(z){return z.unsafe(this.mysql?`\`${this.table}\``:`"${this.table}"`)}now(z){switch(this.dialect){case"postgres":return z`floor(extract(epoch from statement_timestamp()) * 1000)::bigint`;case"mysql":case"mariadb":return z`(TIMESTAMPDIFF(MICROSECOND, '1970-01-01 00:00:00', UTC_TIMESTAMP(6)) DIV 1000)`;case"sqlite":return z`CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER)`}}ms(z,Z){return this.int(z,Math.max(0,Math.round(Z)))}int(z,Z){let $=Math.round(Z);return this.mysql?z`CAST(${$} AS SIGNED)`:z`CAST(${$} AS BIGINT)`}}function p(z){let Z=z;return Math.max(Number(Z.count??0),Number(Z.affectedRows??0))}function _z(z,Z){if(z==="mysql"||z==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${Z}\` (
62
- \`name\` VARCHAR(191) NOT NULL,
63
- \`owner\` VARCHAR(191) NOT NULL,
64
- \`token\` BIGINT NOT NULL DEFAULT 0,
65
- \`expires_at\` BIGINT NOT NULL,
66
- \`updated_at\` BIGINT NOT NULL,
67
-
68
- PRIMARY KEY (\`name\`)
69
- ) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci`];let $=z==="sqlite"?'"name" TEXT NOT NULL PRIMARY KEY,':'"name" TEXT NOT NULL,',V=z==="sqlite"?"":`,
70
-
71
- CONSTRAINT "${Z}_pkey" PRIMARY KEY ("name")`;return[`CREATE TABLE IF NOT EXISTS "${Z}" (
72
- ${$}
73
- "owner" TEXT NOT NULL,
74
- "token" BIGINT NOT NULL DEFAULT 0,
75
- "expires_at" BIGINT NOT NULL,
76
- "updated_at" BIGINT NOT NULL${V}
77
- )`]}class J0{entries=new Map;counters=new Map;async acquire(z,Z,$){let V=Date.now(),X=this.entries.get(z);if(X&&(X.expiresAt>V||X.fences>0))return null;let Y=(X?.token??0)+1;return this.entries.set(z,{owner:Z,token:Y,expiresAt:V+Math.max(0,$),fences:0}),Y}async extend(z,Z,$,V){let X=this.current(z,Z,$);if(!X)return!1;return X.expiresAt=Date.now()+Math.max(0,V),!0}async release(z,Z,$){let V=this.current(z,Z,$);if(!V)return!1;return V.owner="",V.expiresAt=0,!0}async holder(z){let Z=this.entries.get(z);if(!Z||Z.expiresAt<=Date.now())return null;return{owner:Z.owner,token:Z.token}}async held(z,Z,$){return this.current(z,Z,$)!==void 0}async advance(z,Z){if((this.counters.get(z)??-1/0)>=Z)return!1;return this.counters.set(z,Z),!0}async fence(z,Z,$,V){let X=this.current(z,Z,$);if(!X)throw new Q0(z,$);X.fences++;try{return await V()}finally{X.fences--}}windows=new Map;async hit(z,Z,$){let V=Date.now(),X=this.windows.get(z);if(!X||X.endsAt<=V)X={count:0,endsAt:V+Math.max(1,$)},this.windows.set(z,X);if(X.count>=Z)return{allowed:!1,resetInMs:X.endsAt-V};return X.count++,{allowed:!0,resetInMs:X.endsAt-V}}async refund(z){let Z=this.windows.get(z);if(Z&&Z.endsAt>Date.now()&&Z.count>0)Z.count--}current(z,Z,$){let V=this.entries.get(z);if(!V||V.owner!==Z||V.expiresAt<=Date.now())return;if($!==void 0&&V.token!==$)return;return V}}var q="gemi.WorkflowTick",W0=262144;function B0(z,Z){let $=(V)=>V.slice(0,V.lastIndexOf(":"));return $(z)===$(Z)}class I extends Error{constructor(z){super(`The tick running workflow ${z} lost its hold on it (another tick took it over after its lease ran out), so its writes were refused.`);this.name="WorkflowLeaseLostError"}}var Lz=["completed","failed","cancelled"];class C0{db;table;stepTable;itemTable;constructor(z,Z){this.db=z;this.table=Z.table,this.stepTable=Z.stepTable,this.itemTable=Z.itemTable}joinsTransaction(){return this.db.transaction()!==void 0}create(z){let Z=this.db.transaction(),$=Z?this.insertWorkflow(Z,z):this.db.atomically((V)=>this.insertWorkflow(V,z));if(Z)$0($);return $}async insertWorkflow(z,Z){await this.db.configure();let $=this.db.now(z);await l(z`
78
- INSERT INTO ${this.workflows(z)}
79
- (id, name, args, status, progress, retick, created_at, updated_at)
80
- VALUES
81
- (${Z.id}, ${Z.name}, ${Z.args}, 'running',
82
- ${this.db.fraction(z,0)}, 0, ${$}, ${$})
83
- `,this.table),await this.db.insertJob(z,{name:q,args:JSON.stringify([Z.id])})}async find(z,Z={}){await this.db.configure();let $=this.db.sql,[V]=await l($`SELECT * FROM ${this.workflows($)} WHERE id = ${z}`,this.table);if(!V)return null;return{workflow:c0(V),steps:Z.steps===!1?[]:await this.stepsOf($,z)}}acquire(z,Z,$){return this.db.atomically(async(V)=>{let X=await this.lock(V,z);if(!X)return{kind:"missing"};let Y=await this.db.clock(V);if(X.lockedBy!==null&&!B0(X.lockedBy,Z)&&(X.lockedUntil??0)>Y)return await V`UPDATE ${this.workflows(V)} SET retick = 1 WHERE id = ${z}`,{kind:"busy"};let G=Y+Math.max(0,Math.round($));return await V`
84
- UPDATE ${this.workflows(V)}
85
- SET locked_by = ${Z}, locked_until = ${this.db.ms(V,G)}, retick = 0
86
- WHERE id = ${z}
87
- `,{kind:"acquired",workflow:{...X,lockedBy:Z,lockedUntil:G,retick:!1},steps:await this.stepsOf(V,z)}})}async renew(z,Z,$){await this.db.configure();let V=this.db.sql,X=await V`
88
- UPDATE ${this.workflows(V)}
89
- SET locked_until = ${this.db.now(V)} + ${this.db.ms(V,$)}
90
- WHERE id = ${z} AND locked_by = ${Z}
91
- `;return l0(X)>0}update(z,Z,$){return this.db.atomically(async(V)=>{let X=await this.lock(V,z);if(!X)return;if(Z.owner!==void 0&&X.lockedBy!==Z.owner)throw new I(z);let Y=Z.key===void 0?null:await this.stepOf(V,z,Z.key),G=Z.allSteps?await this.stepsOf(V,z):[],Q=Z.items===void 0?[]:await this.itemsOf(V,z,Z.items,["running","retrying"],-1,null),J=$({workflow:X,step:Y,steps:G,items:Q,now:Date.now()});if(J.step){let K=J.step.key===Z.key?Y!==null:await this.stepOf(V,z,J.step.key)!==null;await this.writeStep(V,J.step,K)}if(J.items)await this.writeItems(V,z,J.items);if(J.batch)await this.db.insertBatch(V,J.batch);for(let K of J.cancelBatches??[])await this.db.cancelBatch(V,K);let B={...X,...J.workflow},H=J.unlock===!0,N=V`
92
- status = ${B.status}, current_step = ${B.currentStep},
93
- progress = ${this.db.fraction(V,B.progress)}, result = ${B.result},
94
- error = ${B.error}, wake_at = ${this.db.timeOrNull(V,B.wakeAt)},
95
- updated_at = ${this.db.now(V)}
96
- `;if(H)await V`
97
- UPDATE ${this.workflows(V)}
98
- SET ${N}, locked_by = NULL, locked_until = NULL, retick = 0
99
- WHERE id = ${z}
100
- `;else await V`UPDATE ${this.workflows(V)} SET ${N} WHERE id = ${z}`;let F=(K)=>this.db.insertJob(V,{name:q,args:JSON.stringify([z]),delayMs:Math.max(0,Math.round(K))});if(J.tick)await F(J.tick.delayMs);if(H&&X.retick)await F(0);return J.result})}async listItems(z,Z,$){return await this.db.configure(),this.itemsOf(this.db.sql,z,Z,$.statuses,$.after??-1,$.limit)}async prune(z){let Z=await this.db.atomically(async($)=>{let V=this.endedClause($),X=$`${this.db.now($)} - ${this.db.ms($,z)}`;await $`
101
- DELETE FROM ${this.steps($)}
102
- WHERE workflow_id IN (
103
- SELECT id FROM ${this.workflows($)} WHERE ${V} AND updated_at <= ${X}
104
- )
105
- `;let Y=await $`
106
- DELETE FROM ${this.workflows($)} WHERE ${V} AND updated_at <= ${X}
107
- `;return l0(Y)});try{let $=this.db.sql;await $`
108
- DELETE FROM ${this.items($)}
109
- WHERE NOT EXISTS (
110
- SELECT 1 FROM ${this.workflows($)} w WHERE w.id = ${this.items($)}.workflow_id
111
- )
112
- `}catch($){if(!O0($))throw $}return Z}endedClause(z){return z`status IN (${Lz.map((Z)=>z`${Z}`).reduce((Z,$)=>z`${Z}, ${$}`)})`}async writeItems(z,Z,$){let V=this.db,X=$.step,Y=$.delete??[];for(let Q=0;Q<Y.length;Q+=500){let J=Y.slice(Q,Q+500).map((B)=>z`${B}`);await H0(z`
113
- DELETE FROM ${this.items(z)}
114
- WHERE workflow_id = ${Z} AND step_key = ${X}
115
- AND idx IN (${J.reduce((B,H)=>z`${B}, ${H}`)})
116
- `,this.itemTable)}let G=$.insert??[];for(let Q=0;Q<G.length;Q+=200){let J=V.now(z),B=G.slice(Q,Q+200).map((H)=>z`(
117
- ${Z}, ${X}, ${H.index}, ${H.key}, ${H.status}, ${H.attempt},
118
- ${H.error}, ${H.output}, ${V.timeOrNull(z,H.wakeAt)},
119
- ${V.timeOrNull(z,H.startedAt)}, ${V.timeOrNull(z,H.finishedAt)}, ${J}, ${J}
120
- )`);await H0(z`
121
- INSERT INTO ${this.items(z)}
122
- (workflow_id, step_key, idx, item_key, status, attempt, error, output, wake_at,
123
- started_at, finished_at, created_at, updated_at)
124
- VALUES ${B.reduce((H,N)=>z`${H}, ${N}`)}
125
- `,this.itemTable)}for(let Q of $.update??[])await H0(z`
126
- UPDATE ${this.items(z)}
127
- SET item_key = ${Q.key}, status = ${Q.status}, attempt = ${Q.attempt},
128
- error = ${Q.error}, output = ${Q.output},
129
- wake_at = ${V.timeOrNull(z,Q.wakeAt)},
130
- started_at = ${V.timeOrNull(z,Q.startedAt)},
131
- finished_at = ${V.timeOrNull(z,Q.finishedAt)}, updated_at = ${V.now(z)}
132
- WHERE workflow_id = ${Z} AND step_key = ${X} AND idx = ${Q.index}
133
- `,this.itemTable)}async itemsOf(z,Z,$,V,X,Y){let G=V.map((J)=>z`${J}`).reduce((J,B)=>z`${J}, ${B}`);return(await H0(Y===null?z`
134
- SELECT * FROM ${this.items(z)}
135
- WHERE workflow_id = ${Z} AND step_key = ${$}
136
- AND status IN (${G}) AND idx > ${X}
137
- ORDER BY idx
138
- `:z`
139
- SELECT * FROM ${this.items(z)}
140
- WHERE workflow_id = ${Z} AND step_key = ${$}
141
- AND status IN (${G}) AND idx > ${X}
142
- ORDER BY idx LIMIT ${Y}
143
- `,this.itemTable)).map(Wz)}async writeStep(z,Z,$){let V=this.db,X=this.keyColumn(z);if($){await z`
144
- UPDATE ${this.steps(z)}
145
- SET status = ${Z.status}, attempt = ${Z.attempt}, output = ${Z.output},
146
- error = ${Z.error}, batch_id = ${Z.batchId},
147
- wake_at = ${V.timeOrNull(z,Z.wakeAt)},
148
- started_at = ${V.timeOrNull(z,Z.startedAt)},
149
- finished_at = ${V.timeOrNull(z,Z.finishedAt)}, updated_at = ${V.now(z)}
150
- WHERE workflow_id = ${Z.workflowId} AND ${X} = ${Z.key}
151
- `;return}let Y=V.now(z);await z`
152
- INSERT INTO ${this.steps(z)}
153
- (workflow_id, ${X}, status, attempt, output, error, batch_id, wake_at,
154
- started_at, finished_at, created_at, updated_at)
155
- VALUES
156
- (${Z.workflowId}, ${Z.key}, ${Z.status}, ${Z.attempt}, ${Z.output},
157
- ${Z.error}, ${Z.batchId}, ${V.timeOrNull(z,Z.wakeAt)},
158
- ${V.timeOrNull(z,Z.startedAt)}, ${V.timeOrNull(z,Z.finishedAt)}, ${Y}, ${Y})
159
- `}async lock(z,Z){let $;if(this.db.dialect==="sqlite")await l(z`UPDATE ${this.workflows(z)} SET updated_at = updated_at WHERE id = ${Z}`,this.table),$=await z`SELECT * FROM ${this.workflows(z)} WHERE id = ${Z}`;else $=await l(z`SELECT * FROM ${this.workflows(z)} WHERE id = ${Z} FOR UPDATE`,this.table);return $[0]?c0($[0]):void 0}async stepOf(z,Z,$){let[V]=await l(z`SELECT * FROM ${this.steps(z)} WHERE workflow_id = ${Z} AND ${this.keyColumn(z)} = ${$}`,this.stepTable);return V?d0(V):null}async stepsOf(z,Z){return(await l(z`
160
- SELECT * FROM ${this.steps(z)} WHERE workflow_id = ${Z}
161
- ORDER BY created_at, ${this.keyColumn(z)}
162
- `,this.stepTable)).map(d0)}workflows(z){return z.unsafe(this.db.quoted(this.table))}steps(z){return z.unsafe(this.db.quoted(this.stepTable))}items(z){return z.unsafe(this.db.quoted(this.itemTable))}keyColumn(z){return z.unsafe(this.db.quoted("key"))}}function b(z){return z==null?null:Number(z)}function x(z){return z==null?null:String(z)}function c0(z){return{id:String(z.id),name:String(z.name),args:String(z.args),status:String(z.status),currentStep:x(z.current_step),progress:Number(z.progress??0),result:x(z.result),error:x(z.error),wakeAt:b(z.wake_at),lockedBy:x(z.locked_by),lockedUntil:b(z.locked_until),retick:Number(z.retick??0)!==0,createdAt:Number(z.created_at),updatedAt:Number(z.updated_at)}}function d0(z){return{workflowId:String(z.workflow_id),key:String(z.key),status:String(z.status),attempt:Number(z.attempt??0),output:x(z.output),error:x(z.error),batchId:x(z.batch_id),wakeAt:b(z.wake_at),startedAt:b(z.started_at),finishedAt:b(z.finished_at),createdAt:Number(z.created_at),updatedAt:Number(z.updated_at)}}function Wz(z){return{workflowId:String(z.workflow_id),step:String(z.step_key),index:Number(z.idx),key:x(z.item_key),status:String(z.status),attempt:Number(z.attempt??0),error:x(z.error),output:x(z.output),wakeAt:b(z.wake_at),startedAt:b(z.started_at),finishedAt:b(z.finished_at),createdAt:Number(z.created_at),updatedAt:Number(z.updated_at)}}function l0(z){let Z=z;return Math.max(Number(Z.count??0),Number(Z.affectedRows??0))}function O0(z){let Z=String(z?.message??z);return/does not exist|doesn't exist|unknown column|no such (table|column)|has no column/i.test(Z)}async function l(z,Z){try{return await z}catch($){if(!O0($))throw $;throw Error(`Workflows need the "${Z}" table, and the database says it is missing. Add the GemiWorkflow and GemiWorkflowStep models from the docs (docs/workflows.md#the-workflow-tables) and migrate, or call the queue driver's createTable().`,{cause:$})}}async function H0(z,Z){try{return await z}catch($){if(!O0($))throw $;throw Error(`step.each needs the "${Z}" table, and the database says it is missing. Add the GemiWorkflowItem model from the docs (docs/workflows.md#the-workflow-tables) and migrate, or call the queue driver's createTable().`,{cause:$})}}function i0(z,Z,$){if(z==="mysql"||z==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${Z}\` (
163
- \`id\` VARCHAR(191) NOT NULL,
164
- \`name\` VARCHAR(191) NOT NULL,
165
- \`args\` LONGTEXT NOT NULL,
166
- \`status\` VARCHAR(191) NOT NULL,
167
- \`current_step\` VARCHAR(191) NULL,
168
- \`progress\` DOUBLE NOT NULL DEFAULT 0,
169
- \`result\` LONGTEXT NULL,
170
- \`error\` LONGTEXT NULL,
171
- \`wake_at\` BIGINT NULL,
172
- \`locked_by\` VARCHAR(191) NULL,
173
- \`locked_until\` BIGINT NULL,
174
- \`retick\` INTEGER NOT NULL DEFAULT 0,
175
- \`created_at\` BIGINT NOT NULL,
176
- \`updated_at\` BIGINT NOT NULL,
177
-
178
- INDEX \`${Z}_status_idx\`(\`status\`),
179
- PRIMARY KEY (\`id\`)
180
- ) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci`,`CREATE TABLE IF NOT EXISTS \`${$}\` (
181
- \`workflow_id\` VARCHAR(191) NOT NULL,
182
- \`key\` VARCHAR(191) NOT NULL,
183
- \`status\` VARCHAR(191) NOT NULL,
184
- \`attempt\` INTEGER NOT NULL DEFAULT 0,
185
- \`output\` LONGTEXT NULL,
186
- \`error\` LONGTEXT NULL,
187
- \`batch_id\` VARCHAR(191) NULL,
188
- \`wake_at\` BIGINT NULL,
189
- \`started_at\` BIGINT NULL,
190
- \`finished_at\` BIGINT NULL,
191
- \`created_at\` BIGINT NOT NULL,
192
- \`updated_at\` BIGINT NOT NULL,
193
-
194
- PRIMARY KEY (\`workflow_id\`, \`key\`)
195
- ) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci`];let V=z==="sqlite";return[`CREATE TABLE IF NOT EXISTS "${Z}" (
196
- "id" TEXT NOT NULL${V?" PRIMARY KEY":""},
197
- "name" TEXT NOT NULL,
198
- "args" TEXT NOT NULL,
199
- "status" TEXT NOT NULL,
200
- "current_step" TEXT,
201
- "progress" ${V?"REAL":"DOUBLE PRECISION"} NOT NULL DEFAULT 0,
202
- "result" TEXT,
203
- "error" TEXT,
204
- "wake_at" BIGINT,
205
- "locked_by" TEXT,
206
- "locked_until" BIGINT,
207
- "retick" INTEGER NOT NULL DEFAULT 0,
208
- "created_at" BIGINT NOT NULL,
209
- "updated_at" BIGINT NOT NULL${V?"":`,
210
-
211
- CONSTRAINT "${Z}_pkey" PRIMARY KEY ("id")`}
212
- )`,`CREATE TABLE IF NOT EXISTS "${$}" (
213
- "workflow_id" TEXT NOT NULL,
214
- "key" TEXT NOT NULL,
215
- "status" TEXT NOT NULL,
216
- "attempt" INTEGER NOT NULL DEFAULT 0,
217
- "output" TEXT,
218
- "error" TEXT,
219
- "batch_id" TEXT,
220
- "wake_at" BIGINT,
221
- "started_at" BIGINT,
222
- "finished_at" BIGINT,
223
- "created_at" BIGINT NOT NULL,
224
- "updated_at" BIGINT NOT NULL,
225
-
226
- ${V?'PRIMARY KEY ("workflow_id", "key")':`CONSTRAINT "${$}_pkey" PRIMARY KEY ("workflow_id","key")`}
227
- )`,`CREATE INDEX IF NOT EXISTS "${Z}_status_idx" ON "${Z}"("status")`]}function s0(z,Z){if(z==="mysql"||z==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${Z}\` (
228
- \`workflow_id\` VARCHAR(191) NOT NULL,
229
- \`step_key\` VARCHAR(191) NOT NULL,
230
- \`idx\` INTEGER NOT NULL,
231
- \`item_key\` VARCHAR(191) NULL,
232
- \`status\` VARCHAR(191) NOT NULL,
233
- \`attempt\` INTEGER NOT NULL DEFAULT 0,
234
- \`error\` LONGTEXT NULL,
235
- \`output\` LONGTEXT NULL,
236
- \`wake_at\` BIGINT NULL,
237
- \`started_at\` BIGINT NULL,
238
- \`finished_at\` BIGINT NULL,
239
- \`created_at\` BIGINT NOT NULL,
240
- \`updated_at\` BIGINT NOT NULL,
241
-
242
- PRIMARY KEY (\`workflow_id\`, \`step_key\`, \`idx\`)
243
- ) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci`];return[`CREATE TABLE IF NOT EXISTS "${Z}" (
244
- "workflow_id" TEXT NOT NULL,
245
- "step_key" TEXT NOT NULL,
246
- "idx" INTEGER NOT NULL,
247
- "item_key" TEXT,
248
- "status" TEXT NOT NULL,
249
- "attempt" INTEGER NOT NULL DEFAULT 0,
250
- "error" TEXT,
251
- "output" TEXT,
252
- "wake_at" BIGINT,
253
- "started_at" BIGINT,
254
- "finished_at" BIGINT,
255
- "created_at" BIGINT NOT NULL,
256
- "updated_at" BIGINT NOT NULL,
257
-
258
- ${z==="sqlite"?'PRIMARY KEY ("workflow_id", "step_key", "idx")':`CONSTRAINT "${Z}_pkey" PRIMARY KEY ("workflow_id","step_key","idx")`}
259
- )`]}function P0(z){return{id:z.id,name:z.name,total:z.total,pending:z.total,succeeded:0,failed:0,cancelled:0,failedJobIds:[],cancelledAt:null,finishedAt:null,createdAt:z.now,allowFailures:z.allowFailures,callbacks:z.callbacks}}function U0(z,Z,$){if(z.pending<=0)return z;let V={...z,pending:z.pending-1};if(Z==="succeeded")V.succeeded++;else if(Z==="cancelled")V.cancelled++;else V.failed++,V.failedJobIds=[...z.failedJobIds,$];return V}function K0(z,Z){return!Z.allowFailures&&Z.cancelledAt===null&&Z.finishedAt===null&&Z.failed>z.failed}function i(z,Z,$){let V=Math.min(Math.max(0,$),z.pending);return{...z,cancelledAt:z.cancelledAt??Z,pending:z.pending-V,cancelled:z.cancelled+V}}function s(z,Z,$){let V=Z,X=[],Y=Z.callbacks,G=z.failed===0&&z.cancelledAt===null,Q=Z.failed===0&&Z.cancelledAt===null;if(G&&!Q&&Y.catch)X.push(Y.catch);if(Z.pending===0&&Z.finishedAt===null){if(V={...Z,finishedAt:$},Z.cancelledAt===null&&(Z.failed===0||Z.allowFailures)&&Y.then)X.push(Y.then);if(Y.finally)X.push(Y.finally)}let J=w(V);return{record:V,calls:X.map((B)=>({name:B.name,args:JSON.stringify([...B.args,J])}))}}function w(z,Z=0){let{allowFailures:$,callbacks:V,...X}=z,Y=z.total-z.pending,G=z.total===0?1:Math.min(1,Math.max(0,(Y+Math.max(0,Z))/z.total));return{...X,failedJobIds:[...z.failedJobIds],progress:G}}function g(z){if(typeof z!=="number"||!Number.isFinite(z))throw TypeError(`A job's progress is a number from 0 to 1; got ${String(z)}.`);return Math.min(1,Math.max(0,z))}var a0=200,Cz="Its batch was cancelled before it ran.";class I0{table;batchTable;workflowTable;workflowStepTable;workflowItemTable;workflows;sql;dialect;connection;busyTimeout;configured;sqliteTail=Promise.resolve();constructor(z,Z={}){let $=Z.table??"gemi_jobs",V=Z.batchTable??($==="gemi_jobs"?"gemi_job_batches":`${$}_batches`),X=$==="gemi_jobs",Y=Z.workflowTable??(X?"gemi_workflows":`${$}_workflows`),G=Z.workflowStepTable??(X?"gemi_workflow_steps":`${$}_workflow_steps`),Q=Z.workflowItemTable??(X?"gemi_workflow_items":`${$}_workflow_items`);for(let B of[$,V,Y,G,Q])if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(B))throw Error(`The queue table name "${B}" is not a plain identifier. Use letters, digits and underscores.`);let J=Z.busyTimeout??1000;if(!Number.isInteger(J)||J<0)throw Error(`The queue's busyTimeout must be a whole number of milliseconds, 0 or more; got ${J}.`);this.table=$,this.batchTable=V,this.workflowTable=Y,this.workflowStepTable=G,this.workflowItemTable=Q,this.sql=z.sql,this.dialect=z.dialect,this.connection=z.name,this.busyTimeout=J}configure(){if(this.dialect!=="sqlite"||this.busyTimeout===0)return Promise.resolve();return this.configured??=(async()=>{let[z]=await this.sql.unsafe("PRAGMA busy_timeout");if(Number(z?.timeout??0)!==0)return;await this.sql.unsafe(`PRAGMA busy_timeout = ${this.busyTimeout}`)})().catch((z)=>{throw this.configured=void 0,z}),this.configured}async createTable(){await this.configure();let[z,...Z]=Oz(this.dialect,this.table);if(await this.sql.unsafe(z),!await this.hasBatchColumns())for(let $ of Ez(this.dialect,this.table))await this.sql.unsafe($);for(let $ of Z)await this.sql.unsafe($);for(let $ of Iz(this.dialect,this.batchTable))await this.sql.unsafe($);for(let $ of i0(this.dialect,this.workflowTable,this.workflowStepTable))await this.sql.unsafe($);for(let $ of s0(this.dialect,this.workflowItemTable))await this.sql.unsafe($)}async hasBatchColumns(){try{return await this.sql.unsafe(`SELECT batch_id, progress FROM ${this.quoted(this.table)} WHERE 1 = 0`),!0}catch(z){if(o0(z))return!1;throw z}}enqueue(z){let Z=this.transaction(),$=this.insert(Z??this.sql,z);if(Z)$0($);return $}async insert(z,{name:Z,args:$,delayMs:V=0,id:X=Bun.randomUUIDv7()}){await this.configure();let Y=this.now(z);return await z`
260
- INSERT INTO ${this.name(z)}
261
- (id, name, payload, status, attempts, available_at, created_at, updated_at)
262
- VALUES
263
- (${X}, ${Z}, ${$}, 'pending', 0, ${Y} + ${this.ms(z,V)}, ${Y}, ${Y})
264
- `,X}lockStore(){return new Z0({sql:this.sql,dialect:this.dialect,name:this.connection},{busyTimeout:this.busyTimeout})}joinsTransaction(){return this.transaction()!==void 0}transaction(){if(this.dialect==="sqlite"||this.connection===void 0)return;let z=r0();if(z===void 0||t0()!==this.connection)return;return z}async claim(z,Z){let $=Math.max(0,Math.floor(z));if($===0)return[];return await this.configure(),(this.dialect==="mysql"||this.dialect==="mariadb"?await this.claimLocking($,Z):await this.claimUpdating($,Z)).map((X)=>({order:Number(X.available_at),job:{id:String(X.id),name:String(X.name),args:String(X.payload),attempt:Number(X.attempts),createdAt:Number(X.created_at),...X.batch_id==null?{}:{batchId:String(X.batch_id)}}})).sort((X,Y)=>X.order-Y.order||(X.job.id<Y.job.id?-1:1)).map(({job:X})=>X)}async complete(z){if(z.batchId!==void 0)return this.endBatchJob(z,"succeeded");await this.configure();let Z=this.sql;await Z`
265
- DELETE FROM ${this.name(Z)}
266
- WHERE id = ${z.id} AND status = 'claimed' AND attempts = ${z.attempt}
267
- `}async fail(z,Z){if(z.batchId!==void 0)return this.endBatchJob(z,"failed",Z);await this.configure();let $=this.sql,V=this.now($);if(Z.retryInMs===null){await $`
268
- UPDATE ${this.name($)}
269
- SET status = 'dead', lease_expires_at = NULL, last_error = ${Z.error},
270
- updated_at = ${V}
271
- WHERE id = ${z.id} AND status = 'claimed' AND attempts = ${z.attempt}
272
- `;return}await $`
273
- UPDATE ${this.name($)}
274
- SET status = 'pending', available_at = ${V} + ${this.ms($,Z.retryInMs)},
275
- lease_expires_at = NULL, last_error = ${Z.error}, updated_at = ${V}
276
- WHERE id = ${z.id} AND status = 'claimed' AND attempts = ${z.attempt}
277
- `}async release(z,Z){let $=this.sql,V=this.now($);await $`
278
- UPDATE ${this.name($)}
279
- SET status = 'pending', attempts = attempts - 1,
280
- available_at = ${V} + ${this.ms($,Z.retryInMs)},
281
- lease_expires_at = NULL, updated_at = ${V}
282
- WHERE id = ${z.id} AND status = 'claimed' AND attempts = ${z.attempt}
283
- `}async heartbeat(z,Z){await this.configure();let $=this.sql;await Promise.all(z.map((V)=>{let X=this.now($);return $`
284
- UPDATE ${this.name($)}
285
- SET lease_expires_at = ${X} + ${this.ms($,Z.visibilityTimeoutMs)},
286
- updated_at = ${X}
287
- WHERE id = ${V.id} AND status = 'claimed' AND attempts = ${V.attempt}
288
- `}))}async retryDead(z){await this.configure();let Z=this.sql,[$]=await Z`
289
- SELECT * FROM ${this.name(Z)} WHERE id = ${z} AND status = 'dead'
290
- `;if(!$||$.batch_id!=null)return!1;let V=this.now(Z),X=await Z`
291
- UPDATE ${this.name(Z)}
292
- SET status = 'pending', attempts = 0, available_at = ${V}, lease_expires_at = NULL,
293
- updated_at = ${V}
294
- WHERE id = ${z} AND status = 'dead'
295
- `;return a(X)>0}async prune(z){await this.configure();let Z=this.sql,$=await Z`
296
- DELETE FROM ${this.name(Z)}
297
- WHERE status = 'dead' AND updated_at <= ${this.now(Z)} - ${this.ms(Z,z)}
298
- `;return a($)}enqueueBatch(z){let Z=this.transaction(),$=Z?this.insertBatch(Z,z):this.atomically((V)=>this.insertBatch(V,z));if(Z)$0($);return $}async insertBatch(z,Z){await this.configure();let $=await this.clock(z),V=P0({...Z,total:Z.args.length,now:$}),{record:X,calls:Y}=s(V,V,$);await E0(z`
299
- INSERT INTO ${this.batches(z)}
300
- (id, name, total, pending, succeeded, failed, cancelled, failed_job_ids, options,
301
- cancelled_at, finished_at, created_at, updated_at)
302
- VALUES
303
- (${X.id}, ${X.name}, ${X.total}, ${X.pending}, 0, 0, 0,
304
- '[]', ${Sz(X)}, NULL, ${this.timeOrNull(z,X.finishedAt)},
305
- ${this.ms(z,$)}, ${this.ms(z,$)})
306
- `,this.batchTable);let G=this.ms(z,$);for(let Q=0;Q<Z.args.length;Q+=a0){let J=Z.args.slice(Q,Q+a0).map((B)=>z`(${Bun.randomUUIDv7()}, ${Z.job}, ${B}, 'pending', 0, ${G}, ${G}, ${G}, ${Z.id}, 0)`).reduce((B,H)=>z`${B}, ${H}`);await E0(z`
307
- INSERT INTO ${this.name(z)}
308
- (id, name, payload, status, attempts, available_at, created_at, updated_at, batch_id, progress)
309
- VALUES ${J}
310
- `,this.table)}for(let Q of Y)await this.insert(z,Q)}async findBatch(z,Z={}){await this.configure();let $=this.sql,[V]=await E0($`SELECT * FROM ${this.batches($)} WHERE id = ${z}`,this.batchTable);if(!V)return null;let X=n0(V);if(Z.progress===!1||X.pending===0)return w(X);let[Y]=await $`
311
- SELECT COALESCE(SUM(progress), 0) AS running FROM ${this.name($)}
312
- WHERE batch_id = ${z} AND status IN ('pending', 'claimed')
313
- `;return w(X,Number(Y?.running??0))}async cancelBatch(z){return this.atomically((Z)=>this.cancelBatchOn(Z,z))}async cancelBatchOn(z,Z){let $=await this.lockBatch(z,Z);if(!$||$.finishedAt!==null||$.cancelledAt!==null)return!1;let V=await this.clock(z),X=i($,V,await this.cancelWaiting(z,Z));return await this.saveBatch(z,$,X,V),!0}workflowStore(){return this.workflows??=new C0({sql:this.sql,dialect:this.dialect,connection:this.connection,configure:()=>this.configure(),atomically:(z)=>this.atomically(z),transaction:()=>this.transaction(),now:(z)=>this.now(z),ms:(z,Z)=>this.ms(z,Z),timeOrNull:(z,Z)=>this.timeOrNull(z,Z),fraction:(z,Z)=>this.fraction(z,Z),clock:(z)=>this.clock(z),insertJob:(z,Z)=>this.insert(z,Z),insertBatch:(z,Z)=>this.insertBatch(z,Z),cancelBatch:(z,Z)=>this.cancelBatchOn(z,Z),quoted:(z)=>this.quoted(z)},{table:this.workflowTable,stepTable:this.workflowStepTable,itemTable:this.workflowItemTable}),this.workflows}async reportProgress(z,Z){let $=g(Z);await this.configure();let V=this.sql;await V`
314
- UPDATE ${this.name(V)} SET progress = ${this.fraction(V,$)}
315
- WHERE id = ${z.id} AND status = 'claimed' AND attempts = ${z.attempt}
316
- `}async pruneBatches(z){await this.configure();let Z=this.sql,$=await Z`
317
- DELETE FROM ${this.batches(Z)}
318
- WHERE finished_at IS NOT NULL AND finished_at <= ${this.now(Z)} - ${this.ms(Z,z)}
319
- `;return a($)}endBatchJob(z,Z,$){let V=z.batchId;return this.atomically(async(X)=>{let Y=await this.lockBatch(X,V),G=X`id = ${z.id} AND status = 'claimed' AND attempts = ${z.attempt}`,Q=this.now(X);if(Z==="succeeded"){let H=await X`DELETE FROM ${this.name(X)} WHERE ${G}`;if(a(H)===0||!Y)return;return this.count(X,Y,"succeeded",z.id)}let J=$.cancelled===!0||$.retryInMs!==null&&Y!==void 0&&Y.cancelledAt!==null;if($.retryInMs!==null&&!J){await X`
320
- UPDATE ${this.name(X)}
321
- SET status = 'pending', available_at = ${Q} + ${this.ms(X,$.retryInMs)},
322
- lease_expires_at = NULL, last_error = ${$.error}, progress = 0,
323
- updated_at = ${Q}
324
- WHERE ${G}
325
- `;return}let B=await X`
326
- UPDATE ${this.name(X)}
327
- SET status = 'dead', lease_expires_at = NULL, last_error = ${$.error},
328
- updated_at = ${Q}
329
- WHERE ${G}
330
- `;if(a(B)===0||!Y)return;return this.count(X,Y,J?"cancelled":"failed",z.id)})}async count(z,Z,$,V){let X=await this.clock(z),Y=U0(Z,$,V);if(K0(Z,Y))Y=i(Y,X,await this.cancelWaiting(z,Z.id));await this.saveBatch(z,Z,Y,X)}async cancelWaiting(z,Z){let $=this.now(z),V=await z`
331
- UPDATE ${this.name(z)}
332
- SET status = 'dead', last_error = ${Cz}, updated_at = ${$}
333
- WHERE batch_id = ${Z} AND status = 'pending'
334
- `;return a(V)}async saveBatch(z,Z,$,V){let{record:X,calls:Y}=s(Z,$,V);await z`
335
- UPDATE ${this.batches(z)}
336
- SET pending = ${X.pending}, succeeded = ${X.succeeded}, failed = ${X.failed},
337
- cancelled = ${X.cancelled}, failed_job_ids = ${JSON.stringify(X.failedJobIds)},
338
- cancelled_at = ${this.timeOrNull(z,X.cancelledAt)},
339
- finished_at = ${this.timeOrNull(z,X.finishedAt)}, updated_at = ${this.ms(z,V)}
340
- WHERE id = ${X.id}
341
- `;for(let G of Y)await this.insert(z,G)}async lockBatch(z,Z){let $;if(this.dialect==="sqlite")await z`UPDATE ${this.batches(z)} SET updated_at = updated_at WHERE id = ${Z}`,$=await z`SELECT * FROM ${this.batches(z)} WHERE id = ${Z}`;else $=await z`SELECT * FROM ${this.batches(z)} WHERE id = ${Z} FOR UPDATE`;return $[0]?n0($[0]):void 0}atomically(z){let Z=async()=>{await this.configure();for(let V=0;;V++)try{return await this.sql.begin((X)=>z(X))}catch(X){if(this.dialect!=="sqlite"||V>=50||!/within a transaction/i.test(String(X?.message??X)))throw X;await new Promise((Y)=>setTimeout(Y,20))}};if(this.dialect!=="sqlite")return Z();let $=this.sqliteTail.then(Z,Z);return this.sqliteTail=$.catch(()=>{}),$}async clock(z){let[Z]=await z`SELECT ${this.now(z)} AS now`;return Number(Z.now)}timeOrNull(z,Z){return Z===null?z`NULL`:this.ms(z,Z)}fraction(z,Z){return this.dialect==="postgres"?z`CAST(${Z} AS DOUBLE PRECISION)`:z`${Z}`}async claimUpdating(z,Z){let $=this.sql,V=this.now($),X=this.ms($,Z.visibilityTimeoutMs),Y=this.name($);if(this.dialect==="postgres")return await $`
342
- WITH next AS (
343
- SELECT id FROM ${Y}
344
- WHERE ${this.claimable($,Z)}
345
- ORDER BY available_at, id
346
- LIMIT ${z}
347
- FOR UPDATE SKIP LOCKED
348
- )
349
- UPDATE ${Y} AS job
350
- SET status = 'claimed', attempts = job.attempts + 1, claimed_at = ${V},
351
- lease_expires_at = ${V} + ${X}, updated_at = ${V}
352
- FROM next
353
- WHERE job.id = next.id
354
- RETURNING job.*
355
- `;return await $`
356
- UPDATE ${Y}
357
- SET status = 'claimed', attempts = attempts + 1, claimed_at = ${V},
358
- lease_expires_at = ${V} + ${X}, updated_at = ${V}
359
- WHERE id IN (
360
- SELECT id FROM ${Y}
361
- WHERE ${this.claimable($,Z)}
362
- ORDER BY available_at, id
363
- LIMIT ${z}
364
- )
365
- RETURNING *
366
- `}async claimLocking(z,Z){let $=await this.sql.reserve(),[V]=await $`
367
- SELECT @@transaction_isolation AS level
368
- `;await $`SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED`;try{return await this.claimLockingOn($,z,Z)}finally{let X=V?.level?.replaceAll("-"," ");if(X&&/^[A-Z ]+$/.test(X))await $.unsafe(`SET SESSION TRANSACTION ISOLATION LEVEL ${X}`);$.release()}}async claimLockingOn(z,Z,$){return await z.begin(async(V)=>{let X=this.name(V),Y=V.unsafe("*"),G=await V`
369
- SELECT ${Y} FROM ${X}
370
- WHERE status = 'pending' AND available_at <= ${this.now(V)}
371
- AND ${this.runnable(V,$,"available_at")}
372
- ORDER BY available_at, id
373
- LIMIT ${Z}
374
- FOR UPDATE SKIP LOCKED
375
- `;if(G.length<Z){let Q=await V`
376
- SELECT ${Y} FROM ${X}
377
- WHERE status = 'claimed' AND lease_expires_at <= ${this.now(V)}
378
- AND ${this.runnable(V,$,"lease_expires_at")}
379
- ORDER BY lease_expires_at, id
380
- LIMIT ${Z-G.length}
381
- FOR UPDATE SKIP LOCKED
382
- `;G.push(...Q)}for(let Q of G){let J=this.now(V);await V`
383
- UPDATE ${X}
384
- SET status = 'claimed', attempts = attempts + 1, claimed_at = ${J},
385
- lease_expires_at = ${J} + ${this.ms(V,$.visibilityTimeoutMs)},
386
- updated_at = ${J}
387
- WHERE id = ${Q.id}
388
- `}return G.map((Q)=>({...Q,attempts:Number(Q.attempts)+1}))})}claimable(z,Z){let $=this.now(z);return z`(
389
- (status = 'pending' AND available_at <= ${$}
390
- AND ${this.runnable(z,Z,"available_at")})
391
- OR (status = 'claimed' AND lease_expires_at <= ${$}
392
- AND ${this.runnable(z,Z,"lease_expires_at")})
393
- )`}runnable(z,Z,$){let V=Z.registered;if(!V)return z`1 = 1`;let X=V.names.length?z`name IN (${V.names.map((G)=>z`${G}`).reduce((G,Q)=>z`${G}, ${Q}`)})`:z`1 = 0`;if(!Number.isFinite(V.graceMs))return X;let Y=z.unsafe($);return z`(${X} OR ${Y} <= ${this.now(z)} - ${this.ms(z,V.graceMs)})`}name(z){return z.unsafe(this.quoted(this.table))}batches(z){return z.unsafe(this.quoted(this.batchTable))}quoted(z){return this.dialect==="mysql"||this.dialect==="mariadb"?`\`${z}\``:`"${z}"`}now(z){switch(this.dialect){case"postgres":return z`floor(extract(epoch from statement_timestamp()) * 1000)::bigint`;case"mysql":case"mariadb":return z`(TIMESTAMPDIFF(MICROSECOND, '1970-01-01 00:00:00', UTC_TIMESTAMP(6)) DIV 1000)`;case"sqlite":return z`CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER)`}}ms(z,Z){let $=Math.max(0,Math.round(Z));return this.dialect==="mysql"||this.dialect==="mariadb"?z`CAST(${$} AS SIGNED)`:z`CAST(${$} AS BIGINT)`}}function a(z){let Z=z;return Math.max(Number(Z.count??0),Number(Z.affectedRows??0))}function Oz(z,Z){if(z==="mysql"||z==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${Z}\` (
394
- \`id\` VARCHAR(191) NOT NULL,
395
- \`name\` VARCHAR(191) NOT NULL,
396
- \`payload\` LONGTEXT NOT NULL,
397
- \`status\` VARCHAR(191) NOT NULL,
398
- \`attempts\` INTEGER NOT NULL DEFAULT 0,
399
- \`available_at\` BIGINT NOT NULL,
400
- \`claimed_at\` BIGINT NULL,
401
- \`lease_expires_at\` BIGINT NULL,
402
- \`last_error\` LONGTEXT NULL,
403
- \`created_at\` BIGINT NOT NULL,
404
- \`updated_at\` BIGINT NOT NULL,
405
- \`batch_id\` VARCHAR(191) NULL,
406
- \`progress\` DOUBLE NULL,
407
-
408
- INDEX \`${Z}_status_available_at_idx\`(\`status\`, \`available_at\`),
409
- INDEX \`${Z}_status_lease_expires_at_idx\`(\`status\`, \`lease_expires_at\`),
410
- INDEX \`${Z}_batch_id_idx\`(\`batch_id\`),
411
- PRIMARY KEY (\`id\`)
412
- ) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci`];let $=z==="sqlite"?'"id" TEXT NOT NULL PRIMARY KEY,':'"id" TEXT NOT NULL,',V=z==="sqlite"?"":`,
413
-
414
- CONSTRAINT "${Z}_pkey" PRIMARY KEY ("id")`;return[`CREATE TABLE IF NOT EXISTS "${Z}" (
415
- ${$}
416
- "name" TEXT NOT NULL,
417
- "payload" TEXT NOT NULL,
418
- "status" TEXT NOT NULL,
419
- "attempts" INTEGER NOT NULL DEFAULT 0,
420
- "available_at" BIGINT NOT NULL,
421
- "claimed_at" BIGINT,
422
- "lease_expires_at" BIGINT,
423
- "last_error" TEXT,
424
- "created_at" BIGINT NOT NULL,
425
- "updated_at" BIGINT NOT NULL,
426
- "batch_id" TEXT,
427
- "progress" ${z==="sqlite"?"REAL":"DOUBLE PRECISION"}${V}
428
- )`,`CREATE INDEX IF NOT EXISTS "${Z}_status_available_at_idx" ON "${Z}"("status", "available_at")`,`CREATE INDEX IF NOT EXISTS "${Z}_status_lease_expires_at_idx" ON "${Z}"("status", "lease_expires_at")`,`CREATE INDEX IF NOT EXISTS "${Z}_batch_id_idx" ON "${Z}"("batch_id")`]}function Ez(z,Z){if(z==="mysql"||z==="mariadb")return[`ALTER TABLE \`${Z}\` ADD COLUMN \`batch_id\` VARCHAR(191) NULL,
429
- ADD COLUMN \`progress\` DOUBLE NULL,
430
- ADD INDEX \`${Z}_batch_id_idx\`(\`batch_id\`)`];let $=z==="sqlite"?"REAL":"DOUBLE PRECISION";if(z==="sqlite")return[`ALTER TABLE "${Z}" ADD COLUMN "batch_id" TEXT`,`ALTER TABLE "${Z}" ADD COLUMN "progress" ${$}`,`CREATE INDEX IF NOT EXISTS "${Z}_batch_id_idx" ON "${Z}"("batch_id")`];return[`ALTER TABLE "${Z}" ADD COLUMN IF NOT EXISTS "batch_id" TEXT,
431
- ADD COLUMN IF NOT EXISTS "progress" ${$}`,`CREATE INDEX IF NOT EXISTS "${Z}_batch_id_idx" ON "${Z}"("batch_id")`]}function Iz(z,Z){if(z==="mysql"||z==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${Z}\` (
432
- \`id\` VARCHAR(191) NOT NULL,
433
- \`name\` VARCHAR(191) NULL,
434
- \`total\` INTEGER NOT NULL,
435
- \`pending\` INTEGER NOT NULL,
436
- \`succeeded\` INTEGER NOT NULL DEFAULT 0,
437
- \`failed\` INTEGER NOT NULL DEFAULT 0,
438
- \`cancelled\` INTEGER NOT NULL DEFAULT 0,
439
- \`failed_job_ids\` LONGTEXT NOT NULL,
440
- \`options\` LONGTEXT NOT NULL,
441
- \`cancelled_at\` BIGINT NULL,
442
- \`finished_at\` BIGINT NULL,
443
- \`created_at\` BIGINT NOT NULL,
444
- \`updated_at\` BIGINT NOT NULL,
445
-
446
- PRIMARY KEY (\`id\`)
447
- ) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci`];let $=z==="sqlite"?'"id" TEXT NOT NULL PRIMARY KEY,':'"id" TEXT NOT NULL,',V=z==="sqlite"?"":`,
448
-
449
- CONSTRAINT "${Z}_pkey" PRIMARY KEY ("id")`;return[`CREATE TABLE IF NOT EXISTS "${Z}" (
450
- ${$}
451
- "name" TEXT,
452
- "total" INTEGER NOT NULL,
453
- "pending" INTEGER NOT NULL,
454
- "succeeded" INTEGER NOT NULL DEFAULT 0,
455
- "failed" INTEGER NOT NULL DEFAULT 0,
456
- "cancelled" INTEGER NOT NULL DEFAULT 0,
457
- "failed_job_ids" TEXT NOT NULL,
458
- "options" TEXT NOT NULL,
459
- "cancelled_at" BIGINT,
460
- "finished_at" BIGINT,
461
- "created_at" BIGINT NOT NULL,
462
- "updated_at" BIGINT NOT NULL${V}
463
- )`]}function n0(z){let Z=JSON.parse(z.options),$=(V)=>V==null?null:Number(V);return{id:String(z.id),name:z.name==null?null:String(z.name),total:Number(z.total),pending:Number(z.pending),succeeded:Number(z.succeeded),failed:Number(z.failed),cancelled:Number(z.cancelled),failedJobIds:JSON.parse(z.failed_job_ids),cancelledAt:$(z.cancelled_at),finishedAt:$(z.finished_at),createdAt:Number(z.created_at),allowFailures:Z.allowFailures===!0,callbacks:Z.callbacks??{}}}function Sz(z){return JSON.stringify({allowFailures:z.allowFailures,callbacks:z.callbacks})}function o0(z){let Z=String(z?.message??z);return/does not exist|doesn't exist|unknown column|no such (table|column)|has no column/i.test(Z)}async function E0(z,Z){try{return await z}catch($){if(!o0($))throw $;throw Error(`Job batches need the "${Z}" table and the batch_id and progress columns of the jobs table, and the database says one is missing. Add the GemiJobBatch model and the two GemiJob fields from the docs (docs/jobs-and-queues.md#batches) and migrate, or call the driver's createTable().`,{cause:$})}}function RZ(z){return z}function e0(){return{jobs:[],jobsDir:"app/jobs",workflows:[],workflowsDir:"app/workflows",concurrency:1,driver:"memory",visibilityTimeout:300000,pollInterval:1000,unknownJobGrace:3600000,locks:"auto"}}var Tz=86400000;class S0{queue;workflows=new Map;steps=new Map;items=new Map;constructor(z){this.queue=z}async create(z){if(this.workflows.has(z.id))throw Error(`A workflow with the id ${z.id} already exists.`);this.prune(Tz);let Z=Date.now();this.workflows.set(z.id,{...z,status:"running",currentStep:null,progress:0,result:null,error:null,wakeAt:null,lockedBy:null,lockedUntil:null,retick:!1,createdAt:Z,updatedAt:Z}),this.steps.set(z.id,new Map),this.tick(z.id,0)}async find(z,Z={}){let $=this.workflows.get(z);if(!$)return null;return{workflow:{...$},steps:Z.steps===!1?[]:this.stepsOf(z)}}async acquire(z,Z,$){let V=this.workflows.get(z);if(!V)return{kind:"missing"};let X=Date.now();if(V.lockedBy!==null&&!B0(V.lockedBy,Z)&&(V.lockedUntil??0)>X)return V.retick=!0,{kind:"busy"};return V.lockedBy=Z,V.lockedUntil=X+$,V.retick=!1,{kind:"acquired",workflow:{...V},steps:this.stepsOf(z)}}async renew(z,Z,$){let V=this.workflows.get(z);if(!V||V.lockedBy!==Z)return!1;return V.lockedUntil=Date.now()+$,!0}async update(z,Z,$){let V=this.workflows.get(z);if(!V)return;if(Z.owner!==void 0&&V.lockedBy!==Z.owner)throw new I(z);let X=this.steps.get(z),Y=Z.key===void 0?void 0:X.get(Z.key),G=Date.now(),Q=$({workflow:{...V},step:Y?{...Y}:null,steps:Z.allSteps?this.stepsOf(z):[],items:Z.items===void 0?[]:this.itemsOf(z,Z.items,["running","retrying"],-1,1/0),now:G});if(Q.step){let J=X.get(Q.step.key);X.set(Q.step.key,{...Q.step,createdAt:J?.createdAt??G,updatedAt:G})}if(Q.items){let J=this.rowsOf(z,Q.items.step);for(let B of Q.items.delete??[])J.all.delete(B),J.open.delete(B);for(let B of[...Q.items.insert??[],...Q.items.update??[]]){let H=J.all.get(B.index);if(J.all.set(B.index,{...B,step:Q.items.step,createdAt:H?.createdAt??G,updatedAt:G}),B.status==="running"||B.status==="retrying")J.open.add(B.index);else J.open.delete(B.index)}}if(Q.batch)this.queue.enqueueBatch(Q.batch);for(let J of Q.cancelBatches??[])this.queue.cancelBatch(J);if(Q.workflow)Object.assign(V,Q.workflow);if(V.updatedAt=G,Q.tick)this.tick(z,Q.tick.delayMs);if(Q.unlock){if(V.lockedBy=null,V.lockedUntil=null,V.retick)V.retick=!1,this.tick(z,0)}return Q.result}async prune(z){let Z=Date.now()-z,$=0;for(let[V,X]of this.workflows)if(["completed","failed","cancelled"].includes(X.status)&&X.updatedAt<=Z)this.workflows.delete(V),this.steps.delete(V),this.items.delete(V),$++;return $}async listItems(z,Z,$){return this.itemsOf(z,Z,$.statuses,$.after??-1,$.limit)}itemsOf(z,Z,$,V,X){let Y=this.items.get(z)?.get(Z);if(!Y)return[];let Q=$.every((B)=>B==="running"||B==="retrying")?[...Y.open]:[...Y.all.keys()],J=[];for(let B of Q.sort((H,N)=>H-N)){if(B<=V)continue;let H=Y.all.get(B);if(!$.includes(H.status))continue;if(J.push({...H}),J.length>=X)break}return J}rowsOf(z,Z){let $=this.items.get(z);if(!$)this.items.set(z,$=new Map);let V=$.get(Z);if(!V)$.set(Z,V={all:new Map,open:new Set});return V}stepsOf(z){return[...this.steps.get(z)?.values()??[]].map((Z)=>({...Z}))}tick(z,Z){this.queue.enqueue({name:q,args:JSON.stringify([z]),delayMs:Math.max(0,Math.round(Z))})}}var Mz=86400000;class F0{entries=new Map;batches=new Map;workflows;listeners=new Set;timer;timerAt=1/0;seq=0;get waiting(){let z=0;for(let Z of this.entries.values())if(!Z.leased)z++;return z}get leased(){return this.entries.size-this.waiting}async enqueue(z){let Z=this.add(z);return this.changed(),Z}add({name:z,args:Z,delayMs:$=0,id:V=crypto.randomUUID()},X){let Y=Date.now();return this.entries.set(V,{job:{id:V,name:z,args:Z,attempt:0,createdAt:Y,...X===void 0?{}:{batchId:X}},until:Y+Math.max(0,$),leased:!1,seq:this.seq++,progress:0}),V}async enqueueBatch(z){this.recordBatch(z)}recordBatch(z){let Z=Date.now();this.forgetFinishedBatches(Z);let $=P0({...z,total:z.args.length,now:Z});for(let Y of z.args)this.add({name:z.job,args:Y},z.id);let{record:V,calls:X}=s($,$,Z);this.batches.set(z.id,V);for(let Y of X)this.add(Y);this.changed()}async findBatch(z,Z={}){let $=this.batches.get(z);if(!$)return null;if(Z.progress===!1||$.pending===0)return w($);let V=0;for(let X of this.entries.values())if(X.job.batchId===z)V+=X.progress;return w($,V)}async cancelBatch(z){return this.cancelBatchNow(z)}cancelBatchNow(z){let Z=this.batches.get(z);if(!Z||Z.finishedAt!==null||Z.cancelledAt!==null)return!1;let $=Date.now(),V=i(Z,$,this.cancelWaiting(z));return this.save(Z,V,$),this.changed(),!0}workflowStore(){return this.workflows??=new S0({enqueue:(z)=>{this.add(z),this.changed()},enqueueBatch:(z)=>this.recordBatch(z),cancelBatch:(z)=>void this.cancelBatchNow(z)}),this.workflows}async reportProgress(z,Z){let $=this.current(z);if($)$.progress=g(Z)}async claim(z,Z){let $=Date.now(),V=[...this.entries.values()].filter((X)=>X.until<=$).sort((X,Y)=>X.until-Y.until||X.seq-Y.seq).slice(0,Math.max(0,z));for(let X of V)X.job={...X.job,attempt:X.job.attempt+1},X.leased=!0,X.until=$+Z.visibilityTimeoutMs;if(V.length>0)this.schedule();return V.map((X)=>({...X.job}))}async complete(z){let Z=this.current(z);if(!Z)return;this.entries.delete(z.id),this.count(Z,"succeeded"),this.schedule()}async fail(z,Z){let $=this.current(z);if(!$)return;let V=$.job.batchId===void 0?void 0:this.batches.get($.job.batchId),X=Z.cancelled===!0||Z.retryInMs!==null&&V?.cancelledAt!=null;if(Z.retryInMs===null||X){this.entries.delete(z.id),this.count($,X?"cancelled":"failed"),this.schedule();return}$.leased=!1,$.until=Date.now()+Math.max(0,Z.retryInMs),$.seq=this.seq++,$.progress=0,this.changed()}async release(z,Z){let $=this.current(z);if(!$)return;$.job={...$.job,attempt:$.job.attempt-1},$.leased=!1,$.until=Date.now()+Math.max(0,Z.retryInMs),$.seq=this.seq++,this.changed()}async heartbeat(z,Z){let $=Date.now()+Z.visibilityTimeoutMs;for(let V of z){let X=this.current(V);if(X)X.until=$}this.schedule()}count(z,Z){let $=z.job.batchId;if($===void 0)return;let V=this.batches.get($);if(!V)return;let X=Date.now(),Y=U0(V,Z,z.job.id);if(K0(V,Y))Y=i(Y,X,this.cancelWaiting($));this.save(V,Y,X),this.changed()}save(z,Z,$){let{record:V,calls:X}=s(z,Z,$);this.batches.set(V.id,V);for(let Y of X)this.add(Y)}cancelWaiting(z){let Z=0;for(let[$,V]of this.entries)if(V.job.batchId===z&&!V.leased)this.entries.delete($),Z++;return Z}forgetFinishedBatches(z){for(let[Z,$]of this.batches)if($.finishedAt!==null&&z-$.finishedAt>Mz)this.batches.delete(Z)}subscribe(z){return this.listeners.add(z),()=>void this.listeners.delete(z)}current(z){let Z=this.entries.get(z.id);if(!Z||!Z.leased||Z.job.attempt!==z.attempt)return;return Z}changed(){this.schedule();let z=Date.now();for(let Z of this.entries.values())if(Z.until<=z){this.wake();return}}wake(){for(let z of[...this.listeners])z()}schedule(){let z=Date.now(),Z=1/0;for(let $ of this.entries.values())if($.until>z&&$.until<Z)Z=$.until;if(Z===this.timerAt)return;if(clearTimeout(this.timer),this.timer=void 0,this.timerAt=Z,Z===1/0)return;this.timer=setTimeout(()=>{this.timer=void 0,this.timerAt=1/0,this.changed()},Z-z),this.timer.unref?.()}}function V0(z,Z){let $=Array.isArray(z)?z[Math.min(Z,z.length)-1]:z;return Math.max(0,$??0)}class Qz extends Error{step;batch;constructor(z,Z,$){super(Z);this.step=z;this.batch=$;this.name="StepFailedError"}}class M0 extends Error{step;constructor(z){super(`No signal "${z}" arrived before its timeout.`);this.step=z;this.name="WaitTimeoutError"}}class x0 extends Error{constructor(z,Z){super(`Step "${z}" took longer than its timeout of ${Z}ms.`);this.name="StepTimeoutError"}}class v0 extends Error{constructor(z){super(`Workflow ${z} was cancelled.`);this.name="WorkflowCancelledError"}}class m extends Error{constructor(){super("The workflow is suspended until a step can continue. Rethrow this error if you catch it.");this.name="WorkflowSuspended"}}var zz=Symbol("done");class g0{tick;workflowId;steps;seen=new Set;pending=new Set;suspension;lost=!1;cancelled=!1;current=null;constructor(z){this.tick=z;this.workflowId=z.workflowId,this.steps=new Map(z.steps.map((Z)=>[Z.key,Z]))}run(z,Z,$={}){return this.track(z,()=>this.runStep(z,Z,$))}sleep(z,Z){let $=n(Z);return this.track(z,()=>this.sleepStep(z,$))}waitFor(z,Z={}){let $=Z.timeout===void 0?void 0:n(Z.timeout);return this.track(z,()=>this.waitStep(z,$))}batch(z,Z,$,V={}){return this.track(z,()=>this.batchStep(z,Z,$,V))}each(z,Z,$){return this.track(z,()=>this.eachStep(z,Z,$))}async progress(z){let Z=g(z);this.assertRunning();let $=this.write(void 0,()=>({result:void 0,workflow:{progress:Z}}));this.remember($),await $}async settled(){while(this.pending.size>0)await Promise.allSettled(this.pending)}track(z,Z){if(typeof z!=="string"||z.length===0||z.length>191)throw TypeError(`A step key is a string of 1 to 191 characters; got ${JSON.stringify(z)}.`);if(this.seen.has(z))throw Error(`Two steps of workflow ${this.workflowId} use the key "${z}". Each step needs a key of its own, or the second would return the first one's result.`);this.seen.add(z),this.assertRunning();let $=Z();return this.remember($),$}remember(z){this.pending.add(z);let Z=()=>void this.pending.delete(z);z.then(Z,Z)}assertRunning(){if(this.lost)throw new I(this.workflowId);if(this.suspension)throw new m}suspend(z,Z){if(!this.suspension)this.suspension={status:z,wakes:[]};if(Z!=null)this.suspension.wakes.push(Z);throw new m}async write(z,Z,$={}){let V;try{V=await this.tick.store.update(this.tick.workflowId,{owner:this.tick.owner,...z===void 0?{}:{key:z},...$.items&&z!==void 0?{items:z}:{}},(X)=>{if(X.workflow.status==="cancelling"&&!this.tick.cancelling)return{result:zz};let Y=Z(X);return{...Y,result:{value:Y.result}}})}catch(X){if(X instanceof I)this.lost=!0;throw X}if(V===void 0)throw this.lost=!0,new I(this.tick.workflowId);if(V===zz)this.cancelled=!0,this.suspend("waiting");return V.value}record(z,Z,$){let V={workflowId:this.tick.workflowId,key:z,status:"running",attempt:0,output:null,error:null,batchId:null,wakeAt:null,startedAt:null,finishedAt:null,createdAt:0,updatedAt:0,...Z,...$};return this.steps.set(z,V),V}mismatch(z,Z,$){throw Error(`Step "${z}" of workflow ${this.tick.workflowId} was recorded as a ${Z} step, and is now used as ${$}. A key belongs to one step; rename one of them.`)}async runStep(z,Z,$){let V=Math.max(1,Math.floor($.attempts??3)),X=$.timeout===void 0?void 0:n($.timeout),Y=this.steps.get(z);if(Y?.status==="completed")return h(Y.output);if(Y?.status==="failed")throw c(z,Y);if(Y?.status==="retrying"&&Y.wakeAt!==null&&Y.wakeAt>Date.now())this.current=z,this.suspend("sleeping",Y.wakeAt);for(;;){let G=await this.write(z,({workflow:U,step:P,now:A})=>{if(P?.status==="completed")return{result:{kind:"done",output:P.output}};if(P?.status==="failed")return{result:{kind:"failed",step:P}};if(P&&P.status!=="running"&&P.status!=="retrying")this.mismatch(z,P.status,"step.run");if(P?.status==="retrying"&&P.wakeAt!==null&&P.wakeAt>A)return{result:{kind:"wait",wakeAt:P.wakeAt}};let T=(P?.attempt??0)+1;if(T>V){let o=this.record(z,P,{status:"failed",error:`Attempt ${T-1} of ${V} never finished, most likely because the process running it exited.`+(P?.error?` The last error was: ${P.error}`:""),finishedAt:A,wakeAt:null});return{result:{kind:"failed",step:o},step:o}}let E=this.record(z,P,{status:"running",attempt:T,startedAt:A,finishedAt:null,wakeAt:null});return{result:{kind:"run",attempt:T},step:E,workflow:U.status==="cancelling"?{currentStep:z}:{currentStep:z,status:"running"}}});if(this.current=z,G.kind==="done")return h(G.output);if(G.kind==="failed")throw c(z,G.step);if(G.kind==="wait")this.suspend("sleeping",G.wakeAt);let Q=G.attempt,J,B,H=!0;try{J=await this.execute(z,Z,Q,X)}catch(U){B=U}if(this.cancelled)throw new m;let N=null;if(B===void 0)try{N=Y0(J,`The result of step "${z}"`)}catch(U){B=U,H=!1}if(B===void 0)return await this.write(z,({step:U,now:P})=>({result:void 0,step:this.record(z,U,{status:"completed",output:N,error:null,wakeAt:null,finishedAt:P})})),h(N);let F=r(B);if(H&&Q<V){let U=V0($.backoff??0,Q),P=await this.write(z,({step:A,now:T})=>{let E=U>0?T+U:null;return{result:E,step:this.record(z,A,{status:"retrying",error:F,wakeAt:E})}});if(P!==null)this.suspend("sleeping",P);continue}let K=await this.write(z,({step:U,now:P})=>{let A=this.record(z,U,{status:"failed",error:F,wakeAt:null,finishedAt:P});return{result:A,step:A}});throw c(z,K)}}async execute(z,Z,$,V){let X=new AbortController,Y={idempotencyKey:`${this.tick.workflowId}:${z}`,attempt:$,signal:X.signal},G=Promise.resolve().then(()=>Z(Y)),Q,J,B=new Promise((H,N)=>{let F=(K)=>{X.abort(K),N(K)};if(V!==void 0)Q=setTimeout(()=>F(new x0(z,V)),V);if(!this.tick.cancelling)J=setInterval(()=>{this.tick.store.find(this.tick.workflowId,{steps:!1}).then((K)=>{if(K?.workflow.status!=="cancelling"||X.signal.aborted)return;if(this.cancelled=!0,!this.suspension)this.suspension={status:"waiting",wakes:[]};F(new v0(this.tick.workflowId))}).catch(()=>{})},this.tick.cancelCheckMs),J.unref?.()});try{return await Promise.race([G,B])}finally{clearTimeout(Q),clearInterval(J),G.catch(()=>{}),B.catch(()=>{})}}async sleepStep(z,Z){let $=this.steps.get(z);if($?.status==="completed")return;if(this.current=z,$?.status==="sleeping"&&$.wakeAt!==null&&$.wakeAt>Date.now())this.suspend("sleeping",$.wakeAt);let V=await this.write(z,({step:X,now:Y})=>{if(X?.status==="completed")return{result:null};if(X&&X.status!=="sleeping")this.mismatch(z,X.status,"step.sleep");let G=X?.wakeAt??Y+Z;if(G<=Y)return{result:null,step:this.record(z,X,{status:"completed",wakeAt:G,startedAt:X?.startedAt??Y,finishedAt:Y})};if(X)return{result:G};return{result:G,step:this.record(z,null,{status:"sleeping",wakeAt:G,startedAt:Y}),workflow:{currentStep:z}}});if(V!==null)this.suspend("sleeping",V)}async waitStep(z,Z){let $=this.steps.get(z);if($?.status==="completed")return h($.output);if($?.status==="timed_out")throw new M0(z);if(this.current=z,$?.status==="waiting"&&($.wakeAt===null||$.wakeAt>Date.now()))this.suspend("waiting",$.wakeAt);let V=await this.write(z,({step:X,now:Y})=>{if(X?.status==="completed")return{result:{kind:"value",output:X.output}};if(X?.status==="timed_out")return{result:{kind:"timeout"}};if(X?.status==="signalled")return{result:{kind:"value",output:X.output},step:this.record(z,X,{status:"completed",wakeAt:null,startedAt:X.startedAt??Y,finishedAt:Y})};if(X&&X.status!=="waiting")this.mismatch(z,X.status,"step.waitFor");if(X){if(X.wakeAt!==null&&X.wakeAt<=Y)return{result:{kind:"timeout"},step:this.record(z,X,{status:"timed_out",finishedAt:Y})};return{result:{kind:"wait",wakeAt:X.wakeAt}}}let G=Z===void 0?null:Y+Z;return{result:{kind:"wait",wakeAt:G},step:this.record(z,null,{status:"waiting",wakeAt:G,startedAt:Y}),workflow:{currentStep:z}}});if(V.kind==="value")return h(V.output);if(V.kind==="timeout")throw new M0(z);this.suspend("waiting",V.wakeAt)}async eachStep(z,Z,$){let V=Z.count;if(!Number.isSafeInteger(V)||V<0||V>Zz)throw TypeError(`step.each "${z}" needs a count that is a whole number from 0 to ${Zz}; got ${String(V)}.`);let X=Math.max(1,Math.floor(Z.concurrency??1)),Y=Math.max(1,Math.floor(Z.attempts??3)),G=Z.timeout===void 0?void 0:n(Z.timeout),Q=Z.tickBudget===void 0?xz:n(Z.tickBudget),J=Z.progress!==!1,B=this.tick.store;if(!B.listItems)throw Error("This queue's workflow store does not support step.each. The memory and database drivers do.");let H=this.steps.get(z);if(H?.status==="completed")return Xz(H.output);if(H?.status==="failed")throw c(z,H);if(H&&H.status!=="iterating")this.mismatch(z,H.status,"step.each");if(this.current=z,this.tick.durable===!1)fz();let N=await this.write(z,({workflow:R,step:_,items:M,now:v})=>{if(_?.status==="completed")return{result:{kind:"done",output:_.output}};if(_&&_.status!=="iterating")this.mismatch(z,_.status,"step.each");let u=_?Jz(_.output):jz(V);return{result:{kind:"go",state:u,open:M},..._?{}:{step:this.record(z,null,{status:"iterating",output:Vz(u),startedAt:v})},workflow:R.status==="cancelling"?{currentStep:z}:{currentStep:z,status:"running"}}},{items:!0});if(N.kind==="done")return Xz(N.output);let F=N.state;if(F.count!==V)qz(this.workflowId,z,F.count,V);let K=F.count,U=new Map(N.open.map((R)=>[R.index,R])),P=[],A=new Map,T=Date.now()+Q,E=new AbortController,o=setInterval(()=>{B.find(this.workflowId,{steps:!1}).then((R)=>{if(R?.workflow.status!=="cancelling"||E.signal.aborted)return;if(this.cancelled=!0,!this.suspension)this.suspension={status:"waiting",wakes:[]};E.abort(new v0(this.workflowId))}).catch(()=>{})},this.tick.cancelCheckMs);o.unref?.();let Rz=async(R)=>{let _=null,M=new AbortController,v=()=>M.abort(E.signal.reason);E.signal.addEventListener("abort",v,{once:!0});let u,L0=new Promise((D,W)=>{if(M.signal.addEventListener("abort",()=>W(M.signal.reason),{once:!0}),G!==void 0)u=setTimeout(()=>M.abort(new x0(`${z}[${R.index}]`,G)),G)}),k=(async()=>{let D=await Z.item(R.index);_=hz(Z.key?Z.key(D,R.index):R.index);let W={idempotencyKey:`${this.workflowId}:${z}:${_}`,attempt:R.attempt,signal:M.signal,index:R.index,key:_,skip:(S,e)=>{throw new j0(S,e)}};await $(D,W)})(),f,O=!1;try{await Promise.race([k,L0])}catch(D){O=!0,f=D}finally{clearTimeout(u),E.signal.removeEventListener("abort",v),k.catch(()=>{}),L0.catch(()=>{})}if(E.signal.aborted)return;let j=Date.now();if(!O){P.push({index:R.index,row:null,counter:"succeeded"});return}if(f instanceof j0){let D=null,W=X0(String(f.reason));try{D=yz(f.data)}catch(S){W=X0(`${W} (${r(S)})`)}P.push({index:R.index,row:{...R,key:_,status:"skipped",error:W,output:D,wakeAt:null,finishedAt:j},counter:"skipped"});return}let L=X0(r(f),2000);if(R.attempt<Y){let D=V0(Z.backoff??0,R.attempt);P.push({index:R.index,row:{...R,key:_,status:"retrying",error:L,wakeAt:j+D},counter:null});return}P.push({index:R.index,row:{...R,key:_,status:"failed",error:L,wakeAt:null,finishedAt:j},counter:"failed"})};try{for(;;){let R=Date.now(),_=R>=T||N0()||this.cancelled,M=[],v=0;if(!_){let O=X-A.size,j=new Set(P.map((D)=>D.index));for(let D of[...U.values()].sort((W,S)=>W.index-S.index)){if(O<=0)break;if(A.has(D.index)||j.has(D.index))continue;if(D.status==="running"||(D.wakeAt??0)<=R)M.push(D),O--}let L=X+$z-U.size;v=Math.max(0,Math.min(O,K-F.next,L))}if(P.length>0||M.length>0||v>0){let O=P.splice(0,P.length),j=await this.write(z,({step:L,now:D})=>{let W={...F},S={step:z,insert:[],update:[],delete:[]},e=[],u0=[];for(let C of O){if(C.counter)W[C.counter]++;if(C.row===null)S.delete.push(C.index);else S.update.push(C.row)}for(let C of M){if(C.attempt+1>Y){let k0={...C,status:"failed",error:X0(`Attempt ${C.attempt} of ${Y} never finished, most likely because the process running it exited.`+(C.error?` The last error was: ${C.error}`:""),2000),wakeAt:null,finishedAt:D};W.failed++,S.update.push(k0),u0.push(k0);continue}let z0={...C,status:"running",attempt:C.attempt+1,wakeAt:null,startedAt:D};S.update.push(z0),e.push(z0)}for(let C=0;C<v;C++){let z0=gz(this.workflowId,z,W.next+C,D);S.insert.push(z0),e.push(z0)}W.next+=v;let Dz=W.succeeded+W.skipped+W.failed;return{result:{next:W,started:e,closed:u0},step:this.record(z,L,{status:"iterating",output:Vz(W)}),items:S,...J?{workflow:{progress:K===0?1:g(Dz/K)}}:{}}});F=j.next;for(let L of O)if(L.row?.status==="retrying")U.set(L.index,L.row);else U.delete(L.index);for(let L of j.closed)U.delete(L.index);for(let L of j.started)U.set(L.index,L),A.set(L.index,Rz(L).finally(()=>A.delete(L.index)))}if(A.size>0){await Promise.race(A.values());continue}if(P.length>0)continue;if(this.cancelled)throw new m;if(F.next>=K&&U.size===0)break;if(_)this.suspend("running",Date.now());let u=Date.now();if(F.next<K&&U.size<X+$z||[...U.values()].some((O)=>O.status==="running"||(O.wakeAt??0)<=u))continue;let k=1/0;for(let O of U.values())k=Math.min(k,O.wakeAt??0);let f=k-Date.now();if(f<=Math.min(vz,T-Date.now())){await new Promise((O)=>setTimeout(O,Math.max(0,f)));continue}this.suspend("sleeping",k)}}finally{if(clearInterval(o),!E.signal.aborted)E.abort(new m)}let m0=await B.listItems(this.workflowId,z,{statuses:["failed","skipped"],limit:T0+1}),_0={...h0(F),problems:m0.slice(0,T0).map(y0),moreProblems:m0.length>T0},Az=JSON.stringify({$each:F,problems:_0.problems,moreProblems:_0.moreProblems});return await this.write(z,({step:R,now:_})=>({result:void 0,step:this.record(z,R,{status:"completed",output:Az,finishedAt:_}),...J?{workflow:{progress:1}}:{}})),_0}async batchStep(z,Z,$,V){let X=V.allowFailures===!0,Y=this.steps.get(z);if(Y?.status==="completed")return h(Y.output);if(Y?.status==="failed")throw c(z,Y);if(Y&&Y.status!=="batching")this.mismatch(z,Y.status,"step.batch");if(this.current=z,!Y){let N=this.tick.buildBatch(Z,$,{name:V.name??`workflow:${this.tick.workflowId}:${z}`,allowFailures:X});if(Y=await this.write(z,({step:F,now:K})=>{if(F)return{result:F};let U=this.record(z,null,{status:"batching",batchId:N.id,startedAt:K});return{result:U,step:U,batch:N,workflow:{currentStep:z}}}),this.tick.scheduled(),Y.status==="completed")return h(Y.output);if(Y.status==="failed")throw c(z,Y)}let G=Y.batchId===null?null:await this.tick.findBatch(Y.batchId);if(G&&G.finishedAt===null)this.suspend("waiting");let Q=G!==null&&G.cancelledAt===null&&(G.failed===0||X),J=G===null?null:JSON.stringify(G),B=Q?null:G===null?`The batch of step "${z}" (${Y.batchId}) no longer exists.`:`The batch of step "${z}" failed: ${G.failed} failed and ${G.cancelled} cancelled of ${G.total}.`,H=await this.write(z,({step:N,now:F})=>{let K=this.record(z,N,{status:Q?"completed":"failed",output:J,error:B,finishedAt:F});return{result:K,step:K}});if(!Q)throw c(z,H);return G}}function c(z,Z){let $=Z.batchId!==null&&Z.output!==null?JSON.parse(Z.output):void 0;return new Qz(z,$?Z.error??`Step "${z}" failed.`:`Step "${z}" failed: ${Z.error??"unknown error"}`,$)}function Y0(z,Z){if(z===void 0)return null;let $=JSON.stringify(z);if($===void 0)throw TypeError(`${Z} cannot be stored: JSON has no form for it.`);let V=Buffer.byteLength($,"utf8");if(V>W0)throw RangeError(`${Z} is ${V} bytes as JSON, over the ${W0}-byte limit. Store it elsewhere and return its id.`);return $}function h(z){return z===null?void 0:JSON.parse(z)}function r(z){return z instanceof Error?z.message:String(z)}var Zz=2147483647,xz=30000,$z=100,vz=1000,T0=100;class j0 extends Error{reason;data;constructor(z,Z){super(`Skipped: ${z}`);this.reason=z;this.data=Z;this.name="ItemSkipped"}}function jz(z){return{count:z,next:0,succeeded:0,skipped:0,failed:0}}function Vz(z){return JSON.stringify({$each:z})}function Jz(z){let Z=z===null?null:JSON.parse(z);if(!Z?.$each)throw Error("A step.each step has no state.");return Z.$each}function Bz(z){if(z===null||!z.startsWith('{"$each"'))return null;try{return h0(Jz(z))}catch{return null}}function h0(z){return{total:z.count,done:z.succeeded+z.skipped+z.failed,succeeded:z.succeeded,skipped:z.skipped,failed:z.failed}}function Xz(z){let Z=JSON.parse(z??"null");return{...h0(Z.$each),problems:Z.problems??[],moreProblems:Z.moreProblems===!0}}function y0(z){let Z={index:z.index,key:z.key,status:z.status==="skipped"?"skipped":"failed",reason:X0(z.error??""),attempt:z.attempt};if(z.output!==null)Z.data=JSON.parse(z.output);return Z}function gz(z,Z,$,V){return{workflowId:z,step:Z,index:$,key:null,status:"running",attempt:1,error:null,output:null,wakeAt:null,startedAt:V,finishedAt:null,createdAt:V,updatedAt:V}}function hz(z){let Z=typeof z==="number"&&Number.isFinite(z)?String(z):z;if(typeof Z!=="string"||Z.length===0||Z.length>191)throw TypeError(`An item key is a string of 1 to 191 characters, or a number; got ${JSON.stringify(z)}.`);return Z}function X0(z,Z=500){return z.length<=Z?z:`${z.slice(0,Z-1)}\u2026`}function yz(z){if(z===void 0)return null;let Z=JSON.stringify(z);if(Z===void 0)throw TypeError("its data has no JSON form, so it was not kept");if(Buffer.byteLength(Z,"utf8")>1024)throw RangeError("its data is over 1 KB as JSON, so it was not kept");return Z}var Yz=!1;function fz(){if(Yz||Bun.env.NODE_ENV!=="production")return;Yz=!0,console.warn("[gemi] step.each is running on a queue whose driver keeps nothing across restarts (the memory driver), so a deploy or a crash loses the workflow and the rest of its list. Use the database driver for work that must finish.")}var Gz=new Set;function qz(z,Z,$,V){let X=`${z}:${Z}`;if(Gz.has(X))return;Gz.add(X),console.warn(`[gemi] step.each "${Z}" of workflow ${z} was started with a count of ${$} and is now given ${V}. It goes on with ${$}: the count is fixed when the step first runs.`)}function R0(z){return z==="completed"||z==="failed"||z==="cancelled"}import{AsyncResource as bz}from"async_hooks";import{isMainThread as mz}from"worker_threads";function uz(){let z=process.env.APP_DIR,Z=process.env.ROOT_DIR,$=Bun.env.NODE_ENV==="production"?`${Z}/dist/server/bootstrap.mjs`:`${z}/bootstrap.ts`,V=new File([`
464
- import { app } from "${$}"
465
- self.onmessage = async (event) => {
466
- const clone = app.clone()
467
- let result = null;
468
- let error = null;
469
- try {
470
- result = await clone.dispatchJob(event.data.jobName, event.data.args)
471
- } catch (err) {
472
- error = err
473
- }
474
- clone.destroy()
475
- if(error) {
476
- self.postMessage({error});
477
- } else {
478
- self.postMessage({result});
479
- }
480
- };
481
- `],"worker.ts"),X=URL.createObjectURL(V);return new Worker(X)}async function kz(z,Z){let $=uz();return $.postMessage({jobName:z,args:Z}),await new Promise((V,X)=>{$.onmessage=(Y)=>{let G=Y.data;if("error"in G)X(G.error);else V(G.result)}})}var pz=new bz("gemi.queue"),wz=60000;class t{static token="queue";jobs={};config;driver;application;inFlight=new Map;state="idle";looping=!1;claiming;woken=!1;claimFailures=0;resume;unsubscribe;heartbeatTimer;releasedNames=new Set;lockManager;workflowRuntime;constructor(z={},Z={}){if(this.config=Uz(e0(),z),this.application=Z.application,this.driver=sz(this.config.driver,this.application),this.useJobs(this.config.jobs),this.config.workflows.length>0)this.useWorkflows(this.config.workflows)}useJobs(z){this.config.jobs=z,this.jobs={};for(let Z of z)this.claim(Z);this.registerTickJob()}useWorkflows(z){this.config.workflows=z,this.workflows.use(z),this.registerTickJob()}get registeredWorkflows(){return[...this.config.workflows]}get workflows(){return this.workflowRuntime??=new b0(this),this.workflowRuntime}get boundApplication(){return this.application}registerTickJob(){if(!this.workflowRuntime||Object.keys(this.workflowRuntime.workflows).length===0)return;let z=this.workflowRuntime.tickJob;if(this.jobs[z.name]&&this.jobs[z.name]!==z){console.error(`A queued job is named "${z.name}", which the workflow runtime uses. Workflows will not run until it is renamed.`);return}this.jobs[z.name]=z}registerJob(z){this.config.jobs=[...this.config.jobs,z],this.claim(z)}claim(z){if(this.jobs[z.name]){console.error(`Two queued jobs are named "${z.name}" \u2014 the first is registered `+"and this one is not, so dispatching either would have run one of them. A class name is the queue's key, so only one job can hold it. Rename one.");return}this.jobs[z.name]=z}get registeredJobs(){return[...this.config.jobs]}dispatchJob(z,Z){if(this.jobs[z])return new this.jobs[z]().run(JSON.parse(Z))}push(z,Z,$={}){let V=this.uniqueKey(z,Z);if(V)return this.pushUnique(z,Z,V,$);let X=this.driver.joinsTransaction?.()===!0;if(!X){let Y=Bun.randomUUIDv7();if(y(()=>this.record(z,Z,{id:Y,reportFailure:!0,committed:!0}).then(()=>{},()=>{})))return Promise.resolve(Y)}return this.record(z,Z,{reportFailure:$.reportFailure,joins:X})}pushBatch(z,Z,$={}){let V=this.buildBatch(z,Z,$),X={id:V.id,total:Z.length},Y=this.driver.joinsTransaction?.()===!0;if(!Y){if(y(()=>this.recordBatch(V,{committed:!0}).then(()=>{},()=>{})))return Promise.resolve(X)}return this.recordBatch(V,{joins:Y}).then(()=>X)}buildBatch(z,Z,$={}){if(!this.driver.enqueueBatch)throw Error("This queue's driver does not support batches. The memory and database drivers do.");if(new z().worker)throw Error(`${z.name} is a worker job, and a worker job cannot be dispatched in a batch: its thread has no way to report progress or reach the batch.`);if(z.prototype.uniqueId!==d.prototype.uniqueId)throw Error(`${z.name} is unique (it defines uniqueId), and a unique job cannot be dispatched in a batch: a duplicate would resolve to a job outside the batch, and the batch would wait for it forever.`);let X={};for(let Y of["then","catch","finally"]){let G=$[Y];if(G===void 0)continue;if(typeof G?.name!=="string"||!Array.isArray(G.args))throw Error(`The batch's ${Y} callback is not a job call. Build it with SomeJob.with(...args).`);X[Y]={name:G.name,args:G.args}}return{id:Bun.randomUUIDv7(),name:$.name??null,job:z.name,args:Z,allowFailures:$.allowFailures===!0,callbacks:X}}recordBatch(z,Z){let $=this.driver.enqueueBatch(z);this.startIfIdle();let V=()=>!this.driver.subscribe&&this.state==="running"&&this.wake(),X=Z.joins===!0&&y(V);return $.then(()=>X||V(),(Y)=>{if(!Z.committed)return;console.error(`[gemi] The queue driver could not record a batch of ${z.job}, which was held until its transaction committed. The transaction stays committed; the batch's jobs did not run and will not be retried.`,Y)}),$}async findBatch(z){if(!this.driver.findBatch)throw Error("This queue's driver does not support batches.");return this.driver.findBatch(z)}async cancelBatch(z){if(!this.driver.cancelBatch)throw Error("This queue's driver does not support batches.");let Z=await this.driver.cancelBatch(z);if(Z)this.claimSoon();return Z}get locks(){return this.lockManager??=new Kz(this.resolveLockStore()),this.lockManager}resolveLockStore(){let z=this.config.locks;if(z==="auto"){let Z=this.driver.lockStore?.();if(Z)return Z;if(this.durable)console.warn('[gemi] The queue driver keeps no locks, so unique jobs, withoutOverlapping and onOneServer only hold within this process. Set the queue slice\'s `locks` to "database" or a LockStore.');return new J0}if(z==="memory")return new J0;if(z==="database"||typeof z==="function"){if(!this.application&&(z==="database"||z.length>0))throw Error("The queue's locks need the application they belong to, and this QueueManager was built without one. Pass { application }.");if(z==="database")return new Z0(this.application.make(q0));return z(this.application)}if(typeof z==="string")throw Error(`Unknown queue locks "${z}". The queue slice's locks is "auto", "memory", "database", a LockStore, or a function returning one.`);return z}uniqueKey(z,Z){if(z.prototype.uniqueId===d.prototype.uniqueId)return;let $=new z,V=$.uniqueId(...JSON.parse(Z));if(V===void 0||V===null||V==="")return;return{key:Hz(z.name,V),ttl:Math.max(1,$.uniqueFor)}}pushUnique(z,Z,$,V){let X=Bun.randomUUIDv7();if(y(()=>this.recordUnique(z,Z,$,X,{report:!0,committed:!0}).then(()=>{},()=>{})))return Promise.resolve(X);return this.recordUnique(z,Z,$,X,{report:V.reportFailure!==!1,committed:!1})}recordUnique(z,Z,$,V,X){let Y=this.locks.store,G=(async()=>{for(let Q=0;Q<5;Q++){if(await Y.acquire($.key,V,$.ttl)!==null)try{return await this.record(z,Z,{id:V,reportFailure:!1})}catch(B){throw await Y.release($.key,V).catch(()=>{}),B}let J=await Y.holder($.key);if(J)return J.owner}throw Error(`The unique key "${$.key}" kept changing hands, so ${z.name} was not queued.`)})();return G.catch((Q)=>{if(!X.report)return;console.error(`[gemi] The queue could not record the unique job ${z.name}`+(X.committed?", which was held until its transaction committed. The transaction stays committed; the job did not run and will not be retried.":", so it did not run and will not be retried."),Q)}),G}async releaseUnique(z,Z,$){if(z.uniqueId===d.prototype.uniqueId)return;try{let V=z.uniqueId(...Z);if(V===void 0||V===null||V==="")return;await this.locks.store.release(Hz($.name,V),$.id)}catch(V){console.error(`[gemi] Could not free the unique key of ${$.name} (${$.id}); it frees itself after uniqueFor.`,V)}}record(z,Z,$){let V=this.driver.enqueue({name:z.name,args:Z,...$.id===void 0?{}:{id:$.id}});this.startIfIdle();let X=()=>!this.driver.subscribe&&this.state==="running"&&this.wake(),Y=$.joins===!0&&y(X);return V.then(()=>Y||X(),(G)=>{if($.reportFailure===!1)return;console.error(`[gemi] The queue driver could not record ${z.name}`+($.committed?", which was held until its transaction committed. The transaction stays committed; the job did not run and will not be retried.":", so it did not run and will not be retried."),G)}),V}async retryDead(z){if(!this.driver.retryDead)throw Error("This queue's driver keeps nothing of a dead-lettered job, so there is nothing to retry. The database driver keeps them.");let Z=await this.driver.retryDead(z);if(Z)this.claimSoon();return Z}startIfIdle(){if(this.state==="idle"&&(!this.durable||this.mayClaimHere()))this.start()}claimSoon(){if(this.startIfIdle(),!this.driver.subscribe&&this.state==="running")this.wake()}start(){if(this.state==="running")return;if(this.state="running",this.durable&&this.application&&this.mayClaimHere()&&!cz())globalThis.__gemiDevQueue=this;if(this.unsubscribe=this.driver.subscribe?.(()=>this.wake()),this.looping)return this.wake();pz.runInAsyncScope(()=>void this.loop())}async drain(z=1/0){if(this.state="stopped",globalThis.__gemiDevQueue===this)globalThis.__gemiDevQueue=void 0;this.unsubscribe?.(),this.unsubscribe=void 0,this.wake();let Z,$=new Promise((X)=>{if(z!==1/0)Z=setTimeout(X,z)}),V=(async()=>{await this.claiming?.catch(()=>{}),await Promise.allSettled([...this.inFlight.values()].map((X)=>X.done))})();return await Promise.race([V,$]),clearTimeout(Z),{unfinished:[...this.inFlight.values()].map((X)=>({...X.job}))}}stop(){return this.drain(0)}get running(){return this.inFlight.size}async loop(){this.looping=!0;try{await this.claimWhileRunning()}finally{this.looping=!1}}async claimWhileRunning(){while(this.state==="running"){let z=this.durable&&N0()?0:this.config.concurrency-this.inFlight.size;if(z>0){this.woken=!1;let Z=this.driver.claim(z,{...this.lease(),registered:{names:Object.keys(this.jobs),graceMs:this.config.unknownJobGrace}});this.claiming=Z;let $=[];try{$=await Z,this.claimFailures=0}catch(V){this.claimFailures++,console.error(`The queue could not claim jobs from its driver; it will try again in ${this.retryDelay()}ms.`,V)}finally{this.claiming=void 0}for(let V of $)this.execute(V);if($.length===z)continue;if(this.woken&&this.inFlight.size<this.config.concurrency)continue}await this.sleep()}}sleep(){return new Promise((z)=>{let Z,$=this.claimFailures>0?this.retryDelay():this.driver.subscribe?void 0:this.config.pollInterval;if($!==void 0)Z=setTimeout(()=>this.wake(),$),Z.unref?.();this.resume=()=>{clearTimeout(Z),z()}})}retryDelay(){let z=Math.min(Math.max(0,this.claimFailures-1),30);return Math.min(this.config.pollInterval*2**z,wz)}wake(){this.woken=!0;let z=this.resume;this.resume=void 0,z?.()}get durable(){return!(this.driver instanceof F0)}mayClaimHere(){return!this.application||dz()}lease(){return{visibilityTimeoutMs:this.config.visibilityTimeout}}execute(z){let Z=`${z.id}:${z.attempt}`,$=()=>this.run(z),V=(this.application?Pz.run(this.application,$):$()).catch((X)=>{console.error(`The queue could not record the outcome of ${z.name}.`,X)}).finally(()=>{this.inFlight.delete(Z),this.wake()});this.inFlight.set(Z,{job:z,done:V}),this.heartbeat()}heartbeat(){let z=this.driver;if(!z.heartbeat||this.heartbeatTimer)return;this.heartbeatTimer=setInterval(()=>{if(this.inFlight.size===0){clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0;return}let Z=[...this.inFlight.values()].map(($)=>$.job);z.heartbeat(Z,this.lease()).catch(($)=>{console.error("The queue could not extend its job leases.",$)})},Math.max(1,Math.floor(this.config.visibilityTimeout/3))),this.heartbeatTimer.unref?.()}async run(z){let Z=this.jobs[z.name];if(!Z){let B=Date.now()-z.createdAt;if(this.durable&&B<this.config.unknownJobGrace){if(!this.releasedNames.has(z.name))this.releasedNames.add(z.name),console.error(`Left a queued "${z.name}" for another replica: nothing is registered here under that name. It is dead-lettered if no replica has run it within unknownJobGrace (${this.config.unknownJobGrace}ms) of its dispatch.`);await this.driver.release(z,{retryInMs:Math.round(this.config.pollInterval*(1+Math.random()))});return}console.error(`Dropped a queued job: nothing is registered under the name "${z.name}". If the class exists, it was not `+"discovered \u2014 check that it is under the queue slice's jobsDir "+"(app/jobs by default), or list it in app/config/queue.ts."),await this.driver.fail(z,{error:`No job is registered under the name "${z.name}".`,retryInMs:null});return}let $;try{$=new Z}catch(B){console.error(`Dropped a queued ${z.name}: it could not be constructed.`,B),await this.driver.fail(z,{error:`The job could not be constructed: ${String(B)}`,retryInMs:null});return}let V;try{V=JSON.parse(z.args)}catch(B){console.error(`Dropped a queued ${z.name}: its arguments are not JSON.`,B),await this.driver.fail(z,{error:`The arguments are not JSON: ${String(B)}`,retryInMs:null});return}if(z.attempt>Math.max(1,$.maxAttempts)){let B=Error(`${z.name} was claimed for attempt ${z.attempt} of ${$.maxAttempts}: an earlier attempt never finished, most likely because the process running it exited. Dead-lettered without running it again.`);f0(`${z.name}.onDeadletter`,()=>$.onDeadletter(B,...V)),await this.driver.fail(z,{error:B.message,retryInMs:null}),await this.releaseUnique($,V,z);return}if($.$claimed={...z},z.batchId!==void 0){if((await this.driver.findBatch?.(z.batchId,{progress:!1}))?.cancelledAt!=null){await this.driver.fail(z,{error:"Its batch was cancelled before it ran.",retryInMs:null,cancelled:!0});return}let H=this.batchHandle(z);$.batch=H.batch,$.$progress=H.progress}let X=await this.admit($,V,z);if(!X)return;let Y,G;try{G=await($.worker?kz(z.name,z.args):$.run(...V))}catch(B){Y=B}finally{await X.done()}let Q=$.$outcome;if(Y===void 0&&Q?.kind==="release"){await this.driver.release(z,{retryInMs:Math.max(0,Q.delayMs)});return}if(Y===void 0&&Q?.kind==="fail")Y=Q.error;let J=Q?.kind==="fail"?Q.retry:!0;if(Y===void 0)try{$.onSuccess(G,...V)}catch(B){Y=B}if(Y!==void 0){let B=String(Y?.stack??Y);if(f0(`${z.name}.onFail`,()=>$.onFail(Y,...V)),!J||z.attempt>=$.maxAttempts)f0(`${z.name}.onDeadletter`,()=>$.onDeadletter(Y,...V)),await this.driver.fail(z,{error:B,retryInMs:null}),await this.releaseUnique($,V,z);else await this.driver.fail(z,{error:B,retryInMs:V0($.backoff,z.attempt)});return}await this.driver.complete(z),await this.releaseUnique($,V,z)}batchHandle(z){let Z=z.batchId,$=this.driver;return{batch:{id:Z,cancelled:async()=>(await $.findBatch?.(Z,{progress:!1}))?.cancelledAt!=null},progress:(V)=>$.reportProgress?.(z,V)??Promise.resolve()}}async admit(z,Z,$){let V=z.concurrency(...Z),X=[z.throttle(...Z)??[]].flat();if(!V&&X.length===0)return{done:async()=>{}};let Y=this.locks,G;if(V&&V.limit>0){let J=this.config.visibilityTimeout;for(let B=0;B<V.limit&&!G;B++)G=await Y.acquire(`gemi:concurrency:${V.key}:${B}`,{ttl:J,renew:!0})??void 0;if(!G){await this.driver.release($,{retryInMs:Math.round(this.config.pollInterval*(1+Math.random()))});return}}let Q=[];for(let J of X){let B=`gemi:throttle:${J.key}`,H=await Y.store.hit(B,J.limit,J.window);if(!H.allowed){await Promise.all(Q.map((N)=>Y.store.refund(N))),await G?.release(),await this.driver.release($,{retryInMs:Math.max(1,H.resetInMs)});return}Q.push(B)}return{done:async()=>{await G?.release().catch((J)=>{console.error(`[gemi] Could not free a concurrency slot of ${$.name}.`,J)})}}}}function Hz(z,Z){return`gemi:job:${z}:${String(Z)}`}function f0(z,Z){try{Z()}catch($){console.error(`${z} threw; the job's claim was ended anyway.`,$)}}function cz(){return Bun.env.NODE_ENV==="production"}function dz(){if(!mz)return!1;if(iz())return!0;return process.env.ROOT_DIR!==void 0&&!lz()}function lz(z=process.env){return(z.GEMI_QUEUE_CLAIM??"").trim().toLowerCase()==="off"}var Fz=Symbol.for("gemi.queue.worker");function sZ(z=!0){globalThis[Fz]=z}function iz(){return globalThis[Fz]===!0}function sz(z,Z){if(z==="memory")return new F0;if(z==="database"||typeof z==="function"){if(!Z&&(z==="database"||z.length>0))throw Error("The queue driver needs the application it belongs to, and this QueueManager was built without one. Pass { application }.");if(z==="database")return new I0(Z.make(q0));return z(Z)}if(typeof z==="string")throw Error(`Unknown queue driver "${z}". The queue slice's driver is "memory", "database", a QueueDriver, or a function returning one.`);return z}class d{static name="unset";worker=!1;maxAttempts=3;backoff=0;uniqueId(...z){return}uniqueFor=3600000;throttle(...z){return}concurrency(...z){return}release(z=0){this.$outcome={kind:"release",delayMs:z}}fail(z,Z={}){this.$outcome={kind:"fail",error:z instanceof Error?z:Error(String(z)),retry:Z.retry??!0}}batch=void 0;async progress(z){let Z=g(z);await this.$progress?.(Z)}$progress;$claimed;$outcome;run(...z){}onFail(z,...Z){}onSuccess(z,...Z){}onDeadletter(z,...Z){}static dispatch(...z){if(this.name==="unset")throw Error("Cannot dispatch a job with no name");return G0(t).push(this,JSON.stringify(z))}static dispatchBatch(z,Z={}){if(this.name==="unset")throw Error("Cannot dispatch a job with no name");return G0(t).pushBatch(this,z.map(($)=>JSON.stringify($)),Z)}static with(...z){if(this.name==="unset")throw Error("Cannot use a job with no name as a callback");return JSON.stringify(z),{name:this.name,args:z}}static findBatch(z){return G0(t).findBatch(z)}static cancelBatch(z){return G0(t).cancelBatch(z)}}var A0=["completed","failed","cancelled"],az=1000,nz=250,rz=30000;class b0{queue;registry={};storeInstance;ownFeed;publishing=new Map;published=new Map;tickClass;reportedNames=new Set;constructor(z){this.queue=z}get workflows(){return this.registry}use(z){this.registry={};for(let Z of z){if(Z.name==="unset"||!Z.name){console.error("A workflow class has no `static name`, so it was not registered. Add one.");continue}if(this.registry[Z.name]){console.error(`Two workflows are named "${Z.name}" \u2014 the first is registered `+"and this one is not. A workflow's name is its key in storage. Rename one.");continue}this.registry[Z.name]=Z}}get tickJob(){return this.tickClass??=tz(this),this.tickClass}get store(){if(!this.storeInstance){let z=this.queue.driver.workflowStore?.();if(!z||!this.queue.driver.enqueueBatch)throw Error("This queue's driver does not support workflows. The memory and database drivers do.");this.storeInstance=this.publishingStore(z)}return this.storeInstance}get feed(){let z=this.queue.boundApplication;if(z?.bound(D0))return z.make(D0);return this.ownFeed??=new D0,this.ownFeed}channel(z){return`gemi:workflow:${z}`}async update(z){let Z=await this.find(z);if(!Z)return null;let{args:$,result:V,...X}=Z;return X}stream(z,Z,$={}){return this.feed.stream(z,this.channel(Z),$)}cursor(z){return this.feed.cursor(this.channel(z))}async*subscribe(z,Z={}){let $=this.feed.subscribe(this.channel(z),{signal:Z.signal});try{await $.ready();let V=await this.update(z);if(!V)return;if(yield V,R0(V.status))return;let X=$[Symbol.asyncIterator](),Y=X.next();for(;;){let G=await zZ(Y,rz),Q;if(G==="timeout")Q=await this.update(z);else{if(G.done)return;Y=X.next(),Q=ez(G.value,z)??await this.update(z)}if(!Q||Q.updatedAt<V.updatedAt)continue;if(JSON.stringify(Q)===JSON.stringify(V))continue;if(V=Q,yield V,R0(V.status))return}}finally{$.close()}}publishingStore(z){let Z=(V)=>void Nz(()=>this.schedulePublish(V)),$={create:(V)=>z.create(V).then((X)=>{return Z(V.id),X}),find:(V,X)=>z.find(V,X),acquire:(V,X,Y)=>z.acquire(V,X,Y),renew:(V,X,Y)=>z.renew(V,X,Y),update:(V,X,Y)=>z.update(V,X,Y).then((G)=>{return Z(V),G})};if(z.joinsTransaction)$.joinsTransaction=()=>z.joinsTransaction();if(z.listItems)$.listItems=(...V)=>z.listItems(...V);if(z.prune)$.prune=(V)=>z.prune(V);return $}schedulePublish(z){if(this.publishing.has(z))return;let Z=Math.max(0,(this.published.get(z)??0)+nz-Date.now()),$=setTimeout(()=>{this.publishing.delete(z),this.published.set(z,Date.now()),this.publish(z)},Z);$.unref?.(),this.publishing.set(z,$)}async publish(z){try{let Z=await this.update(z);if(!Z)return;if(R0(Z.status))this.published.delete(z);await this.feed.publish(this.channel(z),Z)}catch(Z){console.error(`[gemi] Workflow ${z}: could not publish its change.`,Z)}}async close(){for(let z of this.publishing.values())clearTimeout(z);this.publishing.clear(),await this.ownFeed?.close(),this.ownFeed=void 0}start(z,Z){if(z.name==="unset"||!z.name)throw Error("Cannot start a workflow with no name");let $=this.store,V={id:Bun.randomUUIDv7(),name:z.name,args:Y0(Z,`The arguments of ${z.name}`)??"[]"},X=()=>this.queue.claimSoon(),Y=$.joinsTransaction?.()===!0;if(!Y){if(y(()=>$.create(V).then(X,(B)=>{console.error(`[gemi] The queue could not record the workflow ${z.name}, which was held until its transaction committed. The transaction stays committed; the workflow did not start.`,B)})))return Promise.resolve(V.id)}let G=$.create(V),Q=Y&&y(X);return G.then(()=>{if(!Q)X();return V.id})}async signal(z,Z,$){if(typeof Z!=="string"||Z.length===0||Z.length>191)throw TypeError("A signal key is a string of 1 to 191 characters.");let V=Y0($,`The payload of signal "${Z}"`),X=await this.store.update(z,{key:Z},({workflow:Y,step:G,now:Q})=>{if(A0.includes(Y.status)||Y.status==="cancelling")return{result:!1};if(!G)return{result:!0,step:{workflowId:z,key:Z,status:"signalled",attempt:0,output:V,error:null,batchId:null,wakeAt:null,startedAt:null,finishedAt:Q,createdAt:Q,updatedAt:Q}};if(G.status!=="waiting")return{result:!1};return{result:!0,step:{...G,status:"signalled",output:V,wakeAt:G.wakeAt,finishedAt:Q},tick:{delayMs:0}}});if(X)this.queue.claimSoon();return X===!0}async cancel(z){let Z=await this.store.update(z,{allSteps:!0},({workflow:$,steps:V})=>{if(A0.includes($.status)||$.status==="cancelling")return{result:!1};return{result:!0,workflow:{status:"cancelling"},cancelBatches:V.filter((X)=>X.status==="batching"&&X.batchId!==null).map((X)=>X.batchId),tick:{delayMs:0}}});if(Z)this.queue.claimSoon();return Z===!0}async find(z){let Z=await this.store.find(z);if(!Z)return null;let{workflow:$,steps:V}=Z,X=[];try{X=JSON.parse($.args)}catch{}return{id:$.id,name:$.name,status:$.status,args:X,currentStep:$.currentStep,progress:$.progress,result:oz($.result),error:$.error,steps:await Promise.all(V.map(async(Y)=>{let G={key:Y.key,status:Y.status,attempt:Y.attempt,error:Y.error,batchId:Y.batchId,wakeAt:Y.wakeAt,startedAt:Y.startedAt,finishedAt:Y.finishedAt},Q=Bz(Y.output);if(Q)return{...G,items:Q,progress:Q.total===0?1:Q.done/Q.total};if(Y.batchId===null)return G;let J=await this.queue.driver.findBatch?.(Y.batchId);return J?{...G,progress:J.progress}:G})),createdAt:$.createdAt,updatedAt:$.updatedAt}}async items(z,Z,$={}){let V=this.store;if(!V.listItems)return[];let X=Math.max(1,Math.min(1000,Math.floor($.limit??100)));return(await V.listItems(z,Z,{statuses:$.status?[$.status]:["failed","skipped"],...$.after===void 0?{}:{after:$.after},limit:X})).map(y0)}async tick(z,Z){let $=this.store,V=Z.$claimed,X=V?`${V.id}:${V.attempt}`:`${crypto.randomUUID()}:1`,Y=Math.max(1,this.queue.config.visibilityTimeout),G=await $.acquire(z,X,Y);if(G.kind!=="acquired")return;let{workflow:Q}=G,J=(U={})=>$.update(z,{owner:X},()=>({...U,result:void 0,unlock:!0})).then(()=>this.queue.claimSoon()).catch((P)=>{if(!(P instanceof I))throw P});if(A0.includes(Q.status))return J();let B=this.registry[Q.name];if(!B)return this.unknown(Q,Z,J);let H;try{H=JSON.parse(Q.args)}catch(U){return J({workflow:{status:"failed",error:`The arguments are not JSON: ${r(U)}`}})}let N=setInterval(()=>{$.renew(z,X,Y).catch((U)=>{console.error(`[gemi] Could not extend the hold on workflow ${z}.`,U)})},Math.max(1,Math.floor(Y/3)));N.unref?.();let F=Q.status==="cancelling",K=new g0({workflowId:z,owner:X,store:$,steps:G.steps,cancelling:F,findBatch:(U)=>this.queue.driver.findBatch?.(U,{progress:!1})??Promise.resolve(null),buildBatch:(U,P,A)=>this.queue.buildBatch(U,P.map((T)=>JSON.stringify(T)),{name:A.name,allowFailures:A.allowFailures,finally:{name:q,args:[z]}}),scheduled:()=>this.queue.claimSoon(),cancelCheckMs:az,durable:this.queue.durable});try{let U;try{let P=new B,A=await(F?P.onCancel(K,...H):P.run(K,...H));U=K.suspension?{kind:"suspended"}:{kind:"completed",result:F?null:Y0(A,`The result of ${Q.name}`)}}catch(P){if(U=K.suspension||P instanceof m?{kind:"suspended"}:{kind:"failed",error:r(P)},P instanceof I)K.lost=!0}if(await K.settled(),K.lost)return;if(U.kind==="completed"&&K.suspension)U={kind:"suspended"};await $.update(z,{owner:X},({workflow:P,now:A})=>this.finish(P,U,K,F,A)),this.queue.claimSoon()}catch(U){if(U instanceof I)return;throw U}finally{clearInterval(N)}}finish(z,Z,$,V,X){let Y={result:void 0,unlock:!0};if(z.status==="cancelling"&&!V)return{...Y,tick:{delayMs:0}};if(Z.kind==="completed")return{...Y,workflow:V?{status:"cancelled",currentStep:null,wakeAt:null}:{status:"completed",result:Z.result,progress:1,currentStep:null,wakeAt:null,error:null}};if(Z.kind==="failed")return{...Y,workflow:{status:V?"cancelled":"failed",error:Z.error,wakeAt:null}};let G=$.suspension??{status:"waiting",wakes:[]},Q={...Y,workflow:{status:V?"cancelling":G.status,currentStep:$.current??z.currentStep}};if(G.wakes.length>0){let J=Math.min(...G.wakes);if(!(z.wakeAt!==null&&z.wakeAt>X&&z.wakeAt<=J))Q.tick={delayMs:Math.max(0,J-X)},Q.workflow.wakeAt=J}return Q}async unknown(z,Z,$){let V=Date.now()-z.createdAt;if(this.queue.durable&&V<this.queue.config.unknownJobGrace){if(!this.reportedNames.has(z.name))this.reportedNames.add(z.name),console.error(`Left workflow "${z.name}" for another replica: nothing is registered here under that name.`);await $(),Z.release(Math.round(this.queue.config.pollInterval*(1+Math.random())));return}console.error(`Failed workflow ${z.id}: nothing is registered under the name "${z.name}". If the class exists, it was not discovered: check that it is under the queue slice's workflowsDir (app/workflows by default), or list it in app/config/queue.ts.`),await $({workflow:{status:"failed",error:`No workflow is registered under the name "${z.name}".`}})}tickDeadLettered(z,Z){console.error(`[gemi] The tick of workflow ${z} was dead-lettered.`,Z),this.store.update(z,{},({workflow:$})=>A0.includes($.status)?{result:void 0}:{result:void 0,workflow:{status:"failed",error:`Its tick job was dead-lettered: ${Z.message}`},unlock:!0}).catch(()=>{})}}function tz(z){return class extends d{static name=q;maxAttempts=20;backoff=[1000,5000,15000,30000,60000];async run($){await z.tick($,this)}onDeadletter($,V){z.tickDeadLettered(V,$)}}}function oz(z){try{return h(z)}catch{return z}}function ez(z,Z){if(z.type!=="change")return null;let $=z.data;if(!$||typeof $!=="object"||$.id!==Z||typeof $.updatedAt!=="number")return null;return $}async function zZ(z,Z){let $,V=new Promise((X)=>{$=setTimeout(()=>X("timeout"),Z)});try{return await Promise.race([z,V])}finally{clearTimeout($)}}
482
- export{Z0 as se,J0 as te,C0 as ue,i0 as ve,I0 as we,RZ as xe,e0 as ye,S0 as ze,F0 as Ae,Qz as Be,M0 as Ce,x0 as De,v0 as Ee,g0 as Fe,R0 as Ge,b0 as He,t as Ie,dz as Je,lz as Ke,sZ as Le,iz as Me,d as Ne};
483
-
484
- //# debugId=4F875BE7ED3A2F9964756E2164756E21