scrapely-client-python 3.1.3__py3-none-any.whl
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.
Potentially problematic release.
This version of scrapely-client-python might be problematic. Click here for more details.
- scrapely_client/__init__.py +30 -0
- scrapely_client/_charging.py +186 -0
- scrapely_client/_client_registry.py +136 -0
- scrapely_client/_consts.py +96 -0
- scrapely_client/_docs.py +37 -0
- scrapely_client/_literals.py +539 -0
- scrapely_client/_logging.py +180 -0
- scrapely_client/_models.py +4172 -0
- scrapely_client/_pagination.py +220 -0
- scrapely_client/_resource_clients/__init__.py +84 -0
- scrapely_client/_resource_clients/_resource_client.py +567 -0
- scrapely_client/_resource_clients/actor.py +1042 -0
- scrapely_client/_resource_clients/actor_collection.py +377 -0
- scrapely_client/_resource_clients/actor_env_var.py +154 -0
- scrapely_client/_resource_clients/actor_env_var_collection.py +165 -0
- scrapely_client/_resource_clients/actor_version.py +254 -0
- scrapely_client/_resource_clients/actor_version_collection.py +232 -0
- scrapely_client/_resource_clients/build.py +244 -0
- scrapely_client/_resource_clients/build_collection.py +164 -0
- scrapely_client/_resource_clients/dataset.py +1151 -0
- scrapely_client/_resource_clients/dataset_collection.py +244 -0
- scrapely_client/_resource_clients/key_value_store.py +906 -0
- scrapely_client/_resource_clients/key_value_store_collection.py +243 -0
- scrapely_client/_resource_clients/log.py +225 -0
- scrapely_client/_resource_clients/request_queue.py +1167 -0
- scrapely_client/_resource_clients/request_queue_collection.py +240 -0
- scrapely_client/_resource_clients/run.py +875 -0
- scrapely_client/_resource_clients/run_collection.py +226 -0
- scrapely_client/_resource_clients/schedule.py +243 -0
- scrapely_client/_resource_clients/schedule_collection.py +260 -0
- scrapely_client/_resource_clients/store_collection.py +242 -0
- scrapely_client/_resource_clients/task.py +793 -0
- scrapely_client/_resource_clients/task_collection.py +322 -0
- scrapely_client/_resource_clients/user.py +262 -0
- scrapely_client/_resource_clients/webhook.py +292 -0
- scrapely_client/_resource_clients/webhook_collection.py +281 -0
- scrapely_client/_resource_clients/webhook_dispatch.py +84 -0
- scrapely_client/_resource_clients/webhook_dispatch_collection.py +158 -0
- scrapely_client/_scrapely_client.py +837 -0
- scrapely_client/_statistics.py +29 -0
- scrapely_client/_status_message_watcher.py +197 -0
- scrapely_client/_streamed_log.py +250 -0
- scrapely_client/_typeddicts.py +408 -0
- scrapely_client/_utils/__init__.py +0 -0
- scrapely_client/_utils/crypto.py +87 -0
- scrapely_client/_utils/encoding.py +133 -0
- scrapely_client/_utils/errors.py +33 -0
- scrapely_client/_utils/http.py +137 -0
- scrapely_client/_utils/time.py +32 -0
- scrapely_client/_utils/try_import.py +61 -0
- scrapely_client/errors.py +190 -0
- scrapely_client/http_clients/__init__.py +10 -0
- scrapely_client/http_clients/_base.py +430 -0
- scrapely_client/http_clients/_impit.py +598 -0
- scrapely_client/http_compressors/__init__.py +18 -0
- scrapely_client/http_compressors/_base.py +25 -0
- scrapely_client/http_compressors/_brotli.py +38 -0
- scrapely_client/http_compressors/_gzip.py +38 -0
- scrapely_client/http_compressors/_resolve.py +38 -0
- scrapely_client/py.typed +0 -0
- scrapely_client/types.py +52 -0
- scrapely_client_python-3.1.3.dist-info/METADATA +269 -0
- scrapely_client_python-3.1.3.dist-info/RECORD +65 -0
- scrapely_client_python-3.1.3.dist-info/WHEEL +4 -0
- scrapely_client_python-3.1.3.dist-info/licenses/LICENSE +201 -0
|
@@ -0,0 +1,1167 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import json
|
|
5
|
+
import math
|
|
6
|
+
from collections.abc import Iterable
|
|
7
|
+
from queue import Queue
|
|
8
|
+
from typing import TYPE_CHECKING, Any, Literal
|
|
9
|
+
|
|
10
|
+
from more_itertools import constrained_batches
|
|
11
|
+
|
|
12
|
+
from scrapely_client._docs import docs_group
|
|
13
|
+
from scrapely_client._models import (
|
|
14
|
+
AddedRequest,
|
|
15
|
+
AddRequestResponse,
|
|
16
|
+
BatchAddResponse,
|
|
17
|
+
BatchAddResult,
|
|
18
|
+
BatchDeleteResponse,
|
|
19
|
+
BatchDeleteResult,
|
|
20
|
+
HeadAndLockResponse,
|
|
21
|
+
HeadResponse,
|
|
22
|
+
ListOfRequests,
|
|
23
|
+
ListOfRequestsResponse,
|
|
24
|
+
LockedRequestQueueHead,
|
|
25
|
+
ProlongRequestLockResponse,
|
|
26
|
+
Request,
|
|
27
|
+
RequestDraft,
|
|
28
|
+
RequestDraftDelete,
|
|
29
|
+
RequestLockInfo,
|
|
30
|
+
RequestQueue,
|
|
31
|
+
RequestQueueHead,
|
|
32
|
+
RequestQueueResponse,
|
|
33
|
+
RequestRegistration,
|
|
34
|
+
RequestResponse,
|
|
35
|
+
UnlockRequestsResponse,
|
|
36
|
+
UnlockRequestsResult,
|
|
37
|
+
)
|
|
38
|
+
from scrapely_client._pagination import DEFAULT_CHUNK_SIZE, get_cursor_iterator, get_cursor_iterator_async
|
|
39
|
+
from scrapely_client._resource_clients._resource_client import ResourceClient, ResourceClientAsync
|
|
40
|
+
from scrapely_client._utils.errors import catch_not_found_or_throw
|
|
41
|
+
from scrapely_client._utils.http import response_to_dict
|
|
42
|
+
from scrapely_client._utils.time import to_seconds
|
|
43
|
+
from scrapely_client.errors import ApifyApiError
|
|
44
|
+
|
|
45
|
+
if TYPE_CHECKING:
|
|
46
|
+
from collections.abc import AsyncIterator, Iterator
|
|
47
|
+
from datetime import timedelta
|
|
48
|
+
|
|
49
|
+
from scrapely_client._literals import GeneralAccess
|
|
50
|
+
from scrapely_client._typeddicts import (
|
|
51
|
+
RequestCamelDict,
|
|
52
|
+
RequestDict,
|
|
53
|
+
RequestDraftCamelDict,
|
|
54
|
+
RequestDraftDeleteCamelDict,
|
|
55
|
+
RequestDraftDeleteDict,
|
|
56
|
+
RequestDraftDict,
|
|
57
|
+
)
|
|
58
|
+
from scrapely_client.types import Timeout
|
|
59
|
+
|
|
60
|
+
_RQ_MAX_REQUESTS_PER_BATCH = 25
|
|
61
|
+
"""Maximum number of requests the API accepts in a single batch call."""
|
|
62
|
+
|
|
63
|
+
_MAX_PAYLOAD_SIZE_BYTES = 9 * 1024 * 1024
|
|
64
|
+
"""Maximum payload size (9 MB) the API accepts for a single batch call."""
|
|
65
|
+
|
|
66
|
+
_SAFETY_BUFFER_PERCENT = 0.01 / 100
|
|
67
|
+
"""Safety margin (0.01%) deducted from the maximum payload size when splitting requests into batches."""
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _serialize_requests(
|
|
71
|
+
requests: list[RequestDraft] | list[RequestDraftDict] | list[RequestDraftCamelDict],
|
|
72
|
+
) -> list[bytes]:
|
|
73
|
+
"""Validate requests and serialize each one into the JSON bytes it will occupy in the batch request body.
|
|
74
|
+
|
|
75
|
+
Each request is serialized exactly once: the same bytes are measured when splitting requests into batches and
|
|
76
|
+
then assembled into the request body, so batch sizes are computed on exactly the bytes that get sent. Validation
|
|
77
|
+
and serialization happen in a single pass, so each intermediate dict stays transient instead of a whole dict list
|
|
78
|
+
being held in memory alongside the serialized requests. Uses the same `json.dumps` options as
|
|
79
|
+
`HttpClientBase._prepare_request_call` to keep the wire format consistent with other endpoints.
|
|
80
|
+
"""
|
|
81
|
+
return [
|
|
82
|
+
json.dumps(
|
|
83
|
+
(request if isinstance(request, RequestDraft) else RequestDraft.model_validate(request)).model_dump(
|
|
84
|
+
by_alias=True, exclude_none=True
|
|
85
|
+
),
|
|
86
|
+
ensure_ascii=False,
|
|
87
|
+
allow_nan=False,
|
|
88
|
+
default=str,
|
|
89
|
+
).encode('utf-8')
|
|
90
|
+
for request in requests
|
|
91
|
+
]
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
@docs_group('Resource clients')
|
|
95
|
+
class RequestQueueClient(ResourceClient):
|
|
96
|
+
"""Sub-client for managing a specific request queue.
|
|
97
|
+
|
|
98
|
+
Provides methods to manage a specific request queue, e.g. update it, delete it, or manage its requests. Obtain an
|
|
99
|
+
instance via an appropriate method on the `ApifyClient` class.
|
|
100
|
+
"""
|
|
101
|
+
|
|
102
|
+
def __init__( # noqa: D417
|
|
103
|
+
self,
|
|
104
|
+
*,
|
|
105
|
+
resource_id: str | None = None,
|
|
106
|
+
resource_path: str = 'request-queues',
|
|
107
|
+
client_key: str | None = None,
|
|
108
|
+
**kwargs: Any,
|
|
109
|
+
) -> None:
|
|
110
|
+
"""Initialize a new instance.
|
|
111
|
+
|
|
112
|
+
Args:
|
|
113
|
+
client_key: A unique identifier of the client accessing the request queue.
|
|
114
|
+
"""
|
|
115
|
+
super().__init__(
|
|
116
|
+
resource_id=resource_id,
|
|
117
|
+
resource_path=resource_path,
|
|
118
|
+
**kwargs,
|
|
119
|
+
)
|
|
120
|
+
self.client_key = client_key
|
|
121
|
+
|
|
122
|
+
def get(self, *, timeout: Timeout = 'short') -> RequestQueue | None:
|
|
123
|
+
"""Retrieve the request queue.
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
Args:
|
|
127
|
+
timeout: Timeout for the API HTTP request.
|
|
128
|
+
|
|
129
|
+
Returns:
|
|
130
|
+
The retrieved request queue, or None, if it does not exist.
|
|
131
|
+
"""
|
|
132
|
+
result = self._get(timeout=timeout)
|
|
133
|
+
if result is None:
|
|
134
|
+
return None
|
|
135
|
+
return RequestQueueResponse.model_validate(result).data
|
|
136
|
+
|
|
137
|
+
def update(
|
|
138
|
+
self,
|
|
139
|
+
*,
|
|
140
|
+
name: str | None = None,
|
|
141
|
+
general_access: GeneralAccess | None = None,
|
|
142
|
+
timeout: Timeout = 'short',
|
|
143
|
+
) -> RequestQueue:
|
|
144
|
+
"""Update the request queue with specified fields.
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
Args:
|
|
148
|
+
name: The new name for the request queue.
|
|
149
|
+
general_access: Determines how others can access the request queue.
|
|
150
|
+
timeout: Timeout for the API HTTP request.
|
|
151
|
+
|
|
152
|
+
Returns:
|
|
153
|
+
The updated request queue.
|
|
154
|
+
"""
|
|
155
|
+
result = self._update(timeout=timeout, name=name, generalAccess=general_access)
|
|
156
|
+
return RequestQueueResponse.model_validate(result).data
|
|
157
|
+
|
|
158
|
+
def delete(self, *, timeout: Timeout = 'short') -> None:
|
|
159
|
+
"""Delete the request queue.
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
Args:
|
|
163
|
+
timeout: Timeout for the API HTTP request.
|
|
164
|
+
"""
|
|
165
|
+
self._delete(timeout=timeout)
|
|
166
|
+
|
|
167
|
+
def list_head(self, *, limit: int | None = None, timeout: Timeout = 'short') -> RequestQueueHead:
|
|
168
|
+
"""Retrieve a given number of requests from the beginning of the queue.
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
Args:
|
|
172
|
+
limit: How many requests to retrieve.
|
|
173
|
+
timeout: Timeout for the API HTTP request.
|
|
174
|
+
|
|
175
|
+
Returns:
|
|
176
|
+
The desired number of requests from the beginning of the queue.
|
|
177
|
+
"""
|
|
178
|
+
request_params = self._build_params(limit=limit, clientKey=self.client_key)
|
|
179
|
+
|
|
180
|
+
response = self._http_client.call(
|
|
181
|
+
url=self._build_url('head'),
|
|
182
|
+
method='GET',
|
|
183
|
+
params=request_params,
|
|
184
|
+
timeout=timeout,
|
|
185
|
+
)
|
|
186
|
+
|
|
187
|
+
result = response_to_dict(response)
|
|
188
|
+
return HeadResponse.model_validate(result).data
|
|
189
|
+
|
|
190
|
+
def list_and_lock_head(
|
|
191
|
+
self,
|
|
192
|
+
*,
|
|
193
|
+
lock_duration: timedelta,
|
|
194
|
+
limit: int | None = None,
|
|
195
|
+
timeout: Timeout = 'medium',
|
|
196
|
+
) -> LockedRequestQueueHead:
|
|
197
|
+
"""Retrieve a given number of unlocked requests from the beginning of the queue and lock them for a given time.
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
Args:
|
|
201
|
+
lock_duration: How long the requests will be locked for.
|
|
202
|
+
limit: How many requests to retrieve.
|
|
203
|
+
timeout: Timeout for the API HTTP request.
|
|
204
|
+
|
|
205
|
+
Returns:
|
|
206
|
+
The desired number of locked requests from the beginning of the queue.
|
|
207
|
+
"""
|
|
208
|
+
request_params = self._build_params(
|
|
209
|
+
lockSecs=to_seconds(lock_duration, as_int=True),
|
|
210
|
+
limit=limit,
|
|
211
|
+
clientKey=self.client_key,
|
|
212
|
+
)
|
|
213
|
+
|
|
214
|
+
response = self._http_client.call(
|
|
215
|
+
url=self._build_url('head/lock'),
|
|
216
|
+
method='POST',
|
|
217
|
+
params=request_params,
|
|
218
|
+
timeout=timeout,
|
|
219
|
+
)
|
|
220
|
+
|
|
221
|
+
result = response_to_dict(response)
|
|
222
|
+
return HeadAndLockResponse.model_validate(result).data
|
|
223
|
+
|
|
224
|
+
def add_request(
|
|
225
|
+
self,
|
|
226
|
+
request: RequestDraftDict | RequestDraftCamelDict | RequestDraft,
|
|
227
|
+
*,
|
|
228
|
+
forefront: bool | None = None,
|
|
229
|
+
timeout: Timeout = 'short',
|
|
230
|
+
) -> RequestRegistration:
|
|
231
|
+
"""Add a request to the queue.
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
Args:
|
|
235
|
+
request: The request to add to the queue.
|
|
236
|
+
forefront: Whether to add the request to the head or the end of the queue.
|
|
237
|
+
timeout: Timeout for the API HTTP request.
|
|
238
|
+
|
|
239
|
+
Returns:
|
|
240
|
+
The added request.
|
|
241
|
+
"""
|
|
242
|
+
if not isinstance(request, RequestDraft):
|
|
243
|
+
request = RequestDraft.model_validate(request)
|
|
244
|
+
|
|
245
|
+
request_params = self._build_params(forefront=forefront, clientKey=self.client_key)
|
|
246
|
+
|
|
247
|
+
response = self._http_client.call(
|
|
248
|
+
url=self._build_url('requests'),
|
|
249
|
+
method='POST',
|
|
250
|
+
json=request.model_dump(by_alias=True, exclude_none=True),
|
|
251
|
+
params=request_params,
|
|
252
|
+
timeout=timeout,
|
|
253
|
+
)
|
|
254
|
+
|
|
255
|
+
result = response_to_dict(response)
|
|
256
|
+
return AddRequestResponse.model_validate(result).data
|
|
257
|
+
|
|
258
|
+
def get_request(self, request_id: str, *, timeout: Timeout = 'short') -> Request | None:
|
|
259
|
+
"""Retrieve a request from the queue.
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
Args:
|
|
263
|
+
request_id: ID of the request to retrieve.
|
|
264
|
+
timeout: Timeout for the API HTTP request.
|
|
265
|
+
|
|
266
|
+
Returns:
|
|
267
|
+
The retrieved request, or None, if it did not exist.
|
|
268
|
+
"""
|
|
269
|
+
try:
|
|
270
|
+
response = self._http_client.call(
|
|
271
|
+
url=self._build_url(f'requests/{request_id}'),
|
|
272
|
+
method='GET',
|
|
273
|
+
params=self._build_params(),
|
|
274
|
+
timeout=timeout,
|
|
275
|
+
)
|
|
276
|
+
result = response_to_dict(response)
|
|
277
|
+
return RequestResponse.model_validate(result).data
|
|
278
|
+
|
|
279
|
+
except ApifyApiError as exc:
|
|
280
|
+
catch_not_found_or_throw(exc)
|
|
281
|
+
|
|
282
|
+
return None
|
|
283
|
+
|
|
284
|
+
def update_request(
|
|
285
|
+
self,
|
|
286
|
+
request: RequestDict | RequestCamelDict | Request,
|
|
287
|
+
*,
|
|
288
|
+
forefront: bool | None = None,
|
|
289
|
+
timeout: Timeout = 'medium',
|
|
290
|
+
) -> RequestRegistration:
|
|
291
|
+
"""Update a request in the queue.
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
Args:
|
|
295
|
+
request: The updated request.
|
|
296
|
+
forefront: Whether to put the updated request in the beginning or the end of the queue.
|
|
297
|
+
timeout: Timeout for the API HTTP request.
|
|
298
|
+
|
|
299
|
+
Returns:
|
|
300
|
+
The updated request.
|
|
301
|
+
"""
|
|
302
|
+
if not isinstance(request, Request):
|
|
303
|
+
request = Request.model_validate(request)
|
|
304
|
+
|
|
305
|
+
request_params = self._build_params(forefront=forefront, clientKey=self.client_key)
|
|
306
|
+
|
|
307
|
+
response = self._http_client.call(
|
|
308
|
+
url=self._build_url(f'requests/{request.id}'),
|
|
309
|
+
method='PUT',
|
|
310
|
+
json=request.model_dump(by_alias=True, exclude_none=True),
|
|
311
|
+
params=request_params,
|
|
312
|
+
timeout=timeout,
|
|
313
|
+
)
|
|
314
|
+
|
|
315
|
+
result = response_to_dict(response)
|
|
316
|
+
return AddRequestResponse.model_validate(result).data
|
|
317
|
+
|
|
318
|
+
def delete_request(self, request_id: str, *, timeout: Timeout = 'short') -> None:
|
|
319
|
+
"""Delete a request from the queue.
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
Args:
|
|
323
|
+
request_id: ID of the request to delete.
|
|
324
|
+
timeout: Timeout for the API HTTP request.
|
|
325
|
+
"""
|
|
326
|
+
request_params = self._build_params(
|
|
327
|
+
clientKey=self.client_key,
|
|
328
|
+
)
|
|
329
|
+
|
|
330
|
+
self._http_client.call(
|
|
331
|
+
url=self._build_url(f'requests/{request_id}'),
|
|
332
|
+
method='DELETE',
|
|
333
|
+
params=request_params,
|
|
334
|
+
timeout=timeout,
|
|
335
|
+
)
|
|
336
|
+
|
|
337
|
+
def prolong_request_lock(
|
|
338
|
+
self,
|
|
339
|
+
request_id: str,
|
|
340
|
+
*,
|
|
341
|
+
forefront: bool | None = None,
|
|
342
|
+
lock_duration: timedelta,
|
|
343
|
+
timeout: Timeout = 'medium',
|
|
344
|
+
) -> RequestLockInfo | None:
|
|
345
|
+
"""Prolong the lock on a request.
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
Args:
|
|
349
|
+
request_id: ID of the request to prolong the lock.
|
|
350
|
+
forefront: Whether to put the request in the beginning or the end of the queue after lock expires.
|
|
351
|
+
lock_duration: By how much to prolong the lock.
|
|
352
|
+
timeout: Timeout for the API HTTP request.
|
|
353
|
+
"""
|
|
354
|
+
request_params = self._build_params(
|
|
355
|
+
clientKey=self.client_key,
|
|
356
|
+
forefront=forefront,
|
|
357
|
+
lockSecs=to_seconds(lock_duration, as_int=True),
|
|
358
|
+
)
|
|
359
|
+
|
|
360
|
+
response = self._http_client.call(
|
|
361
|
+
url=self._build_url(f'requests/{request_id}/lock'),
|
|
362
|
+
method='PUT',
|
|
363
|
+
params=request_params,
|
|
364
|
+
timeout=timeout,
|
|
365
|
+
)
|
|
366
|
+
|
|
367
|
+
result = response_to_dict(response)
|
|
368
|
+
return ProlongRequestLockResponse.model_validate(result).data
|
|
369
|
+
|
|
370
|
+
def delete_request_lock(
|
|
371
|
+
self,
|
|
372
|
+
request_id: str,
|
|
373
|
+
*,
|
|
374
|
+
forefront: bool | None = None,
|
|
375
|
+
timeout: Timeout = 'short',
|
|
376
|
+
) -> None:
|
|
377
|
+
"""Delete the lock on a request.
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
Args:
|
|
381
|
+
request_id: ID of the request to delete the lock.
|
|
382
|
+
forefront: Whether to put the request in the beginning or the end of the queue after the lock is deleted.
|
|
383
|
+
timeout: Timeout for the API HTTP request.
|
|
384
|
+
"""
|
|
385
|
+
request_params = self._build_params(clientKey=self.client_key, forefront=forefront)
|
|
386
|
+
|
|
387
|
+
self._http_client.call(
|
|
388
|
+
url=self._build_url(f'requests/{request_id}/lock'),
|
|
389
|
+
method='DELETE',
|
|
390
|
+
params=request_params,
|
|
391
|
+
timeout=timeout,
|
|
392
|
+
)
|
|
393
|
+
|
|
394
|
+
def batch_add_requests(
|
|
395
|
+
self,
|
|
396
|
+
requests: list[RequestDraft] | list[RequestDraftDict] | list[RequestDraftCamelDict],
|
|
397
|
+
*,
|
|
398
|
+
forefront: bool = False,
|
|
399
|
+
max_parallel: int = 1,
|
|
400
|
+
timeout: Timeout = 'medium',
|
|
401
|
+
) -> BatchAddResult:
|
|
402
|
+
"""Add requests to the request queue in batches.
|
|
403
|
+
|
|
404
|
+
Requests are split into batches based on size and processed in parallel.
|
|
405
|
+
|
|
406
|
+
|
|
407
|
+
Args:
|
|
408
|
+
requests: List of requests to be added to the queue.
|
|
409
|
+
forefront: Whether to add requests to the front of the queue.
|
|
410
|
+
max_parallel: Specifies the maximum number of parallel tasks for API calls. This is only applicable
|
|
411
|
+
to the async client. For the sync client, this value must be set to 1, as parallel execution
|
|
412
|
+
is not supported.
|
|
413
|
+
timeout: Timeout for the API HTTP request.
|
|
414
|
+
|
|
415
|
+
Returns:
|
|
416
|
+
Result containing lists of processed and unprocessed requests.
|
|
417
|
+
"""
|
|
418
|
+
if max_parallel != 1:
|
|
419
|
+
raise NotImplementedError('max_parallel is only supported in async client')
|
|
420
|
+
|
|
421
|
+
# Validate the requests and serialize each of them into JSON bytes.
|
|
422
|
+
serialized_requests = _serialize_requests(requests)
|
|
423
|
+
|
|
424
|
+
# Build the query parameters shared by all the batch API calls.
|
|
425
|
+
request_params = self._build_params(clientKey=self.client_key, forefront=forefront)
|
|
426
|
+
|
|
427
|
+
# Compute the payload size limit to ensure it doesn't exceed the maximum allowed size.
|
|
428
|
+
payload_size_limit_bytes = _MAX_PAYLOAD_SIZE_BYTES - math.ceil(_MAX_PAYLOAD_SIZE_BYTES * _SAFETY_BUFFER_PERCENT)
|
|
429
|
+
|
|
430
|
+
# Split the requests into batches by payload size (counting commas and brackets) and max requests per batch.
|
|
431
|
+
batches = constrained_batches(
|
|
432
|
+
serialized_requests,
|
|
433
|
+
max_size=payload_size_limit_bytes - len(b'[]'),
|
|
434
|
+
max_count=_RQ_MAX_REQUESTS_PER_BATCH,
|
|
435
|
+
get_len=lambda serialized: len(serialized) + len(b','),
|
|
436
|
+
strict=False,
|
|
437
|
+
)
|
|
438
|
+
|
|
439
|
+
# Put the batches into the queue for processing.
|
|
440
|
+
batch_queue = Queue[Iterable[bytes]]()
|
|
441
|
+
|
|
442
|
+
for batch in batches:
|
|
443
|
+
batch_queue.put(batch)
|
|
444
|
+
|
|
445
|
+
processed_requests = list[AddedRequest]()
|
|
446
|
+
unprocessed_requests = list[RequestDraft]()
|
|
447
|
+
|
|
448
|
+
# Process all batches in the queue sequentially.
|
|
449
|
+
while not batch_queue.empty():
|
|
450
|
+
request_batch = batch_queue.get()
|
|
451
|
+
|
|
452
|
+
# Send the batch to the API, assembling the body from the already serialized requests.
|
|
453
|
+
response = self._http_client.call(
|
|
454
|
+
url=self._build_url('requests/batch'),
|
|
455
|
+
method='POST',
|
|
456
|
+
headers={'content-type': 'application/json'},
|
|
457
|
+
params=request_params,
|
|
458
|
+
data=b'[' + b','.join(request_batch) + b']',
|
|
459
|
+
timeout=timeout,
|
|
460
|
+
)
|
|
461
|
+
|
|
462
|
+
result = response_to_dict(response)
|
|
463
|
+
batch_response = BatchAddResponse.model_validate(result)
|
|
464
|
+
processed_requests.extend(batch_response.data.processed_requests)
|
|
465
|
+
unprocessed_requests.extend(batch_response.data.unprocessed_requests)
|
|
466
|
+
|
|
467
|
+
return BatchAddResponse.model_construct(
|
|
468
|
+
data=BatchAddResult.model_construct(
|
|
469
|
+
processed_requests=processed_requests,
|
|
470
|
+
unprocessed_requests=unprocessed_requests,
|
|
471
|
+
)
|
|
472
|
+
).data
|
|
473
|
+
|
|
474
|
+
def batch_delete_requests(
|
|
475
|
+
self,
|
|
476
|
+
requests: list[RequestDraftDelete] | list[RequestDraftDeleteDict] | list[RequestDraftDeleteCamelDict],
|
|
477
|
+
*,
|
|
478
|
+
timeout: Timeout = 'short',
|
|
479
|
+
) -> BatchDeleteResult:
|
|
480
|
+
"""Delete given requests from the queue.
|
|
481
|
+
|
|
482
|
+
|
|
483
|
+
Args:
|
|
484
|
+
requests: List of the requests to delete.
|
|
485
|
+
timeout: Timeout for the API HTTP request.
|
|
486
|
+
"""
|
|
487
|
+
requests_as_dicts = [
|
|
488
|
+
(
|
|
489
|
+
request
|
|
490
|
+
if isinstance(request, RequestDraftDelete)
|
|
491
|
+
else RequestDraftDelete.model_validate(
|
|
492
|
+
request,
|
|
493
|
+
)
|
|
494
|
+
).model_dump(by_alias=True, exclude_none=True)
|
|
495
|
+
for request in requests
|
|
496
|
+
]
|
|
497
|
+
|
|
498
|
+
request_params = self._build_params(clientKey=self.client_key)
|
|
499
|
+
|
|
500
|
+
response = self._http_client.call(
|
|
501
|
+
url=self._build_url('requests/batch'),
|
|
502
|
+
method='DELETE',
|
|
503
|
+
params=request_params,
|
|
504
|
+
json=requests_as_dicts,
|
|
505
|
+
timeout=timeout,
|
|
506
|
+
)
|
|
507
|
+
|
|
508
|
+
result = response_to_dict(response)
|
|
509
|
+
return BatchDeleteResponse.model_validate(result).data
|
|
510
|
+
|
|
511
|
+
def list_requests(
|
|
512
|
+
self,
|
|
513
|
+
*,
|
|
514
|
+
limit: int | None = None,
|
|
515
|
+
filter: list[Literal['pending', 'locked']] | None = None, # noqa: A002
|
|
516
|
+
timeout: Timeout = 'medium',
|
|
517
|
+
cursor: str | None = None,
|
|
518
|
+
) -> ListOfRequests:
|
|
519
|
+
"""List requests in the queue.
|
|
520
|
+
|
|
521
|
+
|
|
522
|
+
Args:
|
|
523
|
+
limit: How many requests to retrieve.
|
|
524
|
+
filter: List of request states to use as a filter. Multiple values mean union of the given filters.
|
|
525
|
+
timeout: Timeout for the API HTTP request.
|
|
526
|
+
cursor: A token returned in previous API response, to continue listing next page of requests
|
|
527
|
+
"""
|
|
528
|
+
request_params = self._build_params(
|
|
529
|
+
limit=limit,
|
|
530
|
+
filter=','.join(filter) if filter else None,
|
|
531
|
+
clientKey=self.client_key,
|
|
532
|
+
cursor=cursor,
|
|
533
|
+
)
|
|
534
|
+
|
|
535
|
+
response = self._http_client.call(
|
|
536
|
+
url=self._build_url('requests'),
|
|
537
|
+
method='GET',
|
|
538
|
+
params=request_params,
|
|
539
|
+
timeout=timeout,
|
|
540
|
+
)
|
|
541
|
+
|
|
542
|
+
result = response_to_dict(response)
|
|
543
|
+
return ListOfRequestsResponse.model_validate(result).data
|
|
544
|
+
|
|
545
|
+
def iterate_requests(
|
|
546
|
+
self,
|
|
547
|
+
*,
|
|
548
|
+
limit: int | None = None,
|
|
549
|
+
filter: list[Literal['pending', 'locked']] | None = None, # noqa: A002
|
|
550
|
+
cursor: str | None = None,
|
|
551
|
+
chunk_size: int | None = None,
|
|
552
|
+
timeout: Timeout = 'medium',
|
|
553
|
+
) -> Iterator[Request]:
|
|
554
|
+
"""Iterate over requests in the queue.
|
|
555
|
+
|
|
556
|
+
Simple `list_requests` does only one API call, possibly not listing all items matching the criteria.
|
|
557
|
+
This method returns an iterator that is capable of making multiple API calls to retrieve all items
|
|
558
|
+
matching the criteria using the opaque `cursor` returned by the API.
|
|
559
|
+
|
|
560
|
+
|
|
561
|
+
Args:
|
|
562
|
+
limit: Maximum number of requests to yield across all pages.
|
|
563
|
+
filter: List of request states to use as a filter. Multiple values mean union of the given filters.
|
|
564
|
+
cursor: A token returned in a previous API response, used as the initial pagination cursor.
|
|
565
|
+
chunk_size: Maximum number of requests requested per API call when iterating across pages.
|
|
566
|
+
timeout: Timeout for the API HTTP request.
|
|
567
|
+
|
|
568
|
+
Yields:
|
|
569
|
+
A request from the queue.
|
|
570
|
+
"""
|
|
571
|
+
|
|
572
|
+
def _callback(*, cursor: str | None = None, limit: int | None = None) -> ListOfRequests:
|
|
573
|
+
return self.list_requests(limit=limit, filter=filter, cursor=cursor, timeout=timeout)
|
|
574
|
+
|
|
575
|
+
return get_cursor_iterator(
|
|
576
|
+
_callback,
|
|
577
|
+
cursor=cursor,
|
|
578
|
+
limit=limit,
|
|
579
|
+
chunk_size=chunk_size or DEFAULT_CHUNK_SIZE,
|
|
580
|
+
)
|
|
581
|
+
|
|
582
|
+
def unlock_requests(self: RequestQueueClient, *, timeout: Timeout = 'long') -> UnlockRequestsResult:
|
|
583
|
+
"""Unlock all requests in the queue, which were locked by the same clientKey or from the same Actor run.
|
|
584
|
+
|
|
585
|
+
|
|
586
|
+
Args:
|
|
587
|
+
timeout: Timeout for the API HTTP request.
|
|
588
|
+
|
|
589
|
+
Returns:
|
|
590
|
+
Result of the unlock operation containing the count of unlocked requests
|
|
591
|
+
"""
|
|
592
|
+
request_params = self._build_params(clientKey=self.client_key)
|
|
593
|
+
|
|
594
|
+
response = self._http_client.call(
|
|
595
|
+
url=self._build_url('requests/unlock'),
|
|
596
|
+
method='POST',
|
|
597
|
+
params=request_params,
|
|
598
|
+
timeout=timeout,
|
|
599
|
+
)
|
|
600
|
+
|
|
601
|
+
result = response_to_dict(response)
|
|
602
|
+
return UnlockRequestsResponse.model_validate(result).data
|
|
603
|
+
|
|
604
|
+
|
|
605
|
+
@docs_group('Resource clients')
|
|
606
|
+
class RequestQueueClientAsync(ResourceClientAsync):
|
|
607
|
+
"""Sub-client for managing a specific request queue.
|
|
608
|
+
|
|
609
|
+
Provides methods to manage a specific request queue, e.g. update it, delete it, or manage its requests. Obtain an
|
|
610
|
+
instance via an appropriate method on the `ApifyClientAsync` class.
|
|
611
|
+
"""
|
|
612
|
+
|
|
613
|
+
def __init__( # noqa: D417
|
|
614
|
+
self,
|
|
615
|
+
*,
|
|
616
|
+
resource_id: str | None = None,
|
|
617
|
+
resource_path: str = 'request-queues',
|
|
618
|
+
client_key: str | None = None,
|
|
619
|
+
**kwargs: Any,
|
|
620
|
+
) -> None:
|
|
621
|
+
"""Initialize a new instance.
|
|
622
|
+
|
|
623
|
+
Args:
|
|
624
|
+
client_key: A unique identifier of the client accessing the request queue.
|
|
625
|
+
"""
|
|
626
|
+
super().__init__(
|
|
627
|
+
resource_id=resource_id,
|
|
628
|
+
resource_path=resource_path,
|
|
629
|
+
**kwargs,
|
|
630
|
+
)
|
|
631
|
+
self.client_key = client_key
|
|
632
|
+
|
|
633
|
+
async def get(self, *, timeout: Timeout = 'short') -> RequestQueue | None:
|
|
634
|
+
"""Retrieve the request queue.
|
|
635
|
+
|
|
636
|
+
|
|
637
|
+
Args:
|
|
638
|
+
timeout: Timeout for the API HTTP request.
|
|
639
|
+
|
|
640
|
+
Returns:
|
|
641
|
+
The retrieved request queue, or None, if it does not exist.
|
|
642
|
+
"""
|
|
643
|
+
result = await self._get(timeout=timeout)
|
|
644
|
+
if result is None:
|
|
645
|
+
return None
|
|
646
|
+
return RequestQueueResponse.model_validate(result).data
|
|
647
|
+
|
|
648
|
+
async def update(
|
|
649
|
+
self,
|
|
650
|
+
*,
|
|
651
|
+
name: str | None = None,
|
|
652
|
+
general_access: GeneralAccess | None = None,
|
|
653
|
+
timeout: Timeout = 'short',
|
|
654
|
+
) -> RequestQueue:
|
|
655
|
+
"""Update the request queue with specified fields.
|
|
656
|
+
|
|
657
|
+
|
|
658
|
+
Args:
|
|
659
|
+
name: The new name for the request queue.
|
|
660
|
+
general_access: Determines how others can access the request queue.
|
|
661
|
+
timeout: Timeout for the API HTTP request.
|
|
662
|
+
|
|
663
|
+
Returns:
|
|
664
|
+
The updated request queue.
|
|
665
|
+
"""
|
|
666
|
+
result = await self._update(timeout=timeout, name=name, generalAccess=general_access)
|
|
667
|
+
return RequestQueueResponse.model_validate(result).data
|
|
668
|
+
|
|
669
|
+
async def delete(self, *, timeout: Timeout = 'short') -> None:
|
|
670
|
+
"""Delete the request queue.
|
|
671
|
+
|
|
672
|
+
|
|
673
|
+
Args:
|
|
674
|
+
timeout: Timeout for the API HTTP request.
|
|
675
|
+
"""
|
|
676
|
+
await self._delete(timeout=timeout)
|
|
677
|
+
|
|
678
|
+
async def list_head(self, *, limit: int | None = None, timeout: Timeout = 'short') -> RequestQueueHead:
|
|
679
|
+
"""Retrieve a given number of requests from the beginning of the queue.
|
|
680
|
+
|
|
681
|
+
|
|
682
|
+
Args:
|
|
683
|
+
limit: How many requests to retrieve.
|
|
684
|
+
timeout: Timeout for the API HTTP request.
|
|
685
|
+
|
|
686
|
+
Returns:
|
|
687
|
+
The desired number of requests from the beginning of the queue.
|
|
688
|
+
"""
|
|
689
|
+
request_params = self._build_params(limit=limit, clientKey=self.client_key)
|
|
690
|
+
|
|
691
|
+
response = await self._http_client.call(
|
|
692
|
+
url=self._build_url('head'),
|
|
693
|
+
method='GET',
|
|
694
|
+
params=request_params,
|
|
695
|
+
timeout=timeout,
|
|
696
|
+
)
|
|
697
|
+
|
|
698
|
+
result = response_to_dict(response)
|
|
699
|
+
return HeadResponse.model_validate(result).data
|
|
700
|
+
|
|
701
|
+
async def list_and_lock_head(
|
|
702
|
+
self,
|
|
703
|
+
*,
|
|
704
|
+
lock_duration: timedelta,
|
|
705
|
+
limit: int | None = None,
|
|
706
|
+
timeout: Timeout = 'medium',
|
|
707
|
+
) -> LockedRequestQueueHead:
|
|
708
|
+
"""Retrieve a given number of unlocked requests from the beginning of the queue and lock them for a given time.
|
|
709
|
+
|
|
710
|
+
|
|
711
|
+
Args:
|
|
712
|
+
lock_duration: How long the requests will be locked for.
|
|
713
|
+
limit: How many requests to retrieve.
|
|
714
|
+
timeout: Timeout for the API HTTP request.
|
|
715
|
+
|
|
716
|
+
Returns:
|
|
717
|
+
The desired number of locked requests from the beginning of the queue.
|
|
718
|
+
"""
|
|
719
|
+
request_params = self._build_params(
|
|
720
|
+
lockSecs=to_seconds(lock_duration, as_int=True),
|
|
721
|
+
limit=limit,
|
|
722
|
+
clientKey=self.client_key,
|
|
723
|
+
)
|
|
724
|
+
|
|
725
|
+
response = await self._http_client.call(
|
|
726
|
+
url=self._build_url('head/lock'),
|
|
727
|
+
method='POST',
|
|
728
|
+
params=request_params,
|
|
729
|
+
timeout=timeout,
|
|
730
|
+
)
|
|
731
|
+
|
|
732
|
+
result = response_to_dict(response)
|
|
733
|
+
return HeadAndLockResponse.model_validate(result).data
|
|
734
|
+
|
|
735
|
+
async def add_request(
|
|
736
|
+
self,
|
|
737
|
+
request: RequestDraftDict | RequestDraftCamelDict | RequestDraft,
|
|
738
|
+
*,
|
|
739
|
+
forefront: bool | None = None,
|
|
740
|
+
timeout: Timeout = 'short',
|
|
741
|
+
) -> RequestRegistration:
|
|
742
|
+
"""Add a request to the queue.
|
|
743
|
+
|
|
744
|
+
|
|
745
|
+
Args:
|
|
746
|
+
request: The request to add to the queue.
|
|
747
|
+
forefront: Whether to add the request to the head or the end of the queue.
|
|
748
|
+
timeout: Timeout for the API HTTP request.
|
|
749
|
+
|
|
750
|
+
Returns:
|
|
751
|
+
The added request.
|
|
752
|
+
"""
|
|
753
|
+
if not isinstance(request, RequestDraft):
|
|
754
|
+
request = RequestDraft.model_validate(request)
|
|
755
|
+
|
|
756
|
+
request_params = self._build_params(forefront=forefront, clientKey=self.client_key)
|
|
757
|
+
|
|
758
|
+
response = await self._http_client.call(
|
|
759
|
+
url=self._build_url('requests'),
|
|
760
|
+
method='POST',
|
|
761
|
+
json=request.model_dump(by_alias=True, exclude_none=True),
|
|
762
|
+
params=request_params,
|
|
763
|
+
timeout=timeout,
|
|
764
|
+
)
|
|
765
|
+
|
|
766
|
+
result = response_to_dict(response)
|
|
767
|
+
return AddRequestResponse.model_validate(result).data
|
|
768
|
+
|
|
769
|
+
async def get_request(self, request_id: str, *, timeout: Timeout = 'short') -> Request | None:
|
|
770
|
+
"""Retrieve a request from the queue.
|
|
771
|
+
|
|
772
|
+
|
|
773
|
+
Args:
|
|
774
|
+
request_id: ID of the request to retrieve.
|
|
775
|
+
timeout: Timeout for the API HTTP request.
|
|
776
|
+
|
|
777
|
+
Returns:
|
|
778
|
+
The retrieved request, or None, if it did not exist.
|
|
779
|
+
"""
|
|
780
|
+
try:
|
|
781
|
+
response = await self._http_client.call(
|
|
782
|
+
url=self._build_url(f'requests/{request_id}'),
|
|
783
|
+
method='GET',
|
|
784
|
+
params=self._build_params(),
|
|
785
|
+
timeout=timeout,
|
|
786
|
+
)
|
|
787
|
+
result = response_to_dict(response)
|
|
788
|
+
return RequestResponse.model_validate(result).data
|
|
789
|
+
except ApifyApiError as exc:
|
|
790
|
+
catch_not_found_or_throw(exc)
|
|
791
|
+
return None
|
|
792
|
+
|
|
793
|
+
async def update_request(
|
|
794
|
+
self,
|
|
795
|
+
request: RequestDict | RequestCamelDict | Request,
|
|
796
|
+
*,
|
|
797
|
+
forefront: bool | None = None,
|
|
798
|
+
timeout: Timeout = 'medium',
|
|
799
|
+
) -> RequestRegistration:
|
|
800
|
+
"""Update a request in the queue.
|
|
801
|
+
|
|
802
|
+
|
|
803
|
+
Args:
|
|
804
|
+
request: The updated request.
|
|
805
|
+
forefront: Whether to put the updated request in the beginning or the end of the queue.
|
|
806
|
+
timeout: Timeout for the API HTTP request.
|
|
807
|
+
|
|
808
|
+
Returns:
|
|
809
|
+
The updated request.
|
|
810
|
+
"""
|
|
811
|
+
if not isinstance(request, Request):
|
|
812
|
+
request = Request.model_validate(request)
|
|
813
|
+
|
|
814
|
+
request_params = self._build_params(forefront=forefront, clientKey=self.client_key)
|
|
815
|
+
|
|
816
|
+
response = await self._http_client.call(
|
|
817
|
+
url=self._build_url(f'requests/{request.id}'),
|
|
818
|
+
method='PUT',
|
|
819
|
+
json=request.model_dump(by_alias=True, exclude_none=True),
|
|
820
|
+
params=request_params,
|
|
821
|
+
timeout=timeout,
|
|
822
|
+
)
|
|
823
|
+
|
|
824
|
+
result = response_to_dict(response)
|
|
825
|
+
return AddRequestResponse.model_validate(result).data
|
|
826
|
+
|
|
827
|
+
async def delete_request(self, request_id: str, *, timeout: Timeout = 'short') -> None:
|
|
828
|
+
"""Delete a request from the queue.
|
|
829
|
+
|
|
830
|
+
|
|
831
|
+
Args:
|
|
832
|
+
request_id: ID of the request to delete.
|
|
833
|
+
timeout: Timeout for the API HTTP request.
|
|
834
|
+
"""
|
|
835
|
+
request_params = self._build_params(clientKey=self.client_key)
|
|
836
|
+
|
|
837
|
+
await self._http_client.call(
|
|
838
|
+
url=self._build_url(f'requests/{request_id}'),
|
|
839
|
+
method='DELETE',
|
|
840
|
+
params=request_params,
|
|
841
|
+
timeout=timeout,
|
|
842
|
+
)
|
|
843
|
+
|
|
844
|
+
async def prolong_request_lock(
|
|
845
|
+
self,
|
|
846
|
+
request_id: str,
|
|
847
|
+
*,
|
|
848
|
+
forefront: bool | None = None,
|
|
849
|
+
lock_duration: timedelta,
|
|
850
|
+
timeout: Timeout = 'medium',
|
|
851
|
+
) -> RequestLockInfo | None:
|
|
852
|
+
"""Prolong the lock on a request.
|
|
853
|
+
|
|
854
|
+
|
|
855
|
+
Args:
|
|
856
|
+
request_id: ID of the request to prolong the lock.
|
|
857
|
+
forefront: Whether to put the request in the beginning or the end of the queue after lock expires.
|
|
858
|
+
lock_duration: By how much to prolong the lock.
|
|
859
|
+
timeout: Timeout for the API HTTP request.
|
|
860
|
+
"""
|
|
861
|
+
request_params = self._build_params(
|
|
862
|
+
clientKey=self.client_key,
|
|
863
|
+
forefront=forefront,
|
|
864
|
+
lockSecs=to_seconds(lock_duration, as_int=True),
|
|
865
|
+
)
|
|
866
|
+
|
|
867
|
+
response = await self._http_client.call(
|
|
868
|
+
url=self._build_url(f'requests/{request_id}/lock'),
|
|
869
|
+
method='PUT',
|
|
870
|
+
params=request_params,
|
|
871
|
+
timeout=timeout,
|
|
872
|
+
)
|
|
873
|
+
|
|
874
|
+
result = response_to_dict(response)
|
|
875
|
+
return ProlongRequestLockResponse.model_validate(result).data
|
|
876
|
+
|
|
877
|
+
async def delete_request_lock(
|
|
878
|
+
self,
|
|
879
|
+
request_id: str,
|
|
880
|
+
*,
|
|
881
|
+
forefront: bool | None = None,
|
|
882
|
+
timeout: Timeout = 'short',
|
|
883
|
+
) -> None:
|
|
884
|
+
"""Delete the lock on a request.
|
|
885
|
+
|
|
886
|
+
|
|
887
|
+
Args:
|
|
888
|
+
request_id: ID of the request to delete the lock.
|
|
889
|
+
forefront: Whether to put the request in the beginning or the end of the queue after the lock is deleted.
|
|
890
|
+
timeout: Timeout for the API HTTP request.
|
|
891
|
+
"""
|
|
892
|
+
request_params = self._build_params(clientKey=self.client_key, forefront=forefront)
|
|
893
|
+
|
|
894
|
+
await self._http_client.call(
|
|
895
|
+
url=self._build_url(f'requests/{request_id}/lock'),
|
|
896
|
+
method='DELETE',
|
|
897
|
+
params=request_params,
|
|
898
|
+
timeout=timeout,
|
|
899
|
+
)
|
|
900
|
+
|
|
901
|
+
async def _batch_add_requests_worker(
|
|
902
|
+
self,
|
|
903
|
+
*,
|
|
904
|
+
queue: asyncio.Queue[Iterable[bytes]],
|
|
905
|
+
request_params: dict,
|
|
906
|
+
timeout: Timeout,
|
|
907
|
+
) -> BatchAddResponse:
|
|
908
|
+
"""Worker function to process a batch of requests.
|
|
909
|
+
|
|
910
|
+
This worker will process batches from the queue.
|
|
911
|
+
|
|
912
|
+
Return result containing lists of processed and unprocessed requests by the worker.
|
|
913
|
+
"""
|
|
914
|
+
processed_requests = list[AddedRequest]()
|
|
915
|
+
unprocessed_requests = list[RequestDraft]()
|
|
916
|
+
|
|
917
|
+
while True:
|
|
918
|
+
# Get the next batch from the queue.
|
|
919
|
+
try:
|
|
920
|
+
request_batch = await queue.get()
|
|
921
|
+
except asyncio.CancelledError:
|
|
922
|
+
break
|
|
923
|
+
|
|
924
|
+
try:
|
|
925
|
+
# Send the batch to the API, assembling the body from the already serialized requests.
|
|
926
|
+
response = await self._http_client.call(
|
|
927
|
+
url=self._build_url('requests/batch'),
|
|
928
|
+
method='POST',
|
|
929
|
+
headers={'content-type': 'application/json'},
|
|
930
|
+
params=request_params,
|
|
931
|
+
data=b'[' + b','.join(request_batch) + b']',
|
|
932
|
+
timeout=timeout,
|
|
933
|
+
)
|
|
934
|
+
|
|
935
|
+
result = response_to_dict(response)
|
|
936
|
+
batch_response = BatchAddResponse.model_validate(result)
|
|
937
|
+
processed_requests.extend(batch_response.data.processed_requests)
|
|
938
|
+
unprocessed_requests.extend(batch_response.data.unprocessed_requests)
|
|
939
|
+
|
|
940
|
+
finally:
|
|
941
|
+
# Mark the batch as done whether it succeeded or failed.
|
|
942
|
+
queue.task_done()
|
|
943
|
+
|
|
944
|
+
return BatchAddResponse.model_construct(
|
|
945
|
+
data=BatchAddResult.model_construct(
|
|
946
|
+
processed_requests=processed_requests,
|
|
947
|
+
unprocessed_requests=unprocessed_requests,
|
|
948
|
+
)
|
|
949
|
+
)
|
|
950
|
+
|
|
951
|
+
async def batch_add_requests(
|
|
952
|
+
self,
|
|
953
|
+
requests: list[RequestDraft] | list[RequestDraftDict] | list[RequestDraftCamelDict],
|
|
954
|
+
*,
|
|
955
|
+
forefront: bool = False,
|
|
956
|
+
max_parallel: int = 5,
|
|
957
|
+
timeout: Timeout = 'medium',
|
|
958
|
+
) -> BatchAddResult:
|
|
959
|
+
"""Add requests to the request queue in batches.
|
|
960
|
+
|
|
961
|
+
Requests are split into batches based on size and processed in parallel.
|
|
962
|
+
|
|
963
|
+
|
|
964
|
+
Args:
|
|
965
|
+
requests: List of requests to be added to the queue.
|
|
966
|
+
forefront: Whether to add requests to the front of the queue.
|
|
967
|
+
max_parallel: Specifies the maximum number of parallel tasks for API calls. This is only applicable
|
|
968
|
+
to the async client. For the sync client, this value must be set to 1, as parallel execution
|
|
969
|
+
is not supported.
|
|
970
|
+
timeout: Timeout for the API HTTP request.
|
|
971
|
+
|
|
972
|
+
Returns:
|
|
973
|
+
Result containing lists of processed and unprocessed requests.
|
|
974
|
+
"""
|
|
975
|
+
# Validate and serialize the requests in a worker thread, as it is CPU-bound and would block the event loop.
|
|
976
|
+
serialized_requests = await asyncio.to_thread(_serialize_requests, requests)
|
|
977
|
+
|
|
978
|
+
# Build the query parameters shared by all the batch API calls.
|
|
979
|
+
request_params = self._build_params(clientKey=self.client_key, forefront=forefront)
|
|
980
|
+
|
|
981
|
+
# Compute the payload size limit to ensure it doesn't exceed the maximum allowed size.
|
|
982
|
+
payload_size_limit_bytes = _MAX_PAYLOAD_SIZE_BYTES - math.ceil(_MAX_PAYLOAD_SIZE_BYTES * _SAFETY_BUFFER_PERCENT)
|
|
983
|
+
|
|
984
|
+
# Split the requests into batches by payload size (counting commas and brackets) and max requests per batch.
|
|
985
|
+
batches = constrained_batches(
|
|
986
|
+
serialized_requests,
|
|
987
|
+
max_size=payload_size_limit_bytes - len(b'[]'),
|
|
988
|
+
max_count=_RQ_MAX_REQUESTS_PER_BATCH,
|
|
989
|
+
get_len=lambda serialized: len(serialized) + len(b','),
|
|
990
|
+
strict=False,
|
|
991
|
+
)
|
|
992
|
+
|
|
993
|
+
# Create a queue with all the batches, from which the worker tasks will consume them.
|
|
994
|
+
batch_queue: asyncio.Queue[Iterable[bytes]] = asyncio.Queue()
|
|
995
|
+
|
|
996
|
+
for batch in batches:
|
|
997
|
+
await batch_queue.put(batch)
|
|
998
|
+
|
|
999
|
+
# Use TaskGroup for structured concurrency — automatic cleanup and error propagation.
|
|
1000
|
+
try:
|
|
1001
|
+
async with asyncio.TaskGroup() as tg:
|
|
1002
|
+
workers = [
|
|
1003
|
+
tg.create_task(
|
|
1004
|
+
self._batch_add_requests_worker(
|
|
1005
|
+
queue=batch_queue, request_params=request_params, timeout=timeout
|
|
1006
|
+
),
|
|
1007
|
+
name=f'batch_add_requests_worker_{i}',
|
|
1008
|
+
)
|
|
1009
|
+
for i in range(max_parallel)
|
|
1010
|
+
]
|
|
1011
|
+
|
|
1012
|
+
# Wait for all batches to be processed, then cancel idle workers.
|
|
1013
|
+
await batch_queue.join()
|
|
1014
|
+
for worker in workers:
|
|
1015
|
+
worker.cancel()
|
|
1016
|
+
except ExceptionGroup as eg:
|
|
1017
|
+
# Re-raise the first worker exception directly to maintain backward-compatible error types.
|
|
1018
|
+
raise eg.exceptions[0] from None
|
|
1019
|
+
|
|
1020
|
+
# Combine the results from all workers and return them.
|
|
1021
|
+
processed_requests = list[AddedRequest]()
|
|
1022
|
+
unprocessed_requests = list[RequestDraft]()
|
|
1023
|
+
|
|
1024
|
+
for worker in workers:
|
|
1025
|
+
result = worker.result()
|
|
1026
|
+
processed_requests.extend(result.data.processed_requests)
|
|
1027
|
+
unprocessed_requests.extend(result.data.unprocessed_requests)
|
|
1028
|
+
|
|
1029
|
+
return BatchAddResponse.model_construct(
|
|
1030
|
+
data=BatchAddResult.model_construct(
|
|
1031
|
+
processed_requests=processed_requests,
|
|
1032
|
+
unprocessed_requests=unprocessed_requests,
|
|
1033
|
+
)
|
|
1034
|
+
).data
|
|
1035
|
+
|
|
1036
|
+
async def batch_delete_requests(
|
|
1037
|
+
self,
|
|
1038
|
+
requests: list[RequestDraftDelete] | list[RequestDraftDeleteDict] | list[RequestDraftDeleteCamelDict],
|
|
1039
|
+
*,
|
|
1040
|
+
timeout: Timeout = 'short',
|
|
1041
|
+
) -> BatchDeleteResult:
|
|
1042
|
+
"""Delete given requests from the queue.
|
|
1043
|
+
|
|
1044
|
+
|
|
1045
|
+
Args:
|
|
1046
|
+
requests: List of the requests to delete.
|
|
1047
|
+
timeout: Timeout for the API HTTP request.
|
|
1048
|
+
"""
|
|
1049
|
+
requests_as_dicts = [
|
|
1050
|
+
(
|
|
1051
|
+
request
|
|
1052
|
+
if isinstance(request, RequestDraftDelete)
|
|
1053
|
+
else RequestDraftDelete.model_validate(
|
|
1054
|
+
request,
|
|
1055
|
+
)
|
|
1056
|
+
).model_dump(by_alias=True, exclude_none=True)
|
|
1057
|
+
for request in requests
|
|
1058
|
+
]
|
|
1059
|
+
|
|
1060
|
+
request_params = self._build_params(clientKey=self.client_key)
|
|
1061
|
+
|
|
1062
|
+
response = await self._http_client.call(
|
|
1063
|
+
url=self._build_url('requests/batch'),
|
|
1064
|
+
method='DELETE',
|
|
1065
|
+
params=request_params,
|
|
1066
|
+
json=requests_as_dicts,
|
|
1067
|
+
timeout=timeout,
|
|
1068
|
+
)
|
|
1069
|
+
result = response_to_dict(response)
|
|
1070
|
+
return BatchDeleteResponse.model_validate(result).data
|
|
1071
|
+
|
|
1072
|
+
async def list_requests(
|
|
1073
|
+
self,
|
|
1074
|
+
*,
|
|
1075
|
+
limit: int | None = None,
|
|
1076
|
+
filter: list[Literal['pending', 'locked']] | None = None, # noqa: A002
|
|
1077
|
+
timeout: Timeout = 'medium',
|
|
1078
|
+
cursor: str | None = None,
|
|
1079
|
+
) -> ListOfRequests:
|
|
1080
|
+
"""List requests in the queue.
|
|
1081
|
+
|
|
1082
|
+
|
|
1083
|
+
Args:
|
|
1084
|
+
limit: How many requests to retrieve.
|
|
1085
|
+
filter: List of request states to use as a filter. Multiple values mean union of the given filters.
|
|
1086
|
+
timeout: Timeout for the API HTTP request.
|
|
1087
|
+
cursor: A token returned in previous API response, to continue listing next page of requests
|
|
1088
|
+
"""
|
|
1089
|
+
request_params = self._build_params(
|
|
1090
|
+
limit=limit,
|
|
1091
|
+
filter=','.join(filter) if filter else None,
|
|
1092
|
+
clientKey=self.client_key,
|
|
1093
|
+
cursor=cursor,
|
|
1094
|
+
)
|
|
1095
|
+
|
|
1096
|
+
response = await self._http_client.call(
|
|
1097
|
+
url=self._build_url('requests'),
|
|
1098
|
+
method='GET',
|
|
1099
|
+
params=request_params,
|
|
1100
|
+
timeout=timeout,
|
|
1101
|
+
)
|
|
1102
|
+
|
|
1103
|
+
result = response_to_dict(response)
|
|
1104
|
+
return ListOfRequestsResponse.model_validate(result).data
|
|
1105
|
+
|
|
1106
|
+
def iterate_requests(
|
|
1107
|
+
self,
|
|
1108
|
+
*,
|
|
1109
|
+
limit: int | None = None,
|
|
1110
|
+
filter: list[Literal['pending', 'locked']] | None = None, # noqa: A002
|
|
1111
|
+
cursor: str | None = None,
|
|
1112
|
+
chunk_size: int | None = None,
|
|
1113
|
+
timeout: Timeout = 'medium',
|
|
1114
|
+
) -> AsyncIterator[Request]:
|
|
1115
|
+
"""Iterate over requests in the queue.
|
|
1116
|
+
|
|
1117
|
+
Simple `list_requests` does only one API call, possibly not listing all items matching the criteria.
|
|
1118
|
+
This method returns an iterator that is capable of making multiple API calls to retrieve all items
|
|
1119
|
+
matching the criteria using the opaque `cursor` returned by the API.
|
|
1120
|
+
|
|
1121
|
+
|
|
1122
|
+
Args:
|
|
1123
|
+
limit: Maximum number of requests to yield across all pages.
|
|
1124
|
+
filter: List of request states to use as a filter. Multiple values mean union of the given filters.
|
|
1125
|
+
cursor: A token returned in a previous API response, used as the initial pagination cursor.
|
|
1126
|
+
chunk_size: Maximum number of requests requested per API call when iterating across pages.
|
|
1127
|
+
timeout: Timeout for the API HTTP request.
|
|
1128
|
+
|
|
1129
|
+
Yields:
|
|
1130
|
+
A request from the queue.
|
|
1131
|
+
"""
|
|
1132
|
+
|
|
1133
|
+
async def _callback(*, cursor: str | None = None, limit: int | None = None) -> ListOfRequests:
|
|
1134
|
+
return await self.list_requests(limit=limit, filter=filter, cursor=cursor, timeout=timeout)
|
|
1135
|
+
|
|
1136
|
+
return get_cursor_iterator_async(
|
|
1137
|
+
_callback,
|
|
1138
|
+
cursor=cursor,
|
|
1139
|
+
limit=limit,
|
|
1140
|
+
chunk_size=chunk_size or DEFAULT_CHUNK_SIZE,
|
|
1141
|
+
)
|
|
1142
|
+
|
|
1143
|
+
async def unlock_requests(
|
|
1144
|
+
self: RequestQueueClientAsync,
|
|
1145
|
+
*,
|
|
1146
|
+
timeout: Timeout = 'long',
|
|
1147
|
+
) -> UnlockRequestsResult:
|
|
1148
|
+
"""Unlock all requests in the queue, which were locked by the same clientKey or from the same Actor run.
|
|
1149
|
+
|
|
1150
|
+
|
|
1151
|
+
Args:
|
|
1152
|
+
timeout: Timeout for the API HTTP request.
|
|
1153
|
+
|
|
1154
|
+
Returns:
|
|
1155
|
+
Result of the unlock operation containing the count of unlocked requests
|
|
1156
|
+
"""
|
|
1157
|
+
request_params = self._build_params(clientKey=self.client_key)
|
|
1158
|
+
|
|
1159
|
+
response = await self._http_client.call(
|
|
1160
|
+
url=self._build_url('requests/unlock'),
|
|
1161
|
+
method='POST',
|
|
1162
|
+
params=request_params,
|
|
1163
|
+
timeout=timeout,
|
|
1164
|
+
)
|
|
1165
|
+
|
|
1166
|
+
result = response_to_dict(response)
|
|
1167
|
+
return UnlockRequestsResponse.model_validate(result).data
|