gemi 0.236.2 → 0.237.1
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.
- package/dist/ai/Agent.d.ts.map +1 -1
- package/dist/ai/AgentProvider.d.ts +22 -0
- package/dist/ai/AgentProvider.d.ts.map +1 -1
- package/dist/ai/FallbackProvider.d.ts +6 -0
- package/dist/ai/FallbackProvider.d.ts.map +1 -1
- package/dist/ai/ImageModel.d.ts.map +1 -1
- package/dist/ai/contextCompaction.d.ts.map +1 -1
- package/dist/ai/generate.d.ts.map +1 -1
- package/dist/ai/index.d.ts +1 -1
- package/dist/ai/index.d.ts.map +1 -1
- package/dist/ai/index.js +172 -172
- package/dist/ai/index.js.map +6 -6
- package/dist/ai/runtime.d.ts +8 -0
- package/dist/ai/runtime.d.ts.map +1 -1
- package/dist/ai/store/DatabaseAgentStore.d.ts.map +1 -1
- package/dist/ai/testing/index.js +2 -2
- package/dist/ai/testing/index.js.map +1 -1
- package/dist/ai/types.d.ts +13 -0
- package/dist/ai/types.d.ts.map +1 -1
- package/dist/ai/usageLimits.d.ts +12 -1
- package/dist/ai/usageLimits.d.ts.map +1 -1
- package/dist/ai/usageMeter.d.ts +67 -10
- package/dist/ai/usageMeter.d.ts.map +1 -1
- package/dist/app/index.js +1 -1
- package/dist/auth/UserProvider.d.ts +5 -22
- package/dist/auth/UserProvider.d.ts.map +1 -1
- package/dist/bun/plugin.js +1 -1
- package/dist/bun/preload.js +1 -1
- package/dist/{chunk-naj8bmj5.js → chunk-0xmk4jyj.js} +2 -2
- package/dist/{chunk-naj8bmj5.js.map → chunk-0xmk4jyj.js.map} +1 -1
- package/dist/{chunk-sh2bd09k.js → chunk-1etmnz40.js} +2 -2
- package/dist/{chunk-sh2bd09k.js.map → chunk-1etmnz40.js.map} +1 -1
- package/dist/{chunk-t60krz4g.js → chunk-2apm69wz.js} +2 -2
- package/dist/{chunk-t60krz4g.js.map → chunk-2apm69wz.js.map} +1 -1
- package/dist/{chunk-8476xvk9.js → chunk-2as2xfem.js} +2 -2
- package/dist/{chunk-8476xvk9.js.map → chunk-2as2xfem.js.map} +1 -1
- package/dist/{chunk-ezea9fpd.js → chunk-2fw9pm64.js} +2 -2
- package/dist/{chunk-ezea9fpd.js.map → chunk-2fw9pm64.js.map} +1 -1
- package/dist/{chunk-h1wmpa03.js → chunk-2g1h9ktj.js} +2 -2
- package/dist/{chunk-h1wmpa03.js.map → chunk-2g1h9ktj.js.map} +1 -1
- package/dist/{chunk-ca5kp6cn.js → chunk-34a5b9xt.js} +2 -2
- package/dist/{chunk-ca5kp6cn.js.map → chunk-34a5b9xt.js.map} +1 -1
- package/dist/{chunk-3y1h3ncf.js → chunk-358krc4n.js} +2 -2
- package/dist/{chunk-3y1h3ncf.js.map → chunk-358krc4n.js.map} +1 -1
- package/dist/{chunk-qvn0w2rt.js → chunk-49kkapvr.js} +2 -2
- package/dist/{chunk-qvn0w2rt.js.map → chunk-49kkapvr.js.map} +1 -1
- package/dist/{chunk-8jc8x9tc.js → chunk-4pjv77s5.js} +2 -2
- package/dist/{chunk-8jc8x9tc.js.map → chunk-4pjv77s5.js.map} +1 -1
- package/dist/{chunk-ts75gcfd.js → chunk-4rs6w1gp.js} +2 -2
- package/dist/{chunk-k2mpxwh2.js.map → chunk-4rs6w1gp.js.map} +1 -1
- package/dist/{chunk-fbk79z21.js → chunk-4wdc4q33.js} +2 -2
- package/dist/{chunk-fbk79z21.js.map → chunk-4wdc4q33.js.map} +1 -1
- package/dist/{chunk-t2p5n8fe.js → chunk-692nx054.js} +2 -2
- package/dist/{chunk-t2p5n8fe.js.map → chunk-692nx054.js.map} +1 -1
- package/dist/{chunk-x2dmgge8.js → chunk-6wv3k8ap.js} +2 -2
- package/dist/{chunk-x2dmgge8.js.map → chunk-6wv3k8ap.js.map} +1 -1
- package/dist/{chunk-jssjfvsz.js → chunk-768yza4f.js} +2 -2
- package/dist/{chunk-jssjfvsz.js.map → chunk-768yza4f.js.map} +1 -1
- package/dist/{chunk-y2vayxcd.js → chunk-7qhqqf0q.js} +2 -2
- package/dist/{chunk-y2vayxcd.js.map → chunk-7qhqqf0q.js.map} +1 -1
- package/dist/chunk-7ytazpjd.js +5 -0
- package/dist/{chunk-gvr7cwxn.js.map → chunk-7ytazpjd.js.map} +3 -3
- package/dist/{chunk-1w6ra6jc.js → chunk-80kga3p1.js} +1 -1
- package/dist/{chunk-1mb7kaxs.js → chunk-88c8ck33.js} +3 -3
- package/dist/{chunk-1mb7kaxs.js.map → chunk-88c8ck33.js.map} +1 -1
- package/dist/{chunk-5exrgw07.js → chunk-8adbpxpm.js} +3 -3
- package/dist/{chunk-5exrgw07.js.map → chunk-8adbpxpm.js.map} +1 -1
- package/dist/{chunk-x185900b.js → chunk-8ccjtbm2.js} +27 -27
- package/dist/{chunk-x185900b.js.map → chunk-8ccjtbm2.js.map} +3 -3
- package/dist/{chunk-2j45vbs2.js → chunk-8kp4rkd3.js} +2 -2
- package/dist/{chunk-2j45vbs2.js.map → chunk-8kp4rkd3.js.map} +1 -1
- package/dist/{chunk-z3tk66vh.js → chunk-9779ngzq.js} +2 -2
- package/dist/{chunk-z3tk66vh.js.map → chunk-9779ngzq.js.map} +1 -1
- package/dist/{chunk-px9h2qgv.js → chunk-97t5t8jp.js} +3 -3
- package/dist/{chunk-px9h2qgv.js.map → chunk-97t5t8jp.js.map} +1 -1
- package/dist/{chunk-a119av2z.js → chunk-9a3wbbr6.js} +2 -2
- package/dist/{chunk-a119av2z.js.map → chunk-9a3wbbr6.js.map} +1 -1
- package/dist/{chunk-7fbnw7e2.js → chunk-9wf36729.js} +1 -1
- package/dist/chunk-ab5xsxyx.js +13 -0
- package/dist/{chunk-fs94x6ef.js.map → chunk-ab5xsxyx.js.map} +3 -3
- package/dist/{chunk-byv7b79h.js → chunk-ajyfp09w.js} +2 -2
- package/dist/{chunk-byv7b79h.js.map → chunk-ajyfp09w.js.map} +1 -1
- package/dist/{chunk-9kt24ctk.js → chunk-bhycdjcv.js} +2 -2
- package/dist/{chunk-9kt24ctk.js.map → chunk-bhycdjcv.js.map} +1 -1
- package/dist/{chunk-hprgj13q.js → chunk-bxby9c62.js} +2 -2
- package/dist/{chunk-hprgj13q.js.map → chunk-bxby9c62.js.map} +1 -1
- package/dist/{chunk-2kzysesp.js → chunk-c3c37k46.js} +3 -3
- package/dist/{chunk-2kzysesp.js.map → chunk-c3c37k46.js.map} +1 -1
- package/dist/{chunk-t6x1r5n6.js → chunk-ca1qwsjj.js} +3 -3
- package/dist/{chunk-t6x1r5n6.js.map → chunk-ca1qwsjj.js.map} +1 -1
- package/dist/{chunk-74dzzd64.js → chunk-cckfxk08.js} +2 -2
- package/dist/{chunk-74dzzd64.js.map → chunk-cckfxk08.js.map} +1 -1
- package/dist/chunk-cwkf46bk.js +5 -0
- package/dist/{chunk-0hy5dsbt.js.map → chunk-cwkf46bk.js.map} +1 -1
- package/dist/{chunk-8gz07168.js → chunk-d2jafhaf.js} +4 -4
- package/dist/{chunk-8gz07168.js.map → chunk-d2jafhaf.js.map} +1 -1
- package/dist/{chunk-gt9ftnhn.js → chunk-dh1wbntq.js} +2 -2
- package/dist/{chunk-gt9ftnhn.js.map → chunk-dh1wbntq.js.map} +1 -1
- package/dist/{chunk-4n3jva4e.js → chunk-dt8bxq4c.js} +2 -2
- package/dist/{chunk-4n3jva4e.js.map → chunk-dt8bxq4c.js.map} +1 -1
- package/dist/{chunk-406ef17s.js → chunk-ea5fv4h9.js} +2 -2
- package/dist/{chunk-406ef17s.js.map → chunk-ea5fv4h9.js.map} +1 -1
- package/dist/{chunk-28yb0q82.js → chunk-engdyem1.js} +2 -2
- package/dist/{chunk-28yb0q82.js.map → chunk-engdyem1.js.map} +1 -1
- package/dist/{chunk-m3fbewhz.js → chunk-fhbre39m.js} +3 -3
- package/dist/{chunk-m3fbewhz.js.map → chunk-fhbre39m.js.map} +1 -1
- package/dist/chunk-g6re0kkk.js +88 -0
- package/dist/{chunk-73541m4t.js.map → chunk-g6re0kkk.js.map} +4 -4
- package/dist/{chunk-yahabnz4.js → chunk-g7exgg3k.js} +3 -3
- package/dist/{chunk-yahabnz4.js.map → chunk-g7exgg3k.js.map} +1 -1
- package/dist/{chunk-2ver7cdt.js → chunk-gbgwtaqq.js} +1 -1
- package/dist/{chunk-p4p8xy74.js → chunk-h0b4rjzn.js} +2 -2
- package/dist/{chunk-p4p8xy74.js.map → chunk-h0b4rjzn.js.map} +1 -1
- package/dist/{chunk-fqndtpwm.js → chunk-h2cvg5r5.js} +3 -3
- package/dist/{chunk-fqndtpwm.js.map → chunk-h2cvg5r5.js.map} +1 -1
- package/dist/{chunk-17bva6b1.js → chunk-hgwtg5zp.js} +2 -2
- package/dist/{chunk-17bva6b1.js.map → chunk-hgwtg5zp.js.map} +1 -1
- package/dist/{chunk-n4kz9vft.js → chunk-hk37x8mp.js} +1 -1
- package/dist/{chunk-np6vee9d.js → chunk-j0bbh93g.js} +3 -3
- package/dist/{chunk-np6vee9d.js.map → chunk-j0bbh93g.js.map} +1 -1
- package/dist/{chunk-ka8dzc6q.js → chunk-j5r7vm8a.js} +2 -2
- package/dist/{chunk-ka8dzc6q.js.map → chunk-j5r7vm8a.js.map} +1 -1
- package/dist/{chunk-9jt5qj1b.js → chunk-kbz5s9wb.js} +2 -2
- package/dist/{chunk-9jt5qj1b.js.map → chunk-kbz5s9wb.js.map} +1 -1
- package/dist/{chunk-8yb9jrj5.js → chunk-kgpqz8te.js} +2 -2
- package/dist/{chunk-8yb9jrj5.js.map → chunk-kgpqz8te.js.map} +1 -1
- package/dist/{chunk-kvtvx64t.js → chunk-mhvg8nnb.js} +2 -2
- package/dist/{chunk-kvtvx64t.js.map → chunk-mhvg8nnb.js.map} +1 -1
- package/dist/{chunk-gftdag48.js → chunk-mk8jwsm4.js} +2 -2
- package/dist/{chunk-gftdag48.js.map → chunk-mk8jwsm4.js.map} +1 -1
- package/dist/{chunk-ehtj7zs2.js → chunk-mn5xxg4q.js} +2 -2
- package/dist/{chunk-ehtj7zs2.js.map → chunk-mn5xxg4q.js.map} +1 -1
- package/dist/{chunk-8mpptpn5.js → chunk-mt68n713.js} +3 -3
- package/dist/{chunk-8mpptpn5.js.map → chunk-mt68n713.js.map} +1 -1
- package/dist/{chunk-1xz206e1.js → chunk-mykr2v6g.js} +3 -3
- package/dist/{chunk-1xz206e1.js.map → chunk-mykr2v6g.js.map} +1 -1
- package/dist/{chunk-kak3vc71.js → chunk-nxap8bmy.js} +2 -2
- package/dist/{chunk-kak3vc71.js.map → chunk-nxap8bmy.js.map} +1 -1
- package/dist/{chunk-zt4hybgg.js → chunk-p7ae0rnf.js} +2 -2
- package/dist/{chunk-zt4hybgg.js.map → chunk-p7ae0rnf.js.map} +1 -1
- package/dist/{chunk-aj9atkwk.js → chunk-pb7n7vaq.js} +1 -1
- package/dist/{chunk-8n40a2sn.js → chunk-pe4f30nw.js} +2 -2
- package/dist/{chunk-8n40a2sn.js.map → chunk-pe4f30nw.js.map} +1 -1
- package/dist/{chunk-9sbhqscs.js → chunk-prvncxxf.js} +3 -3
- package/dist/{chunk-9sbhqscs.js.map → chunk-prvncxxf.js.map} +1 -1
- package/dist/{chunk-x6a5qxpa.js → chunk-q1grt110.js} +2 -2
- package/dist/{chunk-x6a5qxpa.js.map → chunk-q1grt110.js.map} +1 -1
- package/dist/{chunk-h0dch3vh.js → chunk-s3fpkpdh.js} +2 -2
- package/dist/{chunk-h0dch3vh.js.map → chunk-s3fpkpdh.js.map} +1 -1
- package/dist/{chunk-yknc5rgh.js → chunk-sajfdtkt.js} +2 -2
- package/dist/{chunk-yknc5rgh.js.map → chunk-sajfdtkt.js.map} +1 -1
- package/dist/{chunk-gjzwrx5g.js → chunk-tfefp5jh.js} +2 -2
- package/dist/{chunk-gjzwrx5g.js.map → chunk-tfefp5jh.js.map} +1 -1
- package/dist/chunk-txf4kfze.js +48 -0
- package/dist/chunk-txf4kfze.js.map +26 -0
- package/dist/{chunk-zm6b938z.js → chunk-vcmwp7pv.js} +3 -3
- package/dist/{chunk-zm6b938z.js.map → chunk-vcmwp7pv.js.map} +1 -1
- package/dist/{chunk-6v1fbe70.js → chunk-vf9jtq9h.js} +2 -2
- package/dist/{chunk-6v1fbe70.js.map → chunk-vf9jtq9h.js.map} +1 -1
- package/dist/{chunk-sv2mv2q2.js → chunk-vtf7tkef.js} +2 -2
- package/dist/{chunk-sv2mv2q2.js.map → chunk-vtf7tkef.js.map} +1 -1
- package/dist/{chunk-g7hz0dmk.js → chunk-w9v8bbp8.js} +2 -2
- package/dist/{chunk-g7hz0dmk.js.map → chunk-w9v8bbp8.js.map} +1 -1
- package/dist/{chunk-pfkbhqp7.js → chunk-wgpg670d.js} +2 -2
- package/dist/{chunk-pfkbhqp7.js.map → chunk-wgpg670d.js.map} +1 -1
- package/dist/{chunk-17ewxwga.js → chunk-wj0q7tyn.js} +3 -3
- package/dist/{chunk-17ewxwga.js.map → chunk-wj0q7tyn.js.map} +1 -1
- package/dist/{chunk-4mha212g.js → chunk-wskms8nf.js} +1 -1
- package/dist/{chunk-4vn8gyzy.js → chunk-wzng3k56.js} +2 -2
- package/dist/{chunk-4vn8gyzy.js.map → chunk-wzng3k56.js.map} +1 -1
- package/dist/{chunk-k2mpxwh2.js → chunk-xe76d4v6.js} +2 -2
- package/dist/{chunk-ts75gcfd.js.map → chunk-xe76d4v6.js.map} +1 -1
- package/dist/{chunk-at82qczv.js → chunk-xm0fb17q.js} +3 -3
- package/dist/{chunk-at82qczv.js.map → chunk-xm0fb17q.js.map} +1 -1
- package/dist/{chunk-h5wjk91m.js → chunk-xr8mcx1y.js} +2 -2
- package/dist/{chunk-h5wjk91m.js.map → chunk-xr8mcx1y.js.map} +1 -1
- package/dist/{chunk-y56xd7sv.js → chunk-y73xy0zy.js} +2 -2
- package/dist/{chunk-y56xd7sv.js.map → chunk-y73xy0zy.js.map} +1 -1
- package/dist/{chunk-hgwkxn0g.js → chunk-ygfwbh8p.js} +2 -2
- package/dist/{chunk-hgwkxn0g.js.map → chunk-ygfwbh8p.js.map} +1 -1
- package/dist/{chunk-4800w7qx.js → chunk-zz0k1na4.js} +3 -3
- package/dist/{chunk-4800w7qx.js.map → chunk-zz0k1na4.js.map} +3 -3
- package/dist/config/index.js +1 -1
- package/dist/console/run.js +2 -2
- package/dist/console/run.js.map +1 -1
- package/dist/container/index.js +2 -2
- package/dist/container/index.js.map +1 -1
- package/dist/database/index.js +2 -2
- package/dist/database/index.js.map +1 -1
- package/dist/email/index.js +2 -2
- package/dist/email/index.js.map +1 -1
- package/dist/facades/DB.d.ts.map +1 -1
- package/dist/facades/index.js +2 -2
- package/dist/facades/index.js.map +1 -1
- package/dist/foundation/index.js +2 -2
- package/dist/foundation/index.js.map +1 -1
- package/dist/http/index.js +2 -2
- package/dist/http/index.js.map +1 -1
- package/dist/i18n/dictionaryRuntime.js +2 -2
- package/dist/i18n/dictionaryRuntime.js.map +1 -1
- package/dist/i18n/index.js +2 -2
- package/dist/i18n/index.js.map +1 -1
- package/dist/kernel/index.js +2 -2
- package/dist/kernel/index.js.map +1 -1
- package/dist/orm/Model.d.ts.map +1 -1
- package/dist/orm/context.d.ts +50 -0
- package/dist/orm/context.d.ts.map +1 -1
- package/dist/orm/index.js +3 -3
- package/dist/orm/index.js.map +3 -3
- package/dist/probe/index.js +2 -2
- package/dist/probe/index.js.map +1 -1
- package/dist/server/index.js +2 -2
- package/dist/server/index.js.map +1 -1
- package/dist/services/index.js +2 -2
- package/dist/services/index.js.map +1 -1
- package/dist/services/lock/DatabaseLockStore.d.ts.map +1 -1
- package/dist/services/queue/work.js +2 -2
- package/dist/services/queue/work.js.map +1 -1
- package/dist/stats/route-table.js +1 -1
- package/dist/support/index.js +2 -2
- package/dist/support/index.js.map +1 -1
- package/dist/vitest/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-0hy5dsbt.js +0 -5
- package/dist/chunk-73541m4t.js +0 -88
- package/dist/chunk-dav7mv8t.js +0 -48
- package/dist/chunk-dav7mv8t.js.map +0 -26
- package/dist/chunk-fs94x6ef.js +0 -9
- package/dist/chunk-gvr7cwxn.js +0 -5
- /package/dist/{chunk-1w6ra6jc.js.map → chunk-80kga3p1.js.map} +0 -0
- /package/dist/{chunk-7fbnw7e2.js.map → chunk-9wf36729.js.map} +0 -0
- /package/dist/{chunk-2ver7cdt.js.map → chunk-gbgwtaqq.js.map} +0 -0
- /package/dist/{chunk-n4kz9vft.js.map → chunk-hk37x8mp.js.map} +0 -0
- /package/dist/{chunk-aj9atkwk.js.map → chunk-pb7n7vaq.js.map} +0 -0
- /package/dist/{chunk-4mha212g.js.map → chunk-wskms8nf.js.map} +0 -0
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{Vk as r,Wk as x0,Yk as $1,il as l0}from"./chunk-fhbre39m.js";import{kl as Z1}from"./chunk-6wv3k8ap.js";import{Cl as v0,Dl as SZ,ml as fZ,nl as bZ,ol as TZ,ql as o,rl as tZ,tl as O0}from"./chunk-ab5xsxyx.js";import{Wl as DZ}from"./chunk-2as2xfem.js";import{rm as eZ,um as B0}from"./chunk-wj0q7tyn.js";import{Dm as w0}from"./chunk-49kkapvr.js";class C0{table;sql;dialect;connection;busyTimeout;configured;constructor(Z,$={}){let V=$.table??"gemi_locks";if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(V))throw Error(`The lock table name "${V}" is not a plain identifier. Use letters, digits and underscores.`);this.table=V,this.sql=Z.sql,this.dialect=Z.dialect,this.connection=Z.name,this.busyTimeout=$.busyTimeout??1000}async createTable(){await this.configure();for(let Z of H1(this.dialect,this.table))await this.sql.unsafe(Z)}async acquire(Z,$,V){await this.configure();let z=this.sql,X=this.now(z);if(await this.seed(z,Z),this.mysql){let G=await z`
|
|
3
3
|
UPDATE ${this.name(z)}
|
|
4
4
|
SET owner = ${$}, token = token + 1, expires_at = ${X} + ${this.ms(z,V)},
|
|
5
5
|
updated_at = ${X}
|
|
@@ -37,7 +37,7 @@ import{Sk as r,Tk as x0,Vk as Z1,fl as l0}from"./chunk-m3fbewhz.js";import{hl as
|
|
|
37
37
|
SELECT 1 AS held FROM ${this.name(G)}
|
|
38
38
|
WHERE name = ${Z} AND owner = ${$} AND token = ${V} AND expires_at > ${B}
|
|
39
39
|
FOR UPDATE
|
|
40
|
-
`).length>0;if(!H)throw new x0(Z,V);return z()},Y=this.connection;if(Y===void 0)
|
|
40
|
+
`).length>0;if(!H)throw new x0(Z,V);return z()},Y=this.connection;if(Y===void 0){let G=async()=>await this.sql.begin((B)=>X(B));return this.dialect==="sqlite"?SZ(this.sql,G):G()}return v0(this.sql,(G)=>TZ(Y,()=>X(G)),{connection:Y,dialect:this.dialect})}async hit(Z,$,V,z=1){await this.configure();let X=this.sql,Y=this.now(X),G=this.ms(X,Math.max(1,V)),B=this.int(X,z),H=this.int(X,$),Q=this.name(X);if(!this.mysql){let J=await X`
|
|
41
41
|
INSERT INTO ${Q} (name, owner, token, expires_at, updated_at)
|
|
42
42
|
VALUES (${Z}, '', ${B}, ${Y} + ${G}, ${Y})
|
|
43
43
|
ON CONFLICT (name) DO UPDATE
|
|
@@ -72,7 +72,7 @@ import{Sk as r,Tk as x0,Vk as Z1,fl as l0}from"./chunk-m3fbewhz.js";import{hl as
|
|
|
72
72
|
INSERT INTO ${this.name(Z)} (name, owner, token, expires_at, updated_at)
|
|
73
73
|
VALUES (${$}, '', 0, 0, ${V})
|
|
74
74
|
ON CONFLICT (name) DO NOTHING
|
|
75
|
-
`}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,$){return this.int(Z,Math.max(0,Math.round($)))}int(Z,$){let V=Math.round($);return this.mysql?Z`CAST(${V} AS SIGNED)`:Z`CAST(${V} AS BIGINT)`}}function s0(Z,$){return{allowed:Z,resetInMs:Math.max(0,Number($?.reset??0)),count:Number($?.token??0)}}function e(Z){let $=Z;return Math.max(Number($.count??0),Number($.affectedRows??0))}function
|
|
75
|
+
`}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,$){return this.int(Z,Math.max(0,Math.round($)))}int(Z,$){let V=Math.round($);return this.mysql?Z`CAST(${V} AS SIGNED)`:Z`CAST(${V} AS BIGINT)`}}function s0(Z,$){return{allowed:Z,resetInMs:Math.max(0,Number($?.reset??0)),count:Number($?.token??0)}}function e(Z){let $=Z;return Math.max(Number($.count??0),Number($.affectedRows??0))}function H1(Z,$){if(Z==="mysql"||Z==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${$}\` (
|
|
76
76
|
\`name\` VARCHAR(191) NOT NULL,
|
|
77
77
|
\`owner\` VARCHAR(191) NOT NULL,
|
|
78
78
|
\`token\` BIGINT NOT NULL DEFAULT 0,
|
|
@@ -88,13 +88,13 @@ import{Sk as r,Tk as x0,Vk as Z1,fl as l0}from"./chunk-m3fbewhz.js";import{hl as
|
|
|
88
88
|
"token" BIGINT NOT NULL DEFAULT 0,
|
|
89
89
|
"expires_at" BIGINT NOT NULL,
|
|
90
90
|
"updated_at" BIGINT NOT NULL${z}
|
|
91
|
-
)`]}class g0{entries=new Map;counters=new Map;async acquire(Z,$,V){let z=Date.now(),X=this.entries.get(Z);if(X&&(X.expiresAt>z||X.fences>0))return null;let Y=(X?.token??0)+1;return this.entries.set(Z,{owner:$,token:Y,expiresAt:z+Math.max(0,V),fences:0}),Y}async extend(Z,$,V,z){let X=this.current(Z,$,V);if(!X)return!1;return X.expiresAt=Date.now()+Math.max(0,z),!0}async release(Z,$,V){let z=this.current(Z,$,V);if(!z)return!1;return z.owner="",z.expiresAt=0,!0}async holder(Z){let $=this.entries.get(Z);if(!$||$.expiresAt<=Date.now())return null;return{owner:$.owner,token:$.token}}async held(Z,$,V){return this.current(Z,$,V)!==void 0}async advance(Z,$){if((this.counters.get(Z)??-1/0)>=$)return!1;return this.counters.set(Z,$),!0}async fence(Z,$,V,z){let X=this.current(Z,$,V);if(!X)throw new x0(Z,V);X.fences++;try{return await z()}finally{X.fences--}}windows=new Map;async hit(Z,$,V,z=1){let X=Date.now(),Y=this.windows.get(Z);if(!Y||Y.endsAt<=X)Y={count:0,endsAt:X+Math.max(1,V)},this.windows.set(Z,Y);if(Y.count+z>$)return{allowed:!1,resetInMs:Y.endsAt-X,count:Y.count};return Y.count+=z,{allowed:!0,resetInMs:Y.endsAt-X,count:Y.count}}async pruneWindows(Z,$=1000){if(Z==="")throw Error("pruneWindows needs a prefix: it must never reach lock rows.");let V=Date.now(),z=0;for(let[X,Y]of this.windows){if(z>=$)break;if(X.startsWith(Z)&&Y.endsAt<=V)this.windows.delete(X),z++}return z}async refund(Z){let $=this.windows.get(Z);if($&&$.endsAt>Date.now()&&$.count>0)$.count--}current(Z,$,V){let z=this.entries.get(Z);if(!z||z.owner!==$||z.expiresAt<=Date.now())return;if(V!==void 0&&z.token!==V)return;return z}}var m="gemi.WorkflowTick",n0=262144;function h0(Z,$){let V=(z)=>z.slice(0,z.lastIndexOf(":"));return V(Z)===V($)}class b 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
|
|
91
|
+
)`]}class g0{entries=new Map;counters=new Map;async acquire(Z,$,V){let z=Date.now(),X=this.entries.get(Z);if(X&&(X.expiresAt>z||X.fences>0))return null;let Y=(X?.token??0)+1;return this.entries.set(Z,{owner:$,token:Y,expiresAt:z+Math.max(0,V),fences:0}),Y}async extend(Z,$,V,z){let X=this.current(Z,$,V);if(!X)return!1;return X.expiresAt=Date.now()+Math.max(0,z),!0}async release(Z,$,V){let z=this.current(Z,$,V);if(!z)return!1;return z.owner="",z.expiresAt=0,!0}async holder(Z){let $=this.entries.get(Z);if(!$||$.expiresAt<=Date.now())return null;return{owner:$.owner,token:$.token}}async held(Z,$,V){return this.current(Z,$,V)!==void 0}async advance(Z,$){if((this.counters.get(Z)??-1/0)>=$)return!1;return this.counters.set(Z,$),!0}async fence(Z,$,V,z){let X=this.current(Z,$,V);if(!X)throw new x0(Z,V);X.fences++;try{return await z()}finally{X.fences--}}windows=new Map;async hit(Z,$,V,z=1){let X=Date.now(),Y=this.windows.get(Z);if(!Y||Y.endsAt<=X)Y={count:0,endsAt:X+Math.max(1,V)},this.windows.set(Z,Y);if(Y.count+z>$)return{allowed:!1,resetInMs:Y.endsAt-X,count:Y.count};return Y.count+=z,{allowed:!0,resetInMs:Y.endsAt-X,count:Y.count}}async pruneWindows(Z,$=1000){if(Z==="")throw Error("pruneWindows needs a prefix: it must never reach lock rows.");let V=Date.now(),z=0;for(let[X,Y]of this.windows){if(z>=$)break;if(X.startsWith(Z)&&Y.endsAt<=V)this.windows.delete(X),z++}return z}async refund(Z){let $=this.windows.get(Z);if($&&$.endsAt>Date.now()&&$.count>0)$.count--}current(Z,$,V){let z=this.entries.get(Z);if(!z||z.owner!==$||z.expiresAt<=Date.now())return;if(V!==void 0&&z.token!==V)return;return z}}var m="gemi.WorkflowTick",n0=262144;function h0(Z,$){let V=(z)=>z.slice(0,z.lastIndexOf(":"));return V(Z)===V($)}class b 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 J1=["completed","failed","cancelled"];class r0{db;table;stepTable;itemTable;sourceTable;constructor(Z,$){this.db=Z;this.table=$.table,this.stepTable=$.stepTable,this.itemTable=$.itemTable,this.sourceTable=$.sourceTable;let V=Z.connection;if(Z.dialect!=="sqlite"&&V!==void 0)this.transaction=(z)=>v0(Z.sql,()=>z(),{connection:V})}transaction;joinsTransaction(){return this.db.transaction()!==void 0}create(Z){let $=this.db.transaction(),V=$?this.insertWorkflow($,Z):this.db.atomically((z)=>this.insertWorkflow(z,Z));if($)O0(V);return V}async insertWorkflow(Z,$){await this.db.configure();let V=this.db.now(Z);await P0(Z`
|
|
92
92
|
INSERT INTO ${this.workflows(Z)}
|
|
93
93
|
(id, name, args, status, progress, retick, created_at, updated_at)
|
|
94
94
|
VALUES
|
|
95
95
|
(${$.id}, ${$.name}, ${$.args}, 'running',
|
|
96
96
|
${this.db.fraction(Z,0)}, 0, ${V}, ${V})
|
|
97
|
-
`,this.table),await this.db.insertJob(Z,{name:m,args:JSON.stringify([$.id])})}async find(Z,$={}){await this.db.configure();let V=this.db.sql,[z]=await P0(V`SELECT * FROM ${this.workflows(V)} WHERE id = ${Z}`,this.table);if(!z)return null;return{workflow:
|
|
97
|
+
`,this.table),await this.db.insertJob(Z,{name:m,args:JSON.stringify([$.id])})}async find(Z,$={}){await this.db.configure();let V=this.db.sql,[z]=await P0(V`SELECT * FROM ${this.workflows(V)} WHERE id = ${Z}`,this.table);if(!z)return null;return{workflow:IZ(z),steps:$.steps===!1?[]:await this.stepsOf(V,Z)}}acquire(Z,$,V){return this.db.atomically(async(z)=>{let X=await this.lock(z,Z);if(!X)return{kind:"missing"};let Y=await this.db.clock(z);if(X.lockedBy!==null&&!h0(X.lockedBy,$)&&(X.lockedUntil??0)>Y)return await z`UPDATE ${this.workflows(z)} SET retick = 1 WHERE id = ${Z}`,{kind:"busy"};let G=Y+Math.max(0,Math.round(V));return await z`
|
|
98
98
|
UPDATE ${this.workflows(z)}
|
|
99
99
|
SET locked_by = ${$}, locked_until = ${this.db.ms(z,G)}, retick = 0
|
|
100
100
|
WHERE id = ${Z}
|
|
@@ -139,7 +139,7 @@ import{Sk as r,Tk as x0,Vk as Z1,fl as l0}from"./chunk-m3fbewhz.js";import{hl as
|
|
|
139
139
|
DELETE FROM ${this.sources($)}
|
|
140
140
|
WHERE workflow_id IS NULL
|
|
141
141
|
AND created_at <= ${this.db.now($)} - ${this.db.ms($,Z)}
|
|
142
|
-
`,this.sourceTable);return y0(V)}endedClause(Z){return Z`status IN (${
|
|
142
|
+
`,this.sourceTable);return y0(V)}endedClause(Z){return Z`status IN (${J1.map(($)=>Z`${$}`).reduce(($,V)=>Z`${$}, ${V}`)})`}async writeItems(Z,$,V){let z=this.db,X=V.step,Y=V.delete??[];for(let B=0;B<Y.length;B+=500){let H=Y.slice(B,B+500).map((Q)=>Z`${Q}`);await f0(Z`
|
|
143
143
|
DELETE FROM ${this.items(Z)}
|
|
144
144
|
WHERE workflow_id = ${$} AND step_key = ${X}
|
|
145
145
|
AND idx IN (${H.reduce((Q,J)=>Z`${Q}, ${J}`)})
|
|
@@ -170,7 +170,7 @@ import{Sk as r,Tk as x0,Vk as Z1,fl as l0}from"./chunk-m3fbewhz.js";import{hl as
|
|
|
170
170
|
WHERE workflow_id = ${$} AND step_key = ${V}
|
|
171
171
|
AND status IN (${G}) AND idx > ${X}
|
|
172
172
|
ORDER BY idx LIMIT ${Y}
|
|
173
|
-
`,this.itemTable)).map(
|
|
173
|
+
`,this.itemTable)).map(P1)}async writeStep(Z,$,V){let z=this.db,X=this.keyColumn(Z);if(V){await Z`
|
|
174
174
|
UPDATE ${this.steps(Z)}
|
|
175
175
|
SET status = ${$.status}, attempt = ${$.attempt}, output = ${$.output},
|
|
176
176
|
error = ${$.error}, batch_id = ${$.batchId},
|
|
@@ -186,10 +186,10 @@ import{Sk as r,Tk as x0,Vk as Z1,fl as l0}from"./chunk-m3fbewhz.js";import{hl as
|
|
|
186
186
|
(${$.workflowId}, ${$.key}, ${$.status}, ${$.attempt}, ${$.output},
|
|
187
187
|
${$.error}, ${$.batchId}, ${z.timeOrNull(Z,$.wakeAt)},
|
|
188
188
|
${z.timeOrNull(Z,$.startedAt)}, ${z.timeOrNull(Z,$.finishedAt)}, ${Y}, ${Y})
|
|
189
|
-
`}async lock(Z,$){let V;if(this.db.dialect==="sqlite")await P0(Z`UPDATE ${this.workflows(Z)} SET updated_at = updated_at WHERE id = ${$}`,this.table),V=await Z`SELECT * FROM ${this.workflows(Z)} WHERE id = ${$}`;else V=await P0(Z`SELECT * FROM ${this.workflows(Z)} WHERE id = ${$} FOR UPDATE`,this.table);return V[0]?
|
|
189
|
+
`}async lock(Z,$){let V;if(this.db.dialect==="sqlite")await P0(Z`UPDATE ${this.workflows(Z)} SET updated_at = updated_at WHERE id = ${$}`,this.table),V=await Z`SELECT * FROM ${this.workflows(Z)} WHERE id = ${$}`;else V=await P0(Z`SELECT * FROM ${this.workflows(Z)} WHERE id = ${$} FOR UPDATE`,this.table);return V[0]?IZ(V[0]):void 0}async stepOf(Z,$,V){let[z]=await P0(Z`SELECT * FROM ${this.steps(Z)} WHERE workflow_id = ${$} AND ${this.keyColumn(Z)} = ${V}`,this.stepTable);return z?MZ(z):null}async stepsOf(Z,$){return(await P0(Z`
|
|
190
190
|
SELECT * FROM ${this.steps(Z)} WHERE workflow_id = ${$}
|
|
191
191
|
ORDER BY created_at, ${this.keyColumn(Z)}
|
|
192
|
-
`,this.stepTable)).map(
|
|
192
|
+
`,this.stepTable)).map(MZ)}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))}sources(Z){return Z.unsafe(this.db.quoted(this.sourceTable))}keyColumn(Z){return Z.unsafe(this.db.quoted("key"))}}function Z0(Z){return Z==null?null:Number(Z)}function w(Z){return Z==null?null:String(Z)}function IZ(Z){return{id:String(Z.id),name:String(Z.name),args:String(Z.args),status:String(Z.status),currentStep:w(Z.current_step),progress:Number(Z.progress??0),result:w(Z.result),error:w(Z.error),wakeAt:Z0(Z.wake_at),lockedBy:w(Z.locked_by),lockedUntil:Z0(Z.locked_until),retick:Number(Z.retick??0)!==0,createdAt:Number(Z.created_at),updatedAt:Number(Z.updated_at)}}function MZ(Z){return{workflowId:String(Z.workflow_id),key:String(Z.key),status:String(Z.status),attempt:Number(Z.attempt??0),output:w(Z.output),error:w(Z.error),batchId:w(Z.batch_id),wakeAt:Z0(Z.wake_at),startedAt:Z0(Z.started_at),finishedAt:Z0(Z.finished_at),createdAt:Number(Z.created_at),updatedAt:Number(Z.updated_at)}}function P1(Z){return{workflowId:String(Z.workflow_id),step:String(Z.step_key),index:Number(Z.idx),key:w(Z.item_key),status:String(Z.status),attempt:Number(Z.attempt??0),error:w(Z.error),output:w(Z.output),wakeAt:Z0(Z.wake_at),startedAt:Z0(Z.started_at),finishedAt:Z0(Z.finished_at),createdAt:Number(Z.created_at),updatedAt:Number(Z.updated_at)}}function y0(Z){let $=Z;return Math.max(Number($.count??0),Number($.affectedRows??0))}function W0(Z){let $=String(Z?.message??Z);return/does not exist|doesn't exist|unknown column|no such (table|column)|has no column/i.test($)}async function P0(Z,$){try{return await Z}catch(V){if(!W0(V))throw V;throw Error(`Workflows need the "${$}" 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:V})}}async function f0(Z,$){try{return await Z}catch(V){if(!W0(V))throw V;throw Error(`step.each needs the "${$}" 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:V})}}async function b0(Z,$){try{return await Z}catch(V){if(!W0(V))throw V;throw Error(`Item sources need the "${$}" table, and the database says it is missing. Add the GemiWorkflowSource model from the docs (docs/workflows.md#the-workflow-tables) and migrate, or call the queue driver's createTable().`,{cause:V})}}function jZ(Z,$,V){if(Z==="mysql"||Z==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${$}\` (
|
|
193
193
|
\`id\` VARCHAR(191) NOT NULL,
|
|
194
194
|
\`name\` VARCHAR(191) NOT NULL,
|
|
195
195
|
\`args\` LONGTEXT NOT NULL,
|
|
@@ -254,7 +254,7 @@ import{Sk as r,Tk as x0,Vk as Z1,fl as l0}from"./chunk-m3fbewhz.js";import{hl as
|
|
|
254
254
|
"updated_at" BIGINT NOT NULL,
|
|
255
255
|
|
|
256
256
|
${z?'PRIMARY KEY ("workflow_id", "key")':`CONSTRAINT "${V}_pkey" PRIMARY KEY ("workflow_id","key")`}
|
|
257
|
-
)`,`CREATE INDEX IF NOT EXISTS "${$}_status_idx" ON "${$}"("status")`]}function
|
|
257
|
+
)`,`CREATE INDEX IF NOT EXISTS "${$}_status_idx" ON "${$}"("status")`]}function vZ(Z,$){if(Z==="mysql"||Z==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${$}\` (
|
|
258
258
|
\`workflow_id\` VARCHAR(191) NOT NULL,
|
|
259
259
|
\`step_key\` VARCHAR(191) NOT NULL,
|
|
260
260
|
\`idx\` INTEGER NOT NULL,
|
|
@@ -286,7 +286,7 @@ import{Sk as r,Tk as x0,Vk as Z1,fl as l0}from"./chunk-m3fbewhz.js";import{hl as
|
|
|
286
286
|
"updated_at" BIGINT NOT NULL,
|
|
287
287
|
|
|
288
288
|
${Z==="sqlite"?'PRIMARY KEY ("workflow_id", "step_key", "idx")':`CONSTRAINT "${$}_pkey" PRIMARY KEY ("workflow_id","step_key","idx")`}
|
|
289
|
-
)`]}function
|
|
289
|
+
)`]}function xZ(Z,$){if(Z==="mysql"||Z==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${$}\` (
|
|
290
290
|
\`source_id\` VARCHAR(191) NOT NULL,
|
|
291
291
|
\`idx\` INTEGER NOT NULL,
|
|
292
292
|
\`workflow_id\` VARCHAR(191) NULL,
|
|
@@ -303,7 +303,7 @@ import{Sk as r,Tk as x0,Vk as Z1,fl as l0}from"./chunk-m3fbewhz.js";import{hl as
|
|
|
303
303
|
"created_at" BIGINT NOT NULL,
|
|
304
304
|
|
|
305
305
|
${Z==="sqlite"?'PRIMARY KEY ("source_id", "idx")':`CONSTRAINT "${$}_pkey" PRIMARY KEY ("source_id","idx")`}
|
|
306
|
-
)`,`CREATE INDEX IF NOT EXISTS "${$}_workflow_id_idx" ON "${$}"("workflow_id")`]}function q0(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 m0(Z,$,V){if(Z.pending<=0)return Z;let z={...Z,pending:Z.pending-1};if($==="succeeded")z.succeeded++;else if($==="cancelled")z.cancelled++;else z.failed++,z.failedJobIds=[...Z.failedJobIds,V];return z}function k0(Z,$){return!$.allowFailures&&$.cancelledAt===null&&$.finishedAt===null&&$.failed>Z.failed}function K0(Z,$,V){let z=Math.min(Math.max(0,V),Z.pending);return{...Z,cancelledAt:Z.cancelledAt??$,pending:Z.pending-z,cancelled:Z.cancelled+z}}function F0(Z,$,V){let z=$,X=[],Y=$.callbacks,G=Z.failed===0&&Z.cancelledAt===null,B=$.failed===0&&$.cancelledAt===null;if(G&&!B&&Y.catch)X.push(Y.catch);if($.pending===0&&$.finishedAt===null){if(z={...$,finishedAt:V},$.cancelledAt===null&&($.failed===0||$.allowFailures)&&Y.then)X.push(Y.then);if(Y.finally)X.push(Y.finally)}let H=G0(z);return{record:z,calls:X.map((Q)=>({name:Q.name,args:JSON.stringify([...Q.args,H])}))}}function G0(Z,$=0){let{allowFailures:V,callbacks:z,...X}=Z,Y=Z.total-Z.pending,G=Z.total===0?1:Math.min(1,Math.max(0,(Y+Math.max(0,$))/Z.total));return{...X,failedJobIds:[...Z.failedJobIds],progress:G}}function i(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{SQL:
|
|
306
|
+
)`,`CREATE INDEX IF NOT EXISTS "${$}_workflow_id_idx" ON "${$}"("workflow_id")`]}function q0(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 m0(Z,$,V){if(Z.pending<=0)return Z;let z={...Z,pending:Z.pending-1};if($==="succeeded")z.succeeded++;else if($==="cancelled")z.cancelled++;else z.failed++,z.failedJobIds=[...Z.failedJobIds,V];return z}function k0(Z,$){return!$.allowFailures&&$.cancelledAt===null&&$.finishedAt===null&&$.failed>Z.failed}function K0(Z,$,V){let z=Math.min(Math.max(0,V),Z.pending);return{...Z,cancelledAt:Z.cancelledAt??$,pending:Z.pending-z,cancelled:Z.cancelled+z}}function F0(Z,$,V){let z=$,X=[],Y=$.callbacks,G=Z.failed===0&&Z.cancelledAt===null,B=$.failed===0&&$.cancelledAt===null;if(G&&!B&&Y.catch)X.push(Y.catch);if($.pending===0&&$.finishedAt===null){if(z={...$,finishedAt:V},$.cancelledAt===null&&($.failed===0||$.allowFailures)&&Y.then)X.push(Y.then);if(Y.finally)X.push(Y.finally)}let H=G0(z);return{record:z,calls:X.map((Q)=>({name:Q.name,args:JSON.stringify([...Q.args,H])}))}}function G0(Z,$=0){let{allowFailures:V,callbacks:z,...X}=Z,Y=Z.total-Z.pending,G=Z.total===0?1:Math.min(1,Math.max(0,(Y+Math.max(0,$))/Z.total));return{...X,failedJobIds:[...Z.failedJobIds],progress:G}}function i(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{SQL:K1}=globalThis.Bun;class t0{db;statements;own;ownTail=Promise.resolve();constructor(Z,$){this.db=Z;this.statements=N1(Z.dialect,$)}async acquire(Z){return this.step(async($)=>{let V=[...new Set(Z.slots.map((Y)=>Y.key))].sort();for(let Y of V){let{limit:G}=Z.slots.find((B)=>B.key===Y);await $("lockGate",{key:Y,limit:G})}let[z]=await $("placeOf",{holder:Z.holder}),X=z?.queued_at==null?Number((await $("clock",{}))[0].now):Number(z.queued_at);for(let{key:Y,limit:G}of Z.slots){await this.prune($,Y);let[B]=await $("ticket",{key:Y,holder:Z.holder});if(!B)await $("insertWaiting",{key:Y,holder:Z.holder,job:Z.job.id,workflow:Z.workflowId??null,queued:X});else if(String(B.job_id)!==Z.job.id)await $("pointAt",{key:Y,holder:Z.holder,job:Z.job.id});let H=B?Number(B.queued_at):X,Q=async()=>await this.count($,"countHolders",{key:Y})+await this.count($,"countAhead",{key:Y,queued:H,holder:Z.holder,cap:Math.max(1,G)})<G,J=B?.state==="holding";if(!J&&await Q())J=!0;if(!J)await this.wake($,Y,G,Z.holder),J=await Q();if(J&&B?.state!=="holding")await $("hold",{key:Y,holder:Z.holder});if(J){await this.wake($,Y,G,Z.holder);continue}let U=await this.count($,"countAhead",{key:Y,queued:H,holder:Z.holder,cap:Math.max(1,G)})<Math.max(1,G)?Z.recheckMs.near:Z.recheckMs.far;return await $("park",{id:Z.job.id,attempt:Z.job.attempt,ms:Math.max(0,Math.round(U))}),!1}return!0})}async release(Z){await this.step(async($)=>{let V=await $("keysOf",{holder:Z}),z=[...new Set(V.map((X)=>String(X.slot_key)))].sort();for(let X of z)await $("touchGate",{key:X});for(let X of z){await $("deleteTicket",{key:X,holder:Z}),await this.prune($,X);let[Y]=await $("gate",{key:X});await this.wake($,X,Number(Y?.slot_limit??0),Z)}})}async prune(Z,$){if(await Z("pruneJobHolders",{key:$}),(await Z("hasWorkflowHolders",{key:$})).length>0)await Z("pruneWorkflowHolders",{key:$})}async wake(Z,$,V,z){let X=V-await this.count(Z,"countHolders",{key:$});while(X>0){let Y=await Z("nextWaiters",{key:$,except:z,n:X+8});if(Y.length===0)return;let G=0;for(let B of Y){if(X<=0)return;let H=String(B.holder),Q=B.job_id==null?null:String(B.job_id),J=B.workflow_id==null?null:String(B.workflow_id);if(J!==null){let[A]=await Z("workflowStatus",{id:J});if(!A||U1.includes(String(A.status))){await Z("deleteTicket",{key:$,holder:H}),G++;continue}}if(Q!==null)await Z("wakeJob",{id:Q});let[F]=Q===null?[]:await Z("jobStatus",{id:Q});if(!(F!==void 0&&F1.includes(String(F.status)))){if(J===null){await Z("deleteTicket",{key:$,holder:H}),G++;continue}let A=await this.db.insertJob(Z.q,{name:m,args:JSON.stringify([J])});await Z("pointAt",{key:$,holder:H,job:A})}X--}if(G===0)return}}async count(Z,$,V){let[z]=await Z($,V);return Number(z?.n??0)}async step(Z){await this.db.configure();for(let $=0;;$++)try{return await this.transaction((V)=>Z(this.runner(V)))}catch(V){if($>=4||!A1(V))throw D1(V,this.statements.table);await new Promise((z)=>setTimeout(z,10+Math.random()*40*($+1)))}}async transaction(Z){let $=this.ownClient();if($){let X=this.ownTail.then(()=>$.begin((Y)=>Z(Y)));return this.ownTail=X.catch(()=>{}),X}if(this.db.dialect!=="mysql"&&this.db.dialect!=="mariadb")return this.db.atomically(Z);let V=await this.db.sql.reserve(),[z]=await V`SELECT @@transaction_isolation AS level`;await V`SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED`;try{return await V.begin((X)=>Z(X))}finally{let X=z?.level?.replaceAll("-"," ");if(X&&/^[A-Z ]+$/.test(X))await V.unsafe(`SET SESSION TRANSACTION ISOLATION LEVEL ${X}`);V.release()}}ownClient(){if(this.own)return this.own;if(this.db.dialect!=="postgres"||!R1())return;let Z=this.db.sql.options;if(Z?.adapter!=="postgres")return;return this.own=new K1({...Z,max:1,idleTimeout:5}),this.own}runner(Z){let $=async(V,z)=>{let[X,Y]=this.statements.compile(V,z);return await Z.unsafe(X,Y)};return $.q=Z,$}}var F1=["pending","claimed"],U1=["completed","failed","cancelled","paused"];function gZ(Z,$){if(Z==="mysql"||Z==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${$}\` (
|
|
307
307
|
\`slot_key\` VARCHAR(191) NOT NULL,
|
|
308
308
|
\`holder\` VARCHAR(191) NOT NULL,
|
|
309
309
|
\`job_id\` VARCHAR(191) NULL,
|
|
@@ -327,7 +327,7 @@ import{Sk as r,Tk as x0,Vk as Z1,fl as l0}from"./chunk-m3fbewhz.js";import{hl as
|
|
|
327
327
|
"slot_limit" INTEGER NOT NULL DEFAULT 0,
|
|
328
328
|
"queued_at" BIGINT NOT NULL,
|
|
329
329
|
"updated_at" BIGINT NOT NULL${V}
|
|
330
|
-
)`,`CREATE INDEX IF NOT EXISTS "${$}_slot_key_state_queued_at_holder_idx" ON "${$}"("slot_key", "state", "queued_at", "holder")`,`CREATE INDEX IF NOT EXISTS "${$}_holder_idx" ON "${$}"("holder")`]}function
|
|
330
|
+
)`,`CREATE INDEX IF NOT EXISTS "${$}_slot_key_state_queued_at_holder_idx" ON "${$}"("slot_key", "state", "queued_at", "holder")`,`CREATE INDEX IF NOT EXISTS "${$}_holder_idx" ON "${$}"("holder")`]}function N1(Z,$){let V=Z==="mysql"||Z==="mariadb",z=(U)=>V?`\`${U}\``:`"${U}"`,X=z($.slots),Y=z($.jobs),G=z($.workflows),B=Z==="postgres"?"floor(extract(epoch from statement_timestamp()) * 1000)::bigint":V?"(TIMESTAMPDIFF(MICROSECOND, '1970-01-01 00:00:00', UTC_TIMESTAMP(6)) DIV 1000)":"CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER)",H=(U)=>V?`CAST({${U}} AS SIGNED)`:`CAST({${U}} AS BIGINT)`,Q=(U)=>V?`ON DUPLICATE KEY UPDATE ${U.replace(/excluded\.(\w+)/g,"VALUES($1)")}`:`ON CONFLICT (slot_key, holder) DO UPDATE SET ${U}`,J={clock:`SELECT ${B} AS now`,lockGate:`INSERT INTO ${X} (slot_key, holder, state, slot_limit, queued_at, updated_at)
|
|
331
331
|
VALUES ({key}, '', 'gate', ${H("limit")}, ${B}, ${B})
|
|
332
332
|
${Q("slot_limit = excluded.slot_limit, updated_at = excluded.updated_at")}`,touchGate:`INSERT INTO ${X} (slot_key, holder, state, slot_limit, queued_at, updated_at)
|
|
333
333
|
VALUES ({key}, '', 'gate', 0, ${B}, ${B})
|
|
@@ -359,12 +359,12 @@ import{Sk as r,Tk as x0,Vk as Z1,fl as l0}from"./chunk-m3fbewhz.js";import{hl as
|
|
|
359
359
|
WHERE id = {id} AND status = 'pending' AND available_at > ${B}`,jobStatus:`SELECT status FROM ${Y} WHERE id = {id}`,workflowStatus:`SELECT status FROM ${G} WHERE id = {id}`,park:`UPDATE ${Y}
|
|
360
360
|
SET status = 'pending', attempts = attempts - 1, available_at = ${B} + ${H("ms")},
|
|
361
361
|
lease_expires_at = NULL, updated_at = ${B}
|
|
362
|
-
WHERE id = {id} AND status = 'claimed' AND attempts = ${H("attempt")}`},F=new Map;return{table:$.slots,texts:J,compile(U,A){let N=F.get(U);if(!N){let P=[];N={text:J[U].replace(/\{([a-z]+)\}/g,(D,T)=>{if(Z==="postgres"){let _=P.indexOf(T);if(_===-1)_=P.push(T)-1;return`$${_+1}`}return P.push(T),"?"}),names:P},F.set(U,N)}return[N.text,N.names.map((P)=>{if(!(P in A))throw Error(`The slot statement ${U} needs {${P}}.`);return A[P]})]}}}function
|
|
362
|
+
WHERE id = {id} AND status = 'claimed' AND attempts = ${H("attempt")}`},F=new Map;return{table:$.slots,texts:J,compile(U,A){let N=F.get(U);if(!N){let P=[];N={text:J[U].replace(/\{([a-z]+)\}/g,(D,T)=>{if(Z==="postgres"){let _=P.indexOf(T);if(_===-1)_=P.push(T)-1;return`$${_+1}`}return P.push(T),"?"}),names:P},F.set(U,N)}return[N.text,N.names.map((P)=>{if(!(P in A))throw Error(`The slot statement ${U} needs {${P}}.`);return A[P]})]}}}function R1(){let[Z=0,$=0]=Bun.version.split(".").map(Number);return Z<1||Z===1&&$<4}function A1(Z){let $=Z;return $?.errno===1213||$?.code==="40P01"||/deadlock|try restarting transaction/i.test(String($?.message??""))}function D1(Z,$){let V=String(Z?.message??Z);if(!/does not exist|doesn't exist|no such table/i.test(V)||!V.includes($))return Z;return Error(`Concurrency limits on the database driver need the "${$}" table, and the database says it is missing. Add the GemiJobSlot model from the docs (docs/jobs-and-queues.md#concurrency-limits--concurrency) and migrate, or call the driver's createTable().`,{cause:Z})}var hZ=200,_1="Its batch was cancelled before it ran.";class e0{table;batchTable;workflowTable;workflowStepTable;workflowItemTable;workflowSourceTable;slotTable;workflows;slotLines;sql;dialect;connection;busyTimeout;configured;sqliteTail=Promise.resolve();constructor(Z,$={}){let V=$.table??"gemi_jobs",z=$.batchTable??(V==="gemi_jobs"?"gemi_job_batches":`${V}_batches`),X=V==="gemi_jobs",Y=$.workflowTable??(X?"gemi_workflows":`${V}_workflows`),G=$.workflowStepTable??(X?"gemi_workflow_steps":`${V}_workflow_steps`),B=$.workflowItemTable??(X?"gemi_workflow_items":`${V}_workflow_items`),H=$.workflowSourceTable??(X?"gemi_workflow_sources":`${V}_workflow_sources`),Q=$.slotTable??(X?"gemi_job_slots":`${V}_slots`);for(let F of[V,Q,z,Y,G,B,H])if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(F))throw Error(`The queue table name "${F}" is not a plain identifier. Use letters, digits and underscores.`);let J=$.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=V,this.batchTable=z,this.workflowTable=Y,this.workflowStepTable=G,this.workflowItemTable=B,this.workflowSourceTable=H,this.slotTable=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,...$]=L1(this.dialect,this.table);if(await this.sql.unsafe(Z),!await this.hasBatchColumns())for(let V of C1(this.dialect,this.table))await this.sql.unsafe(V);for(let V of $)await this.sql.unsafe(V);for(let V of W1(this.dialect,this.batchTable))await this.sql.unsafe(V);for(let V of jZ(this.dialect,this.workflowTable,this.workflowStepTable))await this.sql.unsafe(V);for(let V of vZ(this.dialect,this.workflowItemTable))await this.sql.unsafe(V);for(let V of xZ(this.dialect,this.workflowSourceTable))await this.sql.unsafe(V);for(let V of gZ(this.dialect,this.slotTable))await this.sql.unsafe(V)}async hasBatchColumns(){try{return await this.sql.unsafe(`SELECT batch_id, progress FROM ${this.quoted(this.table)} WHERE 1 = 0`),!0}catch(Z){if(qZ(Z))return!1;throw Z}}enqueue(Z){let $=this.transaction(),V=this.insert($??this.sql,Z);if($)O0(V);return V}async insert(Z,{name:$,args:V,delayMs:z=0,id:X=Bun.randomUUIDv7()}){await this.configure();let Y=this.now(Z);return await Z`
|
|
363
363
|
INSERT INTO ${this.name(Z)}
|
|
364
364
|
(id, name, payload, status, attempts, available_at, created_at, updated_at)
|
|
365
365
|
VALUES
|
|
366
366
|
(${X}, ${$}, ${V}, 'pending', 0, ${Y} + ${this.ms(Z,z)}, ${Y}, ${Y})
|
|
367
|
-
`,X}lockStore(){return new C0({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=
|
|
367
|
+
`,X}lockStore(){return new C0({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=fZ();if(Z===void 0||bZ()!==this.connection)return;return Z}async claim(Z,$){let V=Math.max(0,Math.floor(Z));if(V===0)return[];return await this.configure(),(this.dialect==="mysql"||this.dialect==="mariadb"?await this.claimLocking(V,$):await this.claimUpdating(V,$)).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 $=this.sql;await $`
|
|
368
368
|
DELETE FROM ${this.name($)}
|
|
369
369
|
WHERE id = ${Z.id} AND status = 'claimed' AND attempts = ${Z.attempt}
|
|
370
370
|
`}async fail(Z,$){if(Z.batchId!==void 0)return this.endBatchJob(Z,"failed",$);await this.configure();let V=this.sql,z=this.now(V);if($.retryInMs===null){await V`
|
|
@@ -404,13 +404,13 @@ import{Sk as r,Tk as x0,Vk as Z1,fl as l0}from"./chunk-m3fbewhz.js";import{hl as
|
|
|
404
404
|
cancelled_at, finished_at, created_at, updated_at)
|
|
405
405
|
VALUES
|
|
406
406
|
(${X.id}, ${X.name}, ${X.total}, ${X.pending}, 0, 0, 0,
|
|
407
|
-
'[]', ${
|
|
407
|
+
'[]', ${O1(X)}, NULL, ${this.timeOrNull(Z,X.finishedAt)},
|
|
408
408
|
${this.ms(Z,V)}, ${this.ms(Z,V)})
|
|
409
|
-
`,this.batchTable);let G=this.ms(Z,V);for(let B=0;B<$.args.length;B+=
|
|
409
|
+
`,this.batchTable);let G=this.ms(Z,V);for(let B=0;B<$.args.length;B+=hZ){let H=$.args.slice(B,B+hZ).map((Q)=>Z`(${Bun.randomUUIDv7()}, ${$.job}, ${Q}, 'pending', 0, ${G}, ${G}, ${G}, ${$.id}, 0)`).reduce((Q,J)=>Z`${Q}, ${J}`);await o0(Z`
|
|
410
410
|
INSERT INTO ${this.name(Z)}
|
|
411
411
|
(id, name, payload, status, attempts, available_at, created_at, updated_at, batch_id, progress)
|
|
412
412
|
VALUES ${H}
|
|
413
|
-
`,this.table)}for(let B of Y)await this.insert(Z,B)}async findBatch(Z,$={}){await this.configure();let V=this.sql,[z]=await o0(V`SELECT * FROM ${this.batches(V)} WHERE id = ${Z}`,this.batchTable);if(!z)return null;let X=
|
|
413
|
+
`,this.table)}for(let B of Y)await this.insert(Z,B)}async findBatch(Z,$={}){await this.configure();let V=this.sql,[z]=await o0(V`SELECT * FROM ${this.batches(V)} WHERE id = ${Z}`,this.batchTable);if(!z)return null;let X=yZ(z);if($.progress===!1||X.pending===0)return G0(X);let[Y]=await V`
|
|
414
414
|
SELECT COALESCE(SUM(progress), 0) AS running FROM ${this.name(V)}
|
|
415
415
|
WHERE batch_id = ${Z} AND status IN ('pending', 'claimed')
|
|
416
416
|
`;return G0(X,Number(Y?.running??0))}async cancelBatch(Z){return this.atomically(($)=>this.cancelBatchOn($,Z))}async cancelBatchOn(Z,$){let V=await this.lockBatch(Z,$);if(!V||V.finishedAt!==null||V.cancelledAt!==null)return!1;let z=await this.clock(Z),X=K0(V,z,await this.cancelWaiting(Z,$));return await this.saveBatch(Z,V,X,z),!0}workflowStore(){return this.workflows??=new r0({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,$)=>this.ms(Z,$),timeOrNull:(Z,$)=>this.timeOrNull(Z,$),fraction:(Z,$)=>this.fraction(Z,$),clock:(Z)=>this.clock(Z),insertJob:(Z,$)=>this.insert(Z,$),insertBatch:(Z,$)=>this.insertBatch(Z,$),cancelBatch:(Z,$)=>this.cancelBatchOn(Z,$),quoted:(Z)=>this.quoted(Z)},{table:this.workflowTable,stepTable:this.workflowStepTable,itemTable:this.workflowItemTable,sourceTable:this.workflowSourceTable}),this.workflows}acquireSlots(Z){return this.slots().acquire(Z)}releaseSlots(Z){return this.slots().release(Z)}slots(){return this.slotLines??=new t0({sql:this.sql,dialect:this.dialect,configure:()=>this.configure(),atomically:(Z)=>this.atomically(Z),insertJob:(Z,$)=>this.insert(Z,$)},{slots:this.slotTable,jobs:this.table,workflows:this.workflowTable}),this.slotLines}async reportProgress(Z,$){let V=i($);await this.configure();let z=this.sql;await z`
|
|
@@ -432,7 +432,7 @@ import{Sk as r,Tk as x0,Vk as Z1,fl as l0}from"./chunk-m3fbewhz.js";import{hl as
|
|
|
432
432
|
WHERE ${G}
|
|
433
433
|
`;if(U0(Q)===0||!Y)return;return this.count(X,Y,H?"cancelled":"failed",Z.id)})}async count(Z,$,V,z){let X=await this.clock(Z),Y=m0($,V,z);if(k0($,Y))Y=K0(Y,X,await this.cancelWaiting(Z,$.id));await this.saveBatch(Z,$,Y,X)}async cancelWaiting(Z,$){let V=this.now(Z),z=await Z`
|
|
434
434
|
UPDATE ${this.name(Z)}
|
|
435
|
-
SET status = 'dead', last_error = ${
|
|
435
|
+
SET status = 'dead', last_error = ${_1}, updated_at = ${V}
|
|
436
436
|
WHERE batch_id = ${$} AND status = 'pending'
|
|
437
437
|
`;return U0(z)}async saveBatch(Z,$,V,z){let{record:X,calls:Y}=F0($,V,z);await Z`
|
|
438
438
|
UPDATE ${this.batches(Z)}
|
|
@@ -441,7 +441,7 @@ import{Sk as r,Tk as x0,Vk as Z1,fl as l0}from"./chunk-m3fbewhz.js";import{hl as
|
|
|
441
441
|
cancelled_at = ${this.timeOrNull(Z,X.cancelledAt)},
|
|
442
442
|
finished_at = ${this.timeOrNull(Z,X.finishedAt)}, updated_at = ${this.ms(Z,z)}
|
|
443
443
|
WHERE id = ${X.id}
|
|
444
|
-
`;for(let G of Y)await this.insert(Z,G)}async lockBatch(Z,$){let V;if(this.dialect==="sqlite")await Z`UPDATE ${this.batches(Z)} SET updated_at = updated_at WHERE id = ${$}`,V=await Z`SELECT * FROM ${this.batches(Z)} WHERE id = ${$}`;else V=await Z`SELECT * FROM ${this.batches(Z)} WHERE id = ${$} FOR UPDATE`;return V[0]?
|
|
444
|
+
`;for(let G of Y)await this.insert(Z,G)}async lockBatch(Z,$){let V;if(this.dialect==="sqlite")await Z`UPDATE ${this.batches(Z)} SET updated_at = updated_at WHERE id = ${$}`,V=await Z`SELECT * FROM ${this.batches(Z)} WHERE id = ${$}`;else V=await Z`SELECT * FROM ${this.batches(Z)} WHERE id = ${$} FOR UPDATE`;return V[0]?yZ(V[0]):void 0}atomically(Z){let $=async()=>{await this.configure();for(let z=0;;z++)try{return await this.sql.begin((X)=>Z(X))}catch(X){if(this.dialect!=="sqlite"||z>=50||!/within a transaction/i.test(String(X?.message??X)))throw X;await new Promise((Y)=>setTimeout(Y,20))}};if(this.dialect!=="sqlite")return $();let V=this.sqliteTail.then($,$);return this.sqliteTail=V.catch(()=>{}),V}async clock(Z){let[$]=await Z`SELECT ${this.now(Z)} AS now`;return Number($.now)}timeOrNull(Z,$){return $===null?Z`NULL`:this.ms(Z,$)}fraction(Z,$){return this.dialect==="postgres"?Z`CAST(${$} AS DOUBLE PRECISION)`:Z`${$}`}async claimUpdating(Z,$){let V=this.sql,z=this.now(V),X=this.ms(V,$.visibilityTimeoutMs),Y=this.name(V);if(this.dialect==="postgres")return await V`
|
|
445
445
|
WITH next AS (
|
|
446
446
|
SELECT id FROM ${Y}
|
|
447
447
|
WHERE ${this.claimable(V,$)}
|
|
@@ -493,7 +493,7 @@ import{Sk as r,Tk as x0,Vk as Z1,fl as l0}from"./chunk-m3fbewhz.js";import{hl as
|
|
|
493
493
|
AND ${this.runnable(Z,$,"available_at")})
|
|
494
494
|
OR (status = 'claimed' AND lease_expires_at <= ${V}
|
|
495
495
|
AND ${this.runnable(Z,$,"lease_expires_at")})
|
|
496
|
-
)`}runnable(Z,$,V){let z=$.registered;if(!z)return Z`1 = 1`;let X=z.names.length?Z`name IN (${z.names.map((G)=>Z`${G}`).reduce((G,B)=>Z`${G}, ${B}`)})`:Z`1 = 0`;if(!Number.isFinite(z.graceMs))return X;let Y=Z.unsafe(V);return Z`(${X} OR ${Y} <= ${this.now(Z)} - ${this.ms(Z,z.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,$){let V=Math.max(0,Math.round($));return this.dialect==="mysql"||this.dialect==="mariadb"?Z`CAST(${V} AS SIGNED)`:Z`CAST(${V} AS BIGINT)`}}function U0(Z){let $=Z;return Math.max(Number($.count??0),Number($.affectedRows??0))}function
|
|
496
|
+
)`}runnable(Z,$,V){let z=$.registered;if(!z)return Z`1 = 1`;let X=z.names.length?Z`name IN (${z.names.map((G)=>Z`${G}`).reduce((G,B)=>Z`${G}, ${B}`)})`:Z`1 = 0`;if(!Number.isFinite(z.graceMs))return X;let Y=Z.unsafe(V);return Z`(${X} OR ${Y} <= ${this.now(Z)} - ${this.ms(Z,z.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,$){let V=Math.max(0,Math.round($));return this.dialect==="mysql"||this.dialect==="mariadb"?Z`CAST(${V} AS SIGNED)`:Z`CAST(${V} AS BIGINT)`}}function U0(Z){let $=Z;return Math.max(Number($.count??0),Number($.affectedRows??0))}function L1(Z,$){if(Z==="mysql"||Z==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${$}\` (
|
|
497
497
|
\`id\` VARCHAR(191) NOT NULL,
|
|
498
498
|
\`name\` VARCHAR(191) NOT NULL,
|
|
499
499
|
\`payload\` LONGTEXT NOT NULL,
|
|
@@ -528,10 +528,10 @@ import{Sk as r,Tk as x0,Vk as Z1,fl as l0}from"./chunk-m3fbewhz.js";import{hl as
|
|
|
528
528
|
"updated_at" BIGINT NOT NULL,
|
|
529
529
|
"batch_id" TEXT,
|
|
530
530
|
"progress" ${Z==="sqlite"?"REAL":"DOUBLE PRECISION"}${z}
|
|
531
|
-
)`,`CREATE INDEX IF NOT EXISTS "${$}_status_available_at_idx" ON "${$}"("status", "available_at")`,`CREATE INDEX IF NOT EXISTS "${$}_status_lease_expires_at_idx" ON "${$}"("status", "lease_expires_at")`,`CREATE INDEX IF NOT EXISTS "${$}_batch_id_idx" ON "${$}"("batch_id")`]}function
|
|
531
|
+
)`,`CREATE INDEX IF NOT EXISTS "${$}_status_available_at_idx" ON "${$}"("status", "available_at")`,`CREATE INDEX IF NOT EXISTS "${$}_status_lease_expires_at_idx" ON "${$}"("status", "lease_expires_at")`,`CREATE INDEX IF NOT EXISTS "${$}_batch_id_idx" ON "${$}"("batch_id")`]}function C1(Z,$){if(Z==="mysql"||Z==="mariadb")return[`ALTER TABLE \`${$}\` ADD COLUMN \`batch_id\` VARCHAR(191) NULL,
|
|
532
532
|
ADD COLUMN \`progress\` DOUBLE NULL,
|
|
533
533
|
ADD INDEX \`${$}_batch_id_idx\`(\`batch_id\`)`];let V=Z==="sqlite"?"REAL":"DOUBLE PRECISION";if(Z==="sqlite")return[`ALTER TABLE "${$}" ADD COLUMN "batch_id" TEXT`,`ALTER TABLE "${$}" ADD COLUMN "progress" ${V}`,`CREATE INDEX IF NOT EXISTS "${$}_batch_id_idx" ON "${$}"("batch_id")`];return[`ALTER TABLE "${$}" ADD COLUMN IF NOT EXISTS "batch_id" TEXT,
|
|
534
|
-
ADD COLUMN IF NOT EXISTS "progress" ${V}`,`CREATE INDEX IF NOT EXISTS "${$}_batch_id_idx" ON "${$}"("batch_id")`]}function
|
|
534
|
+
ADD COLUMN IF NOT EXISTS "progress" ${V}`,`CREATE INDEX IF NOT EXISTS "${$}_batch_id_idx" ON "${$}"("batch_id")`]}function W1(Z,$){if(Z==="mysql"||Z==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${$}\` (
|
|
535
535
|
\`id\` VARCHAR(191) NOT NULL,
|
|
536
536
|
\`name\` VARCHAR(191) NULL,
|
|
537
537
|
\`total\` INTEGER NOT NULL,
|
|
@@ -563,7 +563,7 @@ ADD COLUMN IF NOT EXISTS "progress" ${V}`,`CREATE INDEX IF NOT EXISTS "${$}_batc
|
|
|
563
563
|
"finished_at" BIGINT,
|
|
564
564
|
"created_at" BIGINT NOT NULL,
|
|
565
565
|
"updated_at" BIGINT NOT NULL${z}
|
|
566
|
-
)`]}function hZ(Z){let $=JSON.parse(Z.options),V=(z)=>z==null?null:Number(z);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:V(Z.cancelled_at),finishedAt:V(Z.finished_at),createdAt:Number(Z.created_at),allowFailures:$.allowFailures===!0,callbacks:$.callbacks??{}}}function W1(Z){return JSON.stringify({allowFailures:Z.allowFailures,callbacks:Z.callbacks})}function bZ(Z){let $=String(Z?.message??Z);return/does not exist|doesn't exist|unknown column|no such (table|column)|has no column/i.test($)}async function o0(Z,$){try{return await Z}catch(V){if(!bZ(V))throw V;throw Error(`Job batches need the "${$}" 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:V})}}function O3(Z){return Z}function qZ(){return{jobs:[],jobsDir:"app/jobs",workflows:[],workflowsDir:"app/workflows",concurrency:1,driver:"memory",visibilityTimeout:300000,pollInterval:1000,unknownJobGrace:3600000,locks:"auto"}}var O1=86400000;class ZZ{queue;workflows=new Map;steps=new Map;items=new Map;sources=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(O1);let $=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:$,updatedAt:$}),this.steps.set(Z.id,new Map),this.tick(Z.id,0)}async find(Z,$={}){let V=this.workflows.get(Z);if(!V)return null;return{workflow:{...V},steps:$.steps===!1?[]:this.stepsOf(Z)}}async acquire(Z,$,V){let z=this.workflows.get(Z);if(!z)return{kind:"missing"};let X=Date.now();if(z.lockedBy!==null&&!h0(z.lockedBy,$)&&(z.lockedUntil??0)>X)return z.retick=!0,{kind:"busy"};return z.lockedBy=$,z.lockedUntil=X+V,z.retick=!1,{kind:"acquired",workflow:{...z},steps:this.stepsOf(Z)}}async renew(Z,$,V){let z=this.workflows.get(Z);if(!z||z.lockedBy!==$)return!1;return z.lockedUntil=Date.now()+V,!0}statusOf(Z){return this.workflows.get(Z)?.status}async update(Z,$,V){let z=this.workflows.get(Z);if(!z)return;if($.owner!==void 0&&z.lockedBy!==$.owner)throw new b(Z);let X=this.steps.get(Z),Y=$.key===void 0?void 0:X.get($.key),G=Date.now(),B=V({workflow:{...z},step:Y?{...Y}:null,steps:$.allSteps?this.stepsOf(Z):[],items:$.items===void 0?[]:this.itemsOf(Z,$.items,["running","retrying"],-1,1/0),now:G});if(B.step){let H=X.get(B.step.key);X.set(B.step.key,{...B.step,createdAt:H?.createdAt??G,updatedAt:G})}if(B.items){let H=this.rowsOf(Z,B.items.step);for(let Q of B.items.delete??[])H.all.delete(Q),H.open.delete(Q);for(let Q of[...B.items.insert??[],...B.items.update??[]]){let J=H.all.get(Q.index);if(H.all.set(Q.index,{...Q,step:B.items.step,createdAt:J?.createdAt??G,updatedAt:G}),Q.status==="running"||Q.status==="retrying")H.open.add(Q.index);else H.open.delete(Q.index)}}if(B.batch)this.queue.enqueueBatch(B.batch);for(let H of B.cancelBatches??[])this.queue.cancelBatch(H);if(B.workflow)Object.assign(z,B.workflow);if(z.updatedAt=G,B.tick)this.tick(Z,B.tick.delayMs);if(B.unlock){if(z.lockedBy=null,z.lockedUntil=null,z.retick)z.retick=!1,this.tick(Z,0)}return B.result}async prune(Z){let $=Date.now()-Z,V=0;for(let[z,X]of this.workflows)if(["completed","failed","cancelled"].includes(X.status)&&X.updatedAt<=$){this.workflows.delete(z),this.steps.delete(z),this.items.delete(z);for(let[G,B]of this.sources)if(B.workflowId===z)this.sources.delete(G);V++}return V}async writeSource(Z,$,V){let z=this.sources.get(Z);if(!z)z={workflowId:$,createdAt:Date.now(),rows:new Map},this.sources.set(Z,z);for(let X of V){if(z.rows.has(X.index))throw Error(`Item source "${Z}" already has an item at index ${X.index}.`);z.rows.set(X.index,X.payload)}}async readSource(Z,$,V){let z=this.sources.get(Z)?.rows,X=[];if(!z)return X;for(let Y=Math.max(0,$);Y<V;Y++){let G=z.get(Y);if(G!==void 0)X.push({index:Y,payload:G})}return X}async deleteSource(Z){let $=this.sources.get(Z)?.rows.size??0;return this.sources.delete(Z),$}async pruneSources(Z){let $=Date.now()-Z,V=0;for(let[z,X]of this.sources)if(X.workflowId===null&&X.createdAt<=$)V+=X.rows.size,this.sources.delete(z);return V}async listItems(Z,$,V){return this.itemsOf(Z,$,V.statuses,V.after??-1,V.limit)}itemsOf(Z,$,V,z,X){let Y=this.items.get(Z)?.get($);if(!Y)return[];let B=V.every((Q)=>Q==="running"||Q==="retrying")?[...Y.open]:[...Y.all.keys()],H=[];for(let Q of B.sort((J,F)=>J-F)){if(Q<=z)continue;let J=Y.all.get(Q);if(!V.includes(J.status))continue;if(H.push({...J}),H.length>=X)break}return H}rowsOf(Z,$){let V=this.items.get(Z);if(!V)this.items.set(Z,V=new Map);let z=V.get($);if(!z)V.set($,z={all:new Map,open:new Set});return z}stepsOf(Z){return[...this.steps.get(Z)?.values()??[]].map(($)=>({...$}))}tick(Z,$){this.queue.enqueue({name:m,args:JSON.stringify([Z]),delayMs:Math.max(0,Math.round($))})}}function $Z(Z){return`workflow:${Z}`}var mZ=191;function u0(Z,$){if(Z===void 0||Z===null)return[];let V=Array.isArray(Z)?Z:[Z],z=new Set,X=[];for(let Y of V){if(Y===void 0||Y===null)continue;let{key:G,limit:B}=Y??{};if(typeof G!=="string"||G.length===0||G.length>mZ)throw TypeError(`${$}.concurrency returned a key that is not a string of 1 to ${mZ} characters: ${JSON.stringify(G)}.`);if(typeof B!=="number"||!Number.isInteger(B)||B<0)throw TypeError(`${$}.concurrency returned the limit ${String(B)} for "${G}"; a limit is a whole number, 0 or more.`);if(z.has(G))throw TypeError(`${$}.concurrency returned the key "${G}" twice.`);z.add(G),X.push({key:G,limit:B})}return X}class VZ{host;lines=new Map;keysOf=new Map;order=0;constructor(Z){this.host=Z}line(Z){let $=this.lines.get(Z),V=$?this.sorted($):[];return{holding:V.filter((z)=>z.state==="holding").map((z)=>z.holder),waiting:V.filter((z)=>z.state==="waiting").map((z)=>z.holder)}}acquire(Z){let $;for(let V of this.keysOf.get(Z.holder)??[]){let z=this.lines.get(V)?.tickets.get(Z.holder);if(z&&($===void 0||z.order<$))$=z.order}$??=this.order++;for(let{key:V,limit:z}of Z.slots){let X=this.lines.get(V)??{key:V,limit:z,tickets:new Map};this.lines.set(V,X),X.limit=z,this.prune(X);let Y=X.tickets.get(Z.holder);if(!Y){Y={holder:Z.holder,state:"waiting",order:$,jobId:Z.job.id,workflowId:Z.workflowId},X.tickets.set(Z.holder,Y);let H=this.keysOf.get(Z.holder)??new Set;H.add(V),this.keysOf.set(Z.holder,H)}Y.jobId=Z.job.id;let G=()=>this.holders(X)+this.ahead(X,Y)<z;if(Y.state==="waiting"&&!G())this.wake(X,Z.holder);if(Y.state==="waiting"&&G())Y.state="holding";if(Y.state==="holding"){this.wake(X,Z.holder);continue}let B=this.ahead(X,Y)<Math.max(1,z);return this.host.park(Z.job,B?Z.recheckMs.near:Z.recheckMs.far),!1}return!0}release(Z){let $=this.keysOf.get(Z);if(!$)return;this.keysOf.delete(Z);for(let V of $){let z=this.lines.get(V);if(!z)continue;if(z.tickets.delete(Z),this.prune(z),this.wake(z,Z),z.tickets.size===0)this.lines.delete(V)}}sorted(Z){return[...Z.tickets.values()].sort(($,V)=>$.order-V.order||($.holder<V.holder?-1:$.holder>V.holder?1:0))}holders(Z){let $=0;for(let V of Z.tickets.values())if(V.state==="holding")$++;return $}ahead(Z,$){let V=0;for(let z of Z.tickets.values()){if(z.state!=="waiting"||z===$)continue;if(z.order<$.order||z.order===$.order&&z.holder<$.holder)V++}return V}alive(Z){return Z.workflowId!==void 0?this.host.workflowAlive(Z.workflowId):this.host.jobAlive(Z.jobId)}prune(Z){for(let $ of Z.tickets.values())if($.state==="holding"&&!this.alive($))this.forget(Z,$)}wake(Z,$){let V=Z.limit-this.holders(Z);for(let z of this.sorted(Z)){if(V<=0)return;if(z.state!=="waiting"||z.holder===$)continue;if(!this.alive(z)){this.forget(Z,z);continue}if(!this.host.wake(z.jobId)){if(z.workflowId===void 0){this.forget(Z,z);continue}z.jobId=this.host.tick(z.workflowId)}V--}}forget(Z,$){Z.tickets.delete($.holder);let V=this.keysOf.get($.holder);if(V?.delete(Z.key),V?.size===0)this.keysOf.delete($.holder)}}var E1=86400000;class p0{entries=new Map;batches=new Map;workflows;slots=new VZ({jobAlive:(Z)=>this.entries.has(Z),workflowAlive:(Z)=>{let $=this.workflows?.statusOf(Z);return $!==void 0&&$!=="completed"&&$!=="failed"&&$!=="cancelled"&&$!=="paused"},park:(Z,$)=>{let V=this.current(Z);if(!V)return;V.job={...V.job,attempt:V.job.attempt-1},V.leased=!1,V.until=Date.now()+Math.max(0,$),this.changed()},wake:(Z)=>{let $=this.entries.get(Z);if(!$)return!1;if(!$.leased&&$.until>Date.now())$.until=Date.now(),this.changed();return!0},tick:(Z)=>{let $=this.add({name:m,args:JSON.stringify([Z])});return this.changed(),$}});listeners=new Set;timer;timerAt=1/0;seq=0;get waiting(){let Z=0;for(let $ of this.entries.values())if(!$.leased)Z++;return Z}get leased(){return this.entries.size-this.waiting}async enqueue(Z){let $=this.add(Z);return this.changed(),$}add({name:Z,args:$,delayMs:V=0,id:z=crypto.randomUUID()},X){let Y=Date.now();return this.entries.set(z,{job:{id:z,name:Z,args:$,attempt:0,createdAt:Y,...X===void 0?{}:{batchId:X}},until:Y+Math.max(0,V),leased:!1,seq:this.seq++,progress:0}),z}async enqueueBatch(Z){this.recordBatch(Z)}recordBatch(Z){let $=Date.now();this.forgetFinishedBatches($);let V=q0({...Z,total:Z.args.length,now:$});for(let Y of Z.args)this.add({name:Z.job,args:Y},Z.id);let{record:z,calls:X}=F0(V,V,$);this.batches.set(Z.id,z);for(let Y of X)this.add(Y);this.changed()}async findBatch(Z,$={}){let V=this.batches.get(Z);if(!V)return null;if($.progress===!1||V.pending===0)return G0(V);let z=0;for(let X of this.entries.values())if(X.job.batchId===Z)z+=X.progress;return G0(V,z)}async cancelBatch(Z){return this.cancelBatchNow(Z)}cancelBatchNow(Z){let $=this.batches.get(Z);if(!$||$.finishedAt!==null||$.cancelledAt!==null)return!1;let V=Date.now(),z=K0($,V,this.cancelWaiting(Z));return this.save($,z,V),this.changed(),!0}workflowStore(){return this.workflows??=new ZZ({enqueue:(Z)=>{this.add(Z),this.changed()},enqueueBatch:(Z)=>this.recordBatch(Z),cancelBatch:(Z)=>void this.cancelBatchNow(Z)}),this.workflows}async acquireSlots(Z){return this.slots.acquire(Z)}async releaseSlots(Z){this.slots.release(Z)}async reportProgress(Z,$){let V=this.current(Z);if(V)V.progress=i($)}async claim(Z,$){let V=Date.now(),z=[...this.entries.values()].filter((X)=>X.until<=V).sort((X,Y)=>X.until-Y.until||X.seq-Y.seq).slice(0,Math.max(0,Z));for(let X of z)X.job={...X.job,attempt:X.job.attempt+1},X.leased=!0,X.until=V+$.visibilityTimeoutMs;if(z.length>0)this.schedule();return z.map((X)=>({...X.job}))}async complete(Z){let $=this.current(Z);if(!$)return;this.entries.delete(Z.id),this.count($,"succeeded"),this.schedule()}async fail(Z,$){let V=this.current(Z);if(!V)return;let z=V.job.batchId===void 0?void 0:this.batches.get(V.job.batchId),X=$.cancelled===!0||$.retryInMs!==null&&z?.cancelledAt!=null;if($.retryInMs===null||X){this.entries.delete(Z.id),this.count(V,X?"cancelled":"failed"),this.schedule();return}V.leased=!1,V.until=Date.now()+Math.max(0,$.retryInMs),V.seq=this.seq++,V.progress=0,this.changed()}async release(Z,$){let V=this.current(Z);if(!V)return;V.job={...V.job,attempt:V.job.attempt-1},V.leased=!1,V.until=Date.now()+Math.max(0,$.retryInMs),V.seq=this.seq++,this.changed()}async heartbeat(Z,$){let V=Date.now()+$.visibilityTimeoutMs;for(let z of Z){let X=this.current(z);if(X)X.until=V}this.schedule()}count(Z,$){let V=Z.job.batchId;if(V===void 0)return;let z=this.batches.get(V);if(!z)return;let X=Date.now(),Y=m0(z,$,Z.job.id);if(k0(z,Y))Y=K0(Y,X,this.cancelWaiting(V));this.save(z,Y,X),this.changed()}save(Z,$,V){let{record:z,calls:X}=F0(Z,$,V);this.batches.set(z.id,z);for(let Y of X)this.add(Y)}cancelWaiting(Z){let $=0;for(let[V,z]of this.entries)if(z.job.batchId===Z&&!z.leased)this.entries.delete(V),$++;return $}forgetFinishedBatches(Z){for(let[$,V]of this.batches)if(V.finishedAt!==null&&Z-V.finishedAt>E1)this.batches.delete($)}subscribe(Z){return this.listeners.add(Z),()=>void this.listeners.delete(Z)}current(Z){let $=this.entries.get(Z.id);if(!$||!$.leased||$.job.attempt!==Z.attempt)return;return $}changed(){this.schedule();let Z=Date.now();for(let $ of this.entries.values())if($.until<=Z){this.wake();return}}wake(){for(let Z of[...this.listeners])Z()}schedule(){let Z=Date.now(),$=1/0;for(let V of this.entries.values())if(V.until>Z&&V.until<$)$=V.until;if($===this.timerAt)return;if(clearTimeout(this.timer),this.timer=void 0,this.timerAt=$,$===1/0)return;this.timer=setTimeout(()=>{this.timer=void 0,this.timerAt=1/0,this.changed()},$-Z),this.timer.unref?.()}}import{AsyncResource as w1}from"async_hooks";import{existsSync as d1}from"fs";import{isMainThread as l1}from"worker_threads";class Q0{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,$={}){this.$outcome={kind:"fail",error:Z instanceof Error?Z:Error(String(Z)),retry:$.retry??!0}}batch=void 0;async progress(Z){let $=i(Z);await this.$progress?.($)}$progress;$claimed;$outcome;run(...Z){}onFail(Z,...$){}onSuccess(Z,...$){}onDeadletter(Z,...$){}static dispatch(...Z){if(this.name==="unset")throw Error("Cannot dispatch a job with no name");return B0($0).push(this,JSON.stringify(Z))}static dispatchBatch(Z,$={}){if(this.name==="unset")throw Error("Cannot dispatch a job with no name");return B0($0).pushBatch(this,Z.map((V)=>JSON.stringify(V)),$)}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 B0($0).findBatch(Z)}static cancelBatch(Z){return B0($0).cancelBatch(Z)}}function E0(Z,$){let V=Array.isArray(Z)?Z[Math.min($,Z.length)-1]:Z;return Math.max(0,V??0)}class YZ extends Error{step;batch;summary;constructor(Z,$,V,z){super($);this.step=Z;this.batch=V;this.summary=z;this.name="StepFailedError"}}class GZ extends Error{step;constructor(Z){super(`No signal "${Z}" arrived before its timeout.`);this.step=Z;this.name="WaitTimeoutError"}}class BZ extends Error{constructor(Z,$){super(`Step "${Z}" took longer than its timeout of ${$}ms.`);this.name="StepTimeoutError"}}class QZ extends Error{constructor(Z){super(`Workflow ${Z} was cancelled.`);this.name="WorkflowCancelledError"}}class t extends Error{constructor(){super("The workflow is suspended until a step can continue. Rethrow this error if you catch it.");this.name="WorkflowSuspended"}}var kZ=Symbol("done"),uZ=Symbol("paused");class FZ{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(($)=>[$.key,$]))}run(Z,$,V={}){return this.track(Z,()=>this.runStep(Z,$,V))}sleep(Z,$){let V=r($);return this.track(Z,()=>this.sleepStep(Z,V))}waitFor(Z,$={}){let V=$.timeout===void 0?void 0:r($.timeout);return this.track(Z,()=>this.waitStep(Z,V))}batch(Z,$,V,z={}){return this.track(Z,()=>this.batchStep(Z,$,V,z))}each(Z,$,V){return this.track(Z,()=>this.eachStep(Z,$,V))}source(Z,$,V={}){let z=`${this.workflowId}:${Z}`;return this.run(Z,async()=>KZ(this.tick.store,z,await $(),this.workflowId),V)}async progress(Z){let $=i(Z);this.assertRunning();let V=this.write(void 0,()=>({result:void 0,workflow:{progress:$}}));this.remember(V),await V}async settled(){while(this.pending.size>0)await Promise.allSettled(this.pending)}track(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 V=$();return this.remember(V),V}remember(Z){this.pending.add(Z);let $=()=>void this.pending.delete(Z);Z.then($,$)}assertRunning(){if(this.lost)throw new b(this.workflowId);if(this.suspension)throw new t}suspend(Z,$){if(!this.suspension)this.suspension={status:Z,wakes:[]};if($!=null)this.suspension.wakes.push($);throw new t}async write(Z,$,V={}){let z;try{z=await this.tick.store.update(this.tick.workflowId,{owner:this.tick.owner,...Z===void 0?{}:{key:Z},...V.items&&Z!==void 0?{items:Z}:{},...V.joinTransaction?{joinTransaction:!0}:{}},(X)=>{if(X.workflow.status==="cancelling"&&!this.tick.cancelling)return{result:kZ};if(V.start&&X.workflow.status==="paused"&&!this.tick.cancelling)return{result:uZ};let Y=$(X);return{...Y,result:{value:Y.result}}})}catch(X){if(X instanceof b)this.lost=!0;throw X}if(z===void 0)throw this.lost=!0,new b(this.tick.workflowId);if(z===kZ)this.cancelled=!0,this.suspend("waiting");if(z===uZ)this.suspend("paused");return z.value}record(Z,$,V){let z={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,...$,...V};return this.steps.set(Z,z),z}mismatch(Z,$,V){throw Error(`Step "${Z}" of workflow ${this.tick.workflowId} was recorded as a ${$} step, and is now used as ${V}. A key belongs to one step; rename one of them.`)}async runStep(Z,$,V){let z=Math.max(1,Math.floor(V.attempts??3)),X=V.timeout===void 0?void 0:r(V.timeout),Y=this.steps.get(Z);if(Y?.status==="completed")return n(Y.output);if(Y?.status==="failed")throw s(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:N,step:P,now:W})=>{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>W)return{result:{kind:"wait",wakeAt:P.wakeAt}};let D=(P?.attempt??0)+1;if(D>z){let _=this.record(Z,P,{status:"failed",error:`Attempt ${D-1} of ${z} never finished, most likely because the process running it exited.`+(P?.error?` The last error was: ${P.error}`:""),finishedAt:W,wakeAt:null});return{result:{kind:"failed",step:_},step:_}}let T=this.record(Z,P,{status:"running",attempt:D,startedAt:W,finishedAt:null,wakeAt:null});return{result:{kind:"run",attempt:D},step:T,workflow:N.status==="cancelling"?{currentStep:Z}:{currentStep:Z,status:"running"}}},{start:!0});if(this.current=Z,G.kind==="done")return n(G.output);if(G.kind==="failed")throw s(Z,G.step);if(G.kind==="wait")this.suspend("sleeping",G.wakeAt);let B=G.attempt,H,Q,J=!0;try{H=await this.execute(Z,$,B,X)}catch(N){Q=N}if(this.cancelled)throw new t;let F=null;if(Q===void 0)try{F=S0(H,`The result of step "${Z}"`)}catch(N){Q=N,J=!1}if(Q===void 0)return await this.write(Z,({step:N,now:P})=>({result:void 0,step:this.record(Z,N,{status:"completed",output:F,error:null,wakeAt:null,finishedAt:P})})),n(F);let U=N0(Q);if(J&&B<z){let N=E0(V.backoff??0,B),P=await this.write(Z,({step:W,now:D})=>{let T=N>0?D+N:null;return{result:T,step:this.record(Z,W,{status:"retrying",error:U,wakeAt:T})}});if(P!==null)this.suspend("sleeping",P);continue}let A=await this.write(Z,({step:N,now:P})=>{let W=this.record(Z,N,{status:"failed",error:U,wakeAt:null,finishedAt:P});return{result:W,step:W}});throw s(Z,A)}}async execute(Z,$,V,z){let X=new AbortController,Y={idempotencyKey:`${this.tick.workflowId}:${Z}`,attempt:V,signal:X.signal},G=Promise.resolve().then(()=>$(Y)),B,H,Q=new Promise((J,F)=>{let U=(A)=>{X.abort(A),F(A)};if(z!==void 0)B=setTimeout(()=>U(new BZ(Z,z)),z);if(!this.tick.cancelling)H=setInterval(()=>{this.tick.store.find(this.tick.workflowId,{steps:!1}).then((A)=>{if(A?.workflow.status!=="cancelling"||X.signal.aborted)return;if(this.cancelled=!0,!this.suspension)this.suspension={status:"waiting",wakes:[]};U(new QZ(this.tick.workflowId))}).catch(()=>{})},this.tick.cancelCheckMs),H.unref?.()});try{return await Promise.race([G,Q])}finally{clearTimeout(B),clearInterval(H),G.catch(()=>{}),Q.catch(()=>{})}}async sleepStep(Z,$){let V=this.steps.get(Z);if(V?.status==="completed")return;if(this.current=Z,V?.status==="sleeping"&&V.wakeAt!==null&&V.wakeAt>Date.now())this.suspend("sleeping",V.wakeAt);let z=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+$;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(z!==null)this.suspend("sleeping",z)}async waitStep(Z,$){let V=this.steps.get(Z);if(V?.status==="completed")return n(V.output);if(V?.status==="timed_out")throw new GZ(Z);if(this.current=Z,V?.status==="waiting"&&(V.wakeAt===null||V.wakeAt>Date.now()))this.suspend("waiting",V.wakeAt);let z=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=$===void 0?null:Y+$;return{result:{kind:"wait",wakeAt:G},step:this.record(Z,null,{status:"waiting",wakeAt:G,startedAt:Y}),workflow:{currentStep:Z}}});if(z.kind==="value")return n(z.output);if(z.kind==="timeout")throw new GZ(Z);this.suspend("waiting",z.wakeAt)}async eachStep(Z,$,V){let z=$.source,X=z?z.count:$.count;if(!z&&typeof $.item!=="function")throw TypeError(`step.each "${Z}" needs either { count, item } or { source }.`);if(!Number.isSafeInteger(X)||X<0||X>pZ)throw TypeError(`step.each "${Z}" needs a count that is a whole number from 0 to ${pZ}; got ${String(X)}.`);let Y=Math.max(1,Math.floor($.concurrency??1)),G=Math.max(1,Math.floor($.attempts??3)),B=$.timeout===void 0?void 0:r($.timeout),H=$.tickBudget===void 0?T1:r($.tickBudget),Q=$.progress!==!1,J=$.chunk!==void 0,F=J?Math.max(1,Math.floor($.chunk)):1,U=[$.throttle??[]].flat().map((K)=>({name:`gemi:throttle:${K.key}`,limit:Math.max(0,Math.floor(K.limit)),windowMs:r(K.window)})),A=M1($.maxFailures),N=this.tick.store,P=$.transaction===!0&&N.transaction?(K)=>N.transaction(K):void 0;if($.transaction===!0&&!P)y1();let W=z?sZ(N,z,Math.max(I1,Y*F*4)):$.item;if(!N.listItems)throw Error("This queue's workflow store does not support step.each. The memory and database drivers do.");if(U.length>0&&!this.tick.throttle)throw Error(`step.each "${Z}" has a throttle, and this queue has no lock store.`);let D=this.steps.get(Z);if(D?.status==="completed")return PZ(D.output);if(D?.status==="failed")throw s(Z,D);if(D&&D.status!=="iterating")this.mismatch(Z,D.status,"step.each");if(this.current=Z,this.tick.durable===!1)h1();let T=await this.write(Z,({workflow:K,step:R,items:L,now:O})=>{if(R?.status==="completed")return{result:{kind:"done",output:R.output}};if(R?.status==="failed")return{result:{kind:"failed",step:R}};if(R&&R.status!=="iterating")this.mismatch(Z,R.status,"step.each");let x=R?c0(R.output):j1(X);return{result:{kind:"go",state:x,open:L},...R?{}:{step:this.record(Z,null,{status:"iterating",output:XZ(x),startedAt:O})},workflow:K.status==="cancelling"?{currentStep:Z}:{currentStep:Z,status:"running"}}},{items:!0,start:!0});if(T.kind==="done")return PZ(T.output);if(T.kind==="failed")throw s(Z,T.step);let _=T.state;if(_.count!==X)f1(this.workflowId,Z,_.count,X);let D0=_.count,d=new Map(T.open.map((K)=>[K.index,K])),k=[],_0=new Map,a0=new Map,_Z=Date.now()+H,H0=0,M0=!1,V0=null,p=new AbortController,LZ=setInterval(()=>{N.find(this.workflowId,{steps:!1}).then((K)=>{if(K?.workflow.status==="paused")M0=!0;if(K?.workflow.status!=="cancelling"||p.signal.aborted)return;if(this.cancelled=!0,!this.suspension)this.suspension={status:"waiting",wakes:[]};p.abort(new QZ(this.workflowId))}).catch(()=>{})},this.tick.cancelCheckMs);LZ.unref?.(),V0=A(_);let CZ=(K,R)=>{let L={...K};for(let O of R)if(O.counter)L[O.counter]++;return L},WZ=(K)=>{let R=K.succeeded+K.skipped+K.failed;return Q?{workflow:{progress:D0===0?1:i(R/D0)}}:{}},OZ=(K)=>{if(_={count:_.count,next:Math.max(_.next,K.next),succeeded:Math.max(_.succeeded,K.succeeded),skipped:Math.max(_.skipped,K.skipped),failed:Math.max(_.failed,K.failed)},!V0)V0=A(_);if(V0&&!p.signal.aborted)p.abort(new t)},z1=async(K)=>{let R=K.map(()=>null),L=new Map,O=new AbortController,x=()=>O.abort(p.signal.reason);p.signal.addEventListener("abort",x,{once:!0});let u,z0=K.length===1?`${Z}[${K[0].index}]`:`${Z}[${K[0].index}..${K.at(-1).index}]`,L0=new Promise((C,S)=>{if(O.signal.addEventListener("abort",()=>S(O.signal.reason),{once:!0}),B!==void 0)u=setTimeout(()=>O.abort(new BZ(z0,B)),B)}),y=(C)=>{throw new JZ(Math.max(0,Math.floor(Number(C)||0)))},X0=(C)=>K.map((S,q)=>{let l=L.get(q);if(!l)return{index:S.index,row:null,counter:"succeeded"};return{index:S.index,row:wZ(S,R[q],l.reason,l.data,C),counter:"skipped"}}),Y0=null,g=(async()=>{let C=await Promise.all(K.map((M)=>W(M.index)));K.forEach((M,v)=>{R[v]=x1($.key?$.key(C[v],M.index):M.index)});let S=(M)=>`${this.workflowId}:${Z}:${R[M]}`,q=Math.max(...K.map((M)=>M.attempt)),l=async()=>{if(J){let M={idempotencyKey:S(0),attempt:q,signal:O.signal,items:K.map((v,f)=>({index:v.index,key:R[f],idempotencyKey:S(f)})),skip:(v,f,I)=>{if(!Number.isInteger(v)||v<0||v>=K.length)throw RangeError(`ctx.skip: no item at position ${v} of this chunk.`);L.set(v,{reason:String(f),data:I})},release:y};await V(C,M)}else{let M={idempotencyKey:S(0),attempt:q,signal:O.signal,index:K[0].index,key:R[0],skip:(v,f)=>{throw new HZ(v,f)},release:y};await V(C[0],M)}};if(!P)return l();await P(async()=>{if(await l(),O.signal.aborted)throw O.signal.reason;let M=X0(Date.now()),v=await this.write(Z,({step:f})=>{let I={step:Z,insert:[],update:[],delete:[]};for(let J0 of M)if(J0.row===null)I.delete.push(J0.index);else I.update.push(J0.row);let a=CZ(f?c0(f.output):_,M);return{result:a,step:this.record(Z,f,{status:"iterating",output:XZ(a)}),items:I,...WZ(a)}},{joinTransaction:!0});Y0=M.map((f)=>({...f,recorded:!0})),OZ(v)})})(),j,E=!1;try{await Promise.race([g,L0])}catch(C){E=!0,j=C}finally{clearTimeout(u),p.signal.removeEventListener("abort",x),g.catch(()=>{}),L0.catch(()=>{})}if(Y0){k.push(...Y0);return}if(p.signal.aborted||this.cancelled||this.lost)return;let h=Date.now();if(!E){k.push(...X0(h));return}if(j instanceof HZ){k.push({index:K[0].index,row:wZ(K[0],R[0],j.reason,j.data,h),counter:"skipped"});return}if(j instanceof JZ){H0=Math.max(H0,h+j.delayMs),K.forEach((C,S)=>{k.push({index:C.index,row:{...C,key:R[S],status:"retrying",attempt:Math.max(0,C.attempt-1),wakeAt:h+j.delayMs},counter:null})});return}let c=T0(N0(j),2000);K.forEach((C,S)=>{if(C.attempt<G){let q=E0($.backoff??0,C.attempt);k.push({index:C.index,row:{...C,key:R[S],status:"retrying",error:c,wakeAt:h+q},counter:null});return}k.push({index:C.index,row:{...C,key:R[S],status:"failed",error:c,wakeAt:null,finishedAt:h},counter:"failed"})})},X1=async(K)=>{if(U.length===0||K===0)return K;let R=this.tick.throttle;for(let L=0;L<K;L++){let O=[];for(let x of U){let u=await R.hit(x.name,x.limit,x.windowMs);if(!u.allowed)return await Promise.all(O.map((z0)=>R.refund(z0))),H0=Math.max(H0,Date.now()+Math.max(1,u.resetInMs)),L;O.push(x.name)}}return K},Y1=async(K)=>{if(U.length===0)return;for(let R=0;R<K;R++)for(let L of U)await this.tick.throttle.refund(L.name)};try{for(;;){let K=Date.now(),R=K>=_Z||w0()||this.cancelled||M0||V0!==null,L=[],O=0;if(!R&&K>=H0){let y=(Y-_0.size)*F,X0=new Set(k.map((j)=>j.index));for(let j of[...d.values()].sort((E,h)=>E.index-h.index)){if(L.length>=y)break;if(a0.has(j.index)||X0.has(j.index))continue;if(j.status==="running"||(j.wakeAt??0)<=K)L.push(j)}let Y0=Y*F+cZ-d.size;O=Math.max(0,Math.min(y-L.length,D0-_.next,Y0));let g=await X1(L.length+O);if(g<L.length)L=L.slice(0,g),O=0;else O=g-L.length}if(k.length>0||L.length>0||O>0){let y=k.splice(0,k.length),X0=y.filter((E)=>!E.recorded),Y0=L.length+O,g=await this.write(Z,({workflow:E,step:h,now:c})=>{let C=CZ(h?c0(h.output):_,X0),S={step:Z,insert:[],update:[],delete:[]},q=[],l=[];for(let I of X0)if(I.row===null)S.delete.push(I.index);else S.update.push(I.row);let M=E.status==="paused"&&!this.tick.cancelling;for(let I of M?[]:L){if(I.attempt+1>G){let J0={...I,status:"failed",error:T0(`Attempt ${I.attempt} of ${G} never finished, most likely because the process running it exited.`+(I.error?` The last error was: ${I.error}`:""),2000),wakeAt:null,finishedAt:c};C.failed++,S.update.push(J0),l.push(J0);continue}let a={...I,status:"running",attempt:I.attempt+1,wakeAt:null,startedAt:c};S.update.push(a),q.push(a)}let v=M?0:O,f=q.length;for(let I=0;I<v;I++){let a=v1(this.workflowId,Z,C.next+I,c);S.insert.push(a),q.push(a)}return C.next+=v,{result:{next:C,started:q,closed:l,reruns:f,paused:M},step:this.record(Z,h,{status:"iterating",output:XZ(C)}),items:S,...WZ(C)}});if(OZ(g.next),g.paused)M0=!0;await Y1(Y0-g.started.length);for(let E of y)if(E.row?.status==="retrying")d.set(E.index,E.row);else d.delete(E.index);for(let E of g.closed)d.delete(E.index);for(let E of g.started)d.set(E.index,E);let j=[...dZ(g.started.slice(0,g.reruns),F),...dZ(g.started.slice(g.reruns),F)];for(let E of j){let h=E[0].index;for(let c of E)a0.set(c.index,h);_0.set(h,z1(E).finally(()=>{_0.delete(h);for(let c of E)a0.delete(c.index)}))}}if(_0.size>0){await Promise.race(_0.values());continue}if(k.length>0)continue;if(this.cancelled)throw new t;if(V0)break;if(_.next>=D0&&d.size===0)break;if(M0)this.suspend("paused");if(R)this.suspend("running",Date.now());let x=Date.now(),u=1/0;if(_.next<D0&&d.size<Y*F+cZ)u=x;for(let y of d.values())if(y.status==="running")u=x;else if(y.status==="retrying")u=Math.min(u,y.wakeAt??0);let z0=Math.max(u,H0);if(z0<=x)continue;let L0=z0-x;if(L0<=Math.min(S1,_Z-x)){await new Promise((y)=>setTimeout(y,Math.max(0,L0)));continue}this.suspend("sleeping",z0)}}finally{if(clearInterval(LZ),!p.signal.aborted)p.abort(new t)}let EZ=await N.listItems(this.workflowId,Z,{statuses:["failed","skipped"],limit:zZ+1}),i0={...UZ(_),problems:EZ.slice(0,zZ).map(NZ),moreProblems:EZ.length>zZ},G1=JSON.stringify({$each:_,problems:i0.problems,moreProblems:i0.moreProblems}),j0=V0,B1=await this.write(Z,({step:K,now:R})=>{let L=this.record(Z,K,{status:j0?"failed":"completed",output:G1,error:j0,finishedAt:R});return{result:L,step:L,...Q&&!j0?{workflow:{progress:1}}:{}}});if(j0)throw s(Z,B1);return i0}async batchStep(Z,$,V,z){let X=z.allowFailures===!0,Y=this.steps.get(Z);if(Y?.status==="completed")return n(Y.output);if(Y?.status==="failed")throw s(Z,Y);if(Y&&Y.status!=="batching")this.mismatch(Z,Y.status,"step.batch");if(this.current=Z,!Y){let F=this.tick.buildBatch($,V,{name:z.name??`workflow:${this.tick.workflowId}:${Z}`,allowFailures:X});if(Y=await this.write(Z,({step:U,now:A})=>{if(U)return{result:U};let N=this.record(Z,null,{status:"batching",batchId:F.id,startedAt:A});return{result:N,step:N,batch:F,workflow:{currentStep:Z}}},{start:!0}),this.tick.scheduled(),Y.status==="completed")return n(Y.output);if(Y.status==="failed")throw s(Z,Y)}let G=Y.batchId===null?null:await this.tick.findBatch(Y.batchId);if(G&&G.finishedAt===null)this.suspend("waiting");let B=G!==null&&G.cancelledAt===null&&(G.failed===0||X),H=G===null?null:JSON.stringify(G),Q=B?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}.`,J=await this.write(Z,({step:F,now:U})=>{let A=this.record(Z,F,{status:B?"completed":"failed",output:H,error:Q,finishedAt:U});return{result:A,step:A}});if(!B)throw s(Z,J);return G}}function s(Z,$){if($.output?.startsWith('{"$each"'))return new YZ(Z,`Step "${Z}" failed: ${$.error??"unknown error"}`,void 0,PZ($.output));let V=$.batchId!==null&&$.output!==null?JSON.parse($.output):void 0;return new YZ(Z,V?$.error??`Step "${Z}" failed.`:`Step "${Z}" failed: ${$.error??"unknown error"}`,V)}function S0(Z,$){if(Z===void 0)return null;let V=JSON.stringify(Z);if(V===void 0)throw TypeError(`${$} cannot be stored: JSON has no form for it.`);let z=Buffer.byteLength(V,"utf8");if(z>n0)throw RangeError(`${$} is ${z} bytes as JSON, over the ${n0}-byte limit. Store it elsewhere and return its id.`);return V}function n(Z){return Z===null?void 0:JSON.parse(Z)}function N0(Z){return Z instanceof Error?Z.message:String(Z)}var pZ=2147483647,T1=30000,cZ=100,S1=1000,I1=64,zZ=100;class HZ extends Error{reason;data;constructor(Z,$){super(`Skipped: ${Z}`);this.reason=Z;this.data=$;this.name="ItemSkipped"}}class JZ extends Error{delayMs;constructor(Z){super(`Released for ${Z}ms`);this.delayMs=Z;this.name="ItemReleased"}}function wZ(Z,$,V,z,X){let Y=null,G=T0(String(V));try{Y=g1(z)}catch(B){G=T0(`${G} (${N0(B)})`)}return{...Z,key:$,status:"skipped",error:G,output:Y,wakeAt:null,finishedAt:X}}function dZ(Z,$){let V=[];for(let z=0;z<Z.length;z+=$)V.push(Z.slice(z,z+$));return V}function M1(Z){if(Z===void 0)return()=>null;if(typeof Z==="number"){let z=Math.max(0,Math.floor(Z));return(X)=>X.failed>z?`${X.failed} items failed, more than maxFailures (${z}).`:null}let $=Math.min(1,Math.max(0,Z.ratio)),V=Math.max(1,Math.floor(Z.after??20));return(z)=>{let X=z.succeeded+z.skipped+z.failed;if(X<V||z.failed/X<=$)return null;return`${z.failed} of ${X} items failed, more than maxFailures allows (a ratio of ${$}).`}}function j1(Z){return{count:Z,next:0,succeeded:0,skipped:0,failed:0}}function XZ(Z){return JSON.stringify({$each:Z})}function c0(Z){let $=Z===null?null:JSON.parse(Z);if(!$?.$each)throw Error("A step.each step has no state.");return $.$each}function nZ(Z){if(Z===null||!Z.startsWith('{"$each"'))return null;try{return UZ(c0(Z))}catch{return null}}function UZ(Z){return{total:Z.count,done:Z.succeeded+Z.skipped+Z.failed,succeeded:Z.succeeded,skipped:Z.skipped,failed:Z.failed}}function PZ(Z){let $=JSON.parse(Z??"null");return{...UZ($.$each),problems:$.problems??[],moreProblems:$.moreProblems===!0}}function NZ(Z){let $={index:Z.index,key:Z.key,status:Z.status==="skipped"?"skipped":"failed",reason:T0(Z.error??""),attempt:Z.attempt};if(Z.output!==null)$.data=JSON.parse(Z.output);return $}function v1(Z,$,V,z){return{workflowId:Z,step:$,index:V,key:null,status:"running",attempt:1,error:null,output:null,wakeAt:null,startedAt:z,finishedAt:null,createdAt:z,updatedAt:z}}function x1(Z){let $=typeof Z==="number"&&Number.isFinite(Z)?String(Z):Z;if(typeof $!=="string"||$.length===0||$.length>191)throw TypeError(`An item key is a string of 1 to 191 characters, or a number; got ${JSON.stringify(Z)}.`);return $}function T0(Z,$=500){return Z.length<=$?Z:`${Z.slice(0,$-1)}\u2026`}function g1(Z){if(Z===void 0)return null;let $=JSON.stringify(Z);if($===void 0)throw TypeError("its data has no JSON form, so it was not kept");if(Buffer.byteLength($,"utf8")>1024)throw RangeError("its data is over 1 KB as JSON, so it was not kept");return $}var lZ=!1;function h1(){if(lZ||Bun.env.NODE_ENV!=="production")return;lZ=!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 aZ=!1;function y1(){if(aZ)return;aZ=!0,console.warn("[gemi] step.each with transaction: true runs its items without a transaction: this queue's workflow store cannot record an item in the app's transaction (only the database driver on Postgres or MySQL can). Items are at least once.")}var iZ=new Set;function f1(Z,$,V,z){let X=`${Z}:${$}`;if(iZ.has(X))return;iZ.add(X),console.warn(`[gemi] step.each "${$}" of workflow ${Z} was started with a count of ${V} and is now given ${z}. It goes on with ${V}: the count is fixed when the step first runs.`)}function d0(Z){return Z==="completed"||Z==="failed"||Z==="cancelled"}var R0=["completed","failed","cancelled"],b1=1000,q1=250,m1=30000;class RZ{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 $ of Z){if($.name==="unset"||!$.name){console.error("A workflow class has no `static name`, so it was not registered. Add one.");continue}if(this.registry[$.name]){console.error(`Two workflows are named "${$.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[$.name]=$}}get tickJob(){return this.tickClass??=k1(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(l0))return Z.make(l0);return this.ownFeed??=new l0,this.ownFeed}channel(Z){return`gemi:workflow:${Z}`}async update(Z){let $=await this.find(Z);if(!$)return null;let{args:V,result:z,...X}=$;return X}stream(Z,$,V={}){return this.feed.stream(Z,this.channel($),V)}cursor(Z){return this.feed.cursor(this.channel(Z))}async*subscribe(Z,$={}){let V=this.feed.subscribe(this.channel(Z),{signal:$.signal});try{await V.ready();let z=await this.update(Z);if(!z)return;if(yield z,d0(z.status))return;let X=V[Symbol.asyncIterator](),Y=X.next();for(;;){let G=await c1(Y,m1),B;if(G==="timeout")B=await this.update(Z);else{if(G.done)return;Y=X.next(),B=p1(G.value,Z)??await this.update(Z)}if(!B||B.updatedAt<z.updatedAt)continue;if(JSON.stringify(B)===JSON.stringify(z))continue;if(z=B,yield z,d0(z.status))return}}finally{V.close()}}publishingStore(Z){let $=(z)=>void rZ(()=>this.schedulePublish(z)),V={create:(z)=>Z.create(z).then((X)=>{return $(z.id),X}),find:(z,X)=>Z.find(z,X),acquire:(z,X,Y)=>Z.acquire(z,X,Y),renew:(z,X,Y)=>Z.renew(z,X,Y),update:(z,X,Y)=>Z.update(z,X,Y).then((G)=>{return $(z),G})};if(Z.joinsTransaction)V.joinsTransaction=()=>Z.joinsTransaction();if(Z.transaction)V.transaction=(z)=>Z.transaction(z);if(Z.listItems)V.listItems=(...z)=>Z.listItems(...z);if(Z.prune)V.prune=(z)=>Z.prune(z);if(Z.writeSource)V.writeSource=(...z)=>Z.writeSource(...z),V.readSource=(...z)=>Z.readSource(...z),V.deleteSource=(...z)=>Z.deleteSource(...z),V.pruneSources=(...z)=>Z.pruneSources(...z);return V}schedulePublish(Z){if(this.publishing.has(Z))return;let $=Math.max(0,(this.published.get(Z)??0)+q1-Date.now()),V=setTimeout(()=>{this.publishing.delete(Z),this.published.set(Z,Date.now()),this.publish(Z)},$);V.unref?.(),this.publishing.set(Z,V)}async publish(Z){try{let $=await this.update(Z);if(!$)return;if(d0($.status))this.published.delete(Z);await this.feed.publish(this.channel(Z),$)}catch($){console.error(`[gemi] Workflow ${Z}: could not publish its change.`,$)}}async close(){for(let Z of this.publishing.values())clearTimeout(Z);this.publishing.clear(),await this.ownFeed?.close(),this.ownFeed=void 0}start(Z,$){if(Z.name==="unset"||!Z.name)throw Error("Cannot start a workflow with no name");let V=this.store,z={id:Bun.randomUUIDv7(),name:Z.name,args:S0($,`The arguments of ${Z.name}`)??"[]"},X=()=>this.queue.claimSoon(),Y=V.joinsTransaction?.()===!0;if(!Y){if(o(()=>V.create(z).then(X,(Q)=>{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.`,Q)})))return Promise.resolve(z.id)}let G=V.create(z),B=Y&&o(X);return G.then(()=>{if(!B)X();return z.id})}async signal(Z,$,V){if(typeof $!=="string"||$.length===0||$.length>191)throw TypeError("A signal key is a string of 1 to 191 characters.");let z=S0(V,`The payload of signal "${$}"`),X=await this.store.update(Z,{key:$},({workflow:Y,step:G,now:B})=>{if(R0.includes(Y.status)||Y.status==="cancelling")return{result:!1};if(!G)return{result:!0,step:{workflowId:Z,key:$,status:"signalled",attempt:0,output:z,error:null,batchId:null,wakeAt:null,startedAt:null,finishedAt:B,createdAt:B,updatedAt:B}};if(G.status!=="waiting")return{result:!1};return{result:!0,step:{...G,status:"signalled",output:z,wakeAt:G.wakeAt,finishedAt:B},tick:{delayMs:0}}});if(X)this.queue.claimSoon();return X===!0}async cancel(Z){let $=await this.store.update(Z,{allSteps:!0},({workflow:V,steps:z})=>{if(R0.includes(V.status)||V.status==="cancelling")return{result:!1};return{result:!0,workflow:{status:"cancelling"},cancelBatches:z.filter((X)=>X.status==="batching"&&X.batchId!==null).map((X)=>X.batchId),tick:{delayMs:0}}});if($)this.queue.claimSoon();return $===!0}async pause(Z){let $=await this.store.update(Z,{},({workflow:V})=>{if(R0.includes(V.status)||V.status==="cancelling"||V.status==="paused")return{result:!1};return{result:!0,workflow:{status:"paused"}}});if($===!0)this.releaseSlotsOf(Z);return $===!0}async resume(Z){let $=await this.store.update(Z,{},({workflow:V})=>{if(V.status!=="paused")return{result:!1};return{result:!0,workflow:{status:"running",wakeAt:null},tick:{delayMs:0}}});if($)this.queue.claimSoon();return $===!0}async find(Z){let $=await this.store.find(Z);if(!$)return null;let{workflow:V,steps:z}=$,X=[];try{X=JSON.parse(V.args)}catch{}return{id:V.id,name:V.name,status:V.status,args:X,currentStep:V.currentStep,progress:V.progress,result:u1(V.result),error:V.error,steps:await Promise.all(z.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},B=nZ(Y.output);if(B)return{...G,items:B,progress:B.total===0?1:B.done/B.total};if(Y.batchId===null)return G;let H=await this.queue.driver.findBatch?.(Y.batchId);return H?{...G,progress:H.progress}:G})),createdAt:V.createdAt,updatedAt:V.updatedAt}}async items(Z,$,V={}){let z=this.store;if(!z.listItems)return[];let X=Math.max(1,Math.min(1000,Math.floor(V.limit??100)));return(await z.listItems(Z,$,{statuses:V.status?[V.status]:["failed","skipped"],...V.after===void 0?{}:{after:V.after},limit:X})).map(NZ)}async tick(Z,$){let V=this.store,z=$.$claimed,X=z?`${z.id}:${z.attempt}`:`${crypto.randomUUID()}:1`,Y=Math.max(1,this.queue.config.visibilityTimeout),G=await V.acquire(Z,X,Y);if(G.kind!=="acquired")return;let{workflow:B}=G,H=(P={})=>V.update(Z,{owner:X},()=>({...P,result:void 0,unlock:!0})).then(()=>this.queue.claimSoon()).catch((W)=>{if(!(W instanceof b))throw W});if(R0.includes(B.status)||B.status==="paused"){await H(),await this.releaseSlotsOf(Z,B);return}let Q=this.registry[B.name];if(!Q)return this.unknown(B,$,H);let J;try{J=JSON.parse(B.args)}catch(P){return H({workflow:{status:"failed",error:`The arguments are not JSON: ${N0(P)}`}})}let F=B.status==="cancelling",U;try{U=await this.limitsOf(Q,J)}catch(P){throw await H(),P}if(U.length>0&&!F&&z){let P=this.queue.driver;if(!P.acquireSlots||!P.releaseSlots)return H({workflow:{status:"failed",error:`${B.name} declares concurrency, and this queue's driver has no concurrency slots. The memory and database drivers do.`}});if(!await P.acquireSlots({holder:$Z(Z),workflowId:Z,job:z,slots:U,recheckMs:this.queue.slotRecheck()}))return $.$outcome={kind:"parked"},H()}let A=setInterval(()=>{V.renew(Z,X,Y).catch((P)=>{console.error(`[gemi] Could not extend the hold on workflow ${Z}.`,P)})},Math.max(1,Math.floor(Y/3)));A.unref?.();let N=new FZ({workflowId:Z,owner:X,store:V,steps:G.steps,cancelling:F,findBatch:(P)=>this.queue.driver.findBatch?.(P,{progress:!1})??Promise.resolve(null),buildBatch:(P,W,D)=>this.queue.buildBatch(P,W.map((T)=>JSON.stringify(T)),{name:D.name,allowFailures:D.allowFailures,finally:{name:m,args:[Z]}}),scheduled:()=>this.queue.claimSoon(),cancelCheckMs:b1,durable:this.queue.durable,throttle:{hit:(P,W,D)=>this.queue.locks.store.hit(P,W,D),refund:(P)=>this.queue.locks.store.refund(P)}});try{let P;try{let D=new Q,T=await(F?D.onCancel(N,...J):D.run(N,...J));P=N.suspension?{kind:"suspended"}:{kind:"completed",result:F?null:S0(T,`The result of ${B.name}`)}}catch(D){if(P=N.suspension||D instanceof t?{kind:"suspended"}:{kind:"failed",error:N0(D)},D instanceof b)N.lost=!0}if(await N.settled(),N.lost)return;if(P.kind==="completed"&&N.suspension)P={kind:"suspended"};let W;if(await V.update(Z,{owner:X},({workflow:D,now:T})=>{let _=this.finish(D,P,N,F,T);return W=_.workflow?.status??D.status,_}),this.queue.claimSoon(),U.length>0&&W!==void 0&&(R0.includes(W)||W==="paused"))await this.releaseSlots(Z)}catch(P){if(P instanceof b)return;throw P}finally{clearInterval(A)}}finish(Z,$,V,z,X){let Y={result:void 0,unlock:!0};if(Z.status==="cancelling"&&!z)return{...Y,tick:{delayMs:0}};if($.kind==="completed")return{...Y,workflow:z?{status:"cancelled",currentStep:null,wakeAt:null}:{status:"completed",result:$.result,progress:1,currentStep:null,wakeAt:null,error:null}};if($.kind==="failed")return{...Y,workflow:{status:z?"cancelled":"failed",error:$.error,wakeAt:null}};let G=V.suspension??{status:"waiting",wakes:[]};if(!z&&(Z.status==="paused"||G.status==="paused"))return Z.status==="paused"?{...Y,workflow:{currentStep:V.current??Z.currentStep}}:{...Y,workflow:{status:"running"},tick:{delayMs:0}};let B={...Y,workflow:{status:z?"cancelling":G.status,currentStep:V.current??Z.currentStep}};if(G.wakes.length>0){let H=Math.min(...G.wakes);if(!(Z.wakeAt!==null&&Z.wakeAt>X&&Z.wakeAt<=H))B.tick={delayMs:Math.max(0,H-X)},B.workflow.wakeAt=H}return B}async limitsOf(Z,$){let V=new Z;if(typeof V.concurrency!=="function")return[];return u0(await V.concurrency(...$),Z.name)}async releaseSlots(Z){try{await this.queue.driver.releaseSlots?.($Z(Z))}catch($){console.error(`[gemi] Could not free the concurrency slots of workflow ${Z}.`,$)}}async releaseSlotsOf(Z,$){try{let V=$??(await this.store.find(Z,{steps:!1}))?.workflow,z=V&&this.registry[V.name];if(!V||!z)return;if((await this.limitsOf(z,JSON.parse(V.args))).length>0)await this.releaseSlots(Z)}catch(V){console.error(`[gemi] Could not free the concurrency slots of workflow ${Z}.`,V)}}async unknown(Z,$,V){let z=Date.now()-Z.createdAt;if(this.queue.durable&&z<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 V(),$.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 V({workflow:{status:"failed",error:`No workflow is registered under the name "${Z.name}".`}})}tickDeadLettered(Z,$){console.error(`[gemi] The tick of workflow ${Z} was dead-lettered.`,$),this.store.update(Z,{},({workflow:V})=>R0.includes(V.status)?{result:void 0}:{result:void 0,workflow:{status:"failed",error:`Its tick job was dead-lettered: ${$.message}`},unlock:!0}).then(()=>this.releaseSlotsOf(Z)).catch(()=>{})}}function k1(Z){return class extends Q0{static name=m;maxAttempts=20;backoff=[1000,5000,15000,30000,60000];async run(V){await Z.tick(V,this)}onDeadletter(V,z){Z.tickDeadLettered(z,V)}}}function u1(Z){try{return n(Z)}catch{return Z}}function p1(Z,$){if(Z.type!=="change")return null;let V=Z.data;if(!V||typeof V!=="object"||V.id!==$||typeof V.updatedAt!=="number")return null;return V}async function c1(Z,$){let V,z=new Promise((X)=>{V=setTimeout(()=>X("timeout"),$)});try{return await Promise.race([Z,z])}finally{clearTimeout(V)}}var __dirname="/home/runner/work/gemi/gemi/packages/gemi/services/queue";function a1(Z=process.env){let $=Z.ROOT_DIR??process.cwd(),V=Z.APP_DIR??`${$}/app`,z=Z.NODE_ENV==="production"?`${$}/dist/server/bootstrap.mjs`:`${V}/bootstrap.ts`,X;try{X=Bun.resolveSync("gemi/app",$)}catch{X=Bun.resolveSync("gemi/app",__dirname)}return{bootstrap:d1(z)?z:void 0,kernel:`${V}/kernel/Kernel.ts`,app:X}}function i1(){let Z=a1(),$=Z.bootstrap?`const { app } = await import(${JSON.stringify(Z.bootstrap)});`:`const { App } = await import(${JSON.stringify(Z.app)});
|
|
566
|
+
)`]}function yZ(Z){let $=JSON.parse(Z.options),V=(z)=>z==null?null:Number(z);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:V(Z.cancelled_at),finishedAt:V(Z.finished_at),createdAt:Number(Z.created_at),allowFailures:$.allowFailures===!0,callbacks:$.callbacks??{}}}function O1(Z){return JSON.stringify({allowFailures:Z.allowFailures,callbacks:Z.callbacks})}function qZ(Z){let $=String(Z?.message??Z);return/does not exist|doesn't exist|unknown column|no such (table|column)|has no column/i.test($)}async function o0(Z,$){try{return await Z}catch(V){if(!qZ(V))throw V;throw Error(`Job batches need the "${$}" 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:V})}}function E3(Z){return Z}function mZ(){return{jobs:[],jobsDir:"app/jobs",workflows:[],workflowsDir:"app/workflows",concurrency:1,driver:"memory",visibilityTimeout:300000,pollInterval:1000,unknownJobGrace:3600000,locks:"auto"}}var E1=86400000;class ZZ{queue;workflows=new Map;steps=new Map;items=new Map;sources=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(E1);let $=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:$,updatedAt:$}),this.steps.set(Z.id,new Map),this.tick(Z.id,0)}async find(Z,$={}){let V=this.workflows.get(Z);if(!V)return null;return{workflow:{...V},steps:$.steps===!1?[]:this.stepsOf(Z)}}async acquire(Z,$,V){let z=this.workflows.get(Z);if(!z)return{kind:"missing"};let X=Date.now();if(z.lockedBy!==null&&!h0(z.lockedBy,$)&&(z.lockedUntil??0)>X)return z.retick=!0,{kind:"busy"};return z.lockedBy=$,z.lockedUntil=X+V,z.retick=!1,{kind:"acquired",workflow:{...z},steps:this.stepsOf(Z)}}async renew(Z,$,V){let z=this.workflows.get(Z);if(!z||z.lockedBy!==$)return!1;return z.lockedUntil=Date.now()+V,!0}statusOf(Z){return this.workflows.get(Z)?.status}async update(Z,$,V){let z=this.workflows.get(Z);if(!z)return;if($.owner!==void 0&&z.lockedBy!==$.owner)throw new b(Z);let X=this.steps.get(Z),Y=$.key===void 0?void 0:X.get($.key),G=Date.now(),B=V({workflow:{...z},step:Y?{...Y}:null,steps:$.allSteps?this.stepsOf(Z):[],items:$.items===void 0?[]:this.itemsOf(Z,$.items,["running","retrying"],-1,1/0),now:G});if(B.step){let H=X.get(B.step.key);X.set(B.step.key,{...B.step,createdAt:H?.createdAt??G,updatedAt:G})}if(B.items){let H=this.rowsOf(Z,B.items.step);for(let Q of B.items.delete??[])H.all.delete(Q),H.open.delete(Q);for(let Q of[...B.items.insert??[],...B.items.update??[]]){let J=H.all.get(Q.index);if(H.all.set(Q.index,{...Q,step:B.items.step,createdAt:J?.createdAt??G,updatedAt:G}),Q.status==="running"||Q.status==="retrying")H.open.add(Q.index);else H.open.delete(Q.index)}}if(B.batch)this.queue.enqueueBatch(B.batch);for(let H of B.cancelBatches??[])this.queue.cancelBatch(H);if(B.workflow)Object.assign(z,B.workflow);if(z.updatedAt=G,B.tick)this.tick(Z,B.tick.delayMs);if(B.unlock){if(z.lockedBy=null,z.lockedUntil=null,z.retick)z.retick=!1,this.tick(Z,0)}return B.result}async prune(Z){let $=Date.now()-Z,V=0;for(let[z,X]of this.workflows)if(["completed","failed","cancelled"].includes(X.status)&&X.updatedAt<=$){this.workflows.delete(z),this.steps.delete(z),this.items.delete(z);for(let[G,B]of this.sources)if(B.workflowId===z)this.sources.delete(G);V++}return V}async writeSource(Z,$,V){let z=this.sources.get(Z);if(!z)z={workflowId:$,createdAt:Date.now(),rows:new Map},this.sources.set(Z,z);for(let X of V){if(z.rows.has(X.index))throw Error(`Item source "${Z}" already has an item at index ${X.index}.`);z.rows.set(X.index,X.payload)}}async readSource(Z,$,V){let z=this.sources.get(Z)?.rows,X=[];if(!z)return X;for(let Y=Math.max(0,$);Y<V;Y++){let G=z.get(Y);if(G!==void 0)X.push({index:Y,payload:G})}return X}async deleteSource(Z){let $=this.sources.get(Z)?.rows.size??0;return this.sources.delete(Z),$}async pruneSources(Z){let $=Date.now()-Z,V=0;for(let[z,X]of this.sources)if(X.workflowId===null&&X.createdAt<=$)V+=X.rows.size,this.sources.delete(z);return V}async listItems(Z,$,V){return this.itemsOf(Z,$,V.statuses,V.after??-1,V.limit)}itemsOf(Z,$,V,z,X){let Y=this.items.get(Z)?.get($);if(!Y)return[];let B=V.every((Q)=>Q==="running"||Q==="retrying")?[...Y.open]:[...Y.all.keys()],H=[];for(let Q of B.sort((J,F)=>J-F)){if(Q<=z)continue;let J=Y.all.get(Q);if(!V.includes(J.status))continue;if(H.push({...J}),H.length>=X)break}return H}rowsOf(Z,$){let V=this.items.get(Z);if(!V)this.items.set(Z,V=new Map);let z=V.get($);if(!z)V.set($,z={all:new Map,open:new Set});return z}stepsOf(Z){return[...this.steps.get(Z)?.values()??[]].map(($)=>({...$}))}tick(Z,$){this.queue.enqueue({name:m,args:JSON.stringify([Z]),delayMs:Math.max(0,Math.round($))})}}function $Z(Z){return`workflow:${Z}`}var kZ=191;function u0(Z,$){if(Z===void 0||Z===null)return[];let V=Array.isArray(Z)?Z:[Z],z=new Set,X=[];for(let Y of V){if(Y===void 0||Y===null)continue;let{key:G,limit:B}=Y??{};if(typeof G!=="string"||G.length===0||G.length>kZ)throw TypeError(`${$}.concurrency returned a key that is not a string of 1 to ${kZ} characters: ${JSON.stringify(G)}.`);if(typeof B!=="number"||!Number.isInteger(B)||B<0)throw TypeError(`${$}.concurrency returned the limit ${String(B)} for "${G}"; a limit is a whole number, 0 or more.`);if(z.has(G))throw TypeError(`${$}.concurrency returned the key "${G}" twice.`);z.add(G),X.push({key:G,limit:B})}return X}class VZ{host;lines=new Map;keysOf=new Map;order=0;constructor(Z){this.host=Z}line(Z){let $=this.lines.get(Z),V=$?this.sorted($):[];return{holding:V.filter((z)=>z.state==="holding").map((z)=>z.holder),waiting:V.filter((z)=>z.state==="waiting").map((z)=>z.holder)}}acquire(Z){let $;for(let V of this.keysOf.get(Z.holder)??[]){let z=this.lines.get(V)?.tickets.get(Z.holder);if(z&&($===void 0||z.order<$))$=z.order}$??=this.order++;for(let{key:V,limit:z}of Z.slots){let X=this.lines.get(V)??{key:V,limit:z,tickets:new Map};this.lines.set(V,X),X.limit=z,this.prune(X);let Y=X.tickets.get(Z.holder);if(!Y){Y={holder:Z.holder,state:"waiting",order:$,jobId:Z.job.id,workflowId:Z.workflowId},X.tickets.set(Z.holder,Y);let H=this.keysOf.get(Z.holder)??new Set;H.add(V),this.keysOf.set(Z.holder,H)}Y.jobId=Z.job.id;let G=()=>this.holders(X)+this.ahead(X,Y)<z;if(Y.state==="waiting"&&!G())this.wake(X,Z.holder);if(Y.state==="waiting"&&G())Y.state="holding";if(Y.state==="holding"){this.wake(X,Z.holder);continue}let B=this.ahead(X,Y)<Math.max(1,z);return this.host.park(Z.job,B?Z.recheckMs.near:Z.recheckMs.far),!1}return!0}release(Z){let $=this.keysOf.get(Z);if(!$)return;this.keysOf.delete(Z);for(let V of $){let z=this.lines.get(V);if(!z)continue;if(z.tickets.delete(Z),this.prune(z),this.wake(z,Z),z.tickets.size===0)this.lines.delete(V)}}sorted(Z){return[...Z.tickets.values()].sort(($,V)=>$.order-V.order||($.holder<V.holder?-1:$.holder>V.holder?1:0))}holders(Z){let $=0;for(let V of Z.tickets.values())if(V.state==="holding")$++;return $}ahead(Z,$){let V=0;for(let z of Z.tickets.values()){if(z.state!=="waiting"||z===$)continue;if(z.order<$.order||z.order===$.order&&z.holder<$.holder)V++}return V}alive(Z){return Z.workflowId!==void 0?this.host.workflowAlive(Z.workflowId):this.host.jobAlive(Z.jobId)}prune(Z){for(let $ of Z.tickets.values())if($.state==="holding"&&!this.alive($))this.forget(Z,$)}wake(Z,$){let V=Z.limit-this.holders(Z);for(let z of this.sorted(Z)){if(V<=0)return;if(z.state!=="waiting"||z.holder===$)continue;if(!this.alive(z)){this.forget(Z,z);continue}if(!this.host.wake(z.jobId)){if(z.workflowId===void 0){this.forget(Z,z);continue}z.jobId=this.host.tick(z.workflowId)}V--}}forget(Z,$){Z.tickets.delete($.holder);let V=this.keysOf.get($.holder);if(V?.delete(Z.key),V?.size===0)this.keysOf.delete($.holder)}}var T1=86400000;class p0{entries=new Map;batches=new Map;workflows;slots=new VZ({jobAlive:(Z)=>this.entries.has(Z),workflowAlive:(Z)=>{let $=this.workflows?.statusOf(Z);return $!==void 0&&$!=="completed"&&$!=="failed"&&$!=="cancelled"&&$!=="paused"},park:(Z,$)=>{let V=this.current(Z);if(!V)return;V.job={...V.job,attempt:V.job.attempt-1},V.leased=!1,V.until=Date.now()+Math.max(0,$),this.changed()},wake:(Z)=>{let $=this.entries.get(Z);if(!$)return!1;if(!$.leased&&$.until>Date.now())$.until=Date.now(),this.changed();return!0},tick:(Z)=>{let $=this.add({name:m,args:JSON.stringify([Z])});return this.changed(),$}});listeners=new Set;timer;timerAt=1/0;seq=0;get waiting(){let Z=0;for(let $ of this.entries.values())if(!$.leased)Z++;return Z}get leased(){return this.entries.size-this.waiting}async enqueue(Z){let $=this.add(Z);return this.changed(),$}add({name:Z,args:$,delayMs:V=0,id:z=crypto.randomUUID()},X){let Y=Date.now();return this.entries.set(z,{job:{id:z,name:Z,args:$,attempt:0,createdAt:Y,...X===void 0?{}:{batchId:X}},until:Y+Math.max(0,V),leased:!1,seq:this.seq++,progress:0}),z}async enqueueBatch(Z){this.recordBatch(Z)}recordBatch(Z){let $=Date.now();this.forgetFinishedBatches($);let V=q0({...Z,total:Z.args.length,now:$});for(let Y of Z.args)this.add({name:Z.job,args:Y},Z.id);let{record:z,calls:X}=F0(V,V,$);this.batches.set(Z.id,z);for(let Y of X)this.add(Y);this.changed()}async findBatch(Z,$={}){let V=this.batches.get(Z);if(!V)return null;if($.progress===!1||V.pending===0)return G0(V);let z=0;for(let X of this.entries.values())if(X.job.batchId===Z)z+=X.progress;return G0(V,z)}async cancelBatch(Z){return this.cancelBatchNow(Z)}cancelBatchNow(Z){let $=this.batches.get(Z);if(!$||$.finishedAt!==null||$.cancelledAt!==null)return!1;let V=Date.now(),z=K0($,V,this.cancelWaiting(Z));return this.save($,z,V),this.changed(),!0}workflowStore(){return this.workflows??=new ZZ({enqueue:(Z)=>{this.add(Z),this.changed()},enqueueBatch:(Z)=>this.recordBatch(Z),cancelBatch:(Z)=>void this.cancelBatchNow(Z)}),this.workflows}async acquireSlots(Z){return this.slots.acquire(Z)}async releaseSlots(Z){this.slots.release(Z)}async reportProgress(Z,$){let V=this.current(Z);if(V)V.progress=i($)}async claim(Z,$){let V=Date.now(),z=[...this.entries.values()].filter((X)=>X.until<=V).sort((X,Y)=>X.until-Y.until||X.seq-Y.seq).slice(0,Math.max(0,Z));for(let X of z)X.job={...X.job,attempt:X.job.attempt+1},X.leased=!0,X.until=V+$.visibilityTimeoutMs;if(z.length>0)this.schedule();return z.map((X)=>({...X.job}))}async complete(Z){let $=this.current(Z);if(!$)return;this.entries.delete(Z.id),this.count($,"succeeded"),this.schedule()}async fail(Z,$){let V=this.current(Z);if(!V)return;let z=V.job.batchId===void 0?void 0:this.batches.get(V.job.batchId),X=$.cancelled===!0||$.retryInMs!==null&&z?.cancelledAt!=null;if($.retryInMs===null||X){this.entries.delete(Z.id),this.count(V,X?"cancelled":"failed"),this.schedule();return}V.leased=!1,V.until=Date.now()+Math.max(0,$.retryInMs),V.seq=this.seq++,V.progress=0,this.changed()}async release(Z,$){let V=this.current(Z);if(!V)return;V.job={...V.job,attempt:V.job.attempt-1},V.leased=!1,V.until=Date.now()+Math.max(0,$.retryInMs),V.seq=this.seq++,this.changed()}async heartbeat(Z,$){let V=Date.now()+$.visibilityTimeoutMs;for(let z of Z){let X=this.current(z);if(X)X.until=V}this.schedule()}count(Z,$){let V=Z.job.batchId;if(V===void 0)return;let z=this.batches.get(V);if(!z)return;let X=Date.now(),Y=m0(z,$,Z.job.id);if(k0(z,Y))Y=K0(Y,X,this.cancelWaiting(V));this.save(z,Y,X),this.changed()}save(Z,$,V){let{record:z,calls:X}=F0(Z,$,V);this.batches.set(z.id,z);for(let Y of X)this.add(Y)}cancelWaiting(Z){let $=0;for(let[V,z]of this.entries)if(z.job.batchId===Z&&!z.leased)this.entries.delete(V),$++;return $}forgetFinishedBatches(Z){for(let[$,V]of this.batches)if(V.finishedAt!==null&&Z-V.finishedAt>T1)this.batches.delete($)}subscribe(Z){return this.listeners.add(Z),()=>void this.listeners.delete(Z)}current(Z){let $=this.entries.get(Z.id);if(!$||!$.leased||$.job.attempt!==Z.attempt)return;return $}changed(){this.schedule();let Z=Date.now();for(let $ of this.entries.values())if($.until<=Z){this.wake();return}}wake(){for(let Z of[...this.listeners])Z()}schedule(){let Z=Date.now(),$=1/0;for(let V of this.entries.values())if(V.until>Z&&V.until<$)$=V.until;if($===this.timerAt)return;if(clearTimeout(this.timer),this.timer=void 0,this.timerAt=$,$===1/0)return;this.timer=setTimeout(()=>{this.timer=void 0,this.timerAt=1/0,this.changed()},$-Z),this.timer.unref?.()}}import{AsyncResource as d1}from"async_hooks";import{existsSync as l1}from"fs";import{isMainThread as a1}from"worker_threads";class Q0{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,$={}){this.$outcome={kind:"fail",error:Z instanceof Error?Z:Error(String(Z)),retry:$.retry??!0}}batch=void 0;async progress(Z){let $=i(Z);await this.$progress?.($)}$progress;$claimed;$outcome;run(...Z){}onFail(Z,...$){}onSuccess(Z,...$){}onDeadletter(Z,...$){}static dispatch(...Z){if(this.name==="unset")throw Error("Cannot dispatch a job with no name");return B0($0).push(this,JSON.stringify(Z))}static dispatchBatch(Z,$={}){if(this.name==="unset")throw Error("Cannot dispatch a job with no name");return B0($0).pushBatch(this,Z.map((V)=>JSON.stringify(V)),$)}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 B0($0).findBatch(Z)}static cancelBatch(Z){return B0($0).cancelBatch(Z)}}function E0(Z,$){let V=Array.isArray(Z)?Z[Math.min($,Z.length)-1]:Z;return Math.max(0,V??0)}class YZ extends Error{step;batch;summary;constructor(Z,$,V,z){super($);this.step=Z;this.batch=V;this.summary=z;this.name="StepFailedError"}}class GZ extends Error{step;constructor(Z){super(`No signal "${Z}" arrived before its timeout.`);this.step=Z;this.name="WaitTimeoutError"}}class BZ extends Error{constructor(Z,$){super(`Step "${Z}" took longer than its timeout of ${$}ms.`);this.name="StepTimeoutError"}}class QZ extends Error{constructor(Z){super(`Workflow ${Z} was cancelled.`);this.name="WorkflowCancelledError"}}class t extends Error{constructor(){super("The workflow is suspended until a step can continue. Rethrow this error if you catch it.");this.name="WorkflowSuspended"}}var uZ=Symbol("done"),pZ=Symbol("paused");class FZ{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(($)=>[$.key,$]))}run(Z,$,V={}){return this.track(Z,()=>this.runStep(Z,$,V))}sleep(Z,$){let V=r($);return this.track(Z,()=>this.sleepStep(Z,V))}waitFor(Z,$={}){let V=$.timeout===void 0?void 0:r($.timeout);return this.track(Z,()=>this.waitStep(Z,V))}batch(Z,$,V,z={}){return this.track(Z,()=>this.batchStep(Z,$,V,z))}each(Z,$,V){return this.track(Z,()=>this.eachStep(Z,$,V))}source(Z,$,V={}){let z=`${this.workflowId}:${Z}`;return this.run(Z,async()=>KZ(this.tick.store,z,await $(),this.workflowId),V)}async progress(Z){let $=i(Z);this.assertRunning();let V=this.write(void 0,()=>({result:void 0,workflow:{progress:$}}));this.remember(V),await V}async settled(){while(this.pending.size>0)await Promise.allSettled(this.pending)}track(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 V=$();return this.remember(V),V}remember(Z){this.pending.add(Z);let $=()=>void this.pending.delete(Z);Z.then($,$)}assertRunning(){if(this.lost)throw new b(this.workflowId);if(this.suspension)throw new t}suspend(Z,$){if(!this.suspension)this.suspension={status:Z,wakes:[]};if($!=null)this.suspension.wakes.push($);throw new t}async write(Z,$,V={}){let z;try{z=await this.tick.store.update(this.tick.workflowId,{owner:this.tick.owner,...Z===void 0?{}:{key:Z},...V.items&&Z!==void 0?{items:Z}:{},...V.joinTransaction?{joinTransaction:!0}:{}},(X)=>{if(X.workflow.status==="cancelling"&&!this.tick.cancelling)return{result:uZ};if(V.start&&X.workflow.status==="paused"&&!this.tick.cancelling)return{result:pZ};let Y=$(X);return{...Y,result:{value:Y.result}}})}catch(X){if(X instanceof b)this.lost=!0;throw X}if(z===void 0)throw this.lost=!0,new b(this.tick.workflowId);if(z===uZ)this.cancelled=!0,this.suspend("waiting");if(z===pZ)this.suspend("paused");return z.value}record(Z,$,V){let z={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,...$,...V};return this.steps.set(Z,z),z}mismatch(Z,$,V){throw Error(`Step "${Z}" of workflow ${this.tick.workflowId} was recorded as a ${$} step, and is now used as ${V}. A key belongs to one step; rename one of them.`)}async runStep(Z,$,V){let z=Math.max(1,Math.floor(V.attempts??3)),X=V.timeout===void 0?void 0:r(V.timeout),Y=this.steps.get(Z);if(Y?.status==="completed")return n(Y.output);if(Y?.status==="failed")throw s(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:N,step:P,now:W})=>{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>W)return{result:{kind:"wait",wakeAt:P.wakeAt}};let D=(P?.attempt??0)+1;if(D>z){let _=this.record(Z,P,{status:"failed",error:`Attempt ${D-1} of ${z} never finished, most likely because the process running it exited.`+(P?.error?` The last error was: ${P.error}`:""),finishedAt:W,wakeAt:null});return{result:{kind:"failed",step:_},step:_}}let T=this.record(Z,P,{status:"running",attempt:D,startedAt:W,finishedAt:null,wakeAt:null});return{result:{kind:"run",attempt:D},step:T,workflow:N.status==="cancelling"?{currentStep:Z}:{currentStep:Z,status:"running"}}},{start:!0});if(this.current=Z,G.kind==="done")return n(G.output);if(G.kind==="failed")throw s(Z,G.step);if(G.kind==="wait")this.suspend("sleeping",G.wakeAt);let B=G.attempt,H,Q,J=!0;try{H=await this.execute(Z,$,B,X)}catch(N){Q=N}if(this.cancelled)throw new t;let F=null;if(Q===void 0)try{F=S0(H,`The result of step "${Z}"`)}catch(N){Q=N,J=!1}if(Q===void 0)return await this.write(Z,({step:N,now:P})=>({result:void 0,step:this.record(Z,N,{status:"completed",output:F,error:null,wakeAt:null,finishedAt:P})})),n(F);let U=N0(Q);if(J&&B<z){let N=E0(V.backoff??0,B),P=await this.write(Z,({step:W,now:D})=>{let T=N>0?D+N:null;return{result:T,step:this.record(Z,W,{status:"retrying",error:U,wakeAt:T})}});if(P!==null)this.suspend("sleeping",P);continue}let A=await this.write(Z,({step:N,now:P})=>{let W=this.record(Z,N,{status:"failed",error:U,wakeAt:null,finishedAt:P});return{result:W,step:W}});throw s(Z,A)}}async execute(Z,$,V,z){let X=new AbortController,Y={idempotencyKey:`${this.tick.workflowId}:${Z}`,attempt:V,signal:X.signal},G=Promise.resolve().then(()=>$(Y)),B,H,Q=new Promise((J,F)=>{let U=(A)=>{X.abort(A),F(A)};if(z!==void 0)B=setTimeout(()=>U(new BZ(Z,z)),z);if(!this.tick.cancelling)H=setInterval(()=>{this.tick.store.find(this.tick.workflowId,{steps:!1}).then((A)=>{if(A?.workflow.status!=="cancelling"||X.signal.aborted)return;if(this.cancelled=!0,!this.suspension)this.suspension={status:"waiting",wakes:[]};U(new QZ(this.tick.workflowId))}).catch(()=>{})},this.tick.cancelCheckMs),H.unref?.()});try{return await Promise.race([G,Q])}finally{clearTimeout(B),clearInterval(H),G.catch(()=>{}),Q.catch(()=>{})}}async sleepStep(Z,$){let V=this.steps.get(Z);if(V?.status==="completed")return;if(this.current=Z,V?.status==="sleeping"&&V.wakeAt!==null&&V.wakeAt>Date.now())this.suspend("sleeping",V.wakeAt);let z=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+$;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(z!==null)this.suspend("sleeping",z)}async waitStep(Z,$){let V=this.steps.get(Z);if(V?.status==="completed")return n(V.output);if(V?.status==="timed_out")throw new GZ(Z);if(this.current=Z,V?.status==="waiting"&&(V.wakeAt===null||V.wakeAt>Date.now()))this.suspend("waiting",V.wakeAt);let z=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=$===void 0?null:Y+$;return{result:{kind:"wait",wakeAt:G},step:this.record(Z,null,{status:"waiting",wakeAt:G,startedAt:Y}),workflow:{currentStep:Z}}});if(z.kind==="value")return n(z.output);if(z.kind==="timeout")throw new GZ(Z);this.suspend("waiting",z.wakeAt)}async eachStep(Z,$,V){let z=$.source,X=z?z.count:$.count;if(!z&&typeof $.item!=="function")throw TypeError(`step.each "${Z}" needs either { count, item } or { source }.`);if(!Number.isSafeInteger(X)||X<0||X>cZ)throw TypeError(`step.each "${Z}" needs a count that is a whole number from 0 to ${cZ}; got ${String(X)}.`);let Y=Math.max(1,Math.floor($.concurrency??1)),G=Math.max(1,Math.floor($.attempts??3)),B=$.timeout===void 0?void 0:r($.timeout),H=$.tickBudget===void 0?S1:r($.tickBudget),Q=$.progress!==!1,J=$.chunk!==void 0,F=J?Math.max(1,Math.floor($.chunk)):1,U=[$.throttle??[]].flat().map((K)=>({name:`gemi:throttle:${K.key}`,limit:Math.max(0,Math.floor(K.limit)),windowMs:r(K.window)})),A=j1($.maxFailures),N=this.tick.store,P=$.transaction===!0&&N.transaction?(K)=>N.transaction(K):void 0;if($.transaction===!0&&!P)f1();let W=z?nZ(N,z,Math.max(M1,Y*F*4)):$.item;if(!N.listItems)throw Error("This queue's workflow store does not support step.each. The memory and database drivers do.");if(U.length>0&&!this.tick.throttle)throw Error(`step.each "${Z}" has a throttle, and this queue has no lock store.`);let D=this.steps.get(Z);if(D?.status==="completed")return PZ(D.output);if(D?.status==="failed")throw s(Z,D);if(D&&D.status!=="iterating")this.mismatch(Z,D.status,"step.each");if(this.current=Z,this.tick.durable===!1)y1();let T=await this.write(Z,({workflow:K,step:R,items:L,now:O})=>{if(R?.status==="completed")return{result:{kind:"done",output:R.output}};if(R?.status==="failed")return{result:{kind:"failed",step:R}};if(R&&R.status!=="iterating")this.mismatch(Z,R.status,"step.each");let x=R?c0(R.output):v1(X);return{result:{kind:"go",state:x,open:L},...R?{}:{step:this.record(Z,null,{status:"iterating",output:XZ(x),startedAt:O})},workflow:K.status==="cancelling"?{currentStep:Z}:{currentStep:Z,status:"running"}}},{items:!0,start:!0});if(T.kind==="done")return PZ(T.output);if(T.kind==="failed")throw s(Z,T.step);let _=T.state;if(_.count!==X)b1(this.workflowId,Z,_.count,X);let D0=_.count,d=new Map(T.open.map((K)=>[K.index,K])),k=[],_0=new Map,a0=new Map,_Z=Date.now()+H,H0=0,M0=!1,V0=null,p=new AbortController,LZ=setInterval(()=>{N.find(this.workflowId,{steps:!1}).then((K)=>{if(K?.workflow.status==="paused")M0=!0;if(K?.workflow.status!=="cancelling"||p.signal.aborted)return;if(this.cancelled=!0,!this.suspension)this.suspension={status:"waiting",wakes:[]};p.abort(new QZ(this.workflowId))}).catch(()=>{})},this.tick.cancelCheckMs);LZ.unref?.(),V0=A(_);let CZ=(K,R)=>{let L={...K};for(let O of R)if(O.counter)L[O.counter]++;return L},WZ=(K)=>{let R=K.succeeded+K.skipped+K.failed;return Q?{workflow:{progress:D0===0?1:i(R/D0)}}:{}},OZ=(K)=>{if(_={count:_.count,next:Math.max(_.next,K.next),succeeded:Math.max(_.succeeded,K.succeeded),skipped:Math.max(_.skipped,K.skipped),failed:Math.max(_.failed,K.failed)},!V0)V0=A(_);if(V0&&!p.signal.aborted)p.abort(new t)},X1=async(K)=>{let R=K.map(()=>null),L=new Map,O=new AbortController,x=()=>O.abort(p.signal.reason);p.signal.addEventListener("abort",x,{once:!0});let u,z0=K.length===1?`${Z}[${K[0].index}]`:`${Z}[${K[0].index}..${K.at(-1).index}]`,L0=new Promise((C,S)=>{if(O.signal.addEventListener("abort",()=>S(O.signal.reason),{once:!0}),B!==void 0)u=setTimeout(()=>O.abort(new BZ(z0,B)),B)}),y=(C)=>{throw new JZ(Math.max(0,Math.floor(Number(C)||0)))},X0=(C)=>K.map((S,q)=>{let l=L.get(q);if(!l)return{index:S.index,row:null,counter:"succeeded"};return{index:S.index,row:dZ(S,R[q],l.reason,l.data,C),counter:"skipped"}}),Y0=null,g=(async()=>{let C=await Promise.all(K.map((M)=>W(M.index)));K.forEach((M,v)=>{R[v]=g1($.key?$.key(C[v],M.index):M.index)});let S=(M)=>`${this.workflowId}:${Z}:${R[M]}`,q=Math.max(...K.map((M)=>M.attempt)),l=async()=>{if(J){let M={idempotencyKey:S(0),attempt:q,signal:O.signal,items:K.map((v,f)=>({index:v.index,key:R[f],idempotencyKey:S(f)})),skip:(v,f,I)=>{if(!Number.isInteger(v)||v<0||v>=K.length)throw RangeError(`ctx.skip: no item at position ${v} of this chunk.`);L.set(v,{reason:String(f),data:I})},release:y};await V(C,M)}else{let M={idempotencyKey:S(0),attempt:q,signal:O.signal,index:K[0].index,key:R[0],skip:(v,f)=>{throw new HZ(v,f)},release:y};await V(C[0],M)}};if(!P)return l();await P(async()=>{if(await l(),O.signal.aborted)throw O.signal.reason;let M=X0(Date.now()),v=await this.write(Z,({step:f})=>{let I={step:Z,insert:[],update:[],delete:[]};for(let J0 of M)if(J0.row===null)I.delete.push(J0.index);else I.update.push(J0.row);let a=CZ(f?c0(f.output):_,M);return{result:a,step:this.record(Z,f,{status:"iterating",output:XZ(a)}),items:I,...WZ(a)}},{joinTransaction:!0});Y0=M.map((f)=>({...f,recorded:!0})),OZ(v)})})(),j,E=!1;try{await Promise.race([g,L0])}catch(C){E=!0,j=C}finally{clearTimeout(u),p.signal.removeEventListener("abort",x),g.catch(()=>{}),L0.catch(()=>{})}if(Y0){k.push(...Y0);return}if(p.signal.aborted||this.cancelled||this.lost)return;let h=Date.now();if(!E){k.push(...X0(h));return}if(j instanceof HZ){k.push({index:K[0].index,row:dZ(K[0],R[0],j.reason,j.data,h),counter:"skipped"});return}if(j instanceof JZ){H0=Math.max(H0,h+j.delayMs),K.forEach((C,S)=>{k.push({index:C.index,row:{...C,key:R[S],status:"retrying",attempt:Math.max(0,C.attempt-1),wakeAt:h+j.delayMs},counter:null})});return}let c=T0(N0(j),2000);K.forEach((C,S)=>{if(C.attempt<G){let q=E0($.backoff??0,C.attempt);k.push({index:C.index,row:{...C,key:R[S],status:"retrying",error:c,wakeAt:h+q},counter:null});return}k.push({index:C.index,row:{...C,key:R[S],status:"failed",error:c,wakeAt:null,finishedAt:h},counter:"failed"})})},Y1=async(K)=>{if(U.length===0||K===0)return K;let R=this.tick.throttle;for(let L=0;L<K;L++){let O=[];for(let x of U){let u=await R.hit(x.name,x.limit,x.windowMs);if(!u.allowed)return await Promise.all(O.map((z0)=>R.refund(z0))),H0=Math.max(H0,Date.now()+Math.max(1,u.resetInMs)),L;O.push(x.name)}}return K},G1=async(K)=>{if(U.length===0)return;for(let R=0;R<K;R++)for(let L of U)await this.tick.throttle.refund(L.name)};try{for(;;){let K=Date.now(),R=K>=_Z||w0()||this.cancelled||M0||V0!==null,L=[],O=0;if(!R&&K>=H0){let y=(Y-_0.size)*F,X0=new Set(k.map((j)=>j.index));for(let j of[...d.values()].sort((E,h)=>E.index-h.index)){if(L.length>=y)break;if(a0.has(j.index)||X0.has(j.index))continue;if(j.status==="running"||(j.wakeAt??0)<=K)L.push(j)}let Y0=Y*F+wZ-d.size;O=Math.max(0,Math.min(y-L.length,D0-_.next,Y0));let g=await Y1(L.length+O);if(g<L.length)L=L.slice(0,g),O=0;else O=g-L.length}if(k.length>0||L.length>0||O>0){let y=k.splice(0,k.length),X0=y.filter((E)=>!E.recorded),Y0=L.length+O,g=await this.write(Z,({workflow:E,step:h,now:c})=>{let C=CZ(h?c0(h.output):_,X0),S={step:Z,insert:[],update:[],delete:[]},q=[],l=[];for(let I of X0)if(I.row===null)S.delete.push(I.index);else S.update.push(I.row);let M=E.status==="paused"&&!this.tick.cancelling;for(let I of M?[]:L){if(I.attempt+1>G){let J0={...I,status:"failed",error:T0(`Attempt ${I.attempt} of ${G} never finished, most likely because the process running it exited.`+(I.error?` The last error was: ${I.error}`:""),2000),wakeAt:null,finishedAt:c};C.failed++,S.update.push(J0),l.push(J0);continue}let a={...I,status:"running",attempt:I.attempt+1,wakeAt:null,startedAt:c};S.update.push(a),q.push(a)}let v=M?0:O,f=q.length;for(let I=0;I<v;I++){let a=x1(this.workflowId,Z,C.next+I,c);S.insert.push(a),q.push(a)}return C.next+=v,{result:{next:C,started:q,closed:l,reruns:f,paused:M},step:this.record(Z,h,{status:"iterating",output:XZ(C)}),items:S,...WZ(C)}});if(OZ(g.next),g.paused)M0=!0;await G1(Y0-g.started.length);for(let E of y)if(E.row?.status==="retrying")d.set(E.index,E.row);else d.delete(E.index);for(let E of g.closed)d.delete(E.index);for(let E of g.started)d.set(E.index,E);let j=[...lZ(g.started.slice(0,g.reruns),F),...lZ(g.started.slice(g.reruns),F)];for(let E of j){let h=E[0].index;for(let c of E)a0.set(c.index,h);_0.set(h,X1(E).finally(()=>{_0.delete(h);for(let c of E)a0.delete(c.index)}))}}if(_0.size>0){await Promise.race(_0.values());continue}if(k.length>0)continue;if(this.cancelled)throw new t;if(V0)break;if(_.next>=D0&&d.size===0)break;if(M0)this.suspend("paused");if(R)this.suspend("running",Date.now());let x=Date.now(),u=1/0;if(_.next<D0&&d.size<Y*F+wZ)u=x;for(let y of d.values())if(y.status==="running")u=x;else if(y.status==="retrying")u=Math.min(u,y.wakeAt??0);let z0=Math.max(u,H0);if(z0<=x)continue;let L0=z0-x;if(L0<=Math.min(I1,_Z-x)){await new Promise((y)=>setTimeout(y,Math.max(0,L0)));continue}this.suspend("sleeping",z0)}}finally{if(clearInterval(LZ),!p.signal.aborted)p.abort(new t)}let EZ=await N.listItems(this.workflowId,Z,{statuses:["failed","skipped"],limit:zZ+1}),i0={...UZ(_),problems:EZ.slice(0,zZ).map(NZ),moreProblems:EZ.length>zZ},B1=JSON.stringify({$each:_,problems:i0.problems,moreProblems:i0.moreProblems}),j0=V0,Q1=await this.write(Z,({step:K,now:R})=>{let L=this.record(Z,K,{status:j0?"failed":"completed",output:B1,error:j0,finishedAt:R});return{result:L,step:L,...Q&&!j0?{workflow:{progress:1}}:{}}});if(j0)throw s(Z,Q1);return i0}async batchStep(Z,$,V,z){let X=z.allowFailures===!0,Y=this.steps.get(Z);if(Y?.status==="completed")return n(Y.output);if(Y?.status==="failed")throw s(Z,Y);if(Y&&Y.status!=="batching")this.mismatch(Z,Y.status,"step.batch");if(this.current=Z,!Y){let F=this.tick.buildBatch($,V,{name:z.name??`workflow:${this.tick.workflowId}:${Z}`,allowFailures:X});if(Y=await this.write(Z,({step:U,now:A})=>{if(U)return{result:U};let N=this.record(Z,null,{status:"batching",batchId:F.id,startedAt:A});return{result:N,step:N,batch:F,workflow:{currentStep:Z}}},{start:!0}),this.tick.scheduled(),Y.status==="completed")return n(Y.output);if(Y.status==="failed")throw s(Z,Y)}let G=Y.batchId===null?null:await this.tick.findBatch(Y.batchId);if(G&&G.finishedAt===null)this.suspend("waiting");let B=G!==null&&G.cancelledAt===null&&(G.failed===0||X),H=G===null?null:JSON.stringify(G),Q=B?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}.`,J=await this.write(Z,({step:F,now:U})=>{let A=this.record(Z,F,{status:B?"completed":"failed",output:H,error:Q,finishedAt:U});return{result:A,step:A}});if(!B)throw s(Z,J);return G}}function s(Z,$){if($.output?.startsWith('{"$each"'))return new YZ(Z,`Step "${Z}" failed: ${$.error??"unknown error"}`,void 0,PZ($.output));let V=$.batchId!==null&&$.output!==null?JSON.parse($.output):void 0;return new YZ(Z,V?$.error??`Step "${Z}" failed.`:`Step "${Z}" failed: ${$.error??"unknown error"}`,V)}function S0(Z,$){if(Z===void 0)return null;let V=JSON.stringify(Z);if(V===void 0)throw TypeError(`${$} cannot be stored: JSON has no form for it.`);let z=Buffer.byteLength(V,"utf8");if(z>n0)throw RangeError(`${$} is ${z} bytes as JSON, over the ${n0}-byte limit. Store it elsewhere and return its id.`);return V}function n(Z){return Z===null?void 0:JSON.parse(Z)}function N0(Z){return Z instanceof Error?Z.message:String(Z)}var cZ=2147483647,S1=30000,wZ=100,I1=1000,M1=64,zZ=100;class HZ extends Error{reason;data;constructor(Z,$){super(`Skipped: ${Z}`);this.reason=Z;this.data=$;this.name="ItemSkipped"}}class JZ extends Error{delayMs;constructor(Z){super(`Released for ${Z}ms`);this.delayMs=Z;this.name="ItemReleased"}}function dZ(Z,$,V,z,X){let Y=null,G=T0(String(V));try{Y=h1(z)}catch(B){G=T0(`${G} (${N0(B)})`)}return{...Z,key:$,status:"skipped",error:G,output:Y,wakeAt:null,finishedAt:X}}function lZ(Z,$){let V=[];for(let z=0;z<Z.length;z+=$)V.push(Z.slice(z,z+$));return V}function j1(Z){if(Z===void 0)return()=>null;if(typeof Z==="number"){let z=Math.max(0,Math.floor(Z));return(X)=>X.failed>z?`${X.failed} items failed, more than maxFailures (${z}).`:null}let $=Math.min(1,Math.max(0,Z.ratio)),V=Math.max(1,Math.floor(Z.after??20));return(z)=>{let X=z.succeeded+z.skipped+z.failed;if(X<V||z.failed/X<=$)return null;return`${z.failed} of ${X} items failed, more than maxFailures allows (a ratio of ${$}).`}}function v1(Z){return{count:Z,next:0,succeeded:0,skipped:0,failed:0}}function XZ(Z){return JSON.stringify({$each:Z})}function c0(Z){let $=Z===null?null:JSON.parse(Z);if(!$?.$each)throw Error("A step.each step has no state.");return $.$each}function rZ(Z){if(Z===null||!Z.startsWith('{"$each"'))return null;try{return UZ(c0(Z))}catch{return null}}function UZ(Z){return{total:Z.count,done:Z.succeeded+Z.skipped+Z.failed,succeeded:Z.succeeded,skipped:Z.skipped,failed:Z.failed}}function PZ(Z){let $=JSON.parse(Z??"null");return{...UZ($.$each),problems:$.problems??[],moreProblems:$.moreProblems===!0}}function NZ(Z){let $={index:Z.index,key:Z.key,status:Z.status==="skipped"?"skipped":"failed",reason:T0(Z.error??""),attempt:Z.attempt};if(Z.output!==null)$.data=JSON.parse(Z.output);return $}function x1(Z,$,V,z){return{workflowId:Z,step:$,index:V,key:null,status:"running",attempt:1,error:null,output:null,wakeAt:null,startedAt:z,finishedAt:null,createdAt:z,updatedAt:z}}function g1(Z){let $=typeof Z==="number"&&Number.isFinite(Z)?String(Z):Z;if(typeof $!=="string"||$.length===0||$.length>191)throw TypeError(`An item key is a string of 1 to 191 characters, or a number; got ${JSON.stringify(Z)}.`);return $}function T0(Z,$=500){return Z.length<=$?Z:`${Z.slice(0,$-1)}\u2026`}function h1(Z){if(Z===void 0)return null;let $=JSON.stringify(Z);if($===void 0)throw TypeError("its data has no JSON form, so it was not kept");if(Buffer.byteLength($,"utf8")>1024)throw RangeError("its data is over 1 KB as JSON, so it was not kept");return $}var aZ=!1;function y1(){if(aZ||Bun.env.NODE_ENV!=="production")return;aZ=!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 iZ=!1;function f1(){if(iZ)return;iZ=!0,console.warn("[gemi] step.each with transaction: true runs its items without a transaction: this queue's workflow store cannot record an item in the app's transaction (only the database driver on Postgres or MySQL can). Items are at least once.")}var sZ=new Set;function b1(Z,$,V,z){let X=`${Z}:${$}`;if(sZ.has(X))return;sZ.add(X),console.warn(`[gemi] step.each "${$}" of workflow ${Z} was started with a count of ${V} and is now given ${z}. It goes on with ${V}: the count is fixed when the step first runs.`)}function d0(Z){return Z==="completed"||Z==="failed"||Z==="cancelled"}var R0=["completed","failed","cancelled"],q1=1000,m1=250,k1=30000;class RZ{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 $ of Z){if($.name==="unset"||!$.name){console.error("A workflow class has no `static name`, so it was not registered. Add one.");continue}if(this.registry[$.name]){console.error(`Two workflows are named "${$.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[$.name]=$}}get tickJob(){return this.tickClass??=u1(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(l0))return Z.make(l0);return this.ownFeed??=new l0,this.ownFeed}channel(Z){return`gemi:workflow:${Z}`}async update(Z){let $=await this.find(Z);if(!$)return null;let{args:V,result:z,...X}=$;return X}stream(Z,$,V={}){return this.feed.stream(Z,this.channel($),V)}cursor(Z){return this.feed.cursor(this.channel(Z))}async*subscribe(Z,$={}){let V=this.feed.subscribe(this.channel(Z),{signal:$.signal});try{await V.ready();let z=await this.update(Z);if(!z)return;if(yield z,d0(z.status))return;let X=V[Symbol.asyncIterator](),Y=X.next();for(;;){let G=await w1(Y,k1),B;if(G==="timeout")B=await this.update(Z);else{if(G.done)return;Y=X.next(),B=c1(G.value,Z)??await this.update(Z)}if(!B||B.updatedAt<z.updatedAt)continue;if(JSON.stringify(B)===JSON.stringify(z))continue;if(z=B,yield z,d0(z.status))return}}finally{V.close()}}publishingStore(Z){let $=(z)=>void tZ(()=>this.schedulePublish(z)),V={create:(z)=>Z.create(z).then((X)=>{return $(z.id),X}),find:(z,X)=>Z.find(z,X),acquire:(z,X,Y)=>Z.acquire(z,X,Y),renew:(z,X,Y)=>Z.renew(z,X,Y),update:(z,X,Y)=>Z.update(z,X,Y).then((G)=>{return $(z),G})};if(Z.joinsTransaction)V.joinsTransaction=()=>Z.joinsTransaction();if(Z.transaction)V.transaction=(z)=>Z.transaction(z);if(Z.listItems)V.listItems=(...z)=>Z.listItems(...z);if(Z.prune)V.prune=(z)=>Z.prune(z);if(Z.writeSource)V.writeSource=(...z)=>Z.writeSource(...z),V.readSource=(...z)=>Z.readSource(...z),V.deleteSource=(...z)=>Z.deleteSource(...z),V.pruneSources=(...z)=>Z.pruneSources(...z);return V}schedulePublish(Z){if(this.publishing.has(Z))return;let $=Math.max(0,(this.published.get(Z)??0)+m1-Date.now()),V=setTimeout(()=>{this.publishing.delete(Z),this.published.set(Z,Date.now()),this.publish(Z)},$);V.unref?.(),this.publishing.set(Z,V)}async publish(Z){try{let $=await this.update(Z);if(!$)return;if(d0($.status))this.published.delete(Z);await this.feed.publish(this.channel(Z),$)}catch($){console.error(`[gemi] Workflow ${Z}: could not publish its change.`,$)}}async close(){for(let Z of this.publishing.values())clearTimeout(Z);this.publishing.clear(),await this.ownFeed?.close(),this.ownFeed=void 0}start(Z,$){if(Z.name==="unset"||!Z.name)throw Error("Cannot start a workflow with no name");let V=this.store,z={id:Bun.randomUUIDv7(),name:Z.name,args:S0($,`The arguments of ${Z.name}`)??"[]"},X=()=>this.queue.claimSoon(),Y=V.joinsTransaction?.()===!0;if(!Y){if(o(()=>V.create(z).then(X,(Q)=>{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.`,Q)})))return Promise.resolve(z.id)}let G=V.create(z),B=Y&&o(X);return G.then(()=>{if(!B)X();return z.id})}async signal(Z,$,V){if(typeof $!=="string"||$.length===0||$.length>191)throw TypeError("A signal key is a string of 1 to 191 characters.");let z=S0(V,`The payload of signal "${$}"`),X=await this.store.update(Z,{key:$},({workflow:Y,step:G,now:B})=>{if(R0.includes(Y.status)||Y.status==="cancelling")return{result:!1};if(!G)return{result:!0,step:{workflowId:Z,key:$,status:"signalled",attempt:0,output:z,error:null,batchId:null,wakeAt:null,startedAt:null,finishedAt:B,createdAt:B,updatedAt:B}};if(G.status!=="waiting")return{result:!1};return{result:!0,step:{...G,status:"signalled",output:z,wakeAt:G.wakeAt,finishedAt:B},tick:{delayMs:0}}});if(X)this.queue.claimSoon();return X===!0}async cancel(Z){let $=await this.store.update(Z,{allSteps:!0},({workflow:V,steps:z})=>{if(R0.includes(V.status)||V.status==="cancelling")return{result:!1};return{result:!0,workflow:{status:"cancelling"},cancelBatches:z.filter((X)=>X.status==="batching"&&X.batchId!==null).map((X)=>X.batchId),tick:{delayMs:0}}});if($)this.queue.claimSoon();return $===!0}async pause(Z){let $=await this.store.update(Z,{},({workflow:V})=>{if(R0.includes(V.status)||V.status==="cancelling"||V.status==="paused")return{result:!1};return{result:!0,workflow:{status:"paused"}}});if($===!0)this.releaseSlotsOf(Z);return $===!0}async resume(Z){let $=await this.store.update(Z,{},({workflow:V})=>{if(V.status!=="paused")return{result:!1};return{result:!0,workflow:{status:"running",wakeAt:null},tick:{delayMs:0}}});if($)this.queue.claimSoon();return $===!0}async find(Z){let $=await this.store.find(Z);if(!$)return null;let{workflow:V,steps:z}=$,X=[];try{X=JSON.parse(V.args)}catch{}return{id:V.id,name:V.name,status:V.status,args:X,currentStep:V.currentStep,progress:V.progress,result:p1(V.result),error:V.error,steps:await Promise.all(z.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},B=rZ(Y.output);if(B)return{...G,items:B,progress:B.total===0?1:B.done/B.total};if(Y.batchId===null)return G;let H=await this.queue.driver.findBatch?.(Y.batchId);return H?{...G,progress:H.progress}:G})),createdAt:V.createdAt,updatedAt:V.updatedAt}}async items(Z,$,V={}){let z=this.store;if(!z.listItems)return[];let X=Math.max(1,Math.min(1000,Math.floor(V.limit??100)));return(await z.listItems(Z,$,{statuses:V.status?[V.status]:["failed","skipped"],...V.after===void 0?{}:{after:V.after},limit:X})).map(NZ)}async tick(Z,$){let V=this.store,z=$.$claimed,X=z?`${z.id}:${z.attempt}`:`${crypto.randomUUID()}:1`,Y=Math.max(1,this.queue.config.visibilityTimeout),G=await V.acquire(Z,X,Y);if(G.kind!=="acquired")return;let{workflow:B}=G,H=(P={})=>V.update(Z,{owner:X},()=>({...P,result:void 0,unlock:!0})).then(()=>this.queue.claimSoon()).catch((W)=>{if(!(W instanceof b))throw W});if(R0.includes(B.status)||B.status==="paused"){await H(),await this.releaseSlotsOf(Z,B);return}let Q=this.registry[B.name];if(!Q)return this.unknown(B,$,H);let J;try{J=JSON.parse(B.args)}catch(P){return H({workflow:{status:"failed",error:`The arguments are not JSON: ${N0(P)}`}})}let F=B.status==="cancelling",U;try{U=await this.limitsOf(Q,J)}catch(P){throw await H(),P}if(U.length>0&&!F&&z){let P=this.queue.driver;if(!P.acquireSlots||!P.releaseSlots)return H({workflow:{status:"failed",error:`${B.name} declares concurrency, and this queue's driver has no concurrency slots. The memory and database drivers do.`}});if(!await P.acquireSlots({holder:$Z(Z),workflowId:Z,job:z,slots:U,recheckMs:this.queue.slotRecheck()}))return $.$outcome={kind:"parked"},H()}let A=setInterval(()=>{V.renew(Z,X,Y).catch((P)=>{console.error(`[gemi] Could not extend the hold on workflow ${Z}.`,P)})},Math.max(1,Math.floor(Y/3)));A.unref?.();let N=new FZ({workflowId:Z,owner:X,store:V,steps:G.steps,cancelling:F,findBatch:(P)=>this.queue.driver.findBatch?.(P,{progress:!1})??Promise.resolve(null),buildBatch:(P,W,D)=>this.queue.buildBatch(P,W.map((T)=>JSON.stringify(T)),{name:D.name,allowFailures:D.allowFailures,finally:{name:m,args:[Z]}}),scheduled:()=>this.queue.claimSoon(),cancelCheckMs:q1,durable:this.queue.durable,throttle:{hit:(P,W,D)=>this.queue.locks.store.hit(P,W,D),refund:(P)=>this.queue.locks.store.refund(P)}});try{let P;try{let D=new Q,T=await(F?D.onCancel(N,...J):D.run(N,...J));P=N.suspension?{kind:"suspended"}:{kind:"completed",result:F?null:S0(T,`The result of ${B.name}`)}}catch(D){if(P=N.suspension||D instanceof t?{kind:"suspended"}:{kind:"failed",error:N0(D)},D instanceof b)N.lost=!0}if(await N.settled(),N.lost)return;if(P.kind==="completed"&&N.suspension)P={kind:"suspended"};let W;if(await V.update(Z,{owner:X},({workflow:D,now:T})=>{let _=this.finish(D,P,N,F,T);return W=_.workflow?.status??D.status,_}),this.queue.claimSoon(),U.length>0&&W!==void 0&&(R0.includes(W)||W==="paused"))await this.releaseSlots(Z)}catch(P){if(P instanceof b)return;throw P}finally{clearInterval(A)}}finish(Z,$,V,z,X){let Y={result:void 0,unlock:!0};if(Z.status==="cancelling"&&!z)return{...Y,tick:{delayMs:0}};if($.kind==="completed")return{...Y,workflow:z?{status:"cancelled",currentStep:null,wakeAt:null}:{status:"completed",result:$.result,progress:1,currentStep:null,wakeAt:null,error:null}};if($.kind==="failed")return{...Y,workflow:{status:z?"cancelled":"failed",error:$.error,wakeAt:null}};let G=V.suspension??{status:"waiting",wakes:[]};if(!z&&(Z.status==="paused"||G.status==="paused"))return Z.status==="paused"?{...Y,workflow:{currentStep:V.current??Z.currentStep}}:{...Y,workflow:{status:"running"},tick:{delayMs:0}};let B={...Y,workflow:{status:z?"cancelling":G.status,currentStep:V.current??Z.currentStep}};if(G.wakes.length>0){let H=Math.min(...G.wakes);if(!(Z.wakeAt!==null&&Z.wakeAt>X&&Z.wakeAt<=H))B.tick={delayMs:Math.max(0,H-X)},B.workflow.wakeAt=H}return B}async limitsOf(Z,$){let V=new Z;if(typeof V.concurrency!=="function")return[];return u0(await V.concurrency(...$),Z.name)}async releaseSlots(Z){try{await this.queue.driver.releaseSlots?.($Z(Z))}catch($){console.error(`[gemi] Could not free the concurrency slots of workflow ${Z}.`,$)}}async releaseSlotsOf(Z,$){try{let V=$??(await this.store.find(Z,{steps:!1}))?.workflow,z=V&&this.registry[V.name];if(!V||!z)return;if((await this.limitsOf(z,JSON.parse(V.args))).length>0)await this.releaseSlots(Z)}catch(V){console.error(`[gemi] Could not free the concurrency slots of workflow ${Z}.`,V)}}async unknown(Z,$,V){let z=Date.now()-Z.createdAt;if(this.queue.durable&&z<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 V(),$.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 V({workflow:{status:"failed",error:`No workflow is registered under the name "${Z.name}".`}})}tickDeadLettered(Z,$){console.error(`[gemi] The tick of workflow ${Z} was dead-lettered.`,$),this.store.update(Z,{},({workflow:V})=>R0.includes(V.status)?{result:void 0}:{result:void 0,workflow:{status:"failed",error:`Its tick job was dead-lettered: ${$.message}`},unlock:!0}).then(()=>this.releaseSlotsOf(Z)).catch(()=>{})}}function u1(Z){return class extends Q0{static name=m;maxAttempts=20;backoff=[1000,5000,15000,30000,60000];async run(V){await Z.tick(V,this)}onDeadletter(V,z){Z.tickDeadLettered(z,V)}}}function p1(Z){try{return n(Z)}catch{return Z}}function c1(Z,$){if(Z.type!=="change")return null;let V=Z.data;if(!V||typeof V!=="object"||V.id!==$||typeof V.updatedAt!=="number")return null;return V}async function w1(Z,$){let V,z=new Promise((X)=>{V=setTimeout(()=>X("timeout"),$)});try{return await Promise.race([Z,z])}finally{clearTimeout(V)}}var __dirname="/home/runner/work/gemi/gemi/packages/gemi/services/queue";function i1(Z=process.env){let $=Z.ROOT_DIR??process.cwd(),V=Z.APP_DIR??`${$}/app`,z=Z.NODE_ENV==="production"?`${$}/dist/server/bootstrap.mjs`:`${V}/bootstrap.ts`,X;try{X=Bun.resolveSync("gemi/app",$)}catch{X=Bun.resolveSync("gemi/app",__dirname)}return{bootstrap:l1(z)?z:void 0,kernel:`${V}/kernel/Kernel.ts`,app:X}}function s1(){let Z=i1(),$=Z.bootstrap?`const { app } = await import(${JSON.stringify(Z.bootstrap)});`:`const { App } = await import(${JSON.stringify(Z.app)});
|
|
567
567
|
const { default: Kernel } = await import(${JSON.stringify(Z.kernel)});
|
|
568
568
|
const app = new App({ kernel: Kernel });
|
|
569
569
|
await app.waitForBoot();`,V=new File([`
|
|
@@ -585,7 +585,7 @@ ADD COLUMN IF NOT EXISTS "progress" ${V}`,`CREATE INDEX IF NOT EXISTS "${$}_batc
|
|
|
585
585
|
}
|
|
586
586
|
};
|
|
587
587
|
self.postMessage({ ready: true });
|
|
588
|
-
`],"worker.ts"),z=URL.createObjectURL(V);return new Worker(z)}async function s1(Z,$){let V=i1();try{return await new Promise((z,X)=>{V.onmessage=(Y)=>{let G=Y.data;if(G&&"ready"in G)V.postMessage({jobName:Z,args:$});else if("error"in G)X(G.error);else z(G.result)},V.onerror=(Y)=>{let G=Y.error??Y.message??Y;X(G instanceof Error?G:Error(`The worker thread for ${Z} failed: ${String(G)}`))},V.addEventListener("close",()=>{X(Error(`The worker thread for ${Z} exited before the job finished.`))})})}finally{V.terminate()}}var n1=new w1("gemi.queue"),r1=60000;class $0{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={},$={}){if(this.config=eZ(qZ(),Z),this.application=$.application,this.driver=$3(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 $ of Z)this.claim($);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 RZ(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,$){let V=this.jobs[Z];if(!V)throw Error(`No job is registered under the name "${Z}" in this thread, so it did not run. The thread boots the application from app/kernel/Kernel.ts (or app/bootstrap.ts); check that the job is discovered there.`);return new V().run(...JSON.parse($))}push(Z,$,V={}){let z=this.uniqueKey(Z,$);if(z)return this.pushUnique(Z,$,z,V);let X=this.driver.joinsTransaction?.()===!0;if(!X){let Y=Bun.randomUUIDv7();if(o(()=>this.record(Z,$,{id:Y,reportFailure:!0,committed:!0}).then(()=>{},()=>{})))return Promise.resolve(Y)}return this.record(Z,$,{reportFailure:V.reportFailure,joins:X})}pushBatch(Z,$,V={}){let z=this.buildBatch(Z,$,V),X={id:z.id,total:$.length},Y=this.driver.joinsTransaction?.()===!0;if(!Y){if(o(()=>this.recordBatch(z,{committed:!0}).then(()=>{},()=>{})))return Promise.resolve(X)}return this.recordBatch(z,{joins:Y}).then(()=>X)}buildBatch(Z,$,V={}){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!==Q0.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=V[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:V.name??null,job:Z.name,args:$,allowFailures:V.allowFailures===!0,callbacks:X}}recordBatch(Z,$){let V=this.driver.enqueueBatch(Z);this.startIfIdle();let z=()=>!this.driver.subscribe&&this.state==="running"&&this.wake(),X=$.joins===!0&&o(z);return V.then(()=>X||z(),(Y)=>{if(!$.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)}),V}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 $=await this.driver.cancelBatch(Z);if($)this.claimSoon();return $}get locks(){return this.lockManager??=new Z1(this.resolveLockStore()),this.lockManager}resolveLockStore(){let Z=this.config.locks;if(Z==="auto"){let $=this.driver.lockStore?.();if($)return $;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 g0}if(Z==="memory")return new g0;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 C0(this.application.make(DZ));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,$){if(Z.prototype.uniqueId===Q0.prototype.uniqueId)return;let V=new Z,z=V.uniqueId(...JSON.parse($));if(z===void 0||z===null||z==="")return;return{key:tZ(Z.name,z),ttl:Math.max(1,V.uniqueFor)}}pushUnique(Z,$,V,z){let X=Bun.randomUUIDv7();if(o(()=>this.recordUnique(Z,$,V,X,{report:!0,committed:!0}).then(()=>{},()=>{})))return Promise.resolve(X);return this.recordUnique(Z,$,V,X,{report:z.reportFailure!==!1,committed:!1})}recordUnique(Z,$,V,z,X){let Y=this.locks.store,G=(async()=>{for(let B=0;B<5;B++){if(await Y.acquire(V.key,z,V.ttl)!==null)try{return await this.record(Z,$,{id:z,reportFailure:!1})}catch(Q){throw await Y.release(V.key,z).catch(()=>{}),Q}let H=await Y.holder(V.key);if(H)return H.owner}throw Error(`The unique key "${V.key}" kept changing hands, so ${Z.name} was not queued.`)})();return G.catch((B)=>{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."),B)}),G}async releaseUnique(Z,$,V){if(Z.uniqueId===Q0.prototype.uniqueId)return;try{let z=Z.uniqueId(...$);if(z===void 0||z===null||z==="")return;await this.locks.store.release(tZ(V.name,z),V.id)}catch(z){console.error(`[gemi] Could not free the unique key of ${V.name} (${V.id}); it frees itself after uniqueFor.`,z)}}record(Z,$,V){let z=this.driver.enqueue({name:Z.name,args:$,...V.id===void 0?{}:{id:V.id}});this.startIfIdle();let X=()=>!this.driver.subscribe&&this.state==="running"&&this.wake(),Y=V.joins===!0&&o(X);return z.then(()=>Y||X(),(G)=>{if(V.reportFailure===!1)return;console.error(`[gemi] The queue driver could not record ${Z.name}`+(V.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)}),z}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 $=await this.driver.retryDead(Z);if($)this.claimSoon();return $}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()&&!t1())globalThis.__gemiDevQueue=this;if(this.unsubscribe=this.driver.subscribe?.(()=>this.wake()),this.looping)return this.wake();n1.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 $,V=new Promise((X)=>{if(Z!==1/0)$=setTimeout(X,Z)}),z=(async()=>{await this.claiming?.catch(()=>{}),await Promise.allSettled([...this.inFlight.values()].map((X)=>X.done))})();return await Promise.race([z,V]),clearTimeout($),{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&&w0()?0:this.config.concurrency-this.inFlight.size;if(Z>0){this.woken=!1;let $=this.driver.claim(Z,{...this.lease(),registered:{names:Object.keys(this.jobs),graceMs:this.config.unknownJobGrace}});this.claiming=$;let V=[];try{V=await $,this.claimFailures=0}catch(z){this.claimFailures++,console.error(`The queue could not claim jobs from its driver; it will try again in ${this.retryDelay()}ms.`,z)}finally{this.claiming=void 0}for(let z of V)this.execute(z);if(V.length===Z)continue;if(this.woken&&this.inFlight.size<this.config.concurrency)continue}await this.sleep()}}sleep(){return new Promise((Z)=>{let $,V=this.claimFailures>0?this.retryDelay():this.driver.subscribe?void 0:this.config.pollInterval;if(V!==void 0)$=setTimeout(()=>this.wake(),V),$.unref?.();this.resume=()=>{clearTimeout($),Z()}})}retryDelay(){let Z=Math.min(Math.max(0,this.claimFailures-1),30);return Math.min(this.config.pollInterval*2**Z,r1)}wake(){this.woken=!0;let Z=this.resume;this.resume=void 0,Z?.()}get durable(){return!(this.driver instanceof p0)}mayClaimHere(){return!this.application||o1()}lease(){return{visibilityTimeoutMs:this.config.visibilityTimeout}}execute(Z){let $=`${Z.id}:${Z.attempt}`,V=()=>this.run(Z),z=(this.application?oZ.run(this.application,V):V()).catch((X)=>{console.error(`The queue could not record the outcome of ${Z.name}.`,X)}).finally(()=>{this.inFlight.delete($),this.wake()});this.inFlight.set($,{job:Z,done:z}),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 $=[...this.inFlight.values()].map((V)=>V.job);Z.heartbeat($,this.lease()).catch((V)=>{console.error("The queue could not extend its job leases.",V)})},Math.max(1,Math.floor(this.config.visibilityTimeout/3))),this.heartbeatTimer.unref?.()}async run(Z){let $=this.jobs[Z.name];if(!$){let Q=Date.now()-Z.createdAt;if(this.durable&&Q<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 V;try{V=new $}catch(Q){console.error(`Dropped a queued ${Z.name}: it could not be constructed.`,Q),await this.driver.fail(Z,{error:`The job could not be constructed: ${String(Q)}`,retryInMs:null});return}let z;try{z=JSON.parse(Z.args)}catch(Q){console.error(`Dropped a queued ${Z.name}: its arguments are not JSON.`,Q),await this.driver.fail(Z,{error:`The arguments are not JSON: ${String(Q)}`,retryInMs:null});return}if(Z.attempt>Math.max(1,V.maxAttempts)){let Q=Error(`${Z.name} was claimed for attempt ${Z.attempt} of ${V.maxAttempts}: an earlier attempt never finished, most likely because the process running it exited. Dead-lettered without running it again.`);AZ(`${Z.name}.onDeadletter`,()=>V.onDeadletter(Q,...z)),await this.driver.fail(Z,{error:Q.message,retryInMs:null}),await this.releaseUnique(V,z,Z);return}if(V.$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 J=this.batchHandle(Z);V.batch=J.batch,V.$progress=J.progress}let X,Y;try{Y=await this.admit(V,z,Z)}catch(Q){X=Q}if(!Y&&X===void 0)return;let G;if(Y)try{G=await(V.worker?s1(Z.name,Z.args):V.run(...z))}catch(Q){X=Q}finally{await Y.done()}let B=V.$outcome;if(X===void 0&&B?.kind==="parked")return;if(X===void 0&&B?.kind==="release"){await this.driver.release(Z,{retryInMs:Math.max(0,B.delayMs)});return}if(X===void 0&&B?.kind==="fail")X=B.error;let H=B?.kind==="fail"?B.retry:!0;if(X===void 0)try{V.onSuccess(G,...z)}catch(Q){X=Q}if(X!==void 0){let Q=String(X?.stack??X);if(AZ(`${Z.name}.onFail`,()=>V.onFail(X,...z)),!H||Z.attempt>=V.maxAttempts)AZ(`${Z.name}.onDeadletter`,()=>V.onDeadletter(X,...z)),await this.driver.fail(Z,{error:Q,retryInMs:null}),await this.releaseUnique(V,z,Z);else await this.driver.fail(Z,{error:Q,retryInMs:E0(V.backoff,Z.attempt)});return}await this.driver.complete(Z),await this.releaseUnique(V,z,Z)}batchHandle(Z){let $=Z.batchId,V=this.driver;return{batch:{id:$,cancelled:async()=>(await V.findBatch?.($,{progress:!1}))?.cancelledAt!=null},progress:(z)=>V.reportProgress?.(Z,z)??Promise.resolve()}}async admit(Z,$,V){let z=u0(await Z.concurrency(...$),V.name),X=[Z.throttle(...$)??[]].flat();if(z.length===0&&X.length===0)return{done:async()=>{}};let Y=this.driver,G=async()=>{};if(z.length>0&&Y.acquireSlots&&Y.releaseSlots){if(!await Y.acquireSlots({holder:V.id,job:V,slots:z,recheckMs:this.slotRecheck()}))return;G=()=>Y.releaseSlots(V.id)}else if(z.length>0){let Q=await this.lockSlots(z);if(!Q){await Y.release(V,{retryInMs:Math.round(this.config.pollInterval*(1+Math.random()))});return}G=async()=>{await Promise.all(Q.map((J)=>J.release()))}}let B=this.locks,H=[];try{for(let Q of X){let J=`gemi:throttle:${Q.key}`,F=await B.store.hit(J,Q.limit,Q.window);if(!F.allowed){await Promise.all(H.map((U)=>B.store.refund(U))),await G(),await Y.release(V,{retryInMs:Math.max(1,F.resetInMs)});return}H.push(J)}}catch(Q){throw await G().catch(()=>{}),Q}return{done:async()=>{await G().catch((Q)=>{console.error(`[gemi] Could not free a concurrency slot of ${V.name}.`,Q)})}}}slotRecheck(){return{near:Math.max(1000,this.config.visibilityTimeout),far:3600000}}async lockSlots(Z){let $=this.config.visibilityTimeout,V=[];for(let{key:z,limit:X}of Z){let Y;for(let G=0;G<X&&!Y;G++)Y=await this.locks.acquire(`gemi:concurrency:${z}:${G}`,{ttl:$,renew:!0})??void 0;if(!Y){await Promise.all(V.map((G)=>G.release()));return}V.push(Y)}return V}}function tZ(Z,$){return`gemi:job:${Z}:${String($)}`}function AZ(Z,$){try{$()}catch(V){console.error(`${Z} threw; the job's claim was ended anyway.`,V)}}function t1(){return Bun.env.NODE_ENV==="production"}function o1(){if(!l1)return!1;if(Z3())return!0;return process.env.ROOT_DIR!==void 0&&!e1()}function e1(Z=process.env){return(Z.GEMI_QUEUE_CLAIM??"").trim().toLowerCase()==="off"}var $1=Symbol.for("gemi.queue.worker");function D6(Z=!0){globalThis[$1]=Z}function Z3(){return globalThis[$1]===!0}function $3(Z,$){if(Z==="memory")return new p0;if(Z==="database"||typeof Z==="function"){if(!$&&(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 e0($.make(DZ));return 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}var V1=65536,V3=500;class z3{static write(Z,$){return KZ(I0(),Z,$,null)}static async read(Z,$){let[V]=await A0(I0()).readSource(Z,$,$+1);return V?JSON.parse(V.payload):void 0}static async readRange(Z,$,V){return(await A0(I0()).readSource(Z,$,V)).map((X)=>JSON.parse(X.payload))}static delete(Z){return A0(I0()).deleteSource(Z)}static prune(Z){return A0(I0()).pruneSources(r(Z))}}function I0(){return B0($0).workflows.store}function A0(Z){if(!Z.writeSource||!Z.readSource||!Z.deleteSource||!Z.pruneSources)throw Error("This queue's workflow store does not keep item sources. The memory and database drivers do.");return Z}async function KZ(Z,$,V,z){if(typeof $!=="string"||$.length===0||$.length>191)throw TypeError(`An item source id is a string of 1 to 191 characters; got ${JSON.stringify($)}.`);A0(Z),await Z.deleteSource($);let X=0,Y=[];for await(let G of V){let B=JSON.stringify(G===void 0?null:G);if(B===void 0)throw TypeError(`Item ${X} of source "${$}" has no JSON form.`);let H=Buffer.byteLength(B,"utf8");if(H>V1)throw RangeError(`Item ${X} of source "${$}" is ${H} bytes as JSON, over the ${V1}-byte limit. Store it elsewhere and keep its id.`);if(Y.push({index:X++,payload:B}),Y.length>=V3)await Z.writeSource($,z,Y),Y=[]}return await Z.writeSource($,z,Y),{id:$,count:X}}function sZ(Z,$,V){A0(Z);let z=new Map,X=new Map,Y=0,G=(B,H)=>{let Q=`${B}:${H}`,J=X.get(Q);if(!J)J=Z.readSource($.id,B,H).then((F)=>{for(let U of F)z.set(U.index,U.payload);X.delete(Q)},(F)=>{throw X.delete(Q),F}),X.set(Q,J);return J};return async(B)=>{if(!z.has(B)){let Q=B-B%V,J=Math.min(Q+V,$.count);if(X.has(`${Q}:${J}`))await X.get(`${Q}:${J}`);else if(B>=Y)Y=Math.max(Y,J),await G(Q,J);if(!z.has(B))await G(B,B+1)}let H=z.get(B);if(z.delete(B),H===void 0)throw Error(`Item source "${$.id}" has no item at index ${B}.`);return JSON.parse(H)}}
|
|
589
|
-
export{C0 as
|
|
588
|
+
`],"worker.ts"),z=URL.createObjectURL(V);return new Worker(z)}async function n1(Z,$){let V=s1();try{return await new Promise((z,X)=>{V.onmessage=(Y)=>{let G=Y.data;if(G&&"ready"in G)V.postMessage({jobName:Z,args:$});else if("error"in G)X(G.error);else z(G.result)},V.onerror=(Y)=>{let G=Y.error??Y.message??Y;X(G instanceof Error?G:Error(`The worker thread for ${Z} failed: ${String(G)}`))},V.addEventListener("close",()=>{X(Error(`The worker thread for ${Z} exited before the job finished.`))})})}finally{V.terminate()}}var r1=new d1("gemi.queue"),t1=60000;class $0{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={},$={}){if(this.config=Z1(mZ(),Z),this.application=$.application,this.driver=V3(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 $ of Z)this.claim($);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 RZ(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,$){let V=this.jobs[Z];if(!V)throw Error(`No job is registered under the name "${Z}" in this thread, so it did not run. The thread boots the application from app/kernel/Kernel.ts (or app/bootstrap.ts); check that the job is discovered there.`);return new V().run(...JSON.parse($))}push(Z,$,V={}){let z=this.uniqueKey(Z,$);if(z)return this.pushUnique(Z,$,z,V);let X=this.driver.joinsTransaction?.()===!0;if(!X){let Y=Bun.randomUUIDv7();if(o(()=>this.record(Z,$,{id:Y,reportFailure:!0,committed:!0}).then(()=>{},()=>{})))return Promise.resolve(Y)}return this.record(Z,$,{reportFailure:V.reportFailure,joins:X})}pushBatch(Z,$,V={}){let z=this.buildBatch(Z,$,V),X={id:z.id,total:$.length},Y=this.driver.joinsTransaction?.()===!0;if(!Y){if(o(()=>this.recordBatch(z,{committed:!0}).then(()=>{},()=>{})))return Promise.resolve(X)}return this.recordBatch(z,{joins:Y}).then(()=>X)}buildBatch(Z,$,V={}){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!==Q0.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=V[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:V.name??null,job:Z.name,args:$,allowFailures:V.allowFailures===!0,callbacks:X}}recordBatch(Z,$){let V=this.driver.enqueueBatch(Z);this.startIfIdle();let z=()=>!this.driver.subscribe&&this.state==="running"&&this.wake(),X=$.joins===!0&&o(z);return V.then(()=>X||z(),(Y)=>{if(!$.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)}),V}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 $=await this.driver.cancelBatch(Z);if($)this.claimSoon();return $}get locks(){return this.lockManager??=new $1(this.resolveLockStore()),this.lockManager}resolveLockStore(){let Z=this.config.locks;if(Z==="auto"){let $=this.driver.lockStore?.();if($)return $;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 g0}if(Z==="memory")return new g0;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 C0(this.application.make(DZ));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,$){if(Z.prototype.uniqueId===Q0.prototype.uniqueId)return;let V=new Z,z=V.uniqueId(...JSON.parse($));if(z===void 0||z===null||z==="")return;return{key:oZ(Z.name,z),ttl:Math.max(1,V.uniqueFor)}}pushUnique(Z,$,V,z){let X=Bun.randomUUIDv7();if(o(()=>this.recordUnique(Z,$,V,X,{report:!0,committed:!0}).then(()=>{},()=>{})))return Promise.resolve(X);return this.recordUnique(Z,$,V,X,{report:z.reportFailure!==!1,committed:!1})}recordUnique(Z,$,V,z,X){let Y=this.locks.store,G=(async()=>{for(let B=0;B<5;B++){if(await Y.acquire(V.key,z,V.ttl)!==null)try{return await this.record(Z,$,{id:z,reportFailure:!1})}catch(Q){throw await Y.release(V.key,z).catch(()=>{}),Q}let H=await Y.holder(V.key);if(H)return H.owner}throw Error(`The unique key "${V.key}" kept changing hands, so ${Z.name} was not queued.`)})();return G.catch((B)=>{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."),B)}),G}async releaseUnique(Z,$,V){if(Z.uniqueId===Q0.prototype.uniqueId)return;try{let z=Z.uniqueId(...$);if(z===void 0||z===null||z==="")return;await this.locks.store.release(oZ(V.name,z),V.id)}catch(z){console.error(`[gemi] Could not free the unique key of ${V.name} (${V.id}); it frees itself after uniqueFor.`,z)}}record(Z,$,V){let z=this.driver.enqueue({name:Z.name,args:$,...V.id===void 0?{}:{id:V.id}});this.startIfIdle();let X=()=>!this.driver.subscribe&&this.state==="running"&&this.wake(),Y=V.joins===!0&&o(X);return z.then(()=>Y||X(),(G)=>{if(V.reportFailure===!1)return;console.error(`[gemi] The queue driver could not record ${Z.name}`+(V.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)}),z}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 $=await this.driver.retryDead(Z);if($)this.claimSoon();return $}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()&&!o1())globalThis.__gemiDevQueue=this;if(this.unsubscribe=this.driver.subscribe?.(()=>this.wake()),this.looping)return this.wake();r1.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 $,V=new Promise((X)=>{if(Z!==1/0)$=setTimeout(X,Z)}),z=(async()=>{await this.claiming?.catch(()=>{}),await Promise.allSettled([...this.inFlight.values()].map((X)=>X.done))})();return await Promise.race([z,V]),clearTimeout($),{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&&w0()?0:this.config.concurrency-this.inFlight.size;if(Z>0){this.woken=!1;let $=this.driver.claim(Z,{...this.lease(),registered:{names:Object.keys(this.jobs),graceMs:this.config.unknownJobGrace}});this.claiming=$;let V=[];try{V=await $,this.claimFailures=0}catch(z){this.claimFailures++,console.error(`The queue could not claim jobs from its driver; it will try again in ${this.retryDelay()}ms.`,z)}finally{this.claiming=void 0}for(let z of V)this.execute(z);if(V.length===Z)continue;if(this.woken&&this.inFlight.size<this.config.concurrency)continue}await this.sleep()}}sleep(){return new Promise((Z)=>{let $,V=this.claimFailures>0?this.retryDelay():this.driver.subscribe?void 0:this.config.pollInterval;if(V!==void 0)$=setTimeout(()=>this.wake(),V),$.unref?.();this.resume=()=>{clearTimeout($),Z()}})}retryDelay(){let Z=Math.min(Math.max(0,this.claimFailures-1),30);return Math.min(this.config.pollInterval*2**Z,t1)}wake(){this.woken=!0;let Z=this.resume;this.resume=void 0,Z?.()}get durable(){return!(this.driver instanceof p0)}mayClaimHere(){return!this.application||e1()}lease(){return{visibilityTimeoutMs:this.config.visibilityTimeout}}execute(Z){let $=`${Z.id}:${Z.attempt}`,V=()=>this.run(Z),z=(this.application?eZ.run(this.application,V):V()).catch((X)=>{console.error(`The queue could not record the outcome of ${Z.name}.`,X)}).finally(()=>{this.inFlight.delete($),this.wake()});this.inFlight.set($,{job:Z,done:z}),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 $=[...this.inFlight.values()].map((V)=>V.job);Z.heartbeat($,this.lease()).catch((V)=>{console.error("The queue could not extend its job leases.",V)})},Math.max(1,Math.floor(this.config.visibilityTimeout/3))),this.heartbeatTimer.unref?.()}async run(Z){let $=this.jobs[Z.name];if(!$){let Q=Date.now()-Z.createdAt;if(this.durable&&Q<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 V;try{V=new $}catch(Q){console.error(`Dropped a queued ${Z.name}: it could not be constructed.`,Q),await this.driver.fail(Z,{error:`The job could not be constructed: ${String(Q)}`,retryInMs:null});return}let z;try{z=JSON.parse(Z.args)}catch(Q){console.error(`Dropped a queued ${Z.name}: its arguments are not JSON.`,Q),await this.driver.fail(Z,{error:`The arguments are not JSON: ${String(Q)}`,retryInMs:null});return}if(Z.attempt>Math.max(1,V.maxAttempts)){let Q=Error(`${Z.name} was claimed for attempt ${Z.attempt} of ${V.maxAttempts}: an earlier attempt never finished, most likely because the process running it exited. Dead-lettered without running it again.`);AZ(`${Z.name}.onDeadletter`,()=>V.onDeadletter(Q,...z)),await this.driver.fail(Z,{error:Q.message,retryInMs:null}),await this.releaseUnique(V,z,Z);return}if(V.$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 J=this.batchHandle(Z);V.batch=J.batch,V.$progress=J.progress}let X,Y;try{Y=await this.admit(V,z,Z)}catch(Q){X=Q}if(!Y&&X===void 0)return;let G;if(Y)try{G=await(V.worker?n1(Z.name,Z.args):V.run(...z))}catch(Q){X=Q}finally{await Y.done()}let B=V.$outcome;if(X===void 0&&B?.kind==="parked")return;if(X===void 0&&B?.kind==="release"){await this.driver.release(Z,{retryInMs:Math.max(0,B.delayMs)});return}if(X===void 0&&B?.kind==="fail")X=B.error;let H=B?.kind==="fail"?B.retry:!0;if(X===void 0)try{V.onSuccess(G,...z)}catch(Q){X=Q}if(X!==void 0){let Q=String(X?.stack??X);if(AZ(`${Z.name}.onFail`,()=>V.onFail(X,...z)),!H||Z.attempt>=V.maxAttempts)AZ(`${Z.name}.onDeadletter`,()=>V.onDeadletter(X,...z)),await this.driver.fail(Z,{error:Q,retryInMs:null}),await this.releaseUnique(V,z,Z);else await this.driver.fail(Z,{error:Q,retryInMs:E0(V.backoff,Z.attempt)});return}await this.driver.complete(Z),await this.releaseUnique(V,z,Z)}batchHandle(Z){let $=Z.batchId,V=this.driver;return{batch:{id:$,cancelled:async()=>(await V.findBatch?.($,{progress:!1}))?.cancelledAt!=null},progress:(z)=>V.reportProgress?.(Z,z)??Promise.resolve()}}async admit(Z,$,V){let z=u0(await Z.concurrency(...$),V.name),X=[Z.throttle(...$)??[]].flat();if(z.length===0&&X.length===0)return{done:async()=>{}};let Y=this.driver,G=async()=>{};if(z.length>0&&Y.acquireSlots&&Y.releaseSlots){if(!await Y.acquireSlots({holder:V.id,job:V,slots:z,recheckMs:this.slotRecheck()}))return;G=()=>Y.releaseSlots(V.id)}else if(z.length>0){let Q=await this.lockSlots(z);if(!Q){await Y.release(V,{retryInMs:Math.round(this.config.pollInterval*(1+Math.random()))});return}G=async()=>{await Promise.all(Q.map((J)=>J.release()))}}let B=this.locks,H=[];try{for(let Q of X){let J=`gemi:throttle:${Q.key}`,F=await B.store.hit(J,Q.limit,Q.window);if(!F.allowed){await Promise.all(H.map((U)=>B.store.refund(U))),await G(),await Y.release(V,{retryInMs:Math.max(1,F.resetInMs)});return}H.push(J)}}catch(Q){throw await G().catch(()=>{}),Q}return{done:async()=>{await G().catch((Q)=>{console.error(`[gemi] Could not free a concurrency slot of ${V.name}.`,Q)})}}}slotRecheck(){return{near:Math.max(1000,this.config.visibilityTimeout),far:3600000}}async lockSlots(Z){let $=this.config.visibilityTimeout,V=[];for(let{key:z,limit:X}of Z){let Y;for(let G=0;G<X&&!Y;G++)Y=await this.locks.acquire(`gemi:concurrency:${z}:${G}`,{ttl:$,renew:!0})??void 0;if(!Y){await Promise.all(V.map((G)=>G.release()));return}V.push(Y)}return V}}function oZ(Z,$){return`gemi:job:${Z}:${String($)}`}function AZ(Z,$){try{$()}catch(V){console.error(`${Z} threw; the job's claim was ended anyway.`,V)}}function o1(){return Bun.env.NODE_ENV==="production"}function e1(){if(!a1)return!1;if($3())return!0;return process.env.ROOT_DIR!==void 0&&!Z3()}function Z3(Z=process.env){return(Z.GEMI_QUEUE_CLAIM??"").trim().toLowerCase()==="off"}var V1=Symbol.for("gemi.queue.worker");function _6(Z=!0){globalThis[V1]=Z}function $3(){return globalThis[V1]===!0}function V3(Z,$){if(Z==="memory")return new p0;if(Z==="database"||typeof Z==="function"){if(!$&&(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 e0($.make(DZ));return 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}var z1=65536,z3=500;class X3{static write(Z,$){return KZ(I0(),Z,$,null)}static async read(Z,$){let[V]=await A0(I0()).readSource(Z,$,$+1);return V?JSON.parse(V.payload):void 0}static async readRange(Z,$,V){return(await A0(I0()).readSource(Z,$,V)).map((X)=>JSON.parse(X.payload))}static delete(Z){return A0(I0()).deleteSource(Z)}static prune(Z){return A0(I0()).pruneSources(r(Z))}}function I0(){return B0($0).workflows.store}function A0(Z){if(!Z.writeSource||!Z.readSource||!Z.deleteSource||!Z.pruneSources)throw Error("This queue's workflow store does not keep item sources. The memory and database drivers do.");return Z}async function KZ(Z,$,V,z){if(typeof $!=="string"||$.length===0||$.length>191)throw TypeError(`An item source id is a string of 1 to 191 characters; got ${JSON.stringify($)}.`);A0(Z),await Z.deleteSource($);let X=0,Y=[];for await(let G of V){let B=JSON.stringify(G===void 0?null:G);if(B===void 0)throw TypeError(`Item ${X} of source "${$}" has no JSON form.`);let H=Buffer.byteLength(B,"utf8");if(H>z1)throw RangeError(`Item ${X} of source "${$}" is ${H} bytes as JSON, over the ${z1}-byte limit. Store it elsewhere and keep its id.`);if(Y.push({index:X++,payload:B}),Y.length>=z3)await Z.writeSource($,z,Y),Y=[]}return await Z.writeSource($,z,Y),{id:$,count:X}}function nZ(Z,$,V){A0(Z);let z=new Map,X=new Map,Y=0,G=(B,H)=>{let Q=`${B}:${H}`,J=X.get(Q);if(!J)J=Z.readSource($.id,B,H).then((F)=>{for(let U of F)z.set(U.index,U.payload);X.delete(Q)},(F)=>{throw X.delete(Q),F}),X.set(Q,J);return J};return async(B)=>{if(!z.has(B)){let Q=B-B%V,J=Math.min(Q+V,$.count);if(X.has(`${Q}:${J}`))await X.get(`${Q}:${J}`);else if(B>=Y)Y=Math.max(Y,J),await G(Q,J);if(!z.has(B))await G(B,B+1)}let H=z.get(B);if(z.delete(B),H===void 0)throw Error(`Item source "${$.id}" has no item at index ${B}.`);return JSON.parse(H)}}
|
|
589
|
+
export{C0 as ye,g0 as ze,r0 as Ae,jZ as Be,e0 as Ce,E3 as De,mZ as Ee,ZZ as Fe,p0 as Ge,z1 as He,X3 as Ie,YZ as Je,GZ as Ke,BZ as Le,QZ as Me,FZ as Ne,d0 as Oe,RZ as Pe,$0 as Qe,e1 as Re,Z3 as Se,_6 as Te,$3 as Ue,Q0 as Ve};
|
|
590
590
|
|
|
591
|
-
//# debugId=
|
|
591
|
+
//# debugId=21BB7373F3EBE93A64756E2164756E21
|