-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmessage.py
More file actions
608 lines (540 loc) · 24.9 KB
/
message.py
File metadata and controls
608 lines (540 loc) · 24.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
import json
from typing import Any, Dict, List, Optional, Union
from qstash.asyncio.http import AsyncHttpClient
from qstash.http import HttpMethod
from qstash.message import (
ApiT,
FlowControl,
BatchJsonRequest,
BatchRequest,
BatchResponse,
BatchUrlGroupResponse,
EnqueueResponse,
EnqueueUrlGroupResponse,
Message,
PublishResponse,
PublishUrlGroupResponse,
convert_to_batch_messages,
get_destination,
parse_batch_response,
parse_enqueue_response,
parse_message_response,
parse_publish_response,
prepare_batch_message_body,
prepare_headers,
)
class AsyncMessageApi:
def __init__(self, http: AsyncHttpClient):
self._http = http
async def publish(
self,
*,
url: Optional[str] = None,
url_group: Optional[str] = None,
api: Optional[ApiT] = None,
body: Optional[Union[str, bytes]] = None,
content_type: Optional[str] = None,
method: Optional[HttpMethod] = None,
headers: Optional[Dict[str, str]] = None,
callback_headers: Optional[Dict[str, str]] = None,
failure_callback_headers: Optional[Dict[str, str]] = None,
retries: Optional[int] = None,
retry_delay: Optional[str] = None,
callback: Optional[str] = None,
failure_callback: Optional[str] = None,
delay: Optional[Union[str, int]] = None,
not_before: Optional[int] = None,
deduplication_id: Optional[str] = None,
content_based_deduplication: Optional[bool] = None,
timeout: Optional[Union[str, int]] = None,
flow_control: Optional[FlowControl] = None,
) -> Union[PublishResponse, List[PublishUrlGroupResponse]]:
"""
Publishes a message to QStash.
If the destination is a `url` or an `api`, `PublishResponse`
is returned.
If the destination is a `url_group`, then a list of
`PublishUrlGroupResponse`s are returned, one for each url
in the url group.
:param url: Url to send the message to.
:param url_group: Url group to send the message to.
:param api: Api to send the message to.
:param body: The raw request message body passed to the destination as is.
:param content_type: MIME type of the message.
:param method: The HTTP method to use when sending a webhook to your API.
:param headers: Headers to forward along with the message.
:param callback_headers: Headers to forward along with the callback message.
:param failure_callback_headers: Headers to forward along with the failure
callback message.
:param retries: How often should this message be retried in case the destination
API is not available.
:param retry_delay: Delay between retries.
By default, the `retryDelay` is exponential backoff.
More details can be found in: https://upstash.com/docs/qstash/features/retry.
The `retryDelay` option allows you to customize the delay (in milliseconds) between retry attempts when message delivery fails.
You can use mathematical expressions and the following built-in functions to calculate the delay dynamically.
The special variable `retried` represents the current retry attempt count (starting from 0).
Supported functions:
- `pow`
- `sqrt`
- `abs`
- `exp`
- `floor`
- `ceil`
- `round`
- `min`
- `max`
Examples of valid `retryDelay` values:
```py
1000 # 1 second
1000 * (1 + retried) # 1 second multiplied by the current retry attempt
pow(2, retried) # 2 to the power of the current retry attempt
max(10, pow(2, retried)) # The greater of 10 or 2^retried
```
:param callback: A callback url that will be called after each attempt.
:param failure_callback: A failure callback url that will be called when a delivery
is failed, that is when all the defined retries are exhausted.
:param delay: Delay the message delivery. The format for the delay string is a
number followed by duration abbreviation, like `10s`. Available durations
are `s` (seconds), `m` (minutes), `h` (hours), and `d` (days). As convenience,
it is also possible to specify the delay as an integer, which will be
interpreted as delay in seconds.
:param not_before: Delay the message until a certain time in the future.
The format is a unix timestamp in seconds, based on the UTC timezone.
:param deduplication_id: Id to use while deduplicating messages.
:param content_based_deduplication: Automatically deduplicate messages based on
their content.
:param timeout: The HTTP timeout value to use while calling the destination URL.
When a timeout is specified, it will be used instead of the maximum timeout
value permitted by the QStash plan. It is useful in scenarios, where a message
should be delivered with a shorter timeout.
:param flow_control: Settings for controlling the number of active requests,
as well as the rate of requests with the same flow control key.
"""
headers = headers or {}
destination = get_destination(
url=url,
url_group=url_group,
api=api,
headers=headers,
)
req_headers = prepare_headers(
content_type=content_type,
method=method,
headers=headers,
callback_headers=callback_headers,
failure_callback_headers=failure_callback_headers,
retries=retries,
retry_delay=retry_delay,
callback=callback,
failure_callback=failure_callback,
delay=delay,
not_before=not_before,
deduplication_id=deduplication_id,
content_based_deduplication=content_based_deduplication,
timeout=timeout,
flow_control=flow_control,
)
response = await self._http.request(
path=f"/v2/publish/{destination}",
method="POST",
headers=req_headers,
body=body,
)
return parse_publish_response(response)
async def publish_json(
self,
*,
url: Optional[str] = None,
url_group: Optional[str] = None,
api: Optional[ApiT] = None,
body: Optional[Any] = None,
method: Optional[HttpMethod] = None,
headers: Optional[Dict[str, str]] = None,
callback_headers: Optional[Dict[str, str]] = None,
failure_callback_headers: Optional[Dict[str, str]] = None,
retries: Optional[int] = None,
retry_delay: Optional[str] = None,
callback: Optional[str] = None,
failure_callback: Optional[str] = None,
delay: Optional[Union[str, int]] = None,
not_before: Optional[int] = None,
deduplication_id: Optional[str] = None,
content_based_deduplication: Optional[bool] = None,
timeout: Optional[Union[str, int]] = None,
flow_control: Optional[FlowControl] = None,
) -> Union[PublishResponse, List[PublishUrlGroupResponse]]:
"""
Publish a message to QStash, automatically serializing the
body as JSON string, and setting content type to `application/json`.
If the destination is a `url` or an `api`, `PublishResponse`
is returned.
If the destination is a `url_group`, then a list of
`PublishUrlGroupResponse`s are returned, one for each url
in the url group.
:param url: Url to send the message to.
:param url_group: Url group to send the message to.
:param api: Api to send the message to.
:param body: The request message body passed to the destination after being
serialized as JSON string.
:param method: The HTTP method to use when sending a webhook to your API.
:param headers: Headers to forward along with the message.
:param callback_headers: Headers to forward along with the callback message.
:param failure_callback_headers: Headers to forward along with the failure
callback message.
:param retries: How often should this message be retried in case the destination
API is not available.
:param retry_delay: Delay between retries.
By default, the `retryDelay` is exponential backoff.
More details can be found in: https://upstash.com/docs/qstash/features/retry.
The `retryDelay` option allows you to customize the delay (in milliseconds) between retry attempts when message delivery fails.
You can use mathematical expressions and the following built-in functions to calculate the delay dynamically.
The special variable `retried` represents the current retry attempt count (starting from 0).
Supported functions:
- `pow`
- `sqrt`
- `abs`
- `exp`
- `floor`
- `ceil`
- `round`
- `min`
- `max`
Examples of valid `retryDelay` values:
```py
1000 # 1 second
1000 * (1 + retried) # 1 second multiplied by the current retry attempt
pow(2, retried) # 2 to the power of the current retry attempt
max(10, pow(2, retried)) # The greater of 10 or 2^retried
```
:param callback: A callback url that will be called after each attempt.
:param failure_callback: A failure callback url that will be called when a delivery
is failed, that is when all the defined retries are exhausted.
:param delay: Delay the message delivery. The format for the delay string is a
number followed by duration abbreviation, like `10s`. Available durations
are `s` (seconds), `m` (minutes), `h` (hours), and `d` (days). As convenience,
it is also possible to specify the delay as an integer, which will be
interpreted as delay in seconds.
:param not_before: Delay the message until a certain time in the future.
The format is a unix timestamp in seconds, based on the UTC timezone.
:param deduplication_id: Id to use while deduplicating messages.
:param content_based_deduplication: Automatically deduplicate messages based on
their content.
:param timeout: The HTTP timeout value to use while calling the destination URL.
When a timeout is specified, it will be used instead of the maximum timeout
value permitted by the QStash plan. It is useful in scenarios, where a message
should be delivered with a shorter timeout.
:param flow_control: Settings for controlling the number of active requests,
as well as the rate of requests with the same flow control key.
"""
return await self.publish(
url=url,
url_group=url_group,
api=api,
body=json.dumps(body),
content_type="application/json",
method=method,
headers=headers,
callback_headers=callback_headers,
failure_callback_headers=failure_callback_headers,
retries=retries,
retry_delay=retry_delay,
callback=callback,
failure_callback=failure_callback,
delay=delay,
not_before=not_before,
deduplication_id=deduplication_id,
content_based_deduplication=content_based_deduplication,
timeout=timeout,
flow_control=flow_control,
)
async def enqueue(
self,
*,
queue: str,
url: Optional[str] = None,
url_group: Optional[str] = None,
api: Optional[ApiT] = None,
body: Optional[Union[str, bytes]] = None,
content_type: Optional[str] = None,
method: Optional[HttpMethod] = None,
headers: Optional[Dict[str, str]] = None,
callback_headers: Optional[Dict[str, str]] = None,
failure_callback_headers: Optional[Dict[str, str]] = None,
retries: Optional[int] = None,
retry_delay: Optional[str] = None,
callback: Optional[str] = None,
failure_callback: Optional[str] = None,
deduplication_id: Optional[str] = None,
content_based_deduplication: Optional[bool] = None,
timeout: Optional[Union[str, int]] = None,
) -> Union[EnqueueResponse, List[EnqueueUrlGroupResponse]]:
"""
Enqueues a message, after creating the queue if it does
not exist.
If the destination is a `url` or an `api`, `EnqueueResponse`
is returned.
If the destination is a `url_group`, then a list of
`EnqueueUrlGroupResponse`s are returned, one for each url
in the url group.
:param queue: The name of the queue.
:param url: Url to send the message to.
:param url_group: Url group to send the message to.
:param api: Api to send the message to.
:param body: The raw request message body passed to the destination as is.
:param content_type: MIME type of the message.
:param method: The HTTP method to use when sending a webhook to your API.
:param headers: Headers to forward along with the message.
:param callback_headers: Headers to forward along with the callback message.
:param failure_callback_headers: Headers to forward along with the failure
callback message.
:param retries: How often should this message be retried in case the destination
API is not available.
:param retry_delay: Delay between retries.
By default, the `retryDelay` is exponential backoff.
More details can be found in: https://upstash.com/docs/qstash/features/retry.
The `retryDelay` option allows you to customize the delay (in milliseconds) between retry attempts when message delivery fails.
You can use mathematical expressions and the following built-in functions to calculate the delay dynamically.
The special variable `retried` represents the current retry attempt count (starting from 0).
Supported functions:
- `pow`
- `sqrt`
- `abs`
- `exp`
- `floor`
- `ceil`
- `round`
- `min`
- `max`
Examples of valid `retryDelay` values:
```py
1000 # 1 second
1000 * (1 + retried) # 1 second multiplied by the current retry attempt
pow(2, retried) # 2 to the power of the current retry attempt
max(10, pow(2, retried)) # The greater of 10 or 2^retried
```
:param callback: A callback url that will be called after each attempt.
:param failure_callback: A failure callback url that will be called when a delivery
is failed, that is when all the defined retries are exhausted.
:param deduplication_id: Id to use while deduplicating messages.
:param content_based_deduplication: Automatically deduplicate messages based on
their content.
:param timeout: The HTTP timeout value to use while calling the destination URL.
When a timeout is specified, it will be used instead of the maximum timeout
value permitted by the QStash plan. It is useful in scenarios, where a message
should be delivered with a shorter timeout.
"""
headers = headers or {}
destination = get_destination(
url=url,
url_group=url_group,
api=api,
headers=headers,
)
req_headers = prepare_headers(
content_type=content_type,
method=method,
headers=headers,
callback_headers=callback_headers,
failure_callback_headers=failure_callback_headers,
retries=retries,
retry_delay=retry_delay,
callback=callback,
failure_callback=failure_callback,
delay=None,
not_before=None,
deduplication_id=deduplication_id,
content_based_deduplication=content_based_deduplication,
timeout=timeout,
flow_control=None,
)
response = await self._http.request(
path=f"/v2/enqueue/{queue}/{destination}",
method="POST",
headers=req_headers,
body=body,
)
return parse_enqueue_response(response)
async def enqueue_json(
self,
*,
queue: str,
url: Optional[str] = None,
url_group: Optional[str] = None,
api: Optional[ApiT] = None,
body: Optional[Any] = None,
method: Optional[HttpMethod] = None,
headers: Optional[Dict[str, str]] = None,
callback_headers: Optional[Dict[str, str]] = None,
failure_callback_headers: Optional[Dict[str, str]] = None,
retries: Optional[int] = None,
retry_delay: Optional[str] = None,
callback: Optional[str] = None,
failure_callback: Optional[str] = None,
deduplication_id: Optional[str] = None,
content_based_deduplication: Optional[bool] = None,
timeout: Optional[Union[str, int]] = None,
) -> Union[EnqueueResponse, List[EnqueueUrlGroupResponse]]:
"""
Enqueues a message, after creating the queue if it does
not exist. It automatically serializes the body as JSON string,
and setting content type to `application/json`.
If the destination is a `url` or an `api`, `EnqueueResponse`
is returned.
If the destination is a `url_group`, then a list of
`EnqueueUrlGroupResponse`s are returned, one for each url
in the url group.
:param queue: The name of the queue.
:param url: Url to send the message to.
:param url_group: Url group to send the message to.
:param api: Api to send the message to.
:param body: The request message body passed to the destination after being
serialized as JSON string.
:param method: The HTTP method to use when sending a webhook to your API.
:param headers: Headers to forward along with the message.
:param callback_headers: Headers to forward along with the callback message.
:param failure_callback_headers: Headers to forward along with the failure
callback message.
:param retries: How often should this message be retried in case the destination
API is not available.
:param retry_delay: Delay between retries.
By default, the `retryDelay` is exponential backoff.
More details can be found in: https://upstash.com/docs/qstash/features/retry.
The `retryDelay` option allows you to customize the delay (in milliseconds) between retry attempts when message delivery fails.
You can use mathematical expressions and the following built-in functions to calculate the delay dynamically.
The special variable `retried` represents the current retry attempt count (starting from 0).
Supported functions:
- `pow`
- `sqrt`
- `abs`
- `exp`
- `floor`
- `ceil`
- `round`
- `min`
- `max`
Examples of valid `retryDelay` values:
```py
1000 # 1 second
1000 * (1 + retried) # 1 second multiplied by the current retry attempt
pow(2, retried) # 2 to the power of the current retry attempt
max(10, pow(2, retried)) # The greater of 10 or 2^retried
```
:param callback: A callback url that will be called after each attempt.
:param failure_callback: A failure callback url that will be called when a delivery
is failed, that is when all the defined retries are exhausted.
:param deduplication_id: Id to use while deduplicating messages.
:param content_based_deduplication: Automatically deduplicate messages based on
their content.
:param timeout: The HTTP timeout value to use while calling the destination URL.
When a timeout is specified, it will be used instead of the maximum timeout
value permitted by the QStash plan. It is useful in scenarios, where a message
should be delivered with a shorter timeout.
"""
return await self.enqueue(
queue=queue,
url=url,
url_group=url_group,
api=api,
body=json.dumps(body),
content_type="application/json",
method=method,
headers=headers,
callback_headers=callback_headers,
failure_callback_headers=failure_callback_headers,
retries=retries,
retry_delay=retry_delay,
callback=callback,
failure_callback=failure_callback,
deduplication_id=deduplication_id,
content_based_deduplication=content_based_deduplication,
timeout=timeout,
)
async def batch(
self, messages: List[BatchRequest]
) -> List[Union[BatchResponse, List[BatchUrlGroupResponse]]]:
"""
Publishes or enqueues multiple messages in a single request.
Returns a list of publish or enqueue responses, one for each
message in the batch.
If the message in the batch is sent to a url or an API,
the corresponding item in the response is `BatchResponse`.
If the message in the batch is sent to a url group,
the corresponding item in the response is list of
`BatchUrlGroupResponse`s, one for each url in the url group.
"""
body = prepare_batch_message_body(messages)
response = await self._http.request(
path="/v2/batch",
body=body,
headers={"Content-Type": "application/json"},
method="POST",
)
return parse_batch_response(response)
async def batch_json(
self, messages: List[BatchJsonRequest]
) -> List[Union[BatchResponse, List[BatchUrlGroupResponse]]]:
"""
Publishes or enqueues multiple messages in a single request,
automatically serializing the message bodies as JSON strings,
and setting content type to `application/json`.
Returns a list of publish or enqueue responses, one for each
message in the batch.
If the message in the batch is sent to a url or an API,
the corresponding item in the response is `BatchResponse`.
If the message in the batch is sent to a url group,
the corresponding item in the response is list of
`BatchUrlGroupResponse`s, one for each url in the url group.
"""
batch_messages = convert_to_batch_messages(messages)
return await self.batch(batch_messages)
async def get(self, message_id: str) -> Message:
"""
Gets the message by its id.
"""
response = await self._http.request(
path=f"/v2/messages/{message_id}",
method="GET",
)
return parse_message_response(response)
async def cancel(self, message_id: str) -> None:
"""
Cancels delivery of an existing message.
Cancelling a message will remove it from QStash and stop it from being
delivered in the future. If a message is in flight to your API,
it might be too late to cancel.
"""
await self._http.request(
path=f"/v2/messages/{message_id}",
method="DELETE",
parse_response=False,
)
async def cancel_many(self, message_ids: List[str]) -> int:
"""
Cancels delivery of existing messages.
Cancelling a message will remove it from QStash and stop it from being
delivered in the future. If a message is in flight to your API,
it might be too late to cancel.
Returns how many of the messages are cancelled.
"""
body = json.dumps({"messageIds": message_ids})
response = await self._http.request(
path="/v2/messages",
method="DELETE",
headers={"Content-Type": "application/json"},
body=body,
)
return response["cancelled"] # type:ignore[no-any-return]
async def cancel_all(self) -> int:
"""
Cancels delivery of all the existing messages.
Cancelling a message will remove it from QStash and stop it from being
delivered in the future. If a message is in flight to your API,
it might be too late to cancel.
Returns how many messages are cancelled.
"""
response = await self._http.request(
path="/v2/messages",
method="DELETE",
)
return response["cancelled"] # type:ignore[no-any-return]