@vite-hub/queue 0.6.1 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/README.md +17 -12
  2. package/dist/{client-CwoCdKct.js → client-mT8TUaag.js} +46 -15
  3. package/dist/{cloudflare-client-xWteD-su.js → cloudflare-client-DBgvWY0z.js} +14 -42
  4. package/dist/{cloudflare-resource-name-Bv8Z7nDU.js → cloudflare-resource-name-Coz5CPmn.js} +1 -1
  5. package/dist/{config-Bzp1xmdh.js → config-ByKUipob.js} +4 -2
  6. package/dist/{definition-CIiFfst2.js → definition-Dorliu47.js} +9 -2
  7. package/dist/{duration-C5w_-Rf4.js → duration-BZKArIBP.js} +20 -5
  8. package/dist/{error-diagnostics-kKXseq8d.js → error-diagnostics-CsiNo_oI.js} +3 -3
  9. package/dist/{error-diagnostics-Dv6nKZQW.js → error-diagnostics-Yj8XCiya.js} +30 -6
  10. package/dist/{handler-response-CchTXVjm.js → handler-response-DKhsmxDV.js} +6 -2
  11. package/dist/index.d.ts +13 -8
  12. package/dist/index.js +4 -4
  13. package/dist/internal/runtime/cloudflare-client.d.ts +1 -1
  14. package/dist/internal/runtime/cloudflare-client.js +1 -1
  15. package/dist/internal/runtime/cloudflare-vite.d.ts +1 -1
  16. package/dist/internal/runtime/cloudflare-vite.js +9 -8
  17. package/dist/internal/runtime/local-client.d.ts +3 -3
  18. package/dist/internal/runtime/local-client.js +4 -4
  19. package/dist/internal/runtime/postgres-client.d.ts +8 -6
  20. package/dist/internal/runtime/postgres-client.js +178 -40
  21. package/dist/internal/runtime/state.d.ts +5 -3
  22. package/dist/internal/runtime/state.js +1 -1
  23. package/dist/internal/runtime/vercel-client.d.ts +1 -1
  24. package/dist/internal/runtime/vercel-client.js +28 -57
  25. package/dist/internal/runtime/worker-client.d.ts +2 -2
  26. package/dist/internal/runtime/worker-client.js +1 -1
  27. package/dist/{local-RX10a_Sq.js → local-5pcvR1RC.js} +148 -97
  28. package/dist/{local-B72WRWkS.d.ts → local-DUh8sGn-.d.ts} +1 -1
  29. package/dist/{operations-CoEXxfUW.js → operations-BSouq47k.js} +11 -6
  30. package/dist/{operation-definition-CqZkx1Rm.d.ts → operations-DSslh_vK.d.ts} +169 -1
  31. package/dist/operations.d.ts +13 -4
  32. package/dist/operations.js +98 -37
  33. package/dist/retries-BSAZru9n.js +27 -0
  34. package/dist/run-handler-COXFYL5z.js +61 -0
  35. package/dist/runtime/hosted.d.ts +1 -1
  36. package/dist/runtime/hosted.js +32 -20
  37. package/dist/{scan-module-BaqBao0J.js → scan-module-3HfnrGbT.js} +16 -1
  38. package/dist/source-files-DrAH1-c8.js +147 -0
  39. package/dist/{state-DqxeV11k.js → state-C-t99I4Q.js} +9 -3
  40. package/dist/{types-BevEYrUV.d.ts → types-BPs6OsRv.d.ts} +1 -1
  41. package/dist/{types-BzPGPV9z.d.ts → types-rZHAtkK0.d.ts} +74 -12
  42. package/dist/{vercel-region-DEsR1YJQ.js → vercel-region-Bp3hwRBr.js} +1 -1
  43. package/dist/vite.d.ts +2 -155
  44. package/dist/vite.js +522 -138
  45. package/package.json +4 -3
@@ -1,53 +1,11 @@
1
- import { c as queueRemovedOptionsError, d as normalizeQueueEnqueueInput, l as queueUnsupportedOptionsError, s as queueProviderResult, t as readQueueTimes, u as createQueueMessageId } from "../../duration-C5w_-Rf4.js";
2
- import { t as queueErrorDiagnostics } from "../../error-diagnostics-Dv6nKZQW.js";
3
- import { t as resolveVercelQueueRegion } from "../../vercel-region-DEsR1YJQ.js";
1
+ import { n as isRecord } from "../../object-DRSmpe04.js";
2
+ import { c as queueBatchOptionsError, d as queueUnsupportedOptionsError, l as queueProviderResult, m as normalizeQueueEnqueueInput, p as createQueueMessageId, t as readQueueTimes } from "../../duration-BZKArIBP.js";
3
+ import { t as queueErrorDiagnostics } from "../../error-diagnostics-Yj8XCiya.js";
4
+ import { t as resolveVercelQueueRegion } from "../../vercel-region-Bp3hwRBr.js";
4
5
  // src/providers/vercel.ts
5
6
  function invalidVercelSendResponse(cause) {
6
7
  return [queueErrorDiagnostics.QUEUE_PROVIDER_INVALID_RESPONSE({ cause }), void 0];
7
8
  }
8
- function isVercelQueueSDK(value) {
9
- if (value === null || typeof value !== "object") return false;
10
- try {
11
- if (Array.isArray(value)) return false;
12
- } catch {
13
- return false;
14
- }
15
- const hasCallableMethod = (name) => {
16
- let owner = value;
17
- while (owner && owner !== Object.prototype) {
18
- let descriptor;
19
- try {
20
- descriptor = Object.getOwnPropertyDescriptor(owner, name);
21
- } catch {
22
- return false;
23
- }
24
- if (descriptor) {
25
- if (owner !== value) {
26
- let constructor;
27
- try {
28
- constructor = Object.getOwnPropertyDescriptor(owner, "constructor");
29
- if (!constructor || !("value" in constructor) || typeof constructor.value !== "function" || constructor.value.prototype !== owner) return false;
30
- } catch {
31
- return false;
32
- }
33
- }
34
- if ("value" in descriptor) return typeof descriptor.value === "function";
35
- try {
36
- return typeof Reflect.get(value, name) === "function";
37
- } catch {
38
- return false;
39
- }
40
- }
41
- try {
42
- owner = Object.getPrototypeOf(owner);
43
- } catch {
44
- return false;
45
- }
46
- }
47
- return false;
48
- };
49
- return hasCallableMethod("send") && hasCallableMethod("handleCallback");
50
- }
51
9
  function batchRejected(results) {
52
10
  const failed = results.filter((result) => result.status === "failed").length;
53
11
  return Object.assign(queueErrorDiagnostics.QUEUE_VERCEL_BATCH_REJECTED({
@@ -69,18 +27,24 @@ function parseVercelBatchResults(value, length) {
69
27
  return [void 0, results];
70
28
  }
71
29
  function parseVercelMessageId(value) {
72
- if (!value || typeof value !== "object" || Array.isArray(value)) return invalidVercelSendResponse(value);
73
- let messageId;
74
- try {
75
- if (!Object.prototype.hasOwnProperty.call(value, "messageId")) return invalidVercelSendResponse(value);
76
- messageId = Reflect.get(value, "messageId");
77
- } catch (cause) {
78
- return invalidVercelSendResponse(cause);
79
- }
30
+ if (!isRecord(value) || !Object.hasOwn(value, "messageId")) return invalidVercelSendResponse(value);
31
+ const messageId = value.messageId;
80
32
  if (messageId === null) return [void 0, void 0];
81
33
  if (typeof messageId !== "string" || !messageId || messageId.length > 128 || messageId.trim() !== messageId) return invalidVercelSendResponse(value);
82
34
  return [void 0, messageId];
83
35
  }
36
+ const localVercelQueueRegion = "iad1";
37
+ function readLocalVercelQueueBroker() {
38
+ const baseUrl = process.env.VERCEL_QUEUE_BASE_URL;
39
+ if (!baseUrl || process.env.VERCEL_DEPLOYMENT_ID) return void 0;
40
+ const token = process.env.VERCEL_QUEUE_TOKEN;
41
+ const protocol = URL.parse(baseUrl)?.protocol;
42
+ if (protocol !== "http:" && protocol !== "https:" || !token) throw queueErrorDiagnostics.QUEUE_VERCEL_LOCAL_BROKER_INVALID();
43
+ return {
44
+ resolveBaseUrl: () => new URL(baseUrl),
45
+ token
46
+ };
47
+ }
84
48
  async function loadVercelQueueClient(region) {
85
49
  let module;
86
50
  try {
@@ -101,8 +65,15 @@ async function loadVercelQueueClient(region) {
101
65
  }
102
66
  const { region: resolvedRegion } = resolveVercelQueueRegion(region);
103
67
  if (Object.hasOwn(module, "QueueClient") && typeof module.QueueClient === "function") {
68
+ const QueueClient = module.QueueClient;
69
+ const broker = readLocalVercelQueueBroker();
70
+ if (broker) return new QueueClient({
71
+ ...broker,
72
+ deploymentId: null,
73
+ region: resolvedRegion ?? localVercelQueueRegion
74
+ });
104
75
  if (!resolvedRegion) throw queueErrorDiagnostics.QUEUE_MISSING_REGION();
105
- return new module.QueueClient({ region: resolvedRegion });
76
+ return new QueueClient({ region: resolvedRegion });
106
77
  }
107
78
  if (Object.hasOwn(module, "send") && Object.hasOwn(module, "handleCallback") && typeof module.send === "function" && typeof module.handleCallback === "function") return {
108
79
  handleCallback: module.handleCallback,
@@ -115,7 +86,7 @@ async function createVercelQueueClient(provider) {
115
86
  const topic = provider.topic;
116
87
  if (!topic) throw queueErrorDiagnostics.QUEUE_MISSING_TOPIC();
117
88
  const client = provider.client === void 0 ? await loadVercelQueueClient(provider.region) : provider.client;
118
- if (!isVercelQueueSDK(client)) throw queueErrorDiagnostics.QUEUE_VERCEL_SDK_INVALID();
89
+ if (typeof client?.send !== "function" || typeof client.handleCallback !== "function") throw queueErrorDiagnostics.QUEUE_VERCEL_SDK_INVALID();
119
90
  return {
120
91
  provider: "vercel",
121
92
  native: client,
@@ -141,7 +112,7 @@ async function createVercelQueueClient(provider) {
141
112
  }];
142
113
  },
143
114
  async sendBatch(items, options) {
144
- const removed = queueRemovedOptionsError("vercel", options, items);
115
+ const removed = queueBatchOptionsError("vercel", options, items);
145
116
  if (removed) return [removed, void 0];
146
117
  const messages = [];
147
118
  for (const item of items) {
@@ -1,4 +1,4 @@
1
- import { b as QueueClient } from "../../types-BzPGPV9z.js";
2
- import { t as QueueRuntimeDriverOptions } from "../../types-BevEYrUV.js";
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-Dv6nKZQW.js";
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) {
@@ -1,49 +1,40 @@
1
- import { c as queueRemovedOptionsError, d as normalizeQueueEnqueueInput, i as localUnsupportedEnqueueOptions, l as queueUnsupportedOptionsError, n as cloudflareUnsupportedEnqueueOptions, o as postgresUnsupportedEnqueueOptions, s as queueProviderResult, t as readQueueTimes, u as createQueueMessageId } from "./duration-C5w_-Rf4.js";
2
- import { i as reportQueueDeliveryError, n as createQueueDeliveryErrorReport, r as isNonRetryableQueueError, t as checkQueueHandlerResponse } from "./handler-response-CchTXVjm.js";
3
- import { t as queueErrorDiagnostics } from "./error-diagnostics-Dv6nKZQW.js";
1
+ import { a as localUnsupportedEnqueueOptions, c as queueBatchOptionsError, d as queueUnsupportedOptionsError, f as vercelUnsupportedEnqueueOptions, l as queueProviderResult, m as normalizeQueueEnqueueInput, n as cloudflareUnsupportedEnqueueOptions, p as createQueueMessageId, s as postgresUnsupportedEnqueueOptions, t as readQueueTimes } from "./duration-BZKArIBP.js";
2
+ import { i as reportQueueDeliveryError, n as createQueueDeliveryErrorReport, r as isNonRetryableQueueError } from "./handler-response-DKhsmxDV.js";
3
+ import { n as queueRetryPolicy } from "./retries-BSAZru9n.js";
4
+ import { n as runQueueJob } from "./run-handler-COXFYL5z.js";
5
+ import { t as queueErrorDiagnostics } from "./error-diagnostics-Yj8XCiya.js";
4
6
  import { mkdir, readFile, readdir, rename, rm, writeFile } from "node:fs/promises";
5
7
  import { join, resolve } from "pathe";
6
8
  import { randomUUID } from "node:crypto";
7
- import { runInRunScopes } from "@vite-hub/runtime/internal/run-scope";
8
9
  const maxTimerDelay = 2 ** 31 - 1;
9
10
  const storeRetryMaxMs = 3e4;
10
11
  function storeRetryDelayMs(failures) {
11
12
  return Math.min(10 * 2 ** (failures - 1), storeRetryMaxMs);
12
13
  }
13
- /** Retries after 1, 2, and 4 seconds, up to 60 seconds. The local and postgres providers use it. */
14
- function defaultRetryDelayMs(attempts) {
15
- return Math.min(2 ** (attempts - 1), 60) * 1e3;
16
- }
17
14
  const day = 86400;
18
15
  /**
19
16
  * Delivery rules per provider. `vite dev` runs the jobs of a Cloudflare or Vercel app with the local engine and the
20
- * documented defaults of that provider, so a handler fails, retries, and stops in dev as it does on the host.
17
+ * limits of that provider, so a send fails in dev as it does on the host. Retries follow `retries` of the Queue
18
+ * Definition on every provider.
21
19
  */
22
20
  const localQueueDeliveryRules = {
23
21
  cloudflare: {
24
- maxAttempts: 4,
25
22
  maxBatchBytes: 262144,
26
23
  maxBatchJobs: 100,
27
24
  maxDelaySeconds: day,
28
25
  maxPayloadBytes: 130972,
29
- retryDelayMs: () => 0,
30
26
  rules: "cloudflare",
31
27
  unsupportedOptions: cloudflareUnsupportedEnqueueOptions
32
28
  },
33
29
  local: {
34
- maxAttempts: 4,
35
- retryDelayMs: defaultRetryDelayMs,
36
30
  rules: "local",
37
31
  unsupportedOptions: localUnsupportedEnqueueOptions
38
32
  },
39
33
  postgres: {
40
- maxAttempts: 4,
41
- retryDelayMs: defaultRetryDelayMs,
42
34
  rules: "postgres",
43
- unsupportedOptions: postgresUnsupportedEnqueueOptions
35
+ unsupportedOptions: [...postgresUnsupportedEnqueueOptions, "transaction"]
44
36
  },
45
37
  vercel: {
46
- maxAttempts: Number.POSITIVE_INFINITY,
47
38
  maxBatchJobs: 100,
48
39
  maxDelaySeconds: 7 * day,
49
40
  maxPayloadBytes: 104857600,
@@ -52,9 +43,8 @@ const localQueueDeliveryRules = {
52
43
  maxSeconds: 7 * day,
53
44
  minSeconds: 60
54
45
  },
55
- retryDelayMs: () => 6e4,
56
46
  rules: "vercel",
57
- unsupportedOptions: ["contentType"]
47
+ unsupportedOptions: vercelUnsupportedEnqueueOptions
58
48
  }
59
49
  };
60
50
  function isStoredJob(value) {
@@ -151,7 +141,6 @@ function toJobSummary(job, running) {
151
141
  function createLocalQueueEngine(options) {
152
142
  const base = resolve(options.base);
153
143
  const rules = options.rules ?? localQueueDeliveryRules.local;
154
- const retryDelayMs = options.retryDelayMs ?? rules.retryDelayMs;
155
144
  const jobs = /* @__PURE__ */ new Map();
156
145
  const running = /* @__PURE__ */ new Map();
157
146
  const runningKeys = /* @__PURE__ */ new Set();
@@ -159,15 +148,24 @@ function createLocalQueueEngine(options) {
159
148
  const expiringKeys = /* @__PURE__ */ new Set();
160
149
  const concurrency = /* @__PURE__ */ new Map();
161
150
  const storeFailures = /* @__PURE__ */ new WeakMap();
162
- let enqueueTail = Promise.resolve();
151
+ let mutationTail = Promise.resolve();
163
152
  let started;
164
153
  let timer;
165
154
  let closed = false;
166
155
  const file = (job) => join(base, `${job.key}.json`);
167
156
  const attemptInFlight = (job) => runningKeys.has(job.key) || expiringKeys.has(job.key);
168
- async function persist(job) {
157
+ const keyHeld = (job) => job.idempotencyKey !== void 0 && [...jobs.values()].some((other) => other.key !== job.key && other.queue === job.queue && other.idempotencyKey === job.idempotencyKey && (other.state === "pending" || attemptInFlight(other)));
158
+ function mutate(run) {
159
+ const result = mutationTail.then(run);
160
+ mutationTail = result.then(() => void 0, () => void 0);
161
+ return result;
162
+ }
163
+ async function persist(job, payload) {
169
164
  const target = file(job);
170
- await writeFile(`${target}.tmp`, JSON.stringify(job), "utf8");
165
+ await writeFile(`${target}.tmp`, JSON.stringify({
166
+ ...job,
167
+ ...payload
168
+ }), "utf8");
171
169
  await rename(`${target}.tmp`, target);
172
170
  }
173
171
  async function unlink(job) {
@@ -200,53 +198,63 @@ function createLocalQueueEngine(options) {
200
198
  arm(next);
201
199
  }
202
200
  async function pruneDead(queue) {
203
- const dead = [...jobs.values()].filter((job) => job.queue === queue && job.state === "dead").sort((a, b) => (a.failedAt ?? 0) - (b.failedAt ?? 0));
201
+ const dead = [...jobs.values()].filter((job) => job.queue === queue && job.state === "dead" && !writingKeys.has(job.key)).sort((a, b) => (a.failedAt ?? 0) - (b.failedAt ?? 0));
204
202
  for (const job of dead.slice(0, Math.max(0, dead.length - 100))) {
203
+ if (writingKeys.has(job.key) || jobs.get(job.key) !== job) continue;
205
204
  jobs.delete(job.key);
206
205
  await unlink(job).catch((error) => {
207
206
  console.error(`[vitehub:queue] The local provider cannot delete the dead job file ${file(job)}.`, error);
208
207
  });
209
208
  }
210
209
  }
211
- async function markDead(job, error, reason = `after ${job.attempts} attempts`) {
210
+ async function markDead(job, payload, error, reason = `after ${job.attempts} attempts`) {
212
211
  storeFailures.delete(job);
213
212
  job.state = "dead";
214
213
  job.error = error;
215
214
  job.failedAt = Date.now();
216
215
  console.error(`[vitehub:queue] The local provider stopped delivery of a "${job.queue}" job ${reason}. The job stays in ${file(job)}.`);
217
- await persist(job);
218
- delete job.payload;
216
+ await persist(job, payload);
219
217
  await pruneDead(job.queue);
220
218
  }
221
219
  async function expire(job) {
222
220
  expiringKeys.add(job.key);
223
221
  try {
224
- await markDead(job, {
222
+ await mutate(async () => markDead(job, await readPayload(job), {
225
223
  message: "[vitehub] The job expired at the end of its retention period.",
226
224
  name: "Error"
227
- }, "because its retention period ended");
225
+ }, "because its retention period ended"));
228
226
  } catch (error) {
229
227
  console.error(`[vitehub:queue] The local provider cannot update the job file in ${base}.`, error);
230
228
  } finally {
231
229
  expiringKeys.delete(job.key);
232
230
  }
233
231
  }
234
- async function complete(job) {
232
+ async function complete(job, payload) {
235
233
  job.state = "done";
236
234
  try {
237
235
  await unlink(job);
238
236
  jobs.delete(job.key);
239
237
  } catch (error) {
240
238
  console.error(`[vitehub:queue] The local provider ran a job, but cannot delete ${file(job)}.`, error);
241
- await persist(job).catch((persistError) => console.error(`[vitehub:queue] The local provider cannot mark ${file(job)} done either. The job runs again after a restart.`, persistError));
239
+ await persist(job, payload).catch((persistError) => console.error(`[vitehub:queue] The local provider cannot mark ${file(job)} done either. The job runs again after a restart.`, persistError));
242
240
  }
243
241
  }
242
+ function retryPolicy(definition) {
243
+ const policy = queueRetryPolicy(definition?.retries);
244
+ return options.retryDelayMs ? {
245
+ ...policy,
246
+ delayMs: options.retryDelayMs
247
+ } : policy;
248
+ }
244
249
  async function deliver(job) {
245
250
  runningKeys.add(job.key);
246
251
  running.set(job.queue, (running.get(job.queue) ?? 0) + 1);
252
+ let retries = retryPolicy(void 0);
247
253
  try {
248
- if (job.attempts >= rules.maxAttempts) {
249
- await markDead(job, {
254
+ const payload = await readPayload(job);
255
+ retries = await options.load(job.queue).then(retryPolicy).catch(() => retries);
256
+ if (job.attempts > retries.limit) {
257
+ await markDead(job, payload, {
250
258
  message: "[vitehub] The process stopped during the last attempt of this job.",
251
259
  name: "Error"
252
260
  });
@@ -256,7 +264,7 @@ function createLocalQueueEngine(options) {
256
264
  await persist({
257
265
  ...job,
258
266
  attempts
259
- });
267
+ }, payload);
260
268
  storeFailures.delete(job);
261
269
  job.attempts = attempts;
262
270
  let handled = false;
@@ -266,13 +274,11 @@ function createLocalQueueEngine(options) {
266
274
  const limit = Number(definition.concurrency ?? 1);
267
275
  concurrency.set(job.queue, Number.isFinite(limit) ? Math.max(1, Math.floor(limit)) : 1);
268
276
  schedule();
269
- await runInRunScopes(async () => {
270
- checkQueueHandlerResponse(await definition.handler({
271
- attempts: job.attempts,
272
- id: job.id,
273
- payload: job.payload
274
- }));
275
- });
277
+ await runQueueJob(definition, {
278
+ attempts: job.attempts,
279
+ id: job.id,
280
+ payload: payload.payload
281
+ }, job.queue);
276
282
  handled = true;
277
283
  } catch (error) {
278
284
  const context = {
@@ -283,19 +289,19 @@ function createLocalQueueEngine(options) {
283
289
  queue: job.queue
284
290
  };
285
291
  reportQueueDeliveryError(error, context);
286
- if (isNonRetryableQueueError(error) || job.attempts >= rules.maxAttempts) await markDead(job, createQueueDeliveryErrorReport(error, context).error);
292
+ if (isNonRetryableQueueError(error) || job.attempts > retries.limit) await markDead(job, payload, createQueueDeliveryErrorReport(error, context).error);
287
293
  else {
288
- job.availableAt = Date.now() + retryDelayMs(job.attempts);
294
+ job.availableAt = Date.now() + retries.delayMs(job.attempts);
289
295
  job.error = createQueueDeliveryErrorReport(error, context).error;
290
- await persist(job);
296
+ await persist(job, payload);
291
297
  }
292
298
  }
293
- if (handled) await complete(job);
299
+ if (handled) await complete(job, payload);
294
300
  } catch (storeError) {
295
301
  if (job.state === "pending") {
296
302
  const failures = (storeFailures.get(job) ?? 0) + 1;
297
303
  storeFailures.set(job, failures);
298
- job.availableAt = Date.now() + Math.max(retryDelayMs(Math.max(1, job.attempts)), storeRetryDelayMs(failures));
304
+ job.availableAt = Math.max(job.availableAt, Date.now() + storeRetryDelayMs(failures));
299
305
  }
300
306
  console.error(`[vitehub:queue] The local provider cannot update the job file in ${base}.`, storeError);
301
307
  } finally {
@@ -324,9 +330,9 @@ function createLocalQueueEngine(options) {
324
330
  message: "[vitehub] Queue Delivery failed.",
325
331
  name: "Error"
326
332
  };
327
- await persist(job);
333
+ await persist(job, {});
328
334
  }
329
- if (job.state === "dead") delete job.payload;
335
+ delete job.payload;
330
336
  recovered.push(job);
331
337
  } catch (error) {
332
338
  console.error(`[vitehub:queue] The local provider skips ${join(base, name)}: it cannot read it.`, error);
@@ -344,8 +350,24 @@ function createLocalQueueEngine(options) {
344
350
  }
345
351
  return found;
346
352
  }
353
+ async function revive(job, now) {
354
+ const retry = {
355
+ ...job,
356
+ attempts: 0,
357
+ state: "pending"
358
+ };
359
+ delete retry.error;
360
+ delete retry.failedAt;
361
+ if (job.expiresAt !== void 0) {
362
+ retry.retentionMs = job.retentionMs ?? job.expiresAt - job.enqueuedAt;
363
+ retry.expiresAt = now + retry.retentionMs;
364
+ }
365
+ retry.availableAt = now;
366
+ await persist(retry, await readPayload(job));
367
+ jobs.set(job.key, retry);
368
+ return retry;
369
+ }
347
370
  async function readPayload(job) {
348
- if (job.state !== "dead") return Object.hasOwn(job, "payload") ? { payload: job.payload } : {};
349
371
  const stored = JSON.parse(await readFile(file(job), "utf8"));
350
372
  return isStoredJob(stored) && Object.hasOwn(stored, "payload") ? { payload: stored.payload } : {};
351
373
  }
@@ -353,16 +375,18 @@ function createLocalQueueEngine(options) {
353
375
  base,
354
376
  async clear(filter = {}) {
355
377
  await this.start();
356
- let cleared = 0;
357
- for (const job of [...jobs.values()]) {
358
- if (job.state === "done" || runningKeys.has(job.key) || writingKeys.has(job.key) || expiringKeys.has(job.key)) continue;
359
- if (filter.queue !== void 0 && job.queue !== filter.queue) continue;
360
- if (filter.state !== void 0 && job.state !== filter.state) continue;
361
- jobs.delete(job.key);
362
- await unlink(job);
363
- cleared++;
364
- }
365
- return cleared;
378
+ return await mutate(async () => {
379
+ let cleared = 0;
380
+ for (const job of jobs.values()) {
381
+ if (job.state === "done" || attemptInFlight(job)) continue;
382
+ if (filter.queue !== void 0 && job.queue !== filter.queue) continue;
383
+ if (filter.state !== void 0 && job.state !== filter.state) continue;
384
+ jobs.delete(job.key);
385
+ await unlink(job);
386
+ cleared++;
387
+ }
388
+ return cleared;
389
+ });
366
390
  },
367
391
  close() {
368
392
  closed = true;
@@ -370,7 +394,7 @@ function createLocalQueueEngine(options) {
370
394
  },
371
395
  async enqueue(queue, entries) {
372
396
  await this.start();
373
- const enqueued = enqueueTail.then(async () => {
397
+ return await mutate(async () => {
374
398
  const now = Date.now();
375
399
  const created = [];
376
400
  const ids = [];
@@ -408,23 +432,18 @@ function createLocalQueueEngine(options) {
408
432
  created.push(job);
409
433
  ids.push(job.id);
410
434
  }
411
- for (const job of created) {
412
- jobs.set(job.key, job);
413
- writingKeys.add(job.key);
414
- }
415
- const written = await Promise.allSettled(created.map(persist));
416
- for (const job of created) writingKeys.delete(job.key);
417
- const failed = written.find((result) => result.status === "rejected");
435
+ const failed = (await Promise.allSettled(created.map((job) => persist(job, {})))).find((result) => result.status === "rejected");
418
436
  if (failed) {
419
- for (const job of created) jobs.delete(job.key);
420
437
  await Promise.allSettled(created.map(unlink));
421
438
  throw failed.reason;
422
439
  }
440
+ for (const job of created) {
441
+ delete job.payload;
442
+ jobs.set(job.key, job);
443
+ }
423
444
  schedule();
424
445
  return ids;
425
446
  });
426
- enqueueTail = enqueued.then(() => void 0, () => void 0);
427
- return enqueued;
428
447
  },
429
448
  async job(id) {
430
449
  await this.start();
@@ -443,34 +462,66 @@ function createLocalQueueEngine(options) {
443
462
  },
444
463
  async retry(id) {
445
464
  await this.start();
446
- const job = findJob(id);
447
- if (!job) return "missing";
448
- if (attemptInFlight(job)) return "running";
449
- const now = Date.now();
450
- if (job.state === "dead") {
451
- const { payload } = await readPayload(job);
452
- const retry = {
453
- ...job,
454
- attempts: 0,
455
- ...payload === void 0 ? {} : { payload },
456
- state: "pending"
457
- };
458
- delete retry.error;
459
- delete retry.failedAt;
460
- if (job.expiresAt !== void 0) {
461
- retry.retentionMs = job.retentionMs ?? job.expiresAt - job.enqueuedAt;
462
- retry.expiresAt = now + retry.retentionMs;
465
+ return await mutate(async () => {
466
+ const job = findJob(id);
467
+ if (!job) return "missing";
468
+ if (attemptInFlight(job)) return "running";
469
+ if (job.state === "dead" && keyHeld(job)) return "duplicate";
470
+ writingKeys.add(job.key);
471
+ let retry;
472
+ try {
473
+ if (job.state === "dead") retry = await revive(job, Date.now());
474
+ else {
475
+ retry = {
476
+ ...job,
477
+ availableAt: Date.now()
478
+ };
479
+ await persist(retry, await readPayload(job));
480
+ jobs.set(job.key, retry);
481
+ }
482
+ } finally {
483
+ writingKeys.delete(job.key);
484
+ schedule();
463
485
  }
464
- retry.availableAt = now;
465
- await persist(retry);
466
- jobs.set(job.key, retry);
467
- schedule();
468
486
  return toJobSummary(retry, attemptInFlight(retry));
469
- }
470
- job.availableAt = now;
471
- await persist(job);
472
- schedule();
473
- return toJobSummary(job, attemptInFlight(job));
487
+ });
488
+ },
489
+ async retryDead(queue) {
490
+ await this.start();
491
+ return await mutate(async () => {
492
+ const now = Date.now();
493
+ const held = /* @__PURE__ */ new Set();
494
+ for (const job of jobs.values()) if (job.queue === queue && job.idempotencyKey !== void 0 && (job.state === "pending" || attemptInFlight(job))) held.add(job.idempotencyKey);
495
+ const dead = [...jobs.values()].filter((job) => job.queue === queue && job.state === "dead" && !attemptInFlight(job)).sort((a, b) => (b.failedAt ?? 0) - (a.failedAt ?? 0) || b.enqueuedAt - a.enqueuedAt);
496
+ const result = {
497
+ retried: 0,
498
+ skipped: []
499
+ };
500
+ const selected = [];
501
+ for (const job of dead) {
502
+ if (job.idempotencyKey !== void 0 && held.has(job.idempotencyKey)) {
503
+ result.skipped.push(job.id);
504
+ continue;
505
+ }
506
+ if (job.idempotencyKey !== void 0) held.add(job.idempotencyKey);
507
+ selected.push(job);
508
+ writingKeys.add(job.key);
509
+ }
510
+ try {
511
+ for (let start = 0; start < selected.length; start += 500) {
512
+ for (const job of selected.slice(start, start + 500)) {
513
+ await revive(job, now);
514
+ writingKeys.delete(job.key);
515
+ result.retried++;
516
+ }
517
+ schedule();
518
+ }
519
+ } finally {
520
+ for (const job of selected) writingKeys.delete(job.key);
521
+ if (result.retried) schedule();
522
+ }
523
+ return result;
524
+ });
474
525
  },
475
526
  provider: "local",
476
527
  rules,
@@ -529,7 +580,7 @@ function createLocalQueueClient(engine, queue) {
529
580
  }];
530
581
  },
531
582
  async sendBatch(items, options) {
532
- const removed = queueRemovedOptionsError(engine.rules.rules, options, items);
583
+ const removed = queueBatchOptionsError(engine.rules.rules, options, items);
533
584
  if (removed) return [removed, void 0];
534
585
  const entries = [];
535
586
  for (const item of items) {
@@ -1,4 +1,4 @@
1
- import { A as QueueJobStore } from "./types-BzPGPV9z.js";
1
+ import { j as QueueJobStore } from "./types-rZHAtkK0.js";
2
2
  /** One job for the engine. `vite dev` and the clients read `delay` and `retention` into seconds first. */
3
3
  interface LocalQueueEntry {
4
4
  delaySeconds?: number;
@@ -1,8 +1,8 @@
1
1
  import { t as redactInspectionText } from "./inspect-CwdWUhPj.js";
2
- import { t as queueErrorDiagnostics } from "./error-diagnostics-Dv6nKZQW.js";
3
- import { a as normalizePublicQueueIdentifier, r as isQueueError } from "./duration-C5w_-Rf4.js";
4
- import { i as getQueueRuntimeConfig, o as getQueueRuntimeJobStore, s as listQueueDefinitionNames } from "./state-DqxeV11k.js";
5
- import { n as dynamicQueue } from "./client-CwoCdKct.js";
2
+ import { t as queueErrorDiagnostics } from "./error-diagnostics-Yj8XCiya.js";
3
+ import { i as isQueueError, o as normalizePublicQueueIdentifier } from "./duration-BZKArIBP.js";
4
+ import { c as listQueueDefinitionNames, i as getQueueRuntimeConfig, o as getQueueRuntimeJobStore, s as getQueueRuntimeJobWorkers } from "./state-C-t99I4Q.js";
5
+ import { n as dynamicQueue } from "./client-mT8TUaag.js";
6
6
  import { runtimeErrorDiagnostics } from "@vite-hub/runtime/internal/error-diagnostics";
7
7
  // src/runtime/operations.ts
8
8
  const statuses = {
@@ -40,6 +40,7 @@ async function listQueues() {
40
40
  pending: 0,
41
41
  running: 0
42
42
  };
43
+ const workers = config.driver === "postgres" ? getQueueRuntimeJobWorkers() : void 0;
43
44
  return {
44
45
  provider: config.driver,
45
46
  ...config.driver === "local" && config.rules && config.rules !== "local" ? { rules: config.rules } : {},
@@ -52,7 +53,8 @@ async function listQueues() {
52
53
  base: status.base,
53
54
  deadLimit: status.deadLimit,
54
55
  durability: status.durability
55
- }
56
+ },
57
+ ...workers === void 0 ? {} : { workers }
56
58
  };
57
59
  }
58
60
  }
@@ -116,7 +118,10 @@ async function retryQueueJob(id) {
116
118
  if (result === "duplicate") throw failure(queueErrorDiagnostics.QUEUE_JOB_DUPLICATE());
117
119
  return { job: result };
118
120
  }
121
+ async function retryDeadQueueJobs(queue) {
122
+ return await (await localJobs()).retryDead(queue);
123
+ }
119
124
  async function clearQueueJobs(input) {
120
125
  return { cleared: await (await localJobs()).clear(input) };
121
126
  }
122
- export { clearQueueJobs, listQueueJobs, listQueues, retryQueueJob, sendToQueue, showQueueJob };
127
+ export { clearQueueJobs, listQueueJobs, listQueues, retryDeadQueueJobs, retryQueueJob, sendToQueue, showQueueJob };