@vite-hub/queue 0.6.1 → 0.7.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/README.md +17 -12
- package/dist/{client-CwoCdKct.js → client-B8QVg1mA.js} +46 -15
- package/dist/{cloudflare-client-xWteD-su.js → cloudflare-client-BoaOlFzD.js} +13 -8
- package/dist/{cloudflare-resource-name-Bv8Z7nDU.js → cloudflare-resource-name-Coz5CPmn.js} +1 -1
- package/dist/{config-Bzp1xmdh.js → config-ByKUipob.js} +4 -2
- package/dist/{definition-CIiFfst2.js → definition-Dorliu47.js} +9 -2
- package/dist/{duration-C5w_-Rf4.js → duration-CcLSF94z.js} +20 -5
- package/dist/{error-diagnostics-kKXseq8d.js → error-diagnostics-CsiNo_oI.js} +3 -3
- package/dist/{error-diagnostics-Dv6nKZQW.js → error-diagnostics-Yj8XCiya.js} +30 -6
- package/dist/{handler-response-CchTXVjm.js → handler-response-GFXYd6mF.js} +6 -2
- package/dist/index.d.ts +13 -8
- package/dist/index.js +4 -4
- package/dist/internal/runtime/cloudflare-client.d.ts +1 -1
- package/dist/internal/runtime/cloudflare-client.js +1 -1
- package/dist/internal/runtime/cloudflare-vite.d.ts +1 -1
- package/dist/internal/runtime/cloudflare-vite.js +9 -8
- package/dist/internal/runtime/local-client.d.ts +3 -3
- package/dist/internal/runtime/local-client.js +4 -4
- package/dist/internal/runtime/postgres-client.d.ts +8 -6
- package/dist/internal/runtime/postgres-client.js +174 -36
- package/dist/internal/runtime/state.d.ts +5 -3
- package/dist/internal/runtime/state.js +1 -1
- package/dist/internal/runtime/vercel-client.d.ts +1 -1
- package/dist/internal/runtime/vercel-client.js +24 -5
- package/dist/internal/runtime/worker-client.d.ts +2 -2
- package/dist/internal/runtime/worker-client.js +1 -1
- package/dist/{local-RX10a_Sq.js → local-BR4W57HU.js} +146 -97
- package/dist/{local-B72WRWkS.d.ts → local-DUh8sGn-.d.ts} +1 -1
- package/dist/{operations-CoEXxfUW.js → operations-COCpSoua.js} +11 -6
- package/dist/{operation-definition-CqZkx1Rm.d.ts → operations-DSslh_vK.d.ts} +169 -1
- package/dist/operations.d.ts +13 -4
- package/dist/operations.js +98 -37
- package/dist/retries-BSAZru9n.js +27 -0
- package/dist/run-handler-B_RVXMs5.js +61 -0
- package/dist/runtime/hosted.d.ts +1 -1
- package/dist/runtime/hosted.js +32 -20
- package/dist/{state-DqxeV11k.js → state-C-t99I4Q.js} +9 -3
- package/dist/{types-BevEYrUV.d.ts → types-BPs6OsRv.d.ts} +1 -1
- package/dist/{types-BzPGPV9z.d.ts → types-rZHAtkK0.d.ts} +74 -12
- package/dist/{vercel-region-DEsR1YJQ.js → vercel-region-Bp3hwRBr.js} +1 -1
- package/dist/vite.d.ts +2 -155
- package/dist/vite.js +460 -68
- package/package.json +3 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
export { t as createCloudflareQueueRuntimeClient } from "../../cloudflare-client-
|
|
1
|
+
export { t as createCloudflareQueueRuntimeClient } from "../../cloudflare-client-BoaOlFzD.js";
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { U as ResolvedQueueOptions, a as CloudflareQueueMessageBatch, w as QueueDefinitionRegistry } from "../../types-rZHAtkK0.js";
|
|
2
2
|
type CloudflareWorkerEnv = Record<string, unknown>;
|
|
3
3
|
interface CloudflareWorkerExecutionContext {
|
|
4
4
|
waitUntil?: (promise: Promise<unknown>) => void;
|
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import { t as internalErrorDiagnostics } from "../../error-diagnostics-
|
|
2
|
-
import { n as normalizeQueueOptions } from "../../config-
|
|
1
|
+
import { t as internalErrorDiagnostics } from "../../error-diagnostics-CsiNo_oI.js";
|
|
2
|
+
import { n as normalizeQueueOptions } from "../../config-ByKUipob.js";
|
|
3
3
|
import { n as getCloudflareQueueDefinitionName } from "../../cloudflare-BMc35cBD.js";
|
|
4
|
-
import { t as getCloudflareQueueName } from "../../cloudflare-resource-name-
|
|
5
|
-
import { n as createCloudflareQueueBatchHandler, t as createCloudflareQueueRuntimeClient } from "../../cloudflare-client-
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
4
|
+
import { t as getCloudflareQueueName } from "../../cloudflare-resource-name-Coz5CPmn.js";
|
|
5
|
+
import { n as createCloudflareQueueBatchHandler, t as createCloudflareQueueRuntimeClient } from "../../cloudflare-client-BoaOlFzD.js";
|
|
6
|
+
import { t as runQueueHandler } from "../../run-handler-B_RVXMs5.js";
|
|
7
|
+
import { d as runWithQueueRuntimeEvent, f as setQueueRuntimeConfig, g as createCloudflareRuntimeEvent, h as setQueueRuntimeRegistry, l as loadQueueDefinition, v as runWithActiveCloudflareEnv } from "../../state-C-t99I4Q.js";
|
|
8
|
+
import { t as queueErrorDiagnostics } from "../../error-diagnostics-Yj8XCiya.js";
|
|
9
9
|
// ../internal/src/runtime/app.ts
|
|
10
10
|
function resolveAppFetch(label, app) {
|
|
11
11
|
if (!app) return;
|
|
@@ -95,9 +95,10 @@ function createQueueCloudflareWorker(options = {}) {
|
|
|
95
95
|
await createCloudflareQueueBatchHandler({
|
|
96
96
|
concurrency: definition.concurrency,
|
|
97
97
|
onError: definition.onError,
|
|
98
|
+
retries: definition.retries,
|
|
98
99
|
onMessage: async (message, currentBatch) => {
|
|
99
100
|
await runWithQueueRuntimeEvent(runtimeEvent, async () => {
|
|
100
|
-
await
|
|
101
|
+
await runQueueHandler(definition, createQueueJob(message, currentBatch), definitionName);
|
|
101
102
|
});
|
|
102
103
|
},
|
|
103
104
|
queue: definitionName
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { t as LocalQueueEngine } from "../../local-
|
|
2
|
-
import {
|
|
3
|
-
import { n as QueueRuntimeOptions, t as QueueRuntimeDriverOptions } from "../../types-
|
|
1
|
+
import { t as LocalQueueEngine } from "../../local-DUh8sGn-.js";
|
|
2
|
+
import { h as LocalQueueStatus, x as QueueClient } from "../../types-rZHAtkK0.js";
|
|
3
|
+
import { n as QueueRuntimeOptions, t as QueueRuntimeDriverOptions } from "../../types-BPs6OsRv.js";
|
|
4
4
|
export declare function createLocalQueueRuntimeClient(options: QueueRuntimeDriverOptions): Promise<QueueClient>;
|
|
5
5
|
/**
|
|
6
6
|
* Starts delivery of the stored jobs when the server starts, so jobs from before a restart run without a new send.
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { t as defaultLocalQueueBase } from "../../config-
|
|
2
|
-
import { i as localQueueDeliveryRules, n as createLocalQueueEngine, t as createLocalQueueClient } from "../../local-
|
|
3
|
-
import {
|
|
4
|
-
import { t as queueErrorDiagnostics } from "../../error-diagnostics-
|
|
1
|
+
import { t as defaultLocalQueueBase } from "../../config-ByKUipob.js";
|
|
2
|
+
import { i as localQueueDeliveryRules, n as createLocalQueueEngine, t as createLocalQueueClient } from "../../local-BR4W57HU.js";
|
|
3
|
+
import { l as loadQueueDefinition, u as missingQueueDefinitionError } from "../../state-C-t99I4Q.js";
|
|
4
|
+
import { t as queueErrorDiagnostics } from "../../error-diagnostics-Yj8XCiya.js";
|
|
5
5
|
import { resolve } from "pathe";
|
|
6
6
|
// src/internal/runtime/local-client.ts
|
|
7
7
|
const engines = /* @__PURE__ */ new Map();
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import "../../local-
|
|
3
|
-
import { n as QueueRuntimeOptions, t as QueueRuntimeDriverOptions } from "../../types-
|
|
1
|
+
import { x as QueueClient } from "../../types-rZHAtkK0.js";
|
|
2
|
+
import "../../local-DUh8sGn-.js";
|
|
3
|
+
import { n as QueueRuntimeOptions, t as QueueRuntimeDriverOptions } from "../../types-BPs6OsRv.js";
|
|
4
4
|
import postgres from "postgres";
|
|
5
5
|
/** A postgres.js client. */
|
|
6
6
|
type PostgresQueueSql = postgres.Sql;
|
|
@@ -33,12 +33,14 @@ export declare function resolvePostgresQueueConnection(config: {
|
|
|
33
33
|
database?: string;
|
|
34
34
|
}, databases?: PostgresQueueDatabasesLoader | undefined, env?: Record<string, string | undefined>): Promise<ResolvedConnection>;
|
|
35
35
|
export declare function createPostgresQueueRuntimeClient(options: QueueRuntimeDriverOptions): Promise<QueueClient>;
|
|
36
|
+
export declare function readQueueWorkers(): boolean;
|
|
36
37
|
/**
|
|
37
38
|
* Starts the workers when the server starts: this process takes the due jobs of every Queue Definition from Postgres.
|
|
38
|
-
* `
|
|
39
|
-
* the
|
|
39
|
+
* With `QUEUE_WORKERS=false`, it only sends jobs, so the same build runs as a web server or as a worker. Another value
|
|
40
|
+
* than `true` or `false` throws `QUEUE_WORKERS_INVALID`. `databases` loads the Databases of the app, for a build that found
|
|
41
|
+
* its Default Database on Postgres. Logs once where the jobs are.
|
|
40
42
|
*/
|
|
41
|
-
export declare function startPostgresQueue(config: false | QueueRuntimeOptions, databases?: PostgresQueueDatabasesLoader): void;
|
|
43
|
+
export declare function startPostgresQueue(config: false | QueueRuntimeOptions, databases?: PostgresQueueDatabasesLoader, workers?: boolean): void;
|
|
42
44
|
/** Stops taking jobs, waits for the running jobs up to 10 seconds, and closes the connections it opened. The jobs stay. */
|
|
43
45
|
export declare function closePostgresQueues(): Promise<void>;
|
|
44
46
|
export {};
|
|
@@ -1,14 +1,39 @@
|
|
|
1
|
-
import { r as postgresQueueUrlVariable } from "../../config-
|
|
1
|
+
import { i as queueWorkersVariable, r as postgresQueueUrlVariable } from "../../config-ByKUipob.js";
|
|
2
2
|
import { t as invariant } from "../../invariant-CmdvZ3vp.js";
|
|
3
|
-
import { c as
|
|
4
|
-
import {
|
|
5
|
-
import { i as
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
3
|
+
import { c as queueBatchOptionsError, d as queueUnsupportedOptionsError, i as isQueueError, l as queueProviderResult, m as normalizeQueueEnqueueInput, p as createQueueMessageId, s as postgresUnsupportedEnqueueOptions, t as readQueueTimes } from "../../duration-CcLSF94z.js";
|
|
4
|
+
import { t as queueErrorDiagnostics } from "../../error-diagnostics-Yj8XCiya.js";
|
|
5
|
+
import { i as reportQueueDeliveryError, n as createQueueDeliveryErrorReport, r as isNonRetryableQueueError } from "../../handler-response-GFXYd6mF.js";
|
|
6
|
+
import { n as isRecord } from "../../object-DRSmpe04.js";
|
|
7
|
+
import { n as queueRetryPolicy } from "../../retries-BSAZru9n.js";
|
|
8
|
+
import { n as runQueueJob } from "../../run-handler-B_RVXMs5.js";
|
|
9
|
+
import { i as localQueueDeliveryRules, r as delayMs } from "../../local-BR4W57HU.js";
|
|
10
|
+
import { c as listQueueDefinitionNames, l as loadQueueDefinition, m as setQueueRuntimeJobStore, u as missingQueueDefinitionError } from "../../state-C-t99I4Q.js";
|
|
8
11
|
import { hostname } from "node:os";
|
|
9
12
|
import { randomUUID } from "node:crypto";
|
|
10
|
-
import { runInRunScopes } from "@vite-hub/runtime/internal/run-scope";
|
|
11
13
|
import postgres from "postgres";
|
|
14
|
+
// src/internal/postgres-transaction.ts
|
|
15
|
+
const transactionActive = Symbol.for("vitehub.database.postgres.transaction-active");
|
|
16
|
+
function readRows(value) {
|
|
17
|
+
const rows = Array.isArray(value) ? value : isRecord(value) ? value.rows : void 0;
|
|
18
|
+
return Array.isArray(rows) ? rows.filter(isRecord) : [];
|
|
19
|
+
}
|
|
20
|
+
function postgresTransactionQuery(transaction) {
|
|
21
|
+
const session = isRecord(transaction) && typeof transaction.rollback === "function" && isRecord(transaction._) ? transaction._.session : void 0;
|
|
22
|
+
const client = isRecord(session) ? session.client : void 0;
|
|
23
|
+
const query = typeof client === "function" ? Reflect.get(client, "unsafe") : isRecord(client) ? client.query : void 0;
|
|
24
|
+
if (typeof query !== "function") throw queueErrorDiagnostics.QUEUE_TRANSACTION_DATABASE_MISMATCH({ reason: "driver" });
|
|
25
|
+
const active = Reflect.get(transaction, transactionActive);
|
|
26
|
+
if (typeof active !== "function") throw queueErrorDiagnostics.QUEUE_TRANSACTION_DATABASE_MISMATCH({ reason: "driver" });
|
|
27
|
+
const assertActive = () => {
|
|
28
|
+
if (!active()) throw queueErrorDiagnostics.QUEUE_TRANSACTION_DATABASE_MISMATCH({ reason: "scope" });
|
|
29
|
+
};
|
|
30
|
+
assertActive();
|
|
31
|
+
return (text, params) => {
|
|
32
|
+
assertActive();
|
|
33
|
+
const pending = Reflect.apply(query, client, [text, params]);
|
|
34
|
+
return new Promise((resolve, reject) => pending.then(resolve, reject)).then(readRows);
|
|
35
|
+
};
|
|
36
|
+
}
|
|
12
37
|
const listLimit = 1e3;
|
|
13
38
|
const identifier = /^[a-z_][a-z\d_]{0,62}$/;
|
|
14
39
|
/** Returns `true` for a postgres.js client, such as the `$client` of a Postgres Database. */
|
|
@@ -41,8 +66,10 @@ function toJobSummary(row) {
|
|
|
41
66
|
function createPostgresQueueEngine(options) {
|
|
42
67
|
const table = options.table ?? "vitehub_queue_jobs";
|
|
43
68
|
invariant(identifier.test(table), "the Queue table name is a lowercase SQL identifier, because only the Queue runtime and its tests choose it");
|
|
44
|
-
const rules =
|
|
45
|
-
|
|
69
|
+
const rules = {
|
|
70
|
+
...localQueueDeliveryRules.postgres,
|
|
71
|
+
unsupportedOptions: postgresUnsupportedEnqueueOptions
|
|
72
|
+
};
|
|
46
73
|
const lockSeconds = options.lockSeconds ?? 30;
|
|
47
74
|
const pollIntervalMs = options.pollIntervalMs ?? 1e3;
|
|
48
75
|
const drainTimeoutMs = options.drainTimeoutMs ?? 1e4;
|
|
@@ -50,6 +77,18 @@ function createPostgresQueueEngine(options) {
|
|
|
50
77
|
const channel = table;
|
|
51
78
|
const ownsClient = "url" in options.connection;
|
|
52
79
|
const sql = "url" in options.connection ? postgres(options.connection.url, { onnotice: () => {} }) : options.connection.client;
|
|
80
|
+
let control;
|
|
81
|
+
function controlClient() {
|
|
82
|
+
if (ownsClient) return sql;
|
|
83
|
+
if (control) return control;
|
|
84
|
+
const client = Reflect.apply(postgres, void 0, [{
|
|
85
|
+
...sql.options,
|
|
86
|
+
max: 1,
|
|
87
|
+
idle_timeout: 20
|
|
88
|
+
}]);
|
|
89
|
+
invariant(isPostgresQueueSql(client), "postgres.js returns a SQL client from its parsed options");
|
|
90
|
+
return control = client;
|
|
91
|
+
}
|
|
53
92
|
const base = describePostgresQueueLocation(sql, table);
|
|
54
93
|
const t = sql(table);
|
|
55
94
|
const times = sql`to_json(run_at) #>> '{}' as run_at, to_json(created_at) #>> '{}' as created_at, to_json(failed_at) #>> '{}' as failed_at`;
|
|
@@ -65,6 +104,7 @@ function createPostgresQueueEngine(options) {
|
|
|
65
104
|
let pumpAgain = false;
|
|
66
105
|
let closed = false;
|
|
67
106
|
function ensureTable() {
|
|
107
|
+
const sql = controlClient();
|
|
68
108
|
ready ??= (async () => {
|
|
69
109
|
try {
|
|
70
110
|
await sql`select 1 from ${t} limit 0`;
|
|
@@ -188,8 +228,16 @@ function createPostgresQueueEngine(options) {
|
|
|
188
228
|
console.error(`[vitehub:queue] The postgres provider stopped delivery of a "${row.queue}" job ${reason}. The job stays in ${base}.`);
|
|
189
229
|
await pruneDead(row.queue);
|
|
190
230
|
}
|
|
231
|
+
function retryPolicy(definition) {
|
|
232
|
+
const policy = queueRetryPolicy(definition?.retries);
|
|
233
|
+
return options.retryDelayMs ? {
|
|
234
|
+
...policy,
|
|
235
|
+
delayMs: options.retryDelayMs
|
|
236
|
+
} : policy;
|
|
237
|
+
}
|
|
191
238
|
async function deliver(row) {
|
|
192
|
-
|
|
239
|
+
const retries = await options.load(row.queue).then(retryPolicy).catch(() => retryPolicy(void 0));
|
|
240
|
+
if (row.attempts > retries.limit + 1) {
|
|
193
241
|
await markDead(row, {
|
|
194
242
|
message: "[vitehub] The process stopped during the last attempt of this job.",
|
|
195
243
|
name: "Error"
|
|
@@ -215,13 +263,11 @@ function createPostgresQueueEngine(options) {
|
|
|
215
263
|
try {
|
|
216
264
|
const definition = await options.load(row.queue);
|
|
217
265
|
if (!definition) throw options.missing(row.queue);
|
|
218
|
-
await
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
}));
|
|
224
|
-
});
|
|
266
|
+
await runQueueJob(definition, {
|
|
267
|
+
attempts: row.attempts,
|
|
268
|
+
id: row.message_id,
|
|
269
|
+
payload: row.no_payload ? void 0 : row.payload
|
|
270
|
+
}, row.queue);
|
|
225
271
|
} catch (error) {
|
|
226
272
|
failure = { error };
|
|
227
273
|
} finally {
|
|
@@ -243,11 +289,11 @@ function createPostgresQueueEngine(options) {
|
|
|
243
289
|
};
|
|
244
290
|
reportQueueDeliveryError(failure.error, context);
|
|
245
291
|
const report = createQueueDeliveryErrorReport(failure.error, context).error;
|
|
246
|
-
if (isNonRetryableQueueError(failure.error) || row.attempts
|
|
292
|
+
if (isNonRetryableQueueError(failure.error) || row.attempts > retries.limit) {
|
|
247
293
|
await markDead(row, report, `after ${row.attempts} attempts`);
|
|
248
294
|
return;
|
|
249
295
|
}
|
|
250
|
-
await sql`update ${t} set status = 'pending', run_at = now() + make_interval(secs => ${
|
|
296
|
+
await sql`update ${t} set status = 'pending', run_at = now() + make_interval(secs => ${retries.delayMs(row.attempts) / 1e3}),
|
|
251
297
|
last_error = ${JSON.stringify(report)}::text::jsonb, locked_by = null, locked_until = null, updated_at = now()
|
|
252
298
|
where id = ${row.id} and locked_by = ${workerId} and attempts = ${row.attempts}`;
|
|
253
299
|
} catch (storeError) {
|
|
@@ -265,6 +311,50 @@ function createPostgresQueueEngine(options) {
|
|
|
265
311
|
async function notify(queue) {
|
|
266
312
|
await sql`select pg_notify(${channel}, ${queue})`;
|
|
267
313
|
}
|
|
314
|
+
const identityQuery = `select current_database() as database, extract(epoch from pg_postmaster_start_time())::text as started, to_regclass('${table}')::oid::text as relation`;
|
|
315
|
+
async function enqueueInTransaction(queue, prepared, transaction) {
|
|
316
|
+
const query = postgresTransactionQuery(transaction);
|
|
317
|
+
await ensureTable();
|
|
318
|
+
const [ours] = await controlClient().unsafe(identityQuery);
|
|
319
|
+
const [theirs] = await query(identityQuery, []);
|
|
320
|
+
if (!ours?.relation || !theirs || [
|
|
321
|
+
"database",
|
|
322
|
+
"started",
|
|
323
|
+
"relation"
|
|
324
|
+
].some((key) => theirs[key] !== ours[key])) throw queueErrorDiagnostics.QUEUE_TRANSACTION_DATABASE_MISMATCH({ reason: "database" });
|
|
325
|
+
const accepted = [];
|
|
326
|
+
for (const { delaySeconds, entry, text } of prepared) {
|
|
327
|
+
const [row] = await query(`with inserted as (
|
|
328
|
+
insert into "${table}" (id, message_id, queue, payload, run_at, idempotency_key)
|
|
329
|
+
values ($1::uuid, $2::text, $3::text, $4::text::jsonb, statement_timestamp() + make_interval(secs => $5::double precision), $6::text)
|
|
330
|
+
on conflict (queue, idempotency_key) where idempotency_key is not null and status <> 'dead'
|
|
331
|
+
do update set updated_at = "${table}".updated_at
|
|
332
|
+
returning message_id
|
|
333
|
+
) select message_id, pg_notify($7::text, $3::text) from inserted`, [
|
|
334
|
+
randomUUID(),
|
|
335
|
+
entry.id,
|
|
336
|
+
queue,
|
|
337
|
+
text ?? null,
|
|
338
|
+
delaySeconds,
|
|
339
|
+
entry.idempotencyKey ?? null,
|
|
340
|
+
channel
|
|
341
|
+
]);
|
|
342
|
+
accepted.push(String(row?.message_id));
|
|
343
|
+
}
|
|
344
|
+
return accepted;
|
|
345
|
+
}
|
|
346
|
+
function isDuplicateKey(error) {
|
|
347
|
+
return error instanceof postgres.PostgresError && error.code === "23505";
|
|
348
|
+
}
|
|
349
|
+
const keyHeld = sql`job.idempotency_key is not null and exists (
|
|
350
|
+
select 1 from ${t} as other where other.queue = job.queue and other.idempotency_key = job.idempotency_key and other.id <> job.id
|
|
351
|
+
and (other.status <> 'dead' or (coalesce(other.failed_at, '-infinity'), other.id) > (coalesce(job.failed_at, '-infinity'), job.id)))`;
|
|
352
|
+
async function reviveDead(ids) {
|
|
353
|
+
return (await sql`update ${t} as job set status = 'pending', attempts = 0, last_error = null, failed_at = null,
|
|
354
|
+
run_at = now(), updated_at = now()
|
|
355
|
+
where job.id in ${sql(ids)} and job.status = 'dead' and not (${keyHeld})
|
|
356
|
+
returning job.id`).map((row) => row.id);
|
|
357
|
+
}
|
|
268
358
|
return {
|
|
269
359
|
base,
|
|
270
360
|
async clear(filter = {}) {
|
|
@@ -288,9 +378,10 @@ function createPostgresQueueEngine(options) {
|
|
|
288
378
|
renewals.clear();
|
|
289
379
|
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.`);
|
|
290
380
|
await unlisten?.().catch(() => {});
|
|
381
|
+
if (control) await control.end({ timeout: 5 });
|
|
291
382
|
if (ownsClient) await sql.end({ timeout: 5 });
|
|
292
383
|
},
|
|
293
|
-
async enqueue(queue, entries) {
|
|
384
|
+
async enqueue(queue, entries, transaction) {
|
|
294
385
|
const prepared = entries.map((entry) => {
|
|
295
386
|
const text = JSON.stringify(entry.payload);
|
|
296
387
|
return {
|
|
@@ -299,6 +390,7 @@ function createPostgresQueueEngine(options) {
|
|
|
299
390
|
text
|
|
300
391
|
};
|
|
301
392
|
});
|
|
393
|
+
if (transaction !== void 0) return await enqueueInTransaction(queue, prepared, transaction);
|
|
302
394
|
await ensureTable();
|
|
303
395
|
return await sql.begin(async (tx) => {
|
|
304
396
|
const accepted = [];
|
|
@@ -343,13 +435,47 @@ function createPostgresQueueEngine(options) {
|
|
|
343
435
|
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()
|
|
344
436
|
where id = ${row.id} and not (status = 'running' and locked_until >= now()) returning ${columns}`;
|
|
345
437
|
} catch (error) {
|
|
346
|
-
if (error
|
|
438
|
+
if (isDuplicateKey(error)) return "duplicate";
|
|
347
439
|
throw error;
|
|
348
440
|
}
|
|
349
441
|
if (!updated) return "running";
|
|
350
442
|
await notify(row.queue);
|
|
351
443
|
return toJobSummary(updated);
|
|
352
444
|
},
|
|
445
|
+
async retryDead(queue) {
|
|
446
|
+
await ensureTable();
|
|
447
|
+
const initiallyBlocked = new Set((await sql`select job.id from ${t} as job
|
|
448
|
+
where job.queue = ${queue} and job.status = 'dead' and ${keyHeld}`).map((row) => row.id));
|
|
449
|
+
const result = {
|
|
450
|
+
retried: 0,
|
|
451
|
+
skipped: []
|
|
452
|
+
};
|
|
453
|
+
let after;
|
|
454
|
+
for (;;) {
|
|
455
|
+
const batch = await sql`select id, message_id from ${t}
|
|
456
|
+
where queue = ${queue} and status = 'dead'${after === void 0 ? sql`` : sql` and id > ${after}`}
|
|
457
|
+
order by id limit ${500}`;
|
|
458
|
+
if (!batch.length) break;
|
|
459
|
+
after = batch.at(-1).id;
|
|
460
|
+
const eligible = batch.filter((row) => !initiallyBlocked.has(row.id));
|
|
461
|
+
const revived = /* @__PURE__ */ new Set();
|
|
462
|
+
try {
|
|
463
|
+
if (eligible.length) for (const id of await reviveDead(eligible.map((row) => row.id))) revived.add(id);
|
|
464
|
+
} catch (error) {
|
|
465
|
+
if (!isDuplicateKey(error)) throw error;
|
|
466
|
+
for (const row of eligible) try {
|
|
467
|
+
for (const id of await reviveDead([row.id])) revived.add(id);
|
|
468
|
+
} catch (rowError) {
|
|
469
|
+
if (!isDuplicateKey(rowError)) throw rowError;
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
for (const row of batch) if (!revived.has(row.id)) result.skipped.push(row.message_id);
|
|
473
|
+
result.retried += revived.size;
|
|
474
|
+
if (revived.size) await notify(queue);
|
|
475
|
+
if (batch.length < 500) break;
|
|
476
|
+
}
|
|
477
|
+
return result;
|
|
478
|
+
},
|
|
353
479
|
rules,
|
|
354
480
|
start() {
|
|
355
481
|
if (closed) return Promise.resolve();
|
|
@@ -384,10 +510,10 @@ function createPostgresQueueEngine(options) {
|
|
|
384
510
|
}
|
|
385
511
|
function createPostgresQueueClient(engine, queue, resolveEngine) {
|
|
386
512
|
let activeEngine = engine;
|
|
387
|
-
async function enqueue(entries) {
|
|
513
|
+
async function enqueue(entries, transaction) {
|
|
388
514
|
const current = resolveEngine ? await resolveEngine() : engine;
|
|
389
515
|
activeEngine = current;
|
|
390
|
-
return await current.enqueue(queue, entries);
|
|
516
|
+
return await current.enqueue(queue, entries, transaction);
|
|
391
517
|
}
|
|
392
518
|
return {
|
|
393
519
|
provider: "postgres",
|
|
@@ -406,7 +532,8 @@ function createPostgresQueueClient(engine, queue, resolveEngine) {
|
|
|
406
532
|
id: normalized.id,
|
|
407
533
|
idempotencyKey: normalized.options.idempotencyKey,
|
|
408
534
|
payload: normalized.payload
|
|
409
|
-
}]));
|
|
535
|
+
}], normalized.options.transaction));
|
|
536
|
+
if (isQueueError(error?.cause, ["QUEUE_TRANSACTION_DATABASE_MISMATCH"])) return [error.cause, void 0];
|
|
410
537
|
if (error) return [error, void 0];
|
|
411
538
|
return [void 0, {
|
|
412
539
|
messageId: ids[0],
|
|
@@ -414,7 +541,7 @@ function createPostgresQueueClient(engine, queue, resolveEngine) {
|
|
|
414
541
|
}];
|
|
415
542
|
},
|
|
416
543
|
async sendBatch(items, options) {
|
|
417
|
-
const removed =
|
|
544
|
+
const removed = queueBatchOptionsError("postgres", options, items);
|
|
418
545
|
if (removed) return [removed, void 0];
|
|
419
546
|
const entries = [];
|
|
420
547
|
for (const item of items) {
|
|
@@ -438,7 +565,6 @@ function createPostgresQueueClient(engine, queue, resolveEngine) {
|
|
|
438
565
|
}
|
|
439
566
|
// src/internal/runtime/postgres-client.ts
|
|
440
567
|
const postgresUrl = /^postgres(?:ql)?:\/\//i;
|
|
441
|
-
/** A Postgres Database answers this key with a function that returns its connection URL. `@vite-hub/database` sets it. */
|
|
442
568
|
const databaseConnectionUrl = Symbol.for("vitehub.database.postgres.connection-url");
|
|
443
569
|
let loadDatabases;
|
|
444
570
|
let closing;
|
|
@@ -451,14 +577,18 @@ function engineState(config) {
|
|
|
451
577
|
const key = JSON.stringify([config.database ?? null, config.development === true]);
|
|
452
578
|
let state = engines.get(key);
|
|
453
579
|
if (!state) {
|
|
454
|
-
state = {
|
|
580
|
+
state = {};
|
|
455
581
|
engines.set(key, state);
|
|
456
582
|
}
|
|
457
583
|
return state;
|
|
458
584
|
}
|
|
459
585
|
function startWorkers(state, engine) {
|
|
460
|
-
if (
|
|
586
|
+
if (state.workers === void 0 || state.started === engine) return;
|
|
461
587
|
state.started = engine;
|
|
588
|
+
if (!state.workers) {
|
|
589
|
+
console.info(`[vitehub:queue] Queue uses the postgres driver with workers: false. Jobs are in ${engine.base}. ${queueWorkersVariable}=false, so this instance sends jobs and does not run them.`);
|
|
590
|
+
return;
|
|
591
|
+
}
|
|
462
592
|
console.info(`[vitehub:queue] Queue uses the postgres driver. Jobs are in ${engine.base}. Every instance of the app takes jobs from it.`);
|
|
463
593
|
engine.start().catch((error) => {
|
|
464
594
|
console.error(`[vitehub:queue] The postgres driver cannot start the workers on ${engine.base}.`, error);
|
|
@@ -541,19 +671,27 @@ async function createPostgresQueueRuntimeClient(options) {
|
|
|
541
671
|
if (!options.queue) throw queueErrorDiagnostics.QUEUE_MISSING_QUEUE();
|
|
542
672
|
return createPostgresQueueClient(await usePostgresQueueEngine(options), options.queue, () => usePostgresQueueEngine(options));
|
|
543
673
|
}
|
|
674
|
+
function readQueueWorkers() {
|
|
675
|
+
const value = process.env[queueWorkersVariable]?.trim().toLowerCase();
|
|
676
|
+
if (!value || value === "true") return true;
|
|
677
|
+
if (value === "false") return false;
|
|
678
|
+
throw queueErrorDiagnostics.QUEUE_WORKERS_INVALID();
|
|
679
|
+
}
|
|
544
680
|
/**
|
|
545
681
|
* Starts the workers when the server starts: this process takes the due jobs of every Queue Definition from Postgres.
|
|
546
|
-
* `
|
|
547
|
-
* the
|
|
682
|
+
* With `QUEUE_WORKERS=false`, it only sends jobs, so the same build runs as a web server or as a worker. Another value
|
|
683
|
+
* than `true` or `false` throws `QUEUE_WORKERS_INVALID`. `databases` loads the Databases of the app, for a build that found
|
|
684
|
+
* its Default Database on Postgres. Logs once where the jobs are.
|
|
548
685
|
*/
|
|
549
|
-
function startPostgresQueue(config, databases) {
|
|
686
|
+
function startPostgresQueue(config, databases, workers) {
|
|
550
687
|
if (config === false || config.driver !== "postgres") return;
|
|
551
688
|
assertOpen();
|
|
689
|
+
workers ??= readQueueWorkers();
|
|
552
690
|
loadDatabases = databases;
|
|
553
|
-
engineState(config).workers =
|
|
554
|
-
setQueueRuntimeJobStore(() => usePostgresQueueEngine(config));
|
|
691
|
+
engineState(config).workers = workers;
|
|
692
|
+
setQueueRuntimeJobStore(() => usePostgresQueueEngine(config), workers);
|
|
555
693
|
usePostgresQueueEngine(config).catch((error) => {
|
|
556
|
-
console.error("[vitehub:queue] The postgres driver cannot start
|
|
694
|
+
console.error("[vitehub:queue] The postgres driver cannot start.", error);
|
|
557
695
|
});
|
|
558
696
|
}
|
|
559
697
|
/** Stops taking jobs, waits for the running jobs up to 10 seconds, and closes the connections it opened. The jobs stay. */
|
|
@@ -561,7 +699,7 @@ function closePostgresQueues() {
|
|
|
561
699
|
if (closing) return closing;
|
|
562
700
|
closing = (async () => {
|
|
563
701
|
const states = [...engines.values()];
|
|
564
|
-
for (const state of states) state.workers =
|
|
702
|
+
for (const state of states) state.workers = void 0;
|
|
565
703
|
setQueueRuntimeJobStore(void 0);
|
|
566
704
|
await Promise.all(states.map((state) => state.pending?.catch(() => {})));
|
|
567
705
|
await Promise.all([...states.map((state) => state.current?.engine.close()), ...retiring]);
|
|
@@ -572,4 +710,4 @@ function closePostgresQueues() {
|
|
|
572
710
|
});
|
|
573
711
|
return closing;
|
|
574
712
|
}
|
|
575
|
-
export { closePostgresQueues, createPostgresQueueRuntimeClient, resolvePostgresQueueConnection, startPostgresQueue };
|
|
713
|
+
export { closePostgresQueues, createPostgresQueueRuntimeClient, readQueueWorkers, resolvePostgresQueueConnection, startPostgresQueue };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { n as QueueRuntimeOptions, t as QueueRuntimeDriverOptions } from "../../types-
|
|
1
|
+
import { S as QueueDefinition, j as QueueJobStore, w as QueueDefinitionRegistry, x as QueueClient } from "../../types-rZHAtkK0.js";
|
|
2
|
+
import { n as QueueRuntimeOptions, t as QueueRuntimeDriverOptions } from "../../types-BPs6OsRv.js";
|
|
3
3
|
export type QueueRuntimeClientFactory = (options: QueueRuntimeDriverOptions) => QueueClient | Promise<QueueClient>;
|
|
4
4
|
export declare function missingQueueDefinitionError(queue: string): Error;
|
|
5
5
|
export declare function setQueueRuntimeConfig(config: false | QueueRuntimeOptions | undefined, createClient?: QueueRuntimeClientFactory): void;
|
|
@@ -7,7 +7,9 @@ export declare function setQueueRuntimeConfig(config: false | QueueRuntimeOption
|
|
|
7
7
|
* The stored jobs of a provider that does not keep them in this package's process state. The generated server sets it
|
|
8
8
|
* for the postgres provider, so the Queue operations read jobs without importing the Postgres driver.
|
|
9
9
|
*/
|
|
10
|
-
export declare function setQueueRuntimeJobStore(store: (() => Promise<QueueJobStore> | QueueJobStore) | undefined): void;
|
|
10
|
+
export declare function setQueueRuntimeJobStore(store: (() => Promise<QueueJobStore> | QueueJobStore) | undefined, workers?: boolean): void;
|
|
11
|
+
/** Whether this process runs the jobs of the store that `setQueueRuntimeJobStore()` set. `QUEUE_WORKERS=false` turns it off. */
|
|
12
|
+
export declare function getQueueRuntimeJobWorkers(): boolean | undefined;
|
|
11
13
|
export declare function getQueueRuntimeJobStore(): Promise<QueueJobStore | undefined>;
|
|
12
14
|
export declare function getQueueRuntimeConfig(): false | QueueRuntimeOptions | undefined;
|
|
13
15
|
export declare function getQueueRuntimeClientFactory(): QueueRuntimeClientFactory | undefined;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export { t as enterQueueRuntimeEvent, n as getOrCreateQueueClient, r as getQueueRuntimeClientFactory, i as getQueueRuntimeConfig, a as getQueueRuntimeEvent, o as getQueueRuntimeJobStore, s as
|
|
1
|
+
export { t as enterQueueRuntimeEvent, n as getOrCreateQueueClient, r as getQueueRuntimeClientFactory, i as getQueueRuntimeConfig, a as getQueueRuntimeEvent, o as getQueueRuntimeJobStore, s as getQueueRuntimeJobWorkers, c as listQueueDefinitionNames, l as loadQueueDefinition, u as missingQueueDefinitionError, d as runWithQueueRuntimeEvent, f as setQueueRuntimeConfig, p as setQueueRuntimeEventDefaults, m as setQueueRuntimeJobStore, h as setQueueRuntimeRegistry } from "../../state-C-t99I4Q.js";
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { E as QueueDriverOptions, x as QueueClient } from "../../types-rZHAtkK0.js";
|
|
2
2
|
export declare function createVercelQueueRuntimeClient(options: QueueDriverOptions): Promise<QueueClient>;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { c as
|
|
2
|
-
import { t as queueErrorDiagnostics } from "../../error-diagnostics-
|
|
3
|
-
import { t as resolveVercelQueueRegion } from "../../vercel-region-
|
|
1
|
+
import { c as queueBatchOptionsError, d as queueUnsupportedOptionsError, l as queueProviderResult, m as normalizeQueueEnqueueInput, p as createQueueMessageId, t as readQueueTimes } from "../../duration-CcLSF94z.js";
|
|
2
|
+
import { t as queueErrorDiagnostics } from "../../error-diagnostics-Yj8XCiya.js";
|
|
3
|
+
import { t as resolveVercelQueueRegion } from "../../vercel-region-Bp3hwRBr.js";
|
|
4
4
|
// src/providers/vercel.ts
|
|
5
5
|
function invalidVercelSendResponse(cause) {
|
|
6
6
|
return [queueErrorDiagnostics.QUEUE_PROVIDER_INVALID_RESPONSE({ cause }), void 0];
|
|
@@ -81,6 +81,18 @@ function parseVercelMessageId(value) {
|
|
|
81
81
|
if (typeof messageId !== "string" || !messageId || messageId.length > 128 || messageId.trim() !== messageId) return invalidVercelSendResponse(value);
|
|
82
82
|
return [void 0, messageId];
|
|
83
83
|
}
|
|
84
|
+
const localVercelQueueRegion = "iad1";
|
|
85
|
+
function readLocalVercelQueueBroker() {
|
|
86
|
+
const baseUrl = process.env.VERCEL_QUEUE_BASE_URL;
|
|
87
|
+
if (!baseUrl || process.env.VERCEL_DEPLOYMENT_ID) return void 0;
|
|
88
|
+
const token = process.env.VERCEL_QUEUE_TOKEN;
|
|
89
|
+
const protocol = URL.parse(baseUrl)?.protocol;
|
|
90
|
+
if (protocol !== "http:" && protocol !== "https:" || !token) throw queueErrorDiagnostics.QUEUE_VERCEL_LOCAL_BROKER_INVALID();
|
|
91
|
+
return {
|
|
92
|
+
resolveBaseUrl: () => new URL(baseUrl),
|
|
93
|
+
token
|
|
94
|
+
};
|
|
95
|
+
}
|
|
84
96
|
async function loadVercelQueueClient(region) {
|
|
85
97
|
let module;
|
|
86
98
|
try {
|
|
@@ -101,8 +113,15 @@ async function loadVercelQueueClient(region) {
|
|
|
101
113
|
}
|
|
102
114
|
const { region: resolvedRegion } = resolveVercelQueueRegion(region);
|
|
103
115
|
if (Object.hasOwn(module, "QueueClient") && typeof module.QueueClient === "function") {
|
|
116
|
+
const QueueClient = module.QueueClient;
|
|
117
|
+
const broker = readLocalVercelQueueBroker();
|
|
118
|
+
if (broker) return new QueueClient({
|
|
119
|
+
...broker,
|
|
120
|
+
deploymentId: null,
|
|
121
|
+
region: resolvedRegion ?? localVercelQueueRegion
|
|
122
|
+
});
|
|
104
123
|
if (!resolvedRegion) throw queueErrorDiagnostics.QUEUE_MISSING_REGION();
|
|
105
|
-
return new
|
|
124
|
+
return new QueueClient({ region: resolvedRegion });
|
|
106
125
|
}
|
|
107
126
|
if (Object.hasOwn(module, "send") && Object.hasOwn(module, "handleCallback") && typeof module.send === "function" && typeof module.handleCallback === "function") return {
|
|
108
127
|
handleCallback: module.handleCallback,
|
|
@@ -141,7 +160,7 @@ async function createVercelQueueClient(provider) {
|
|
|
141
160
|
}];
|
|
142
161
|
},
|
|
143
162
|
async sendBatch(items, options) {
|
|
144
|
-
const removed =
|
|
163
|
+
const removed = queueBatchOptionsError("vercel", options, items);
|
|
145
164
|
if (removed) return [removed, void 0];
|
|
146
165
|
const messages = [];
|
|
147
166
|
for (const item of items) {
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { t as QueueRuntimeDriverOptions } from "../../types-
|
|
1
|
+
import { x as QueueClient } from "../../types-rZHAtkK0.js";
|
|
2
|
+
import { t as QueueRuntimeDriverOptions } from "../../types-BPs6OsRv.js";
|
|
3
3
|
/** Worker package conditions keep the Node driver and its optional peer outside the build graph. */
|
|
4
4
|
export declare function createPostgresQueueRuntimeClient(options: QueueRuntimeDriverOptions): Promise<QueueClient>;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { t as queueErrorDiagnostics } from "../../error-diagnostics-
|
|
1
|
+
import { t as queueErrorDiagnostics } from "../../error-diagnostics-Yj8XCiya.js";
|
|
2
2
|
// src/internal/runtime/worker-client.ts
|
|
3
3
|
/** Worker package conditions keep the Node driver and its optional peer outside the build graph. */
|
|
4
4
|
async function createPostgresQueueRuntimeClient(options) {
|