vercel-queue-bundle 0.7.1__tar.gz

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 (55) hide show
  1. vercel_queue_bundle-0.7.1/LICENSE +21 -0
  2. vercel_queue_bundle-0.7.1/PKG-INFO +683 -0
  3. vercel_queue_bundle-0.7.1/README.md +664 -0
  4. vercel_queue_bundle-0.7.1/_vercel_hatch_build.py +116 -0
  5. vercel_queue_bundle-0.7.1/hatch_build.py +29 -0
  6. vercel_queue_bundle-0.7.1/pyproject.toml +223 -0
  7. vercel_queue_bundle-0.7.1/vercel/queue/__init__.py +8 -0
  8. vercel_queue_bundle-0.7.1/vercel/queue/__main__.py +10 -0
  9. vercel_queue_bundle-0.7.1/vercel/queue/_internal/__init__.py +1 -0
  10. vercel_queue_bundle-0.7.1/vercel/queue/_internal/api_async.py +219 -0
  11. vercel_queue_bundle-0.7.1/vercel/queue/_internal/api_common.py +104 -0
  12. vercel_queue_bundle-0.7.1/vercel/queue/_internal/api_sync.py +137 -0
  13. vercel_queue_bundle-0.7.1/vercel/queue/_internal/asgi.py +145 -0
  14. vercel_queue_bundle-0.7.1/vercel/queue/_internal/asynctools.py +40 -0
  15. vercel_queue_bundle-0.7.1/vercel/queue/_internal/cli.py +313 -0
  16. vercel_queue_bundle-0.7.1/vercel/queue/_internal/client.py +1109 -0
  17. vercel_queue_bundle-0.7.1/vercel/queue/_internal/client_sync.py +432 -0
  18. vercel_queue_bundle-0.7.1/vercel/queue/_internal/config.py +160 -0
  19. vercel_queue_bundle-0.7.1/vercel/queue/_internal/constants.py +50 -0
  20. vercel_queue_bundle-0.7.1/vercel/queue/_internal/devserver.py +205 -0
  21. vercel_queue_bundle-0.7.1/vercel/queue/_internal/embedded.py +1900 -0
  22. vercel_queue_bundle-0.7.1/vercel/queue/_internal/errors.py +262 -0
  23. vercel_queue_bundle-0.7.1/vercel/queue/_internal/http.py +634 -0
  24. vercel_queue_bundle-0.7.1/vercel/queue/_internal/lease.py +1007 -0
  25. vercel_queue_bundle-0.7.1/vercel/queue/_internal/log.py +143 -0
  26. vercel_queue_bundle-0.7.1/vercel/queue/_internal/messages.py +122 -0
  27. vercel_queue_bundle-0.7.1/vercel/queue/_internal/multipart.py +255 -0
  28. vercel_queue_bundle-0.7.1/vercel/queue/_internal/names.py +101 -0
  29. vercel_queue_bundle-0.7.1/vercel/queue/_internal/polling.py +200 -0
  30. vercel_queue_bundle-0.7.1/vercel/queue/_internal/push.py +246 -0
  31. vercel_queue_bundle-0.7.1/vercel/queue/_internal/response.py +111 -0
  32. vercel_queue_bundle-0.7.1/vercel/queue/_internal/retry.py +86 -0
  33. vercel_queue_bundle-0.7.1/vercel/queue/_internal/streams.py +313 -0
  34. vercel_queue_bundle-0.7.1/vercel/queue/_internal/subscribers.py +1025 -0
  35. vercel_queue_bundle-0.7.1/vercel/queue/_internal/transports.py +363 -0
  36. vercel_queue_bundle-0.7.1/vercel/queue/_internal/types.py +300 -0
  37. vercel_queue_bundle-0.7.1/vercel/queue/_internal/typeutils.py +203 -0
  38. vercel_queue_bundle-0.7.1/vercel/queue/_vendor/LICENSE.python-multipart.txt +202 -0
  39. vercel_queue_bundle-0.7.1/vercel/queue/_vendor/__init__.py +1 -0
  40. vercel_queue_bundle-0.7.1/vercel/queue/_vendor/multipart/__init__.py +38 -0
  41. vercel_queue_bundle-0.7.1/vercel/queue/_vendor/multipart/decoders.py +1 -0
  42. vercel_queue_bundle-0.7.1/vercel/queue/_vendor/multipart/exceptions.py +1 -0
  43. vercel_queue_bundle-0.7.1/vercel/queue/_vendor/multipart/multipart.py +1 -0
  44. vercel_queue_bundle-0.7.1/vercel/queue/_vendor/python_multipart/__init__.py +35 -0
  45. vercel_queue_bundle-0.7.1/vercel/queue/_vendor/python_multipart/decoders.py +185 -0
  46. vercel_queue_bundle-0.7.1/vercel/queue/_vendor/python_multipart/exceptions.py +34 -0
  47. vercel_queue_bundle-0.7.1/vercel/queue/_vendor/python_multipart/multipart.py +1925 -0
  48. vercel_queue_bundle-0.7.1/vercel/queue/devserver.py +24 -0
  49. vercel_queue_bundle-0.7.1/vercel/queue/embedded.py +50 -0
  50. vercel_queue_bundle-0.7.1/vercel/queue/py.typed +1 -0
  51. vercel_queue_bundle-0.7.1/vercel/queue/sync.py +8 -0
  52. vercel_queue_bundle-0.7.1/vercel/queue/testing/__init__.py +14 -0
  53. vercel_queue_bundle-0.7.1/vercel/queue/testing/pytest.py +42 -0
  54. vercel_queue_bundle-0.7.1/vercel/queue/testing/state.py +32 -0
  55. vercel_queue_bundle-0.7.1/vercel/queue/version.py +3 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) Vercel Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,683 @@
1
+ Metadata-Version: 2.4
2
+ Name: vercel-queue-bundle
3
+ Version: 0.7.1
4
+ Summary: Vercel Queue client for Python
5
+ License-Expression: MIT
6
+ License-File: LICENSE
7
+ License-File: vercel/queue/_vendor/LICENSE.python-multipart.txt
8
+ Requires-Python: >=3.10
9
+ Requires-Dist: vercel-headers-bundle>=0.7.1
10
+ Requires-Dist: vercel-internal-shared-vendored-deps>=0.1.0
11
+ Requires-Dist: vercel-oidc-bundle>=0.7.1
12
+ Provides-Extra: devserver
13
+ Requires-Dist: uvicorn; extra == 'devserver'
14
+ Provides-Extra: trio
15
+ Requires-Dist: anyio[trio]>=4.0.0; extra == 'trio'
16
+ Provides-Extra: typed
17
+ Requires-Dist: pydantic>=2.7.0; extra == 'typed'
18
+ Description-Content-Type: text/markdown
19
+
20
+ # vercel-queue-bundle
21
+
22
+ This is a version of `vercel-queue` with third-party dependencies bundled. For normal use, install the unbundled `vercel-queue` package instead: https://pypi.org/project/vercel-queue/
23
+
24
+ # Vercel Queues
25
+
26
+ A Python client library for interacting with the Vercel Queues API,
27
+ designed for seamless integration with Vercel deployments.
28
+
29
+ ## Features
30
+
31
+ - **Simple API**: `send`, `subscribe`, and `asgi_app` cover standard workflows.
32
+ - **Automatic Triggering on Vercel**: Vercel invokes your function when messages are ready.
33
+ - **Works Anywhere**: `send`, decorated subscribers, and manual `poll` loops work on Vercel, self-hosted workers, and locally.
34
+ - **Sync and Async Clients**: Prefer async for applications, use sync for scripts and blocking workers.
35
+ - **Type Safety**: `Topic[T]`, typed messages, and optional Pydantic validation.
36
+ - **Customizable Serialization**: Built-in JSON, text, binary, and streaming transports.
37
+ - **Local Development Support**: Embedded queue helpers for tests and development.
38
+
39
+ ## Installation
40
+
41
+ ```bash
42
+ uv add vercel-queue
43
+ ```
44
+
45
+ For Pydantic-backed typed payloads, add the optional `typed` extra:
46
+
47
+ ```bash
48
+ uv add "vercel-queue[typed]"
49
+ ```
50
+
51
+ ## Quick Start
52
+
53
+ **1. Link your Vercel project and pull credentials:**
54
+
55
+ The SDK authenticates via OIDC. Link your project if you haven't already, then
56
+ pull to get fresh tokens:
57
+
58
+ ```bash
59
+ npm i -g vercel
60
+ vc link # if you haven't already
61
+ vc env pull
62
+ ```
63
+
64
+ **2. Send a message anywhere in your app:**
65
+
66
+ ```python
67
+ from vercel.queue import send
68
+
69
+ message_id = await send("my-topic", {"message": "Hello world"})
70
+ ```
71
+
72
+ **3. Handle incoming messages with an API route function:**
73
+
74
+ ```python
75
+ # api/queue.py
76
+ from vercel.queue import asgi_app, subscribe
77
+
78
+
79
+ @subscribe(topic="my-topic", consumer_group="api/queue.py")
80
+ async def process_message(message):
81
+ print("Processing:", message)
82
+
83
+
84
+ # An ASGI app instance that converts incoming message callbacks
85
+ # sent by Vercel Queues and routes them to handlers.
86
+ app = asgi_app()
87
+ ```
88
+
89
+ **4. Configure `vercel.json`:**
90
+
91
+ ```json
92
+ {
93
+ "functions": {
94
+ "api/queue.py": {
95
+ "experimentalTriggers": [{ "type": "queue/v2beta", "topic": "my-topic" }]
96
+ }
97
+ }
98
+ }
99
+ ```
100
+
101
+ **5. Deploy:**
102
+
103
+ ```bash
104
+ vc deploy
105
+ ```
106
+
107
+ ## Publishing Messages
108
+
109
+ ```python
110
+ from datetime import timedelta
111
+ from vercel.queue import send
112
+
113
+ # Simple send
114
+ message_id = await send("my-topic", {"message": "Hello world"})
115
+
116
+ # With options
117
+ message_id = await send(
118
+ "my-topic",
119
+ {"message": "Hello world"},
120
+ idempotency_key="unique-key", # Prevent duplicate messages
121
+ retention=timedelta(hours=1),
122
+ delay=timedelta(minutes=1), # Delay delivery by 1 minute
123
+ )
124
+ ```
125
+
126
+ Example usage in a FastAPI route:
127
+
128
+ ```python
129
+ from fastapi import FastAPI
130
+
131
+ from vercel.queue import send
132
+
133
+ app = FastAPI()
134
+
135
+
136
+ @app.post("/orders")
137
+ async def create_order(order: dict[str, str]) -> dict[str, str | None]:
138
+ message_id = await send("my-topic", {"message": "Hello world"})
139
+ return {"message_id": message_id}
140
+ ```
141
+
142
+ `send` returns a message ID, or `None` when the server accepted the message for delivery,
143
+ but could not process it fully yet. Deferred messages are still delivered.
144
+
145
+ ## Receiving and Handling Messages
146
+
147
+ Decorated subscribers are the recommended way to handle messages. Register
148
+ subscribers with the `@subscribe` decorator:
149
+
150
+ ```python
151
+ # handle_orders.py
152
+ from vercel.queue import subscribe
153
+
154
+
155
+ @subscribe(topic="orders")
156
+ async def fulfill_order(order):
157
+ await process_order(order)
158
+ # Raising an error will automatically retry the message.
159
+ ```
160
+
161
+ Decorating a function with `@subscribe` only declares it as a handler for a
162
+ particular topic. You also need a way to accept and route messages to handlers.
163
+ There are two primary ways: deploying handlers as Vercel Functions in push mode
164
+ and running polling loops on other infrastructure.
165
+
166
+ ### Auto-scaled push-mode on Vercel
167
+
168
+ The recommended way of deploying queue subscribers is to deploy them as Vercel Functions
169
+
170
+ **Vercel Function (plain `/api` directory):**
171
+
172
+ ```python
173
+ # api/handle_orders.py
174
+ from vercel.queue import asgi_app, subscribe
175
+
176
+
177
+ @subscribe(topic="orders", consumer_group="api/handle_orders.py")
178
+ async def handle_order(message):
179
+ print("Processing:", message)
180
+
181
+
182
+ # An ASGI app instance that converts incoming message callbacks
183
+ # sent by Vercel Queues and routes them to handlers.
184
+ app = asgi_app()
185
+ ```
186
+
187
+ **vercel.json**:
188
+
189
+ ```json
190
+ {
191
+ "functions": {
192
+ "api/queue/orders.py": {
193
+ "experimentalTriggers": [
194
+ {
195
+ "type": "queue/v2beta",
196
+ "topic": "orders",
197
+ "retryAfterSeconds": 60,
198
+ "initialDelaySeconds": 0
199
+ }
200
+ ]
201
+ }
202
+ }
203
+ }
204
+ ```
205
+
206
+ ### Automatic Polling Loop
207
+
208
+ Queue message handlers can also be invoked by polling a topic manually. `vercel.queue` provides a
209
+ convenience API that starts an infinite polling loop for messages matching a given subscriber:
210
+
211
+ ```python
212
+ # subscriber_poll.py
213
+ import asyncio
214
+ from vercel.queue import poll_and_handle, subscribe
215
+
216
+
217
+ @subscribe(topic="orders")
218
+ async def fulfill_order(order):
219
+ print("Processing Order:", order)
220
+
221
+
222
+ async def main():
223
+ poller = asyncio.create_task(poll_and_handle(fulfill_order, interval=1))
224
+ # do work and cancel poller on a condition, such as a signal
225
+
226
+
227
+ asyncio.run(main())
228
+ ```
229
+
230
+ See [subscriber_poll.py example](./examples/subscriber_poll.py) for a complete
231
+ example.
232
+
233
+ Naturally, a synchronous polling loop helper is also available:
234
+
235
+ ```python
236
+ # subscriber_poll_sync.py
237
+ from vercel.queue.sync import poll_and_handle, subscribe
238
+
239
+
240
+ @subscribe(topic="orders")
241
+ def fulfill_order(order):
242
+ print("Processing Order:", order)
243
+
244
+
245
+ def main():
246
+ poller = poll_and_handle(fulfill_order, interval=1)
247
+ # ...
248
+ poller.cancel()
249
+
250
+
251
+ main()
252
+ ```
253
+
254
+ Synchronous polling loops use threads instead of async tasks.
255
+
256
+ ### Manual Polling
257
+
258
+ It is also possible to poll a topic and receive messages directly:
259
+
260
+ ```python
261
+ # poll_loop.py
262
+ from vercel.queue import poll
263
+
264
+
265
+ async def main():
266
+ async for delivery in poll(
267
+ topic="orders",
268
+ consumer_group="fulfillment",
269
+ limit=10,
270
+ ):
271
+ async with delivery as message:
272
+ await process_order(message.payload)
273
+ ```
274
+
275
+ `poll()` polls the topic once for up to `limit` message deliverires which are then yielded by the
276
+ iterator. Use the yielded `delivery` as a context manager to obtain the message envelope which
277
+ contains the `payload` and `metadata` properties. Note that `limit` means _up-to_ and it is
278
+ possible for `poll()` to return an empty iterator. In other words, `poll()` does not block until
279
+ new messages are available and it is usually necessary to build a polling loop around it.
280
+
281
+ ### Region Considerations when Polling
282
+
283
+ Messages can only be received from the region they were sent to. When polling, use a fixed region
284
+ for both sending and receiving, such as `"iad1"`. Avoid using a changing runtime region for manual
285
+ polling, because it can distribute messages across regions unpredictably.
286
+
287
+ ## Retry and Backoff
288
+
289
+ When a topic handler raises, the message is not acknowledged and becomes available for redelivery
290
+ after the `retryAfterSeconds` interval configured in `vercel.json`. Retries continue until the
291
+ handler succeeds or the message expires.
292
+
293
+ For finer control over retry timing, raise `RetryAfter` from a subscriber:
294
+
295
+ ```python
296
+ from vercel.queue import RetryAfter, subscribe
297
+
298
+
299
+ @subscribe(topic="orders")
300
+ async def fulfill_order(order: dict[str, str]) -> None:
301
+ try:
302
+ await process_order(order)
303
+ except RateLimitError as exc:
304
+ raise RetryAfter(60) from exc
305
+ ```
306
+
307
+ Use `message.metadata.delivery_count` for exponential backoff:
308
+
309
+ ```python
310
+ from vercel.queue import Message, RetryAfter, subscribe
311
+
312
+
313
+ @subscribe(topic="orders")
314
+ async def fulfill_order(message: Message[dict[str, str]]) -> None:
315
+ try:
316
+ await process_order(message.payload)
317
+ except TemporaryError as exc:
318
+ delay = min(300, 2**message.metadata.delivery_count * 5)
319
+ raise RetryAfter(delay) from exc
320
+ ```
321
+
322
+ ## Custom Client Configuration
323
+
324
+ For most use cases, the top-level `send`, `poll_and_handle`, and `poll` are all you need. For
325
+ advanced configuration such as explicit authentication, custom headers, deployment pinning, or
326
+ custom queue service URLs, create a `QueueClient` explicitly:
327
+
328
+ ```python
329
+ # explicit_client.py
330
+ from vercel.queue import ALL_DEPLOYMENTS, QueueClient
331
+
332
+ queue = QueueClient(
333
+ region="iad1", # Required unless VERCEL_REGION is set
334
+ token="my-token", # Auth token; detected from the environment by default
335
+ headers={"X-Custom": "header"},
336
+ deployment=ALL_DEPLOYMENTS, # Receive messages from all deployments when polling
337
+ timeout=10, # default timeout for API operations
338
+ http_client_factory=httpx2.AsyncClient, # any httpx-compatible HTTP client
339
+ )
340
+
341
+ await queue.send("my-topic", {"message": "Hello world"})
342
+ ```
343
+
344
+ By default queue clients send requests to `https://<region>.vercel-queue.com/`. A custom endpoint
345
+ can be configured by passing a `base_url` keyword argument to the client constructor. The value
346
+ can be a fixed string, a `format()` template containing a `{region}` placeholder, or a callable
347
+ taking region name as a string and returning a formatted URL:
348
+
349
+ ```python
350
+ from vercel.queue import QueueClient
351
+
352
+ # Custom domain with a base path.
353
+ queue = QueueClient(base_url="https://proxy.example/queues/{region}")
354
+
355
+ # Callable resolver.
356
+ queue = QueueClient(base_url=lambda region: f"https://{region}.queue.internal")
357
+ ```
358
+
359
+ ## Type-safe Message Passing and Streaming
360
+
361
+ By default, messages passed to `send()` and received by `@subscribe` handlers and `poll()` are
362
+ transmitted as JSON, so values must be JSON-serializable by Python. This is usually fine for
363
+ unstructured data, such as dictionaries and lists containing simple data. For more complex types,
364
+ such as `dataclasses` or Pydantic models, simply annotate the first argument of the handler
365
+ function:
366
+
367
+ ```python
368
+ from dataclasses import dataclass
369
+ from vercel.queue import send, subscribe
370
+
371
+
372
+ @dataclass
373
+ class Email:
374
+ to: str
375
+ subject: str
376
+ body: str
377
+
378
+
379
+ @subscribe(topic="emails")
380
+ async def receive_email(email: Email) -> None:
381
+ print(f"Received email to {email.to}: {email.subject}")
382
+ ```
383
+
384
+ Note that type-safe message handling requires `pydantic>=2.0` to be available. The simplest way
385
+ to ensure the correct version of Pydantic is to install the `vercel-queue` package with the
386
+ `[typed]` feature: `uv add vercel-queue[typed]`.
387
+
388
+ To send types that require non-trivial serialization, pass the topic name not as a plain string,
389
+ but as a type-specialized `Topic` instance:
390
+
391
+ ```python
392
+ # custom_transport.py
393
+ from vercel.queue import Topic, send
394
+
395
+
396
+ @dataclass
397
+ class Email:
398
+ to: str
399
+ subject: str
400
+ body: str
401
+
402
+
403
+ emails_topic = Topic[Email]("emails")
404
+
405
+
406
+ async def send_email(to, subject, body):
407
+ await send(emails_topic, Email(to, subject, body))
408
+
409
+
410
+ # Type-specialized topics can also be used with @subscribe, in which case the
411
+ # type annotation on the handler argument must match the type of the topic
412
+ @subscribe(topic=emails_topic)
413
+ async def receive_email(email: Email) -> None:
414
+ print(f"Received email to {email.to}: {email.subject}")
415
+ ```
416
+
417
+ Explicit type annotations can also be used to enable payload streaming for large messages:
418
+
419
+ ```python
420
+ # streaming.py
421
+ from collections.abc import AsyncIterable, AsyncIterator
422
+
423
+ from vercel.queue import ByteStreamTransport, QueueClient, Topic, subscribe
424
+
425
+ large_file = Topic[AsyncIterable[bytes]]("large-file")
426
+
427
+
428
+ async def file_chunks():
429
+ with open("large.bin", "rb") as file:
430
+ while chunk := file.read(1024 * 1024):
431
+ yield chunk
432
+
433
+
434
+ async def send_file():
435
+ await queue.send(large_file, file_chunks())
436
+
437
+
438
+ @subscribe(topic=large_file, consumer_group="archive")
439
+ async def archive_file(chunks: AsyncIterable[bytes]) -> None:
440
+ async for chunk in chunks:
441
+ await write_chunk(chunk)
442
+ ```
443
+
444
+ Message transport is automatically determined from the handler argument type annotation
445
+ or `Topic` type specialization according to the following table:
446
+
447
+ | Topic payload type | Default transport | Message format |
448
+ | ------------------------------------------------ | ----------------------- | ---------------------------- |
449
+ | JSON-compatible values, `dict[...]`, `list[...]` | `RawJsonTransport[Any]` | JSON |
450
+ | Pydantic models and other structured annotations | `TypedJsonTransport[T]` | JSON with receive validation |
451
+ | `bytes` | `ByteBufferTransport` | Buffered binary |
452
+ | `str` | `TextBufferTransport` | Buffered UTF-8 text |
453
+ | `Iterable[bytes]` or `AsyncIterable[bytes]` | `ByteStreamTransport` | Streaming binary |
454
+ | `Iterable[str]` or `AsyncIterable[str]` | `TextStreamTransport` | Streaming UTF-8 text |
455
+
456
+ Transport can also be set explicitly on the topic when the topic is unstructured or
457
+ when custom serialization is needed:
458
+
459
+ ```python
460
+ # custom_transport.py
461
+
462
+
463
+ @dataclass
464
+ class Invoice:
465
+ invoice_id: str
466
+ customer_id: str
467
+ total_cents: int
468
+
469
+
470
+ class InvoiceFormTransport:
471
+ content_type = "application/x-www-form-urlencoded"
472
+
473
+ def serialize(self, value: Invoice) -> bytes:
474
+ return urlencode({
475
+ "invoice_id": value.invoice_id,
476
+ "customer_id": value.customer_id,
477
+ "total_cents": str(value.total_cents),
478
+ }).encode("utf-8")
479
+
480
+ async def deserialize(
481
+ self,
482
+ payload: AsyncIterator[bytes],
483
+ *,
484
+ content_type: str,
485
+ ) -> Invoice:
486
+ body = bytearray()
487
+ async for chunk in payload:
488
+ body.extend(chunk)
489
+
490
+ parsed = parse_qs(body.decode("utf-8"), strict_parsing=True)
491
+ return Invoice(
492
+ invoice_id=_single(parsed, "invoice_id"),
493
+ customer_id=_single(parsed, "customer_id"),
494
+ total_cents=int(_single(parsed, "total_cents")),
495
+ )
496
+
497
+
498
+ invoice_topic = Topic[Invoice](
499
+ "invoices",
500
+ transport=InvoiceFormTransport(),
501
+ )
502
+
503
+
504
+ @subscribe(topic=invoice_topic)
505
+ async def handle_invoice(invoice: Invoice) -> None: ...
506
+ ```
507
+
508
+ ## Error Handling
509
+
510
+ ```python
511
+ from vercel.queue import (
512
+ BadRequestError,
513
+ DuplicateIdempotencyKeyError,
514
+ ForbiddenError,
515
+ InternalServerError,
516
+ UnauthorizedError,
517
+ send,
518
+ )
519
+
520
+ try:
521
+ await send("my-topic", payload)
522
+ except UnauthorizedError:
523
+ print("Invalid token - refresh authentication")
524
+ except ForbiddenError:
525
+ print("Environment mismatch - check configuration")
526
+ except BadRequestError as exc:
527
+ print("Invalid parameters:", exc)
528
+ except DuplicateIdempotencyKeyError as exc:
529
+ print("Duplicate idempotency key:", exc)
530
+ except InternalServerError:
531
+ print("Server error - retry with backoff")
532
+ ```
533
+
534
+ All error types:
535
+
536
+ | Error | Description |
537
+ | ------------------------------------ | --------------------------------------------- |
538
+ | `BadRequestError` | Invalid request parameters |
539
+ | `UnauthorizedError` | Authentication failed |
540
+ | `ForbiddenError` | Access denied or environment mismatch |
541
+ | `DuplicateIdempotencyKeyError` | Idempotency key already used |
542
+ | `ConsumerDiscoveryError` | Could not reach consumer deployment |
543
+ | `ConsumerRegistryNotConfiguredError` | Project is not configured for queues |
544
+ | `DeploymentResolutionError` | Deployment ID could not be resolved |
545
+ | `DuplicateSubscriptionError` | Local subscriber registration overlaps |
546
+ | `InternalServerError` | Unexpected server error |
547
+ | `InvalidLimitError` | Batch limit outside valid range |
548
+ | `MessageAlreadyProcessedError` | Message already successfully processed |
549
+ | `MessageCorruptedError` | Message data could not be parsed |
550
+ | `MessageLockedError` | Message is being processed elsewhere |
551
+ | `MessageNotFoundError` | Message does not exist or expired |
552
+ | `MessageUnavailableError` | Message exists but cannot be claimed |
553
+ | `PayloadValidationError` | Payload validation failed |
554
+ | `ProtocolError` | Queue service returned malformed metadata |
555
+ | `ServiceError` | Unexpected queue response |
556
+ | `SubscriptionError` | Subscriber signature or configuration invalid |
557
+ | `ThrottledError` | Queue service throttled the request |
558
+ | `TokenResolutionError` | OIDC token could not be resolved |
559
+ | `UnhandledMessageError` | No subscriber matched an incoming delivery |
560
+
561
+ ## Environment Variables
562
+
563
+ | Variable | Description | Default |
564
+ | ----------------------- | ---------------------------------------------- | ------- |
565
+ | `VERCEL_REGION` | Current region, auto-set by Vercel | - |
566
+ | `VERCEL_QUEUE_BASE_URL` | Fixed base URL or `{region}` template override | - |
567
+ | `VERCEL_QUEUE_DEBUG` | Enable debug logging with `1` or `true` | - |
568
+ | `VERCEL_QUEUE_TOKEN` | Queue bearer token override | - |
569
+ | `VERCEL_DEPLOYMENT_ID` | Deployment ID, auto-set by Vercel | - |
570
+
571
+ ## Service Limits & Constraints
572
+
573
+ ### Throughput & Storage
574
+
575
+ | Limit | Value | Notes |
576
+ | --------------------------- | --------------------- | ----------------------------------- |
577
+ | Message throughput | 10,000+ msg/sec/topic | Scales horizontally |
578
+ | Payload size | 100 MB | Smaller messages have lower latency |
579
+ | Number of topics | Unlimited | No hard limit |
580
+ | Consumer groups per message | ~4,000 | Per-message limit |
581
+ | Messages per queue | Unlimited | No hard limit |
582
+
583
+ ### Parameter Constraints
584
+
585
+ #### Publishing Messages
586
+
587
+ | Parameter | Default | Min | Max | Notes |
588
+ | ----------------- | ------------ | --- | ------------ | ----------------------------------- |
589
+ | `retention` | 86,400 (24h) | 60 | 604,800 (7d) | Message TTL |
590
+ | `delay` | 0 | 0 | 604,800 (7d) | Cannot exceed retention |
591
+ | `idempotency_key` | - | - | - | Dedup window: `min(retention, 24h)` |
592
+
593
+ #### Receiving Messages
594
+
595
+ | Parameter | Default | Min | Max | Notes |
596
+ | ---------------- | ------- | --- | ----- | ------------------------------- |
597
+ | `lease_duration` | 300 | 30 | 3,600 | Lock duration during processing |
598
+ | `limit` | 1 | 1 | 10 | Messages per request |
599
+
600
+ ### Identifier Formats
601
+
602
+ | Identifier | Input | Stored queue name |
603
+ | -------------- | -------------------- | ---------------------------- |
604
+ | Topic name | `[A-Za-z0-9_-]+` | Same as input |
605
+ | Consumer group | Any non-empty string | `sanitize_name(...)` |
606
+ | Message ID | Opaque string | `0-1`, `3-7K9mNpQrS` |
607
+ | Receipt handle | Opaque string | Used for ack and lease calls |
608
+
609
+ Use `sanitize_name` to convert arbitrary non-empty names to `SanitizedName`
610
+ markers. Plain strings are reversibly escaped, including underscores. Use
611
+ `SanitizedName` only when passing a queue-safe name that has already been
612
+ sanitized and must not be escaped again.
613
+
614
+ ## Wildcard Topics
615
+
616
+ It is possible to subscribe to multiple topics by using a wildcard (`*`) at the
617
+ end of the topic name. Bare wildcards are also allowed and act as catch-all
618
+ handlers.
619
+
620
+ ```python
621
+ # wildcard_topic.py
622
+
623
+ from vercel.queue import subscribe
624
+
625
+
626
+ @subscribe(topic="user-*")
627
+ async def handle_user_event(event: dict[str, str]) -> None:
628
+ await process_user_event(event)
629
+ ```
630
+
631
+ Wildcard topics are not supported by `poll()` and if a wildcard handler is passed to
632
+ `poll_and_handle()`, a non-wildcard list of topics must also be specified to disambiguate
633
+ polling.
634
+
635
+ ## Local Development
636
+
637
+ For local tests and integration development, use the embedded queue service or
638
+ pytest plugin. It exercises the same client send, subscriber callback, lease renewal,
639
+ and acknowledgement paths without requiring a deployed Vercel Function.
640
+
641
+ ```python
642
+ import anyio
643
+
644
+ from vercel.queue import subscribe
645
+ from vercel.queue.embedded import embedded_queue_service
646
+
647
+
648
+ async def wait_until(predicate) -> None:
649
+ while not predicate():
650
+ await anyio.sleep(0.01)
651
+
652
+
653
+ async def test_queue() -> None:
654
+ seen: list[str] = []
655
+
656
+ @subscribe(topic="my-topic")
657
+ async def handler(message: dict[str, str]) -> None:
658
+ seen.append(message["message"])
659
+
660
+ async with embedded_queue_service() as service:
661
+ client = service.get_async_client()
662
+ message_id = await client.send("my-topic", {"message": "Hello world"})
663
+ assert message_id is not None
664
+ service.dispatcher.wake()
665
+ await wait_until(lambda: service.server.state.by_id[message_id].acknowledged)
666
+
667
+ assert seen == ["Hello world"]
668
+ ```
669
+
670
+ Standalone HTTP dev server support is available through the `devserver` extra:
671
+
672
+ ```bash
673
+ python -m vercel.queue.devserver --host 127.0.0.1
674
+ ```
675
+
676
+ Install it with `vercel-queue[devserver]`. The command prints a JSON `baseUrl`
677
+ for the local queue API, including the random available port selected when
678
+ `--port` is omitted. Pass `--port 8000` to bind a fixed port. This is useful for
679
+ cross-process or cross-runtime local integration.
680
+
681
+ ## License
682
+
683
+ MIT