@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.
Files changed (43) hide show
  1. package/README.md +17 -12
  2. package/dist/{client-CwoCdKct.js → client-B8QVg1mA.js} +46 -15
  3. package/dist/{cloudflare-client-xWteD-su.js → cloudflare-client-BoaOlFzD.js} +13 -8
  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-CcLSF94z.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-GFXYd6mF.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 +174 -36
  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 +24 -5
  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-BR4W57HU.js} +146 -97
  28. package/dist/{local-B72WRWkS.d.ts → local-DUh8sGn-.d.ts} +1 -1
  29. package/dist/{operations-CoEXxfUW.js → operations-COCpSoua.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-B_RVXMs5.js +61 -0
  35. package/dist/runtime/hosted.d.ts +1 -1
  36. package/dist/runtime/hosted.js +32 -20
  37. package/dist/{state-DqxeV11k.js → state-C-t99I4Q.js} +9 -3
  38. package/dist/{types-BevEYrUV.d.ts → types-BPs6OsRv.d.ts} +1 -1
  39. package/dist/{types-BzPGPV9z.d.ts → types-rZHAtkK0.d.ts} +74 -12
  40. package/dist/{vercel-region-DEsR1YJQ.js → vercel-region-Bp3hwRBr.js} +1 -1
  41. package/dist/vite.d.ts +2 -155
  42. package/dist/vite.js +460 -68
  43. package/package.json +3 -3
@@ -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-CcLSF94z.js";
2
+ import { i as reportQueueDeliveryError, n as createQueueDeliveryErrorReport, r as isNonRetryableQueueError } from "./handler-response-GFXYd6mF.js";
3
+ import { n as queueRetryPolicy } from "./retries-BSAZru9n.js";
4
+ import { n as runQueueJob } from "./run-handler-B_RVXMs5.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,23 @@ 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
+ function mutate(run) {
158
+ const result = mutationTail.then(run);
159
+ mutationTail = result.then(() => void 0, () => void 0);
160
+ return result;
161
+ }
162
+ async function persist(job, payload) {
169
163
  const target = file(job);
170
- await writeFile(`${target}.tmp`, JSON.stringify(job), "utf8");
164
+ await writeFile(`${target}.tmp`, JSON.stringify({
165
+ ...job,
166
+ ...payload
167
+ }), "utf8");
171
168
  await rename(`${target}.tmp`, target);
172
169
  }
173
170
  async function unlink(job) {
@@ -200,53 +197,63 @@ function createLocalQueueEngine(options) {
200
197
  arm(next);
201
198
  }
202
199
  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));
200
+ 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
201
  for (const job of dead.slice(0, Math.max(0, dead.length - 100))) {
202
+ if (writingKeys.has(job.key) || jobs.get(job.key) !== job) continue;
205
203
  jobs.delete(job.key);
206
204
  await unlink(job).catch((error) => {
207
205
  console.error(`[vitehub:queue] The local provider cannot delete the dead job file ${file(job)}.`, error);
208
206
  });
209
207
  }
210
208
  }
211
- async function markDead(job, error, reason = `after ${job.attempts} attempts`) {
209
+ async function markDead(job, payload, error, reason = `after ${job.attempts} attempts`) {
212
210
  storeFailures.delete(job);
213
211
  job.state = "dead";
214
212
  job.error = error;
215
213
  job.failedAt = Date.now();
216
214
  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;
215
+ await persist(job, payload);
219
216
  await pruneDead(job.queue);
220
217
  }
221
218
  async function expire(job) {
222
219
  expiringKeys.add(job.key);
223
220
  try {
224
- await markDead(job, {
221
+ await mutate(async () => markDead(job, await readPayload(job), {
225
222
  message: "[vitehub] The job expired at the end of its retention period.",
226
223
  name: "Error"
227
- }, "because its retention period ended");
224
+ }, "because its retention period ended"));
228
225
  } catch (error) {
229
226
  console.error(`[vitehub:queue] The local provider cannot update the job file in ${base}.`, error);
230
227
  } finally {
231
228
  expiringKeys.delete(job.key);
232
229
  }
233
230
  }
234
- async function complete(job) {
231
+ async function complete(job, payload) {
235
232
  job.state = "done";
236
233
  try {
237
234
  await unlink(job);
238
235
  jobs.delete(job.key);
239
236
  } catch (error) {
240
237
  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));
238
+ 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
239
  }
243
240
  }
241
+ function retryPolicy(definition) {
242
+ const policy = queueRetryPolicy(definition?.retries);
243
+ return options.retryDelayMs ? {
244
+ ...policy,
245
+ delayMs: options.retryDelayMs
246
+ } : policy;
247
+ }
244
248
  async function deliver(job) {
245
249
  runningKeys.add(job.key);
246
250
  running.set(job.queue, (running.get(job.queue) ?? 0) + 1);
251
+ let retries = retryPolicy(void 0);
247
252
  try {
248
- if (job.attempts >= rules.maxAttempts) {
249
- await markDead(job, {
253
+ const payload = await readPayload(job);
254
+ retries = await options.load(job.queue).then(retryPolicy).catch(() => retries);
255
+ if (job.attempts > retries.limit) {
256
+ await markDead(job, payload, {
250
257
  message: "[vitehub] The process stopped during the last attempt of this job.",
251
258
  name: "Error"
252
259
  });
@@ -256,7 +263,7 @@ function createLocalQueueEngine(options) {
256
263
  await persist({
257
264
  ...job,
258
265
  attempts
259
- });
266
+ }, payload);
260
267
  storeFailures.delete(job);
261
268
  job.attempts = attempts;
262
269
  let handled = false;
@@ -266,13 +273,11 @@ function createLocalQueueEngine(options) {
266
273
  const limit = Number(definition.concurrency ?? 1);
267
274
  concurrency.set(job.queue, Number.isFinite(limit) ? Math.max(1, Math.floor(limit)) : 1);
268
275
  schedule();
269
- await runInRunScopes(async () => {
270
- checkQueueHandlerResponse(await definition.handler({
271
- attempts: job.attempts,
272
- id: job.id,
273
- payload: job.payload
274
- }));
275
- });
276
+ await runQueueJob(definition, {
277
+ attempts: job.attempts,
278
+ id: job.id,
279
+ payload: payload.payload
280
+ }, job.queue);
276
281
  handled = true;
277
282
  } catch (error) {
278
283
  const context = {
@@ -283,19 +288,19 @@ function createLocalQueueEngine(options) {
283
288
  queue: job.queue
284
289
  };
285
290
  reportQueueDeliveryError(error, context);
286
- if (isNonRetryableQueueError(error) || job.attempts >= rules.maxAttempts) await markDead(job, createQueueDeliveryErrorReport(error, context).error);
291
+ if (isNonRetryableQueueError(error) || job.attempts > retries.limit) await markDead(job, payload, createQueueDeliveryErrorReport(error, context).error);
287
292
  else {
288
- job.availableAt = Date.now() + retryDelayMs(job.attempts);
293
+ job.availableAt = Date.now() + retries.delayMs(job.attempts);
289
294
  job.error = createQueueDeliveryErrorReport(error, context).error;
290
- await persist(job);
295
+ await persist(job, payload);
291
296
  }
292
297
  }
293
- if (handled) await complete(job);
298
+ if (handled) await complete(job, payload);
294
299
  } catch (storeError) {
295
300
  if (job.state === "pending") {
296
301
  const failures = (storeFailures.get(job) ?? 0) + 1;
297
302
  storeFailures.set(job, failures);
298
- job.availableAt = Date.now() + Math.max(retryDelayMs(Math.max(1, job.attempts)), storeRetryDelayMs(failures));
303
+ job.availableAt = Math.max(job.availableAt, Date.now() + storeRetryDelayMs(failures));
299
304
  }
300
305
  console.error(`[vitehub:queue] The local provider cannot update the job file in ${base}.`, storeError);
301
306
  } finally {
@@ -324,9 +329,9 @@ function createLocalQueueEngine(options) {
324
329
  message: "[vitehub] Queue Delivery failed.",
325
330
  name: "Error"
326
331
  };
327
- await persist(job);
332
+ await persist(job, {});
328
333
  }
329
- if (job.state === "dead") delete job.payload;
334
+ delete job.payload;
330
335
  recovered.push(job);
331
336
  } catch (error) {
332
337
  console.error(`[vitehub:queue] The local provider skips ${join(base, name)}: it cannot read it.`, error);
@@ -344,8 +349,24 @@ function createLocalQueueEngine(options) {
344
349
  }
345
350
  return found;
346
351
  }
352
+ async function revive(job, now) {
353
+ const retry = {
354
+ ...job,
355
+ attempts: 0,
356
+ state: "pending"
357
+ };
358
+ delete retry.error;
359
+ delete retry.failedAt;
360
+ if (job.expiresAt !== void 0) {
361
+ retry.retentionMs = job.retentionMs ?? job.expiresAt - job.enqueuedAt;
362
+ retry.expiresAt = now + retry.retentionMs;
363
+ }
364
+ retry.availableAt = now;
365
+ await persist(retry, await readPayload(job));
366
+ jobs.set(job.key, retry);
367
+ return retry;
368
+ }
347
369
  async function readPayload(job) {
348
- if (job.state !== "dead") return Object.hasOwn(job, "payload") ? { payload: job.payload } : {};
349
370
  const stored = JSON.parse(await readFile(file(job), "utf8"));
350
371
  return isStoredJob(stored) && Object.hasOwn(stored, "payload") ? { payload: stored.payload } : {};
351
372
  }
@@ -353,16 +374,18 @@ function createLocalQueueEngine(options) {
353
374
  base,
354
375
  async clear(filter = {}) {
355
376
  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;
377
+ return await mutate(async () => {
378
+ let cleared = 0;
379
+ for (const job of jobs.values()) {
380
+ if (job.state === "done" || attemptInFlight(job)) continue;
381
+ if (filter.queue !== void 0 && job.queue !== filter.queue) continue;
382
+ if (filter.state !== void 0 && job.state !== filter.state) continue;
383
+ jobs.delete(job.key);
384
+ await unlink(job);
385
+ cleared++;
386
+ }
387
+ return cleared;
388
+ });
366
389
  },
367
390
  close() {
368
391
  closed = true;
@@ -370,7 +393,7 @@ function createLocalQueueEngine(options) {
370
393
  },
371
394
  async enqueue(queue, entries) {
372
395
  await this.start();
373
- const enqueued = enqueueTail.then(async () => {
396
+ return await mutate(async () => {
374
397
  const now = Date.now();
375
398
  const created = [];
376
399
  const ids = [];
@@ -408,23 +431,18 @@ function createLocalQueueEngine(options) {
408
431
  created.push(job);
409
432
  ids.push(job.id);
410
433
  }
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");
434
+ const failed = (await Promise.allSettled(created.map((job) => persist(job, {})))).find((result) => result.status === "rejected");
418
435
  if (failed) {
419
- for (const job of created) jobs.delete(job.key);
420
436
  await Promise.allSettled(created.map(unlink));
421
437
  throw failed.reason;
422
438
  }
439
+ for (const job of created) {
440
+ delete job.payload;
441
+ jobs.set(job.key, job);
442
+ }
423
443
  schedule();
424
444
  return ids;
425
445
  });
426
- enqueueTail = enqueued.then(() => void 0, () => void 0);
427
- return enqueued;
428
446
  },
429
447
  async job(id) {
430
448
  await this.start();
@@ -443,34 +461,65 @@ function createLocalQueueEngine(options) {
443
461
  },
444
462
  async retry(id) {
445
463
  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;
464
+ return await mutate(async () => {
465
+ const job = findJob(id);
466
+ if (!job) return "missing";
467
+ if (attemptInFlight(job)) return "running";
468
+ writingKeys.add(job.key);
469
+ let retry;
470
+ try {
471
+ if (job.state === "dead") retry = await revive(job, Date.now());
472
+ else {
473
+ retry = {
474
+ ...job,
475
+ availableAt: Date.now()
476
+ };
477
+ await persist(retry, await readPayload(job));
478
+ jobs.set(job.key, retry);
479
+ }
480
+ } finally {
481
+ writingKeys.delete(job.key);
482
+ schedule();
463
483
  }
464
- retry.availableAt = now;
465
- await persist(retry);
466
- jobs.set(job.key, retry);
467
- schedule();
468
484
  return toJobSummary(retry, attemptInFlight(retry));
469
- }
470
- job.availableAt = now;
471
- await persist(job);
472
- schedule();
473
- return toJobSummary(job, attemptInFlight(job));
485
+ });
486
+ },
487
+ async retryDead(queue) {
488
+ await this.start();
489
+ return await mutate(async () => {
490
+ const now = Date.now();
491
+ const held = /* @__PURE__ */ new Set();
492
+ for (const job of jobs.values()) if (job.queue === queue && job.idempotencyKey !== void 0 && (job.state === "pending" || attemptInFlight(job))) held.add(job.idempotencyKey);
493
+ 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);
494
+ const result = {
495
+ retried: 0,
496
+ skipped: []
497
+ };
498
+ const selected = [];
499
+ for (const job of dead) {
500
+ if (job.idempotencyKey !== void 0 && held.has(job.idempotencyKey)) {
501
+ result.skipped.push(job.id);
502
+ continue;
503
+ }
504
+ if (job.idempotencyKey !== void 0) held.add(job.idempotencyKey);
505
+ selected.push(job);
506
+ writingKeys.add(job.key);
507
+ }
508
+ try {
509
+ for (let start = 0; start < selected.length; start += 500) {
510
+ for (const job of selected.slice(start, start + 500)) {
511
+ await revive(job, now);
512
+ writingKeys.delete(job.key);
513
+ result.retried++;
514
+ }
515
+ schedule();
516
+ }
517
+ } finally {
518
+ for (const job of selected) writingKeys.delete(job.key);
519
+ if (result.retried) schedule();
520
+ }
521
+ return result;
522
+ });
474
523
  },
475
524
  provider: "local",
476
525
  rules,
@@ -529,7 +578,7 @@ function createLocalQueueClient(engine, queue) {
529
578
  }];
530
579
  },
531
580
  async sendBatch(items, options) {
532
- const removed = queueRemovedOptionsError(engine.rules.rules, options, items);
581
+ const removed = queueBatchOptionsError(engine.rules.rules, options, items);
533
582
  if (removed) return [removed, void 0];
534
583
  const entries = [];
535
584
  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-CcLSF94z.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-B8QVg1mA.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 };
@@ -1,3 +1,171 @@
1
+ import "nostics";
2
+ interface HostCliRunResult {
3
+ exitCode: number | null;
4
+ stdout: string;
5
+ stderr?: string;
6
+ }
7
+ /** Runs a host CLI with an argument array and no shell, and returns its stdout. */
8
+ type HostCliRun = (command: string, args: readonly string[], options: {
9
+ cwd?: string;
10
+ env: NodeJS.ProcessEnv;
11
+ signal?: AbortSignal;
12
+ }) => Promise<HostCliRunResult>;
13
+ type ProvisionProvider = "cloudflare" | "vercel";
14
+ interface ProvisionLogger {
15
+ log: (message: string) => void;
16
+ warn: (message: string) => void;
17
+ }
18
+ interface ProvisionContext {
19
+ env: Record<string, string | undefined>;
20
+ fetch: typeof globalThis.fetch;
21
+ logger: ProvisionLogger;
22
+ markPlanUnchecked?: () => void;
23
+ }
24
+ interface ProvisionState {
25
+ cloudflare?: Record<string, Record<string, string>>;
26
+ vercel?: Record<string, Record<string, string>>;
27
+ }
28
+ interface ProvisionResult {
29
+ ids?: ProvisionState;
30
+ }
31
+ interface ProvisionAction {
32
+ kind: string;
33
+ name: string;
34
+ exists: boolean;
35
+ pending?: boolean;
36
+ /** Describes the change that `apply()` makes to an existing resource, for example `read replication: disabled -> auto`. */
37
+ update?: string;
38
+ apply: () => Promise<ProvisionResult>;
39
+ }
40
+ /** One Provision State category that a step records, with the keys that current Definitions use. */
41
+ interface ProvisionStateCategory {
42
+ category: string;
43
+ declared: readonly string[];
44
+ /** Provider resource identity for shared-resource checks. Return undefined when the recorded id lacks enough information. Defaults to the recorded id. */
45
+ resourceIdentity?: (entry: {
46
+ id: string;
47
+ key: string;
48
+ }) => string | undefined;
49
+ /** Identity expected by current config for a declared key. Omit when it cannot be established without provider access. */
50
+ declaredResourceIdentity?: (key: string) => string | undefined;
51
+ /** Tells a developer how to delete the resource of a recorded entry that no Definition declares. ViteHub never runs it. */
52
+ deleteHint: (entry: {
53
+ id: string;
54
+ key: string;
55
+ }) => string;
56
+ }
57
+ interface ProvisionStep {
58
+ id: string;
59
+ provider: ProvisionProvider;
60
+ plan: (context: ProvisionContext) => Promise<ProvisionAction[]>;
61
+ hasResources?: (context: Pick<ProvisionContext, "env">) => boolean;
62
+ /** Describes the Provision State this step records. Runs without network access, also without credentials. */
63
+ recordedState?: (context: Pick<ProvisionContext, "env">) => ProvisionStateCategory[];
64
+ }
65
+ interface ViteHubCliStreams {
66
+ stderr: {
67
+ write: (chunk: string | Uint8Array, encoding?: BufferEncoding | StdoutWriteCallback, callback?: StdoutWriteCallback) => unknown;
68
+ };
69
+ stdout: {
70
+ write: (chunk: string | Uint8Array) => unknown;
71
+ };
72
+ }
73
+ interface ViteHubCliSpawnResult {
74
+ exitCode: number | null;
75
+ signal?: NodeJS.Signals | null;
76
+ /** The output of the child when `stdout` is `pipe`. */
77
+ stdout?: string;
78
+ /** The error output of the child when `stderr` is `pipe`. */
79
+ stderr?: string;
80
+ }
81
+ interface ViteHubCliSpawnOptions {
82
+ cwd?: string;
83
+ env?: NodeJS.ProcessEnv;
84
+ onOutput?: (text: string, stream: "stdout" | "stderr") => void;
85
+ stderr?: "inherit" | "pipe";
86
+ /** `ignore` gives the child no terminal input, so a tool that asks questions on a terminal does not ask. */
87
+ stdin?: "ignore" | "inherit";
88
+ /** `stderr` sends the child's stdout to the parent's stderr, so the parent's stdout keeps only its own output. */
89
+ stdout?: "inherit" | "pipe" | "stderr";
90
+ }
91
+ type ViteHubCliSpawn = (command: string, args: string[], options?: ViteHubCliSpawnOptions) => Promise<ViteHubCliSpawnResult>;
92
+ /** Where a call to an app goes through the Console: the operation endpoint of the app's Console project, and the token of `vitehub login`. */
93
+ interface ViteHubCliConsoleRoute {
94
+ authorization: string;
95
+ target: string;
96
+ }
97
+ interface ViteHubCliContext extends ViteHubCliStreams {
98
+ /**
99
+ * Finds the app at `url` in the Console of `vitehub login` and returns the route that lets the Console sign the call.
100
+ * Returns nothing when the command must call the app directly, such as when a `VITEHUB_CONSOLE_PRIVATE_KEY_<NAME>` is set.
101
+ */
102
+ consoleRoute?: (url: string, signal: AbortSignal) => Promise<ViteHubCliConsoleRoute | undefined>;
103
+ cwd: string;
104
+ env: NodeJS.ProcessEnv;
105
+ /** Replaces `fetch` for commands that call a running app, so tests need no server. */
106
+ fetch?: typeof fetch;
107
+ /**
108
+ * Loads the project config for a build on `host` and returns the Provision Steps of its plugins, with the config root
109
+ * that holds `.vitehub/provision.json`. Setup commands, such as `vitehub deploy`, call it only when they need the
110
+ * steps, so they still run on a config that throws.
111
+ */
112
+ loadProvision?: (host: ProvisionProvider) => Promise<ViteHubCliProvision>;
113
+ /** The deployed app's public origin from `vitehub({ publicUrl })`, when it is one string. */
114
+ publicUrl?: string;
115
+ rootDir: string;
116
+ /** Replaces the host CLI runner, such as for `wrangler auth token`, so tests need no real host CLI. */
117
+ runHostCli?: HostCliRun;
118
+ spawn: ViteHubCliSpawn;
119
+ }
120
+ interface ViteHubCliProvision {
121
+ env?: NodeJS.ProcessEnv;
122
+ rootDir: string;
123
+ steps: readonly ProvisionStep[];
124
+ }
125
+ interface ViteHubCliFeature {
126
+ description?: string;
127
+ name: string;
128
+ run: (args: string[], context: ViteHubCliContext) => Promise<number | void> | number | void;
129
+ usage?: string;
130
+ }
131
+ interface ViteHubCliCommandNamespace {
132
+ /** The feature that `vitehub <name>` runs when the next argument names no other feature. It gets every argument after `<name>`. */
133
+ defaultFeature?: string;
134
+ description?: string;
135
+ features: ViteHubCliFeature[];
136
+ name: string;
137
+ }
138
+ /** The flags of `vitehub seed` that every seed gets. */
139
+ interface ViteHubCliSeedOptions {
140
+ /** `--database <name>`: seed only this Database. Only the Database seed runs. */
141
+ database?: string;
142
+ /** The process environment with the env files of `--stage`. */
143
+ env: NodeJS.ProcessEnv;
144
+ /** `--remote`: write the deployed stores. Without it, a seed writes only local data. */
145
+ remote: boolean;
146
+ /** `--timeout <ms>` of each call to the app. */
147
+ timeout?: number;
148
+ /** The deployed app with `--remote`: `--url`, or `vitehub({ publicUrl })`. */
149
+ url?: string;
150
+ }
151
+ /** The seed files of one primitive, which `vitehub seed` writes. */
152
+ interface ViteHubCliSeed {
153
+ /** Where the seed files are, such as `server/seed/kv/`. `vitehub seed` names it when it finds no seed files. */
154
+ files: string;
155
+ /** The primitive, such as `database` or `kv`. `vitehub seed <name>` runs only this seed. */
156
+ name: string;
157
+ /** Writes the seed files and returns the exit code, or `undefined` when the project has no seed files for this primitive. */
158
+ run: (options: ViteHubCliSeedOptions, context: ViteHubCliContext) => Promise<number | undefined>;
159
+ }
160
+ interface ViteHubCliContributor {
161
+ namespaces: ViteHubCliCommandNamespace[];
162
+ provision?: ProvisionStep[];
163
+ /** The seed files that `vitehub seed` writes. */
164
+ seeds?: ViteHubCliSeed[];
165
+ /** The deployed app's public origin. Commands receive it as `context.publicUrl`. */
166
+ publicUrl?: string;
167
+ }
168
+ type StdoutWriteCallback = (error?: Error | null) => void;
1
169
  /** The Standard Typed interface. This is a base type extended by other specs. */
2
170
  interface StandardTypedV1<Input = unknown, Output = Input> {
3
171
  /** The Standard properties. */
@@ -238,4 +406,4 @@ interface OperationContributionEntry {
238
406
  /** `false`: the app already has these operations at runtime. Only tools such as the CLI and `vitehub inspect` read the entry. */
239
407
  runtime?: false;
240
408
  }
241
- export { OperationContributionEntry as n, AnyOperation as t };
409
+ export { OperationContributionEntry as n, ViteHubCliContributor as r, AnyOperation as t };