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