@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
package/dist/index.d.ts CHANGED
@@ -1,14 +1,18 @@
1
- import { A as QueueJobStore, B as VercelQueueCallbackOptions, C as QueueDefinitionRegistry, D as QueueErrorCode, E as QueueEnqueueOptions, F as QueueRegistry, G as VercelQueueSendBatchMessage, H as VercelQueueErrorCode, I as QueueSendResult, K as VercelQueueSendBatchOptions, L as ResolvedLocalQueueOptions, M as QueueName, N as QueueOptions, O as QueueHandler, P as QueuePayload, R as ResolvedQueueOptions, S as QueueDefinitionOptions, T as QueueDriverOptions, U as VercelQueueRetryDirective, V as VercelQueueClient, W as VercelQueueRetryHandler, _ as PostgresQueueClient, a as CloudflareQueueMessageBatch, b as QueueClient, c as LocalQueueClient, g as NodeQueueDriver, i as CloudflareQueueMessage, j as QueueModuleDriverOptions, k as QueueJob, l as LocalQueueDriverOptions, m as LocalQueueSendBatchMessage, n as CloudflareQueueClient, o as CloudflareQueueSendBatchItem, p as LocalQueueRules, q as VercelQueueSendResult, r as CloudflareQueueErrorCode, s as DiscoveredQueueDefinition, t as CloudflareQueueBatchHandlerOptions, u as LocalQueueErrorCode, v as PostgresQueueDriverOptions, w as QueueDriver, x as QueueDefinition, y as PostgresQueueErrorCode, z as VercelQueueBatchSendResult } from "./types-BzPGPV9z.js";
1
+ import { A as QueueJob, B as QueueSendResult, C as QueueDefinitionOptions, D as QueueEnqueueOptions, E as QueueDriverOptions, F as QueuePayload, G as VercelQueueCallbackOptions, H as ResolvedLocalQueueOptions, I as QueueRegistry, J as VercelQueueRetryDirective, K as VercelQueueClient, L as QueueRetries, M as QueueModuleDriverOptions, N as QueueName, O as QueueErrorCode, P as QueueOptions, Q as VercelQueueSendResult, R as QueueRetryBackoff, S as QueueDefinition, T as QueueDriver, U as ResolvedQueueOptions, V as QueueTransaction, W as VercelQueueBatchSendResult, X as VercelQueueSendBatchMessage, Y as VercelQueueRetryHandler, Z as VercelQueueSendBatchOptions, _ as NodeQueueDriver, a as CloudflareQueueMessageBatch, b as PostgresQueueErrorCode, c as LocalQueueClient, g as NamedQueueClient, i as CloudflareQueueMessage, j as QueueJobStore, k as QueueHandler, l as LocalQueueDriverOptions, m as LocalQueueSendBatchMessage, n as CloudflareQueueClient, o as CloudflareQueueSendBatchItem, p as LocalQueueRules, q as VercelQueueErrorCode, r as CloudflareQueueErrorCode, s as DiscoveredQueueDefinition, t as CloudflareQueueBatchHandlerOptions, u as LocalQueueErrorCode, v as PostgresQueueClient, w as QueueDefinitionRegistry, x as QueueClient, y as PostgresQueueDriverOptions, z as QueueRetryDeadResult } from "./types-rZHAtkK0.js";
2
2
  import { Result } from "@vite-hub/runtime";
3
3
  /**
4
4
  * Defines a Queue from one object: `defineQueue({ handler, concurrency })`. The handler receives one object,
5
- * `{ payload, id, attempts, metadata }`. The payload type of `handler` types `sendQueue()` for this Queue.
5
+ * `{ payload, id, attempts, metadata, signal }`. The payload type of `handler` types `sendQueue()` for this Queue.
6
6
  */
7
7
  export declare function defineQueue<TPayload = unknown, TResult = unknown>(definition: QueueDefinition<TPayload, TResult>): QueueDefinition<TPayload, TResult>;
8
8
  export declare function createQueueMessageId(prefix?: string): string;
9
- declare function useDynamicQueue(name: string): Promise<QueueClient>;
10
9
  declare function sendDynamicQueue(name: string, payload: unknown, options?: QueueEnqueueOptions): Promise<Result<QueueSendResult, QueueErrorCode>>;
11
- declare function deferDynamicQueue(name: string, payload: unknown, options?: QueueEnqueueOptions): void;
10
+ declare function useDynamicQueue(name: string): NamedQueueClient;
11
+ /** Options of `deferQueue()`. A deferred send runs after the response, when a Database transaction has ended. */
12
+ type QueueDeferOptions = Omit<QueueEnqueueOptions, "transaction"> & {
13
+ transaction?: never;
14
+ };
15
+ declare function deferDynamicQueue(name: string, payload: unknown, options?: QueueDeferOptions): void;
12
16
  /** Dispatch externally supplied names and payloads after application validation. */
13
17
  export declare const dynamicQueue: {
14
18
  defer: typeof deferDynamicQueue;
@@ -16,9 +20,10 @@ export declare const dynamicQueue: {
16
20
  use: typeof useDynamicQueue;
17
21
  };
18
22
  /**
19
- * Returns the QueueClient of a discovered Queue Definition, for `sendBatch()` and provider methods. Config errors, for example an unknown name, throw.
23
+ * Returns the client of a discovered Queue Definition, for `send()` and `sendBatch()`. It loads the provider on the
24
+ * first call. Config errors, for example an unknown name, reject that call.
20
25
  */
21
- export declare function useQueue<TName extends QueueName>(name: TName): Promise<QueueClient<QueueDriver, QueuePayload<TName>>>;
26
+ export declare function useQueue<TName extends QueueName>(name: TName): NamedQueueClient<QueueDriver, QueuePayload<TName>>;
22
27
  /**
23
28
  * Sends one job to the Queue and returns `[error, result]`. `error.code` is a `QueueErrorCode`.
24
29
  * Config errors, for example an unknown Queue name, throw.
@@ -28,6 +33,6 @@ export declare function sendQueue<TName extends QueueName>(name: TName, payload:
28
33
  * Sends one job after the response, through `waitUntil`. It returns nothing: a failure goes to the log and to the
29
34
  * `onDispatchError` option of the Queue Definition. Call `sendQueue()` when the caller needs the message ID.
30
35
  */
31
- export declare function deferQueue<TName extends QueueName>(name: TName, payload: NoInfer<QueuePayload<TName>>, options?: QueueEnqueueOptions): void;
36
+ export declare function deferQueue<TName extends QueueName>(name: TName, payload: NoInfer<QueuePayload<TName>>, options?: QueueDeferOptions): void;
32
37
  export declare function createQueueClient(options: QueueDriverOptions): Promise<QueueClient>;
33
- export type { CloudflareQueueBatchHandlerOptions, CloudflareQueueClient, CloudflareQueueErrorCode, CloudflareQueueMessage, CloudflareQueueMessageBatch, CloudflareQueueSendBatchItem, DiscoveredQueueDefinition, LocalQueueClient, LocalQueueDriverOptions, LocalQueueErrorCode, LocalQueueRules, LocalQueueSendBatchMessage, NodeQueueDriver, PostgresQueueClient, PostgresQueueDriverOptions, PostgresQueueErrorCode, QueueClient, QueueDefinition, QueueDefinitionOptions, QueueDefinitionRegistry, QueueDriver, QueueDriverOptions, QueueEnqueueOptions, QueueErrorCode, QueueHandler, QueueJob, QueueJobStore, QueueModuleDriverOptions, QueueName, QueueOptions, QueuePayload, QueueRegistry, QueueSendResult, ResolvedLocalQueueOptions, ResolvedQueueOptions, VercelQueueBatchSendResult, VercelQueueCallbackOptions, VercelQueueClient, VercelQueueErrorCode, VercelQueueRetryDirective, VercelQueueRetryHandler, VercelQueueSendBatchMessage, VercelQueueSendBatchOptions, VercelQueueSendResult };
38
+ export type { CloudflareQueueBatchHandlerOptions, CloudflareQueueClient, CloudflareQueueErrorCode, CloudflareQueueMessage, CloudflareQueueMessageBatch, CloudflareQueueSendBatchItem, DiscoveredQueueDefinition, LocalQueueClient, LocalQueueDriverOptions, LocalQueueErrorCode, LocalQueueRules, LocalQueueSendBatchMessage, NamedQueueClient, NodeQueueDriver, PostgresQueueClient, PostgresQueueDriverOptions, PostgresQueueErrorCode, QueueClient, QueueDeferOptions, QueueDefinition, QueueDefinitionOptions, QueueDefinitionRegistry, QueueDriver, QueueDriverOptions, QueueEnqueueOptions, QueueErrorCode, QueueHandler, QueueJob, QueueJobStore, QueueModuleDriverOptions, QueueName, QueueOptions, QueuePayload, QueueRegistry, QueueRetries, QueueRetryBackoff, QueueRetryDeadResult, QueueSendResult, QueueTransaction, ResolvedLocalQueueOptions, ResolvedQueueOptions, VercelQueueBatchSendResult, VercelQueueCallbackOptions, VercelQueueClient, VercelQueueErrorCode, VercelQueueRetryDirective, VercelQueueRetryHandler, VercelQueueSendBatchMessage, VercelQueueSendBatchOptions, VercelQueueSendResult };
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
- import { t as defineQueue } from "./definition-CIiFfst2.js";
2
- import { u as createQueueMessageId } from "./duration-C5w_-Rf4.js";
3
- import { i as useQueue, n as dynamicQueue, r as sendQueue, t as deferQueue } from "./client-CwoCdKct.js";
4
- import { t as queueErrorDiagnostics } from "./error-diagnostics-Dv6nKZQW.js";
1
+ import { t as defineQueue } from "./definition-Dorliu47.js";
2
+ import { p as createQueueMessageId } from "./duration-BZKArIBP.js";
3
+ import { a as useQueue, i as sendQueue, n as dynamicQueue, t as deferQueue } from "./client-mT8TUaag.js";
4
+ import { t as queueErrorDiagnostics } from "./error-diagnostics-Yj8XCiya.js";
5
5
  // src/runtime/create-client.ts
6
6
  async function createQueueClient(options) {
7
7
  if (options.driver === void 0 && Object.hasOwn(options, "provider")) {
@@ -1,2 +1,2 @@
1
- import { T as QueueDriverOptions, b as QueueClient } from "../../types-BzPGPV9z.js";
1
+ import { E as QueueDriverOptions, x as QueueClient } from "../../types-rZHAtkK0.js";
2
2
  export declare function createCloudflareQueueRuntimeClient(options: QueueDriverOptions): Promise<QueueClient>;
@@ -1 +1 @@
1
- export { t as createCloudflareQueueRuntimeClient } from "../../cloudflare-client-xWteD-su.js";
1
+ export { t as createCloudflareQueueRuntimeClient } from "../../cloudflare-client-DBgvWY0z.js";
@@ -1,4 +1,4 @@
1
- import { C as QueueDefinitionRegistry, R as ResolvedQueueOptions, a as CloudflareQueueMessageBatch } from "../../types-BzPGPV9z.js";
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-kKXseq8d.js";
2
- import { n as normalizeQueueOptions } from "../../config-Bzp1xmdh.js";
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-Bv8Z7nDU.js";
5
- import { n as createCloudflareQueueBatchHandler, t as createCloudflareQueueRuntimeClient } from "../../cloudflare-client-xWteD-su.js";
6
- import { _ as runWithActiveCloudflareEnv, c as loadQueueDefinition, d as setQueueRuntimeConfig, h as createCloudflareRuntimeEvent, m as setQueueRuntimeRegistry, u as runWithQueueRuntimeEvent } from "../../state-DqxeV11k.js";
7
- import { t as queueErrorDiagnostics } from "../../error-diagnostics-Dv6nKZQW.js";
8
- import { runInRunScopes } from "@vite-hub/runtime/internal/run-scope";
4
+ import { t as getCloudflareQueueName } from "../../cloudflare-resource-name-Coz5CPmn.js";
5
+ import { n as createCloudflareQueueBatchHandler, t as createCloudflareQueueRuntimeClient } from "../../cloudflare-client-DBgvWY0z.js";
6
+ import { t as runQueueHandler } from "../../run-handler-COXFYL5z.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 runInRunScopes(() => definition.handler(createQueueJob(message, currentBatch)));
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-B72WRWkS.js";
2
- import { b as QueueClient, h as LocalQueueStatus } from "../../types-BzPGPV9z.js";
3
- import { n as QueueRuntimeOptions, t as QueueRuntimeDriverOptions } from "../../types-BevEYrUV.js";
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-Bzp1xmdh.js";
2
- import { i as localQueueDeliveryRules, n as createLocalQueueEngine, t as createLocalQueueClient } from "../../local-RX10a_Sq.js";
3
- import { c as loadQueueDefinition, l as missingQueueDefinitionError } from "../../state-DqxeV11k.js";
4
- import { t as queueErrorDiagnostics } from "../../error-diagnostics-Dv6nKZQW.js";
1
+ import { t as defaultLocalQueueBase } from "../../config-ByKUipob.js";
2
+ import { i as localQueueDeliveryRules, n as createLocalQueueEngine, t as createLocalQueueClient } from "../../local-5pcvR1RC.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 { b as QueueClient } from "../../types-BzPGPV9z.js";
2
- import "../../local-B72WRWkS.js";
3
- import { n as QueueRuntimeOptions, t as QueueRuntimeDriverOptions } from "../../types-BevEYrUV.js";
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
- * `databases` loads the Databases of the app, for a build that found its Default Database on Postgres. Logs once where
39
- * the jobs are.
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-Bzp1xmdh.js";
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 queueRemovedOptionsError, d as normalizeQueueEnqueueInput, l as queueUnsupportedOptionsError, s as queueProviderResult, t as readQueueTimes, u as createQueueMessageId } from "../../duration-C5w_-Rf4.js";
4
- import { i as reportQueueDeliveryError, n as createQueueDeliveryErrorReport, r as isNonRetryableQueueError, t as checkQueueHandlerResponse } from "../../handler-response-CchTXVjm.js";
5
- import { i as localQueueDeliveryRules, r as delayMs } from "../../local-RX10a_Sq.js";
6
- import { c as loadQueueDefinition, l as missingQueueDefinitionError, p as setQueueRuntimeJobStore, s as listQueueDefinitionNames } from "../../state-DqxeV11k.js";
7
- import { t as queueErrorDiagnostics } from "../../error-diagnostics-Dv6nKZQW.js";
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-BZKArIBP.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-DKhsmxDV.js";
6
+ import { n as isRecord, r as isRecordOrFunction } from "../../object-DRSmpe04.js";
7
+ import { n as queueRetryPolicy } from "../../retries-BSAZru9n.js";
8
+ import { n as runQueueJob } from "../../run-handler-COXFYL5z.js";
9
+ import { i as localQueueDeliveryRules, r as delayMs } from "../../local-5pcvR1RC.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 = isRecord(client) ? client.query : isRecordOrFunction(client) ? client.unsafe : 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 = query.call(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 = localQueueDeliveryRules.postgres;
45
- const retryDelayMs = options.retryDelayMs ?? rules.retryDelayMs;
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
- if (row.attempts > rules.maxAttempts) {
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 runInRunScopes(async () => {
219
- checkQueueHandlerResponse(await definition.handler({
220
- attempts: row.attempts,
221
- id: row.message_id,
222
- payload: row.no_payload ? void 0 : row.payload
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 >= rules.maxAttempts) {
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 => ${retryDelayMs(row.attempts) / 1e3}),
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 instanceof postgres.PostgresError && error.code === "23505") return "duplicate";
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 = queueRemovedOptionsError("postgres", options, items);
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) {
@@ -437,9 +564,8 @@ function createPostgresQueueClient(engine, queue, resolveEngine) {
437
564
  };
438
565
  }
439
566
  // src/internal/runtime/postgres-client.ts
440
- 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
567
  const databaseConnectionUrl = Symbol.for("vitehub.database.postgres.connection-url");
568
+ const postgresUrl = /^postgres(?:ql)?:\/\//i;
443
569
  let loadDatabases;
444
570
  let closing;
445
571
  const engines = /* @__PURE__ */ new Map();
@@ -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 = { workers: false };
580
+ state = {};
455
581
  engines.set(key, state);
456
582
  }
457
583
  return state;
458
584
  }
459
585
  function startWorkers(state, engine) {
460
- if (!state.workers || state.started === engine) return;
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);
@@ -480,13 +610,13 @@ async function resolvePostgresQueueConnection(config, databases = loadDatabases,
480
610
  };
481
611
  }
482
612
  if (config.database && databases) {
483
- const entry = (await databases())[config.database];
484
- const client = entry ? Reflect.get(entry.db, "$client") : void 0;
613
+ const database = (await databases())[config.database]?.db;
614
+ const client = database?.$client;
485
615
  if (isPostgresQueueSql(client)) return {
486
616
  connection: { client },
487
617
  key: client
488
618
  };
489
- const readUrl = entry ? Reflect.get(entry.db, databaseConnectionUrl) : void 0;
619
+ const readUrl = database?.[databaseConnectionUrl];
490
620
  const databaseUrl = typeof readUrl === "function" ? readUrl() : void 0;
491
621
  if (typeof databaseUrl === "string") return {
492
622
  connection: { url: databaseUrl },
@@ -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
- * `databases` loads the Databases of the app, for a build that found its Default Database on Postgres. Logs once where
547
- * the jobs are.
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 = true;
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 the workers.", error);
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 = false;
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 { A as QueueJobStore, C as QueueDefinitionRegistry, b as QueueClient, x as QueueDefinition } from "../../types-BzPGPV9z.js";
2
- import { n as QueueRuntimeOptions, t as QueueRuntimeDriverOptions } from "../../types-BevEYrUV.js";
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 listQueueDefinitionNames, c as loadQueueDefinition, l as missingQueueDefinitionError, u as runWithQueueRuntimeEvent, d as setQueueRuntimeConfig, f as setQueueRuntimeEventDefaults, p as setQueueRuntimeJobStore, m as setQueueRuntimeRegistry } from "../../state-DqxeV11k.js";
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 { T as QueueDriverOptions, b as QueueClient } from "../../types-BzPGPV9z.js";
1
+ import { E as QueueDriverOptions, x as QueueClient } from "../../types-rZHAtkK0.js";
2
2
  export declare function createVercelQueueRuntimeClient(options: QueueDriverOptions): Promise<QueueClient>;