@vercel/queue 0.0.0-alpha.34 → 0.0.0-alpha.35

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -19,6 +19,12 @@ var JsonTransport = class {
19
19
  contentType = "application/json";
20
20
  replacer;
21
21
  reviver;
22
+ /**
23
+ * Create a new JsonTransport.
24
+ * @param options - Optional JSON serialization options
25
+ * @param options.replacer - Custom replacer for JSON.stringify
26
+ * @param options.reviver - Custom reviver for JSON.parse
27
+ */
22
28
  constructor(options = {}) {
23
29
  this.replacer = options.replacer;
24
30
  this.reviver = options.reviver;
@@ -48,6 +54,10 @@ var StreamTransport = class {
48
54
  async deserialize(stream) {
49
55
  return stream;
50
56
  }
57
+ /**
58
+ * Consume any remaining stream data to prevent resource leaks.
59
+ * Called automatically by ConsumerGroup; manual call required for direct client usage.
60
+ */
51
61
  async finalize(payload) {
52
62
  const reader = payload.getReader();
53
63
  try {
@@ -98,6 +108,7 @@ var QueueEmptyError = class extends Error {
98
108
  }
99
109
  };
100
110
  var MessageLockedError = class extends Error {
111
+ /** Suggested retry delay in seconds, if provided by the server. */
101
112
  retryAfter;
102
113
  constructor(messageId, retryAfter) {
103
114
  const retryMessage = retryAfter ? ` Retry after ${retryAfter} seconds.` : " Try again later.";
@@ -143,7 +154,9 @@ var MessageAlreadyProcessedError = class extends Error {
143
154
  }
144
155
  };
145
156
  var ConcurrencyLimitError = class extends Error {
157
+ /** Current number of in-flight messages for this consumer group. */
146
158
  currentInflight;
159
+ /** Maximum allowed concurrent messages (as configured). */
147
160
  maxConcurrency;
148
161
  constructor(message = "Concurrency limit exceeded", currentInflight, maxConcurrency) {
149
162
  super(message);
@@ -530,6 +543,25 @@ var QueueClient = class {
530
543
  }
531
544
  return response;
532
545
  }
546
+ /**
547
+ * Send a message to a topic.
548
+ *
549
+ * @param options - Message options including queue name, payload, and optional settings
550
+ * @param options.queueName - Topic name (pattern: `[A-Za-z0-9_-]+`)
551
+ * @param options.payload - Message payload
552
+ * @param options.idempotencyKey - Optional deduplication key (dedup window: min(retention, 24h))
553
+ * @param options.retentionSeconds - Message TTL (default: 86400, min: 60, max: 86400)
554
+ * @param options.delaySeconds - Delivery delay (default: 0, max: retentionSeconds)
555
+ * @param transport - Serializer for the payload
556
+ * @returns Promise with the generated messageId
557
+ * @throws {DuplicateMessageError} When idempotency key was already used
558
+ * @throws {ConsumerDiscoveryError} When consumer discovery fails
559
+ * @throws {ConsumerRegistryNotConfiguredError} When registry not configured
560
+ * @throws {BadRequestError} When parameters are invalid
561
+ * @throws {UnauthorizedError} When authentication fails
562
+ * @throws {ForbiddenError} When access is denied
563
+ * @throws {InternalServerError} When server encounters an error
564
+ */
533
565
  async sendMessage(options, transport) {
534
566
  const {
535
567
  queueName,
@@ -592,6 +624,25 @@ var QueueClient = class {
592
624
  const responseData = await response.json();
593
625
  return responseData;
594
626
  }
627
+ /**
628
+ * Receive messages from a topic as an async generator.
629
+ *
630
+ * @param options - Receive options
631
+ * @param options.queueName - Topic name (pattern: `[A-Za-z0-9_-]+`)
632
+ * @param options.consumerGroup - Consumer group name (pattern: `[A-Za-z0-9_-]+`)
633
+ * @param options.visibilityTimeoutSeconds - Lock duration (default: 30, min: 0, max: 3600)
634
+ * @param options.limit - Max messages to retrieve (default: 1, min: 1, max: 10)
635
+ * @param options.maxConcurrency - Max in-flight messages (default: unlimited, min: 1)
636
+ * @param transport - Deserializer for message payloads
637
+ * @yields Message objects with payload, messageId, receiptHandle, etc.
638
+ * @throws {QueueEmptyError} When no messages available
639
+ * @throws {InvalidLimitError} When limit is outside 1-10 range
640
+ * @throws {ConcurrencyLimitError} When maxConcurrency exceeded
641
+ * @throws {BadRequestError} When parameters are invalid
642
+ * @throws {UnauthorizedError} When authentication fails
643
+ * @throws {ForbiddenError} When access is denied
644
+ * @throws {InternalServerError} When server encounters an error
645
+ */
595
646
  async *receiveMessages(options, transport) {
596
647
  const {
597
648
  queueName,
@@ -677,6 +728,26 @@ var QueueClient = class {
677
728
  }
678
729
  }
679
730
  }
731
+ /**
732
+ * Receive a specific message by its ID.
733
+ *
734
+ * @param options - Receive options
735
+ * @param options.queueName - Topic name (pattern: `[A-Za-z0-9_-]+`)
736
+ * @param options.consumerGroup - Consumer group name (pattern: `[A-Za-z0-9_-]+`)
737
+ * @param options.messageId - Message ID to retrieve
738
+ * @param options.visibilityTimeoutSeconds - Lock duration (default: 30, min: 0, max: 3600)
739
+ * @param options.maxConcurrency - Max in-flight messages (default: unlimited, min: 1)
740
+ * @param transport - Deserializer for the message payload
741
+ * @returns Promise with the message
742
+ * @throws {MessageNotFoundError} When message doesn't exist
743
+ * @throws {MessageNotAvailableError} When message is in wrong state or was a duplicate
744
+ * @throws {MessageAlreadyProcessedError} When message was already processed
745
+ * @throws {ConcurrencyLimitError} When maxConcurrency exceeded
746
+ * @throws {BadRequestError} When parameters are invalid
747
+ * @throws {UnauthorizedError} When authentication fails
748
+ * @throws {ForbiddenError} When access is denied
749
+ * @throws {InternalServerError} When server encounters an error
750
+ */
680
751
  async receiveMessageById(options, transport) {
681
752
  const {
682
753
  queueName,
@@ -771,6 +842,21 @@ var QueueClient = class {
771
842
  }
772
843
  throw new MessageNotFoundError(messageId);
773
844
  }
845
+ /**
846
+ * Delete (acknowledge) a message after successful processing.
847
+ *
848
+ * @param options - Delete options
849
+ * @param options.queueName - Topic name
850
+ * @param options.consumerGroup - Consumer group name
851
+ * @param options.receiptHandle - Receipt handle from the received message (must use same deployment ID as receive)
852
+ * @returns Promise indicating deletion success
853
+ * @throws {MessageNotFoundError} When receipt handle not found
854
+ * @throws {MessageNotAvailableError} When receipt handle invalid or message already processed
855
+ * @throws {BadRequestError} When parameters are invalid
856
+ * @throws {UnauthorizedError} When authentication fails
857
+ * @throws {ForbiddenError} When access is denied
858
+ * @throws {InternalServerError} When server encounters an error
859
+ */
774
860
  async deleteMessage(options) {
775
861
  const { queueName, consumerGroup, receiptHandle } = options;
776
862
  const headers = new Headers({
@@ -815,6 +901,23 @@ var QueueClient = class {
815
901
  }
816
902
  return { deleted: true };
817
903
  }
904
+ /**
905
+ * Extend or change the visibility timeout of a message.
906
+ * Used to prevent message redelivery while still processing.
907
+ *
908
+ * @param options - Visibility options
909
+ * @param options.queueName - Topic name
910
+ * @param options.consumerGroup - Consumer group name
911
+ * @param options.receiptHandle - Receipt handle from the received message (must use same deployment ID as receive)
912
+ * @param options.visibilityTimeoutSeconds - New timeout (min: 0, max: 3600, cannot exceed message expiration)
913
+ * @returns Promise indicating success
914
+ * @throws {MessageNotFoundError} When receipt handle not found
915
+ * @throws {MessageNotAvailableError} When receipt handle invalid or message already processed
916
+ * @throws {BadRequestError} When parameters are invalid
917
+ * @throws {UnauthorizedError} When authentication fails
918
+ * @throws {ForbiddenError} When access is denied
919
+ * @throws {InternalServerError} When server encounters an error
920
+ */
818
921
  async changeVisibility(options) {
819
922
  const {
820
923
  queueName,
@@ -937,36 +1040,26 @@ var ConsumerGroup = class {
937
1040
  refreshInterval;
938
1041
  transport;
939
1042
  /**
940
- * Create a new ConsumerGroup instance
941
- * @param client QueueClient instance to use for API calls
942
- * @param topicName Name of the topic to consume from
943
- * @param consumerGroupName Name of the consumer group
944
- * @param options Optional configuration
1043
+ * Create a new ConsumerGroup instance.
1044
+ *
1045
+ * @param client - QueueClient instance to use for API calls
1046
+ * @param topicName - Name of the topic to consume from (pattern: `[A-Za-z0-9_-]+`)
1047
+ * @param consumerGroupName - Name of the consumer group (pattern: `[A-Za-z0-9_-]+`)
1048
+ * @param options - Optional configuration
1049
+ * @param options.transport - Payload serializer (default: JsonTransport)
1050
+ * @param options.visibilityTimeoutSeconds - Message lock duration (default: 30, max: 3600)
1051
+ * @param options.visibilityRefreshInterval - Lock refresh interval in seconds (default: visibilityTimeout / 3)
945
1052
  */
946
1053
  constructor(client, topicName, consumerGroupName, options = {}) {
947
1054
  this.client = client;
948
1055
  this.topicName = topicName;
949
1056
  this.consumerGroupName = consumerGroupName;
950
- this.visibilityTimeout = options.visibilityTimeoutSeconds || 30;
951
- this.refreshInterval = options.refreshInterval || 10;
1057
+ this.visibilityTimeout = options.visibilityTimeoutSeconds ?? 30;
1058
+ this.refreshInterval = options.visibilityRefreshInterval ?? Math.floor(this.visibilityTimeout / 3);
952
1059
  this.transport = options.transport || new JsonTransport();
953
1060
  }
954
1061
  /**
955
1062
  * Starts a background loop that periodically extends the visibility timeout for a message.
956
- * This prevents the message from becoming visible to other consumers while it's being processed.
957
- *
958
- * The extension loop runs every `refreshInterval` seconds and updates the message's
959
- * visibility timeout to `visibilityTimeout` seconds from the current time.
960
- *
961
- * @param receiptHandle - The receipt handle that proves ownership of the message
962
- * @returns A function that when called will stop the extension loop
963
- *
964
- * @remarks
965
- * - The first extension attempt occurs after `refreshInterval` seconds, not immediately
966
- * - If an extension fails, the loop terminates with an error logged to console
967
- * - The returned stop function is idempotent - calling it multiple times is safe
968
- * - By default, the stop function returns immediately without waiting for in-flight
969
- * - Pass `true` to the stop function to wait for any in-flight extension to complete
970
1063
  */
971
1064
  startVisibilityExtension(receiptHandle) {
972
1065
  let isRunning = true;
@@ -1238,7 +1331,7 @@ async function parseCallback(request) {
1238
1331
  messageId
1239
1332
  };
1240
1333
  }
1241
- function createCallbackHandler(handlers, client) {
1334
+ function createCallbackHandler(handlers, client, visibilityTimeoutSeconds) {
1242
1335
  for (const topicPattern in handlers) {
1243
1336
  if (topicPattern.includes("*")) {
1244
1337
  if (!validateWildcardPattern(topicPattern)) {
@@ -1274,7 +1367,10 @@ function createCallbackHandler(handlers, client) {
1274
1367
  );
1275
1368
  }
1276
1369
  const topic = new Topic(client, queueName);
1277
- const cg = topic.consumerGroup(consumerGroup);
1370
+ const cg = topic.consumerGroup(
1371
+ consumerGroup,
1372
+ visibilityTimeoutSeconds !== void 0 ? { visibilityTimeoutSeconds } : void 0
1373
+ );
1278
1374
  await cg.consume(consumerGroupHandler, { messageId });
1279
1375
  return Response.json({ status: "success" });
1280
1376
  } catch (error) {
@@ -1290,8 +1386,12 @@ function createCallbackHandler(handlers, client) {
1290
1386
  };
1291
1387
  return routeHandler;
1292
1388
  }
1293
- function handleCallback(handlers, client) {
1294
- return createCallbackHandler(handlers, client || new QueueClient());
1389
+ function handleCallback(handlers, options) {
1390
+ return createCallbackHandler(
1391
+ handlers,
1392
+ options?.client || new QueueClient(),
1393
+ options?.visibilityTimeoutSeconds
1394
+ );
1295
1395
  }
1296
1396
 
1297
1397
  // src/factory.ts
@@ -1354,23 +1454,39 @@ var Client = class {
1354
1454
  });
1355
1455
  }
1356
1456
  /**
1357
- * Create a callback handler for processing queue messages
1358
- * Returns a Next.js route handler function that routes messages to appropriate handlers
1359
- * @param handlers Object with topic-specific handlers organized by consumer groups
1457
+ * Create a callback handler for processing queue messages.
1458
+ * Returns a Next.js route handler function that routes messages to appropriate handlers.
1459
+ *
1460
+ * @param handlers - Object with topic-specific handlers organized by consumer groups
1461
+ * @param options - Optional configuration
1462
+ * @param options.visibilityTimeoutSeconds - Message lock duration (default: 30, max: 3600)
1360
1463
  * @returns A Next.js route handler function
1361
1464
  *
1362
1465
  * @example
1363
1466
  * ```typescript
1467
+ * // Basic usage
1364
1468
  * export const POST = client.handleCallback({
1365
1469
  * "user-events": {
1366
1470
  * "welcome": (user, metadata) => console.log("Welcoming user", user),
1367
1471
  * "analytics": (user, metadata) => console.log("Tracking user", user),
1368
1472
  * },
1369
1473
  * });
1474
+ *
1475
+ * // With custom visibility timeout
1476
+ * export const POST = client.handleCallback({
1477
+ * "video-processing": {
1478
+ * "transcode": async (video) => await transcodeVideo(video),
1479
+ * },
1480
+ * }, {
1481
+ * visibilityTimeoutSeconds: 300, // 5 minutes for long operations
1482
+ * });
1370
1483
  * ```
1371
1484
  */
1372
- handleCallback(handlers) {
1373
- return handleCallback(handlers, this.client);
1485
+ handleCallback(handlers, options) {
1486
+ return handleCallback(handlers, {
1487
+ ...options,
1488
+ client: this.client
1489
+ });
1374
1490
  }
1375
1491
  };
1376
1492
  export {