-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathrequest_queue.py
More file actions
846 lines (653 loc) · 29.7 KB
/
request_queue.py
File metadata and controls
846 lines (653 loc) · 29.7 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
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
from __future__ import annotations
import asyncio
import logging
import math
from dataclasses import dataclass
from datetime import timedelta
from queue import Queue
from time import sleep
from typing import TYPE_CHECKING, Any, TypedDict
from apify_shared.utils import filter_out_none_values_recursively, ignore_docs, parse_date_fields
from more_itertools import constrained_batches
from apify_client._errors import ApifyApiError
from apify_client._utils import catch_not_found_or_throw, pluck_data
from apify_client.clients.base import ResourceClient, ResourceClientAsync
if TYPE_CHECKING:
from collections.abc import Iterable
from apify_shared.consts import StorageGeneralAccess
logger = logging.getLogger(__name__)
_RQ_MAX_REQUESTS_PER_BATCH = 25
_MAX_PAYLOAD_SIZE_BYTES = 9 * 1024 * 1024 # 9 MB
_SAFETY_BUFFER_PERCENT = 0.01 / 100 # 0.01%
_SMALL_TIMEOUT = 5 # For fast and common actions. Suitable for idempotent actions.
_MEDIUM_TIMEOUT = 30 # For actions that may take longer.
class BatchAddRequestsResult(TypedDict):
"""Result of the batch add requests operation.
Args:
processedRequests: List of successfully added requests.
unprocessedRequests: List of requests that failed to be added.
"""
processedRequests: list[dict]
unprocessedRequests: list[dict]
@dataclass
class AddRequestsBatch:
"""Batch of requests to add to the request queue.
Args:
requests: List of requests to be added to the request queue.
num_of_retries: Number of times this batch has been retried.
"""
requests: Iterable[dict]
num_of_retries: int = 0
class RequestQueueClient(ResourceClient):
"""Sub-client for manipulating a single request queue."""
@ignore_docs
def __init__( # noqa: D417
self,
*args: Any,
client_key: str | None = None,
**kwargs: Any,
) -> None:
"""Initialize a new instance.
Args:
client_key: A unique identifier of the client accessing the request queue.
"""
resource_path = kwargs.pop('resource_path', 'request-queues')
super().__init__(*args, resource_path=resource_path, **kwargs)
self.client_key = client_key
def get(self) -> dict | None:
"""Retrieve the request queue.
https://docs.apify.com/api/v2#/reference/request-queues/queue/get-request-queue
Returns:
The retrieved request queue, or None, if it does not exist.
"""
return self._get(timeout_secs=_SMALL_TIMEOUT)
def update(self, *, name: str | None = None, general_access: StorageGeneralAccess | None = None) -> dict:
"""Update the request queue with specified fields.
https://docs.apify.com/api/v2#/reference/request-queues/queue/update-request-queue
Args:
name: The new name for the request queue.
general_access: Determines how others can access the request queue.
Returns:
The updated request queue.
"""
updated_fields = {
'name': name,
'generalAccess': general_access,
}
return self._update(filter_out_none_values_recursively(updated_fields), timeout_secs=_SMALL_TIMEOUT)
def delete(self) -> None:
"""Delete the request queue.
https://docs.apify.com/api/v2#/reference/request-queues/queue/delete-request-queue
"""
return self._delete(timeout_secs=_SMALL_TIMEOUT)
def list_head(self, *, limit: int | None = None) -> dict:
"""Retrieve a given number of requests from the beginning of the queue.
https://docs.apify.com/api/v2#/reference/request-queues/queue-head/get-head
Args:
limit: How many requests to retrieve.
Returns:
The desired number of requests from the beginning of the queue.
"""
request_params = self._params(limit=limit, clientKey=self.client_key)
response = self.http_client.call(
url=self._url('head'),
method='GET',
params=request_params,
timeout_secs=_SMALL_TIMEOUT,
)
return parse_date_fields(pluck_data(response.json()))
def list_and_lock_head(self, *, lock_secs: int, limit: int | None = None) -> dict:
"""Retrieve a given number of unlocked requests from the beginning of the queue and lock them for a given time.
https://docs.apify.com/api/v2#/reference/request-queues/queue-head-with-locks/get-head-and-lock
Args:
lock_secs: How long the requests will be locked for, in seconds.
limit: How many requests to retrieve.
Returns:
The desired number of locked requests from the beginning of the queue.
"""
request_params = self._params(lockSecs=lock_secs, limit=limit, clientKey=self.client_key)
response = self.http_client.call(
url=self._url('head/lock'),
method='POST',
params=request_params,
timeout_secs=_MEDIUM_TIMEOUT,
)
return parse_date_fields(pluck_data(response.json()))
def add_request(self, request: dict, *, forefront: bool | None = None) -> dict:
"""Add a request to the queue.
https://docs.apify.com/api/v2#/reference/request-queues/request-collection/add-request
Args:
request: The request to add to the queue.
forefront: Whether to add the request to the head or the end of the queue.
Returns:
The added request.
"""
request_params = self._params(forefront=forefront, clientKey=self.client_key)
response = self.http_client.call(
url=self._url('requests'),
method='POST',
json=request,
params=request_params,
timeout_secs=_SMALL_TIMEOUT,
)
return parse_date_fields(pluck_data(response.json()))
def get_request(self, request_id: str) -> dict | None:
"""Retrieve a request from the queue.
https://docs.apify.com/api/v2#/reference/request-queues/request/get-request
Args:
request_id: ID of the request to retrieve.
Returns:
The retrieved request, or None, if it did not exist.
"""
try:
response = self.http_client.call(
url=self._url(f'requests/{request_id}'),
method='GET',
params=self._params(),
timeout_secs=_SMALL_TIMEOUT,
)
return parse_date_fields(pluck_data(response.json()))
except ApifyApiError as exc:
catch_not_found_or_throw(exc)
return None
def update_request(self, request: dict, *, forefront: bool | None = None) -> dict:
"""Update a request in the queue.
https://docs.apify.com/api/v2#/reference/request-queues/request/update-request
Args:
request: The updated request.
forefront: Whether to put the updated request in the beginning or the end of the queue.
Returns:
The updated request.
"""
request_id = request['id']
request_params = self._params(forefront=forefront, clientKey=self.client_key)
response = self.http_client.call(
url=self._url(f'requests/{request_id}'),
method='PUT',
json=request,
params=request_params,
timeout_secs=_MEDIUM_TIMEOUT,
)
return parse_date_fields(pluck_data(response.json()))
def delete_request(self, request_id: str) -> None:
"""Delete a request from the queue.
https://docs.apify.com/api/v2#/reference/request-queues/request/delete-request
Args:
request_id: ID of the request to delete.
"""
request_params = self._params(
clientKey=self.client_key,
)
self.http_client.call(
url=self._url(f'requests/{request_id}'),
method='DELETE',
params=request_params,
timeout_secs=_SMALL_TIMEOUT,
)
def prolong_request_lock(
self,
request_id: str,
*,
forefront: bool | None = None,
lock_secs: int,
) -> dict:
"""Prolong the lock on a request.
https://docs.apify.com/api/v2#/reference/request-queues/request-lock/prolong-request-lock
Args:
request_id: ID of the request to prolong the lock.
forefront: Whether to put the request in the beginning or the end of the queue after lock expires.
lock_secs: By how much to prolong the lock, in seconds.
"""
request_params = self._params(clientKey=self.client_key, forefront=forefront, lockSecs=lock_secs)
response = self.http_client.call(
url=self._url(f'requests/{request_id}/lock'),
method='PUT',
params=request_params,
timeout_secs=_MEDIUM_TIMEOUT,
)
return parse_date_fields(pluck_data(response.json()))
def delete_request_lock(self, request_id: str, *, forefront: bool | None = None) -> None:
"""Delete the lock on a request.
https://docs.apify.com/api/v2#/reference/request-queues/request-lock/delete-request-lock
Args:
request_id: ID of the request to delete the lock.
forefront: Whether to put the request in the beginning or the end of the queue after the lock is deleted.
"""
request_params = self._params(clientKey=self.client_key, forefront=forefront)
self.http_client.call(
url=self._url(f'requests/{request_id}/lock'),
method='DELETE',
params=request_params,
timeout_secs=_SMALL_TIMEOUT,
)
def batch_add_requests(
self,
requests: list[dict],
*,
forefront: bool = False,
max_parallel: int = 1,
max_unprocessed_requests_retries: int = 3,
min_delay_between_unprocessed_requests_retries: timedelta = timedelta(milliseconds=500),
) -> BatchAddRequestsResult:
"""Add requests to the request queue in batches.
Requests are split into batches based on size and processed in parallel.
https://docs.apify.com/api/v2#/reference/request-queues/batch-request-operations/add-requests
Args:
requests: List of requests to be added to the queue.
forefront: Whether to add requests to the front of the queue.
max_parallel: Specifies the maximum number of parallel tasks for API calls. This is only applicable
to the async client. For the sync client, this value must be set to 1, as parallel execution
is not supported.
max_unprocessed_requests_retries: Number of retry attempts for unprocessed requests.
min_delay_between_unprocessed_requests_retries: Minimum delay between retry attempts for unprocessed
requests.
Returns:
Result containing lists of processed and unprocessed requests.
"""
if max_parallel != 1:
raise NotImplementedError('max_parallel is only supported in async client')
request_params = self._params(clientKey=self.client_key, forefront=forefront)
# Compute the payload size limit to ensure it doesn't exceed the maximum allowed size.
payload_size_limit_bytes = _MAX_PAYLOAD_SIZE_BYTES - math.ceil(_MAX_PAYLOAD_SIZE_BYTES * _SAFETY_BUFFER_PERCENT)
# Split the requests into batches, constrained by the max payload size and max requests per batch.
batches = constrained_batches(
requests,
max_size=payload_size_limit_bytes,
max_count=_RQ_MAX_REQUESTS_PER_BATCH,
)
# Put the batches into the queue for processing.
queue = Queue[AddRequestsBatch]()
for b in batches:
queue.put(AddRequestsBatch(b))
processed_requests = list[dict]()
unprocessed_requests = list[dict]()
# Process all batches in the queue sequentially.
while not queue.empty():
batch = queue.get()
# Send the batch to the API.
response = self.http_client.call(
url=self._url('requests/batch'),
method='POST',
params=request_params,
json=list(batch.requests),
timeout_secs=_MEDIUM_TIMEOUT,
)
# Retry if the request failed and the retry limit has not been reached.
if not response.is_success and batch.num_of_retries < max_unprocessed_requests_retries:
batch.num_of_retries += 1
sleep(min_delay_between_unprocessed_requests_retries.total_seconds())
queue.put(batch)
# Otherwise, add the processed/unprocessed requests to their respective lists.
else:
response_parsed = parse_date_fields(pluck_data(response.json()))
processed_requests.extend(response_parsed.get('processedRequests', []))
unprocessed_requests.extend(response_parsed.get('unprocessedRequests', []))
return {
'processedRequests': processed_requests,
'unprocessedRequests': unprocessed_requests,
}
def batch_delete_requests(self, requests: list[dict]) -> dict:
"""Delete given requests from the queue.
https://docs.apify.com/api/v2#/reference/request-queues/batch-request-operations/delete-requests
Args:
requests: List of the requests to delete.
"""
request_params = self._params(clientKey=self.client_key)
response = self.http_client.call(
url=self._url('requests/batch'),
method='DELETE',
params=request_params,
json=requests,
timeout_secs=_SMALL_TIMEOUT,
)
return parse_date_fields(pluck_data(response.json()))
def list_requests(
self,
*,
limit: int | None = None,
exclusive_start_id: str | None = None,
) -> dict:
"""List requests in the queue.
https://docs.apify.com/api/v2#/reference/request-queues/request-collection/list-requests
Args:
limit: How many requests to retrieve.
exclusive_start_id: All requests up to this one (including) are skipped from the result.
"""
request_params = self._params(limit=limit, exclusive_start_id=exclusive_start_id, clientKey=self.client_key)
response = self.http_client.call(
url=self._url('requests'),
method='GET',
params=request_params,
timeout_secs=_MEDIUM_TIMEOUT,
)
return parse_date_fields(pluck_data(response.json()))
class RequestQueueClientAsync(ResourceClientAsync):
"""Async sub-client for manipulating a single request queue."""
@ignore_docs
def __init__( # noqa: D417
self,
*args: Any,
client_key: str | None = None,
**kwargs: Any,
) -> None:
"""Initialize a new instance.
Args:
client_key: A unique identifier of the client accessing the request queue.
"""
resource_path = kwargs.pop('resource_path', 'request-queues')
super().__init__(*args, resource_path=resource_path, **kwargs)
self.client_key = client_key
async def get(self) -> dict | None:
"""Retrieve the request queue.
https://docs.apify.com/api/v2#/reference/request-queues/queue/get-request-queue
Returns:
The retrieved request queue, or None, if it does not exist.
"""
return await self._get(timeout_secs=_SMALL_TIMEOUT)
async def update(self, *, name: str | None = None, general_access: StorageGeneralAccess | None = None) -> dict:
"""Update the request queue with specified fields.
https://docs.apify.com/api/v2#/reference/request-queues/queue/update-request-queue
Args:
name: The new name for the request queue.
general_access: Determines how others can access the request queue.
Returns:
The updated request queue.
"""
updated_fields = {
'name': name,
'generalAccess': general_access,
}
return await self._update(filter_out_none_values_recursively(updated_fields), timeout_secs=_SMALL_TIMEOUT)
async def delete(self) -> None:
"""Delete the request queue.
https://docs.apify.com/api/v2#/reference/request-queues/queue/delete-request-queue
"""
return await self._delete(timeout_secs=_SMALL_TIMEOUT)
async def list_head(self, *, limit: int | None = None) -> dict:
"""Retrieve a given number of requests from the beginning of the queue.
https://docs.apify.com/api/v2#/reference/request-queues/queue-head/get-head
Args:
limit: How many requests to retrieve.
Returns:
The desired number of requests from the beginning of the queue.
"""
request_params = self._params(limit=limit, clientKey=self.client_key)
response = await self.http_client.call(
url=self._url('head'),
method='GET',
params=request_params,
timeout_secs=_SMALL_TIMEOUT,
)
return parse_date_fields(pluck_data(response.json()))
async def list_and_lock_head(self, *, lock_secs: int, limit: int | None = None) -> dict:
"""Retrieve a given number of unlocked requests from the beginning of the queue and lock them for a given time.
https://docs.apify.com/api/v2#/reference/request-queues/queue-head-with-locks/get-head-and-lock
Args:
lock_secs: How long the requests will be locked for, in seconds.
limit: How many requests to retrieve.
Returns:
The desired number of locked requests from the beginning of the queue.
"""
request_params = self._params(lockSecs=lock_secs, limit=limit, clientKey=self.client_key)
response = await self.http_client.call(
url=self._url('head/lock'),
method='POST',
params=request_params,
timeout_secs=_MEDIUM_TIMEOUT,
)
return parse_date_fields(pluck_data(response.json()))
async def add_request(self, request: dict, *, forefront: bool | None = None) -> dict:
"""Add a request to the queue.
https://docs.apify.com/api/v2#/reference/request-queues/request-collection/add-request
Args:
request: The request to add to the queue.
forefront: Whether to add the request to the head or the end of the queue.
Returns:
The added request.
"""
request_params = self._params(forefront=forefront, clientKey=self.client_key)
response = await self.http_client.call(
url=self._url('requests'),
method='POST',
json=request,
params=request_params,
timeout_secs=_SMALL_TIMEOUT,
)
return parse_date_fields(pluck_data(response.json()))
async def get_request(self, request_id: str) -> dict | None:
"""Retrieve a request from the queue.
https://docs.apify.com/api/v2#/reference/request-queues/request/get-request
Args:
request_id: ID of the request to retrieve.
Returns:
The retrieved request, or None, if it did not exist.
"""
try:
response = await self.http_client.call(
url=self._url(f'requests/{request_id}'),
method='GET',
params=self._params(),
timeout_secs=_SMALL_TIMEOUT,
)
return parse_date_fields(pluck_data(response.json()))
except ApifyApiError as exc:
catch_not_found_or_throw(exc)
return None
async def update_request(self, request: dict, *, forefront: bool | None = None) -> dict:
"""Update a request in the queue.
https://docs.apify.com/api/v2#/reference/request-queues/request/update-request
Args:
request: The updated request.
forefront: Whether to put the updated request in the beginning or the end of the queue.
Returns:
The updated request.
"""
request_id = request['id']
request_params = self._params(forefront=forefront, clientKey=self.client_key)
response = await self.http_client.call(
url=self._url(f'requests/{request_id}'),
method='PUT',
json=request,
params=request_params,
timeout_secs=_MEDIUM_TIMEOUT,
)
return parse_date_fields(pluck_data(response.json()))
async def delete_request(self, request_id: str) -> None:
"""Delete a request from the queue.
https://docs.apify.com/api/v2#/reference/request-queues/request/delete-request
Args:
request_id: ID of the request to delete.
"""
request_params = self._params(clientKey=self.client_key)
await self.http_client.call(
url=self._url(f'requests/{request_id}'),
method='DELETE',
params=request_params,
timeout_secs=_SMALL_TIMEOUT,
)
async def prolong_request_lock(
self,
request_id: str,
*,
forefront: bool | None = None,
lock_secs: int,
) -> dict:
"""Prolong the lock on a request.
https://docs.apify.com/api/v2#/reference/request-queues/request-lock/prolong-request-lock
Args:
request_id: ID of the request to prolong the lock.
forefront: Whether to put the request in the beginning or the end of the queue after lock expires.
lock_secs: By how much to prolong the lock, in seconds.
"""
request_params = self._params(clientKey=self.client_key, forefront=forefront, lockSecs=lock_secs)
response = await self.http_client.call(
url=self._url(f'requests/{request_id}/lock'),
method='PUT',
params=request_params,
timeout_secs=_MEDIUM_TIMEOUT,
)
return parse_date_fields(pluck_data(response.json()))
async def delete_request_lock(
self,
request_id: str,
*,
forefront: bool | None = None,
) -> None:
"""Delete the lock on a request.
https://docs.apify.com/api/v2#/reference/request-queues/request-lock/delete-request-lock
Args:
request_id: ID of the request to delete the lock.
forefront: Whether to put the request in the beginning or the end of the queue after the lock is deleted.
"""
request_params = self._params(clientKey=self.client_key, forefront=forefront)
await self.http_client.call(
url=self._url(f'requests/{request_id}/lock'),
method='DELETE',
params=request_params,
timeout_secs=_SMALL_TIMEOUT,
)
async def _batch_add_requests_worker(
self,
queue: asyncio.Queue[AddRequestsBatch],
request_params: dict,
max_unprocessed_requests_retries: int,
min_delay_between_unprocessed_requests_retries: timedelta,
) -> BatchAddRequestsResult:
"""Worker function to process a batch of requests.
This worker will process batches from the queue, retrying requests that fail until the retry limit is reached.
Return result containing lists of processed and unprocessed requests by the worker.
"""
processed_requests = list[dict]()
unprocessed_requests = list[dict]()
while True:
# Get the next batch from the queue.
try:
batch = await queue.get()
except asyncio.CancelledError:
break
try:
# Send the batch to the API.
response = await self.http_client.call(
url=self._url('requests/batch'),
method='POST',
params=request_params,
json=list(batch.requests),
timeout_secs=_MEDIUM_TIMEOUT,
)
response_parsed = parse_date_fields(pluck_data(response.json()))
# Retry if the request failed and the retry limit has not been reached.
if not response.is_success and batch.num_of_retries < max_unprocessed_requests_retries:
batch.num_of_retries += 1
await asyncio.sleep(min_delay_between_unprocessed_requests_retries.total_seconds())
await queue.put(batch)
# Otherwise, add the processed/unprocessed requests to their respective lists.
else:
processed_requests.extend(response_parsed.get('processedRequests', []))
unprocessed_requests.extend(response_parsed.get('unprocessedRequests', []))
except Exception as exc:
logger.warning(f'Error occurred while processing a batch of requests: {exc}')
finally:
# Mark the batch as done whether it succeeded or failed.
queue.task_done()
return {
'processedRequests': processed_requests,
'unprocessedRequests': unprocessed_requests,
}
async def batch_add_requests(
self,
requests: list[dict],
*,
forefront: bool = False,
max_parallel: int = 5,
max_unprocessed_requests_retries: int = 3,
min_delay_between_unprocessed_requests_retries: timedelta = timedelta(milliseconds=500),
) -> BatchAddRequestsResult:
"""Add requests to the request queue in batches.
Requests are split into batches based on size and processed in parallel.
https://docs.apify.com/api/v2#/reference/request-queues/batch-request-operations/add-requests
Args:
requests: List of requests to be added to the queue.
forefront: Whether to add requests to the front of the queue.
max_parallel: Specifies the maximum number of parallel tasks for API calls. This is only applicable
to the async client. For the sync client, this value must be set to 1, as parallel execution
is not supported.
max_unprocessed_requests_retries: Number of retry attempts for unprocessed requests.
min_delay_between_unprocessed_requests_retries: Minimum delay between retry attempts for unprocessed
requests.
Returns:
Result containing lists of processed and unprocessed requests.
"""
tasks = set[asyncio.Task]()
queue: asyncio.Queue[AddRequestsBatch] = asyncio.Queue()
request_params = self._params(clientKey=self.client_key, forefront=forefront)
# Compute the payload size limit to ensure it doesn't exceed the maximum allowed size.
payload_size_limit_bytes = _MAX_PAYLOAD_SIZE_BYTES - math.ceil(_MAX_PAYLOAD_SIZE_BYTES * _SAFETY_BUFFER_PERCENT)
# Split the requests into batches, constrained by the max payload size and max requests per batch.
batches = constrained_batches(
requests,
max_size=payload_size_limit_bytes,
max_count=_RQ_MAX_REQUESTS_PER_BATCH,
)
for batch in batches:
await queue.put(AddRequestsBatch(batch))
# Start a required number of worker tasks to process the batches.
for i in range(max_parallel):
coro = self._batch_add_requests_worker(
queue,
request_params,
max_unprocessed_requests_retries,
min_delay_between_unprocessed_requests_retries,
)
task = asyncio.create_task(coro, name=f'batch_add_requests_worker_{i}')
tasks.add(task)
# Wait for all batches to be processed.
await queue.join()
# Send cancellation signals to all worker tasks and wait for them to finish.
for task in tasks:
task.cancel()
results: list[BatchAddRequestsResult] = await asyncio.gather(*tasks)
# Combine the results from all workers and return them.
processed_requests = []
unprocessed_requests = []
for result in results:
processed_requests.extend(result['processedRequests'])
unprocessed_requests.extend(result['unprocessedRequests'])
return {
'processedRequests': processed_requests,
'unprocessedRequests': unprocessed_requests,
}
async def batch_delete_requests(self, requests: list[dict]) -> dict:
"""Delete given requests from the queue.
https://docs.apify.com/api/v2#/reference/request-queues/batch-request-operations/delete-requests
Args:
requests: List of the requests to delete.
"""
request_params = self._params(clientKey=self.client_key)
response = await self.http_client.call(
url=self._url('requests/batch'),
method='DELETE',
params=request_params,
json=requests,
timeout_secs=_SMALL_TIMEOUT,
)
return parse_date_fields(pluck_data(response.json()))
async def list_requests(
self,
*,
limit: int | None = None,
exclusive_start_id: str | None = None,
) -> dict:
"""List requests in the queue.
https://docs.apify.com/api/v2#/reference/request-queues/request-collection/list-requests
Args:
limit: How many requests to retrieve.
exclusive_start_id: All requests up to this one (including) are skipped from the result.
"""
request_params = self._params(limit=limit, exclusive_start_id=exclusive_start_id, clientKey=self.client_key)
response = await self.http_client.call(
url=self._url('requests'),
method='GET',
params=request_params,
timeout_secs=_MEDIUM_TIMEOUT,
)
return parse_date_fields(pluck_data(response.json()))