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.
- package/dist/ai/index.js +1 -1
- package/dist/{chunk-ejvjn9tq.js → chunk-fn166jp3.js} +1 -1
- package/dist/{chunk-nqjchwdj.js → chunk-ke1q6hfm.js} +1 -1
- package/dist/chunk-p1ern8r4.js +577 -0
- package/dist/chunk-p1ern8r4.js.map +27 -0
- package/dist/{chunk-y8dpexn0.js → chunk-qtczhd81.js} +2 -2
- package/dist/{chunk-y8dpexn0.js.map → chunk-qtczhd81.js.map} +1 -1
- package/dist/{chunk-t7ppe7gt.js → chunk-qvxs1vjh.js} +1 -1
- package/dist/{chunk-dy01vy29.js → chunk-rw45xz3f.js} +3 -3
- package/dist/{chunk-dy01vy29.js.map → chunk-rw45xz3f.js.map} +3 -3
- package/dist/{chunk-qvspq5tm.js → chunk-sqyf0gey.js} +1 -1
- package/dist/console/run.js +1 -1
- package/dist/kernel/index.js +1 -1
- package/dist/server/index.js +1 -1
- package/dist/services/index.d.ts +2 -1
- package/dist/services/index.d.ts.map +1 -1
- package/dist/services/index.js +1 -1
- package/dist/services/queue/DatabaseQueueDriver.d.ts +16 -0
- package/dist/services/queue/DatabaseQueueDriver.d.ts.map +1 -1
- package/dist/services/queue/DatabaseSlots.d.ts +100 -0
- package/dist/services/queue/DatabaseSlots.d.ts.map +1 -0
- package/dist/services/queue/Job.d.ts +20 -3
- package/dist/services/queue/Job.d.ts.map +1 -1
- package/dist/services/queue/MemoryQueueDriver.d.ts +11 -1
- package/dist/services/queue/MemoryQueueDriver.d.ts.map +1 -1
- package/dist/services/queue/QueueDriver.d.ts +24 -0
- package/dist/services/queue/QueueDriver.d.ts.map +1 -1
- package/dist/services/queue/QueueManager.d.ts +28 -8
- package/dist/services/queue/QueueManager.d.ts.map +1 -1
- package/dist/services/queue/slots.d.ts +111 -0
- package/dist/services/queue/slots.d.ts.map +1 -0
- package/dist/services/queue/work.js +1 -1
- package/dist/services/queue/workflow/MemoryWorkflowStore.d.ts +2 -0
- package/dist/services/queue/workflow/MemoryWorkflowStore.d.ts.map +1 -1
- package/dist/services/queue/workflow/Workflow.d.ts +16 -0
- package/dist/services/queue/workflow/Workflow.d.ts.map +1 -1
- package/dist/services/queue/workflow/WorkflowRuntime.d.ts +10 -0
- package/dist/services/queue/workflow/WorkflowRuntime.d.ts.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-9kdqdjdf.js +0 -521
- package/dist/chunk-9kdqdjdf.js.map +0 -25
- /package/dist/{chunk-ejvjn9tq.js.map → chunk-fn166jp3.js.map} +0 -0
- /package/dist/{chunk-nqjchwdj.js.map → chunk-ke1q6hfm.js.map} +0 -0
- /package/dist/{chunk-t7ppe7gt.js.map → chunk-qvxs1vjh.js.map} +0 -0
- /package/dist/{chunk-qvspq5tm.js.map → chunk-sqyf0gey.js.map} +0 -0
package/dist/chunk-9kdqdjdf.js
DELETED
|
@@ -1,521 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{Nk as n,Ok as x0,Qk as iZ,al as l0}from"./chunk-tac25cnj.js";import{cl as aZ}from"./chunk-0k2r6bep.js";import{el as MZ,fl as vZ,gl as LZ,il as t,jl as cZ,ll as W0,ul as j0}from"./chunk-0av1gyns.js";import{Nl as FZ}from"./chunk-zmt5kdpb.js";import{im as dZ,lm as B0}from"./chunk-37209psn.js";import{um as w0}from"./chunk-6r7956dh.js";class L0{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 $1(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),Q;if(this.dialect==="sqlite"){let J=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
|
-
`;Q=Y0(J)>0}else Q=(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(!Q)throw new x0(Z,V);return z()},Y=this.connection;if(Y===void 0)return await this.sql.begin((G)=>X(G));return j0(this.sql,(G)=>LZ(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,[Q]=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(Q?.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 $1(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 o="gemi.WorkflowTick",i0=262144;function h0(Z,$){let V=(z)=>z.slice(0,z.lastIndexOf(":"));return V(Z)===V($)}class f 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 V1=["completed","failed","cancelled"];class s0{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)=>j0(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($)W0(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:o,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:CZ(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 y0(X)>0}update(Z,$,V){let z=async(Y)=>{let G=await this.lock(Y,Z);if(!G)return;if($.owner!==void 0&&G.lockedBy!==$.owner)throw new f(Z);let B=$.key===void 0?null:await this.stepOf(Y,Z,$.key),Q=$.allSteps?await this.stepsOf(Y,Z):[],J=$.items===void 0?[]:await this.itemsOf(Y,Z,$.items,["running","retrying"],-1,null),H=V({workflow:G,step:B,steps:Q,items:J,now:Date.now()});if(H.step){let K=H.step.key===$.key?B!==null:await this.stepOf(Y,Z,H.step.key)!==null;await this.writeStep(Y,H.step,K)}if(H.items)await this.writeItems(Y,Z,H.items);if(H.batch)await this.db.insertBatch(Y,H.batch);for(let K of H.cancelBatches??[])await this.db.cancelBatch(Y,K);let U={...G,...H.workflow},D=H.unlock===!0,_=Y`
|
|
92
|
-
status = ${U.status}, current_step = ${U.currentStep},
|
|
93
|
-
progress = ${this.db.fraction(Y,U.progress)}, result = ${U.result},
|
|
94
|
-
error = ${U.error}, wake_at = ${this.db.timeOrNull(Y,U.wakeAt)},
|
|
95
|
-
updated_at = ${this.db.now(Y)}
|
|
96
|
-
`;if(D)await Y`
|
|
97
|
-
UPDATE ${this.workflows(Y)}
|
|
98
|
-
SET ${_}, locked_by = NULL, locked_until = NULL, retick = 0
|
|
99
|
-
WHERE id = ${Z}
|
|
100
|
-
`;else await Y`UPDATE ${this.workflows(Y)} SET ${_} WHERE id = ${Z}`;let F=(K)=>this.db.insertJob(Y,{name:o,args:JSON.stringify([Z]),delayMs:Math.max(0,Math.round(K))});if(H.tick)await F(H.tick.delayMs);if(D&&G.retick)await F(0);return H.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 y0(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(!C0(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(!C0(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 q0(z`
|
|
118
|
-
INSERT INTO ${this.sources(z)} (source_id, idx, workflow_id, payload, created_at)
|
|
119
|
-
VALUES ${G.reduce((B,Q)=>z`${B}, ${Q}`)}
|
|
120
|
-
`,this.sourceTable)}}async readSource(Z,$,V){await this.db.configure();let z=this.db.sql;return(await q0(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 q0($`DELETE FROM ${this.sources($)} WHERE source_id = ${Z}`,this.sourceTable);return y0(V)}async pruneSources(Z){await this.db.configure();let $=this.db.sql,V=await q0($`
|
|
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 y0(V)}endedClause(Z){return Z`status IN (${V1.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 Q=Y.slice(B,B+500).map((J)=>Z`${J}`);await f0(Z`
|
|
129
|
-
DELETE FROM ${this.items(Z)}
|
|
130
|
-
WHERE workflow_id = ${$} AND step_key = ${X}
|
|
131
|
-
AND idx IN (${Q.reduce((J,H)=>Z`${J}, ${H}`)})
|
|
132
|
-
`,this.itemTable)}let G=V.insert??[];for(let B=0;B<G.length;B+=200){let Q=z.now(Z),J=G.slice(B,B+200).map((H)=>Z`(
|
|
133
|
-
${$}, ${X}, ${H.index}, ${H.key}, ${H.status}, ${H.attempt},
|
|
134
|
-
${H.error}, ${H.output}, ${z.timeOrNull(Z,H.wakeAt)},
|
|
135
|
-
${z.timeOrNull(Z,H.startedAt)}, ${z.timeOrNull(Z,H.finishedAt)}, ${Q}, ${Q}
|
|
136
|
-
)`);await f0(Z`
|
|
137
|
-
INSERT INTO ${this.items(Z)}
|
|
138
|
-
(workflow_id, step_key, idx, item_key, status, attempt, error, output, wake_at,
|
|
139
|
-
started_at, finished_at, created_at, updated_at)
|
|
140
|
-
VALUES ${J.reduce((H,U)=>Z`${H}, ${U}`)}
|
|
141
|
-
`,this.itemTable)}for(let B of V.update??[])await f0(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((Q)=>Z`${Q}`).reduce((Q,J)=>Z`${Q}, ${J}`);return(await f0(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(z1)}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]?CZ(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?WZ(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(WZ)}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 w(Z){return Z==null?null:String(Z)}function CZ(Z){return{id:String(Z.id),name:String(Z.name),args:String(Z.args),status:String(Z.status),currentStep:w(Z.current_step),progress:Number(Z.progress??0),result:w(Z.result),error:w(Z.error),wakeAt:e(Z.wake_at),lockedBy:w(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 WZ(Z){return{workflowId:String(Z.workflow_id),key:String(Z.key),status:String(Z.status),attempt:Number(Z.attempt??0),output:w(Z.output),error:w(Z.error),batchId:w(Z.batch_id),wakeAt: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 z1(Z){return{workflowId:String(Z.workflow_id),step:String(Z.step_key),index:Number(Z.idx),key:w(Z.item_key),status:String(Z.status),attempt:Number(Z.attempt??0),error:w(Z.error),output:w(Z.output),wakeAt: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 y0(Z){let $=Z;return Math.max(Number($.count??0),Number($.affectedRows??0))}function C0(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(!C0(V))throw V;throw Error(`Workflows need the "${$}" table, and the database says it is missing. Add the GemiWorkflow and GemiWorkflowStep models from the docs (docs/workflows.md#the-workflow-tables) and migrate, or call the queue driver's createTable().`,{cause:V})}}async function f0(Z,$){try{return await Z}catch(V){if(!C0(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 q0(Z,$){try{return await Z}catch(V){if(!C0(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 OZ(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 EZ(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 SZ(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 b0(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 Q=G0(z);return{record:z,calls:X.map((J)=>({name:J.name,args:JSON.stringify([...J.args,Q])}))}}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 a(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 TZ=200,X1="Its batch was cancelled before it ran.";class r0{table;batchTable;workflowTable;workflowStepTable;workflowItemTable;workflowSourceTable;workflows;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`),Q=$.workflowSourceTable??(X?"gemi_workflow_sources":`${V}_workflow_sources`);for(let H of[V,z,Y,G,B,Q])if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(H))throw Error(`The queue table name "${H}" is not a plain identifier. Use letters, digits and underscores.`);let J=$.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=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,...$]=Y1(this.dialect,this.table);if(await this.sql.unsafe(Z),!await this.hasBatchColumns())for(let V of G1(this.dialect,this.table))await this.sql.unsafe(V);for(let V of $)await this.sql.unsafe(V);for(let V of B1(this.dialect,this.batchTable))await this.sql.unsafe(V);for(let V of OZ(this.dialect,this.workflowTable,this.workflowStepTable))await this.sql.unsafe(V);for(let V of EZ(this.dialect,this.workflowItemTable))await this.sql.unsafe(V);for(let V of SZ(this.dialect,this.workflowSourceTable))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(jZ(Z))return!1;throw Z}}enqueue(Z){let $=this.transaction(),V=this.insert($??this.sql,Z);if($)W0(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`
|
|
293
|
-
INSERT INTO ${this.name(Z)}
|
|
294
|
-
(id, name, payload, status, attempts, available_at, created_at, updated_at)
|
|
295
|
-
VALUES
|
|
296
|
-
(${X}, ${$}, ${V}, 'pending', 0, ${Y} + ${this.ms(Z,z)}, ${Y}, ${Y})
|
|
297
|
-
`,X}lockStore(){return new L0({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=MZ();if(Z===void 0||vZ()!==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 $`
|
|
298
|
-
DELETE FROM ${this.name($)}
|
|
299
|
-
WHERE id = ${Z.id} AND status = 'claimed' AND attempts = ${Z.attempt}
|
|
300
|
-
`}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`
|
|
301
|
-
UPDATE ${this.name(V)}
|
|
302
|
-
SET status = 'dead', lease_expires_at = NULL, last_error = ${$.error},
|
|
303
|
-
updated_at = ${z}
|
|
304
|
-
WHERE id = ${Z.id} AND status = 'claimed' AND attempts = ${Z.attempt}
|
|
305
|
-
`;return}await V`
|
|
306
|
-
UPDATE ${this.name(V)}
|
|
307
|
-
SET status = 'pending', available_at = ${z} + ${this.ms(V,$.retryInMs)},
|
|
308
|
-
lease_expires_at = NULL, last_error = ${$.error}, updated_at = ${z}
|
|
309
|
-
WHERE id = ${Z.id} AND status = 'claimed' AND attempts = ${Z.attempt}
|
|
310
|
-
`}async release(Z,$){let V=this.sql,z=this.now(V);await V`
|
|
311
|
-
UPDATE ${this.name(V)}
|
|
312
|
-
SET status = 'pending', attempts = attempts - 1,
|
|
313
|
-
available_at = ${z} + ${this.ms(V,$.retryInMs)},
|
|
314
|
-
lease_expires_at = NULL, updated_at = ${z}
|
|
315
|
-
WHERE id = ${Z.id} AND status = 'claimed' AND attempts = ${Z.attempt}
|
|
316
|
-
`}async heartbeat(Z,$){await this.configure();let V=this.sql;await Promise.all(Z.map((z)=>{let X=this.now(V);return V`
|
|
317
|
-
UPDATE ${this.name(V)}
|
|
318
|
-
SET lease_expires_at = ${X} + ${this.ms(V,$.visibilityTimeoutMs)},
|
|
319
|
-
updated_at = ${X}
|
|
320
|
-
WHERE id = ${z.id} AND status = 'claimed' AND attempts = ${z.attempt}
|
|
321
|
-
`}))}async retryDead(Z){await this.configure();let $=this.sql,[V]=await $`
|
|
322
|
-
SELECT * FROM ${this.name($)} WHERE id = ${Z} AND status = 'dead'
|
|
323
|
-
`;if(!V||V.batch_id!=null)return!1;let z=this.now($),X=await $`
|
|
324
|
-
UPDATE ${this.name($)}
|
|
325
|
-
SET status = 'pending', attempts = 0, available_at = ${z}, lease_expires_at = NULL,
|
|
326
|
-
updated_at = ${z}
|
|
327
|
-
WHERE id = ${Z} AND status = 'dead'
|
|
328
|
-
`;return U0(X)>0}async prune(Z){await this.configure();let $=this.sql,V=await $`
|
|
329
|
-
DELETE FROM ${this.name($)}
|
|
330
|
-
WHERE status = 'dead' AND updated_at <= ${this.now($)} - ${this.ms($,Z)}
|
|
331
|
-
`;return U0(V)}enqueueBatch(Z){let $=this.transaction(),V=$?this.insertBatch($,Z):this.atomically((z)=>this.insertBatch(z,Z));if($)W0(V);return V}async insertBatch(Z,$){await this.configure();let V=await this.clock(Z),z=b0({...$,total:$.args.length,now:V}),{record:X,calls:Y}=F0(z,z,V);await n0(Z`
|
|
332
|
-
INSERT INTO ${this.batches(Z)}
|
|
333
|
-
(id, name, total, pending, succeeded, failed, cancelled, failed_job_ids, options,
|
|
334
|
-
cancelled_at, finished_at, created_at, updated_at)
|
|
335
|
-
VALUES
|
|
336
|
-
(${X.id}, ${X.name}, ${X.total}, ${X.pending}, 0, 0, 0,
|
|
337
|
-
'[]', ${J1(X)}, NULL, ${this.timeOrNull(Z,X.finishedAt)},
|
|
338
|
-
${this.ms(Z,V)}, ${this.ms(Z,V)})
|
|
339
|
-
`,this.batchTable);let G=this.ms(Z,V);for(let B=0;B<$.args.length;B+=TZ){let Q=$.args.slice(B,B+TZ).map((J)=>Z`(${Bun.randomUUIDv7()}, ${$.job}, ${J}, 'pending', 0, ${G}, ${G}, ${G}, ${$.id}, 0)`).reduce((J,H)=>Z`${J}, ${H}`);await n0(Z`
|
|
340
|
-
INSERT INTO ${this.name(Z)}
|
|
341
|
-
(id, name, payload, status, attempts, available_at, created_at, updated_at, batch_id, progress)
|
|
342
|
-
VALUES ${Q}
|
|
343
|
-
`,this.table)}for(let B of Y)await this.insert(Z,B)}async findBatch(Z,$={}){await this.configure();let V=this.sql,[z]=await n0(V`SELECT * FROM ${this.batches(V)} WHERE id = ${Z}`,this.batchTable);if(!z)return null;let X=IZ(z);if($.progress===!1||X.pending===0)return G0(X);let[Y]=await V`
|
|
344
|
-
SELECT COALESCE(SUM(progress), 0) AS running FROM ${this.name(V)}
|
|
345
|
-
WHERE batch_id = ${Z} AND status IN ('pending', 'claimed')
|
|
346
|
-
`;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 s0({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}async reportProgress(Z,$){let V=a($);await this.configure();let z=this.sql;await z`
|
|
347
|
-
UPDATE ${this.name(z)} SET progress = ${this.fraction(z,V)}
|
|
348
|
-
WHERE id = ${Z.id} AND status = 'claimed' AND attempts = ${Z.attempt}
|
|
349
|
-
`}async pruneBatches(Z){await this.configure();let $=this.sql,V=await $`
|
|
350
|
-
DELETE FROM ${this.batches($)}
|
|
351
|
-
WHERE finished_at IS NOT NULL AND finished_at <= ${this.now($)} - ${this.ms($,Z)}
|
|
352
|
-
`;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 H=await X`DELETE FROM ${this.name(X)} WHERE ${G}`;if(U0(H)===0||!Y)return;return this.count(X,Y,"succeeded",Z.id)}let Q=V.cancelled===!0||V.retryInMs!==null&&Y!==void 0&&Y.cancelledAt!==null;if(V.retryInMs!==null&&!Q){await X`
|
|
353
|
-
UPDATE ${this.name(X)}
|
|
354
|
-
SET status = 'pending', available_at = ${B} + ${this.ms(X,V.retryInMs)},
|
|
355
|
-
lease_expires_at = NULL, last_error = ${V.error}, progress = 0,
|
|
356
|
-
updated_at = ${B}
|
|
357
|
-
WHERE ${G}
|
|
358
|
-
`;return}let J=await X`
|
|
359
|
-
UPDATE ${this.name(X)}
|
|
360
|
-
SET status = 'dead', lease_expires_at = NULL, last_error = ${V.error},
|
|
361
|
-
updated_at = ${B}
|
|
362
|
-
WHERE ${G}
|
|
363
|
-
`;if(U0(J)===0||!Y)return;return this.count(X,Y,Q?"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`
|
|
364
|
-
UPDATE ${this.name(Z)}
|
|
365
|
-
SET status = 'dead', last_error = ${X1}, updated_at = ${V}
|
|
366
|
-
WHERE batch_id = ${$} AND status = 'pending'
|
|
367
|
-
`;return U0(z)}async saveBatch(Z,$,V,z){let{record:X,calls:Y}=F0($,V,z);await Z`
|
|
368
|
-
UPDATE ${this.batches(Z)}
|
|
369
|
-
SET pending = ${X.pending}, succeeded = ${X.succeeded}, failed = ${X.failed},
|
|
370
|
-
cancelled = ${X.cancelled}, failed_job_ids = ${JSON.stringify(X.failedJobIds)},
|
|
371
|
-
cancelled_at = ${this.timeOrNull(Z,X.cancelledAt)},
|
|
372
|
-
finished_at = ${this.timeOrNull(Z,X.finishedAt)}, updated_at = ${this.ms(Z,z)}
|
|
373
|
-
WHERE id = ${X.id}
|
|
374
|
-
`;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]?IZ(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`
|
|
375
|
-
WITH next AS (
|
|
376
|
-
SELECT id FROM ${Y}
|
|
377
|
-
WHERE ${this.claimable(V,$)}
|
|
378
|
-
ORDER BY available_at, id
|
|
379
|
-
LIMIT ${Z}
|
|
380
|
-
FOR UPDATE SKIP LOCKED
|
|
381
|
-
)
|
|
382
|
-
UPDATE ${Y} AS job
|
|
383
|
-
SET status = 'claimed', attempts = job.attempts + 1, claimed_at = ${z},
|
|
384
|
-
lease_expires_at = ${z} + ${X}, updated_at = ${z}
|
|
385
|
-
FROM next
|
|
386
|
-
WHERE job.id = next.id
|
|
387
|
-
RETURNING job.*
|
|
388
|
-
`;return await V`
|
|
389
|
-
UPDATE ${Y}
|
|
390
|
-
SET status = 'claimed', attempts = attempts + 1, claimed_at = ${z},
|
|
391
|
-
lease_expires_at = ${z} + ${X}, updated_at = ${z}
|
|
392
|
-
WHERE id IN (
|
|
393
|
-
SELECT id FROM ${Y}
|
|
394
|
-
WHERE ${this.claimable(V,$)}
|
|
395
|
-
ORDER BY available_at, id
|
|
396
|
-
LIMIT ${Z}
|
|
397
|
-
)
|
|
398
|
-
RETURNING *
|
|
399
|
-
`}async claimLocking(Z,$){let V=await this.sql.reserve(),[z]=await V`
|
|
400
|
-
SELECT @@transaction_isolation AS level
|
|
401
|
-
`;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`
|
|
402
|
-
SELECT ${Y} FROM ${X}
|
|
403
|
-
WHERE status = 'pending' AND available_at <= ${this.now(z)}
|
|
404
|
-
AND ${this.runnable(z,V,"available_at")}
|
|
405
|
-
ORDER BY available_at, id
|
|
406
|
-
LIMIT ${$}
|
|
407
|
-
FOR UPDATE SKIP LOCKED
|
|
408
|
-
`;if(G.length<$){let B=await z`
|
|
409
|
-
SELECT ${Y} FROM ${X}
|
|
410
|
-
WHERE status = 'claimed' AND lease_expires_at <= ${this.now(z)}
|
|
411
|
-
AND ${this.runnable(z,V,"lease_expires_at")}
|
|
412
|
-
ORDER BY lease_expires_at, id
|
|
413
|
-
LIMIT ${$-G.length}
|
|
414
|
-
FOR UPDATE SKIP LOCKED
|
|
415
|
-
`;G.push(...B)}for(let B of G){let Q=this.now(z);await z`
|
|
416
|
-
UPDATE ${X}
|
|
417
|
-
SET status = 'claimed', attempts = attempts + 1, claimed_at = ${Q},
|
|
418
|
-
lease_expires_at = ${Q} + ${this.ms(z,V.visibilityTimeoutMs)},
|
|
419
|
-
updated_at = ${Q}
|
|
420
|
-
WHERE id = ${B.id}
|
|
421
|
-
`}return G.map((B)=>({...B,attempts:Number(B.attempts)+1}))})}claimable(Z,$){let V=this.now(Z);return Z`(
|
|
422
|
-
(status = 'pending' AND available_at <= ${V}
|
|
423
|
-
AND ${this.runnable(Z,$,"available_at")})
|
|
424
|
-
OR (status = 'claimed' AND lease_expires_at <= ${V}
|
|
425
|
-
AND ${this.runnable(Z,$,"lease_expires_at")})
|
|
426
|
-
)`}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 Y1(Z,$){if(Z==="mysql"||Z==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${$}\` (
|
|
427
|
-
\`id\` VARCHAR(191) NOT NULL,
|
|
428
|
-
\`name\` VARCHAR(191) NOT NULL,
|
|
429
|
-
\`payload\` LONGTEXT NOT NULL,
|
|
430
|
-
\`status\` VARCHAR(191) NOT NULL,
|
|
431
|
-
\`attempts\` INTEGER NOT NULL DEFAULT 0,
|
|
432
|
-
\`available_at\` BIGINT NOT NULL,
|
|
433
|
-
\`claimed_at\` BIGINT NULL,
|
|
434
|
-
\`lease_expires_at\` BIGINT NULL,
|
|
435
|
-
\`last_error\` LONGTEXT NULL,
|
|
436
|
-
\`created_at\` BIGINT NOT NULL,
|
|
437
|
-
\`updated_at\` BIGINT NOT NULL,
|
|
438
|
-
\`batch_id\` VARCHAR(191) NULL,
|
|
439
|
-
\`progress\` DOUBLE NULL,
|
|
440
|
-
|
|
441
|
-
INDEX \`${$}_status_available_at_idx\`(\`status\`, \`available_at\`),
|
|
442
|
-
INDEX \`${$}_status_lease_expires_at_idx\`(\`status\`, \`lease_expires_at\`),
|
|
443
|
-
INDEX \`${$}_batch_id_idx\`(\`batch_id\`),
|
|
444
|
-
PRIMARY KEY (\`id\`)
|
|
445
|
-
) 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"?"":`,
|
|
446
|
-
|
|
447
|
-
CONSTRAINT "${$}_pkey" PRIMARY KEY ("id")`;return[`CREATE TABLE IF NOT EXISTS "${$}" (
|
|
448
|
-
${V}
|
|
449
|
-
"name" TEXT NOT NULL,
|
|
450
|
-
"payload" TEXT NOT NULL,
|
|
451
|
-
"status" TEXT NOT NULL,
|
|
452
|
-
"attempts" INTEGER NOT NULL DEFAULT 0,
|
|
453
|
-
"available_at" BIGINT NOT NULL,
|
|
454
|
-
"claimed_at" BIGINT,
|
|
455
|
-
"lease_expires_at" BIGINT,
|
|
456
|
-
"last_error" TEXT,
|
|
457
|
-
"created_at" BIGINT NOT NULL,
|
|
458
|
-
"updated_at" BIGINT NOT NULL,
|
|
459
|
-
"batch_id" TEXT,
|
|
460
|
-
"progress" ${Z==="sqlite"?"REAL":"DOUBLE PRECISION"}${z}
|
|
461
|
-
)`,`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 G1(Z,$){if(Z==="mysql"||Z==="mariadb")return[`ALTER TABLE \`${$}\` ADD COLUMN \`batch_id\` VARCHAR(191) NULL,
|
|
462
|
-
ADD COLUMN \`progress\` DOUBLE NULL,
|
|
463
|
-
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,
|
|
464
|
-
ADD COLUMN IF NOT EXISTS "progress" ${V}`,`CREATE INDEX IF NOT EXISTS "${$}_batch_id_idx" ON "${$}"("batch_id")`]}function B1(Z,$){if(Z==="mysql"||Z==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${$}\` (
|
|
465
|
-
\`id\` VARCHAR(191) NOT NULL,
|
|
466
|
-
\`name\` VARCHAR(191) NULL,
|
|
467
|
-
\`total\` INTEGER NOT NULL,
|
|
468
|
-
\`pending\` INTEGER NOT NULL,
|
|
469
|
-
\`succeeded\` INTEGER NOT NULL DEFAULT 0,
|
|
470
|
-
\`failed\` INTEGER NOT NULL DEFAULT 0,
|
|
471
|
-
\`cancelled\` INTEGER NOT NULL DEFAULT 0,
|
|
472
|
-
\`failed_job_ids\` LONGTEXT NOT NULL,
|
|
473
|
-
\`options\` LONGTEXT NOT NULL,
|
|
474
|
-
\`cancelled_at\` BIGINT NULL,
|
|
475
|
-
\`finished_at\` BIGINT NULL,
|
|
476
|
-
\`created_at\` BIGINT NOT NULL,
|
|
477
|
-
\`updated_at\` BIGINT NOT NULL,
|
|
478
|
-
|
|
479
|
-
PRIMARY KEY (\`id\`)
|
|
480
|
-
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci`];let V=Z==="sqlite"?'"id" TEXT NOT NULL PRIMARY KEY,':'"id" TEXT NOT NULL,',z=Z==="sqlite"?"":`,
|
|
481
|
-
|
|
482
|
-
CONSTRAINT "${$}_pkey" PRIMARY KEY ("id")`;return[`CREATE TABLE IF NOT EXISTS "${$}" (
|
|
483
|
-
${V}
|
|
484
|
-
"name" TEXT,
|
|
485
|
-
"total" INTEGER NOT NULL,
|
|
486
|
-
"pending" INTEGER NOT NULL,
|
|
487
|
-
"succeeded" INTEGER NOT NULL DEFAULT 0,
|
|
488
|
-
"failed" INTEGER NOT NULL DEFAULT 0,
|
|
489
|
-
"cancelled" INTEGER NOT NULL DEFAULT 0,
|
|
490
|
-
"failed_job_ids" TEXT NOT NULL,
|
|
491
|
-
"options" TEXT NOT NULL,
|
|
492
|
-
"cancelled_at" BIGINT,
|
|
493
|
-
"finished_at" BIGINT,
|
|
494
|
-
"created_at" BIGINT NOT NULL,
|
|
495
|
-
"updated_at" BIGINT NOT NULL${z}
|
|
496
|
-
)`]}function IZ(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 J1(Z){return JSON.stringify({allowFailures:Z.allowFailures,callbacks:Z.callbacks})}function jZ(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 n0(Z,$){try{return await Z}catch(V){if(!jZ(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 Y2(Z){return Z}function xZ(){return{jobs:[],jobsDir:"app/jobs",workflows:[],workflowsDir:"app/workflows",concurrency:1,driver:"memory",visibilityTimeout:300000,pollInterval:1000,unknownJobGrace:3600000,locks:"auto"}}var Q1=86400000;class t0{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(Q1);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}async update(Z,$,V){let z=this.workflows.get(Z);if(!z)return;if($.owner!==void 0&&z.lockedBy!==$.owner)throw new f(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 Q=X.get(B.step.key);X.set(B.step.key,{...B.step,createdAt:Q?.createdAt??G,updatedAt:G})}if(B.items){let Q=this.rowsOf(Z,B.items.step);for(let J of B.items.delete??[])Q.all.delete(J),Q.open.delete(J);for(let J of[...B.items.insert??[],...B.items.update??[]]){let H=Q.all.get(J.index);if(Q.all.set(J.index,{...J,step:B.items.step,createdAt:H?.createdAt??G,updatedAt:G}),J.status==="running"||J.status==="retrying")Q.open.add(J.index);else Q.open.delete(J.index)}}if(B.batch)this.queue.enqueueBatch(B.batch);for(let Q of B.cancelBatches??[])this.queue.cancelBatch(Q);if(B.workflow)Object.assign(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((J)=>J==="running"||J==="retrying")?[...Y.open]:[...Y.all.keys()],Q=[];for(let J of B.sort((H,U)=>H-U)){if(J<=z)continue;let H=Y.all.get(J);if(!V.includes(H.status))continue;if(Q.push({...H}),Q.length>=X)break}return Q}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:o,args:JSON.stringify([Z]),delayMs:Math.max(0,Math.round($))})}}var H1=86400000;class u0{entries=new Map;batches=new Map;workflows;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=b0({...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 t0({enqueue:(Z)=>{this.add(Z),this.changed()},enqueueBatch:(Z)=>this.recordBatch(Z),cancelBatch:(Z)=>void this.cancelBatchNow(Z)}),this.workflows}async reportProgress(Z,$){let V=this.current(Z);if(V)V.progress=a($)}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>H1)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 v1}from"async_hooks";import{existsSync as j1}from"fs";import{isMainThread as x1}from"worker_threads";class J0{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 $=a(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 O0(Z,$){let V=Array.isArray(Z)?Z[Math.min($,Z.length)-1]:Z;return Math.max(0,V??0)}class ZZ extends Error{step;batch;summary;constructor(Z,$,V,z){super($);this.step=Z;this.batch=V;this.summary=z;this.name="StepFailedError"}}class $Z extends Error{step;constructor(Z){super(`No signal "${Z}" arrived before its timeout.`);this.step=Z;this.name="WaitTimeoutError"}}class VZ extends Error{constructor(Z,$){super(`Step "${Z}" took longer than its timeout of ${$}ms.`);this.name="StepTimeoutError"}}class zZ extends Error{constructor(Z){super(`Workflow ${Z} was cancelled.`);this.name="WorkflowCancelledError"}}class r extends Error{constructor(){super("The workflow is suspended until a step can continue. Rethrow this error if you catch it.");this.name="WorkflowSuspended"}}var gZ=Symbol("done"),hZ=Symbol("paused");class JZ{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=n($);return this.track(Z,()=>this.sleepStep(Z,V))}waitFor(Z,$={}){let V=$.timeout===void 0?void 0:n($.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()=>BZ(this.tick.store,z,await $(),this.workflowId),V)}async progress(Z){let $=a(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 f(this.workflowId);if(this.suspension)throw new r}suspend(Z,$){if(!this.suspension)this.suspension={status:Z,wakes:[]};if($!=null)this.suspension.wakes.push($);throw new r}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:gZ};if(V.start&&X.workflow.status==="paused"&&!this.tick.cancelling)return{result:hZ};let Y=$(X);return{...Y,result:{value:Y.result}}})}catch(X){if(X instanceof f)this.lost=!0;throw X}if(z===void 0)throw this.lost=!0,new f(this.tick.workflowId);if(z===gZ)this.cancelled=!0,this.suspend("waiting");if(z===hZ)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:n(V.timeout),Y=this.steps.get(Z);if(Y?.status==="completed")return s(Y.output);if(Y?.status==="failed")throw i(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:F,step:K,now:T})=>{if(K?.status==="completed")return{result:{kind:"done",output:K.output}};if(K?.status==="failed")return{result:{kind:"failed",step:K}};if(K&&K.status!=="running"&&K.status!=="retrying")this.mismatch(Z,K.status,"step.run");if(K?.status==="retrying"&&K.wakeAt!==null&&K.wakeAt>T)return{result:{kind:"wait",wakeAt:K.wakeAt}};let v=(K?.attempt??0)+1;if(v>z){let W=this.record(Z,K,{status:"failed",error:`Attempt ${v-1} of ${z} never finished, most likely because the process running it exited.`+(K?.error?` The last error was: ${K.error}`:""),finishedAt:T,wakeAt:null});return{result:{kind:"failed",step:W},step:W}}let b=this.record(Z,K,{status:"running",attempt:v,startedAt:T,finishedAt:null,wakeAt:null});return{result:{kind:"run",attempt:v},step:b,workflow:F.status==="cancelling"?{currentStep:Z}:{currentStep:Z,status:"running"}}},{start:!0});if(this.current=Z,G.kind==="done")return s(G.output);if(G.kind==="failed")throw i(Z,G.step);if(G.kind==="wait")this.suspend("sleeping",G.wakeAt);let B=G.attempt,Q,J,H=!0;try{Q=await this.execute(Z,$,B,X)}catch(F){J=F}if(this.cancelled)throw new r;let U=null;if(J===void 0)try{U=S0(Q,`The result of step "${Z}"`)}catch(F){J=F,H=!1}if(J===void 0)return await this.write(Z,({step:F,now:K})=>({result:void 0,step:this.record(Z,F,{status:"completed",output:U,error:null,wakeAt:null,finishedAt:K})})),s(U);let D=N0(J);if(H&&B<z){let F=O0(V.backoff??0,B),K=await this.write(Z,({step:T,now:v})=>{let b=F>0?v+F:null;return{result:b,step:this.record(Z,T,{status:"retrying",error:D,wakeAt:b})}});if(K!==null)this.suspend("sleeping",K);continue}let _=await this.write(Z,({step:F,now:K})=>{let T=this.record(Z,F,{status:"failed",error:D,wakeAt:null,finishedAt:K});return{result:T,step:T}});throw i(Z,_)}}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,Q,J=new Promise((H,U)=>{let D=(_)=>{X.abort(_),U(_)};if(z!==void 0)B=setTimeout(()=>D(new VZ(Z,z)),z);if(!this.tick.cancelling)Q=setInterval(()=>{this.tick.store.find(this.tick.workflowId,{steps:!1}).then((_)=>{if(_?.workflow.status!=="cancelling"||X.signal.aborted)return;if(this.cancelled=!0,!this.suspension)this.suspension={status:"waiting",wakes:[]};D(new zZ(this.tick.workflowId))}).catch(()=>{})},this.tick.cancelCheckMs),Q.unref?.()});try{return await Promise.race([G,J])}finally{clearTimeout(B),clearInterval(Q),G.catch(()=>{}),J.catch(()=>{})}}async sleepStep(Z,$){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 s(V.output);if(V?.status==="timed_out")throw new $Z(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 s(z.output);if(z.kind==="timeout")throw new $Z(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>yZ)throw TypeError(`step.each "${Z}" needs a count that is a whole number from 0 to ${yZ}; 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:n($.timeout),Q=$.tickBudget===void 0?P1:n($.tickBudget),J=$.progress!==!1,H=$.chunk!==void 0,U=H?Math.max(1,Math.floor($.chunk)):1,D=[$.throttle??[]].flat().map((P)=>({name:`gemi:throttle:${P.key}`,limit:Math.max(0,Math.floor(P.limit)),windowMs:n(P.window)})),_=U1($.maxFailures),F=this.tick.store,K=$.transaction===!0&&F.transaction?(P)=>F.transaction(P):void 0;if($.transaction===!0&&!K)L1();let T=z?pZ(F,z,Math.max(F1,Y*U*4)):$.item;if(!F.listItems)throw Error("This queue's workflow store does not support step.each. The memory and database drivers do.");if(D.length>0&&!this.tick.throttle)throw Error(`step.each "${Z}" has a throttle, and this queue has no lock store.`);let v=this.steps.get(Z);if(v?.status==="completed")return GZ(v.output);if(v?.status==="failed")throw i(Z,v);if(v&&v.status!=="iterating")this.mismatch(Z,v.status,"step.each");if(this.current=Z,this.tick.durable===!1)_1();let b=await this.write(Z,({workflow:P,step:N,items:R,now:L})=>{if(N?.status==="completed")return{result:{kind:"done",output:N.output}};if(N?.status==="failed")return{result:{kind:"failed",step:N}};if(N&&N.status!=="iterating")this.mismatch(Z,N.status,"step.each");let j=N?p0(N.output):N1(X);return{result:{kind:"go",state:j,open:R},...N?{}:{step:this.record(Z,null,{status:"iterating",output:e0(j),startedAt:L})},workflow:P.status==="cancelling"?{currentStep:Z}:{currentStep:Z,status:"running"}}},{items:!0,start:!0});if(b.kind==="done")return GZ(b.output);if(b.kind==="failed")throw i(Z,b.step);let W=b.state;if(W.count!==X)C1(this.workflowId,Z,W.count,X);let A0=W.count,c=new Map(b.open.map((P)=>[P.index,P])),m=[],D0=new Map,d0=new Map,UZ=Date.now()+Q,Q0=0,M0=!1,$0=null,u=new AbortController,NZ=setInterval(()=>{F.find(this.workflowId,{steps:!1}).then((P)=>{if(P?.workflow.status==="paused")M0=!0;if(P?.workflow.status!=="cancelling"||u.signal.aborted)return;if(this.cancelled=!0,!this.suspension)this.suspension={status:"waiting",wakes:[]};u.abort(new zZ(this.workflowId))}).catch(()=>{})},this.tick.cancelCheckMs);NZ.unref?.(),$0=_(W);let RZ=(P,N)=>{let R={...P};for(let L of N)if(L.counter)R[L.counter]++;return R},AZ=(P)=>{let N=P.succeeded+P.skipped+P.failed;return J?{workflow:{progress:A0===0?1:a(N/A0)}}:{}},DZ=(P)=>{if(W={count:W.count,next:Math.max(W.next,P.next),succeeded:Math.max(W.succeeded,P.succeeded),skipped:Math.max(W.skipped,P.skipped),failed:Math.max(W.failed,P.failed)},!$0)$0=_(W);if($0&&!u.signal.aborted)u.abort(new r)},rZ=async(P)=>{let N=P.map(()=>null),R=new Map,L=new AbortController,j=()=>L.abort(u.signal.reason);u.signal.addEventListener("abort",j,{once:!0});let k,V0=P.length===1?`${Z}[${P[0].index}]`:`${Z}[${P[0].index}..${P.at(-1).index}]`,_0=new Promise((A,O)=>{if(L.signal.addEventListener("abort",()=>O(L.signal.reason),{once:!0}),B!==void 0)k=setTimeout(()=>L.abort(new VZ(V0,B)),B)}),h=(A)=>{throw new YZ(Math.max(0,Math.floor(Number(A)||0)))},z0=(A)=>P.map((O,q)=>{let l=R.get(q);if(!l)return{index:O.index,row:null,counter:"succeeded"};return{index:O.index,row:qZ(O,N[q],l.reason,l.data,A),counter:"skipped"}}),X0=null,x=(async()=>{let A=await Promise.all(P.map((S)=>T(S.index)));P.forEach((S,M)=>{N[M]=A1($.key?$.key(A[M],S.index):S.index)});let O=(S)=>`${this.workflowId}:${Z}:${N[S]}`,q=Math.max(...P.map((S)=>S.attempt)),l=async()=>{if(H){let S={idempotencyKey:O(0),attempt:q,signal:L.signal,items:P.map((M,y)=>({index:M.index,key:N[y],idempotencyKey:O(y)})),skip:(M,y,E)=>{if(!Number.isInteger(M)||M<0||M>=P.length)throw RangeError(`ctx.skip: no item at position ${M} of this chunk.`);R.set(M,{reason:String(y),data:E})},release:h};await V(A,S)}else{let S={idempotencyKey:O(0),attempt:q,signal:L.signal,index:P[0].index,key:N[0],skip:(M,y)=>{throw new XZ(M,y)},release:h};await V(A[0],S)}};if(!K)return l();await K(async()=>{if(await l(),L.signal.aborted)throw L.signal.reason;let S=z0(Date.now()),M=await this.write(Z,({step:y})=>{let E={step:Z,insert:[],update:[],delete:[]};for(let H0 of S)if(H0.row===null)E.delete.push(H0.index);else E.update.push(H0.row);let d=RZ(y?p0(y.output):W,S);return{result:d,step:this.record(Z,y,{status:"iterating",output:e0(d)}),items:E,...AZ(d)}},{joinTransaction:!0});X0=S.map((y)=>({...y,recorded:!0})),DZ(M)})})(),I,C=!1;try{await Promise.race([x,_0])}catch(A){C=!0,I=A}finally{clearTimeout(k),u.signal.removeEventListener("abort",j),x.catch(()=>{}),_0.catch(()=>{})}if(X0){m.push(...X0);return}if(u.signal.aborted||this.cancelled||this.lost)return;let g=Date.now();if(!C){m.push(...z0(g));return}if(I instanceof XZ){m.push({index:P[0].index,row:qZ(P[0],N[0],I.reason,I.data,g),counter:"skipped"});return}if(I instanceof YZ){Q0=Math.max(Q0,g+I.delayMs),P.forEach((A,O)=>{m.push({index:A.index,row:{...A,key:N[O],status:"retrying",attempt:Math.max(0,A.attempt-1),wakeAt:g+I.delayMs},counter:null})});return}let p=E0(N0(I),2000);P.forEach((A,O)=>{if(A.attempt<G){let q=O0($.backoff??0,A.attempt);m.push({index:A.index,row:{...A,key:N[O],status:"retrying",error:p,wakeAt:g+q},counter:null});return}m.push({index:A.index,row:{...A,key:N[O],status:"failed",error:p,wakeAt:null,finishedAt:g},counter:"failed"})})},tZ=async(P)=>{if(D.length===0||P===0)return P;let N=this.tick.throttle;for(let R=0;R<P;R++){let L=[];for(let j of D){let k=await N.hit(j.name,j.limit,j.windowMs);if(!k.allowed)return await Promise.all(L.map((V0)=>N.refund(V0))),Q0=Math.max(Q0,Date.now()+Math.max(1,k.resetInMs)),R;L.push(j.name)}}return P},oZ=async(P)=>{if(D.length===0)return;for(let N=0;N<P;N++)for(let R of D)await this.tick.throttle.refund(R.name)};try{for(;;){let P=Date.now(),N=P>=UZ||w0()||this.cancelled||M0||$0!==null,R=[],L=0;if(!N&&P>=Q0){let h=(Y-D0.size)*U,z0=new Set(m.map((I)=>I.index));for(let I of[...c.values()].sort((C,g)=>C.index-g.index)){if(R.length>=h)break;if(d0.has(I.index)||z0.has(I.index))continue;if(I.status==="running"||(I.wakeAt??0)<=P)R.push(I)}let X0=Y*U+fZ-c.size;L=Math.max(0,Math.min(h-R.length,A0-W.next,X0));let x=await tZ(R.length+L);if(x<R.length)R=R.slice(0,x),L=0;else L=x-R.length}if(m.length>0||R.length>0||L>0){let h=m.splice(0,m.length),z0=h.filter((C)=>!C.recorded),X0=R.length+L,x=await this.write(Z,({workflow:C,step:g,now:p})=>{let A=RZ(g?p0(g.output):W,z0),O={step:Z,insert:[],update:[],delete:[]},q=[],l=[];for(let E of z0)if(E.row===null)O.delete.push(E.index);else O.update.push(E.row);let S=C.status==="paused"&&!this.tick.cancelling;for(let E of S?[]:R){if(E.attempt+1>G){let H0={...E,status:"failed",error:E0(`Attempt ${E.attempt} of ${G} never finished, most likely because the process running it exited.`+(E.error?` The last error was: ${E.error}`:""),2000),wakeAt:null,finishedAt:p};A.failed++,O.update.push(H0),l.push(H0);continue}let d={...E,status:"running",attempt:E.attempt+1,wakeAt:null,startedAt:p};O.update.push(d),q.push(d)}let M=S?0:L,y=q.length;for(let E=0;E<M;E++){let d=R1(this.workflowId,Z,A.next+E,p);O.insert.push(d),q.push(d)}return A.next+=M,{result:{next:A,started:q,closed:l,reruns:y,paused:S},step:this.record(Z,g,{status:"iterating",output:e0(A)}),items:O,...AZ(A)}});if(DZ(x.next),x.paused)M0=!0;await oZ(X0-x.started.length);for(let C of h)if(C.row?.status==="retrying")c.set(C.index,C.row);else c.delete(C.index);for(let C of x.closed)c.delete(C.index);for(let C of x.started)c.set(C.index,C);let I=[...bZ(x.started.slice(0,x.reruns),U),...bZ(x.started.slice(x.reruns),U)];for(let C of I){let g=C[0].index;for(let p of C)d0.set(p.index,g);D0.set(g,rZ(C).finally(()=>{D0.delete(g);for(let p of C)d0.delete(p.index)}))}}if(D0.size>0){await Promise.race(D0.values());continue}if(m.length>0)continue;if(this.cancelled)throw new r;if($0)break;if(W.next>=A0&&c.size===0)break;if(M0)this.suspend("paused");if(N)this.suspend("running",Date.now());let j=Date.now(),k=1/0;if(W.next<A0&&c.size<Y*U+fZ)k=j;for(let h of c.values())if(h.status==="running")k=j;else if(h.status==="retrying")k=Math.min(k,h.wakeAt??0);let V0=Math.max(k,Q0);if(V0<=j)continue;let _0=V0-j;if(_0<=Math.min(K1,UZ-j)){await new Promise((h)=>setTimeout(h,Math.max(0,_0)));continue}this.suspend("sleeping",V0)}}finally{if(clearInterval(NZ),!u.signal.aborted)u.abort(new r)}let _Z=await F.listItems(this.workflowId,Z,{statuses:["failed","skipped"],limit:o0+1}),a0={...QZ(W),problems:_Z.slice(0,o0).map(HZ),moreProblems:_Z.length>o0},eZ=JSON.stringify({$each:W,problems:a0.problems,moreProblems:a0.moreProblems}),v0=$0,Z1=await this.write(Z,({step:P,now:N})=>{let R=this.record(Z,P,{status:v0?"failed":"completed",output:eZ,error:v0,finishedAt:N});return{result:R,step:R,...J&&!v0?{workflow:{progress:1}}:{}}});if(v0)throw i(Z,Z1);return a0}async batchStep(Z,$,V,z){let X=z.allowFailures===!0,Y=this.steps.get(Z);if(Y?.status==="completed")return s(Y.output);if(Y?.status==="failed")throw i(Z,Y);if(Y&&Y.status!=="batching")this.mismatch(Z,Y.status,"step.batch");if(this.current=Z,!Y){let U=this.tick.buildBatch($,V,{name:z.name??`workflow:${this.tick.workflowId}:${Z}`,allowFailures:X});if(Y=await this.write(Z,({step:D,now:_})=>{if(D)return{result:D};let F=this.record(Z,null,{status:"batching",batchId:U.id,startedAt:_});return{result:F,step:F,batch:U,workflow:{currentStep:Z}}},{start:!0}),this.tick.scheduled(),Y.status==="completed")return s(Y.output);if(Y.status==="failed")throw i(Z,Y)}let G=Y.batchId===null?null:await this.tick.findBatch(Y.batchId);if(G&&G.finishedAt===null)this.suspend("waiting");let B=G!==null&&G.cancelledAt===null&&(G.failed===0||X),Q=G===null?null:JSON.stringify(G),J=B?null:G===null?`The batch of step "${Z}" (${Y.batchId}) no longer exists.`:`The batch of step "${Z}" failed: ${G.failed} failed and ${G.cancelled} cancelled of ${G.total}.`,H=await this.write(Z,({step:U,now:D})=>{let _=this.record(Z,U,{status:B?"completed":"failed",output:Q,error:J,finishedAt:D});return{result:_,step:_}});if(!B)throw i(Z,H);return G}}function i(Z,$){if($.output?.startsWith('{"$each"'))return new ZZ(Z,`Step "${Z}" failed: ${$.error??"unknown error"}`,void 0,GZ($.output));let V=$.batchId!==null&&$.output!==null?JSON.parse($.output):void 0;return new ZZ(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>i0)throw RangeError(`${$} is ${z} bytes as JSON, over the ${i0}-byte limit. Store it elsewhere and return its id.`);return V}function s(Z){return Z===null?void 0:JSON.parse(Z)}function N0(Z){return Z instanceof Error?Z.message:String(Z)}var yZ=2147483647,P1=30000,fZ=100,K1=1000,F1=64,o0=100;class XZ extends Error{reason;data;constructor(Z,$){super(`Skipped: ${Z}`);this.reason=Z;this.data=$;this.name="ItemSkipped"}}class YZ extends Error{delayMs;constructor(Z){super(`Released for ${Z}ms`);this.delayMs=Z;this.name="ItemReleased"}}function qZ(Z,$,V,z,X){let Y=null,G=E0(String(V));try{Y=D1(z)}catch(B){G=E0(`${G} (${N0(B)})`)}return{...Z,key:$,status:"skipped",error:G,output:Y,wakeAt:null,finishedAt:X}}function bZ(Z,$){let V=[];for(let z=0;z<Z.length;z+=$)V.push(Z.slice(z,z+$));return V}function U1(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 N1(Z){return{count:Z,next:0,succeeded:0,skipped:0,failed:0}}function e0(Z){return JSON.stringify({$each:Z})}function p0(Z){let $=Z===null?null:JSON.parse(Z);if(!$?.$each)throw Error("A step.each step has no state.");return $.$each}function wZ(Z){if(Z===null||!Z.startsWith('{"$each"'))return null;try{return QZ(p0(Z))}catch{return null}}function QZ(Z){return{total:Z.count,done:Z.succeeded+Z.skipped+Z.failed,succeeded:Z.succeeded,skipped:Z.skipped,failed:Z.failed}}function GZ(Z){let $=JSON.parse(Z??"null");return{...QZ($.$each),problems:$.problems??[],moreProblems:$.moreProblems===!0}}function HZ(Z){let $={index:Z.index,key:Z.key,status:Z.status==="skipped"?"skipped":"failed",reason:E0(Z.error??""),attempt:Z.attempt};if(Z.output!==null)$.data=JSON.parse(Z.output);return $}function R1(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 A1(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 E0(Z,$=500){return Z.length<=$?Z:`${Z.slice(0,$-1)}\u2026`}function D1(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 mZ=!1;function _1(){if(mZ||Bun.env.NODE_ENV!=="production")return;mZ=!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 kZ=!1;function L1(){if(kZ)return;kZ=!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 uZ=new Set;function C1(Z,$,V,z){let X=`${Z}:${$}`;if(uZ.has(X))return;uZ.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 c0(Z){return Z==="completed"||Z==="failed"||Z==="cancelled"}var T0=["completed","failed","cancelled"],W1=1000,O1=250,E1=30000;class PZ{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??=S1(this),this.tickClass}get store(){if(!this.storeInstance){let Z=this.queue.driver.workflowStore?.();if(!Z||!this.queue.driver.enqueueBatch)throw Error("This queue's driver does not support workflows. The memory and database drivers do.");this.storeInstance=this.publishingStore(Z)}return this.storeInstance}get feed(){let Z=this.queue.boundApplication;if(Z?.bound(l0))return Z.make(l0);return this.ownFeed??=new l0,this.ownFeed}channel(Z){return`gemi:workflow:${Z}`}async update(Z){let $=await this.find(Z);if(!$)return null;let{args:V,result:z,...X}=$;return X}stream(Z,$,V={}){return this.feed.stream(Z,this.channel($),V)}cursor(Z){return this.feed.cursor(this.channel(Z))}async*subscribe(Z,$={}){let V=this.feed.subscribe(this.channel(Z),{signal:$.signal});try{await V.ready();let z=await this.update(Z);if(!z)return;if(yield z,c0(z.status))return;let X=V[Symbol.asyncIterator](),Y=X.next();for(;;){let G=await M1(Y,E1),B;if(G==="timeout")B=await this.update(Z);else{if(G.done)return;Y=X.next(),B=I1(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,c0(z.status))return}}finally{V.close()}}publishingStore(Z){let $=(z)=>void cZ(()=>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)+O1-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(c0($.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(t(()=>V.create(z).then(X,(J)=>{console.error(`[gemi] The queue could not record the workflow ${Z.name}, which was held until its transaction committed. The transaction stays committed; the workflow did not start.`,J)})))return Promise.resolve(z.id)}let G=V.create(z),B=Y&&t(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(T0.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(T0.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){return await this.store.update(Z,{},({workflow:V})=>{if(T0.includes(V.status)||V.status==="cancelling"||V.status==="paused")return{result:!1};return{result:!0,workflow:{status:"paused"}}})===!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:T1(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=wZ(Y.output);if(B)return{...G,items:B,progress:B.total===0?1:B.done/B.total};if(Y.batchId===null)return G;let Q=await this.queue.driver.findBatch?.(Y.batchId);return Q?{...G,progress:Q.progress}:G})),createdAt: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(HZ)}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,Q=(F={})=>V.update(Z,{owner:X},()=>({...F,result:void 0,unlock:!0})).then(()=>this.queue.claimSoon()).catch((K)=>{if(!(K instanceof f))throw K});if(T0.includes(B.status)||B.status==="paused")return Q();let J=this.registry[B.name];if(!J)return this.unknown(B,$,Q);let H;try{H=JSON.parse(B.args)}catch(F){return Q({workflow:{status:"failed",error:`The arguments are not JSON: ${N0(F)}`}})}let U=setInterval(()=>{V.renew(Z,X,Y).catch((F)=>{console.error(`[gemi] Could not extend the hold on workflow ${Z}.`,F)})},Math.max(1,Math.floor(Y/3)));U.unref?.();let D=B.status==="cancelling",_=new JZ({workflowId:Z,owner:X,store:V,steps:G.steps,cancelling:D,findBatch:(F)=>this.queue.driver.findBatch?.(F,{progress:!1})??Promise.resolve(null),buildBatch:(F,K,T)=>this.queue.buildBatch(F,K.map((v)=>JSON.stringify(v)),{name:T.name,allowFailures:T.allowFailures,finally:{name:o,args:[Z]}}),scheduled:()=>this.queue.claimSoon(),cancelCheckMs:W1,durable:this.queue.durable,throttle:{hit:(F,K,T)=>this.queue.locks.store.hit(F,K,T),refund:(F)=>this.queue.locks.store.refund(F)}});try{let F;try{let K=new J,T=await(D?K.onCancel(_,...H):K.run(_,...H));F=_.suspension?{kind:"suspended"}:{kind:"completed",result:D?null:S0(T,`The result of ${B.name}`)}}catch(K){if(F=_.suspension||K instanceof r?{kind:"suspended"}:{kind:"failed",error:N0(K)},K instanceof f)_.lost=!0}if(await _.settled(),_.lost)return;if(F.kind==="completed"&&_.suspension)F={kind:"suspended"};await V.update(Z,{owner:X},({workflow:K,now:T})=>this.finish(K,F,_,D,T)),this.queue.claimSoon()}catch(F){if(F instanceof f)return;throw F}finally{clearInterval(U)}}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 Q=Math.min(...G.wakes);if(!(Z.wakeAt!==null&&Z.wakeAt>X&&Z.wakeAt<=Q))B.tick={delayMs:Math.max(0,Q-X)},B.workflow.wakeAt=Q}return B}async unknown(Z,$,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})=>T0.includes(V.status)?{result:void 0}:{result:void 0,workflow:{status:"failed",error:`Its tick job was dead-lettered: ${$.message}`},unlock:!0}).catch(()=>{})}}function S1(Z){return class extends J0{static name=o;maxAttempts=20;backoff=[1000,5000,15000,30000,60000];async run(V){await Z.tick(V,this)}onDeadletter(V,z){Z.tickDeadLettered(z,V)}}}function T1(Z){try{return s(Z)}catch{return Z}}function I1(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 M1(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 g1(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:j1(z)?z:void 0,kernel:`${V}/kernel/Kernel.ts`,app:X}}function h1(){let Z=g1(),$=Z.bootstrap?`const { app } = await import(${JSON.stringify(Z.bootstrap)});`:`const { App } = await import(${JSON.stringify(Z.app)});
|
|
497
|
-
const { default: Kernel } = await import(${JSON.stringify(Z.kernel)});
|
|
498
|
-
const app = new App({ kernel: Kernel });
|
|
499
|
-
await app.waitForBoot();`,V=new File([`
|
|
500
|
-
${$}
|
|
501
|
-
self.onmessage = async (event) => {
|
|
502
|
-
const clone = app.clone()
|
|
503
|
-
let result = null;
|
|
504
|
-
let error = null;
|
|
505
|
-
try {
|
|
506
|
-
result = await clone.dispatchJob(event.data.jobName, event.data.args)
|
|
507
|
-
} catch (err) {
|
|
508
|
-
error = err
|
|
509
|
-
}
|
|
510
|
-
clone.destroy()
|
|
511
|
-
if(error) {
|
|
512
|
-
self.postMessage({error});
|
|
513
|
-
} else {
|
|
514
|
-
self.postMessage({result});
|
|
515
|
-
}
|
|
516
|
-
};
|
|
517
|
-
self.postMessage({ ready: true });
|
|
518
|
-
`],"worker.ts"),z=URL.createObjectURL(V);return new Worker(z)}async function y1(Z,$){let V=h1();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 f1=new v1("gemi.queue"),q1=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=aZ(xZ(),Z),this.application=$.application,this.driver=p1(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 PZ(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(t(()=>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(t(()=>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!==J0.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&&t(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 iZ(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 L0(this.application.make(FZ));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===J0.prototype.uniqueId)return;let V=new Z,z=V.uniqueId(...JSON.parse($));if(z===void 0||z===null||z==="")return;return{key:lZ(Z.name,z),ttl:Math.max(1,V.uniqueFor)}}pushUnique(Z,$,V,z){let X=Bun.randomUUIDv7();if(t(()=>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(J){throw await Y.release(V.key,z).catch(()=>{}),J}let Q=await Y.holder(V.key);if(Q)return Q.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===J0.prototype.uniqueId)return;try{let z=Z.uniqueId(...$);if(z===void 0||z===null||z==="")return;await this.locks.store.release(lZ(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&&t(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()&&!b1())globalThis.__gemiDevQueue=this;if(this.unsubscribe=this.driver.subscribe?.(()=>this.wake()),this.looping)return this.wake();f1.runInAsyncScope(()=>void this.loop())}async drain(Z=1/0){if(this.state="stopped",globalThis.__gemiDevQueue===this)globalThis.__gemiDevQueue=void 0;this.unsubscribe?.(),this.unsubscribe=void 0,this.wake();let $,V=new Promise((X)=>{if(Z!==1/0)$=setTimeout(X,Z)}),z=(async()=>{await this.claiming?.catch(()=>{}),await Promise.allSettled([...this.inFlight.values()].map((X)=>X.done))})();return await Promise.race([z,V]),clearTimeout($),{unfinished:[...this.inFlight.values()].map((X)=>({...X.job}))}}stop(){return this.drain(0)}get running(){return this.inFlight.size}async loop(){this.looping=!0;try{await this.claimWhileRunning()}finally{this.looping=!1}}async claimWhileRunning(){while(this.state==="running"){let Z=this.durable&&w0()?0:this.config.concurrency-this.inFlight.size;if(Z>0){this.woken=!1;let $=this.driver.claim(Z,{...this.lease(),registered:{names:Object.keys(this.jobs),graceMs:this.config.unknownJobGrace}});this.claiming=$;let V=[];try{V=await $,this.claimFailures=0}catch(z){this.claimFailures++,console.error(`The queue could not claim jobs from its driver; it will try again in ${this.retryDelay()}ms.`,z)}finally{this.claiming=void 0}for(let z of V)this.execute(z);if(V.length===Z)continue;if(this.woken&&this.inFlight.size<this.config.concurrency)continue}await this.sleep()}}sleep(){return new Promise((Z)=>{let $,V=this.claimFailures>0?this.retryDelay():this.driver.subscribe?void 0:this.config.pollInterval;if(V!==void 0)$=setTimeout(()=>this.wake(),V),$.unref?.();this.resume=()=>{clearTimeout($),Z()}})}retryDelay(){let Z=Math.min(Math.max(0,this.claimFailures-1),30);return Math.min(this.config.pollInterval*2**Z,q1)}wake(){this.woken=!0;let Z=this.resume;this.resume=void 0,Z?.()}get durable(){return!(this.driver instanceof u0)}mayClaimHere(){return!this.application||m1()}lease(){return{visibilityTimeoutMs:this.config.visibilityTimeout}}execute(Z){let $=`${Z.id}:${Z.attempt}`,V=()=>this.run(Z),z=(this.application?dZ.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 J=Date.now()-Z.createdAt;if(this.durable&&J<this.config.unknownJobGrace){if(!this.releasedNames.has(Z.name))this.releasedNames.add(Z.name),console.error(`Left a queued "${Z.name}" for another replica: nothing is registered here under that name. It is dead-lettered if no replica has run it within unknownJobGrace (${this.config.unknownJobGrace}ms) of its dispatch.`);await this.driver.release(Z,{retryInMs:Math.round(this.config.pollInterval*(1+Math.random()))});return}console.error(`Dropped a queued job: nothing is registered under the name "${Z.name}". If the class exists, it was not `+"discovered \u2014 check that it is under the queue slice's jobsDir "+"(app/jobs by default), or list it in app/config/queue.ts."),await this.driver.fail(Z,{error:`No job is registered under the name "${Z.name}".`,retryInMs:null});return}let V;try{V=new $}catch(J){console.error(`Dropped a queued ${Z.name}: it could not be constructed.`,J),await this.driver.fail(Z,{error:`The job could not be constructed: ${String(J)}`,retryInMs:null});return}let z;try{z=JSON.parse(Z.args)}catch(J){console.error(`Dropped a queued ${Z.name}: its arguments are not JSON.`,J),await this.driver.fail(Z,{error:`The arguments are not JSON: ${String(J)}`,retryInMs:null});return}if(Z.attempt>Math.max(1,V.maxAttempts)){let J=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.`);KZ(`${Z.name}.onDeadletter`,()=>V.onDeadletter(J,...z)),await this.driver.fail(Z,{error:J.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 H=this.batchHandle(Z);V.batch=H.batch,V.$progress=H.progress}let X=await this.admit(V,z,Z);if(!X)return;let Y,G;try{G=await(V.worker?y1(Z.name,Z.args):V.run(...z))}catch(J){Y=J}finally{await X.done()}let B=V.$outcome;if(Y===void 0&&B?.kind==="release"){await this.driver.release(Z,{retryInMs:Math.max(0,B.delayMs)});return}if(Y===void 0&&B?.kind==="fail")Y=B.error;let Q=B?.kind==="fail"?B.retry:!0;if(Y===void 0)try{V.onSuccess(G,...z)}catch(J){Y=J}if(Y!==void 0){let J=String(Y?.stack??Y);if(KZ(`${Z.name}.onFail`,()=>V.onFail(Y,...z)),!Q||Z.attempt>=V.maxAttempts)KZ(`${Z.name}.onDeadletter`,()=>V.onDeadletter(Y,...z)),await this.driver.fail(Z,{error:J,retryInMs:null}),await this.releaseUnique(V,z,Z);else await this.driver.fail(Z,{error:J,retryInMs:O0(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=Z.concurrency(...$),X=[Z.throttle(...$)??[]].flat();if(!z&&X.length===0)return{done:async()=>{}};let Y=this.locks,G;if(z&&z.limit>0){let Q=this.config.visibilityTimeout;for(let J=0;J<z.limit&&!G;J++)G=await Y.acquire(`gemi:concurrency:${z.key}:${J}`,{ttl:Q,renew:!0})??void 0;if(!G){await this.driver.release(V,{retryInMs:Math.round(this.config.pollInterval*(1+Math.random()))});return}}let B=[];for(let Q of X){let J=`gemi:throttle:${Q.key}`,H=await Y.store.hit(J,Q.limit,Q.window);if(!H.allowed){await Promise.all(B.map((U)=>Y.store.refund(U))),await G?.release(),await this.driver.release(V,{retryInMs:Math.max(1,H.resetInMs)});return}B.push(J)}return{done:async()=>{await G?.release().catch((Q)=>{console.error(`[gemi] Could not free a concurrency slot of ${V.name}.`,Q)})}}}}function lZ(Z,$){return`gemi:job:${Z}:${String($)}`}function KZ(Z,$){try{$()}catch(V){console.error(`${Z} threw; the job's claim was ended anyway.`,V)}}function b1(){return Bun.env.NODE_ENV==="production"}function m1(){if(!x1)return!1;if(u1())return!0;return process.env.ROOT_DIR!==void 0&&!k1()}function k1(Z=process.env){return(Z.GEMI_QUEUE_CLAIM??"").trim().toLowerCase()==="off"}var sZ=Symbol.for("gemi.queue.worker");function n2(Z=!0){globalThis[sZ]=Z}function u1(){return globalThis[sZ]===!0}function p1(Z,$){if(Z==="memory")return new u0;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 r0($.make(FZ));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 nZ=65536,w1=500;class c1{static write(Z,$){return BZ(I0(),Z,$,null)}static async read(Z,$){let[V]=await R0(I0()).readSource(Z,$,$+1);return V?JSON.parse(V.payload):void 0}static async readRange(Z,$,V){return(await R0(I0()).readSource(Z,$,V)).map((X)=>JSON.parse(X.payload))}static delete(Z){return R0(I0()).deleteSource(Z)}static prune(Z){return R0(I0()).pruneSources(n(Z))}}function I0(){return B0(Z0).workflows.store}function R0(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 BZ(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($)}.`);R0(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 Q=Buffer.byteLength(B,"utf8");if(Q>nZ)throw RangeError(`Item ${X} of source "${$}" is ${Q} bytes as JSON, over the ${nZ}-byte limit. Store it elsewhere and keep its id.`);if(Y.push({index:X++,payload:B}),Y.length>=w1)await Z.writeSource($,z,Y),Y=[]}return await Z.writeSource($,z,Y),{id:$,count:X}}function pZ(Z,$,V){R0(Z);let z=new Map,X=new Map,Y=0,G=(B,Q)=>{let J=`${B}:${Q}`,H=X.get(J);if(!H)H=Z.readSource($.id,B,Q).then((U)=>{for(let D of U)z.set(D.index,D.payload);X.delete(J)},(U)=>{throw X.delete(J),U}),X.set(J,H);return H};return async(B)=>{if(!z.has(B)){let J=B-B%V,H=Math.min(J+V,$.count);if(X.has(`${J}:${H}`))await X.get(`${J}:${H}`);else if(B>=Y)Y=Math.max(Y,H),await G(J,H);if(!z.has(B))await G(B,B+1)}let Q=z.get(B);if(z.delete(B),Q===void 0)throw Error(`Item source "${$.id}" has no item at index ${B}.`);return JSON.parse(Q)}}
|
|
519
|
-
export{L0 as se,g0 as te,s0 as ue,OZ as ve,r0 as we,Y2 as xe,xZ as ye,t0 as ze,u0 as Ae,nZ as Be,c1 as Ce,ZZ as De,$Z as Ee,VZ as Fe,zZ as Ge,JZ as He,c0 as Ie,PZ as Je,Z0 as Ke,m1 as Le,k1 as Me,n2 as Ne,u1 as Oe,J0 as Pe};
|
|
520
|
-
|
|
521
|
-
//# debugId=C74796F6B326021964756E2164756E21
|