@vite-hub/queue 0.1.0 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +141 -20
- package/dist/client-Cj50hQYp.js +180 -0
- package/dist/{cloudflare-client-COzQ8fHk.js → cloudflare-client-DYsAjM8B.js} +9 -16
- package/dist/{cloudflare-resource-name-CCuLDvSP.js → cloudflare-resource-name-BJHYRCMQ.js} +1 -1
- package/dist/config-BcTDeQIP.js +105 -0
- package/dist/durability.d.ts +13 -0
- package/dist/durability.js +47 -0
- package/dist/error-diagnostics-BRartC1z.js +181 -0
- package/dist/error-diagnostics-DSkCJC_L.js +266 -0
- package/dist/errors-DL3pcNO4.js +77 -0
- package/dist/{handler-response-CBwIkmTS.js → handler-response-By0Fpspv.js} +9 -4
- package/dist/index.d.ts +15 -31
- package/dist/index.js +23 -11
- package/dist/internal/runtime/cloudflare-client.d.ts +2 -2
- package/dist/internal/runtime/cloudflare-client.js +1 -1
- package/dist/internal/runtime/cloudflare-vite.d.ts +30 -2
- package/dist/internal/runtime/cloudflare-vite.js +111 -1
- package/dist/internal/runtime/local-client.d.ts +17 -0
- package/dist/internal/runtime/local-client.js +71 -0
- package/dist/internal/runtime/postgres-client.d.ts +46 -0
- package/dist/internal/runtime/postgres-client.js +560 -0
- package/dist/internal/runtime/state.d.ts +11 -4
- package/dist/internal/runtime/state.js +2 -2
- package/dist/internal/runtime/vercel-client.d.ts +2 -2
- package/dist/internal/runtime/vercel-client.js +52 -26
- package/dist/internal/runtime/worker-client.d.ts +6 -0
- package/dist/internal/runtime/worker-client.js +11 -0
- package/dist/invariant-D8_xBqmZ.js +22 -0
- package/dist/local-CGckW5nr.js +540 -0
- package/dist/local-CVVRVWeR.d.ts +22 -0
- package/dist/object-D8pRdprI.js +15 -0
- package/dist/{operations-tNUdj3G4.d.ts → operation-definition-8gOe-ubD.d.ts} +37 -15
- package/dist/operations-Crwjca91.js +124 -0
- package/dist/operations.d.ts +45 -8
- package/dist/operations.js +173 -24
- package/dist/runtime/hosted.d.ts +3 -5
- package/dist/runtime/hosted.js +21 -45
- package/dist/{state-G9s378-e.js → state-mVA2X_wa.js} +59 -47
- package/dist/types-BD-8U9zS.d.ts +420 -0
- package/dist/types-DS_rqu9l.d.ts +10 -0
- package/dist/vercel-region-D1CivgdA.js +26 -0
- package/dist/virtual.d.ts +4 -0
- package/dist/vite.d.ts +364 -49
- package/dist/vite.js +2071 -2
- package/package.json +39 -46
- package/dist/client-CIc3jsj2.js +0 -114
- package/dist/cloudflare-vite-BCuJOXcT.js +0 -111
- package/dist/cloudflare-vite-CjdP5yBN.d.ts +0 -29
- package/dist/config-BINujLv4.js +0 -74
- package/dist/enqueue-CnQ0QR3O.js +0 -22
- package/dist/error-diagnostics-A_8Kp-48.js +0 -116
- package/dist/error-diagnostics-qzRF6IVB.js +0 -109
- package/dist/errors-DIFaM9tW.js +0 -42
- package/dist/nuxt.d.ts +0 -39
- package/dist/nuxt.js +0 -34
- package/dist/object-B1NW521B.js +0 -7
- package/dist/operations-Cnjbz8kk.js +0 -63
- package/dist/types-1GRMYES1.d.ts +0 -180
- package/dist/vercel-region-cjskrOKl.js +0 -122
- package/dist/vite-ChWLzOVu.js +0 -1512
|
@@ -0,0 +1,560 @@
|
|
|
1
|
+
import { t as queueErrorDiagnostics } from "../../error-diagnostics-BRartC1z.js";
|
|
2
|
+
import { c as createQueueMessageId, l as normalizeQueueEnqueueInput, o as queueProviderResult, s as queueUnsupportedOptionsError } from "../../errors-DL3pcNO4.js";
|
|
3
|
+
import { c as loadQueueDefinition, l as missingQueueDefinitionError, p as setQueueRuntimeJobStore, s as listQueueDefinitionNames } from "../../state-mVA2X_wa.js";
|
|
4
|
+
import { r as postgresQueueUrlVariable } from "../../config-BcTDeQIP.js";
|
|
5
|
+
import { t as invariant } from "../../invariant-D8_xBqmZ.js";
|
|
6
|
+
import { i as reportQueueDeliveryError, n as createQueueDeliveryErrorReport, r as isNonRetryableQueueError, t as checkQueueHandlerResponse } from "../../handler-response-By0Fpspv.js";
|
|
7
|
+
import { i as localQueueDeliveryRules, r as delayMs } from "../../local-CGckW5nr.js";
|
|
8
|
+
import { hostname } from "node:os";
|
|
9
|
+
import { randomUUID } from "node:crypto";
|
|
10
|
+
import { runInRunScopes } from "@vite-hub/runtime/internal/run-scope";
|
|
11
|
+
import postgres from "postgres";
|
|
12
|
+
/** Jobs that `jobs()` lists at most. */
|
|
13
|
+
const listLimit = 1e3;
|
|
14
|
+
const identifier = /^[a-z_][a-z\d_]{0,62}$/;
|
|
15
|
+
/** Returns `true` for a postgres.js client, such as the `$client` of a Postgres Database. */
|
|
16
|
+
function isPostgresQueueSql(value) {
|
|
17
|
+
return typeof value === "function" && [
|
|
18
|
+
"begin",
|
|
19
|
+
"end",
|
|
20
|
+
"listen",
|
|
21
|
+
"unsafe"
|
|
22
|
+
].every((name) => typeof Reflect.get(value, name) === "function");
|
|
23
|
+
}
|
|
24
|
+
/** The host, port, and database of the client without credentials, for logs, `vitehub queue list`, and the Console. */
|
|
25
|
+
function describePostgresQueueLocation(sql, table) {
|
|
26
|
+
const { database, host, port } = sql.options;
|
|
27
|
+
return `postgres://${host.map((name, index) => `${name}${port[index] ? `:${port[index]}` : ""}`).join(",")}/${database} (table ${table})`;
|
|
28
|
+
}
|
|
29
|
+
const iso = (date) => new Date(date).toISOString();
|
|
30
|
+
function toJobSummary(row) {
|
|
31
|
+
return {
|
|
32
|
+
attempts: row.attempts,
|
|
33
|
+
availableAt: iso(row.run_at),
|
|
34
|
+
enqueuedAt: iso(row.created_at),
|
|
35
|
+
...row.last_error ? { error: row.last_error } : {},
|
|
36
|
+
...row.failed_at ? { failedAt: iso(row.failed_at) } : {},
|
|
37
|
+
id: row.message_id,
|
|
38
|
+
queue: row.queue,
|
|
39
|
+
state: row.status === "running" && !row.locked ? "pending" : row.status
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
function createPostgresQueueEngine(options) {
|
|
43
|
+
const table = options.table ?? "vitehub_queue_jobs";
|
|
44
|
+
invariant(identifier.test(table), "the Queue table name is a lowercase SQL identifier, because only the Queue runtime and its tests choose it");
|
|
45
|
+
const rules = localQueueDeliveryRules.postgres;
|
|
46
|
+
const retryDelayMs = options.retryDelayMs ?? rules.retryDelayMs;
|
|
47
|
+
const lockSeconds = options.lockSeconds ?? 30;
|
|
48
|
+
const pollIntervalMs = options.pollIntervalMs ?? 1e3;
|
|
49
|
+
const drainTimeoutMs = options.drainTimeoutMs ?? 1e4;
|
|
50
|
+
const workerId = options.workerId ?? `${hostname()}:${process.pid}:${randomUUID().slice(0, 8)}`;
|
|
51
|
+
const channel = table;
|
|
52
|
+
const ownsClient = "url" in options.connection;
|
|
53
|
+
const sql = "url" in options.connection ? postgres(options.connection.url, { onnotice: () => {} }) : options.connection.client;
|
|
54
|
+
const base = describePostgresQueueLocation(sql, table);
|
|
55
|
+
const t = sql(table);
|
|
56
|
+
const times = sql`to_json(run_at) #>> '{}' as run_at, to_json(created_at) #>> '{}' as created_at, to_json(failed_at) #>> '{}' as failed_at`;
|
|
57
|
+
const running = /* @__PURE__ */ new Map();
|
|
58
|
+
const renewals = /* @__PURE__ */ new Set();
|
|
59
|
+
const runningPerQueue = /* @__PURE__ */ new Map();
|
|
60
|
+
const concurrency = /* @__PURE__ */ new Map();
|
|
61
|
+
let ready;
|
|
62
|
+
let started;
|
|
63
|
+
let unlisten;
|
|
64
|
+
let timer;
|
|
65
|
+
let pumping;
|
|
66
|
+
let pumpAgain = false;
|
|
67
|
+
let closed = false;
|
|
68
|
+
/** Creates the table once per process. Concurrent cold starts wait for one transaction lock, so they do not race. */
|
|
69
|
+
function ensureTable() {
|
|
70
|
+
ready ??= (async () => {
|
|
71
|
+
try {
|
|
72
|
+
await sql`select 1 from ${t} limit 0`;
|
|
73
|
+
return;
|
|
74
|
+
} catch {}
|
|
75
|
+
await sql.begin(async (tx) => {
|
|
76
|
+
await tx`select pg_advisory_xact_lock(hashtext(${`vitehub:queue:${table}`}))`;
|
|
77
|
+
await tx`create table if not exists ${t} (
|
|
78
|
+
id uuid primary key,
|
|
79
|
+
message_id text not null,
|
|
80
|
+
queue text not null,
|
|
81
|
+
payload jsonb,
|
|
82
|
+
status text not null default 'pending' check (status in ('pending', 'running', 'dead')),
|
|
83
|
+
attempts integer not null default 0,
|
|
84
|
+
run_at timestamptz not null default now(),
|
|
85
|
+
locked_until timestamptz,
|
|
86
|
+
locked_by text,
|
|
87
|
+
idempotency_key text,
|
|
88
|
+
last_error jsonb,
|
|
89
|
+
created_at timestamptz not null default now(),
|
|
90
|
+
updated_at timestamptz not null default now(),
|
|
91
|
+
failed_at timestamptz
|
|
92
|
+
)`;
|
|
93
|
+
await tx`create unique index if not exists ${sql(`${table}_idempotency`)} on ${t} (queue, idempotency_key) where idempotency_key is not null and status <> 'dead'`;
|
|
94
|
+
await tx`create index if not exists ${sql(`${table}_due`)} on ${t} (queue, run_at) where status <> 'dead'`;
|
|
95
|
+
await tx`create index if not exists ${sql(`${table}_message`)} on ${t} (message_id)`;
|
|
96
|
+
});
|
|
97
|
+
})().catch((error) => {
|
|
98
|
+
ready = void 0;
|
|
99
|
+
throw error;
|
|
100
|
+
});
|
|
101
|
+
return ready;
|
|
102
|
+
}
|
|
103
|
+
function arm(ms) {
|
|
104
|
+
if (timer) clearTimeout(timer);
|
|
105
|
+
timer = void 0;
|
|
106
|
+
if (closed) return;
|
|
107
|
+
timer = setTimeout(wake, ms);
|
|
108
|
+
timer.unref?.();
|
|
109
|
+
}
|
|
110
|
+
function wake() {
|
|
111
|
+
if (closed) return;
|
|
112
|
+
if (pumping) {
|
|
113
|
+
pumpAgain = true;
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
pumping = pump();
|
|
117
|
+
}
|
|
118
|
+
async function queueConcurrency(queue) {
|
|
119
|
+
const known = concurrency.get(queue);
|
|
120
|
+
if (known !== void 0) return known;
|
|
121
|
+
const definition = await options.load(queue);
|
|
122
|
+
if (!definition) return void 0;
|
|
123
|
+
const limit = Number(definition.options?.concurrency ?? 1);
|
|
124
|
+
const value = Number.isFinite(limit) ? Math.max(1, Math.floor(limit)) : 1;
|
|
125
|
+
concurrency.set(queue, value);
|
|
126
|
+
return value;
|
|
127
|
+
}
|
|
128
|
+
/** Takes due jobs while a Queue Definition has a free slot, and starts them. */
|
|
129
|
+
async function pump() {
|
|
130
|
+
let wait = pollIntervalMs;
|
|
131
|
+
try {
|
|
132
|
+
if (closed) return;
|
|
133
|
+
await options.refreshConnection?.();
|
|
134
|
+
if (closed) return;
|
|
135
|
+
await ensureTable();
|
|
136
|
+
for (const queue of options.queues()) {
|
|
137
|
+
if (closed) return;
|
|
138
|
+
const limit = await queueConcurrency(queue).catch((error) => {
|
|
139
|
+
console.error(`[vitehub:queue] The postgres provider cannot load the Queue Definition "${queue}".`, error);
|
|
140
|
+
});
|
|
141
|
+
if (limit === void 0) continue;
|
|
142
|
+
const free = limit - (runningPerQueue.get(queue) ?? 0);
|
|
143
|
+
if (free <= 0) continue;
|
|
144
|
+
for (const row of await claim(queue, free)) start(row);
|
|
145
|
+
}
|
|
146
|
+
} catch (error) {
|
|
147
|
+
wait = Math.max(wait, 5e3);
|
|
148
|
+
console.error(`[vitehub:queue] The postgres provider cannot read the jobs in ${base}. It tries again in ${Math.round(wait / 1e3)} s.`, error);
|
|
149
|
+
} finally {
|
|
150
|
+
queueMicrotask(() => {
|
|
151
|
+
pumping = void 0;
|
|
152
|
+
if (pumpAgain && !closed) {
|
|
153
|
+
pumpAgain = false;
|
|
154
|
+
wake();
|
|
155
|
+
} else arm(wait);
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
async function claim(queue, limit) {
|
|
160
|
+
return await sql`
|
|
161
|
+
with next_jobs as materialized (
|
|
162
|
+
select id as claim_id from ${t}
|
|
163
|
+
where queue = ${queue} and run_at <= now() and (status = 'pending' or (status = 'running' and locked_until < now()))
|
|
164
|
+
${running.size ? sql`and id not in ${sql([...running.keys()])}` : sql``}
|
|
165
|
+
order by run_at, created_at
|
|
166
|
+
for update skip locked
|
|
167
|
+
limit ${limit}
|
|
168
|
+
)
|
|
169
|
+
update ${t} set status = 'running', attempts = attempts + 1, locked_by = ${workerId},
|
|
170
|
+
locked_until = now() + make_interval(secs => ${lockSeconds}), updated_at = now()
|
|
171
|
+
from next_jobs where id = next_jobs.claim_id
|
|
172
|
+
returning id, message_id, queue, payload, payload is null as no_payload, attempts, status, ${times}, last_error, idempotency_key, true as locked`;
|
|
173
|
+
}
|
|
174
|
+
function start(row) {
|
|
175
|
+
runningPerQueue.set(row.queue, (runningPerQueue.get(row.queue) ?? 0) + 1);
|
|
176
|
+
const delivery = deliver(row).finally(() => {
|
|
177
|
+
running.delete(row.id);
|
|
178
|
+
runningPerQueue.set(row.queue, (runningPerQueue.get(row.queue) ?? 1) - 1);
|
|
179
|
+
wake();
|
|
180
|
+
});
|
|
181
|
+
running.set(row.id, delivery);
|
|
182
|
+
}
|
|
183
|
+
async function pruneDead(queue) {
|
|
184
|
+
await sql`delete from ${t} where id in (
|
|
185
|
+
select id from ${t} where queue = ${queue} and status = 'dead' order by failed_at desc offset ${100}
|
|
186
|
+
)`;
|
|
187
|
+
}
|
|
188
|
+
async function markDead(row, error, reason) {
|
|
189
|
+
if (!(await sql`update ${t} set status = 'dead', last_error = ${JSON.stringify(error)}::text::jsonb, failed_at = now(), locked_by = null,
|
|
190
|
+
locked_until = null, updated_at = now() where id = ${row.id} and locked_by = ${workerId} and attempts = ${row.attempts}`).count) return;
|
|
191
|
+
console.error(`[vitehub:queue] The postgres provider stopped delivery of a "${row.queue}" job ${reason}. The job stays in ${base}.`);
|
|
192
|
+
await pruneDead(row.queue);
|
|
193
|
+
}
|
|
194
|
+
async function deliver(row) {
|
|
195
|
+
if (row.attempts > rules.maxAttempts) {
|
|
196
|
+
await markDead(row, {
|
|
197
|
+
message: "[vitehub] The process stopped during the last attempt of this job.",
|
|
198
|
+
name: "Error"
|
|
199
|
+
}, `after ${row.attempts - 1} attempts`).catch((error) => console.error(`[vitehub:queue] The postgres provider cannot update a job in ${base}.`, error));
|
|
200
|
+
return;
|
|
201
|
+
}
|
|
202
|
+
let handling = true;
|
|
203
|
+
const renew = setInterval(() => {
|
|
204
|
+
sql`update ${t} set locked_until = now() + make_interval(secs => ${lockSeconds}), updated_at = now()
|
|
205
|
+
where id = ${row.id} and locked_by = ${workerId} and attempts = ${row.attempts}`.then((result) => {
|
|
206
|
+
if (!result.count && handling) {
|
|
207
|
+
clearInterval(renew);
|
|
208
|
+
renewals.delete(renew);
|
|
209
|
+
console.warn(`[vitehub:queue] The postgres provider lost the claim of a "${row.queue}" job ${row.message_id}. Another delivery may be running.`);
|
|
210
|
+
}
|
|
211
|
+
}).catch((error) => {
|
|
212
|
+
console.error(`[vitehub:queue] The postgres provider cannot renew the claim of a "${row.queue}" job.`, error);
|
|
213
|
+
});
|
|
214
|
+
}, Math.max(250, lockSeconds * 1e3 / 3));
|
|
215
|
+
renewals.add(renew);
|
|
216
|
+
renew.unref?.();
|
|
217
|
+
let failure;
|
|
218
|
+
try {
|
|
219
|
+
const definition = await options.load(row.queue);
|
|
220
|
+
if (!definition) throw options.missing(row.queue);
|
|
221
|
+
await runInRunScopes(async () => {
|
|
222
|
+
checkQueueHandlerResponse(await definition.handler({
|
|
223
|
+
attempts: row.attempts,
|
|
224
|
+
id: row.message_id,
|
|
225
|
+
payload: row.no_payload ? void 0 : row.payload
|
|
226
|
+
}));
|
|
227
|
+
});
|
|
228
|
+
} catch (error) {
|
|
229
|
+
failure = { error };
|
|
230
|
+
} finally {
|
|
231
|
+
handling = false;
|
|
232
|
+
clearInterval(renew);
|
|
233
|
+
renewals.delete(renew);
|
|
234
|
+
}
|
|
235
|
+
try {
|
|
236
|
+
if (!failure) {
|
|
237
|
+
await sql`delete from ${t} where id = ${row.id} and locked_by = ${workerId} and attempts = ${row.attempts}`;
|
|
238
|
+
return;
|
|
239
|
+
}
|
|
240
|
+
const context = {
|
|
241
|
+
attempts: row.attempts,
|
|
242
|
+
development: options.development,
|
|
243
|
+
id: row.message_id,
|
|
244
|
+
provider: "postgres",
|
|
245
|
+
queue: row.queue
|
|
246
|
+
};
|
|
247
|
+
reportQueueDeliveryError(failure.error, context);
|
|
248
|
+
const report = createQueueDeliveryErrorReport(failure.error, context).error;
|
|
249
|
+
if (isNonRetryableQueueError(failure.error) || row.attempts >= rules.maxAttempts) {
|
|
250
|
+
await markDead(row, report, `after ${row.attempts} attempts`);
|
|
251
|
+
return;
|
|
252
|
+
}
|
|
253
|
+
await sql`update ${t} set status = 'pending', run_at = now() + make_interval(secs => ${retryDelayMs(row.attempts) / 1e3}),
|
|
254
|
+
last_error = ${JSON.stringify(report)}::text::jsonb, locked_by = null, locked_until = null, updated_at = now()
|
|
255
|
+
where id = ${row.id} and locked_by = ${workerId} and attempts = ${row.attempts}`;
|
|
256
|
+
} catch (storeError) {
|
|
257
|
+
console.error(`[vitehub:queue] The postgres provider cannot update a job in ${base}. The job runs again when its claim ends.`, storeError);
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
const columns = sql`id, message_id, queue, attempts, status, ${times}, last_error, idempotency_key,
|
|
261
|
+
(status = 'running' and locked_until >= now()) as locked`;
|
|
262
|
+
async function findJob(id, payload) {
|
|
263
|
+
await ensureTable();
|
|
264
|
+
const [row] = await sql`select ${columns}${payload ? sql`, payload, payload is null as no_payload` : sql``} from ${t}
|
|
265
|
+
where message_id = ${id} order by created_at desc limit 1`;
|
|
266
|
+
return row;
|
|
267
|
+
}
|
|
268
|
+
async function notify(queue) {
|
|
269
|
+
await sql`select pg_notify(${channel}, ${queue})`;
|
|
270
|
+
}
|
|
271
|
+
return {
|
|
272
|
+
base,
|
|
273
|
+
async clear(filter = {}) {
|
|
274
|
+
await ensureTable();
|
|
275
|
+
const state = filter.state === "dead" ? sql`status = 'dead'` : filter.state === "pending" ? sql`(status = 'pending' or (status = 'running' and locked_until < now()))` : sql`not (status = 'running' and locked_until >= now())`;
|
|
276
|
+
return (await sql`delete from ${t} where ${state}${filter.queue === void 0 ? sql`` : sql` and queue = ${filter.queue}`}`).count;
|
|
277
|
+
},
|
|
278
|
+
async close() {
|
|
279
|
+
if (closed) return;
|
|
280
|
+
closed = true;
|
|
281
|
+
if (timer) clearTimeout(timer);
|
|
282
|
+
timer = void 0;
|
|
283
|
+
await started;
|
|
284
|
+
await pumping;
|
|
285
|
+
let drainTimer;
|
|
286
|
+
await Promise.race([Promise.allSettled(running.values()), new Promise((resolve) => {
|
|
287
|
+
drainTimer = setTimeout(resolve, drainTimeoutMs);
|
|
288
|
+
})]);
|
|
289
|
+
clearTimeout(drainTimer);
|
|
290
|
+
for (const renew of renewals) clearInterval(renew);
|
|
291
|
+
renewals.clear();
|
|
292
|
+
if (running.size) console.warn(`[vitehub:queue] The postgres provider stopped with ${running.size} running job${running.size === 1 ? "" : "s"}. Another instance runs ${running.size === 1 ? "it" : "them"} again in ${lockSeconds} s.`);
|
|
293
|
+
await unlisten?.().catch(() => {});
|
|
294
|
+
if (ownsClient) await sql.end({ timeout: 5 });
|
|
295
|
+
},
|
|
296
|
+
async enqueue(queue, entries) {
|
|
297
|
+
const prepared = entries.map((entry) => {
|
|
298
|
+
const text = JSON.stringify(entry.payload);
|
|
299
|
+
return {
|
|
300
|
+
delaySeconds: delayMs(entry.delaySeconds, rules) / 1e3,
|
|
301
|
+
entry,
|
|
302
|
+
text
|
|
303
|
+
};
|
|
304
|
+
});
|
|
305
|
+
await ensureTable();
|
|
306
|
+
return await sql.begin(async (tx) => {
|
|
307
|
+
const accepted = [];
|
|
308
|
+
for (const { delaySeconds, entry, text } of prepared) {
|
|
309
|
+
const [row] = await tx`
|
|
310
|
+
insert into ${t} (id, message_id, queue, payload, run_at, idempotency_key)
|
|
311
|
+
values (${randomUUID()}, ${entry.id}, ${queue}, ${text === void 0 ? null : text}::text::jsonb,
|
|
312
|
+
now() + make_interval(secs => ${delaySeconds}), ${entry.idempotencyKey ?? null})
|
|
313
|
+
on conflict (queue, idempotency_key) where idempotency_key is not null and status <> 'dead'
|
|
314
|
+
do update set updated_at = ${t}.updated_at
|
|
315
|
+
returning message_id`;
|
|
316
|
+
accepted.push(row.message_id);
|
|
317
|
+
}
|
|
318
|
+
await tx`select pg_notify(${channel}, ${queue})`;
|
|
319
|
+
return accepted;
|
|
320
|
+
});
|
|
321
|
+
},
|
|
322
|
+
async job(id) {
|
|
323
|
+
const row = await findJob(id, true);
|
|
324
|
+
if (!row) return void 0;
|
|
325
|
+
return {
|
|
326
|
+
...toJobSummary(row),
|
|
327
|
+
...row.idempotency_key === null ? {} : { idempotencyKey: row.idempotency_key },
|
|
328
|
+
...row.no_payload ? {} : { payload: row.payload }
|
|
329
|
+
};
|
|
330
|
+
},
|
|
331
|
+
async jobs(filter = {}) {
|
|
332
|
+
await ensureTable();
|
|
333
|
+
const state = filter.state === "running" ? sql` and status = 'running' and locked_until >= now()` : filter.state === "pending" ? sql` and (status = 'pending' or (status = 'running' and locked_until < now()))` : filter.state === "dead" ? sql` and status = 'dead'` : sql``;
|
|
334
|
+
return (await sql`select ${columns} from ${t}
|
|
335
|
+
where true${filter.queue === void 0 ? sql`` : sql` and queue = ${filter.queue}`}${state}
|
|
336
|
+
order by created_at desc limit ${listLimit}`).map(toJobSummary);
|
|
337
|
+
},
|
|
338
|
+
provider: "postgres",
|
|
339
|
+
async retry(id) {
|
|
340
|
+
const row = await findJob(id, false);
|
|
341
|
+
if (!row) return "missing";
|
|
342
|
+
if (row.locked) return "running";
|
|
343
|
+
let updated;
|
|
344
|
+
try {
|
|
345
|
+
[updated] = row.status === "dead" ? await sql`update ${t} set status = 'pending', attempts = 0, last_error = null, failed_at = null,
|
|
346
|
+
run_at = now(), updated_at = now() where id = ${row.id} and status = 'dead' returning ${columns}` : await sql`update ${t} set run_at = now(), updated_at = now()
|
|
347
|
+
where id = ${row.id} and not (status = 'running' and locked_until >= now()) returning ${columns}`;
|
|
348
|
+
} catch (error) {
|
|
349
|
+
if (error instanceof postgres.PostgresError && error.code === "23505") return "duplicate";
|
|
350
|
+
throw error;
|
|
351
|
+
}
|
|
352
|
+
if (!updated) return "running";
|
|
353
|
+
await notify(row.queue);
|
|
354
|
+
return toJobSummary(updated);
|
|
355
|
+
},
|
|
356
|
+
rules,
|
|
357
|
+
start() {
|
|
358
|
+
if (closed) return Promise.resolve();
|
|
359
|
+
started ??= (async () => {
|
|
360
|
+
try {
|
|
361
|
+
unlisten = (await sql.listen(channel, () => wake())).unlisten;
|
|
362
|
+
} catch (error) {
|
|
363
|
+
console.warn(`[vitehub:queue] The postgres provider cannot LISTEN on ${base}. It checks for jobs every ${pollIntervalMs} ms.`, error);
|
|
364
|
+
}
|
|
365
|
+
wake();
|
|
366
|
+
})();
|
|
367
|
+
return started;
|
|
368
|
+
},
|
|
369
|
+
async status() {
|
|
370
|
+
await ensureTable();
|
|
371
|
+
const rows = await sql`select queue,
|
|
372
|
+
count(*) filter (where status = 'dead')::int as dead,
|
|
373
|
+
count(*) filter (where status = 'running' and locked_until >= now())::int as running,
|
|
374
|
+
count(*) filter (where status = 'pending' or (status = 'running' and locked_until < now()))::int as pending
|
|
375
|
+
from ${t} group by queue`;
|
|
376
|
+
const queues = {};
|
|
377
|
+
for (const { queue, ...counts } of rows) queues[queue] = counts;
|
|
378
|
+
return {
|
|
379
|
+
base,
|
|
380
|
+
deadLimit: 100,
|
|
381
|
+
durability: "shared",
|
|
382
|
+
queues
|
|
383
|
+
};
|
|
384
|
+
},
|
|
385
|
+
workerId
|
|
386
|
+
};
|
|
387
|
+
}
|
|
388
|
+
function createPostgresQueueClient(engine, queue, resolveEngine) {
|
|
389
|
+
let activeEngine = engine;
|
|
390
|
+
async function enqueue(entries) {
|
|
391
|
+
const current = resolveEngine ? await resolveEngine() : engine;
|
|
392
|
+
activeEngine = current;
|
|
393
|
+
return await current.enqueue(queue, entries);
|
|
394
|
+
}
|
|
395
|
+
return {
|
|
396
|
+
provider: "postgres",
|
|
397
|
+
get native() {
|
|
398
|
+
return activeEngine;
|
|
399
|
+
},
|
|
400
|
+
queue,
|
|
401
|
+
async send(payload, options) {
|
|
402
|
+
const normalized = normalizeQueueEnqueueInput(payload, options);
|
|
403
|
+
const optionsError = queueUnsupportedOptionsError(normalized.options, "postgres", engine.rules.unsupportedOptions);
|
|
404
|
+
if (optionsError) return [optionsError, void 0];
|
|
405
|
+
const [error, ids] = await queueProviderResult("postgres", "send", () => enqueue([{
|
|
406
|
+
delaySeconds: normalized.options.delaySeconds,
|
|
407
|
+
id: normalized.id,
|
|
408
|
+
idempotencyKey: normalized.options.idempotencyKey,
|
|
409
|
+
payload: normalized.payload
|
|
410
|
+
}]));
|
|
411
|
+
if (error) return [error, void 0];
|
|
412
|
+
return [void 0, {
|
|
413
|
+
messageId: ids[0],
|
|
414
|
+
status: "queued"
|
|
415
|
+
}];
|
|
416
|
+
},
|
|
417
|
+
async sendBatch(items, options) {
|
|
418
|
+
const [error, ids] = await queueProviderResult("postgres", "send-batch", () => enqueue(items.map((item) => ({
|
|
419
|
+
delaySeconds: item.delaySeconds ?? options?.delaySeconds,
|
|
420
|
+
id: createQueueMessageId(),
|
|
421
|
+
idempotencyKey: item.idempotencyKey,
|
|
422
|
+
payload: item.body
|
|
423
|
+
}))));
|
|
424
|
+
if (error) return [error, void 0];
|
|
425
|
+
return [void 0, ids.map((messageId) => ({
|
|
426
|
+
messageId,
|
|
427
|
+
status: "queued"
|
|
428
|
+
}))];
|
|
429
|
+
}
|
|
430
|
+
};
|
|
431
|
+
}
|
|
432
|
+
//#endregion
|
|
433
|
+
//#region src/internal/runtime/postgres-client.ts
|
|
434
|
+
const postgresUrl = /^postgres(?:ql)?:\/\//i;
|
|
435
|
+
let loadDatabases;
|
|
436
|
+
let closing;
|
|
437
|
+
const engines = /* @__PURE__ */ new Map();
|
|
438
|
+
const retiring = /* @__PURE__ */ new Set();
|
|
439
|
+
function assertOpen() {
|
|
440
|
+
if (closing) throw queueErrorDiagnostics.QUEUE_POSTGRES_CLOSING();
|
|
441
|
+
}
|
|
442
|
+
function engineState(config) {
|
|
443
|
+
const key = JSON.stringify([config.database ?? null, config.development === true]);
|
|
444
|
+
let state = engines.get(key);
|
|
445
|
+
if (!state) {
|
|
446
|
+
state = { workers: false };
|
|
447
|
+
engines.set(key, state);
|
|
448
|
+
}
|
|
449
|
+
return state;
|
|
450
|
+
}
|
|
451
|
+
function startWorkers(state, engine) {
|
|
452
|
+
if (!state.workers || state.started === engine) return;
|
|
453
|
+
state.started = engine;
|
|
454
|
+
console.info(`[vitehub:queue] Queue uses the postgres driver. Jobs are in ${engine.base}. Every instance of the app takes jobs from it.`);
|
|
455
|
+
engine.start().catch((error) => {
|
|
456
|
+
console.error(`[vitehub:queue] The postgres driver cannot start the workers on ${engine.base}.`, error);
|
|
457
|
+
});
|
|
458
|
+
}
|
|
459
|
+
/**
|
|
460
|
+
* The connection of the jobs: `QUEUE_POSTGRES_URL` when it is set, else the postgres.js client of the Database that the
|
|
461
|
+
* build found on Postgres. The jobs then use the connection that the Database resolves, whatever variable it reads.
|
|
462
|
+
*/
|
|
463
|
+
async function resolvePostgresQueueConnection(config, databases = loadDatabases, env = process.env) {
|
|
464
|
+
const url = env[postgresQueueUrlVariable]?.trim();
|
|
465
|
+
if (url) {
|
|
466
|
+
if (!postgresUrl.test(url)) throw queueErrorDiagnostics.QUEUE_POSTGRES_INVALID_URL({ variable: postgresQueueUrlVariable });
|
|
467
|
+
return {
|
|
468
|
+
connection: { url },
|
|
469
|
+
key: url
|
|
470
|
+
};
|
|
471
|
+
}
|
|
472
|
+
if (config.database && databases) {
|
|
473
|
+
const entry = (await databases())[config.database];
|
|
474
|
+
const client = entry ? Reflect.get(entry.db, "$client") : void 0;
|
|
475
|
+
if (isPostgresQueueSql(client)) return {
|
|
476
|
+
connection: { client },
|
|
477
|
+
key: client
|
|
478
|
+
};
|
|
479
|
+
}
|
|
480
|
+
throw queueErrorDiagnostics.QUEUE_POSTGRES_MISSING_CONNECTION({ database: config.database });
|
|
481
|
+
}
|
|
482
|
+
function usePostgresQueueEngine(config) {
|
|
483
|
+
assertOpen();
|
|
484
|
+
const state = engineState(config);
|
|
485
|
+
const pending = (state.pending?.catch(() => {}) ?? Promise.resolve()).then(async () => {
|
|
486
|
+
assertOpen();
|
|
487
|
+
const { connection, key } = await resolvePostgresQueueConnection(config);
|
|
488
|
+
assertOpen();
|
|
489
|
+
if (state.current?.key === key) {
|
|
490
|
+
startWorkers(state, state.current.engine);
|
|
491
|
+
return state.current.engine;
|
|
492
|
+
}
|
|
493
|
+
const previous = state.current?.engine;
|
|
494
|
+
const engine = createPostgresQueueEngine({
|
|
495
|
+
connection,
|
|
496
|
+
development: config.development === true,
|
|
497
|
+
load: loadQueueDefinition,
|
|
498
|
+
missing: missingQueueDefinitionError,
|
|
499
|
+
queues: listQueueDefinitionNames,
|
|
500
|
+
refreshConnection: async () => {
|
|
501
|
+
await usePostgresQueueEngine(config);
|
|
502
|
+
}
|
|
503
|
+
});
|
|
504
|
+
state.current = {
|
|
505
|
+
engine,
|
|
506
|
+
key
|
|
507
|
+
};
|
|
508
|
+
if (previous) {
|
|
509
|
+
const closing = previous.close().catch((error) => {
|
|
510
|
+
console.error("[vitehub:queue] The postgres driver cannot close its previous connection.", error);
|
|
511
|
+
}).finally(() => retiring.delete(closing));
|
|
512
|
+
retiring.add(closing);
|
|
513
|
+
}
|
|
514
|
+
startWorkers(state, engine);
|
|
515
|
+
return engine;
|
|
516
|
+
});
|
|
517
|
+
state.pending = pending;
|
|
518
|
+
return pending;
|
|
519
|
+
}
|
|
520
|
+
async function createPostgresQueueRuntimeClient(options) {
|
|
521
|
+
if (options.driver !== "postgres") throw queueErrorDiagnostics.QUEUE_DRIVER_MISMATCH({
|
|
522
|
+
driver: options.driver,
|
|
523
|
+
expected: "postgres"
|
|
524
|
+
});
|
|
525
|
+
if (!options.queue) throw queueErrorDiagnostics.QUEUE_MISSING_QUEUE();
|
|
526
|
+
return createPostgresQueueClient(await usePostgresQueueEngine(options), options.queue, () => usePostgresQueueEngine(options));
|
|
527
|
+
}
|
|
528
|
+
/**
|
|
529
|
+
* Starts the workers when the server starts: this process takes the due jobs of every Queue Definition from Postgres.
|
|
530
|
+
* `databases` loads the Databases of the app, for a build that found its Default Database on Postgres. Logs once where
|
|
531
|
+
* the jobs are.
|
|
532
|
+
*/
|
|
533
|
+
function startPostgresQueue(config, databases) {
|
|
534
|
+
if (config === false || config.driver !== "postgres") return;
|
|
535
|
+
assertOpen();
|
|
536
|
+
loadDatabases = databases;
|
|
537
|
+
engineState(config).workers = true;
|
|
538
|
+
setQueueRuntimeJobStore(() => usePostgresQueueEngine(config));
|
|
539
|
+
usePostgresQueueEngine(config).catch((error) => {
|
|
540
|
+
console.error("[vitehub:queue] The postgres driver cannot start the workers.", error);
|
|
541
|
+
});
|
|
542
|
+
}
|
|
543
|
+
/** Stops taking jobs, waits for the running jobs up to 10 seconds, and closes the connections it opened. The jobs stay. */
|
|
544
|
+
function closePostgresQueues() {
|
|
545
|
+
if (closing) return closing;
|
|
546
|
+
closing = (async () => {
|
|
547
|
+
const states = [...engines.values()];
|
|
548
|
+
for (const state of states) state.workers = false;
|
|
549
|
+
setQueueRuntimeJobStore(void 0);
|
|
550
|
+
await Promise.all(states.map((state) => state.pending?.catch(() => {})));
|
|
551
|
+
await Promise.all([...states.map((state) => state.current?.engine.close()), ...retiring]);
|
|
552
|
+
engines.clear();
|
|
553
|
+
loadDatabases = void 0;
|
|
554
|
+
})().finally(() => {
|
|
555
|
+
closing = void 0;
|
|
556
|
+
});
|
|
557
|
+
return closing;
|
|
558
|
+
}
|
|
559
|
+
//#endregion
|
|
560
|
+
export { closePostgresQueues, createPostgresQueueRuntimeClient, resolvePostgresQueueConnection, startPostgresQueue };
|
|
@@ -1,9 +1,16 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { S as QueueDefinitionRegistry, b as QueueDefinition, k as QueueJobStore, y as QueueClient } from "../../types-BD-8U9zS.js";
|
|
2
|
+
import { n as QueueRuntimeOptions, t as QueueRuntimeDriverOptions } from "../../types-DS_rqu9l.js";
|
|
2
3
|
//#region src/internal/runtime/state.d.ts
|
|
3
|
-
export type QueueRuntimeClientFactory = (options:
|
|
4
|
+
export type QueueRuntimeClientFactory = (options: QueueRuntimeDriverOptions) => QueueClient | Promise<QueueClient>;
|
|
4
5
|
export declare function missingQueueDefinitionError(queue: string): Error;
|
|
5
|
-
export declare function setQueueRuntimeConfig(config: false |
|
|
6
|
-
|
|
6
|
+
export declare function setQueueRuntimeConfig(config: false | QueueRuntimeOptions | undefined, createClient?: QueueRuntimeClientFactory): void;
|
|
7
|
+
/**
|
|
8
|
+
* The stored jobs of a provider that does not keep them in this package's process state. The generated server sets it
|
|
9
|
+
* for the postgres provider, so the Queue operations read jobs without importing the Postgres driver.
|
|
10
|
+
*/
|
|
11
|
+
export declare function setQueueRuntimeJobStore(store: (() => Promise<QueueJobStore> | QueueJobStore) | undefined): void;
|
|
12
|
+
export declare function getQueueRuntimeJobStore(): Promise<QueueJobStore | undefined>;
|
|
13
|
+
export declare function getQueueRuntimeConfig(): false | QueueRuntimeOptions | undefined;
|
|
7
14
|
export declare function getQueueRuntimeClientFactory(): QueueRuntimeClientFactory | undefined;
|
|
8
15
|
export declare function runWithQueueRuntimeEvent<T>(event: unknown, callback: () => T): T;
|
|
9
16
|
export declare function enterQueueRuntimeEvent(event: unknown): void;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as getQueueRuntimeEvent, c as
|
|
2
|
-
export { enterQueueRuntimeEvent, getOrCreateQueueClient, getQueueRuntimeClientFactory, getQueueRuntimeConfig, getQueueRuntimeEvent, listQueueDefinitionNames, loadQueueDefinition, missingQueueDefinitionError, runWithQueueRuntimeEvent, setQueueRuntimeConfig, setQueueRuntimeEventDefaults, setQueueRuntimeRegistry };
|
|
1
|
+
import { a as getQueueRuntimeEvent, c as loadQueueDefinition, d as setQueueRuntimeConfig, f as setQueueRuntimeEventDefaults, i as getQueueRuntimeConfig, l as missingQueueDefinitionError, m as setQueueRuntimeRegistry, n as getOrCreateQueueClient, o as getQueueRuntimeJobStore, p as setQueueRuntimeJobStore, r as getQueueRuntimeClientFactory, s as listQueueDefinitionNames, t as enterQueueRuntimeEvent, u as runWithQueueRuntimeEvent } from "../../state-mVA2X_wa.js";
|
|
2
|
+
export { enterQueueRuntimeEvent, getOrCreateQueueClient, getQueueRuntimeClientFactory, getQueueRuntimeConfig, getQueueRuntimeEvent, getQueueRuntimeJobStore, listQueueDefinitionNames, loadQueueDefinition, missingQueueDefinitionError, runWithQueueRuntimeEvent, setQueueRuntimeConfig, setQueueRuntimeEventDefaults, setQueueRuntimeJobStore, setQueueRuntimeRegistry };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { w as QueueDriverOptions, y as QueueClient } from "../../types-BD-8U9zS.js";
|
|
2
2
|
//#region src/internal/runtime/vercel-client.d.ts
|
|
3
|
-
export declare function createVercelQueueRuntimeClient(options:
|
|
3
|
+
export declare function createVercelQueueRuntimeClient(options: QueueDriverOptions): Promise<QueueClient>;
|
|
4
4
|
//#endregion
|