gemi 0.228.0 → 0.229.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ai/index.js +1 -1
- package/dist/ai/providers/live.d.ts.map +1 -1
- package/dist/ai/testing/index.js +1 -1
- package/dist/chunk-0zakpsep.js.map +2 -2
- package/dist/{chunk-9jz5ts7h.js → chunk-2spm1f1j.js} +1 -1
- package/dist/{chunk-hhpme9te.js → chunk-5z7mzg77.js} +1 -1
- package/dist/{chunk-xv46emqt.js → chunk-c71dr883.js} +65 -51
- package/dist/{chunk-xv46emqt.js.map → chunk-c71dr883.js.map} +4 -4
- package/dist/{chunk-z0s09je5.js → chunk-enyer84t.js} +7 -7
- package/dist/{chunk-z0s09je5.js.map → chunk-enyer84t.js.map} +3 -3
- package/dist/{chunk-dpn78sq7.js → chunk-kpmp5hmc.js} +1 -1
- package/dist/chunk-nrcjn6v3.js +10 -0
- package/dist/{chunk-hddxvnh7.js.map → chunk-nrcjn6v3.js.map} +6 -6
- package/dist/{chunk-wyb6k943.js → chunk-yjn9fbw0.js} +2 -2
- package/dist/{chunk-wyb6k943.js.map → chunk-yjn9fbw0.js.map} +1 -1
- package/dist/{chunk-z6zvemqa.js → chunk-z2932q74.js} +1 -1
- package/dist/console/run.js +1 -1
- package/dist/kernel/index.js +1 -1
- package/dist/server/index.js +1 -1
- package/dist/services/cron/ScheduleServiceProvider.d.ts.map +1 -1
- package/dist/services/index.d.ts +1 -0
- package/dist/services/index.d.ts.map +1 -1
- package/dist/services/index.js +9 -9
- package/dist/services/index.js.map +4 -3
- package/dist/services/lock/DatabaseLockStore.d.ts +23 -3
- package/dist/services/lock/DatabaseLockStore.d.ts.map +1 -1
- package/dist/services/lock/LockStore.d.ts +14 -1
- package/dist/services/lock/LockStore.d.ts.map +1 -1
- package/dist/services/lock/MemoryLockStore.d.ts +3 -1
- package/dist/services/lock/MemoryLockStore.d.ts.map +1 -1
- package/dist/services/lock/lockStoreContract.d.ts.map +1 -1
- package/dist/services/queue/work.js +1 -1
- package/dist/services/rate-limiter/RateLimiterServiceProvider.d.ts +11 -0
- package/dist/services/rate-limiter/RateLimiterServiceProvider.d.ts.map +1 -1
- package/dist/services/rate-limiter/config.d.ts +4 -2
- package/dist/services/rate-limiter/config.d.ts.map +1 -1
- package/dist/services/rate-limiter/drivers/DatabaseRateLimiterDriver.d.ts +75 -0
- package/dist/services/rate-limiter/drivers/DatabaseRateLimiterDriver.d.ts.map +1 -0
- package/dist/services/rate-limiter/drivers/rateLimiterDriverContract.d.ts +15 -0
- package/dist/services/rate-limiter/drivers/rateLimiterDriverContract.d.ts.map +1 -0
- package/package.json +1 -1
- package/dist/chunk-hddxvnh7.js +0 -10
- /package/dist/{chunk-9jz5ts7h.js.map → chunk-2spm1f1j.js.map} +0 -0
- /package/dist/{chunk-hhpme9te.js.map → chunk-5z7mzg77.js.map} +0 -0
- /package/dist/{chunk-dpn78sq7.js.map → chunk-kpmp5hmc.js.map} +0 -0
- /package/dist/{chunk-z6zvemqa.js.map → chunk-z2932q74.js.map} +0 -0
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Rk as r,Sk as x0,Uk as
|
|
2
|
+
import{Rk as r,Sk as x0,Uk as Z1,el as l0}from"./chunk-0zakpsep.js";import{gl as eZ}from"./chunk-djhr379j.js";import{il as yZ,jl as fZ,kl as TZ,ml as o,nl as rZ,pl as O0,yl as v0}from"./chunk-qgka1mvf.js";import{Rl as DZ}from"./chunk-znh1mbqs.js";import{mm as oZ,pm as B0}from"./chunk-6fpjc2eg.js";import{ym as w0}from"./chunk-0dp6jvrg.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 Q1(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}
|
|
6
6
|
WHERE name = ${Z} AND expires_at <= ${X}
|
|
7
|
-
`;if(
|
|
7
|
+
`;if(e(G)===0)return null;let[B]=await z`
|
|
8
8
|
SELECT token FROM ${this.name(z)} WHERE name = ${Z} AND owner = ${$}
|
|
9
9
|
`;return B?Number(B.token):null}let Y=await z`
|
|
10
10
|
UPDATE ${this.name(z)}
|
|
@@ -16,11 +16,11 @@ import{Rk as r,Sk as x0,Uk as eZ,el as d0}from"./chunk-0zakpsep.js";import{gl as
|
|
|
16
16
|
UPDATE ${this.name(X)}
|
|
17
17
|
SET expires_at = ${Y} + ${this.ms(X,z)}, updated_at = ${Y}
|
|
18
18
|
WHERE name = ${Z} AND owner = ${$} AND token = ${V} AND expires_at > ${Y}
|
|
19
|
-
`;if(
|
|
19
|
+
`;if(e(G)>0)return!0;return this.mysql?this.held(Z,$,V):!1}async release(Z,$,V){await this.configure();let z=this.sql,X=this.now(z),Y=V===void 0?z`1 = 1`:z`token = ${V}`,G=await z`
|
|
20
20
|
UPDATE ${this.name(z)}
|
|
21
21
|
SET owner = '', expires_at = 0, updated_at = ${X}
|
|
22
22
|
WHERE name = ${Z} AND owner = ${$} AND ${Y} AND expires_at > ${X}
|
|
23
|
-
`;return
|
|
23
|
+
`;return e(G)>0}async holder(Z){await this.configure();let $=this.sql,[V]=await $`
|
|
24
24
|
SELECT owner, token FROM ${this.name($)}
|
|
25
25
|
WHERE name = ${Z} AND expires_at > ${this.now($)}
|
|
26
26
|
`;return V?{owner:String(V.owner),token:Number(V.token)}:null}async held(Z,$,V){await this.configure();let z=this.sql;return(await z`
|
|
@@ -30,35 +30,49 @@ import{Rk as r,Sk as x0,Uk as eZ,el as d0}from"./chunk-0zakpsep.js";import{gl as
|
|
|
30
30
|
UPDATE ${this.name(V)}
|
|
31
31
|
SET token = ${this.int(V,$)}, updated_at = ${this.now(V)}
|
|
32
32
|
WHERE name = ${Z} AND token < ${this.int(V,$)}
|
|
33
|
-
`;return
|
|
33
|
+
`;return e(z)>0}async fence(Z,$,V,z){await this.configure();let X=async(G)=>{let B=this.now(G),H;if(this.dialect==="sqlite"){let Q=await G`
|
|
34
34
|
UPDATE ${this.name(G)} SET updated_at = ${B}
|
|
35
35
|
WHERE name = ${Z} AND owner = ${$} AND token = ${V} AND expires_at > ${B}
|
|
36
|
-
`;H=
|
|
36
|
+
`;H=e(Q)>0}else H=(await G`
|
|
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)return await this.sql.begin((G)=>X(G));return v0(this.sql,(G)=>
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
40
|
+
`).length>0;if(!H)throw new x0(Z,V);return z()},Y=this.connection;if(Y===void 0)return await this.sql.begin((G)=>X(G));return v0(this.sql,(G)=>TZ(Y,()=>X(G)),{connection:Y})}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
|
+
INSERT INTO ${Q} (name, owner, token, expires_at, updated_at)
|
|
42
|
+
VALUES (${Z}, '', ${B}, ${Y} + ${G}, ${Y})
|
|
43
|
+
ON CONFLICT (name) DO UPDATE
|
|
44
|
+
SET token = CASE WHEN ${Q}.expires_at <= ${Y} THEN ${B} ELSE ${Q}.token + ${B} END,
|
|
45
|
+
expires_at = CASE WHEN ${Q}.expires_at <= ${Y} THEN ${Y} + ${G} ELSE ${Q}.expires_at END,
|
|
46
|
+
updated_at = ${Y}
|
|
47
|
+
WHERE ${Q}.expires_at <= ${Y} OR ${Q}.token + ${B} <= ${H}
|
|
48
|
+
RETURNING token, expires_at - ${Y} AS reset
|
|
49
|
+
`;if(J[0])return s0(!0,J[0]);return s0(!1,await this.window(X,Z))}for(let J=0;;J++){await this.seed(X,Z);let F=await X`
|
|
50
|
+
UPDATE ${Q}
|
|
51
|
+
SET token = CASE WHEN expires_at <= ${Y} THEN ${B} ELSE token + ${B} END,
|
|
52
|
+
expires_at = CASE WHEN expires_at <= ${Y} THEN ${Y} + ${G} ELSE expires_at END,
|
|
53
|
+
updated_at = ${Y}
|
|
54
|
+
WHERE name = ${Z} AND (expires_at <= ${Y} OR token + ${B} <= ${H})
|
|
55
|
+
`,U=e(F)>0,A=await this.window(X,Z);if(U||A||J>0)return s0(U,A)}}async pruneWindows(Z,$=1000){if(Z==="")throw Error("pruneWindows needs a prefix: it must never reach lock rows.");await this.configure();let V=this.sql,z=this.now(V),X=this.name(V),Y=V.unsafe(String(Math.max(1,Math.floor($)))),G=V.unsafe(String(Z.length)),B=this.mysql?V`CAST(substr(name, 1, ${G}) AS BINARY) = CAST(${Z} AS BINARY) AND expires_at <= ${z}`:V`substr(name, 1, ${G}) = ${Z} AND expires_at <= ${z}`,H=this.mysql?await V`DELETE FROM ${X} WHERE ${B} LIMIT ${Y}`:await V`
|
|
56
|
+
DELETE FROM ${X}
|
|
57
|
+
WHERE name IN (SELECT name FROM ${X} WHERE ${B} LIMIT ${Y})
|
|
58
|
+
-- Again here: a hit may have restarted a window since the select.
|
|
59
|
+
AND expires_at <= ${z}
|
|
60
|
+
`;return e(H)}async window(Z,$){let[V]=await Z`
|
|
61
|
+
SELECT token, expires_at - ${this.now(Z)} AS reset FROM ${this.name(Z)} WHERE name = ${$}
|
|
62
|
+
`;return V}async refund(Z){await this.configure();let $=this.sql,V=this.now($);await $`
|
|
49
63
|
UPDATE ${this.name($)} SET token = token - 1, updated_at = ${V}
|
|
50
64
|
WHERE name = ${Z} AND token > 0 AND expires_at > ${V}
|
|
51
65
|
`}async prune(Z){await this.configure();let $=this.sql,V=this.now($),z=await $`
|
|
52
66
|
DELETE FROM ${this.name($)}
|
|
53
67
|
WHERE expires_at <= ${V} AND updated_at <= ${V} - ${this.ms($,Z)}
|
|
54
|
-
`;return
|
|
68
|
+
`;return e(z)}async seed(Z,$){let V=this.now(Z);if(this.mysql){await Z`
|
|
55
69
|
INSERT IGNORE INTO ${this.name(Z)} (name, owner, token, expires_at, updated_at)
|
|
56
70
|
VALUES (${$}, '', 0, 0, ${V})
|
|
57
71
|
`;return}await Z`
|
|
58
72
|
INSERT INTO ${this.name(Z)} (name, owner, token, expires_at, updated_at)
|
|
59
73
|
VALUES (${$}, '', 0, 0, ${V})
|
|
60
74
|
ON CONFLICT (name) DO NOTHING
|
|
61
|
-
`}get mysql(){return this.dialect==="mysql"||this.dialect==="mariadb"}configure(){if(this.dialect!=="sqlite"||this.busyTimeout===0)return Promise.resolve();return this.configured??=(async()=>{let[Z]=await this.sql.unsafe("PRAGMA busy_timeout");if(Number(Z?.timeout??0)!==0)return;await this.sql.unsafe(`PRAGMA busy_timeout = ${this.busyTimeout}`)})().catch((Z)=>{throw this.configured=void 0,Z}),this.configured}name(Z){return Z.unsafe(this.mysql?`\`${this.table}\``:`"${this.table}"`)}now(Z){switch(this.dialect){case"postgres":return Z`floor(extract(epoch from statement_timestamp()) * 1000)::bigint`;case"mysql":case"mariadb":return Z`(TIMESTAMPDIFF(MICROSECOND, '1970-01-01 00:00:00', UTC_TIMESTAMP(6)) DIV 1000)`;case"sqlite":return Z`CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER)`}}ms(Z,$){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
|
|
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 Q1(Z,$){if(Z==="mysql"||Z==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${$}\` (
|
|
62
76
|
\`name\` VARCHAR(191) NOT NULL,
|
|
63
77
|
\`owner\` VARCHAR(191) NOT NULL,
|
|
64
78
|
\`token\` BIGINT NOT NULL DEFAULT 0,
|
|
@@ -74,13 +88,13 @@ import{Rk as r,Sk as x0,Uk as eZ,el as d0}from"./chunk-0zakpsep.js";import{gl as
|
|
|
74
88
|
"token" BIGINT NOT NULL DEFAULT 0,
|
|
75
89
|
"expires_at" BIGINT NOT NULL,
|
|
76
90
|
"updated_at" BIGINT NOT NULL${z}
|
|
77
|
-
)`]}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){let
|
|
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 H1=["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`
|
|
78
92
|
INSERT INTO ${this.workflows(Z)}
|
|
79
93
|
(id, name, args, status, progress, retick, created_at, updated_at)
|
|
80
94
|
VALUES
|
|
81
95
|
(${$.id}, ${$.name}, ${$.args}, 'running',
|
|
82
96
|
${this.db.fraction(Z,0)}, 0, ${V}, ${V})
|
|
83
|
-
`,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:SZ(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`
|
|
84
98
|
UPDATE ${this.workflows(z)}
|
|
85
99
|
SET locked_by = ${$}, locked_until = ${this.db.ms(z,G)}, retick = 0
|
|
86
100
|
WHERE id = ${Z}
|
|
@@ -88,23 +102,23 @@ import{Rk as r,Sk as x0,Uk as eZ,el as d0}from"./chunk-0zakpsep.js";import{gl as
|
|
|
88
102
|
UPDATE ${this.workflows(z)}
|
|
89
103
|
SET locked_until = ${this.db.now(z)} + ${this.db.ms(z,V)}
|
|
90
104
|
WHERE id = ${Z} AND locked_by = ${$}
|
|
91
|
-
`;return
|
|
105
|
+
`;return y0(X)>0}update(Z,$,V){let z=async(Y)=>{let G=await this.lock(Y,Z);if(!G)return;if($.owner!==void 0&&G.lockedBy!==$.owner)throw new b(Z);let B=$.key===void 0?null:await this.stepOf(Y,Z,$.key),H=$.allSteps?await this.stepsOf(Y,Z):[],Q=$.items===void 0?[]:await this.itemsOf(Y,Z,$.items,["running","retrying"],-1,null),J=V({workflow:G,step:B,steps:H,items:Q,now:Date.now()});if(J.step){let P=J.step.key===$.key?B!==null:await this.stepOf(Y,Z,J.step.key)!==null;await this.writeStep(Y,J.step,P)}if(J.items)await this.writeItems(Y,Z,J.items);if(J.batch)await this.db.insertBatch(Y,J.batch);for(let P of J.cancelBatches??[])await this.db.cancelBatch(Y,P);let F={...G,...J.workflow},U=J.unlock===!0,A=Y`
|
|
92
106
|
status = ${F.status}, current_step = ${F.currentStep},
|
|
93
107
|
progress = ${this.db.fraction(Y,F.progress)}, result = ${F.result},
|
|
94
108
|
error = ${F.error}, wake_at = ${this.db.timeOrNull(Y,F.wakeAt)},
|
|
95
109
|
updated_at = ${this.db.now(Y)}
|
|
96
110
|
`;if(U)await Y`
|
|
97
111
|
UPDATE ${this.workflows(Y)}
|
|
98
|
-
SET ${
|
|
112
|
+
SET ${A}, locked_by = NULL, locked_until = NULL, retick = 0
|
|
99
113
|
WHERE id = ${Z}
|
|
100
|
-
`;else await Y`UPDATE ${this.workflows(Y)} SET ${
|
|
114
|
+
`;else await Y`UPDATE ${this.workflows(Y)} SET ${A} WHERE id = ${Z}`;let N=(P)=>this.db.insertJob(Y,{name:m,args:JSON.stringify([Z]),delayMs:Math.max(0,Math.round(P))});if(J.tick)await N(J.tick.delayMs);if(U&&G.retick)await N(0);return J.result},X=$.joinTransaction?this.db.transaction():void 0;return X?z(X):this.db.atomically(z)}async listItems(Z,$,V){return await this.db.configure(),this.itemsOf(this.db.sql,Z,$,V.statuses,V.after??-1,V.limit)}async prune(Z){let $=await this.db.atomically(async(V)=>{let z=this.endedClause(V),X=V`${this.db.now(V)} - ${this.db.ms(V,Z)}`;await V`
|
|
101
115
|
DELETE FROM ${this.steps(V)}
|
|
102
116
|
WHERE workflow_id IN (
|
|
103
117
|
SELECT id FROM ${this.workflows(V)} WHERE ${z} AND updated_at <= ${X}
|
|
104
118
|
)
|
|
105
119
|
`;let Y=await V`
|
|
106
120
|
DELETE FROM ${this.workflows(V)} WHERE ${z} AND updated_at <= ${X}
|
|
107
|
-
`;return
|
|
121
|
+
`;return y0(Y)});try{let V=this.db.sql;await V`
|
|
108
122
|
DELETE FROM ${this.items(V)}
|
|
109
123
|
WHERE NOT EXISTS (
|
|
110
124
|
SELECT 1 FROM ${this.workflows(V)} w WHERE w.id = ${this.items(V)}.workflow_id
|
|
@@ -121,11 +135,11 @@ import{Rk as r,Sk as x0,Uk as eZ,el as d0}from"./chunk-0zakpsep.js";import{gl as
|
|
|
121
135
|
SELECT idx, payload FROM ${this.sources(z)}
|
|
122
136
|
WHERE source_id = ${Z} AND idx >= ${$} AND idx < ${V}
|
|
123
137
|
ORDER BY idx
|
|
124
|
-
`,this.sourceTable)).map((Y)=>({index:Number(Y.idx),payload:String(Y.payload)}))}async deleteSource(Z){await this.db.configure();let $=this.db.sql,V=await b0($`DELETE FROM ${this.sources($)} WHERE source_id = ${Z}`,this.sourceTable);return
|
|
138
|
+
`,this.sourceTable)).map((Y)=>({index:Number(Y.idx),payload:String(Y.payload)}))}async deleteSource(Z){await this.db.configure();let $=this.db.sql,V=await b0($`DELETE FROM ${this.sources($)} WHERE source_id = ${Z}`,this.sourceTable);return y0(V)}async pruneSources(Z){await this.db.configure();let $=this.db.sql,V=await b0($`
|
|
125
139
|
DELETE FROM ${this.sources($)}
|
|
126
140
|
WHERE workflow_id IS NULL
|
|
127
141
|
AND created_at <= ${this.db.now($)} - ${this.db.ms($,Z)}
|
|
128
|
-
`,this.sourceTable);return
|
|
142
|
+
`,this.sourceTable);return y0(V)}endedClause(Z){return Z`status IN (${H1.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`
|
|
129
143
|
DELETE FROM ${this.items(Z)}
|
|
130
144
|
WHERE workflow_id = ${$} AND step_key = ${X}
|
|
131
145
|
AND idx IN (${H.reduce((Q,J)=>Z`${Q}, ${J}`)})
|
|
@@ -133,12 +147,12 @@ import{Rk as r,Sk as x0,Uk as eZ,el as d0}from"./chunk-0zakpsep.js";import{gl as
|
|
|
133
147
|
${$}, ${X}, ${J.index}, ${J.key}, ${J.status}, ${J.attempt},
|
|
134
148
|
${J.error}, ${J.output}, ${z.timeOrNull(Z,J.wakeAt)},
|
|
135
149
|
${z.timeOrNull(Z,J.startedAt)}, ${z.timeOrNull(Z,J.finishedAt)}, ${H}, ${H}
|
|
136
|
-
)`);await
|
|
150
|
+
)`);await f0(Z`
|
|
137
151
|
INSERT INTO ${this.items(Z)}
|
|
138
152
|
(workflow_id, step_key, idx, item_key, status, attempt, error, output, wake_at,
|
|
139
153
|
started_at, finished_at, created_at, updated_at)
|
|
140
154
|
VALUES ${Q.reduce((J,F)=>Z`${J}, ${F}`)}
|
|
141
|
-
`,this.itemTable)}for(let B of V.update??[])await
|
|
155
|
+
`,this.itemTable)}for(let B of V.update??[])await f0(Z`
|
|
142
156
|
UPDATE ${this.items(Z)}
|
|
143
157
|
SET item_key = ${B.key}, status = ${B.status}, attempt = ${B.attempt},
|
|
144
158
|
error = ${B.error}, output = ${B.output},
|
|
@@ -146,7 +160,7 @@ import{Rk as r,Sk as x0,Uk as eZ,el as d0}from"./chunk-0zakpsep.js";import{gl as
|
|
|
146
160
|
started_at = ${z.timeOrNull(Z,B.startedAt)},
|
|
147
161
|
finished_at = ${z.timeOrNull(Z,B.finishedAt)}, updated_at = ${z.now(Z)}
|
|
148
162
|
WHERE workflow_id = ${$} AND step_key = ${X} AND idx = ${B.index}
|
|
149
|
-
`,this.itemTable)}async itemsOf(Z,$,V,z,X,Y){let G=z.map((H)=>Z`${H}`).reduce((H,Q)=>Z`${H}, ${Q}`);return(await
|
|
163
|
+
`,this.itemTable)}async itemsOf(Z,$,V,z,X,Y){let G=z.map((H)=>Z`${H}`).reduce((H,Q)=>Z`${H}, ${Q}`);return(await f0(Y===null?Z`
|
|
150
164
|
SELECT * FROM ${this.items(Z)}
|
|
151
165
|
WHERE workflow_id = ${$} AND step_key = ${V}
|
|
152
166
|
AND status IN (${G}) AND idx > ${X}
|
|
@@ -156,7 +170,7 @@ import{Rk as r,Sk as x0,Uk as eZ,el as d0}from"./chunk-0zakpsep.js";import{gl as
|
|
|
156
170
|
WHERE workflow_id = ${$} AND step_key = ${V}
|
|
157
171
|
AND status IN (${G}) AND idx > ${X}
|
|
158
172
|
ORDER BY idx LIMIT ${Y}
|
|
159
|
-
`,this.itemTable)).map(
|
|
173
|
+
`,this.itemTable)).map(J1)}async writeStep(Z,$,V){let z=this.db,X=this.keyColumn(Z);if(V){await Z`
|
|
160
174
|
UPDATE ${this.steps(Z)}
|
|
161
175
|
SET status = ${$.status}, attempt = ${$.attempt}, output = ${$.output},
|
|
162
176
|
error = ${$.error}, batch_id = ${$.batchId},
|
|
@@ -172,10 +186,10 @@ import{Rk as r,Sk as x0,Uk as eZ,el as d0}from"./chunk-0zakpsep.js";import{gl as
|
|
|
172
186
|
(${$.workflowId}, ${$.key}, ${$.status}, ${$.attempt}, ${$.output},
|
|
173
187
|
${$.error}, ${$.batchId}, ${z.timeOrNull(Z,$.wakeAt)},
|
|
174
188
|
${z.timeOrNull(Z,$.startedAt)}, ${z.timeOrNull(Z,$.finishedAt)}, ${Y}, ${Y})
|
|
175
|
-
`}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]?SZ(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?IZ(z):null}async stepsOf(Z,$){return(await P0(Z`
|
|
176
190
|
SELECT * FROM ${this.steps(Z)} WHERE workflow_id = ${$}
|
|
177
191
|
ORDER BY created_at, ${this.keyColumn(Z)}
|
|
178
|
-
`,this.stepTable)).map(
|
|
192
|
+
`,this.stepTable)).map(IZ)}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 SZ(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 IZ(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 J1(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 MZ(Z,$,V){if(Z==="mysql"||Z==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${$}\` (
|
|
179
193
|
\`id\` VARCHAR(191) NOT NULL,
|
|
180
194
|
\`name\` VARCHAR(191) NOT NULL,
|
|
181
195
|
\`args\` LONGTEXT NOT NULL,
|
|
@@ -240,7 +254,7 @@ import{Rk as r,Sk as x0,Uk as eZ,el as d0}from"./chunk-0zakpsep.js";import{gl as
|
|
|
240
254
|
"updated_at" BIGINT NOT NULL,
|
|
241
255
|
|
|
242
256
|
${z?'PRIMARY KEY ("workflow_id", "key")':`CONSTRAINT "${V}_pkey" PRIMARY KEY ("workflow_id","key")`}
|
|
243
|
-
)`,`CREATE INDEX IF NOT EXISTS "${$}_status_idx" ON "${$}"("status")`]}function
|
|
257
|
+
)`,`CREATE INDEX IF NOT EXISTS "${$}_status_idx" ON "${$}"("status")`]}function jZ(Z,$){if(Z==="mysql"||Z==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${$}\` (
|
|
244
258
|
\`workflow_id\` VARCHAR(191) NOT NULL,
|
|
245
259
|
\`step_key\` VARCHAR(191) NOT NULL,
|
|
246
260
|
\`idx\` INTEGER NOT NULL,
|
|
@@ -272,7 +286,7 @@ import{Rk as r,Sk as x0,Uk as eZ,el as d0}from"./chunk-0zakpsep.js";import{gl as
|
|
|
272
286
|
"updated_at" BIGINT NOT NULL,
|
|
273
287
|
|
|
274
288
|
${Z==="sqlite"?'PRIMARY KEY ("workflow_id", "step_key", "idx")':`CONSTRAINT "${$}_pkey" PRIMARY KEY ("workflow_id","step_key","idx")`}
|
|
275
|
-
)`]}function
|
|
289
|
+
)`]}function vZ(Z,$){if(Z==="mysql"||Z==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${$}\` (
|
|
276
290
|
\`source_id\` VARCHAR(191) NOT NULL,
|
|
277
291
|
\`idx\` INTEGER NOT NULL,
|
|
278
292
|
\`workflow_id\` VARCHAR(191) NULL,
|
|
@@ -289,7 +303,7 @@ import{Rk as r,Sk as x0,Uk as eZ,el as d0}from"./chunk-0zakpsep.js";import{gl as
|
|
|
289
303
|
"created_at" BIGINT NOT NULL,
|
|
290
304
|
|
|
291
305
|
${Z==="sqlite"?'PRIMARY KEY ("source_id", "idx")':`CONSTRAINT "${$}_pkey" PRIMARY KEY ("source_id","idx")`}
|
|
292
|
-
)`,`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:P1}=globalThis.Bun;class t0{db;statements;own;ownTail=Promise.resolve();constructor(Z,$){this.db=Z;this.statements=U1(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||F1.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&&K1.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||!R1(V))throw A1(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"||!N1())return;let Z=this.db.sql.options;if(Z?.adapter!=="postgres")return;return this.own=new P1({...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 K1=["pending","claimed"],F1=["completed","failed","cancelled","paused"];function xZ(Z,$){if(Z==="mysql"||Z==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${$}\` (
|
|
293
307
|
\`slot_key\` VARCHAR(191) NOT NULL,
|
|
294
308
|
\`holder\` VARCHAR(191) NOT NULL,
|
|
295
309
|
\`job_id\` VARCHAR(191) NULL,
|
|
@@ -313,7 +327,7 @@ import{Rk as r,Sk as x0,Uk as eZ,el as d0}from"./chunk-0zakpsep.js";import{gl as
|
|
|
313
327
|
"slot_limit" INTEGER NOT NULL DEFAULT 0,
|
|
314
328
|
"queued_at" BIGINT NOT NULL,
|
|
315
329
|
"updated_at" BIGINT NOT NULL${V}
|
|
316
|
-
)`,`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 U1(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)
|
|
317
331
|
VALUES ({key}, '', 'gate', ${H("limit")}, ${B}, ${B})
|
|
318
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)
|
|
319
333
|
VALUES ({key}, '', 'gate', 0, ${B}, ${B})
|
|
@@ -345,12 +359,12 @@ import{Rk as r,Sk as x0,Uk as eZ,el as d0}from"./chunk-0zakpsep.js";import{gl as
|
|
|
345
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}
|
|
346
360
|
SET status = 'pending', attempts = attempts - 1, available_at = ${B} + ${H("ms")},
|
|
347
361
|
lease_expires_at = NULL, updated_at = ${B}
|
|
348
|
-
WHERE id = {id} AND status = 'claimed' AND attempts = ${H("attempt")}`},F=new Map;return{table:$.slots,texts:J,compile(U,
|
|
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 N1(){let[Z=0,$=0]=Bun.version.split(".").map(Number);return Z<1||Z===1&&$<4}function R1(Z){let $=Z;return $?.errno===1213||$?.code==="40P01"||/deadlock|try restarting transaction/i.test(String($?.message??""))}function A1(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 gZ=200,D1="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,...$]=_1(this.dialect,this.table);if(await this.sql.unsafe(Z),!await this.hasBatchColumns())for(let V of L1(this.dialect,this.table))await this.sql.unsafe(V);for(let V of $)await this.sql.unsafe(V);for(let V of C1(this.dialect,this.batchTable))await this.sql.unsafe(V);for(let V of MZ(this.dialect,this.workflowTable,this.workflowStepTable))await this.sql.unsafe(V);for(let V of jZ(this.dialect,this.workflowItemTable))await this.sql.unsafe(V);for(let V of vZ(this.dialect,this.workflowSourceTable))await this.sql.unsafe(V);for(let V of xZ(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(bZ(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`
|
|
349
363
|
INSERT INTO ${this.name(Z)}
|
|
350
364
|
(id, name, payload, status, attempts, available_at, created_at, updated_at)
|
|
351
365
|
VALUES
|
|
352
366
|
(${X}, ${$}, ${V}, 'pending', 0, ${Y} + ${this.ms(Z,z)}, ${Y}, ${Y})
|
|
353
|
-
`,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=yZ();if(Z===void 0||fZ()!==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 $`
|
|
354
368
|
DELETE FROM ${this.name($)}
|
|
355
369
|
WHERE id = ${Z.id} AND status = 'claimed' AND attempts = ${Z.attempt}
|
|
356
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`
|
|
@@ -384,22 +398,22 @@ import{Rk as r,Sk as x0,Uk as eZ,el as d0}from"./chunk-0zakpsep.js";import{gl as
|
|
|
384
398
|
`;return U0(X)>0}async prune(Z){await this.configure();let $=this.sql,V=await $`
|
|
385
399
|
DELETE FROM ${this.name($)}
|
|
386
400
|
WHERE status = 'dead' AND updated_at <= ${this.now($)} - ${this.ms($,Z)}
|
|
387
|
-
`;return U0(V)}enqueueBatch(Z){let $=this.transaction(),V=$?this.insertBatch($,Z):this.atomically((z)=>this.insertBatch(z,Z));if($)O0(V);return V}async insertBatch(Z,$){await this.configure();let V=await this.clock(Z),z=q0({...$,total:$.args.length,now:V}),{record:X,calls:Y}=F0(z,z,V);await
|
|
401
|
+
`;return U0(V)}enqueueBatch(Z){let $=this.transaction(),V=$?this.insertBatch($,Z):this.atomically((z)=>this.insertBatch(z,Z));if($)O0(V);return V}async insertBatch(Z,$){await this.configure();let V=await this.clock(Z),z=q0({...$,total:$.args.length,now:V}),{record:X,calls:Y}=F0(z,z,V);await o0(Z`
|
|
388
402
|
INSERT INTO ${this.batches(Z)}
|
|
389
403
|
(id, name, total, pending, succeeded, failed, cancelled, failed_job_ids, options,
|
|
390
404
|
cancelled_at, finished_at, created_at, updated_at)
|
|
391
405
|
VALUES
|
|
392
406
|
(${X.id}, ${X.name}, ${X.total}, ${X.pending}, 0, 0, 0,
|
|
393
|
-
'[]', ${
|
|
407
|
+
'[]', ${W1(X)}, NULL, ${this.timeOrNull(Z,X.finishedAt)},
|
|
394
408
|
${this.ms(Z,V)}, ${this.ms(Z,V)})
|
|
395
|
-
`,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+=gZ){let H=$.args.slice(B,B+gZ).map((Q)=>Z`(${Bun.randomUUIDv7()}, ${$.job}, ${Q}, 'pending', 0, ${G}, ${G}, ${G}, ${$.id}, 0)`).reduce((Q,J)=>Z`${Q}, ${J}`);await o0(Z`
|
|
396
410
|
INSERT INTO ${this.name(Z)}
|
|
397
411
|
(id, name, payload, status, attempts, available_at, created_at, updated_at, batch_id, progress)
|
|
398
412
|
VALUES ${H}
|
|
399
|
-
`,this.table)}for(let B of Y)await this.insert(Z,B)}async findBatch(Z,$={}){await this.configure();let V=this.sql,[z]=await
|
|
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=hZ(z);if($.progress===!1||X.pending===0)return G0(X);let[Y]=await V`
|
|
400
414
|
SELECT COALESCE(SUM(progress), 0) AS running FROM ${this.name(V)}
|
|
401
415
|
WHERE batch_id = ${Z} AND status IN ('pending', 'claimed')
|
|
402
|
-
`;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
|
|
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`
|
|
403
417
|
UPDATE ${this.name(z)} SET progress = ${this.fraction(z,V)}
|
|
404
418
|
WHERE id = ${Z.id} AND status = 'claimed' AND attempts = ${Z.attempt}
|
|
405
419
|
`}async pruneBatches(Z){await this.configure();let $=this.sql,V=await $`
|
|
@@ -418,7 +432,7 @@ import{Rk as r,Sk as x0,Uk as eZ,el as d0}from"./chunk-0zakpsep.js";import{gl as
|
|
|
418
432
|
WHERE ${G}
|
|
419
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`
|
|
420
434
|
UPDATE ${this.name(Z)}
|
|
421
|
-
SET status = 'dead', last_error = ${
|
|
435
|
+
SET status = 'dead', last_error = ${D1}, updated_at = ${V}
|
|
422
436
|
WHERE batch_id = ${$} AND status = 'pending'
|
|
423
437
|
`;return U0(z)}async saveBatch(Z,$,V,z){let{record:X,calls:Y}=F0($,V,z);await Z`
|
|
424
438
|
UPDATE ${this.batches(Z)}
|
|
@@ -427,7 +441,7 @@ import{Rk as r,Sk as x0,Uk as eZ,el as d0}from"./chunk-0zakpsep.js";import{gl as
|
|
|
427
441
|
cancelled_at = ${this.timeOrNull(Z,X.cancelledAt)},
|
|
428
442
|
finished_at = ${this.timeOrNull(Z,X.finishedAt)}, updated_at = ${this.ms(Z,z)}
|
|
429
443
|
WHERE id = ${X.id}
|
|
430
|
-
`;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]?hZ(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`
|
|
431
445
|
WITH next AS (
|
|
432
446
|
SELECT id FROM ${Y}
|
|
433
447
|
WHERE ${this.claimable(V,$)}
|
|
@@ -479,7 +493,7 @@ import{Rk as r,Sk as x0,Uk as eZ,el as d0}from"./chunk-0zakpsep.js";import{gl as
|
|
|
479
493
|
AND ${this.runnable(Z,$,"available_at")})
|
|
480
494
|
OR (status = 'claimed' AND lease_expires_at <= ${V}
|
|
481
495
|
AND ${this.runnable(Z,$,"lease_expires_at")})
|
|
482
|
-
)`}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 _1(Z,$){if(Z==="mysql"||Z==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${$}\` (
|
|
483
497
|
\`id\` VARCHAR(191) NOT NULL,
|
|
484
498
|
\`name\` VARCHAR(191) NOT NULL,
|
|
485
499
|
\`payload\` LONGTEXT NOT NULL,
|
|
@@ -514,10 +528,10 @@ import{Rk as r,Sk as x0,Uk as eZ,el as d0}from"./chunk-0zakpsep.js";import{gl as
|
|
|
514
528
|
"updated_at" BIGINT NOT NULL,
|
|
515
529
|
"batch_id" TEXT,
|
|
516
530
|
"progress" ${Z==="sqlite"?"REAL":"DOUBLE PRECISION"}${z}
|
|
517
|
-
)`,`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 L1(Z,$){if(Z==="mysql"||Z==="mariadb")return[`ALTER TABLE \`${$}\` ADD COLUMN \`batch_id\` VARCHAR(191) NULL,
|
|
518
532
|
ADD COLUMN \`progress\` DOUBLE NULL,
|
|
519
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,
|
|
520
|
-
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 C1(Z,$){if(Z==="mysql"||Z==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${$}\` (
|
|
521
535
|
\`id\` VARCHAR(191) NOT NULL,
|
|
522
536
|
\`name\` VARCHAR(191) NULL,
|
|
523
537
|
\`total\` INTEGER NOT NULL,
|
|
@@ -549,7 +563,7 @@ ADD COLUMN IF NOT EXISTS "progress" ${V}`,`CREATE INDEX IF NOT EXISTS "${$}_batc
|
|
|
549
563
|
"finished_at" BIGINT,
|
|
550
564
|
"created_at" BIGINT NOT NULL,
|
|
551
565
|
"updated_at" BIGINT NOT NULL${z}
|
|
552
|
-
)`]}function gZ(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 C1(Z){return JSON.stringify({allowFailures:Z.allowFailures,callbacks:Z.callbacks})}function yZ(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 t0(Z,$){try{return await Z}catch(V){if(!yZ(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 W3(Z){return Z}function bZ(){return{jobs:[],jobsDir:"app/jobs",workflows:[],workflowsDir:"app/workflows",concurrency:1,driver:"memory",visibilityTimeout:300000,pollInterval:1000,unknownJobGrace:3600000,locks:"auto"}}var W1=86400000;class e0{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(W1);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 ZZ(Z){return`workflow:${Z}`}var qZ=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>qZ)throw TypeError(`${$}.concurrency returned a key that is not a string of 1 to ${qZ} 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 $Z{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 O1=86400000;class p0{entries=new Map;batches=new Map;workflows;slots=new $Z({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 e0({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>O1)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 c1}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(Z0).push(this,JSON.stringify(Z))}static dispatchBatch(Z,$={}){if(this.name==="unset")throw Error("Cannot dispatch a job with no name");return B0(Z0).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(Z0).findBatch(Z)}static cancelBatch(Z){return B0(Z0).cancelBatch(Z)}}function E0(Z,$){let V=Array.isArray(Z)?Z[Math.min($,Z.length)-1]:Z;return Math.max(0,V??0)}class XZ extends Error{step;batch;summary;constructor(Z,$,V,z){super($);this.step=Z;this.batch=V;this.summary=z;this.name="StepFailedError"}}class YZ extends Error{step;constructor(Z){super(`No signal "${Z}" arrived before its timeout.`);this.step=Z;this.name="WaitTimeoutError"}}class GZ extends Error{constructor(Z,$){super(`Step "${Z}" took longer than its timeout of ${$}ms.`);this.name="StepTimeoutError"}}class BZ 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 mZ=Symbol("done"),kZ=Symbol("paused");class KZ{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()=>PZ(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:mZ};if(V.start&&X.workflow.status==="paused"&&!this.tick.cancelling)return{result:kZ};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===mZ)this.cancelled=!0,this.suspend("waiting");if(z===kZ)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 A=(P?.attempt??0)+1;if(A>z){let _=this.record(Z,P,{status:"failed",error:`Attempt ${A-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:A,startedAt:W,finishedAt:null,wakeAt:null});return{result:{kind:"run",attempt:A},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:A})=>{let T=N>0?A+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 D=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,D)}}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=(D)=>{X.abort(D),F(D)};if(z!==void 0)B=setTimeout(()=>U(new GZ(Z,z)),z);if(!this.tick.cancelling)H=setInterval(()=>{this.tick.store.find(this.tick.workflowId,{steps:!1}).then((D)=>{if(D?.workflow.status!=="cancelling"||X.signal.aborted)return;if(this.cancelled=!0,!this.suspension)this.suspension={status:"waiting",wakes:[]};U(new BZ(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 YZ(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 YZ(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>uZ)throw TypeError(`step.each "${Z}" needs a count that is a whole number from 0 to ${uZ}; 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?E1: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)})),D=I1($.maxFailures),N=this.tick.store,P=$.transaction===!0&&N.transaction?(K)=>N.transaction(K):void 0;if($.transaction===!0&&!P)h1();let W=z?iZ(N,z,Math.max(S1,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 A=this.steps.get(Z);if(A?.status==="completed")return JZ(A.output);if(A?.status==="failed")throw s(Z,A);if(A&&A.status!=="iterating")this.mismatch(Z,A.status,"step.each");if(this.current=Z,this.tick.durable===!1)g1();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?w0(R.output):M1(X);return{result:{kind:"go",state:x,open:L},...R?{}:{step:this.record(Z,null,{status:"iterating",output:zZ(x),startedAt:O})},workflow:K.status==="cancelling"?{currentStep:Z}:{currentStep:Z,status:"running"}}},{items:!0,start:!0});if(T.kind==="done")return JZ(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,l=new Map(T.open.map((K)=>[K.index,K])),k=[],_0=new Map,a0=new Map,DZ=Date.now()+H,H0=0,M0=!1,$0=null,p=new AbortController,_Z=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 BZ(this.workflowId))}).catch(()=>{})},this.tick.cancelCheckMs);_Z.unref?.(),$0=D(_);let LZ=(K,R)=>{let L={...K};for(let O of R)if(O.counter)L[O.counter]++;return L},CZ=(K)=>{let R=K.succeeded+K.skipped+K.failed;return Q?{workflow:{progress:D0===0?1:i(R/D0)}}:{}},WZ=(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)},!$0)$0=D(_);if($0&&!p.signal.aborted)p.abort(new t)},V1=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,V0=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 GZ(V0,B)),B)}),f=(C)=>{throw new HZ(Math.max(0,Math.floor(Number(C)||0)))},z0=(C)=>K.map((S,q)=>{let d=L.get(q);if(!d)return{index:S.index,row:null,counter:"succeeded"};return{index:S.index,row:wZ(S,R[q],d.reason,d.data,C),counter:"skipped"}}),X0=null,g=(async()=>{let C=await Promise.all(K.map((M)=>W(M.index)));K.forEach((M,v)=>{R[v]=v1($.key?$.key(C[v],M.index):M.index)});let S=(M)=>`${this.workflowId}:${Z}:${R[M]}`,q=Math.max(...K.map((M)=>M.attempt)),d=async()=>{if(J){let M={idempotencyKey:S(0),attempt:q,signal:O.signal,items:K.map((v,y)=>({index:v.index,key:R[y],idempotencyKey:S(y)})),skip:(v,y,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(y),data:I})},release:f};await V(C,M)}else{let M={idempotencyKey:S(0),attempt:q,signal:O.signal,index:K[0].index,key:R[0],skip:(v,y)=>{throw new QZ(v,y)},release:f};await V(C[0],M)}};if(!P)return d();await P(async()=>{if(await d(),O.signal.aborted)throw O.signal.reason;let M=z0(Date.now()),v=await this.write(Z,({step:y})=>{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=LZ(y?w0(y.output):_,M);return{result:a,step:this.record(Z,y,{status:"iterating",output:zZ(a)}),items:I,...CZ(a)}},{joinTransaction:!0});X0=M.map((y)=>({...y,recorded:!0})),WZ(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(X0){k.push(...X0);return}if(p.signal.aborted||this.cancelled||this.lost)return;let h=Date.now();if(!E){k.push(...z0(h));return}if(j instanceof QZ){k.push({index:K[0].index,row:wZ(K[0],R[0],j.reason,j.data,h),counter:"skipped"});return}if(j instanceof HZ){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 w=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:w,wakeAt:h+q},counter:null});return}k.push({index:C.index,row:{...C,key:R[S],status:"failed",error:w,wakeAt:null,finishedAt:h},counter:"failed"})})},z1=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((V0)=>R.refund(V0))),H0=Math.max(H0,Date.now()+Math.max(1,u.resetInMs)),L;O.push(x.name)}}return K},X1=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>=DZ||c0()||this.cancelled||M0||$0!==null,L=[],O=0;if(!R&&K>=H0){let f=(Y-_0.size)*F,z0=new Set(k.map((j)=>j.index));for(let j of[...l.values()].sort((E,h)=>E.index-h.index)){if(L.length>=f)break;if(a0.has(j.index)||z0.has(j.index))continue;if(j.status==="running"||(j.wakeAt??0)<=K)L.push(j)}let X0=Y*F+pZ-l.size;O=Math.max(0,Math.min(f-L.length,D0-_.next,X0));let g=await z1(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 f=k.splice(0,k.length),z0=f.filter((E)=>!E.recorded),X0=L.length+O,g=await this.write(Z,({workflow:E,step:h,now:w})=>{let C=LZ(h?w0(h.output):_,z0),S={step:Z,insert:[],update:[],delete:[]},q=[],d=[];for(let I of z0)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:w};C.failed++,S.update.push(J0),d.push(J0);continue}let a={...I,status:"running",attempt:I.attempt+1,wakeAt:null,startedAt:w};S.update.push(a),q.push(a)}let v=M?0:O,y=q.length;for(let I=0;I<v;I++){let a=j1(this.workflowId,Z,C.next+I,w);S.insert.push(a),q.push(a)}return C.next+=v,{result:{next:C,started:q,closed:d,reruns:y,paused:M},step:this.record(Z,h,{status:"iterating",output:zZ(C)}),items:S,...CZ(C)}});if(WZ(g.next),g.paused)M0=!0;await X1(X0-g.started.length);for(let E of f)if(E.row?.status==="retrying")l.set(E.index,E.row);else l.delete(E.index);for(let E of g.closed)l.delete(E.index);for(let E of g.started)l.set(E.index,E);let j=[...cZ(g.started.slice(0,g.reruns),F),...cZ(g.started.slice(g.reruns),F)];for(let E of j){let h=E[0].index;for(let w of E)a0.set(w.index,h);_0.set(h,V1(E).finally(()=>{_0.delete(h);for(let w of E)a0.delete(w.index)}))}}if(_0.size>0){await Promise.race(_0.values());continue}if(k.length>0)continue;if(this.cancelled)throw new t;if($0)break;if(_.next>=D0&&l.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&&l.size<Y*F+pZ)u=x;for(let f of l.values())if(f.status==="running")u=x;else if(f.status==="retrying")u=Math.min(u,f.wakeAt??0);let V0=Math.max(u,H0);if(V0<=x)continue;let L0=V0-x;if(L0<=Math.min(T1,DZ-x)){await new Promise((f)=>setTimeout(f,Math.max(0,L0)));continue}this.suspend("sleeping",V0)}}finally{if(clearInterval(_Z),!p.signal.aborted)p.abort(new t)}let OZ=await N.listItems(this.workflowId,Z,{statuses:["failed","skipped"],limit:VZ+1}),i0={...FZ(_),problems:OZ.slice(0,VZ).map(UZ),moreProblems:OZ.length>VZ},Y1=JSON.stringify({$each:_,problems:i0.problems,moreProblems:i0.moreProblems}),j0=$0,G1=await this.write(Z,({step:K,now:R})=>{let L=this.record(Z,K,{status:j0?"failed":"completed",output:Y1,error:j0,finishedAt:R});return{result:L,step:L,...Q&&!j0?{workflow:{progress:1}}:{}}});if(j0)throw s(Z,G1);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:D})=>{if(U)return{result:U};let N=this.record(Z,null,{status:"batching",batchId:F.id,startedAt:D});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 D=this.record(Z,F,{status:B?"completed":"failed",output:H,error:Q,finishedAt:U});return{result:D,step:D}});if(!B)throw s(Z,J);return G}}function s(Z,$){if($.output?.startsWith('{"$each"'))return new XZ(Z,`Step "${Z}" failed: ${$.error??"unknown error"}`,void 0,JZ($.output));let V=$.batchId!==null&&$.output!==null?JSON.parse($.output):void 0;return new XZ(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>s0)throw RangeError(`${$} is ${z} bytes as JSON, over the ${s0}-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 uZ=2147483647,E1=30000,pZ=100,T1=1000,S1=64,VZ=100;class QZ extends Error{reason;data;constructor(Z,$){super(`Skipped: ${Z}`);this.reason=Z;this.data=$;this.name="ItemSkipped"}}class HZ 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=x1(z)}catch(B){G=T0(`${G} (${N0(B)})`)}return{...Z,key:$,status:"skipped",error:G,output:Y,wakeAt:null,finishedAt:X}}function cZ(Z,$){let V=[];for(let z=0;z<Z.length;z+=$)V.push(Z.slice(z,z+$));return V}function I1(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 M1(Z){return{count:Z,next:0,succeeded:0,skipped:0,failed:0}}function zZ(Z){return JSON.stringify({$each:Z})}function w0(Z){let $=Z===null?null:JSON.parse(Z);if(!$?.$each)throw Error("A step.each step has no state.");return $.$each}function sZ(Z){if(Z===null||!Z.startsWith('{"$each"'))return null;try{return FZ(w0(Z))}catch{return null}}function FZ(Z){return{total:Z.count,done:Z.succeeded+Z.skipped+Z.failed,succeeded:Z.succeeded,skipped:Z.skipped,failed:Z.failed}}function JZ(Z){let $=JSON.parse(Z??"null");return{...FZ($.$each),problems:$.problems??[],moreProblems:$.moreProblems===!0}}function UZ(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 j1(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 v1(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 x1(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 g1(){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 dZ=!1;function h1(){if(dZ)return;dZ=!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 aZ=new Set;function f1(Z,$,V,z){let X=`${Z}:${$}`;if(aZ.has(X))return;aZ.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 l0(Z){return Z==="completed"||Z==="failed"||Z==="cancelled"}var R0=["completed","failed","cancelled"],y1=1000,b1=250,q1=30000;class NZ{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??=m1(this),this.tickClass}get store(){if(!this.storeInstance){let Z=this.queue.driver.workflowStore?.();if(!Z||!this.queue.driver.enqueueBatch)throw Error("This queue's driver does not support workflows. The memory and database drivers do.");this.storeInstance=this.publishingStore(Z)}return this.storeInstance}get feed(){let Z=this.queue.boundApplication;if(Z?.bound(d0))return Z.make(d0);return this.ownFeed??=new d0,this.ownFeed}channel(Z){return`gemi:workflow:${Z}`}async update(Z){let $=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,l0(z.status))return;let X=V[Symbol.asyncIterator](),Y=X.next();for(;;){let G=await p1(Y,q1),B;if(G==="timeout")B=await this.update(Z);else{if(G.done)return;Y=X.next(),B=u1(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,l0(z.status))return}}finally{V.close()}}publishingStore(Z){let $=(z)=>void nZ(()=>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)+b1-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(l0($.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:k1(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=sZ(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(UZ)}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:ZZ(Z),workflowId:Z,job:z,slots:U,recheckMs:this.queue.slotRecheck()}))return $.$outcome={kind:"parked"},H()}let D=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)));D.unref?.();let N=new KZ({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,A)=>this.queue.buildBatch(P,W.map((T)=>JSON.stringify(T)),{name:A.name,allowFailures:A.allowFailures,finally:{name:m,args:[Z]}}),scheduled:()=>this.queue.claimSoon(),cancelCheckMs:y1,durable:this.queue.durable,throttle:{hit:(P,W,A)=>this.queue.locks.store.hit(P,W,A),refund:(P)=>this.queue.locks.store.refund(P)}});try{let P;try{let A=new Q,T=await(F?A.onCancel(N,...J):A.run(N,...J));P=N.suspension?{kind:"suspended"}:{kind:"completed",result:F?null:S0(T,`The result of ${B.name}`)}}catch(A){if(P=N.suspension||A instanceof t?{kind:"suspended"}:{kind:"failed",error:N0(A)},A 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:A,now:T})=>{let _=this.finish(A,P,N,F,T);return W=_.workflow?.status??A.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(D)}}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?.(ZZ(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 m1(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 k1(Z){try{return n(Z)}catch{return Z}}function u1(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 p1(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 d1(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:c1(z)?z:void 0,kernel:`${V}/kernel/Kernel.ts`,app:X}}function a1(){let Z=d1(),$=Z.bootstrap?`const { app } = await import(${JSON.stringify(Z.bootstrap)});`:`const { App } = await import(${JSON.stringify(Z.app)});
|
|
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)});
|
|
553
567
|
const { default: Kernel } = await import(${JSON.stringify(Z.kernel)});
|
|
554
568
|
const app = new App({ kernel: Kernel });
|
|
555
569
|
await app.waitForBoot();`,V=new File([`
|
|
@@ -571,7 +585,7 @@ ADD COLUMN IF NOT EXISTS "progress" ${V}`,`CREATE INDEX IF NOT EXISTS "${$}_batc
|
|
|
571
585
|
}
|
|
572
586
|
};
|
|
573
587
|
self.postMessage({ ready: true });
|
|
574
|
-
`],"worker.ts"),z=URL.createObjectURL(V);return new Worker(z)}async function i1(Z,$){let V=a1();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 s1=new w1("gemi.queue"),n1=60000;class Z0{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=oZ(bZ(),Z),this.application=$.application,this.driver=Z3(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 NZ(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 eZ(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(AZ));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:rZ(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(rZ(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()&&!r1())globalThis.__gemiDevQueue=this;if(this.unsubscribe=this.driver.subscribe?.(()=>this.wake()),this.looping)return this.wake();s1.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&&c0()?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,n1)}wake(){this.woken=!0;let Z=this.resume;this.resume=void 0,Z?.()}get durable(){return!(this.driver instanceof p0)}mayClaimHere(){return!this.application||t1()}lease(){return{visibilityTimeoutMs:this.config.visibilityTimeout}}execute(Z){let $=`${Z.id}:${Z.attempt}`,V=()=>this.run(Z),z=(this.application?tZ.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.`);RZ(`${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?i1(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(RZ(`${Z.name}.onFail`,()=>V.onFail(X,...z)),!H||Z.attempt>=V.maxAttempts)RZ(`${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 rZ(Z,$){return`gemi:job:${Z}:${String($)}`}function RZ(Z,$){try{$()}catch(V){console.error(`${Z} threw; the job's claim was ended anyway.`,V)}}function r1(){return Bun.env.NODE_ENV==="production"}function t1(){if(!l1)return!1;if(e1())return!0;return process.env.ROOT_DIR!==void 0&&!o1()}function o1(Z=process.env){return(Z.GEMI_QUEUE_CLAIM??"").trim().toLowerCase()==="off"}var Z1=Symbol.for("gemi.queue.worker");function A6(Z=!0){globalThis[Z1]=Z}function e1(){return globalThis[Z1]===!0}function Z3(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 o0($.make(AZ));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 $1=65536,$3=500;class V3{static write(Z,$){return PZ(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(Z0).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 PZ(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>$1)throw RangeError(`Item ${X} of source "${$}" is ${H} bytes as JSON, over the ${$1}-byte limit. Store it elsewhere and keep its id.`);if(Y.push({index:X++,payload:B}),Y.length>=$3)await Z.writeSource($,z,Y),Y=[]}return await Z.writeSource($,z,Y),{id:$,count:X}}function iZ(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)}}
|
|
575
|
-
export{C0 as ue,g0 as ve,
|
|
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 ue,g0 as ve,r0 as we,MZ as xe,e0 as ye,O3 as ze,qZ as Ae,ZZ as Be,p0 as Ce,V1 as De,z3 as Ee,YZ as Fe,GZ as Ge,BZ as He,QZ as Ie,FZ as Je,d0 as Ke,RZ as Le,$0 as Me,o1 as Ne,e1 as Oe,D6 as Pe,Z3 as Qe,Q0 as Re};
|
|
576
590
|
|
|
577
|
-
//# debugId=
|
|
591
|
+
//# debugId=9D05883E6DC62E9D64756E2164756E21
|