gemi 0.222.1 → 0.223.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/dist/ai/index.js +1 -1
  2. package/dist/{chunk-ejvjn9tq.js → chunk-fn166jp3.js} +1 -1
  3. package/dist/{chunk-nqjchwdj.js → chunk-ke1q6hfm.js} +1 -1
  4. package/dist/chunk-p1ern8r4.js +577 -0
  5. package/dist/chunk-p1ern8r4.js.map +27 -0
  6. package/dist/{chunk-y8dpexn0.js → chunk-qtczhd81.js} +2 -2
  7. package/dist/{chunk-y8dpexn0.js.map → chunk-qtczhd81.js.map} +1 -1
  8. package/dist/{chunk-t7ppe7gt.js → chunk-qvxs1vjh.js} +1 -1
  9. package/dist/{chunk-dy01vy29.js → chunk-rw45xz3f.js} +3 -3
  10. package/dist/{chunk-dy01vy29.js.map → chunk-rw45xz3f.js.map} +3 -3
  11. package/dist/{chunk-qvspq5tm.js → chunk-sqyf0gey.js} +1 -1
  12. package/dist/console/run.js +1 -1
  13. package/dist/kernel/index.js +1 -1
  14. package/dist/server/index.js +1 -1
  15. package/dist/services/index.d.ts +2 -1
  16. package/dist/services/index.d.ts.map +1 -1
  17. package/dist/services/index.js +1 -1
  18. package/dist/services/queue/DatabaseQueueDriver.d.ts +16 -0
  19. package/dist/services/queue/DatabaseQueueDriver.d.ts.map +1 -1
  20. package/dist/services/queue/DatabaseSlots.d.ts +100 -0
  21. package/dist/services/queue/DatabaseSlots.d.ts.map +1 -0
  22. package/dist/services/queue/Job.d.ts +20 -3
  23. package/dist/services/queue/Job.d.ts.map +1 -1
  24. package/dist/services/queue/MemoryQueueDriver.d.ts +11 -1
  25. package/dist/services/queue/MemoryQueueDriver.d.ts.map +1 -1
  26. package/dist/services/queue/QueueDriver.d.ts +24 -0
  27. package/dist/services/queue/QueueDriver.d.ts.map +1 -1
  28. package/dist/services/queue/QueueManager.d.ts +28 -8
  29. package/dist/services/queue/QueueManager.d.ts.map +1 -1
  30. package/dist/services/queue/slots.d.ts +111 -0
  31. package/dist/services/queue/slots.d.ts.map +1 -0
  32. package/dist/services/queue/work.js +1 -1
  33. package/dist/services/queue/workflow/MemoryWorkflowStore.d.ts +2 -0
  34. package/dist/services/queue/workflow/MemoryWorkflowStore.d.ts.map +1 -1
  35. package/dist/services/queue/workflow/Workflow.d.ts +16 -0
  36. package/dist/services/queue/workflow/Workflow.d.ts.map +1 -1
  37. package/dist/services/queue/workflow/WorkflowRuntime.d.ts +10 -0
  38. package/dist/services/queue/workflow/WorkflowRuntime.d.ts.map +1 -1
  39. package/package.json +1 -1
  40. package/dist/chunk-9kdqdjdf.js +0 -521
  41. package/dist/chunk-9kdqdjdf.js.map +0 -25
  42. /package/dist/{chunk-ejvjn9tq.js.map → chunk-fn166jp3.js.map} +0 -0
  43. /package/dist/{chunk-nqjchwdj.js.map → chunk-ke1q6hfm.js.map} +0 -0
  44. /package/dist/{chunk-t7ppe7gt.js.map → chunk-qvxs1vjh.js.map} +0 -0
  45. /package/dist/{chunk-qvspq5tm.js.map → chunk-sqyf0gey.js.map} +0 -0
@@ -0,0 +1,577 @@
1
+ // @bun
2
+ import{Nk as r,Ok as x0,Qk as eZ,al as d0}from"./chunk-tac25cnj.js";import{cl as oZ}from"./chunk-0k2r6bep.js";import{el as hZ,fl as fZ,gl as EZ,il as o,jl as nZ,ll as O0,ul as v0}from"./chunk-0av1gyns.js";import{Nl as AZ}from"./chunk-zmt5kdpb.js";import{im as tZ,lm as B0}from"./chunk-37209psn.js";import{um as c0}from"./chunk-6r7956dh.js";class C0{table;sql;dialect;connection;busyTimeout;configured;constructor(Z,$={}){let V=$.table??"gemi_locks";if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(V))throw Error(`The lock table name "${V}" is not a plain identifier. Use letters, digits and underscores.`);this.table=V,this.sql=Z.sql,this.dialect=Z.dialect,this.connection=Z.name,this.busyTimeout=$.busyTimeout??1000}async createTable(){await this.configure();for(let Z of B1(this.dialect,this.table))await this.sql.unsafe(Z)}async acquire(Z,$,V){await this.configure();let z=this.sql,X=this.now(z);if(await this.seed(z,Z),this.mysql){let G=await z`
3
+ UPDATE ${this.name(z)}
4
+ SET owner = ${$}, token = token + 1, expires_at = ${X} + ${this.ms(z,V)},
5
+ updated_at = ${X}
6
+ WHERE name = ${Z} AND expires_at <= ${X}
7
+ `;if(Y0(G)===0)return null;let[B]=await z`
8
+ SELECT token FROM ${this.name(z)} WHERE name = ${Z} AND owner = ${$}
9
+ `;return B?Number(B.token):null}let Y=await z`
10
+ UPDATE ${this.name(z)}
11
+ SET owner = ${$}, token = token + 1, expires_at = ${X} + ${this.ms(z,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,$,V,z){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,z)}, updated_at = ${Y}
18
+ WHERE name = ${Z} AND owner = ${$} AND token = ${V} AND expires_at > ${Y}
19
+ `;if(Y0(G)>0)return!0;return this.mysql?this.held(Z,$,V):!1}async release(Z,$,V){await this.configure();let z=this.sql,X=this.now(z),Y=V===void 0?z`1 = 1`:z`token = ${V}`,G=await z`
20
+ UPDATE ${this.name(z)}
21
+ SET owner = '', expires_at = 0, updated_at = ${X}
22
+ WHERE name = ${Z} AND owner = ${$} AND ${Y} AND expires_at > ${X}
23
+ `;return Y0(G)>0}async holder(Z){await this.configure();let $=this.sql,[V]=await $`
24
+ SELECT owner, token FROM ${this.name($)}
25
+ WHERE name = ${Z} AND expires_at > ${this.now($)}
26
+ `;return V?{owner:String(V.owner),token:Number(V.token)}:null}async held(Z,$,V){await this.configure();let z=this.sql;return(await z`
27
+ SELECT 1 AS held FROM ${this.name(z)}
28
+ WHERE name = ${Z} AND owner = ${$} AND token = ${V} AND expires_at > ${this.now(z)}
29
+ `).length>0}async advance(Z,$){await this.configure();let V=this.sql;await this.seed(V,Z);let z=await V`
30
+ UPDATE ${this.name(V)}
31
+ SET token = ${this.int(V,$)}, updated_at = ${this.now(V)}
32
+ WHERE name = ${Z} AND token < ${this.int(V,$)}
33
+ `;return Y0(z)>0}async fence(Z,$,V,z){await this.configure();let X=async(G)=>{let B=this.now(G),H;if(this.dialect==="sqlite"){let Q=await G`
34
+ UPDATE ${this.name(G)} SET updated_at = ${B}
35
+ WHERE name = ${Z} AND owner = ${$} AND token = ${V} AND expires_at > ${B}
36
+ `;H=Y0(Q)>0}else H=(await G`
37
+ SELECT 1 AS held FROM ${this.name(G)}
38
+ WHERE name = ${Z} AND owner = ${$} AND token = ${V} AND expires_at > ${B}
39
+ FOR UPDATE
40
+ `).length>0;if(!H)throw new x0(Z,V);return z()},Y=this.connection;if(Y===void 0)return await this.sql.begin((G)=>X(G));return v0(this.sql,(G)=>EZ(Y,()=>X(G)),{connection:Y})}async hit(Z,$,V){await this.configure();let z=this.sql,X=this.now(z);await this.seed(z,Z);let Y=this.ms(z,Math.max(1,V)),G=await z`
41
+ UPDATE ${this.name(z)}
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(z,$)})
46
+ `,B=Y0(G)>0,[H]=await z`
47
+ SELECT expires_at - ${X} AS reset FROM ${this.name(z)} WHERE name = ${Z}
48
+ `;return{allowed:B,resetInMs:Math.max(0,Number(H?.reset??0))}}async refund(Z){await this.configure();let $=this.sql,V=this.now($);await $`
49
+ UPDATE ${this.name($)} SET token = token - 1, updated_at = ${V}
50
+ WHERE name = ${Z} AND token > 0 AND expires_at > ${V}
51
+ `}async prune(Z){await this.configure();let $=this.sql,V=this.now($),z=await $`
52
+ DELETE FROM ${this.name($)}
53
+ WHERE expires_at <= ${V} AND updated_at <= ${V} - ${this.ms($,Z)}
54
+ `;return Y0(z)}async seed(Z,$){let V=this.now(Z);if(this.mysql){await Z`
55
+ INSERT IGNORE INTO ${this.name(Z)} (name, owner, token, expires_at, updated_at)
56
+ VALUES (${$}, '', 0, 0, ${V})
57
+ `;return}await Z`
58
+ INSERT INTO ${this.name(Z)} (name, owner, token, expires_at, updated_at)
59
+ VALUES (${$}, '', 0, 0, ${V})
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,$){return this.int(Z,Math.max(0,Math.round($)))}int(Z,$){let V=Math.round($);return this.mysql?Z`CAST(${V} AS SIGNED)`:Z`CAST(${V} AS BIGINT)`}}function Y0(Z){let $=Z;return Math.max(Number($.count??0),Number($.affectedRows??0))}function B1(Z,$){if(Z==="mysql"||Z==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${$}\` (
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 V=Z==="sqlite"?'"name" TEXT NOT NULL PRIMARY KEY,':'"name" TEXT NOT NULL,',z=Z==="sqlite"?"":`,
70
+
71
+ CONSTRAINT "${$}_pkey" PRIMARY KEY ("name")`;return[`CREATE TABLE IF NOT EXISTS "${$}" (
72
+ ${V}
73
+ "owner" TEXT NOT NULL,
74
+ "token" BIGINT NOT NULL DEFAULT 0,
75
+ "expires_at" BIGINT NOT NULL,
76
+ "updated_at" BIGINT NOT NULL${z}
77
+ )`]}class g0{entries=new Map;counters=new Map;async acquire(Z,$,V){let z=Date.now(),X=this.entries.get(Z);if(X&&(X.expiresAt>z||X.fences>0))return null;let Y=(X?.token??0)+1;return this.entries.set(Z,{owner:$,token:Y,expiresAt:z+Math.max(0,V),fences:0}),Y}async extend(Z,$,V,z){let X=this.current(Z,$,V);if(!X)return!1;return X.expiresAt=Date.now()+Math.max(0,z),!0}async release(Z,$,V){let z=this.current(Z,$,V);if(!z)return!1;return z.owner="",z.expiresAt=0,!0}async holder(Z){let $=this.entries.get(Z);if(!$||$.expiresAt<=Date.now())return null;return{owner:$.owner,token:$.token}}async held(Z,$,V){return this.current(Z,$,V)!==void 0}async advance(Z,$){if((this.counters.get(Z)??-1/0)>=$)return!1;return this.counters.set(Z,$),!0}async fence(Z,$,V,z){let X=this.current(Z,$,V);if(!X)throw new x0(Z,V);X.fences++;try{return await z()}finally{X.fences--}}windows=new Map;async hit(Z,$,V){let z=Date.now(),X=this.windows.get(Z);if(!X||X.endsAt<=z)X={count:0,endsAt:z+Math.max(1,V)},this.windows.set(Z,X);if(X.count>=$)return{allowed:!1,resetInMs:X.endsAt-z};return X.count++,{allowed:!0,resetInMs:X.endsAt-z}}async refund(Z){let $=this.windows.get(Z);if($&&$.endsAt>Date.now()&&$.count>0)$.count--}current(Z,$,V){let z=this.entries.get(Z);if(!z||z.owner!==$||z.expiresAt<=Date.now())return;if(V!==void 0&&z.token!==V)return;return z}}var m="gemi.WorkflowTick",s0=262144;function h0(Z,$){let V=(z)=>z.slice(0,z.lastIndexOf(":"));return V(Z)===V($)}class b extends Error{constructor(Z){super(`The tick running workflow ${Z} lost its hold on it (another tick took it over after its lease ran out), so its writes were refused.`);this.name="WorkflowLeaseLostError"}}var Q1=["completed","failed","cancelled"];class n0{db;table;stepTable;itemTable;sourceTable;constructor(Z,$){this.db=Z;this.table=$.table,this.stepTable=$.stepTable,this.itemTable=$.itemTable,this.sourceTable=$.sourceTable;let V=Z.connection;if(Z.dialect!=="sqlite"&&V!==void 0)this.transaction=(z)=>v0(Z.sql,()=>z(),{connection:V})}transaction;joinsTransaction(){return this.db.transaction()!==void 0}create(Z){let $=this.db.transaction(),V=$?this.insertWorkflow($,Z):this.db.atomically((z)=>this.insertWorkflow(z,Z));if($)O0(V);return V}async insertWorkflow(Z,$){await this.db.configure();let V=this.db.now(Z);await P0(Z`
78
+ INSERT INTO ${this.workflows(Z)}
79
+ (id, name, args, status, progress, retick, created_at, updated_at)
80
+ VALUES
81
+ (${$.id}, ${$.name}, ${$.args}, 'running',
82
+ ${this.db.fraction(Z,0)}, 0, ${V}, ${V})
83
+ `,this.table),await this.db.insertJob(Z,{name:m,args:JSON.stringify([$.id])})}async find(Z,$={}){await this.db.configure();let V=this.db.sql,[z]=await P0(V`SELECT * FROM ${this.workflows(V)} WHERE id = ${Z}`,this.table);if(!z)return null;return{workflow:TZ(z),steps:$.steps===!1?[]:await this.stepsOf(V,Z)}}acquire(Z,$,V){return this.db.atomically(async(z)=>{let X=await this.lock(z,Z);if(!X)return{kind:"missing"};let Y=await this.db.clock(z);if(X.lockedBy!==null&&!h0(X.lockedBy,$)&&(X.lockedUntil??0)>Y)return await z`UPDATE ${this.workflows(z)} SET retick = 1 WHERE id = ${Z}`,{kind:"busy"};let G=Y+Math.max(0,Math.round(V));return await z`
84
+ UPDATE ${this.workflows(z)}
85
+ SET locked_by = ${$}, locked_until = ${this.db.ms(z,G)}, retick = 0
86
+ WHERE id = ${Z}
87
+ `,{kind:"acquired",workflow:{...X,lockedBy:$,lockedUntil:G,retick:!1},steps:await this.stepsOf(z,Z)}})}async renew(Z,$,V){await this.db.configure();let z=this.db.sql,X=await z`
88
+ UPDATE ${this.workflows(z)}
89
+ SET locked_until = ${this.db.now(z)} + ${this.db.ms(z,V)}
90
+ WHERE id = ${Z} AND locked_by = ${$}
91
+ `;return f0(X)>0}update(Z,$,V){let z=async(Y)=>{let G=await this.lock(Y,Z);if(!G)return;if($.owner!==void 0&&G.lockedBy!==$.owner)throw new b(Z);let B=$.key===void 0?null:await this.stepOf(Y,Z,$.key),H=$.allSteps?await this.stepsOf(Y,Z):[],Q=$.items===void 0?[]:await this.itemsOf(Y,Z,$.items,["running","retrying"],-1,null),J=V({workflow:G,step:B,steps:H,items:Q,now:Date.now()});if(J.step){let P=J.step.key===$.key?B!==null:await this.stepOf(Y,Z,J.step.key)!==null;await this.writeStep(Y,J.step,P)}if(J.items)await this.writeItems(Y,Z,J.items);if(J.batch)await this.db.insertBatch(Y,J.batch);for(let P of J.cancelBatches??[])await this.db.cancelBatch(Y,P);let F={...G,...J.workflow},U=J.unlock===!0,D=Y`
92
+ status = ${F.status}, current_step = ${F.currentStep},
93
+ progress = ${this.db.fraction(Y,F.progress)}, result = ${F.result},
94
+ error = ${F.error}, wake_at = ${this.db.timeOrNull(Y,F.wakeAt)},
95
+ updated_at = ${this.db.now(Y)}
96
+ `;if(U)await Y`
97
+ UPDATE ${this.workflows(Y)}
98
+ SET ${D}, locked_by = NULL, locked_until = NULL, retick = 0
99
+ WHERE id = ${Z}
100
+ `;else await Y`UPDATE ${this.workflows(Y)} SET ${D} WHERE id = ${Z}`;let N=(P)=>this.db.insertJob(Y,{name:m,args:JSON.stringify([Z]),delayMs:Math.max(0,Math.round(P))});if(J.tick)await N(J.tick.delayMs);if(U&&G.retick)await N(0);return J.result},X=$.joinTransaction?this.db.transaction():void 0;return X?z(X):this.db.atomically(z)}async listItems(Z,$,V){return await this.db.configure(),this.itemsOf(this.db.sql,Z,$,V.statuses,V.after??-1,V.limit)}async prune(Z){let $=await this.db.atomically(async(V)=>{let z=this.endedClause(V),X=V`${this.db.now(V)} - ${this.db.ms(V,Z)}`;await V`
101
+ DELETE FROM ${this.steps(V)}
102
+ WHERE workflow_id IN (
103
+ SELECT id FROM ${this.workflows(V)} WHERE ${z} AND updated_at <= ${X}
104
+ )
105
+ `;let Y=await V`
106
+ DELETE FROM ${this.workflows(V)} WHERE ${z} AND updated_at <= ${X}
107
+ `;return f0(Y)});try{let V=this.db.sql;await V`
108
+ DELETE FROM ${this.items(V)}
109
+ WHERE NOT EXISTS (
110
+ SELECT 1 FROM ${this.workflows(V)} w WHERE w.id = ${this.items(V)}.workflow_id
111
+ )
112
+ `}catch(V){if(!W0(V))throw V}try{let V=this.db.sql;await V`
113
+ DELETE FROM ${this.sources(V)}
114
+ WHERE workflow_id IS NOT NULL AND NOT EXISTS (
115
+ SELECT 1 FROM ${this.workflows(V)} w WHERE w.id = ${this.sources(V)}.workflow_id
116
+ )
117
+ `}catch(V){if(!W0(V))throw V}return $}async writeSource(Z,$,V){if(V.length===0)return;await this.db.configure();let z=this.db.sql;for(let X=0;X<V.length;X+=500){let Y=this.db.now(z),G=V.slice(X,X+500).map((B)=>z`(${Z}, ${B.index}, ${$}, ${B.payload}, ${Y})`);await b0(z`
118
+ INSERT INTO ${this.sources(z)} (source_id, idx, workflow_id, payload, created_at)
119
+ VALUES ${G.reduce((B,H)=>z`${B}, ${H}`)}
120
+ `,this.sourceTable)}}async readSource(Z,$,V){await this.db.configure();let z=this.db.sql;return(await b0(z`
121
+ SELECT idx, payload FROM ${this.sources(z)}
122
+ WHERE source_id = ${Z} AND idx >= ${$} AND idx < ${V}
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 $=this.db.sql,V=await b0($`DELETE FROM ${this.sources($)} WHERE source_id = ${Z}`,this.sourceTable);return f0(V)}async pruneSources(Z){await this.db.configure();let $=this.db.sql,V=await b0($`
125
+ DELETE FROM ${this.sources($)}
126
+ WHERE workflow_id IS NULL
127
+ AND created_at <= ${this.db.now($)} - ${this.db.ms($,Z)}
128
+ `,this.sourceTable);return f0(V)}endedClause(Z){return Z`status IN (${Q1.map(($)=>Z`${$}`).reduce(($,V)=>Z`${$}, ${V}`)})`}async writeItems(Z,$,V){let z=this.db,X=V.step,Y=V.delete??[];for(let B=0;B<Y.length;B+=500){let H=Y.slice(B,B+500).map((Q)=>Z`${Q}`);await y0(Z`
129
+ DELETE FROM ${this.items(Z)}
130
+ WHERE workflow_id = ${$} AND step_key = ${X}
131
+ AND idx IN (${H.reduce((Q,J)=>Z`${Q}, ${J}`)})
132
+ `,this.itemTable)}let G=V.insert??[];for(let B=0;B<G.length;B+=200){let H=z.now(Z),Q=G.slice(B,B+200).map((J)=>Z`(
133
+ ${$}, ${X}, ${J.index}, ${J.key}, ${J.status}, ${J.attempt},
134
+ ${J.error}, ${J.output}, ${z.timeOrNull(Z,J.wakeAt)},
135
+ ${z.timeOrNull(Z,J.startedAt)}, ${z.timeOrNull(Z,J.finishedAt)}, ${H}, ${H}
136
+ )`);await y0(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 ${Q.reduce((J,F)=>Z`${J}, ${F}`)}
141
+ `,this.itemTable)}for(let B of V.update??[])await y0(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 = ${z.timeOrNull(Z,B.wakeAt)},
146
+ started_at = ${z.timeOrNull(Z,B.startedAt)},
147
+ finished_at = ${z.timeOrNull(Z,B.finishedAt)}, updated_at = ${z.now(Z)}
148
+ WHERE workflow_id = ${$} AND step_key = ${X} AND idx = ${B.index}
149
+ `,this.itemTable)}async itemsOf(Z,$,V,z,X,Y){let G=z.map((H)=>Z`${H}`).reduce((H,Q)=>Z`${H}, ${Q}`);return(await y0(Y===null?Z`
150
+ SELECT * FROM ${this.items(Z)}
151
+ WHERE workflow_id = ${$} AND step_key = ${V}
152
+ AND status IN (${G}) AND idx > ${X}
153
+ ORDER BY idx
154
+ `:Z`
155
+ SELECT * FROM ${this.items(Z)}
156
+ WHERE workflow_id = ${$} AND step_key = ${V}
157
+ AND status IN (${G}) AND idx > ${X}
158
+ ORDER BY idx LIMIT ${Y}
159
+ `,this.itemTable)).map(H1)}async writeStep(Z,$,V){let z=this.db,X=this.keyColumn(Z);if(V){await Z`
160
+ UPDATE ${this.steps(Z)}
161
+ SET status = ${$.status}, attempt = ${$.attempt}, output = ${$.output},
162
+ error = ${$.error}, batch_id = ${$.batchId},
163
+ wake_at = ${z.timeOrNull(Z,$.wakeAt)},
164
+ started_at = ${z.timeOrNull(Z,$.startedAt)},
165
+ finished_at = ${z.timeOrNull(Z,$.finishedAt)}, updated_at = ${z.now(Z)}
166
+ WHERE workflow_id = ${$.workflowId} AND ${X} = ${$.key}
167
+ `;return}let Y=z.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
+ (${$.workflowId}, ${$.key}, ${$.status}, ${$.attempt}, ${$.output},
173
+ ${$.error}, ${$.batchId}, ${z.timeOrNull(Z,$.wakeAt)},
174
+ ${z.timeOrNull(Z,$.startedAt)}, ${z.timeOrNull(Z,$.finishedAt)}, ${Y}, ${Y})
175
+ `}async lock(Z,$){let V;if(this.db.dialect==="sqlite")await P0(Z`UPDATE ${this.workflows(Z)} SET updated_at = updated_at WHERE id = ${$}`,this.table),V=await Z`SELECT * FROM ${this.workflows(Z)} WHERE id = ${$}`;else V=await P0(Z`SELECT * FROM ${this.workflows(Z)} WHERE id = ${$} FOR UPDATE`,this.table);return V[0]?TZ(V[0]):void 0}async stepOf(Z,$,V){let[z]=await P0(Z`SELECT * FROM ${this.steps(Z)} WHERE workflow_id = ${$} AND ${this.keyColumn(Z)} = ${V}`,this.stepTable);return z?SZ(z):null}async stepsOf(Z,$){return(await P0(Z`
176
+ SELECT * FROM ${this.steps(Z)} WHERE workflow_id = ${$}
177
+ ORDER BY created_at, ${this.keyColumn(Z)}
178
+ `,this.stepTable)).map(SZ)}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 e(Z){return Z==null?null:Number(Z)}function c(Z){return Z==null?null:String(Z)}function TZ(Z){return{id:String(Z.id),name:String(Z.name),args:String(Z.args),status:String(Z.status),currentStep:c(Z.current_step),progress:Number(Z.progress??0),result:c(Z.result),error:c(Z.error),wakeAt:e(Z.wake_at),lockedBy:c(Z.locked_by),lockedUntil:e(Z.locked_until),retick:Number(Z.retick??0)!==0,createdAt:Number(Z.created_at),updatedAt:Number(Z.updated_at)}}function SZ(Z){return{workflowId:String(Z.workflow_id),key:String(Z.key),status:String(Z.status),attempt:Number(Z.attempt??0),output:c(Z.output),error:c(Z.error),batchId:c(Z.batch_id),wakeAt:e(Z.wake_at),startedAt:e(Z.started_at),finishedAt:e(Z.finished_at),createdAt:Number(Z.created_at),updatedAt:Number(Z.updated_at)}}function H1(Z){return{workflowId:String(Z.workflow_id),step:String(Z.step_key),index:Number(Z.idx),key:c(Z.item_key),status:String(Z.status),attempt:Number(Z.attempt??0),error:c(Z.error),output:c(Z.output),wakeAt:e(Z.wake_at),startedAt:e(Z.started_at),finishedAt:e(Z.finished_at),createdAt:Number(Z.created_at),updatedAt:Number(Z.updated_at)}}function f0(Z){let $=Z;return Math.max(Number($.count??0),Number($.affectedRows??0))}function W0(Z){let $=String(Z?.message??Z);return/does not exist|doesn't exist|unknown column|no such (table|column)|has no column/i.test($)}async function P0(Z,$){try{return await Z}catch(V){if(!W0(V))throw V;throw Error(`Workflows need the "${$}" table, and the database says it is missing. Add the GemiWorkflow and GemiWorkflowStep models from the docs (docs/workflows.md#the-workflow-tables) and migrate, or call the queue driver's createTable().`,{cause:V})}}async function y0(Z,$){try{return await Z}catch(V){if(!W0(V))throw V;throw Error(`step.each needs the "${$}" table, and the database says it is missing. Add the GemiWorkflowItem model from the docs (docs/workflows.md#the-workflow-tables) and migrate, or call the queue driver's createTable().`,{cause:V})}}async function b0(Z,$){try{return await Z}catch(V){if(!W0(V))throw V;throw Error(`Item sources need the "${$}" table, and the database says it is missing. Add the GemiWorkflowSource model from the docs (docs/workflows.md#the-workflow-tables) and migrate, or call the queue driver's createTable().`,{cause:V})}}function IZ(Z,$,V){if(Z==="mysql"||Z==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${$}\` (
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 \`${$}_status_idx\`(\`status\`),
195
+ PRIMARY KEY (\`id\`)
196
+ ) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci`,`CREATE TABLE IF NOT EXISTS \`${V}\` (
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 z=Z==="sqlite";return[`CREATE TABLE IF NOT EXISTS "${$}" (
212
+ "id" TEXT NOT NULL${z?" PRIMARY KEY":""},
213
+ "name" TEXT NOT NULL,
214
+ "args" TEXT NOT NULL,
215
+ "status" TEXT NOT NULL,
216
+ "current_step" TEXT,
217
+ "progress" ${z?"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${z?"":`,
226
+
227
+ CONSTRAINT "${$}_pkey" PRIMARY KEY ("id")`}
228
+ )`,`CREATE TABLE IF NOT EXISTS "${V}" (
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
+ ${z?'PRIMARY KEY ("workflow_id", "key")':`CONSTRAINT "${V}_pkey" PRIMARY KEY ("workflow_id","key")`}
243
+ )`,`CREATE INDEX IF NOT EXISTS "${$}_status_idx" ON "${$}"("status")`]}function MZ(Z,$){if(Z==="mysql"||Z==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${$}\` (
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 "${$}" (
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 "${$}_pkey" PRIMARY KEY ("workflow_id","step_key","idx")`}
275
+ )`]}function jZ(Z,$){if(Z==="mysql"||Z==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${$}\` (
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 \`${$}_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 "${$}" (
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 "${$}_pkey" PRIMARY KEY ("source_id","idx")`}
292
+ )`,`CREATE INDEX IF NOT EXISTS "${$}_workflow_id_idx" ON "${$}"("workflow_id")`]}function q0(Z){return{id:Z.id,name:Z.name,total:Z.total,pending:Z.total,succeeded:0,failed:0,cancelled:0,failedJobIds:[],cancelledAt:null,finishedAt:null,createdAt:Z.now,allowFailures:Z.allowFailures,callbacks:Z.callbacks}}function m0(Z,$,V){if(Z.pending<=0)return Z;let z={...Z,pending:Z.pending-1};if($==="succeeded")z.succeeded++;else if($==="cancelled")z.cancelled++;else z.failed++,z.failedJobIds=[...Z.failedJobIds,V];return z}function k0(Z,$){return!$.allowFailures&&$.cancelledAt===null&&$.finishedAt===null&&$.failed>Z.failed}function K0(Z,$,V){let z=Math.min(Math.max(0,V),Z.pending);return{...Z,cancelledAt:Z.cancelledAt??$,pending:Z.pending-z,cancelled:Z.cancelled+z}}function F0(Z,$,V){let z=$,X=[],Y=$.callbacks,G=Z.failed===0&&Z.cancelledAt===null,B=$.failed===0&&$.cancelledAt===null;if(G&&!B&&Y.catch)X.push(Y.catch);if($.pending===0&&$.finishedAt===null){if(z={...$,finishedAt:V},$.cancelledAt===null&&($.failed===0||$.allowFailures)&&Y.then)X.push(Y.then);if(Y.finally)X.push(Y.finally)}let H=G0(z);return{record:z,calls:X.map((Q)=>({name:Q.name,args:JSON.stringify([...Q.args,H])}))}}function G0(Z,$=0){let{allowFailures:V,callbacks:z,...X}=Z,Y=Z.total-Z.pending,G=Z.total===0?1:Math.min(1,Math.max(0,(Y+Math.max(0,$))/Z.total));return{...X,failedJobIds:[...Z.failedJobIds],progress:G}}function i(Z){if(typeof Z!=="number"||!Number.isFinite(Z))throw TypeError(`A job's progress is a number from 0 to 1; got ${String(Z)}.`);return Math.min(1,Math.max(0,Z))}var{SQL:J1}=globalThis.Bun;class r0{db;statements;own;ownTail=Promise.resolve();constructor(Z,$){this.db=Z;this.statements=F1(Z.dialect,$)}async acquire(Z){return this.step(async($)=>{let V=[...new Set(Z.slots.map((Y)=>Y.key))].sort();for(let Y of V){let{limit:G}=Z.slots.find((B)=>B.key===Y);await $("lockGate",{key:Y,limit:G})}let[z]=await $("placeOf",{holder:Z.holder}),X=z?.queued_at==null?Number((await $("clock",{}))[0].now):Number(z.queued_at);for(let{key:Y,limit:G}of Z.slots){await this.prune($,Y);let[B]=await $("ticket",{key:Y,holder:Z.holder});if(!B)await $("insertWaiting",{key:Y,holder:Z.holder,job:Z.job.id,workflow:Z.workflowId??null,queued:X});else if(String(B.job_id)!==Z.job.id)await $("pointAt",{key:Y,holder:Z.holder,job:Z.job.id});let H=B?Number(B.queued_at):X,Q=async()=>await this.count($,"countHolders",{key:Y})+await this.count($,"countAhead",{key:Y,queued:H,holder:Z.holder,cap:Math.max(1,G)})<G,J=B?.state==="holding";if(!J&&await Q())J=!0;if(!J)await this.wake($,Y,G,Z.holder),J=await Q();if(J&&B?.state!=="holding")await $("hold",{key:Y,holder:Z.holder});if(J){await this.wake($,Y,G,Z.holder);continue}let U=await this.count($,"countAhead",{key:Y,queued:H,holder:Z.holder,cap:Math.max(1,G)})<Math.max(1,G)?Z.recheckMs.near:Z.recheckMs.far;return await $("park",{id:Z.job.id,attempt:Z.job.attempt,ms:Math.max(0,Math.round(U))}),!1}return!0})}async release(Z){await this.step(async($)=>{let V=await $("keysOf",{holder:Z}),z=[...new Set(V.map((X)=>String(X.slot_key)))].sort();for(let X of z)await $("touchGate",{key:X});for(let X of z){await $("deleteTicket",{key:X,holder:Z}),await this.prune($,X);let[Y]=await $("gate",{key:X});await this.wake($,X,Number(Y?.slot_limit??0),Z)}})}async prune(Z,$){if(await Z("pruneJobHolders",{key:$}),(await Z("hasWorkflowHolders",{key:$})).length>0)await Z("pruneWorkflowHolders",{key:$})}async wake(Z,$,V,z){let X=V-await this.count(Z,"countHolders",{key:$});while(X>0){let Y=await Z("nextWaiters",{key:$,except:z,n:X+8});if(Y.length===0)return;let G=0;for(let B of Y){if(X<=0)return;let H=String(B.holder),Q=B.job_id==null?null:String(B.job_id),J=B.workflow_id==null?null:String(B.workflow_id);if(J!==null){let[D]=await Z("workflowStatus",{id:J});if(!D||K1.includes(String(D.status))){await Z("deleteTicket",{key:$,holder:H}),G++;continue}}if(Q!==null)await Z("wakeJob",{id:Q});let[F]=Q===null?[]:await Z("jobStatus",{id:Q});if(!(F!==void 0&&P1.includes(String(F.status)))){if(J===null){await Z("deleteTicket",{key:$,holder:H}),G++;continue}let D=await this.db.insertJob(Z.q,{name:m,args:JSON.stringify([J])});await Z("pointAt",{key:$,holder:H,job:D})}X--}if(G===0)return}}async count(Z,$,V){let[z]=await Z($,V);return Number(z?.n??0)}async step(Z){await this.db.configure();for(let $=0;;$++)try{return await this.transaction((V)=>Z(this.runner(V)))}catch(V){if($>=4||!N1(V))throw R1(V,this.statements.table);await new Promise((z)=>setTimeout(z,10+Math.random()*40*($+1)))}}async transaction(Z){let $=this.ownClient();if($){let X=this.ownTail.then(()=>$.begin((Y)=>Z(Y)));return this.ownTail=X.catch(()=>{}),X}if(this.db.dialect!=="mysql"&&this.db.dialect!=="mariadb")return this.db.atomically(Z);let V=await this.db.sql.reserve(),[z]=await V`SELECT @@transaction_isolation AS level`;await V`SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED`;try{return await V.begin((X)=>Z(X))}finally{let X=z?.level?.replaceAll("-"," ");if(X&&/^[A-Z ]+$/.test(X))await V.unsafe(`SET SESSION TRANSACTION ISOLATION LEVEL ${X}`);V.release()}}ownClient(){if(this.own)return this.own;if(this.db.dialect!=="postgres"||!U1())return;let Z=this.db.sql.options;if(Z?.adapter!=="postgres")return;return this.own=new J1({...Z,max:1,idleTimeout:5}),this.own}runner(Z){let $=async(V,z)=>{let[X,Y]=this.statements.compile(V,z);return await Z.unsafe(X,Y)};return $.q=Z,$}}var P1=["pending","claimed"],K1=["completed","failed","cancelled","paused"];function vZ(Z,$){if(Z==="mysql"||Z==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${$}\` (
293
+ \`slot_key\` VARCHAR(191) NOT NULL,
294
+ \`holder\` VARCHAR(191) NOT NULL,
295
+ \`job_id\` VARCHAR(191) NULL,
296
+ \`workflow_id\` VARCHAR(191) NULL,
297
+ \`state\` VARCHAR(191) NOT NULL,
298
+ \`slot_limit\` INTEGER NOT NULL DEFAULT 0,
299
+ \`queued_at\` BIGINT NOT NULL,
300
+ \`updated_at\` BIGINT NOT NULL,
301
+
302
+ INDEX \`${$}_slot_key_state_queued_at_holder_idx\`(\`slot_key\`, \`state\`, \`queued_at\`, \`holder\`),
303
+ INDEX \`${$}_holder_idx\`(\`holder\`),
304
+ PRIMARY KEY (\`slot_key\`, \`holder\`)
305
+ ) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci`];let V=`,
306
+
307
+ CONSTRAINT "${$}_pkey" PRIMARY KEY ("slot_key", "holder")`;return[`CREATE TABLE IF NOT EXISTS "${$}" (
308
+ "slot_key" TEXT NOT NULL,
309
+ "holder" TEXT NOT NULL,
310
+ "job_id" TEXT,
311
+ "workflow_id" TEXT,
312
+ "state" TEXT NOT NULL,
313
+ "slot_limit" INTEGER NOT NULL DEFAULT 0,
314
+ "queued_at" BIGINT NOT NULL,
315
+ "updated_at" BIGINT NOT NULL${V}
316
+ )`,`CREATE INDEX IF NOT EXISTS "${$}_slot_key_state_queued_at_holder_idx" ON "${$}"("slot_key", "state", "queued_at", "holder")`,`CREATE INDEX IF NOT EXISTS "${$}_holder_idx" ON "${$}"("holder")`]}function F1(Z,$){let V=Z==="mysql"||Z==="mariadb",z=(U)=>V?`\`${U}\``:`"${U}"`,X=z($.slots),Y=z($.jobs),G=z($.workflows),B=Z==="postgres"?"floor(extract(epoch from statement_timestamp()) * 1000)::bigint":V?"(TIMESTAMPDIFF(MICROSECOND, '1970-01-01 00:00:00', UTC_TIMESTAMP(6)) DIV 1000)":"CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER)",H=(U)=>V?`CAST({${U}} AS SIGNED)`:`CAST({${U}} AS BIGINT)`,Q=(U)=>V?`ON DUPLICATE KEY UPDATE ${U.replace(/excluded\.(\w+)/g,"VALUES($1)")}`:`ON CONFLICT (slot_key, holder) DO UPDATE SET ${U}`,J={clock:`SELECT ${B} AS now`,lockGate:`INSERT INTO ${X} (slot_key, holder, state, slot_limit, queued_at, updated_at)
317
+ VALUES ({key}, '', 'gate', ${H("limit")}, ${B}, ${B})
318
+ ${Q("slot_limit = excluded.slot_limit, updated_at = excluded.updated_at")}`,touchGate:`INSERT INTO ${X} (slot_key, holder, state, slot_limit, queued_at, updated_at)
319
+ VALUES ({key}, '', 'gate', 0, ${B}, ${B})
320
+ ${Q("updated_at = excluded.updated_at")}`,gate:`SELECT slot_limit FROM ${X} WHERE slot_key = {key} AND holder = ''`,placeOf:`SELECT MIN(queued_at) AS queued_at FROM ${X} WHERE holder = {holder}`,ticket:`SELECT state, queued_at, job_id FROM ${X} WHERE slot_key = {key} AND holder = {holder}`,insertWaiting:`INSERT INTO ${X}
321
+ (slot_key, holder, job_id, workflow_id, state, slot_limit, queued_at, updated_at)
322
+ VALUES ({key}, {holder}, {job}, {workflow}, 'waiting', 0, ${H("queued")}, ${B})`,pointAt:`UPDATE ${X} SET job_id = {job}, updated_at = ${B}
323
+ WHERE slot_key = {key} AND holder = {holder}`,hold:`UPDATE ${X} SET state = 'holding', updated_at = ${B}
324
+ WHERE slot_key = {key} AND holder = {holder}`,deleteTicket:`DELETE FROM ${X} WHERE slot_key = {key} AND holder = {holder}`,keysOf:`SELECT slot_key FROM ${X} WHERE holder = {holder}`,countHolders:`SELECT COUNT(*) AS n FROM ${X} WHERE slot_key = {key} AND state = 'holding'`,countAhead:`SELECT COUNT(*) AS n FROM (
325
+ SELECT holder FROM ${X}
326
+ WHERE slot_key = {key} AND state = 'waiting'
327
+ AND (queued_at < ${H("queued")} OR (queued_at = ${H("queued")} AND holder < {holder}))
328
+ LIMIT {cap}
329
+ ) ahead`,nextWaiters:`SELECT holder, job_id, workflow_id FROM ${X}
330
+ WHERE slot_key = {key} AND state = 'waiting' AND holder <> {except}
331
+ ORDER BY queued_at, holder
332
+ LIMIT {n}`,pruneJobHolders:`DELETE FROM ${X}
333
+ WHERE slot_key = {key} AND state = 'holding' AND workflow_id IS NULL
334
+ AND NOT EXISTS (
335
+ SELECT 1 FROM ${Y} WHERE ${Y}.id = ${X}.holder AND ${Y}.status IN ('pending', 'claimed')
336
+ )`,hasWorkflowHolders:`SELECT holder FROM ${X}
337
+ WHERE slot_key = {key} AND state = 'holding' AND workflow_id IS NOT NULL
338
+ LIMIT 1`,pruneWorkflowHolders:`DELETE FROM ${X}
339
+ WHERE slot_key = {key} AND state = 'holding' AND workflow_id IS NOT NULL
340
+ AND NOT EXISTS (
341
+ SELECT 1 FROM ${G}
342
+ WHERE ${G}.id = ${X}.workflow_id
343
+ AND ${G}.status NOT IN ('completed', 'failed', 'cancelled', 'paused')
344
+ )`,wakeJob:`UPDATE ${Y} SET available_at = ${B}, updated_at = ${B}
345
+ WHERE id = {id} AND status = 'pending' AND available_at > ${B}`,jobStatus:`SELECT status FROM ${Y} WHERE id = {id}`,workflowStatus:`SELECT status FROM ${G} WHERE id = {id}`,park:`UPDATE ${Y}
346
+ SET status = 'pending', attempts = attempts - 1, available_at = ${B} + ${H("ms")},
347
+ lease_expires_at = NULL, updated_at = ${B}
348
+ WHERE id = {id} AND status = 'claimed' AND attempts = ${H("attempt")}`},F=new Map;return{table:$.slots,texts:J,compile(U,D){let N=F.get(U);if(!N){let P=[];N={text:J[U].replace(/\{([a-z]+)\}/g,(A,T)=>{if(Z==="postgres"){let _=P.indexOf(T);if(_===-1)_=P.push(T)-1;return`$${_+1}`}return P.push(T),"?"}),names:P},F.set(U,N)}return[N.text,N.names.map((P)=>{if(!(P in D))throw Error(`The slot statement ${U} needs {${P}}.`);return D[P]})]}}}function U1(){let[Z=0,$=0]=Bun.version.split(".").map(Number);return Z<1||Z===1&&$<4}function N1(Z){let $=Z;return $?.errno===1213||$?.code==="40P01"||/deadlock|try restarting transaction/i.test(String($?.message??""))}function R1(Z,$){let V=String(Z?.message??Z);if(!/does not exist|doesn't exist|no such table/i.test(V)||!V.includes($))return Z;return Error(`Concurrency limits on the database driver need the "${$}" table, and the database says it is missing. Add the GemiJobSlot model from the docs (docs/jobs-and-queues.md#concurrency-limits--concurrency) and migrate, or call the driver's createTable().`,{cause:Z})}var xZ=200,A1="Its batch was cancelled before it ran.";class o0{table;batchTable;workflowTable;workflowStepTable;workflowItemTable;workflowSourceTable;slotTable;workflows;slotLines;sql;dialect;connection;busyTimeout;configured;sqliteTail=Promise.resolve();constructor(Z,$={}){let V=$.table??"gemi_jobs",z=$.batchTable??(V==="gemi_jobs"?"gemi_job_batches":`${V}_batches`),X=V==="gemi_jobs",Y=$.workflowTable??(X?"gemi_workflows":`${V}_workflows`),G=$.workflowStepTable??(X?"gemi_workflow_steps":`${V}_workflow_steps`),B=$.workflowItemTable??(X?"gemi_workflow_items":`${V}_workflow_items`),H=$.workflowSourceTable??(X?"gemi_workflow_sources":`${V}_workflow_sources`),Q=$.slotTable??(X?"gemi_job_slots":`${V}_slots`);for(let F of[V,Q,z,Y,G,B,H])if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(F))throw Error(`The queue table name "${F}" is not a plain identifier. Use letters, digits and underscores.`);let J=$.busyTimeout??1000;if(!Number.isInteger(J)||J<0)throw Error(`The queue's busyTimeout must be a whole number of milliseconds, 0 or more; got ${J}.`);this.table=V,this.batchTable=z,this.workflowTable=Y,this.workflowStepTable=G,this.workflowItemTable=B,this.workflowSourceTable=H,this.slotTable=Q,this.sql=Z.sql,this.dialect=Z.dialect,this.connection=Z.name,this.busyTimeout=J}configure(){if(this.dialect!=="sqlite"||this.busyTimeout===0)return Promise.resolve();return this.configured??=(async()=>{let[Z]=await this.sql.unsafe("PRAGMA busy_timeout");if(Number(Z?.timeout??0)!==0)return;await this.sql.unsafe(`PRAGMA busy_timeout = ${this.busyTimeout}`)})().catch((Z)=>{throw this.configured=void 0,Z}),this.configured}async createTable(){await this.configure();let[Z,...$]=D1(this.dialect,this.table);if(await this.sql.unsafe(Z),!await this.hasBatchColumns())for(let V of _1(this.dialect,this.table))await this.sql.unsafe(V);for(let V of $)await this.sql.unsafe(V);for(let V of L1(this.dialect,this.batchTable))await this.sql.unsafe(V);for(let V of IZ(this.dialect,this.workflowTable,this.workflowStepTable))await this.sql.unsafe(V);for(let V of MZ(this.dialect,this.workflowItemTable))await this.sql.unsafe(V);for(let V of jZ(this.dialect,this.workflowSourceTable))await this.sql.unsafe(V);for(let V of vZ(this.dialect,this.slotTable))await this.sql.unsafe(V)}async hasBatchColumns(){try{return await this.sql.unsafe(`SELECT batch_id, progress FROM ${this.quoted(this.table)} WHERE 1 = 0`),!0}catch(Z){if(yZ(Z))return!1;throw Z}}enqueue(Z){let $=this.transaction(),V=this.insert($??this.sql,Z);if($)O0(V);return V}async insert(Z,{name:$,args:V,delayMs:z=0,id:X=Bun.randomUUIDv7()}){await this.configure();let Y=this.now(Z);return await Z`
349
+ INSERT INTO ${this.name(Z)}
350
+ (id, name, payload, status, attempts, available_at, created_at, updated_at)
351
+ VALUES
352
+ (${X}, ${$}, ${V}, 'pending', 0, ${Y} + ${this.ms(Z,z)}, ${Y}, ${Y})
353
+ `,X}lockStore(){return new C0({sql:this.sql,dialect:this.dialect,name:this.connection},{busyTimeout:this.busyTimeout})}joinsTransaction(){return this.transaction()!==void 0}transaction(){if(this.dialect==="sqlite"||this.connection===void 0)return;let Z=hZ();if(Z===void 0||fZ()!==this.connection)return;return Z}async claim(Z,$){let V=Math.max(0,Math.floor(Z));if(V===0)return[];return await this.configure(),(this.dialect==="mysql"||this.dialect==="mariadb"?await this.claimLocking(V,$):await this.claimUpdating(V,$)).map((X)=>({order:Number(X.available_at),job:{id:String(X.id),name:String(X.name),args:String(X.payload),attempt:Number(X.attempts),createdAt:Number(X.created_at),...X.batch_id==null?{}:{batchId:String(X.batch_id)}}})).sort((X,Y)=>X.order-Y.order||(X.job.id<Y.job.id?-1:1)).map(({job:X})=>X)}async complete(Z){if(Z.batchId!==void 0)return this.endBatchJob(Z,"succeeded");await this.configure();let $=this.sql;await $`
354
+ DELETE FROM ${this.name($)}
355
+ WHERE id = ${Z.id} AND status = 'claimed' AND attempts = ${Z.attempt}
356
+ `}async fail(Z,$){if(Z.batchId!==void 0)return this.endBatchJob(Z,"failed",$);await this.configure();let V=this.sql,z=this.now(V);if($.retryInMs===null){await V`
357
+ UPDATE ${this.name(V)}
358
+ SET status = 'dead', lease_expires_at = NULL, last_error = ${$.error},
359
+ updated_at = ${z}
360
+ WHERE id = ${Z.id} AND status = 'claimed' AND attempts = ${Z.attempt}
361
+ `;return}await V`
362
+ UPDATE ${this.name(V)}
363
+ SET status = 'pending', available_at = ${z} + ${this.ms(V,$.retryInMs)},
364
+ lease_expires_at = NULL, last_error = ${$.error}, updated_at = ${z}
365
+ WHERE id = ${Z.id} AND status = 'claimed' AND attempts = ${Z.attempt}
366
+ `}async release(Z,$){let V=this.sql,z=this.now(V);await V`
367
+ UPDATE ${this.name(V)}
368
+ SET status = 'pending', attempts = attempts - 1,
369
+ available_at = ${z} + ${this.ms(V,$.retryInMs)},
370
+ lease_expires_at = NULL, updated_at = ${z}
371
+ WHERE id = ${Z.id} AND status = 'claimed' AND attempts = ${Z.attempt}
372
+ `}async heartbeat(Z,$){await this.configure();let V=this.sql;await Promise.all(Z.map((z)=>{let X=this.now(V);return V`
373
+ UPDATE ${this.name(V)}
374
+ SET lease_expires_at = ${X} + ${this.ms(V,$.visibilityTimeoutMs)},
375
+ updated_at = ${X}
376
+ WHERE id = ${z.id} AND status = 'claimed' AND attempts = ${z.attempt}
377
+ `}))}async retryDead(Z){await this.configure();let $=this.sql,[V]=await $`
378
+ SELECT * FROM ${this.name($)} WHERE id = ${Z} AND status = 'dead'
379
+ `;if(!V||V.batch_id!=null)return!1;let z=this.now($),X=await $`
380
+ UPDATE ${this.name($)}
381
+ SET status = 'pending', attempts = 0, available_at = ${z}, lease_expires_at = NULL,
382
+ updated_at = ${z}
383
+ WHERE id = ${Z} AND status = 'dead'
384
+ `;return U0(X)>0}async prune(Z){await this.configure();let $=this.sql,V=await $`
385
+ DELETE FROM ${this.name($)}
386
+ WHERE status = 'dead' AND updated_at <= ${this.now($)} - ${this.ms($,Z)}
387
+ `;return U0(V)}enqueueBatch(Z){let $=this.transaction(),V=$?this.insertBatch($,Z):this.atomically((z)=>this.insertBatch(z,Z));if($)O0(V);return V}async insertBatch(Z,$){await this.configure();let V=await this.clock(Z),z=q0({...$,total:$.args.length,now:V}),{record:X,calls:Y}=F0(z,z,V);await t0(Z`
388
+ INSERT INTO ${this.batches(Z)}
389
+ (id, name, total, pending, succeeded, failed, cancelled, failed_job_ids, options,
390
+ cancelled_at, finished_at, created_at, updated_at)
391
+ VALUES
392
+ (${X.id}, ${X.name}, ${X.total}, ${X.pending}, 0, 0, 0,
393
+ '[]', ${C1(X)}, NULL, ${this.timeOrNull(Z,X.finishedAt)},
394
+ ${this.ms(Z,V)}, ${this.ms(Z,V)})
395
+ `,this.batchTable);let G=this.ms(Z,V);for(let B=0;B<$.args.length;B+=xZ){let H=$.args.slice(B,B+xZ).map((Q)=>Z`(${Bun.randomUUIDv7()}, ${$.job}, ${Q}, 'pending', 0, ${G}, ${G}, ${G}, ${$.id}, 0)`).reduce((Q,J)=>Z`${Q}, ${J}`);await t0(Z`
396
+ INSERT INTO ${this.name(Z)}
397
+ (id, name, payload, status, attempts, available_at, created_at, updated_at, batch_id, progress)
398
+ VALUES ${H}
399
+ `,this.table)}for(let B of Y)await this.insert(Z,B)}async findBatch(Z,$={}){await this.configure();let V=this.sql,[z]=await t0(V`SELECT * FROM ${this.batches(V)} WHERE id = ${Z}`,this.batchTable);if(!z)return null;let X=gZ(z);if($.progress===!1||X.pending===0)return G0(X);let[Y]=await V`
400
+ SELECT COALESCE(SUM(progress), 0) AS running FROM ${this.name(V)}
401
+ WHERE batch_id = ${Z} AND status IN ('pending', 'claimed')
402
+ `;return G0(X,Number(Y?.running??0))}async cancelBatch(Z){return this.atomically(($)=>this.cancelBatchOn($,Z))}async cancelBatchOn(Z,$){let V=await this.lockBatch(Z,$);if(!V||V.finishedAt!==null||V.cancelledAt!==null)return!1;let z=await this.clock(Z),X=K0(V,z,await this.cancelWaiting(Z,$));return await this.saveBatch(Z,V,X,z),!0}workflowStore(){return this.workflows??=new n0({sql:this.sql,dialect:this.dialect,connection:this.connection,configure:()=>this.configure(),atomically:(Z)=>this.atomically(Z),transaction:()=>this.transaction(),now:(Z)=>this.now(Z),ms:(Z,$)=>this.ms(Z,$),timeOrNull:(Z,$)=>this.timeOrNull(Z,$),fraction:(Z,$)=>this.fraction(Z,$),clock:(Z)=>this.clock(Z),insertJob:(Z,$)=>this.insert(Z,$),insertBatch:(Z,$)=>this.insertBatch(Z,$),cancelBatch:(Z,$)=>this.cancelBatchOn(Z,$),quoted:(Z)=>this.quoted(Z)},{table:this.workflowTable,stepTable:this.workflowStepTable,itemTable:this.workflowItemTable,sourceTable:this.workflowSourceTable}),this.workflows}acquireSlots(Z){return this.slots().acquire(Z)}releaseSlots(Z){return this.slots().release(Z)}slots(){return this.slotLines??=new r0({sql:this.sql,dialect:this.dialect,configure:()=>this.configure(),atomically:(Z)=>this.atomically(Z),insertJob:(Z,$)=>this.insert(Z,$)},{slots:this.slotTable,jobs:this.table,workflows:this.workflowTable}),this.slotLines}async reportProgress(Z,$){let V=i($);await this.configure();let z=this.sql;await z`
403
+ UPDATE ${this.name(z)} SET progress = ${this.fraction(z,V)}
404
+ WHERE id = ${Z.id} AND status = 'claimed' AND attempts = ${Z.attempt}
405
+ `}async pruneBatches(Z){await this.configure();let $=this.sql,V=await $`
406
+ DELETE FROM ${this.batches($)}
407
+ WHERE finished_at IS NOT NULL AND finished_at <= ${this.now($)} - ${this.ms($,Z)}
408
+ `;return U0(V)}endBatchJob(Z,$,V){let z=Z.batchId;return this.atomically(async(X)=>{let Y=await this.lockBatch(X,z),G=X`id = ${Z.id} AND status = 'claimed' AND attempts = ${Z.attempt}`,B=this.now(X);if($==="succeeded"){let J=await X`DELETE FROM ${this.name(X)} WHERE ${G}`;if(U0(J)===0||!Y)return;return this.count(X,Y,"succeeded",Z.id)}let H=V.cancelled===!0||V.retryInMs!==null&&Y!==void 0&&Y.cancelledAt!==null;if(V.retryInMs!==null&&!H){await X`
409
+ UPDATE ${this.name(X)}
410
+ SET status = 'pending', available_at = ${B} + ${this.ms(X,V.retryInMs)},
411
+ lease_expires_at = NULL, last_error = ${V.error}, progress = 0,
412
+ updated_at = ${B}
413
+ WHERE ${G}
414
+ `;return}let Q=await X`
415
+ UPDATE ${this.name(X)}
416
+ SET status = 'dead', lease_expires_at = NULL, last_error = ${V.error},
417
+ updated_at = ${B}
418
+ WHERE ${G}
419
+ `;if(U0(Q)===0||!Y)return;return this.count(X,Y,H?"cancelled":"failed",Z.id)})}async count(Z,$,V,z){let X=await this.clock(Z),Y=m0($,V,z);if(k0($,Y))Y=K0(Y,X,await this.cancelWaiting(Z,$.id));await this.saveBatch(Z,$,Y,X)}async cancelWaiting(Z,$){let V=this.now(Z),z=await Z`
420
+ UPDATE ${this.name(Z)}
421
+ SET status = 'dead', last_error = ${A1}, updated_at = ${V}
422
+ WHERE batch_id = ${$} AND status = 'pending'
423
+ `;return U0(z)}async saveBatch(Z,$,V,z){let{record:X,calls:Y}=F0($,V,z);await Z`
424
+ UPDATE ${this.batches(Z)}
425
+ SET pending = ${X.pending}, succeeded = ${X.succeeded}, failed = ${X.failed},
426
+ cancelled = ${X.cancelled}, failed_job_ids = ${JSON.stringify(X.failedJobIds)},
427
+ cancelled_at = ${this.timeOrNull(Z,X.cancelledAt)},
428
+ finished_at = ${this.timeOrNull(Z,X.finishedAt)}, updated_at = ${this.ms(Z,z)}
429
+ WHERE id = ${X.id}
430
+ `;for(let G of Y)await this.insert(Z,G)}async lockBatch(Z,$){let V;if(this.dialect==="sqlite")await Z`UPDATE ${this.batches(Z)} SET updated_at = updated_at WHERE id = ${$}`,V=await Z`SELECT * FROM ${this.batches(Z)} WHERE id = ${$}`;else V=await Z`SELECT * FROM ${this.batches(Z)} WHERE id = ${$} FOR UPDATE`;return V[0]?gZ(V[0]):void 0}atomically(Z){let $=async()=>{await this.configure();for(let z=0;;z++)try{return await this.sql.begin((X)=>Z(X))}catch(X){if(this.dialect!=="sqlite"||z>=50||!/within a transaction/i.test(String(X?.message??X)))throw X;await new Promise((Y)=>setTimeout(Y,20))}};if(this.dialect!=="sqlite")return $();let V=this.sqliteTail.then($,$);return this.sqliteTail=V.catch(()=>{}),V}async clock(Z){let[$]=await Z`SELECT ${this.now(Z)} AS now`;return Number($.now)}timeOrNull(Z,$){return $===null?Z`NULL`:this.ms(Z,$)}fraction(Z,$){return this.dialect==="postgres"?Z`CAST(${$} AS DOUBLE PRECISION)`:Z`${$}`}async claimUpdating(Z,$){let V=this.sql,z=this.now(V),X=this.ms(V,$.visibilityTimeoutMs),Y=this.name(V);if(this.dialect==="postgres")return await V`
431
+ WITH next AS (
432
+ SELECT id FROM ${Y}
433
+ WHERE ${this.claimable(V,$)}
434
+ ORDER BY available_at, id
435
+ LIMIT ${Z}
436
+ FOR UPDATE SKIP LOCKED
437
+ )
438
+ UPDATE ${Y} AS job
439
+ SET status = 'claimed', attempts = job.attempts + 1, claimed_at = ${z},
440
+ lease_expires_at = ${z} + ${X}, updated_at = ${z}
441
+ FROM next
442
+ WHERE job.id = next.id
443
+ RETURNING job.*
444
+ `;return await V`
445
+ UPDATE ${Y}
446
+ SET status = 'claimed', attempts = attempts + 1, claimed_at = ${z},
447
+ lease_expires_at = ${z} + ${X}, updated_at = ${z}
448
+ WHERE id IN (
449
+ SELECT id FROM ${Y}
450
+ WHERE ${this.claimable(V,$)}
451
+ ORDER BY available_at, id
452
+ LIMIT ${Z}
453
+ )
454
+ RETURNING *
455
+ `}async claimLocking(Z,$){let V=await this.sql.reserve(),[z]=await V`
456
+ SELECT @@transaction_isolation AS level
457
+ `;await V`SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED`;try{return await this.claimLockingOn(V,Z,$)}finally{let X=z?.level?.replaceAll("-"," ");if(X&&/^[A-Z ]+$/.test(X))await V.unsafe(`SET SESSION TRANSACTION ISOLATION LEVEL ${X}`);V.release()}}async claimLockingOn(Z,$,V){return await Z.begin(async(z)=>{let X=this.name(z),Y=z.unsafe("*"),G=await z`
458
+ SELECT ${Y} FROM ${X}
459
+ WHERE status = 'pending' AND available_at <= ${this.now(z)}
460
+ AND ${this.runnable(z,V,"available_at")}
461
+ ORDER BY available_at, id
462
+ LIMIT ${$}
463
+ FOR UPDATE SKIP LOCKED
464
+ `;if(G.length<$){let B=await z`
465
+ SELECT ${Y} FROM ${X}
466
+ WHERE status = 'claimed' AND lease_expires_at <= ${this.now(z)}
467
+ AND ${this.runnable(z,V,"lease_expires_at")}
468
+ ORDER BY lease_expires_at, id
469
+ LIMIT ${$-G.length}
470
+ FOR UPDATE SKIP LOCKED
471
+ `;G.push(...B)}for(let B of G){let H=this.now(z);await z`
472
+ UPDATE ${X}
473
+ SET status = 'claimed', attempts = attempts + 1, claimed_at = ${H},
474
+ lease_expires_at = ${H} + ${this.ms(z,V.visibilityTimeoutMs)},
475
+ updated_at = ${H}
476
+ WHERE id = ${B.id}
477
+ `}return G.map((B)=>({...B,attempts:Number(B.attempts)+1}))})}claimable(Z,$){let V=this.now(Z);return Z`(
478
+ (status = 'pending' AND available_at <= ${V}
479
+ AND ${this.runnable(Z,$,"available_at")})
480
+ OR (status = 'claimed' AND lease_expires_at <= ${V}
481
+ AND ${this.runnable(Z,$,"lease_expires_at")})
482
+ )`}runnable(Z,$,V){let z=$.registered;if(!z)return Z`1 = 1`;let X=z.names.length?Z`name IN (${z.names.map((G)=>Z`${G}`).reduce((G,B)=>Z`${G}, ${B}`)})`:Z`1 = 0`;if(!Number.isFinite(z.graceMs))return X;let Y=Z.unsafe(V);return Z`(${X} OR ${Y} <= ${this.now(Z)} - ${this.ms(Z,z.graceMs)})`}name(Z){return Z.unsafe(this.quoted(this.table))}batches(Z){return Z.unsafe(this.quoted(this.batchTable))}quoted(Z){return this.dialect==="mysql"||this.dialect==="mariadb"?`\`${Z}\``:`"${Z}"`}now(Z){switch(this.dialect){case"postgres":return Z`floor(extract(epoch from statement_timestamp()) * 1000)::bigint`;case"mysql":case"mariadb":return Z`(TIMESTAMPDIFF(MICROSECOND, '1970-01-01 00:00:00', UTC_TIMESTAMP(6)) DIV 1000)`;case"sqlite":return Z`CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER)`}}ms(Z,$){let V=Math.max(0,Math.round($));return this.dialect==="mysql"||this.dialect==="mariadb"?Z`CAST(${V} AS SIGNED)`:Z`CAST(${V} AS BIGINT)`}}function U0(Z){let $=Z;return Math.max(Number($.count??0),Number($.affectedRows??0))}function D1(Z,$){if(Z==="mysql"||Z==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${$}\` (
483
+ \`id\` VARCHAR(191) NOT NULL,
484
+ \`name\` VARCHAR(191) NOT NULL,
485
+ \`payload\` LONGTEXT NOT NULL,
486
+ \`status\` VARCHAR(191) NOT NULL,
487
+ \`attempts\` INTEGER NOT NULL DEFAULT 0,
488
+ \`available_at\` BIGINT NOT NULL,
489
+ \`claimed_at\` BIGINT NULL,
490
+ \`lease_expires_at\` BIGINT NULL,
491
+ \`last_error\` LONGTEXT NULL,
492
+ \`created_at\` BIGINT NOT NULL,
493
+ \`updated_at\` BIGINT NOT NULL,
494
+ \`batch_id\` VARCHAR(191) NULL,
495
+ \`progress\` DOUBLE NULL,
496
+
497
+ INDEX \`${$}_status_available_at_idx\`(\`status\`, \`available_at\`),
498
+ INDEX \`${$}_status_lease_expires_at_idx\`(\`status\`, \`lease_expires_at\`),
499
+ INDEX \`${$}_batch_id_idx\`(\`batch_id\`),
500
+ PRIMARY KEY (\`id\`)
501
+ ) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci`];let V=Z==="sqlite"?'"id" TEXT NOT NULL PRIMARY KEY,':'"id" TEXT NOT NULL,',z=Z==="sqlite"?"":`,
502
+
503
+ CONSTRAINT "${$}_pkey" PRIMARY KEY ("id")`;return[`CREATE TABLE IF NOT EXISTS "${$}" (
504
+ ${V}
505
+ "name" TEXT NOT NULL,
506
+ "payload" TEXT NOT NULL,
507
+ "status" TEXT NOT NULL,
508
+ "attempts" INTEGER NOT NULL DEFAULT 0,
509
+ "available_at" BIGINT NOT NULL,
510
+ "claimed_at" BIGINT,
511
+ "lease_expires_at" BIGINT,
512
+ "last_error" TEXT,
513
+ "created_at" BIGINT NOT NULL,
514
+ "updated_at" BIGINT NOT NULL,
515
+ "batch_id" TEXT,
516
+ "progress" ${Z==="sqlite"?"REAL":"DOUBLE PRECISION"}${z}
517
+ )`,`CREATE INDEX IF NOT EXISTS "${$}_status_available_at_idx" ON "${$}"("status", "available_at")`,`CREATE INDEX IF NOT EXISTS "${$}_status_lease_expires_at_idx" ON "${$}"("status", "lease_expires_at")`,`CREATE INDEX IF NOT EXISTS "${$}_batch_id_idx" ON "${$}"("batch_id")`]}function _1(Z,$){if(Z==="mysql"||Z==="mariadb")return[`ALTER TABLE \`${$}\` ADD COLUMN \`batch_id\` VARCHAR(191) NULL,
518
+ ADD COLUMN \`progress\` DOUBLE NULL,
519
+ ADD INDEX \`${$}_batch_id_idx\`(\`batch_id\`)`];let V=Z==="sqlite"?"REAL":"DOUBLE PRECISION";if(Z==="sqlite")return[`ALTER TABLE "${$}" ADD COLUMN "batch_id" TEXT`,`ALTER TABLE "${$}" ADD COLUMN "progress" ${V}`,`CREATE INDEX IF NOT EXISTS "${$}_batch_id_idx" ON "${$}"("batch_id")`];return[`ALTER TABLE "${$}" ADD COLUMN IF NOT EXISTS "batch_id" TEXT,
520
+ ADD COLUMN IF NOT EXISTS "progress" ${V}`,`CREATE INDEX IF NOT EXISTS "${$}_batch_id_idx" ON "${$}"("batch_id")`]}function L1(Z,$){if(Z==="mysql"||Z==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${$}\` (
521
+ \`id\` VARCHAR(191) NOT NULL,
522
+ \`name\` VARCHAR(191) NULL,
523
+ \`total\` INTEGER NOT NULL,
524
+ \`pending\` INTEGER NOT NULL,
525
+ \`succeeded\` INTEGER NOT NULL DEFAULT 0,
526
+ \`failed\` INTEGER NOT NULL DEFAULT 0,
527
+ \`cancelled\` INTEGER NOT NULL DEFAULT 0,
528
+ \`failed_job_ids\` LONGTEXT NOT NULL,
529
+ \`options\` LONGTEXT NOT NULL,
530
+ \`cancelled_at\` BIGINT NULL,
531
+ \`finished_at\` BIGINT NULL,
532
+ \`created_at\` BIGINT NOT NULL,
533
+ \`updated_at\` BIGINT NOT NULL,
534
+
535
+ PRIMARY KEY (\`id\`)
536
+ ) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci`];let V=Z==="sqlite"?'"id" TEXT NOT NULL PRIMARY KEY,':'"id" TEXT NOT NULL,',z=Z==="sqlite"?"":`,
537
+
538
+ CONSTRAINT "${$}_pkey" PRIMARY KEY ("id")`;return[`CREATE TABLE IF NOT EXISTS "${$}" (
539
+ ${V}
540
+ "name" TEXT,
541
+ "total" INTEGER NOT NULL,
542
+ "pending" INTEGER NOT NULL,
543
+ "succeeded" INTEGER NOT NULL DEFAULT 0,
544
+ "failed" INTEGER NOT NULL DEFAULT 0,
545
+ "cancelled" INTEGER NOT NULL DEFAULT 0,
546
+ "failed_job_ids" TEXT NOT NULL,
547
+ "options" TEXT NOT NULL,
548
+ "cancelled_at" BIGINT,
549
+ "finished_at" BIGINT,
550
+ "created_at" BIGINT NOT NULL,
551
+ "updated_at" BIGINT NOT NULL${z}
552
+ )`]}function gZ(Z){let $=JSON.parse(Z.options),V=(z)=>z==null?null:Number(z);return{id:String(Z.id),name:Z.name==null?null:String(Z.name),total:Number(Z.total),pending:Number(Z.pending),succeeded:Number(Z.succeeded),failed:Number(Z.failed),cancelled:Number(Z.cancelled),failedJobIds:JSON.parse(Z.failed_job_ids),cancelledAt:V(Z.cancelled_at),finishedAt:V(Z.finished_at),createdAt:Number(Z.created_at),allowFailures:$.allowFailures===!0,callbacks:$.callbacks??{}}}function C1(Z){return JSON.stringify({allowFailures:Z.allowFailures,callbacks:Z.callbacks})}function yZ(Z){let $=String(Z?.message??Z);return/does not exist|doesn't exist|unknown column|no such (table|column)|has no column/i.test($)}async function t0(Z,$){try{return await Z}catch(V){if(!yZ(V))throw V;throw Error(`Job batches need the "${$}" table and the batch_id and progress columns of the jobs table, and the database says one is missing. Add the GemiJobBatch model and the two GemiJob fields from the docs (docs/jobs-and-queues.md#batches) and migrate, or call the driver's createTable().`,{cause:V})}}function W3(Z){return Z}function bZ(){return{jobs:[],jobsDir:"app/jobs",workflows:[],workflowsDir:"app/workflows",concurrency:1,driver:"memory",visibilityTimeout:300000,pollInterval:1000,unknownJobGrace:3600000,locks:"auto"}}var W1=86400000;class e0{queue;workflows=new Map;steps=new Map;items=new Map;sources=new Map;constructor(Z){this.queue=Z}async create(Z){if(this.workflows.has(Z.id))throw Error(`A workflow with the id ${Z.id} already exists.`);this.prune(W1);let $=Date.now();this.workflows.set(Z.id,{...Z,status:"running",currentStep:null,progress:0,result:null,error:null,wakeAt:null,lockedBy:null,lockedUntil:null,retick:!1,createdAt:$,updatedAt:$}),this.steps.set(Z.id,new Map),this.tick(Z.id,0)}async find(Z,$={}){let V=this.workflows.get(Z);if(!V)return null;return{workflow:{...V},steps:$.steps===!1?[]:this.stepsOf(Z)}}async acquire(Z,$,V){let z=this.workflows.get(Z);if(!z)return{kind:"missing"};let X=Date.now();if(z.lockedBy!==null&&!h0(z.lockedBy,$)&&(z.lockedUntil??0)>X)return z.retick=!0,{kind:"busy"};return z.lockedBy=$,z.lockedUntil=X+V,z.retick=!1,{kind:"acquired",workflow:{...z},steps:this.stepsOf(Z)}}async renew(Z,$,V){let z=this.workflows.get(Z);if(!z||z.lockedBy!==$)return!1;return z.lockedUntil=Date.now()+V,!0}statusOf(Z){return this.workflows.get(Z)?.status}async update(Z,$,V){let z=this.workflows.get(Z);if(!z)return;if($.owner!==void 0&&z.lockedBy!==$.owner)throw new b(Z);let X=this.steps.get(Z),Y=$.key===void 0?void 0:X.get($.key),G=Date.now(),B=V({workflow:{...z},step:Y?{...Y}:null,steps:$.allSteps?this.stepsOf(Z):[],items:$.items===void 0?[]:this.itemsOf(Z,$.items,["running","retrying"],-1,1/0),now:G});if(B.step){let H=X.get(B.step.key);X.set(B.step.key,{...B.step,createdAt:H?.createdAt??G,updatedAt:G})}if(B.items){let H=this.rowsOf(Z,B.items.step);for(let Q of B.items.delete??[])H.all.delete(Q),H.open.delete(Q);for(let Q of[...B.items.insert??[],...B.items.update??[]]){let J=H.all.get(Q.index);if(H.all.set(Q.index,{...Q,step:B.items.step,createdAt:J?.createdAt??G,updatedAt:G}),Q.status==="running"||Q.status==="retrying")H.open.add(Q.index);else H.open.delete(Q.index)}}if(B.batch)this.queue.enqueueBatch(B.batch);for(let H of B.cancelBatches??[])this.queue.cancelBatch(H);if(B.workflow)Object.assign(z,B.workflow);if(z.updatedAt=G,B.tick)this.tick(Z,B.tick.delayMs);if(B.unlock){if(z.lockedBy=null,z.lockedUntil=null,z.retick)z.retick=!1,this.tick(Z,0)}return B.result}async prune(Z){let $=Date.now()-Z,V=0;for(let[z,X]of this.workflows)if(["completed","failed","cancelled"].includes(X.status)&&X.updatedAt<=$){this.workflows.delete(z),this.steps.delete(z),this.items.delete(z);for(let[G,B]of this.sources)if(B.workflowId===z)this.sources.delete(G);V++}return V}async writeSource(Z,$,V){let z=this.sources.get(Z);if(!z)z={workflowId:$,createdAt:Date.now(),rows:new Map},this.sources.set(Z,z);for(let X of V){if(z.rows.has(X.index))throw Error(`Item source "${Z}" already has an item at index ${X.index}.`);z.rows.set(X.index,X.payload)}}async readSource(Z,$,V){let z=this.sources.get(Z)?.rows,X=[];if(!z)return X;for(let Y=Math.max(0,$);Y<V;Y++){let G=z.get(Y);if(G!==void 0)X.push({index:Y,payload:G})}return X}async deleteSource(Z){let $=this.sources.get(Z)?.rows.size??0;return this.sources.delete(Z),$}async pruneSources(Z){let $=Date.now()-Z,V=0;for(let[z,X]of this.sources)if(X.workflowId===null&&X.createdAt<=$)V+=X.rows.size,this.sources.delete(z);return V}async listItems(Z,$,V){return this.itemsOf(Z,$,V.statuses,V.after??-1,V.limit)}itemsOf(Z,$,V,z,X){let Y=this.items.get(Z)?.get($);if(!Y)return[];let B=V.every((Q)=>Q==="running"||Q==="retrying")?[...Y.open]:[...Y.all.keys()],H=[];for(let Q of B.sort((J,F)=>J-F)){if(Q<=z)continue;let J=Y.all.get(Q);if(!V.includes(J.status))continue;if(H.push({...J}),H.length>=X)break}return H}rowsOf(Z,$){let V=this.items.get(Z);if(!V)this.items.set(Z,V=new Map);let z=V.get($);if(!z)V.set($,z={all:new Map,open:new Set});return z}stepsOf(Z){return[...this.steps.get(Z)?.values()??[]].map(($)=>({...$}))}tick(Z,$){this.queue.enqueue({name:m,args:JSON.stringify([Z]),delayMs:Math.max(0,Math.round($))})}}function ZZ(Z){return`workflow:${Z}`}var qZ=191;function u0(Z,$){if(Z===void 0||Z===null)return[];let V=Array.isArray(Z)?Z:[Z],z=new Set,X=[];for(let Y of V){if(Y===void 0||Y===null)continue;let{key:G,limit:B}=Y??{};if(typeof G!=="string"||G.length===0||G.length>qZ)throw TypeError(`${$}.concurrency returned a key that is not a string of 1 to ${qZ} characters: ${JSON.stringify(G)}.`);if(typeof B!=="number"||!Number.isInteger(B)||B<0)throw TypeError(`${$}.concurrency returned the limit ${String(B)} for "${G}"; a limit is a whole number, 0 or more.`);if(z.has(G))throw TypeError(`${$}.concurrency returned the key "${G}" twice.`);z.add(G),X.push({key:G,limit:B})}return X}class $Z{host;lines=new Map;keysOf=new Map;order=0;constructor(Z){this.host=Z}line(Z){let $=this.lines.get(Z),V=$?this.sorted($):[];return{holding:V.filter((z)=>z.state==="holding").map((z)=>z.holder),waiting:V.filter((z)=>z.state==="waiting").map((z)=>z.holder)}}acquire(Z){let $;for(let V of this.keysOf.get(Z.holder)??[]){let z=this.lines.get(V)?.tickets.get(Z.holder);if(z&&($===void 0||z.order<$))$=z.order}$??=this.order++;for(let{key:V,limit:z}of Z.slots){let X=this.lines.get(V)??{key:V,limit:z,tickets:new Map};this.lines.set(V,X),X.limit=z,this.prune(X);let Y=X.tickets.get(Z.holder);if(!Y){Y={holder:Z.holder,state:"waiting",order:$,jobId:Z.job.id,workflowId:Z.workflowId},X.tickets.set(Z.holder,Y);let H=this.keysOf.get(Z.holder)??new Set;H.add(V),this.keysOf.set(Z.holder,H)}Y.jobId=Z.job.id;let G=()=>this.holders(X)+this.ahead(X,Y)<z;if(Y.state==="waiting"&&!G())this.wake(X,Z.holder);if(Y.state==="waiting"&&G())Y.state="holding";if(Y.state==="holding"){this.wake(X,Z.holder);continue}let B=this.ahead(X,Y)<Math.max(1,z);return this.host.park(Z.job,B?Z.recheckMs.near:Z.recheckMs.far),!1}return!0}release(Z){let $=this.keysOf.get(Z);if(!$)return;this.keysOf.delete(Z);for(let V of $){let z=this.lines.get(V);if(!z)continue;if(z.tickets.delete(Z),this.prune(z),this.wake(z,Z),z.tickets.size===0)this.lines.delete(V)}}sorted(Z){return[...Z.tickets.values()].sort(($,V)=>$.order-V.order||($.holder<V.holder?-1:$.holder>V.holder?1:0))}holders(Z){let $=0;for(let V of Z.tickets.values())if(V.state==="holding")$++;return $}ahead(Z,$){let V=0;for(let z of Z.tickets.values()){if(z.state!=="waiting"||z===$)continue;if(z.order<$.order||z.order===$.order&&z.holder<$.holder)V++}return V}alive(Z){return Z.workflowId!==void 0?this.host.workflowAlive(Z.workflowId):this.host.jobAlive(Z.jobId)}prune(Z){for(let $ of Z.tickets.values())if($.state==="holding"&&!this.alive($))this.forget(Z,$)}wake(Z,$){let V=Z.limit-this.holders(Z);for(let z of this.sorted(Z)){if(V<=0)return;if(z.state!=="waiting"||z.holder===$)continue;if(!this.alive(z)){this.forget(Z,z);continue}if(!this.host.wake(z.jobId)){if(z.workflowId===void 0){this.forget(Z,z);continue}z.jobId=this.host.tick(z.workflowId)}V--}}forget(Z,$){Z.tickets.delete($.holder);let V=this.keysOf.get($.holder);if(V?.delete(Z.key),V?.size===0)this.keysOf.delete($.holder)}}var O1=86400000;class p0{entries=new Map;batches=new Map;workflows;slots=new $Z({jobAlive:(Z)=>this.entries.has(Z),workflowAlive:(Z)=>{let $=this.workflows?.statusOf(Z);return $!==void 0&&$!=="completed"&&$!=="failed"&&$!=="cancelled"&&$!=="paused"},park:(Z,$)=>{let V=this.current(Z);if(!V)return;V.job={...V.job,attempt:V.job.attempt-1},V.leased=!1,V.until=Date.now()+Math.max(0,$),this.changed()},wake:(Z)=>{let $=this.entries.get(Z);if(!$)return!1;if(!$.leased&&$.until>Date.now())$.until=Date.now(),this.changed();return!0},tick:(Z)=>{let $=this.add({name:m,args:JSON.stringify([Z])});return this.changed(),$}});listeners=new Set;timer;timerAt=1/0;seq=0;get waiting(){let Z=0;for(let $ of this.entries.values())if(!$.leased)Z++;return Z}get leased(){return this.entries.size-this.waiting}async enqueue(Z){let $=this.add(Z);return this.changed(),$}add({name:Z,args:$,delayMs:V=0,id:z=crypto.randomUUID()},X){let Y=Date.now();return this.entries.set(z,{job:{id:z,name:Z,args:$,attempt:0,createdAt:Y,...X===void 0?{}:{batchId:X}},until:Y+Math.max(0,V),leased:!1,seq:this.seq++,progress:0}),z}async enqueueBatch(Z){this.recordBatch(Z)}recordBatch(Z){let $=Date.now();this.forgetFinishedBatches($);let V=q0({...Z,total:Z.args.length,now:$});for(let Y of Z.args)this.add({name:Z.job,args:Y},Z.id);let{record:z,calls:X}=F0(V,V,$);this.batches.set(Z.id,z);for(let Y of X)this.add(Y);this.changed()}async findBatch(Z,$={}){let V=this.batches.get(Z);if(!V)return null;if($.progress===!1||V.pending===0)return G0(V);let z=0;for(let X of this.entries.values())if(X.job.batchId===Z)z+=X.progress;return G0(V,z)}async cancelBatch(Z){return this.cancelBatchNow(Z)}cancelBatchNow(Z){let $=this.batches.get(Z);if(!$||$.finishedAt!==null||$.cancelledAt!==null)return!1;let V=Date.now(),z=K0($,V,this.cancelWaiting(Z));return this.save($,z,V),this.changed(),!0}workflowStore(){return this.workflows??=new e0({enqueue:(Z)=>{this.add(Z),this.changed()},enqueueBatch:(Z)=>this.recordBatch(Z),cancelBatch:(Z)=>void this.cancelBatchNow(Z)}),this.workflows}async acquireSlots(Z){return this.slots.acquire(Z)}async releaseSlots(Z){this.slots.release(Z)}async reportProgress(Z,$){let V=this.current(Z);if(V)V.progress=i($)}async claim(Z,$){let V=Date.now(),z=[...this.entries.values()].filter((X)=>X.until<=V).sort((X,Y)=>X.until-Y.until||X.seq-Y.seq).slice(0,Math.max(0,Z));for(let X of z)X.job={...X.job,attempt:X.job.attempt+1},X.leased=!0,X.until=V+$.visibilityTimeoutMs;if(z.length>0)this.schedule();return z.map((X)=>({...X.job}))}async complete(Z){let $=this.current(Z);if(!$)return;this.entries.delete(Z.id),this.count($,"succeeded"),this.schedule()}async fail(Z,$){let V=this.current(Z);if(!V)return;let z=V.job.batchId===void 0?void 0:this.batches.get(V.job.batchId),X=$.cancelled===!0||$.retryInMs!==null&&z?.cancelledAt!=null;if($.retryInMs===null||X){this.entries.delete(Z.id),this.count(V,X?"cancelled":"failed"),this.schedule();return}V.leased=!1,V.until=Date.now()+Math.max(0,$.retryInMs),V.seq=this.seq++,V.progress=0,this.changed()}async release(Z,$){let V=this.current(Z);if(!V)return;V.job={...V.job,attempt:V.job.attempt-1},V.leased=!1,V.until=Date.now()+Math.max(0,$.retryInMs),V.seq=this.seq++,this.changed()}async heartbeat(Z,$){let V=Date.now()+$.visibilityTimeoutMs;for(let z of Z){let X=this.current(z);if(X)X.until=V}this.schedule()}count(Z,$){let V=Z.job.batchId;if(V===void 0)return;let z=this.batches.get(V);if(!z)return;let X=Date.now(),Y=m0(z,$,Z.job.id);if(k0(z,Y))Y=K0(Y,X,this.cancelWaiting(V));this.save(z,Y,X),this.changed()}save(Z,$,V){let{record:z,calls:X}=F0(Z,$,V);this.batches.set(z.id,z);for(let Y of X)this.add(Y)}cancelWaiting(Z){let $=0;for(let[V,z]of this.entries)if(z.job.batchId===Z&&!z.leased)this.entries.delete(V),$++;return $}forgetFinishedBatches(Z){for(let[$,V]of this.batches)if(V.finishedAt!==null&&Z-V.finishedAt>O1)this.batches.delete($)}subscribe(Z){return this.listeners.add(Z),()=>void this.listeners.delete(Z)}current(Z){let $=this.entries.get(Z.id);if(!$||!$.leased||$.job.attempt!==Z.attempt)return;return $}changed(){this.schedule();let Z=Date.now();for(let $ of this.entries.values())if($.until<=Z){this.wake();return}}wake(){for(let Z of[...this.listeners])Z()}schedule(){let Z=Date.now(),$=1/0;for(let V of this.entries.values())if(V.until>Z&&V.until<$)$=V.until;if($===this.timerAt)return;if(clearTimeout(this.timer),this.timer=void 0,this.timerAt=$,$===1/0)return;this.timer=setTimeout(()=>{this.timer=void 0,this.timerAt=1/0,this.changed()},$-Z),this.timer.unref?.()}}import{AsyncResource as w1}from"async_hooks";import{existsSync as c1}from"fs";import{isMainThread as l1}from"worker_threads";class Q0{static name="unset";worker=!1;maxAttempts=3;backoff=0;uniqueId(...Z){return}uniqueFor=3600000;throttle(...Z){return}concurrency(...Z){return}release(Z=0){this.$outcome={kind:"release",delayMs:Z}}fail(Z,$={}){this.$outcome={kind:"fail",error:Z instanceof Error?Z:Error(String(Z)),retry:$.retry??!0}}batch=void 0;async progress(Z){let $=i(Z);await this.$progress?.($)}$progress;$claimed;$outcome;run(...Z){}onFail(Z,...$){}onSuccess(Z,...$){}onDeadletter(Z,...$){}static dispatch(...Z){if(this.name==="unset")throw Error("Cannot dispatch a job with no name");return B0(Z0).push(this,JSON.stringify(Z))}static dispatchBatch(Z,$={}){if(this.name==="unset")throw Error("Cannot dispatch a job with no name");return B0(Z0).pushBatch(this,Z.map((V)=>JSON.stringify(V)),$)}static with(...Z){if(this.name==="unset")throw Error("Cannot use a job with no name as a callback");return JSON.stringify(Z),{name:this.name,args:Z}}static findBatch(Z){return B0(Z0).findBatch(Z)}static cancelBatch(Z){return B0(Z0).cancelBatch(Z)}}function E0(Z,$){let V=Array.isArray(Z)?Z[Math.min($,Z.length)-1]:Z;return Math.max(0,V??0)}class XZ extends Error{step;batch;summary;constructor(Z,$,V,z){super($);this.step=Z;this.batch=V;this.summary=z;this.name="StepFailedError"}}class YZ extends Error{step;constructor(Z){super(`No signal "${Z}" arrived before its timeout.`);this.step=Z;this.name="WaitTimeoutError"}}class GZ extends Error{constructor(Z,$){super(`Step "${Z}" took longer than its timeout of ${$}ms.`);this.name="StepTimeoutError"}}class BZ extends Error{constructor(Z){super(`Workflow ${Z} was cancelled.`);this.name="WorkflowCancelledError"}}class t extends Error{constructor(){super("The workflow is suspended until a step can continue. Rethrow this error if you catch it.");this.name="WorkflowSuspended"}}var mZ=Symbol("done"),kZ=Symbol("paused");class KZ{tick;workflowId;steps;seen=new Set;pending=new Set;suspension;lost=!1;cancelled=!1;current=null;constructor(Z){this.tick=Z;this.workflowId=Z.workflowId,this.steps=new Map(Z.steps.map(($)=>[$.key,$]))}run(Z,$,V={}){return this.track(Z,()=>this.runStep(Z,$,V))}sleep(Z,$){let V=r($);return this.track(Z,()=>this.sleepStep(Z,V))}waitFor(Z,$={}){let V=$.timeout===void 0?void 0:r($.timeout);return this.track(Z,()=>this.waitStep(Z,V))}batch(Z,$,V,z={}){return this.track(Z,()=>this.batchStep(Z,$,V,z))}each(Z,$,V){return this.track(Z,()=>this.eachStep(Z,$,V))}source(Z,$,V={}){let z=`${this.workflowId}:${Z}`;return this.run(Z,async()=>PZ(this.tick.store,z,await $(),this.workflowId),V)}async progress(Z){let $=i(Z);this.assertRunning();let V=this.write(void 0,()=>({result:void 0,workflow:{progress:$}}));this.remember(V),await V}async settled(){while(this.pending.size>0)await Promise.allSettled(this.pending)}track(Z,$){if(typeof Z!=="string"||Z.length===0||Z.length>191)throw TypeError(`A step key is a string of 1 to 191 characters; got ${JSON.stringify(Z)}.`);if(this.seen.has(Z))throw Error(`Two steps of workflow ${this.workflowId} use the key "${Z}". Each step needs a key of its own, or the second would return the first one's result.`);this.seen.add(Z),this.assertRunning();let V=$();return this.remember(V),V}remember(Z){this.pending.add(Z);let $=()=>void this.pending.delete(Z);Z.then($,$)}assertRunning(){if(this.lost)throw new b(this.workflowId);if(this.suspension)throw new t}suspend(Z,$){if(!this.suspension)this.suspension={status:Z,wakes:[]};if($!=null)this.suspension.wakes.push($);throw new t}async write(Z,$,V={}){let z;try{z=await this.tick.store.update(this.tick.workflowId,{owner:this.tick.owner,...Z===void 0?{}:{key:Z},...V.items&&Z!==void 0?{items:Z}:{},...V.joinTransaction?{joinTransaction:!0}:{}},(X)=>{if(X.workflow.status==="cancelling"&&!this.tick.cancelling)return{result:mZ};if(V.start&&X.workflow.status==="paused"&&!this.tick.cancelling)return{result:kZ};let Y=$(X);return{...Y,result:{value:Y.result}}})}catch(X){if(X instanceof b)this.lost=!0;throw X}if(z===void 0)throw this.lost=!0,new b(this.tick.workflowId);if(z===mZ)this.cancelled=!0,this.suspend("waiting");if(z===kZ)this.suspend("paused");return z.value}record(Z,$,V){let z={workflowId:this.tick.workflowId,key:Z,status:"running",attempt:0,output:null,error:null,batchId:null,wakeAt:null,startedAt:null,finishedAt:null,createdAt:0,updatedAt:0,...$,...V};return this.steps.set(Z,z),z}mismatch(Z,$,V){throw Error(`Step "${Z}" of workflow ${this.tick.workflowId} was recorded as a ${$} step, and is now used as ${V}. A key belongs to one step; rename one of them.`)}async runStep(Z,$,V){let z=Math.max(1,Math.floor(V.attempts??3)),X=V.timeout===void 0?void 0:r(V.timeout),Y=this.steps.get(Z);if(Y?.status==="completed")return n(Y.output);if(Y?.status==="failed")throw s(Z,Y);if(Y?.status==="retrying"&&Y.wakeAt!==null&&Y.wakeAt>Date.now())this.current=Z,this.suspend("sleeping",Y.wakeAt);for(;;){let G=await this.write(Z,({workflow:N,step:P,now:W})=>{if(P?.status==="completed")return{result:{kind:"done",output:P.output}};if(P?.status==="failed")return{result:{kind:"failed",step:P}};if(P&&P.status!=="running"&&P.status!=="retrying")this.mismatch(Z,P.status,"step.run");if(P?.status==="retrying"&&P.wakeAt!==null&&P.wakeAt>W)return{result:{kind:"wait",wakeAt:P.wakeAt}};let A=(P?.attempt??0)+1;if(A>z){let _=this.record(Z,P,{status:"failed",error:`Attempt ${A-1} of ${z} never finished, most likely because the process running it exited.`+(P?.error?` The last error was: ${P.error}`:""),finishedAt:W,wakeAt:null});return{result:{kind:"failed",step:_},step:_}}let T=this.record(Z,P,{status:"running",attempt:A,startedAt:W,finishedAt:null,wakeAt:null});return{result:{kind:"run",attempt:A},step:T,workflow:N.status==="cancelling"?{currentStep:Z}:{currentStep:Z,status:"running"}}},{start:!0});if(this.current=Z,G.kind==="done")return n(G.output);if(G.kind==="failed")throw s(Z,G.step);if(G.kind==="wait")this.suspend("sleeping",G.wakeAt);let B=G.attempt,H,Q,J=!0;try{H=await this.execute(Z,$,B,X)}catch(N){Q=N}if(this.cancelled)throw new t;let F=null;if(Q===void 0)try{F=S0(H,`The result of step "${Z}"`)}catch(N){Q=N,J=!1}if(Q===void 0)return await this.write(Z,({step:N,now:P})=>({result:void 0,step:this.record(Z,N,{status:"completed",output:F,error:null,wakeAt:null,finishedAt:P})})),n(F);let U=N0(Q);if(J&&B<z){let N=E0(V.backoff??0,B),P=await this.write(Z,({step:W,now:A})=>{let T=N>0?A+N:null;return{result:T,step:this.record(Z,W,{status:"retrying",error:U,wakeAt:T})}});if(P!==null)this.suspend("sleeping",P);continue}let D=await this.write(Z,({step:N,now:P})=>{let W=this.record(Z,N,{status:"failed",error:U,wakeAt:null,finishedAt:P});return{result:W,step:W}});throw s(Z,D)}}async execute(Z,$,V,z){let X=new AbortController,Y={idempotencyKey:`${this.tick.workflowId}:${Z}`,attempt:V,signal:X.signal},G=Promise.resolve().then(()=>$(Y)),B,H,Q=new Promise((J,F)=>{let U=(D)=>{X.abort(D),F(D)};if(z!==void 0)B=setTimeout(()=>U(new GZ(Z,z)),z);if(!this.tick.cancelling)H=setInterval(()=>{this.tick.store.find(this.tick.workflowId,{steps:!1}).then((D)=>{if(D?.workflow.status!=="cancelling"||X.signal.aborted)return;if(this.cancelled=!0,!this.suspension)this.suspension={status:"waiting",wakes:[]};U(new BZ(this.tick.workflowId))}).catch(()=>{})},this.tick.cancelCheckMs),H.unref?.()});try{return await Promise.race([G,Q])}finally{clearTimeout(B),clearInterval(H),G.catch(()=>{}),Q.catch(()=>{})}}async sleepStep(Z,$){let V=this.steps.get(Z);if(V?.status==="completed")return;if(this.current=Z,V?.status==="sleeping"&&V.wakeAt!==null&&V.wakeAt>Date.now())this.suspend("sleeping",V.wakeAt);let z=await this.write(Z,({step:X,now:Y})=>{if(X?.status==="completed")return{result:null};if(X&&X.status!=="sleeping")this.mismatch(Z,X.status,"step.sleep");let G=X?.wakeAt??Y+$;if(G<=Y)return{result:null,step:this.record(Z,X,{status:"completed",wakeAt:G,startedAt:X?.startedAt??Y,finishedAt:Y})};if(X)return{result:G};return{result:G,step:this.record(Z,null,{status:"sleeping",wakeAt:G,startedAt:Y}),workflow:{currentStep:Z}}});if(z!==null)this.suspend("sleeping",z)}async waitStep(Z,$){let V=this.steps.get(Z);if(V?.status==="completed")return n(V.output);if(V?.status==="timed_out")throw new YZ(Z);if(this.current=Z,V?.status==="waiting"&&(V.wakeAt===null||V.wakeAt>Date.now()))this.suspend("waiting",V.wakeAt);let z=await this.write(Z,({step:X,now:Y})=>{if(X?.status==="completed")return{result:{kind:"value",output:X.output}};if(X?.status==="timed_out")return{result:{kind:"timeout"}};if(X?.status==="signalled")return{result:{kind:"value",output:X.output},step:this.record(Z,X,{status:"completed",wakeAt:null,startedAt:X.startedAt??Y,finishedAt:Y})};if(X&&X.status!=="waiting")this.mismatch(Z,X.status,"step.waitFor");if(X){if(X.wakeAt!==null&&X.wakeAt<=Y)return{result:{kind:"timeout"},step:this.record(Z,X,{status:"timed_out",finishedAt:Y})};return{result:{kind:"wait",wakeAt:X.wakeAt}}}let G=$===void 0?null:Y+$;return{result:{kind:"wait",wakeAt:G},step:this.record(Z,null,{status:"waiting",wakeAt:G,startedAt:Y}),workflow:{currentStep:Z}}});if(z.kind==="value")return n(z.output);if(z.kind==="timeout")throw new YZ(Z);this.suspend("waiting",z.wakeAt)}async eachStep(Z,$,V){let z=$.source,X=z?z.count:$.count;if(!z&&typeof $.item!=="function")throw TypeError(`step.each "${Z}" needs either { count, item } or { source }.`);if(!Number.isSafeInteger(X)||X<0||X>uZ)throw TypeError(`step.each "${Z}" needs a count that is a whole number from 0 to ${uZ}; got ${String(X)}.`);let Y=Math.max(1,Math.floor($.concurrency??1)),G=Math.max(1,Math.floor($.attempts??3)),B=$.timeout===void 0?void 0:r($.timeout),H=$.tickBudget===void 0?E1:r($.tickBudget),Q=$.progress!==!1,J=$.chunk!==void 0,F=J?Math.max(1,Math.floor($.chunk)):1,U=[$.throttle??[]].flat().map((K)=>({name:`gemi:throttle:${K.key}`,limit:Math.max(0,Math.floor(K.limit)),windowMs:r(K.window)})),D=I1($.maxFailures),N=this.tick.store,P=$.transaction===!0&&N.transaction?(K)=>N.transaction(K):void 0;if($.transaction===!0&&!P)h1();let W=z?iZ(N,z,Math.max(S1,Y*F*4)):$.item;if(!N.listItems)throw Error("This queue's workflow store does not support step.each. The memory and database drivers do.");if(U.length>0&&!this.tick.throttle)throw Error(`step.each "${Z}" has a throttle, and this queue has no lock store.`);let A=this.steps.get(Z);if(A?.status==="completed")return JZ(A.output);if(A?.status==="failed")throw s(Z,A);if(A&&A.status!=="iterating")this.mismatch(Z,A.status,"step.each");if(this.current=Z,this.tick.durable===!1)g1();let T=await this.write(Z,({workflow:K,step:R,items:L,now:O})=>{if(R?.status==="completed")return{result:{kind:"done",output:R.output}};if(R?.status==="failed")return{result:{kind:"failed",step:R}};if(R&&R.status!=="iterating")this.mismatch(Z,R.status,"step.each");let x=R?w0(R.output):M1(X);return{result:{kind:"go",state:x,open:L},...R?{}:{step:this.record(Z,null,{status:"iterating",output:zZ(x),startedAt:O})},workflow:K.status==="cancelling"?{currentStep:Z}:{currentStep:Z,status:"running"}}},{items:!0,start:!0});if(T.kind==="done")return JZ(T.output);if(T.kind==="failed")throw s(Z,T.step);let _=T.state;if(_.count!==X)f1(this.workflowId,Z,_.count,X);let D0=_.count,l=new Map(T.open.map((K)=>[K.index,K])),k=[],_0=new Map,a0=new Map,DZ=Date.now()+H,H0=0,M0=!1,$0=null,p=new AbortController,_Z=setInterval(()=>{N.find(this.workflowId,{steps:!1}).then((K)=>{if(K?.workflow.status==="paused")M0=!0;if(K?.workflow.status!=="cancelling"||p.signal.aborted)return;if(this.cancelled=!0,!this.suspension)this.suspension={status:"waiting",wakes:[]};p.abort(new BZ(this.workflowId))}).catch(()=>{})},this.tick.cancelCheckMs);_Z.unref?.(),$0=D(_);let LZ=(K,R)=>{let L={...K};for(let O of R)if(O.counter)L[O.counter]++;return L},CZ=(K)=>{let R=K.succeeded+K.skipped+K.failed;return Q?{workflow:{progress:D0===0?1:i(R/D0)}}:{}},WZ=(K)=>{if(_={count:_.count,next:Math.max(_.next,K.next),succeeded:Math.max(_.succeeded,K.succeeded),skipped:Math.max(_.skipped,K.skipped),failed:Math.max(_.failed,K.failed)},!$0)$0=D(_);if($0&&!p.signal.aborted)p.abort(new t)},V1=async(K)=>{let R=K.map(()=>null),L=new Map,O=new AbortController,x=()=>O.abort(p.signal.reason);p.signal.addEventListener("abort",x,{once:!0});let u,V0=K.length===1?`${Z}[${K[0].index}]`:`${Z}[${K[0].index}..${K.at(-1).index}]`,L0=new Promise((C,S)=>{if(O.signal.addEventListener("abort",()=>S(O.signal.reason),{once:!0}),B!==void 0)u=setTimeout(()=>O.abort(new GZ(V0,B)),B)}),f=(C)=>{throw new HZ(Math.max(0,Math.floor(Number(C)||0)))},z0=(C)=>K.map((S,q)=>{let d=L.get(q);if(!d)return{index:S.index,row:null,counter:"succeeded"};return{index:S.index,row:wZ(S,R[q],d.reason,d.data,C),counter:"skipped"}}),X0=null,g=(async()=>{let C=await Promise.all(K.map((M)=>W(M.index)));K.forEach((M,v)=>{R[v]=v1($.key?$.key(C[v],M.index):M.index)});let S=(M)=>`${this.workflowId}:${Z}:${R[M]}`,q=Math.max(...K.map((M)=>M.attempt)),d=async()=>{if(J){let M={idempotencyKey:S(0),attempt:q,signal:O.signal,items:K.map((v,y)=>({index:v.index,key:R[y],idempotencyKey:S(y)})),skip:(v,y,I)=>{if(!Number.isInteger(v)||v<0||v>=K.length)throw RangeError(`ctx.skip: no item at position ${v} of this chunk.`);L.set(v,{reason:String(y),data:I})},release:f};await V(C,M)}else{let M={idempotencyKey:S(0),attempt:q,signal:O.signal,index:K[0].index,key:R[0],skip:(v,y)=>{throw new QZ(v,y)},release:f};await V(C[0],M)}};if(!P)return d();await P(async()=>{if(await d(),O.signal.aborted)throw O.signal.reason;let M=z0(Date.now()),v=await this.write(Z,({step:y})=>{let I={step:Z,insert:[],update:[],delete:[]};for(let J0 of M)if(J0.row===null)I.delete.push(J0.index);else I.update.push(J0.row);let a=LZ(y?w0(y.output):_,M);return{result:a,step:this.record(Z,y,{status:"iterating",output:zZ(a)}),items:I,...CZ(a)}},{joinTransaction:!0});X0=M.map((y)=>({...y,recorded:!0})),WZ(v)})})(),j,E=!1;try{await Promise.race([g,L0])}catch(C){E=!0,j=C}finally{clearTimeout(u),p.signal.removeEventListener("abort",x),g.catch(()=>{}),L0.catch(()=>{})}if(X0){k.push(...X0);return}if(p.signal.aborted||this.cancelled||this.lost)return;let h=Date.now();if(!E){k.push(...z0(h));return}if(j instanceof QZ){k.push({index:K[0].index,row:wZ(K[0],R[0],j.reason,j.data,h),counter:"skipped"});return}if(j instanceof HZ){H0=Math.max(H0,h+j.delayMs),K.forEach((C,S)=>{k.push({index:C.index,row:{...C,key:R[S],status:"retrying",attempt:Math.max(0,C.attempt-1),wakeAt:h+j.delayMs},counter:null})});return}let w=T0(N0(j),2000);K.forEach((C,S)=>{if(C.attempt<G){let q=E0($.backoff??0,C.attempt);k.push({index:C.index,row:{...C,key:R[S],status:"retrying",error:w,wakeAt:h+q},counter:null});return}k.push({index:C.index,row:{...C,key:R[S],status:"failed",error:w,wakeAt:null,finishedAt:h},counter:"failed"})})},z1=async(K)=>{if(U.length===0||K===0)return K;let R=this.tick.throttle;for(let L=0;L<K;L++){let O=[];for(let x of U){let u=await R.hit(x.name,x.limit,x.windowMs);if(!u.allowed)return await Promise.all(O.map((V0)=>R.refund(V0))),H0=Math.max(H0,Date.now()+Math.max(1,u.resetInMs)),L;O.push(x.name)}}return K},X1=async(K)=>{if(U.length===0)return;for(let R=0;R<K;R++)for(let L of U)await this.tick.throttle.refund(L.name)};try{for(;;){let K=Date.now(),R=K>=DZ||c0()||this.cancelled||M0||$0!==null,L=[],O=0;if(!R&&K>=H0){let f=(Y-_0.size)*F,z0=new Set(k.map((j)=>j.index));for(let j of[...l.values()].sort((E,h)=>E.index-h.index)){if(L.length>=f)break;if(a0.has(j.index)||z0.has(j.index))continue;if(j.status==="running"||(j.wakeAt??0)<=K)L.push(j)}let X0=Y*F+pZ-l.size;O=Math.max(0,Math.min(f-L.length,D0-_.next,X0));let g=await z1(L.length+O);if(g<L.length)L=L.slice(0,g),O=0;else O=g-L.length}if(k.length>0||L.length>0||O>0){let f=k.splice(0,k.length),z0=f.filter((E)=>!E.recorded),X0=L.length+O,g=await this.write(Z,({workflow:E,step:h,now:w})=>{let C=LZ(h?w0(h.output):_,z0),S={step:Z,insert:[],update:[],delete:[]},q=[],d=[];for(let I of z0)if(I.row===null)S.delete.push(I.index);else S.update.push(I.row);let M=E.status==="paused"&&!this.tick.cancelling;for(let I of M?[]:L){if(I.attempt+1>G){let J0={...I,status:"failed",error:T0(`Attempt ${I.attempt} of ${G} never finished, most likely because the process running it exited.`+(I.error?` The last error was: ${I.error}`:""),2000),wakeAt:null,finishedAt:w};C.failed++,S.update.push(J0),d.push(J0);continue}let a={...I,status:"running",attempt:I.attempt+1,wakeAt:null,startedAt:w};S.update.push(a),q.push(a)}let v=M?0:O,y=q.length;for(let I=0;I<v;I++){let a=j1(this.workflowId,Z,C.next+I,w);S.insert.push(a),q.push(a)}return C.next+=v,{result:{next:C,started:q,closed:d,reruns:y,paused:M},step:this.record(Z,h,{status:"iterating",output:zZ(C)}),items:S,...CZ(C)}});if(WZ(g.next),g.paused)M0=!0;await X1(X0-g.started.length);for(let E of f)if(E.row?.status==="retrying")l.set(E.index,E.row);else l.delete(E.index);for(let E of g.closed)l.delete(E.index);for(let E of g.started)l.set(E.index,E);let j=[...cZ(g.started.slice(0,g.reruns),F),...cZ(g.started.slice(g.reruns),F)];for(let E of j){let h=E[0].index;for(let w of E)a0.set(w.index,h);_0.set(h,V1(E).finally(()=>{_0.delete(h);for(let w of E)a0.delete(w.index)}))}}if(_0.size>0){await Promise.race(_0.values());continue}if(k.length>0)continue;if(this.cancelled)throw new t;if($0)break;if(_.next>=D0&&l.size===0)break;if(M0)this.suspend("paused");if(R)this.suspend("running",Date.now());let x=Date.now(),u=1/0;if(_.next<D0&&l.size<Y*F+pZ)u=x;for(let f of l.values())if(f.status==="running")u=x;else if(f.status==="retrying")u=Math.min(u,f.wakeAt??0);let V0=Math.max(u,H0);if(V0<=x)continue;let L0=V0-x;if(L0<=Math.min(T1,DZ-x)){await new Promise((f)=>setTimeout(f,Math.max(0,L0)));continue}this.suspend("sleeping",V0)}}finally{if(clearInterval(_Z),!p.signal.aborted)p.abort(new t)}let OZ=await N.listItems(this.workflowId,Z,{statuses:["failed","skipped"],limit:VZ+1}),i0={...FZ(_),problems:OZ.slice(0,VZ).map(UZ),moreProblems:OZ.length>VZ},Y1=JSON.stringify({$each:_,problems:i0.problems,moreProblems:i0.moreProblems}),j0=$0,G1=await this.write(Z,({step:K,now:R})=>{let L=this.record(Z,K,{status:j0?"failed":"completed",output:Y1,error:j0,finishedAt:R});return{result:L,step:L,...Q&&!j0?{workflow:{progress:1}}:{}}});if(j0)throw s(Z,G1);return i0}async batchStep(Z,$,V,z){let X=z.allowFailures===!0,Y=this.steps.get(Z);if(Y?.status==="completed")return n(Y.output);if(Y?.status==="failed")throw s(Z,Y);if(Y&&Y.status!=="batching")this.mismatch(Z,Y.status,"step.batch");if(this.current=Z,!Y){let F=this.tick.buildBatch($,V,{name:z.name??`workflow:${this.tick.workflowId}:${Z}`,allowFailures:X});if(Y=await this.write(Z,({step:U,now:D})=>{if(U)return{result:U};let N=this.record(Z,null,{status:"batching",batchId:F.id,startedAt:D});return{result:N,step:N,batch:F,workflow:{currentStep:Z}}},{start:!0}),this.tick.scheduled(),Y.status==="completed")return n(Y.output);if(Y.status==="failed")throw s(Z,Y)}let G=Y.batchId===null?null:await this.tick.findBatch(Y.batchId);if(G&&G.finishedAt===null)this.suspend("waiting");let B=G!==null&&G.cancelledAt===null&&(G.failed===0||X),H=G===null?null:JSON.stringify(G),Q=B?null:G===null?`The batch of step "${Z}" (${Y.batchId}) no longer exists.`:`The batch of step "${Z}" failed: ${G.failed} failed and ${G.cancelled} cancelled of ${G.total}.`,J=await this.write(Z,({step:F,now:U})=>{let D=this.record(Z,F,{status:B?"completed":"failed",output:H,error:Q,finishedAt:U});return{result:D,step:D}});if(!B)throw s(Z,J);return G}}function s(Z,$){if($.output?.startsWith('{"$each"'))return new XZ(Z,`Step "${Z}" failed: ${$.error??"unknown error"}`,void 0,JZ($.output));let V=$.batchId!==null&&$.output!==null?JSON.parse($.output):void 0;return new XZ(Z,V?$.error??`Step "${Z}" failed.`:`Step "${Z}" failed: ${$.error??"unknown error"}`,V)}function S0(Z,$){if(Z===void 0)return null;let V=JSON.stringify(Z);if(V===void 0)throw TypeError(`${$} cannot be stored: JSON has no form for it.`);let z=Buffer.byteLength(V,"utf8");if(z>s0)throw RangeError(`${$} is ${z} bytes as JSON, over the ${s0}-byte limit. Store it elsewhere and return its id.`);return V}function n(Z){return Z===null?void 0:JSON.parse(Z)}function N0(Z){return Z instanceof Error?Z.message:String(Z)}var uZ=2147483647,E1=30000,pZ=100,T1=1000,S1=64,VZ=100;class QZ extends Error{reason;data;constructor(Z,$){super(`Skipped: ${Z}`);this.reason=Z;this.data=$;this.name="ItemSkipped"}}class HZ extends Error{delayMs;constructor(Z){super(`Released for ${Z}ms`);this.delayMs=Z;this.name="ItemReleased"}}function wZ(Z,$,V,z,X){let Y=null,G=T0(String(V));try{Y=x1(z)}catch(B){G=T0(`${G} (${N0(B)})`)}return{...Z,key:$,status:"skipped",error:G,output:Y,wakeAt:null,finishedAt:X}}function cZ(Z,$){let V=[];for(let z=0;z<Z.length;z+=$)V.push(Z.slice(z,z+$));return V}function I1(Z){if(Z===void 0)return()=>null;if(typeof Z==="number"){let z=Math.max(0,Math.floor(Z));return(X)=>X.failed>z?`${X.failed} items failed, more than maxFailures (${z}).`:null}let $=Math.min(1,Math.max(0,Z.ratio)),V=Math.max(1,Math.floor(Z.after??20));return(z)=>{let X=z.succeeded+z.skipped+z.failed;if(X<V||z.failed/X<=$)return null;return`${z.failed} of ${X} items failed, more than maxFailures allows (a ratio of ${$}).`}}function M1(Z){return{count:Z,next:0,succeeded:0,skipped:0,failed:0}}function zZ(Z){return JSON.stringify({$each:Z})}function w0(Z){let $=Z===null?null:JSON.parse(Z);if(!$?.$each)throw Error("A step.each step has no state.");return $.$each}function sZ(Z){if(Z===null||!Z.startsWith('{"$each"'))return null;try{return FZ(w0(Z))}catch{return null}}function FZ(Z){return{total:Z.count,done:Z.succeeded+Z.skipped+Z.failed,succeeded:Z.succeeded,skipped:Z.skipped,failed:Z.failed}}function JZ(Z){let $=JSON.parse(Z??"null");return{...FZ($.$each),problems:$.problems??[],moreProblems:$.moreProblems===!0}}function UZ(Z){let $={index:Z.index,key:Z.key,status:Z.status==="skipped"?"skipped":"failed",reason:T0(Z.error??""),attempt:Z.attempt};if(Z.output!==null)$.data=JSON.parse(Z.output);return $}function j1(Z,$,V,z){return{workflowId:Z,step:$,index:V,key:null,status:"running",attempt:1,error:null,output:null,wakeAt:null,startedAt:z,finishedAt:null,createdAt:z,updatedAt:z}}function v1(Z){let $=typeof Z==="number"&&Number.isFinite(Z)?String(Z):Z;if(typeof $!=="string"||$.length===0||$.length>191)throw TypeError(`An item key is a string of 1 to 191 characters, or a number; got ${JSON.stringify(Z)}.`);return $}function T0(Z,$=500){return Z.length<=$?Z:`${Z.slice(0,$-1)}\u2026`}function x1(Z){if(Z===void 0)return null;let $=JSON.stringify(Z);if($===void 0)throw TypeError("its data has no JSON form, so it was not kept");if(Buffer.byteLength($,"utf8")>1024)throw RangeError("its data is over 1 KB as JSON, so it was not kept");return $}var lZ=!1;function g1(){if(lZ||Bun.env.NODE_ENV!=="production")return;lZ=!0,console.warn("[gemi] step.each is running on a queue whose driver keeps nothing across restarts (the memory driver), so a deploy or a crash loses the workflow and the rest of its list. Use the database driver for work that must finish.")}var dZ=!1;function h1(){if(dZ)return;dZ=!0,console.warn("[gemi] step.each with transaction: true runs its items without a transaction: this queue's workflow store cannot record an item in the app's transaction (only the database driver on Postgres or MySQL can). Items are at least once.")}var aZ=new Set;function f1(Z,$,V,z){let X=`${Z}:${$}`;if(aZ.has(X))return;aZ.add(X),console.warn(`[gemi] step.each "${$}" of workflow ${Z} was started with a count of ${V} and is now given ${z}. It goes on with ${V}: the count is fixed when the step first runs.`)}function l0(Z){return Z==="completed"||Z==="failed"||Z==="cancelled"}var R0=["completed","failed","cancelled"],y1=1000,b1=250,q1=30000;class NZ{queue;registry={};storeInstance;ownFeed;publishing=new Map;published=new Map;tickClass;reportedNames=new Set;constructor(Z){this.queue=Z}get workflows(){return this.registry}use(Z){this.registry={};for(let $ of Z){if($.name==="unset"||!$.name){console.error("A workflow class has no `static name`, so it was not registered. Add one.");continue}if(this.registry[$.name]){console.error(`Two workflows are named "${$.name}" \u2014 the first is registered `+"and this one is not. A workflow's name is its key in storage. Rename one.");continue}this.registry[$.name]=$}}get tickJob(){return this.tickClass??=m1(this),this.tickClass}get store(){if(!this.storeInstance){let Z=this.queue.driver.workflowStore?.();if(!Z||!this.queue.driver.enqueueBatch)throw Error("This queue's driver does not support workflows. The memory and database drivers do.");this.storeInstance=this.publishingStore(Z)}return this.storeInstance}get feed(){let Z=this.queue.boundApplication;if(Z?.bound(d0))return Z.make(d0);return this.ownFeed??=new d0,this.ownFeed}channel(Z){return`gemi:workflow:${Z}`}async update(Z){let $=await this.find(Z);if(!$)return null;let{args:V,result:z,...X}=$;return X}stream(Z,$,V={}){return this.feed.stream(Z,this.channel($),V)}cursor(Z){return this.feed.cursor(this.channel(Z))}async*subscribe(Z,$={}){let V=this.feed.subscribe(this.channel(Z),{signal:$.signal});try{await V.ready();let z=await this.update(Z);if(!z)return;if(yield z,l0(z.status))return;let X=V[Symbol.asyncIterator](),Y=X.next();for(;;){let G=await p1(Y,q1),B;if(G==="timeout")B=await this.update(Z);else{if(G.done)return;Y=X.next(),B=u1(G.value,Z)??await this.update(Z)}if(!B||B.updatedAt<z.updatedAt)continue;if(JSON.stringify(B)===JSON.stringify(z))continue;if(z=B,yield z,l0(z.status))return}}finally{V.close()}}publishingStore(Z){let $=(z)=>void nZ(()=>this.schedulePublish(z)),V={create:(z)=>Z.create(z).then((X)=>{return $(z.id),X}),find:(z,X)=>Z.find(z,X),acquire:(z,X,Y)=>Z.acquire(z,X,Y),renew:(z,X,Y)=>Z.renew(z,X,Y),update:(z,X,Y)=>Z.update(z,X,Y).then((G)=>{return $(z),G})};if(Z.joinsTransaction)V.joinsTransaction=()=>Z.joinsTransaction();if(Z.transaction)V.transaction=(z)=>Z.transaction(z);if(Z.listItems)V.listItems=(...z)=>Z.listItems(...z);if(Z.prune)V.prune=(z)=>Z.prune(z);if(Z.writeSource)V.writeSource=(...z)=>Z.writeSource(...z),V.readSource=(...z)=>Z.readSource(...z),V.deleteSource=(...z)=>Z.deleteSource(...z),V.pruneSources=(...z)=>Z.pruneSources(...z);return V}schedulePublish(Z){if(this.publishing.has(Z))return;let $=Math.max(0,(this.published.get(Z)??0)+b1-Date.now()),V=setTimeout(()=>{this.publishing.delete(Z),this.published.set(Z,Date.now()),this.publish(Z)},$);V.unref?.(),this.publishing.set(Z,V)}async publish(Z){try{let $=await this.update(Z);if(!$)return;if(l0($.status))this.published.delete(Z);await this.feed.publish(this.channel(Z),$)}catch($){console.error(`[gemi] Workflow ${Z}: could not publish its change.`,$)}}async close(){for(let Z of this.publishing.values())clearTimeout(Z);this.publishing.clear(),await this.ownFeed?.close(),this.ownFeed=void 0}start(Z,$){if(Z.name==="unset"||!Z.name)throw Error("Cannot start a workflow with no name");let V=this.store,z={id:Bun.randomUUIDv7(),name:Z.name,args:S0($,`The arguments of ${Z.name}`)??"[]"},X=()=>this.queue.claimSoon(),Y=V.joinsTransaction?.()===!0;if(!Y){if(o(()=>V.create(z).then(X,(Q)=>{console.error(`[gemi] The queue could not record the workflow ${Z.name}, which was held until its transaction committed. The transaction stays committed; the workflow did not start.`,Q)})))return Promise.resolve(z.id)}let G=V.create(z),B=Y&&o(X);return G.then(()=>{if(!B)X();return z.id})}async signal(Z,$,V){if(typeof $!=="string"||$.length===0||$.length>191)throw TypeError("A signal key is a string of 1 to 191 characters.");let z=S0(V,`The payload of signal "${$}"`),X=await this.store.update(Z,{key:$},({workflow:Y,step:G,now:B})=>{if(R0.includes(Y.status)||Y.status==="cancelling")return{result:!1};if(!G)return{result:!0,step:{workflowId:Z,key:$,status:"signalled",attempt:0,output:z,error:null,batchId:null,wakeAt:null,startedAt:null,finishedAt:B,createdAt:B,updatedAt:B}};if(G.status!=="waiting")return{result:!1};return{result:!0,step:{...G,status:"signalled",output:z,wakeAt:G.wakeAt,finishedAt:B},tick:{delayMs:0}}});if(X)this.queue.claimSoon();return X===!0}async cancel(Z){let $=await this.store.update(Z,{allSteps:!0},({workflow:V,steps:z})=>{if(R0.includes(V.status)||V.status==="cancelling")return{result:!1};return{result:!0,workflow:{status:"cancelling"},cancelBatches:z.filter((X)=>X.status==="batching"&&X.batchId!==null).map((X)=>X.batchId),tick:{delayMs:0}}});if($)this.queue.claimSoon();return $===!0}async pause(Z){let $=await this.store.update(Z,{},({workflow:V})=>{if(R0.includes(V.status)||V.status==="cancelling"||V.status==="paused")return{result:!1};return{result:!0,workflow:{status:"paused"}}});if($===!0)this.releaseSlotsOf(Z);return $===!0}async resume(Z){let $=await this.store.update(Z,{},({workflow:V})=>{if(V.status!=="paused")return{result:!1};return{result:!0,workflow:{status:"running",wakeAt:null},tick:{delayMs:0}}});if($)this.queue.claimSoon();return $===!0}async find(Z){let $=await this.store.find(Z);if(!$)return null;let{workflow:V,steps:z}=$,X=[];try{X=JSON.parse(V.args)}catch{}return{id:V.id,name:V.name,status:V.status,args:X,currentStep:V.currentStep,progress:V.progress,result:k1(V.result),error:V.error,steps:await Promise.all(z.map(async(Y)=>{let G={key:Y.key,status:Y.status,attempt:Y.attempt,error:Y.error,batchId:Y.batchId,wakeAt:Y.wakeAt,startedAt:Y.startedAt,finishedAt:Y.finishedAt},B=sZ(Y.output);if(B)return{...G,items:B,progress:B.total===0?1:B.done/B.total};if(Y.batchId===null)return G;let H=await this.queue.driver.findBatch?.(Y.batchId);return H?{...G,progress:H.progress}:G})),createdAt:V.createdAt,updatedAt:V.updatedAt}}async items(Z,$,V={}){let z=this.store;if(!z.listItems)return[];let X=Math.max(1,Math.min(1000,Math.floor(V.limit??100)));return(await z.listItems(Z,$,{statuses:V.status?[V.status]:["failed","skipped"],...V.after===void 0?{}:{after:V.after},limit:X})).map(UZ)}async tick(Z,$){let V=this.store,z=$.$claimed,X=z?`${z.id}:${z.attempt}`:`${crypto.randomUUID()}:1`,Y=Math.max(1,this.queue.config.visibilityTimeout),G=await V.acquire(Z,X,Y);if(G.kind!=="acquired")return;let{workflow:B}=G,H=(P={})=>V.update(Z,{owner:X},()=>({...P,result:void 0,unlock:!0})).then(()=>this.queue.claimSoon()).catch((W)=>{if(!(W instanceof b))throw W});if(R0.includes(B.status)||B.status==="paused"){await H(),await this.releaseSlotsOf(Z,B);return}let Q=this.registry[B.name];if(!Q)return this.unknown(B,$,H);let J;try{J=JSON.parse(B.args)}catch(P){return H({workflow:{status:"failed",error:`The arguments are not JSON: ${N0(P)}`}})}let F=B.status==="cancelling",U;try{U=await this.limitsOf(Q,J)}catch(P){throw await H(),P}if(U.length>0&&!F&&z){let P=this.queue.driver;if(!P.acquireSlots||!P.releaseSlots)return H({workflow:{status:"failed",error:`${B.name} declares concurrency, and this queue's driver has no concurrency slots. The memory and database drivers do.`}});if(!await P.acquireSlots({holder:ZZ(Z),workflowId:Z,job:z,slots:U,recheckMs:this.queue.slotRecheck()}))return $.$outcome={kind:"parked"},H()}let D=setInterval(()=>{V.renew(Z,X,Y).catch((P)=>{console.error(`[gemi] Could not extend the hold on workflow ${Z}.`,P)})},Math.max(1,Math.floor(Y/3)));D.unref?.();let N=new KZ({workflowId:Z,owner:X,store:V,steps:G.steps,cancelling:F,findBatch:(P)=>this.queue.driver.findBatch?.(P,{progress:!1})??Promise.resolve(null),buildBatch:(P,W,A)=>this.queue.buildBatch(P,W.map((T)=>JSON.stringify(T)),{name:A.name,allowFailures:A.allowFailures,finally:{name:m,args:[Z]}}),scheduled:()=>this.queue.claimSoon(),cancelCheckMs:y1,durable:this.queue.durable,throttle:{hit:(P,W,A)=>this.queue.locks.store.hit(P,W,A),refund:(P)=>this.queue.locks.store.refund(P)}});try{let P;try{let A=new Q,T=await(F?A.onCancel(N,...J):A.run(N,...J));P=N.suspension?{kind:"suspended"}:{kind:"completed",result:F?null:S0(T,`The result of ${B.name}`)}}catch(A){if(P=N.suspension||A instanceof t?{kind:"suspended"}:{kind:"failed",error:N0(A)},A instanceof b)N.lost=!0}if(await N.settled(),N.lost)return;if(P.kind==="completed"&&N.suspension)P={kind:"suspended"};let W;if(await V.update(Z,{owner:X},({workflow:A,now:T})=>{let _=this.finish(A,P,N,F,T);return W=_.workflow?.status??A.status,_}),this.queue.claimSoon(),U.length>0&&W!==void 0&&(R0.includes(W)||W==="paused"))await this.releaseSlots(Z)}catch(P){if(P instanceof b)return;throw P}finally{clearInterval(D)}}finish(Z,$,V,z,X){let Y={result:void 0,unlock:!0};if(Z.status==="cancelling"&&!z)return{...Y,tick:{delayMs:0}};if($.kind==="completed")return{...Y,workflow:z?{status:"cancelled",currentStep:null,wakeAt:null}:{status:"completed",result:$.result,progress:1,currentStep:null,wakeAt:null,error:null}};if($.kind==="failed")return{...Y,workflow:{status:z?"cancelled":"failed",error:$.error,wakeAt:null}};let G=V.suspension??{status:"waiting",wakes:[]};if(!z&&(Z.status==="paused"||G.status==="paused"))return Z.status==="paused"?{...Y,workflow:{currentStep:V.current??Z.currentStep}}:{...Y,workflow:{status:"running"},tick:{delayMs:0}};let B={...Y,workflow:{status:z?"cancelling":G.status,currentStep:V.current??Z.currentStep}};if(G.wakes.length>0){let H=Math.min(...G.wakes);if(!(Z.wakeAt!==null&&Z.wakeAt>X&&Z.wakeAt<=H))B.tick={delayMs:Math.max(0,H-X)},B.workflow.wakeAt=H}return B}async limitsOf(Z,$){let V=new Z;if(typeof V.concurrency!=="function")return[];return u0(await V.concurrency(...$),Z.name)}async releaseSlots(Z){try{await this.queue.driver.releaseSlots?.(ZZ(Z))}catch($){console.error(`[gemi] Could not free the concurrency slots of workflow ${Z}.`,$)}}async releaseSlotsOf(Z,$){try{let V=$??(await this.store.find(Z,{steps:!1}))?.workflow,z=V&&this.registry[V.name];if(!V||!z)return;if((await this.limitsOf(z,JSON.parse(V.args))).length>0)await this.releaseSlots(Z)}catch(V){console.error(`[gemi] Could not free the concurrency slots of workflow ${Z}.`,V)}}async unknown(Z,$,V){let z=Date.now()-Z.createdAt;if(this.queue.durable&&z<this.queue.config.unknownJobGrace){if(!this.reportedNames.has(Z.name))this.reportedNames.add(Z.name),console.error(`Left workflow "${Z.name}" for another replica: nothing is registered here under that name.`);await V(),$.release(Math.round(this.queue.config.pollInterval*(1+Math.random())));return}console.error(`Failed workflow ${Z.id}: nothing is registered under the name "${Z.name}". If the class exists, it was not discovered: check that it is under the queue slice's workflowsDir (app/workflows by default), or list it in app/config/queue.ts.`),await V({workflow:{status:"failed",error:`No workflow is registered under the name "${Z.name}".`}})}tickDeadLettered(Z,$){console.error(`[gemi] The tick of workflow ${Z} was dead-lettered.`,$),this.store.update(Z,{},({workflow:V})=>R0.includes(V.status)?{result:void 0}:{result:void 0,workflow:{status:"failed",error:`Its tick job was dead-lettered: ${$.message}`},unlock:!0}).then(()=>this.releaseSlotsOf(Z)).catch(()=>{})}}function m1(Z){return class extends Q0{static name=m;maxAttempts=20;backoff=[1000,5000,15000,30000,60000];async run(V){await Z.tick(V,this)}onDeadletter(V,z){Z.tickDeadLettered(z,V)}}}function k1(Z){try{return n(Z)}catch{return Z}}function u1(Z,$){if(Z.type!=="change")return null;let V=Z.data;if(!V||typeof V!=="object"||V.id!==$||typeof V.updatedAt!=="number")return null;return V}async function p1(Z,$){let V,z=new Promise((X)=>{V=setTimeout(()=>X("timeout"),$)});try{return await Promise.race([Z,z])}finally{clearTimeout(V)}}var __dirname="/home/runner/work/gemi/gemi/packages/gemi/services/queue";function d1(Z=process.env){let $=Z.ROOT_DIR??process.cwd(),V=Z.APP_DIR??`${$}/app`,z=Z.NODE_ENV==="production"?`${$}/dist/server/bootstrap.mjs`:`${V}/bootstrap.ts`,X;try{X=Bun.resolveSync("gemi/app",$)}catch{X=Bun.resolveSync("gemi/app",__dirname)}return{bootstrap:c1(z)?z:void 0,kernel:`${V}/kernel/Kernel.ts`,app:X}}function a1(){let Z=d1(),$=Z.bootstrap?`const { app } = await import(${JSON.stringify(Z.bootstrap)});`:`const { App } = await import(${JSON.stringify(Z.app)});
553
+ const { default: Kernel } = await import(${JSON.stringify(Z.kernel)});
554
+ const app = new App({ kernel: Kernel });
555
+ await app.waitForBoot();`,V=new File([`
556
+ ${$}
557
+ self.onmessage = async (event) => {
558
+ const clone = app.clone()
559
+ let result = null;
560
+ let error = null;
561
+ try {
562
+ result = await clone.dispatchJob(event.data.jobName, event.data.args)
563
+ } catch (err) {
564
+ error = err
565
+ }
566
+ clone.destroy()
567
+ if(error) {
568
+ self.postMessage({error});
569
+ } else {
570
+ self.postMessage({result});
571
+ }
572
+ };
573
+ self.postMessage({ ready: true });
574
+ `],"worker.ts"),z=URL.createObjectURL(V);return new Worker(z)}async function i1(Z,$){let V=a1();try{return await new Promise((z,X)=>{V.onmessage=(Y)=>{let G=Y.data;if(G&&"ready"in G)V.postMessage({jobName:Z,args:$});else if("error"in G)X(G.error);else z(G.result)},V.onerror=(Y)=>{let G=Y.error??Y.message??Y;X(G instanceof Error?G:Error(`The worker thread for ${Z} failed: ${String(G)}`))},V.addEventListener("close",()=>{X(Error(`The worker thread for ${Z} exited before the job finished.`))})})}finally{V.terminate()}}var s1=new w1("gemi.queue"),n1=60000;class Z0{static token="queue";jobs={};config;driver;application;inFlight=new Map;state="idle";looping=!1;claiming;woken=!1;claimFailures=0;resume;unsubscribe;heartbeatTimer;releasedNames=new Set;lockManager;workflowRuntime;constructor(Z={},$={}){if(this.config=oZ(bZ(),Z),this.application=$.application,this.driver=Z3(this.config.driver,this.application),this.useJobs(this.config.jobs),this.config.workflows.length>0)this.useWorkflows(this.config.workflows)}useJobs(Z){this.config.jobs=Z,this.jobs={};for(let $ of Z)this.claim($);this.registerTickJob()}useWorkflows(Z){this.config.workflows=Z,this.workflows.use(Z),this.registerTickJob()}get registeredWorkflows(){return[...this.config.workflows]}get workflows(){return this.workflowRuntime??=new NZ(this),this.workflowRuntime}get boundApplication(){return this.application}registerTickJob(){if(!this.workflowRuntime||Object.keys(this.workflowRuntime.workflows).length===0)return;let Z=this.workflowRuntime.tickJob;if(this.jobs[Z.name]&&this.jobs[Z.name]!==Z){console.error(`A queued job is named "${Z.name}", which the workflow runtime uses. Workflows will not run until it is renamed.`);return}this.jobs[Z.name]=Z}registerJob(Z){this.config.jobs=[...this.config.jobs,Z],this.claim(Z)}claim(Z){if(this.jobs[Z.name]){console.error(`Two queued jobs are named "${Z.name}" \u2014 the first is registered `+"and this one is not, so dispatching either would have run one of them. A class name is the queue's key, so only one job can hold it. Rename one.");return}this.jobs[Z.name]=Z}get registeredJobs(){return[...this.config.jobs]}dispatchJob(Z,$){let V=this.jobs[Z];if(!V)throw Error(`No job is registered under the name "${Z}" in this thread, so it did not run. The thread boots the application from app/kernel/Kernel.ts (or app/bootstrap.ts); check that the job is discovered there.`);return new V().run(...JSON.parse($))}push(Z,$,V={}){let z=this.uniqueKey(Z,$);if(z)return this.pushUnique(Z,$,z,V);let X=this.driver.joinsTransaction?.()===!0;if(!X){let Y=Bun.randomUUIDv7();if(o(()=>this.record(Z,$,{id:Y,reportFailure:!0,committed:!0}).then(()=>{},()=>{})))return Promise.resolve(Y)}return this.record(Z,$,{reportFailure:V.reportFailure,joins:X})}pushBatch(Z,$,V={}){let z=this.buildBatch(Z,$,V),X={id:z.id,total:$.length},Y=this.driver.joinsTransaction?.()===!0;if(!Y){if(o(()=>this.recordBatch(z,{committed:!0}).then(()=>{},()=>{})))return Promise.resolve(X)}return this.recordBatch(z,{joins:Y}).then(()=>X)}buildBatch(Z,$,V={}){if(!this.driver.enqueueBatch)throw Error("This queue's driver does not support batches. The memory and database drivers do.");if(new Z().worker)throw Error(`${Z.name} is a worker job, and a worker job cannot be dispatched in a batch: its thread has no way to report progress or reach the batch.`);if(Z.prototype.uniqueId!==Q0.prototype.uniqueId)throw Error(`${Z.name} is unique (it defines uniqueId), and a unique job cannot be dispatched in a batch: a duplicate would resolve to a job outside the batch, and the batch would wait for it forever.`);let X={};for(let Y of["then","catch","finally"]){let G=V[Y];if(G===void 0)continue;if(typeof G?.name!=="string"||!Array.isArray(G.args))throw Error(`The batch's ${Y} callback is not a job call. Build it with SomeJob.with(...args).`);X[Y]={name:G.name,args:G.args}}return{id:Bun.randomUUIDv7(),name:V.name??null,job:Z.name,args:$,allowFailures:V.allowFailures===!0,callbacks:X}}recordBatch(Z,$){let V=this.driver.enqueueBatch(Z);this.startIfIdle();let z=()=>!this.driver.subscribe&&this.state==="running"&&this.wake(),X=$.joins===!0&&o(z);return V.then(()=>X||z(),(Y)=>{if(!$.committed)return;console.error(`[gemi] The queue driver could not record a batch of ${Z.job}, which was held until its transaction committed. The transaction stays committed; the batch's jobs did not run and will not be retried.`,Y)}),V}async findBatch(Z){if(!this.driver.findBatch)throw Error("This queue's driver does not support batches.");return this.driver.findBatch(Z)}async cancelBatch(Z){if(!this.driver.cancelBatch)throw Error("This queue's driver does not support batches.");let $=await this.driver.cancelBatch(Z);if($)this.claimSoon();return $}get locks(){return this.lockManager??=new eZ(this.resolveLockStore()),this.lockManager}resolveLockStore(){let Z=this.config.locks;if(Z==="auto"){let $=this.driver.lockStore?.();if($)return $;if(this.durable)console.warn('[gemi] The queue driver keeps no locks, so unique jobs, withoutOverlapping and onOneServer only hold within this process. Set the queue slice\'s `locks` to "database" or a LockStore.');return new g0}if(Z==="memory")return new g0;if(Z==="database"||typeof Z==="function"){if(!this.application&&(Z==="database"||Z.length>0))throw Error("The queue's locks need the application they belong to, and this QueueManager was built without one. Pass { application }.");if(Z==="database")return new C0(this.application.make(AZ));return Z(this.application)}if(typeof Z==="string")throw Error(`Unknown queue locks "${Z}". The queue slice's locks is "auto", "memory", "database", a LockStore, or a function returning one.`);return Z}uniqueKey(Z,$){if(Z.prototype.uniqueId===Q0.prototype.uniqueId)return;let V=new Z,z=V.uniqueId(...JSON.parse($));if(z===void 0||z===null||z==="")return;return{key:rZ(Z.name,z),ttl:Math.max(1,V.uniqueFor)}}pushUnique(Z,$,V,z){let X=Bun.randomUUIDv7();if(o(()=>this.recordUnique(Z,$,V,X,{report:!0,committed:!0}).then(()=>{},()=>{})))return Promise.resolve(X);return this.recordUnique(Z,$,V,X,{report:z.reportFailure!==!1,committed:!1})}recordUnique(Z,$,V,z,X){let Y=this.locks.store,G=(async()=>{for(let B=0;B<5;B++){if(await Y.acquire(V.key,z,V.ttl)!==null)try{return await this.record(Z,$,{id:z,reportFailure:!1})}catch(Q){throw await Y.release(V.key,z).catch(()=>{}),Q}let H=await Y.holder(V.key);if(H)return H.owner}throw Error(`The unique key "${V.key}" kept changing hands, so ${Z.name} was not queued.`)})();return G.catch((B)=>{if(!X.report)return;console.error(`[gemi] The queue could not record the unique job ${Z.name}`+(X.committed?", which was held until its transaction committed. The transaction stays committed; the job did not run and will not be retried.":", so it did not run and will not be retried."),B)}),G}async releaseUnique(Z,$,V){if(Z.uniqueId===Q0.prototype.uniqueId)return;try{let z=Z.uniqueId(...$);if(z===void 0||z===null||z==="")return;await this.locks.store.release(rZ(V.name,z),V.id)}catch(z){console.error(`[gemi] Could not free the unique key of ${V.name} (${V.id}); it frees itself after uniqueFor.`,z)}}record(Z,$,V){let z=this.driver.enqueue({name:Z.name,args:$,...V.id===void 0?{}:{id:V.id}});this.startIfIdle();let X=()=>!this.driver.subscribe&&this.state==="running"&&this.wake(),Y=V.joins===!0&&o(X);return z.then(()=>Y||X(),(G)=>{if(V.reportFailure===!1)return;console.error(`[gemi] The queue driver could not record ${Z.name}`+(V.committed?", which was held until its transaction committed. The transaction stays committed; the job did not run and will not be retried.":", so it did not run and will not be retried."),G)}),z}async retryDead(Z){if(!this.driver.retryDead)throw Error("This queue's driver keeps nothing of a dead-lettered job, so there is nothing to retry. The database driver keeps them.");let $=await this.driver.retryDead(Z);if($)this.claimSoon();return $}startIfIdle(){if(this.state==="idle"&&(!this.durable||this.mayClaimHere()))this.start()}claimSoon(){if(this.startIfIdle(),!this.driver.subscribe&&this.state==="running")this.wake()}start(){if(this.state==="running")return;if(this.state="running",this.durable&&this.application&&this.mayClaimHere()&&!r1())globalThis.__gemiDevQueue=this;if(this.unsubscribe=this.driver.subscribe?.(()=>this.wake()),this.looping)return this.wake();s1.runInAsyncScope(()=>void this.loop())}async drain(Z=1/0){if(this.state="stopped",globalThis.__gemiDevQueue===this)globalThis.__gemiDevQueue=void 0;this.unsubscribe?.(),this.unsubscribe=void 0,this.wake();let $,V=new Promise((X)=>{if(Z!==1/0)$=setTimeout(X,Z)}),z=(async()=>{await this.claiming?.catch(()=>{}),await Promise.allSettled([...this.inFlight.values()].map((X)=>X.done))})();return await Promise.race([z,V]),clearTimeout($),{unfinished:[...this.inFlight.values()].map((X)=>({...X.job}))}}stop(){return this.drain(0)}get running(){return this.inFlight.size}async loop(){this.looping=!0;try{await this.claimWhileRunning()}finally{this.looping=!1}}async claimWhileRunning(){while(this.state==="running"){let Z=this.durable&&c0()?0:this.config.concurrency-this.inFlight.size;if(Z>0){this.woken=!1;let $=this.driver.claim(Z,{...this.lease(),registered:{names:Object.keys(this.jobs),graceMs:this.config.unknownJobGrace}});this.claiming=$;let V=[];try{V=await $,this.claimFailures=0}catch(z){this.claimFailures++,console.error(`The queue could not claim jobs from its driver; it will try again in ${this.retryDelay()}ms.`,z)}finally{this.claiming=void 0}for(let z of V)this.execute(z);if(V.length===Z)continue;if(this.woken&&this.inFlight.size<this.config.concurrency)continue}await this.sleep()}}sleep(){return new Promise((Z)=>{let $,V=this.claimFailures>0?this.retryDelay():this.driver.subscribe?void 0:this.config.pollInterval;if(V!==void 0)$=setTimeout(()=>this.wake(),V),$.unref?.();this.resume=()=>{clearTimeout($),Z()}})}retryDelay(){let Z=Math.min(Math.max(0,this.claimFailures-1),30);return Math.min(this.config.pollInterval*2**Z,n1)}wake(){this.woken=!0;let Z=this.resume;this.resume=void 0,Z?.()}get durable(){return!(this.driver instanceof p0)}mayClaimHere(){return!this.application||t1()}lease(){return{visibilityTimeoutMs:this.config.visibilityTimeout}}execute(Z){let $=`${Z.id}:${Z.attempt}`,V=()=>this.run(Z),z=(this.application?tZ.run(this.application,V):V()).catch((X)=>{console.error(`The queue could not record the outcome of ${Z.name}.`,X)}).finally(()=>{this.inFlight.delete($),this.wake()});this.inFlight.set($,{job:Z,done:z}),this.heartbeat()}heartbeat(){let Z=this.driver;if(!Z.heartbeat||this.heartbeatTimer)return;this.heartbeatTimer=setInterval(()=>{if(this.inFlight.size===0){clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0;return}let $=[...this.inFlight.values()].map((V)=>V.job);Z.heartbeat($,this.lease()).catch((V)=>{console.error("The queue could not extend its job leases.",V)})},Math.max(1,Math.floor(this.config.visibilityTimeout/3))),this.heartbeatTimer.unref?.()}async run(Z){let $=this.jobs[Z.name];if(!$){let Q=Date.now()-Z.createdAt;if(this.durable&&Q<this.config.unknownJobGrace){if(!this.releasedNames.has(Z.name))this.releasedNames.add(Z.name),console.error(`Left a queued "${Z.name}" for another replica: nothing is registered here under that name. It is dead-lettered if no replica has run it within unknownJobGrace (${this.config.unknownJobGrace}ms) of its dispatch.`);await this.driver.release(Z,{retryInMs:Math.round(this.config.pollInterval*(1+Math.random()))});return}console.error(`Dropped a queued job: nothing is registered under the name "${Z.name}". If the class exists, it was not `+"discovered \u2014 check that it is under the queue slice's jobsDir "+"(app/jobs by default), or list it in app/config/queue.ts."),await this.driver.fail(Z,{error:`No job is registered under the name "${Z.name}".`,retryInMs:null});return}let V;try{V=new $}catch(Q){console.error(`Dropped a queued ${Z.name}: it could not be constructed.`,Q),await this.driver.fail(Z,{error:`The job could not be constructed: ${String(Q)}`,retryInMs:null});return}let z;try{z=JSON.parse(Z.args)}catch(Q){console.error(`Dropped a queued ${Z.name}: its arguments are not JSON.`,Q),await this.driver.fail(Z,{error:`The arguments are not JSON: ${String(Q)}`,retryInMs:null});return}if(Z.attempt>Math.max(1,V.maxAttempts)){let Q=Error(`${Z.name} was claimed for attempt ${Z.attempt} of ${V.maxAttempts}: an earlier attempt never finished, most likely because the process running it exited. Dead-lettered without running it again.`);RZ(`${Z.name}.onDeadletter`,()=>V.onDeadletter(Q,...z)),await this.driver.fail(Z,{error:Q.message,retryInMs:null}),await this.releaseUnique(V,z,Z);return}if(V.$claimed={...Z},Z.batchId!==void 0){if((await this.driver.findBatch?.(Z.batchId,{progress:!1}))?.cancelledAt!=null){await this.driver.fail(Z,{error:"Its batch was cancelled before it ran.",retryInMs:null,cancelled:!0});return}let J=this.batchHandle(Z);V.batch=J.batch,V.$progress=J.progress}let X,Y;try{Y=await this.admit(V,z,Z)}catch(Q){X=Q}if(!Y&&X===void 0)return;let G;if(Y)try{G=await(V.worker?i1(Z.name,Z.args):V.run(...z))}catch(Q){X=Q}finally{await Y.done()}let B=V.$outcome;if(X===void 0&&B?.kind==="parked")return;if(X===void 0&&B?.kind==="release"){await this.driver.release(Z,{retryInMs:Math.max(0,B.delayMs)});return}if(X===void 0&&B?.kind==="fail")X=B.error;let H=B?.kind==="fail"?B.retry:!0;if(X===void 0)try{V.onSuccess(G,...z)}catch(Q){X=Q}if(X!==void 0){let Q=String(X?.stack??X);if(RZ(`${Z.name}.onFail`,()=>V.onFail(X,...z)),!H||Z.attempt>=V.maxAttempts)RZ(`${Z.name}.onDeadletter`,()=>V.onDeadletter(X,...z)),await this.driver.fail(Z,{error:Q,retryInMs:null}),await this.releaseUnique(V,z,Z);else await this.driver.fail(Z,{error:Q,retryInMs:E0(V.backoff,Z.attempt)});return}await this.driver.complete(Z),await this.releaseUnique(V,z,Z)}batchHandle(Z){let $=Z.batchId,V=this.driver;return{batch:{id:$,cancelled:async()=>(await V.findBatch?.($,{progress:!1}))?.cancelledAt!=null},progress:(z)=>V.reportProgress?.(Z,z)??Promise.resolve()}}async admit(Z,$,V){let z=u0(await Z.concurrency(...$),V.name),X=[Z.throttle(...$)??[]].flat();if(z.length===0&&X.length===0)return{done:async()=>{}};let Y=this.driver,G=async()=>{};if(z.length>0&&Y.acquireSlots&&Y.releaseSlots){if(!await Y.acquireSlots({holder:V.id,job:V,slots:z,recheckMs:this.slotRecheck()}))return;G=()=>Y.releaseSlots(V.id)}else if(z.length>0){let Q=await this.lockSlots(z);if(!Q){await Y.release(V,{retryInMs:Math.round(this.config.pollInterval*(1+Math.random()))});return}G=async()=>{await Promise.all(Q.map((J)=>J.release()))}}let B=this.locks,H=[];try{for(let Q of X){let J=`gemi:throttle:${Q.key}`,F=await B.store.hit(J,Q.limit,Q.window);if(!F.allowed){await Promise.all(H.map((U)=>B.store.refund(U))),await G(),await Y.release(V,{retryInMs:Math.max(1,F.resetInMs)});return}H.push(J)}}catch(Q){throw await G().catch(()=>{}),Q}return{done:async()=>{await G().catch((Q)=>{console.error(`[gemi] Could not free a concurrency slot of ${V.name}.`,Q)})}}}slotRecheck(){return{near:Math.max(1000,this.config.visibilityTimeout),far:3600000}}async lockSlots(Z){let $=this.config.visibilityTimeout,V=[];for(let{key:z,limit:X}of Z){let Y;for(let G=0;G<X&&!Y;G++)Y=await this.locks.acquire(`gemi:concurrency:${z}:${G}`,{ttl:$,renew:!0})??void 0;if(!Y){await Promise.all(V.map((G)=>G.release()));return}V.push(Y)}return V}}function rZ(Z,$){return`gemi:job:${Z}:${String($)}`}function RZ(Z,$){try{$()}catch(V){console.error(`${Z} threw; the job's claim was ended anyway.`,V)}}function r1(){return Bun.env.NODE_ENV==="production"}function t1(){if(!l1)return!1;if(e1())return!0;return process.env.ROOT_DIR!==void 0&&!o1()}function o1(Z=process.env){return(Z.GEMI_QUEUE_CLAIM??"").trim().toLowerCase()==="off"}var Z1=Symbol.for("gemi.queue.worker");function A6(Z=!0){globalThis[Z1]=Z}function e1(){return globalThis[Z1]===!0}function Z3(Z,$){if(Z==="memory")return new p0;if(Z==="database"||typeof Z==="function"){if(!$&&(Z==="database"||Z.length>0))throw Error("The queue driver needs the application it belongs to, and this QueueManager was built without one. Pass { application }.");if(Z==="database")return new o0($.make(AZ));return Z($)}if(typeof Z==="string")throw Error(`Unknown queue driver "${Z}". The queue slice's driver is "memory", "database", a QueueDriver, or a function returning one.`);return Z}var $1=65536,$3=500;class V3{static write(Z,$){return PZ(I0(),Z,$,null)}static async read(Z,$){let[V]=await A0(I0()).readSource(Z,$,$+1);return V?JSON.parse(V.payload):void 0}static async readRange(Z,$,V){return(await A0(I0()).readSource(Z,$,V)).map((X)=>JSON.parse(X.payload))}static delete(Z){return A0(I0()).deleteSource(Z)}static prune(Z){return A0(I0()).pruneSources(r(Z))}}function I0(){return B0(Z0).workflows.store}function A0(Z){if(!Z.writeSource||!Z.readSource||!Z.deleteSource||!Z.pruneSources)throw Error("This queue's workflow store does not keep item sources. The memory and database drivers do.");return Z}async function PZ(Z,$,V,z){if(typeof $!=="string"||$.length===0||$.length>191)throw TypeError(`An item source id is a string of 1 to 191 characters; got ${JSON.stringify($)}.`);A0(Z),await Z.deleteSource($);let X=0,Y=[];for await(let G of V){let B=JSON.stringify(G===void 0?null:G);if(B===void 0)throw TypeError(`Item ${X} of source "${$}" has no JSON form.`);let H=Buffer.byteLength(B,"utf8");if(H>$1)throw RangeError(`Item ${X} of source "${$}" is ${H} bytes as JSON, over the ${$1}-byte limit. Store it elsewhere and keep its id.`);if(Y.push({index:X++,payload:B}),Y.length>=$3)await Z.writeSource($,z,Y),Y=[]}return await Z.writeSource($,z,Y),{id:$,count:X}}function iZ(Z,$,V){A0(Z);let z=new Map,X=new Map,Y=0,G=(B,H)=>{let Q=`${B}:${H}`,J=X.get(Q);if(!J)J=Z.readSource($.id,B,H).then((F)=>{for(let U of F)z.set(U.index,U.payload);X.delete(Q)},(F)=>{throw X.delete(Q),F}),X.set(Q,J);return J};return async(B)=>{if(!z.has(B)){let Q=B-B%V,J=Math.min(Q+V,$.count);if(X.has(`${Q}:${J}`))await X.get(`${Q}:${J}`);else if(B>=Y)Y=Math.max(Y,J),await G(Q,J);if(!z.has(B))await G(B,B+1)}let H=z.get(B);if(z.delete(B),H===void 0)throw Error(`Item source "${$.id}" has no item at index ${B}.`);return JSON.parse(H)}}
575
+ export{C0 as se,g0 as te,n0 as ue,IZ as ve,o0 as we,W3 as xe,bZ as ye,e0 as ze,p0 as Ae,$1 as Be,V3 as Ce,XZ as De,YZ as Ee,GZ as Fe,BZ as Ge,KZ as He,l0 as Ie,NZ as Je,Z0 as Ke,t1 as Le,o1 as Me,A6 as Ne,e1 as Oe,Q0 as Pe};
576
+
577
+ //# debugId=2686F3191F5B372064756E2164756E21